# @deliverart/sdk-js-core 中文文档

规范地址：https://npmcn.com/package/%40deliverart/sdk-js-core/

版本：3\.0\.1
npm 元数据更新时间：2026-11-10T20:25:31.430Z
中文译文更新时间：2026-11-11T21:43:05.936Z
软件包许可：未声明

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

原始 npm 页面：https://www.npmjs.com/package/%40deliverart/sdk-js-core
原文对照：https://npmcn.com/package/%40deliverart/sdk-js-core/?lang=original

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

- 包体积（解压后）：45.1 kB，6 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：3 个
- 首次发布：2025-06-08T20:16:07.974Z
- 最新版本发布：2026-11-10T20:25:31.276Z
- 近 30 天下载量：6640（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：329（近 12 个月 230 个）

## 中文简介

交付艺术的核心SDK,提供基本功能和公用事业.

## 安装

```sh
npm install @deliverart/sdk-js-core
```

也可以使用：`pnpm add @deliverart/sdk-js-core`、`yarn add @deliverart/sdk-js-core`、`bun add @deliverart/sdk-js-core`

## README

# @ deliverart/ sdk- js- 分数

交付艺术JavaScript SDK的核心包. 提供API客户端,插件系统,以及基础请求/响应处理.

## 安装

```bash
npm install @deliverart/sdk-js-core
# or
pnpm add @deliverart/sdk-js-core
# or
yarn add @deliverart/sdk-js-core
```

## 导出类型

### 图像

```typescript
type ApiClient<Extensions extends ApiExtension = NonNullable<unknown>>
```

主要API客户端接口提供了制作API调用和管理插件的方法.

**方法:**

-   `call<TInputSchema, TOutputSchema, Q, H>(request: AbstractApiRequest): Promise<output<TOutputSchema>>` - 执行API请求
-   `addPlugin<T extends ApiExtension>(plugin: ApiClientPlugin<T>): ApiClient<T>` - 添加插件以扩展客户端功能
-   `addRequestMiddleware(middleware: RequestMiddleware): void` - 添加中间软件拦截请求
-   `addResponseMiddleware(middleware: ResponseMiddleware): void` - 添加中间软件以拦截响应

### 抽象请求

```typescript
abstract class AbstractApiRequest<
  TInputSchema extends ZodType<any, any, any>,
  TOutputSchema extends ZodType<any, any, any>,
  Query = unknown,
  Headers = unknown
>
```

所有 API 请求的基础类 。 扩展此类以创建自定义 API 请求 .

**摘要属性 :**

-   `method: 'GET' | 'POST' | 'PATCH' | 'DELETE'` - HTTP方法(所需)
-   `contentType: 'application/json' | 'multipart/form-data' | 'application/merge-patch+json'` - 内容-类型标题(需要)
-   `accept: 'application/json'` - 接受信头(需要)
-   `inputSchema: TInputSchema` - 请求审定的Zod计划(需要)
-   `outputSchema: TOutputSchema` - Zod schema用于响应验证(需要)
-   `querySchema?: ZodType<Query>` - 用于查询参数的Zod计划(可选)
-   `headersSchema?: ZodType<Headers>` - 标头的Zod schema(可选)

**摘要方法:**

-   `getPath(): string` - 返回 API 端点路径( 需要)

**内设方法:**

-   `validateInput(): output<TInputSchema>` - 验证请求输入
-   `validateQuery(): Query | undefined` - 验证查询参数
-   `validateHeaders(): Headers | undefined` - 验证信头
-   `validateOutput(data: unknown): output<TOutputSchema>` - 验证答复
-   `parseResponse(data: unknown, rawResponse?: Response): output<TOutputSchema>` - 分析并验证反应(可以推翻)

### 扩展

```typescript
type ApiExtension = Record<string, unknown>
```

添加新方法到 API 客户端的插件扩展的基础类型 .

### ApiClient 缓冲

```typescript
interface ApiClientPlugin<T extends ApiExtension = Record<string, unknown>> {
  setup: (client: ApiClient<Record<string, unknown>>) => T
}
```

用于创建扩展API客户端功能的插件的接口.

### 错误

#### 输入参数错误

```typescript
class InputValidationError extends Error {
  constructor(public readonly issues: ZodIssue[])
}
```

当请求输入验证失败时抛出 .

**属性 :**

-   `issues: ZodIssue[]` - Zod的验证错误矩阵

