# @compassdigital/sdk\.typescript 中文文档

规范地址：https://npmcn.com/package/%40compassdigital/sdk.typescript/

版本：4\.941\.0
npm 元数据更新时间：2026-11-10T00:20:23.404Z
中文译文更新时间：2026-11-10T13:35:14.671Z
软件包许可：ISC

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40compassdigital/sdk.typescript
原文对照：https://npmcn.com/package/%40compassdigital/sdk.typescript/?lang=original
项目主页：https://github.com/compassdigital/cdl#readme
源码仓库：https://github.com/compassdigital/cdl

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：4.7 MB，739 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2021-09-02T15:15:21.540Z
- 最新版本发布：2026-11-10T00:20:23.201Z
- 近 30 天下载量：16989（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：1062（近 12 个月 600 个）

## 中文简介

编译数字实验室类型SDK

## 安装

```sh
npm install @compassdigital/sdk.typescript
```

也可以使用：`pnpm add @compassdigital/sdk.typescript`、`yarn add @compassdigital/sdk.typescript`、`bun add @compassdigital/sdk.typescript`

## README

# @compassdigital/sdk.typescript

编译数字实验室类型SDK

## 安装

```
$ npm install --save @compassdigital/sdk.typescript@latest
```

## 服务器使用示例

```typescript
import Provider from "@compassdigital/provider";
import { GetTaskRequest, GetTaskResponse } from "@compassdigital/sdk.typescript/interface/task";

const provider = new Provider({ type: "task" });

provider.on<GetTaskRequest, GetTaskResponse>("get_task", function (req, next): void {
    // ...
})
```

## 客户端使用示例

**证明客户端 :**

```typescript
import { ServiceClient } from "@compassdigital/sdk.typescript";

const api = new ServiceClient({ stage: "dev" });
```

**基本请求 :**

```typescript
const task = await api.get_task(id);
```

**请求选项 :**

这些选择可转交任何请求.

```typescript
interface RequestOptions {
  // environment to make requests to
  stage?: string;
  // authentication token
  token?: string;
  // additional headers
  headers?: Record<string, string>;
  // log all requests and responses
  debug?: boolean;
  // the number of times to retry a request
  retry?: number;
  // timeout in milliseconds
  timeout?: number;
  // make requests against this base url.
  // per-service base urls are configured as an object
  // eg. { order: 'http://localhost:3000', shoppingcart: 'http://localhost:4000' }
  // note: the stage property is ignored if base_url is set
  base_url?: string;
  // intercept outgoing http requests
  intercept?: InterceptFn;
}
```

-   这个 `RequestOptions` 可提供给 `ServiceClient` 建筑师或应请求呼叫现场.
-   呼叫站点提供的选项将超越转给建筑商的选项.

```typescript
const api = new ServiceClient({
    token: "<token>",
    retry: 2,
})

const location = await api.get_location(id, {
    token: "<token>",
    retry: 2,
})
```

以下环境变量可用于设定调试目的的默认选项:

-   `P2_SDK_STAGE`
-   `P2_SDK_TOKEN`
-   `P2_SDK_DEBUG`
-   `P2_SDK_BASE_URL`
    -   可以通过一个url来拦截所有请求
    -   参见http://localhost:3:00
    -   可以通过一个逗号分隔列表来配置每个服务的基数 urls
    -   http://localhost:3:00,购物车=http://localhost:4:00

**处理错误 :**

非200份答复被否决 `ServiceError`。 。 。 .

```typescript
try {
    const shoppingcart = await api.get_shoppingcart(id);
} catch (err) {
    // Since the error type is `unknown` we must type assert before
    // accessing the properties.
    if (err instanceof ServiceError) {
        console.log(err.status, err.code, err.message);
    }

    // There are helpers for accessing the status and code
    if (ServiceError.code(err) === 400.31) {
        console.log("Failed to get menu");
    }
}
```

有一个 `ignore` 忽略特定状态和错误代码的方便方法 .

```typescript
const issue: OrderIssue = { items: [] };
await api.post_order_issue(id, issue).ignore(400.18, 400.21);
```

有一个 `combine` 返回含有响应或错误的对象的方便方法.

```typescript
const res = await api.get_task(id).combine();

if (res.ok) {
  console.log("task", res.data);
} else {
  console.log("error", res.err);
}
```

**测试 :**

您可以注册 `intercept` 函数将重排所有请求.

```typescript

import {
  ServiceClient,
  RequestData,
  ResponseData,
  FetchFn,
} from "@compassdigital/sdk.typescript";

async function intercept(req: RequestData, fetch: FetchFn): Promise<ResponseData> {
    expect(req.name).toBe("get_shoppingcart");
    return { ok: true, status: 200, body: JSON.stringify({}) }
}

const api = new ServiceClient({ intercept });
```

## 代码 Gen

1.  添加新服务到 `manifest.json`。 。 。 .
2.  运行 `npm run gen`。 。 。 .

## 常见问题

### @compassdigital/sdk\.typescript 是什么？

编译数字实验室类型SDK

### 如何安装 @compassdigital/sdk\.typescript？

在项目目录运行 npm install @compassdigital/sdk\.typescript，或使用 pnpm add / yarn add / bun add。

### @compassdigital/sdk\.typescript 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @compassdigital/sdk\.typescript 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @compassdigital/sdk\.typescript 可以商用吗？

@compassdigital/sdk\.typescript 使用 ISC 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @compassdigital/sdk\.typescript 的下载量有多少？

根据 npm 官方下载统计，@compassdigital/sdk\.typescript 在 2026/10/11 – 2026/11/09 这 30 天内被下载 16,989 次，日均约 566 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @compassdigital/sdk\.typescript 还在维护吗？

最新版本 4\.941\.0 发布于 2026/11/10（今天）；至今共发布 1062 个版本，其中过去 12 个月发布了 600 个；首次发布于 2021/09/02。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

