# @critical-path/client 中文文档

规范地址：https://npmcn.com/package/%40critical-path/client/

版本：0\.29\.2
npm 元数据更新时间：2026-11-05T14:30:56.233Z
中文译文更新时间：2026-11-11T00:59:05.084Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40critical-path/client
原文对照：https://npmcn.com/package/%40critical-path/client/?lang=original
项目主页：https://github.com/Pixerate/critical-path#readme
源码仓库：https://github.com/Pixerate/critical-path

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

- 包体积（解压后）：162 kB，12 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=24\.0\.0
- 运行依赖：1 个
- 首次发布：2026-08-24T12:22:39.543Z
- 最新版本发布：2026-11-05T14:30:55.775Z
- 近 30 天下载量：4491（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：86（近 12 个月 86 个）

## 中文简介

类型安全 JavaScript/ TypeScript 客户端 SDK 用于消耗关键路径 API 端点

## 安装

```sh
npm install @critical-path/client
```

也可以使用：`pnpm add @critical-path/client`、`yarn add @critical-path/client`、`bun add @critical-path/client`

## README

# @ 关键路径/客户端

> **Type-safet JavaScript/TypeScript HTTP客户端 SDK 为关键路径.**

> **升级?** 升级一次 `@critical-path/*` 组合在一起。 编码代理: 遵循 [更新(md)](https://github.com/Pixerate/critical-path/blob/main/UPGRADING.md); 已标记断开的更改 **刹车** 此软件包中 `CHANGELOG.md`。 。 。 .

`@critical-path/client` 提供轻量级,端到端类型安全的SDK,用于与来自任何网络或节点.js应用程序的临界路径REST API端点进行交互.

* * *

## \* 安装

```bash
npm install @critical-path/client
# or
pnpm add @critical-path/client
```

* * *

## 使用示例

```ts
import { CriticalPathClient } from '@critical-path/client';

const client = new CriticalPathClient({
  baseUrl: '/api/critical-path'
});

// Fetch projects
const projects = await client.getProjects();

// Fetch tasks for a project
const tasks = await client.getTasks('proj_1'); // every task, following pagination

// One page at a time, with filters
const { items, nextCursor } = await client.queryTasks({ projectId: 'proj_1', status: ['todo', 'in_progress'], limit: 50 });

// Create a new task
const newTask = await client.createTask({
  projectId: 'proj_1',
  title: 'Design UI Wireframes',
  priority: 'high',
  status: 'todo'
});

// Identity comes from your auth headers (resolved by the server's getContext), never from
// request bodies. Without auth, writes are attributed to "anonymous".

// Update task status
await client.updateTask(newTask.id, { status: 'in_progress' });

// Add threaded comment
const comment = await client.addComment({
  taskId: newTask.id,
  content: 'Initial implementation ready for review'
}); // authored by the caller the server resolves from your auth headers

// Add emoji reaction
await client.addCommentReaction(comment.id, { emoji: '🚀' });

// Remove emoji reaction
await client.removeCommentReaction(comment.id, { emoji: '🚀' });

// Upload file directly or register storage attachment
const attachment = await client.uploadAttachmentFile({
  filename: 'architecture.png',
  data: fileBuffer,
  mimeType: 'image/png',
  taskId: newTask.id,
  commentId: comment.id
}); // binary data is base64-encoded automatically

// Calculate Critical Path Method (CPM) schedule & bottlenecks
const cpmAnalysis = await client.calculateCriticalPath('proj_1'); // or { calendars: 'assignee', levelResources: true }
const portfolio = await client.calculatePortfolioCriticalPath({ projectIds: ['proj_1', 'proj_2'], calendars: 'assignee', levelResources: true });
// Options on both: effort: 'remaining'; on portfolio: includeHiddenWork, projectOrder
console.log('Total project duration:', cpmAnalysis.totalDurationHours);
console.log('Bottleneck tasks:', cpmAnalysis.criticalTaskIds);

// Ladder of Abstraction (macro, standard, concrete rungs)
const ladder = await client.getTimelineLadder('proj_1', { level: 'all' });
console.log('Macro phase progress:', ladder.macro?.overallProgressPercentage);
console.log('Standard Gantt items:', ladder.standard?.tasks.length);
console.log('Concrete deliverables & daily effort:', ladder.concrete);

// Single task ladder drilldown
const taskLadder = await client.getTaskLadder(newTask.id);
```

* * *

## QQ 配置

```ts
const client = new CriticalPathClient({
  baseUrl: '/api/critical-path',
  // Static headers, or a function called before every request (e.g. to refresh tokens)
  headers: async () => ({ Authorization: `Bearer ${await auth.getAccessToken()}` }),
  timeoutMs: 15_000,                       // abort slow requests (default: none)
  retry: { retries: 2, baseDelayMs: 250 }, // GET only: network errors, 429, 502-504 (default: off)
  fetch: customFetch                       // optional fetch implementation
});
```

### 注销和每个呼叫标题

`with()` 返回对每次调用都应用选项的有范围客户端:

```ts
const controller = new AbortController();
const tasks = await client.with({ signal: controller.signal }).getTasks(projectId);
// later, e.g. when a component unmounts:
controller.abort();

await client.with({ headers: { 'X-Request-Id': id }, timeoutMs: 5_000 }).getProject(projectId);
```

### 错误

非-2xx 响应抛出 `CriticalPathError`数字 :

```ts
import { CriticalPathError } from '@critical-path/client';

try {
  await client.addDependency(taskId, { dependsOnTaskId });
} catch (err) {
  if (err instanceof CriticalPathError) {
    err.status;          // e.g. 409
    err.issues;          // field-level problems for 400 validation errors
    err.body?.cyclePath; // the rest of the server's error body
  }
}
```

删除方法解析到 `false` 而不是在资源不存在时投掷。 网络故障、 超时( E)`TimeoutError`)和取消(`AbortError`)被抛出一地.

每个服务器路径都有客户端方法; 3; `routes.test.ts` 如果添加一条没有一条路由, 则失败 .

* * *

## 许可证

麻省理工学院 [关键路径](https://github.com/Pixerate/Critical-Path)

## 常见问题

### @critical-path/client 是什么？

类型安全 JavaScript/ TypeScript 客户端 SDK 用于消耗关键路径 API 端点

### 如何安装 @critical-path/client？

在项目目录运行 npm install @critical-path/client，或使用 pnpm add / yarn add / bun add。它还提供命令行工具 critical-path，可以用 npx critical-path 直接运行。

### @critical-path/client 支持 TypeScript 吗？

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

### @critical-path/client 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @critical-path/client 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=24\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @critical-path/client 可以商用吗？

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

### @critical-path/client 的下载量有多少？

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

### @critical-path/client 还在维护吗？

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