#### 输出校正误差

```typescript
class OutputValidationError extends Error {
  constructor(public readonly issues: ZodIssue[])
}
```

当响应验证失败时抛出 .

**属性 :**

-   `issues: ZodIssue[]` - Zod的验证错误矩阵

## 使用量

### 创建 API 客户端

```typescript
import { createApiClient } from '@deliverart/sdk-js-core';

const client = createApiClient({
  baseUrl: 'https://api.deliverart.com'
});
```

**参数:**

-   `baseUrl: string` (需要) - 所有 API 请求的基础 URL

### 创建自定义请求

```typescript
import { AbstractApiRequest } from '@deliverart/sdk-js-core';
import { z } from 'zod';

// Define input schema
const createUserInputSchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.coerce.number().min(18).optional()
});

// Define output schema
const userResponseSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string(),
  age: z.coerce.number().nullable(),
  createdAt: z.string()
});

// Define query parameters schema (optional)
const getUsersQuerySchema = z.object({
  page: z.coerce.number().optional(),
  limit: z.coerce.number().optional(),
  search: z.string().optional()
});

// Create the request class
class CreateUser extends AbstractApiRequest<
  typeof createUserInputSchema,
  typeof userResponseSchema
> {
  readonly method = 'POST';
  readonly contentType = 'application/json';
  readonly accept = 'application/json';
  
  readonly inputSchema = createUserInputSchema;
  readonly outputSchema = userResponseSchema;
  readonly querySchema = undefined;
  readonly headersSchema = undefined;

  constructor(input: z.input<typeof createUserInputSchema>) {
    super(input);
  }

  getPath(): string {
    return '/users';
  }
}

// Request with path parameters
class GetUser extends AbstractApiRequest<
  typeof z.undefined,
  typeof userResponseSchema
> {
  readonly method = 'GET';
  readonly contentType = 'application/json';
  readonly accept = 'application/json';
  
  readonly inputSchema = z.undefined();
  readonly outputSchema = userResponseSchema;
  readonly querySchema = undefined;
  readonly headersSchema = undefined;

  private readonly userId: string;

  constructor(userId: string) {
    super(undefined);
    this.userId = userId;
  }

  getPath(): string {
    return `/users/${this.userId}`;
  }
}

// Request with query parameters
class GetUsers extends AbstractApiRequest<
  typeof z.undefined,
  typeof z.array(userResponseSchema),
  z.infer<typeof getUsersQuerySchema>
> {
  readonly method = 'GET';
  readonly contentType = 'application/json';
  readonly accept = 'application/json';
  
  readonly inputSchema = z.undefined();
  readonly outputSchema = z.array(userResponseSchema);
  readonly querySchema = getUsersQuerySchema;
  readonly headersSchema = undefined;

  constructor(options?: { query?: z.infer<typeof getUsersQuerySchema> }) {
    super(undefined, options);
  }

  getPath(): string {
    return '/users';
  }
}
```

### 制作API电话

```typescript
import { client } from './client';

// Create a user
const newUser = await client.call(new CreateUser({
  name: 'John Doe',
  email: 'john@example.com',
  age: 25
}));

// Get a user
const user = await client.call(new GetUser('user-123'));

// Get users with filters
const users = await client.call(new GetUsers({
  query: {
    page: 1,
    limit: 10,
    search: 'john'
  }
}));
```

### 正在添加中间软件

#### 请求中间软件

```typescript
client.addRequestMiddleware(async (ctx) => {
  console.log('Making request to:', ctx.url.toString());
  
  // Modify headers
  return {
    ...ctx,
    init: {
      ...ctx.init,
      headers: {
        ...ctx.init.headers,
        'X-Custom-Header': 'value'
      }
    }
  };
});
```

**参数:**

-   `ctx.url: URL` - 请求 URL
-   `ctx.init: RequestInit` - 获取选项

**返回 :** 已修改 `RequestContext` 或原上下文

#### 中间响应软件

```typescript
client.addResponseMiddleware(async (parsed, requestCtx) => {
  console.log('Response status:', parsed.response.status);
  console.log('Response body:', parsed.body);
  
  return parsed;
});
```

**参数:**

-   `parsed.response: Response` - 获取响应对象
-   `parsed.body: unknown` - 解析的反应机构
-   `requestCtx: RequestContext` - 最初请求的背景

**返回 :** 已修改 `ParsedResponse` 或原始解析的答复

### 创建插件

```typescript
import { ApiClient, ApiClientPlugin, ApiExtension } from '@deliverart/sdk-js-core';

// Define the extension interface
interface LoggerExtension extends ApiExtension {
  logger: {
    enable: () => void;
    disable: () => void;
  };
}

// Create the plugin
class LoggerPlugin implements ApiClientPlugin<LoggerExtension> {
  private enabled = true;

  setup(client: ApiClient): LoggerExtension {
    // Add request middleware
    client.addRequestMiddleware(async (ctx) => {
      if (this.enabled) {
        console.log('[Request]', ctx.init.method, ctx.url.toString());
      }
      return ctx;
    });

    // Add response middleware
    client.addResponseMiddleware(async (parsed, ctx) => {
      if (this.enabled) {
        console.log('[Response]', parsed.response.status);
      }
      return parsed;
    });

    // Return extension methods
    return {
      logger: {
        enable: () => {
          this.enabled = true;
        },
        disable: () => {
          this.enabled = false;
        }
      }
    };
  }
}

// Use the plugin
const client = createApiClient({ baseUrl: 'https://api.example.com' })
  .addPlugin(new LoggerPlugin());

// Now you can use the logger methods
client.logger.disable();
client.logger.enable();
```

### 处理错误

```typescript
import { InputValidationError, OutputValidationError } from '@deliverart/sdk-js-core';

try {
  await client.call(new CreateUser({
    name: '', // Invalid: min length is 1
    email: 'invalid-email', // Invalid email format
  }));
} catch (error) {
  if (error instanceof InputValidationError) {
    console.error('Input validation failed:');
    error.issues.forEach(issue => {
      console.error(`- ${issue.path.join('.')}: ${issue.message}`);
    });
  } else if (error instanceof OutputValidationError) {
    console.error('Response validation failed:');
    error.issues.forEach(issue => {
      console.error(`- ${issue.path.join('.')}: ${issue.message}`);
    });
  } else {
    console.error('Other error:', error);
  }
}
```

## 高级特性

### 自定义响应解析

覆盖 `parseResponse` 以自定义解析回复:

```typescript
import { Paginated, responseToPagination } from '@deliverart/sdk-js-global-types';

class GetUsers extends AbstractApiRequest</*...*/> {
  // ... other properties ...

  parseResponse(data: unknown, rawResponse: Response): Paginated<User> {
    const users = z.array(userResponseSchema).parse(data);
    
    return this.validateOutput({
      data: users,
      pagination: responseToPagination(rawResponse)
    });
  }
}
```

### 格式数据请求

```typescript
const uploadImageInputSchema = z.instanceof(FormData);

class UploadImage extends AbstractApiRequest<
  typeof uploadImageInputSchema,
  typeof imageResponseSchema
> {
  readonly method = 'POST';
  readonly contentType = 'multipart/form-data';
  readonly accept = 'application/json';
  
  readonly inputSchema = uploadImageInputSchema;
  readonly outputSchema = imageResponseSchema;

  constructor(formData: FormData) {
    super(formData);
  }

  getPath(): string {
    return '/images';
  }
}

// Usage
const formData = new FormData();
formData.append('file', fileBlob);
formData.append('name', 'My Image');

const image = await client.call(new UploadImage(formData));
```

## 共享运行时间类型

`@deliverart/sdk-js-global-types` 是一个运行时间依赖。 核心序列化 返回同样的 `IriObject` 类; 捆绑私有 复制中断实例检查和消费者使用的名义声明类型. 新建两个软件包后运行 `pnpm --filter @deliverart/sdk-js-core test:artifacts` 核查无害环境管理和通用JS软件包的边界.

## 许可证

麻省理工学院

## 常见问题

### @deliverart/sdk-js-core 是什么？

交付艺术的核心SDK,提供基本功能和公用事业\.

### 如何安装 @deliverart/sdk-js-core？

在项目目录运行 npm install @deliverart/sdk-js-core，或使用 pnpm add / yarn add / bun add。

### @deliverart/sdk-js-core 支持 TypeScript 吗？

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

### @deliverart/sdk-js-core 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @deliverart/sdk-js-core 可以商用吗？

@deliverart/sdk-js-core 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @deliverart/sdk-js-core 的下载量有多少？

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

### @deliverart/sdk-js-core 还在维护吗？

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

