# @dvina/sdk 中文文档

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

版本：5\.0\.67
npm 元数据更新时间：2026-11-13T07:51:03.621Z
中文译文更新时间：2026-11-13T01:06:43.275Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：3.7 MB，25 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：3 个
- peer 依赖：ai ^7\.0\.0，react \>=18\.0\.0
- 首次发布：2026-03-18T11:32:38.697Z
- 最新版本发布：2026-11-13T07:51:02.619Z
- 近 30 天下载量：7197（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：129（近 12 个月 129 个）

## 中文简介

Dvina GraphQL API 的 SDK 类型安全

## 安装

```sh
npm install @dvina/sdk
```

也可以使用：`pnpm add @dvina/sdk`、`yarn add @dvina/sdk`、`bun add @dvina/sdk`

## README

# @dvina/ sdk (英语)

Dvina GraphQL API 的 SDK 类型安全 。 离线第一架构具有正版本地商店(IndexedDB),实时同步,一个回放适配器和一个AI SDK聊天传输.

## 安装

```bash
npm i @dvina/sdk
```

## 工作空间发展

从寄存器根 :

```bash
pnpm bootstrap
pnpm --filter @dvina/sdk run generate:workspace
pnpm --filter @dvina/sdk run build
```

或使用根快捷键 :

```bash
pnpm build:sdk
```

`generate:workspace` 首先构建编码器帮助包,再再生成SDK源. `build:workspace` 在一个命令中运行完整的生成+构建流.

同伴依赖 :

```bash
npm i graphql
```

框架适配器( 可选) :

```bash
# React
npm i react

# Chat (AI SDK)
npm i ai
```

## 快速启动

```typescript
import { DvinaSdk } from '@dvina/sdk';

const sdk = new DvinaSdk({ token: 'your-auth-token' });
```

用于制作带符号刷新的应用程序 :

```typescript
const sdk = new DvinaSdk({
    getToken: async () => {
        // return a fresh token from your auth provider
        return await authService.getAccessToken();
    },
});
```

### 选项

| 选项 | 类型 | 说明 |
| --- | --- | --- |
| `token` | `string` | 静态认证符 (标语, CLI, 测试) |
| `getToken` | `() => Promise<string>` | Async 令牌召回( 制作应用程序) |
| `baseUrl` | `string` | 没有协议的 API 基础 URL 。 默认 : `api.dvina.ai` |
| `language` | `string | (() => string)` | API 回复的首选语言 |

## 查询

### 获取单个实体

```typescript
const chat = await sdk.chat({ id: 'chat-id' }).fetch();

console.log(chat.id);
console.log(chat.title);
```

### 获取连接( 列表)

```typescript
const insights = await sdk.insights({ first: 20 }).fetch();

for (const insight of insights.nodes) {
    console.log(insight.id, insight.name);
}

console.log(insights.totalCount);
console.log(insights.pageInfo.hasNextPage);
```

### 智能获取( 包含关系)

链状关系方法 `.fetch()` 将相关数据纳入一项请求:

```typescript
// Include agent data inline with each chat
const chats = await sdk.chats({ first: 50 }).agent().fetch();

// agent is directly available on each node (no extra request)
for (const chat of chats.nodes) {
    console.log(chat.agent.id, chat.agent.name);
}

// Single entity with includes
const chat = await sdk.chat({ id: 'chat-id' }).agent().fetch();
console.log(chat.agent.name);
```

包含变量:

```typescript
const databases = await sdk.databases({ first: 100 }).tables({ first: 10 }).fetch();

for (const database of databases.nodes) {
    for (const table of database.tables.nodes) {
        console.log(table.name);
    }
}
```

### 懒惰关系获取

没有Smart Facker, 关系通过方法调用按需获取 :

```typescript
const chat = await sdk.chat({ id: 'chat-id' }).fetch();

// Separate request for the agent
const agent = await chat.agent().fetch();
console.log(agent.name);
```

## 倾斜

使用内置的 pagination 帮助连接遵循中继光标的规格 :

```typescript
const insights = await sdk.insights({ first: 20 }).fetch();

// Load next page (appends nodes, updates pageInfo)
if (insights.pageInfo.hasNextPage) {
    await insights.fetchNext();
}

// Load previous page (prepends nodes, updates pageInfo)
if (insights.pageInfo.hasPreviousPage) {
    await insights.fetchPrevious();
}
```

工具函数 :

```typescript
import { extractNodes, mergeConnections } from '@dvina/sdk/pagination';

const allNodes = extractNodes(insights);

// Returns a new connection without modifying the originals
const merged = mergeConnections(firstPage, secondPage);
```

## 变异

```typescript
// Create
const agent = await sdk.createAgent({
    data: { name: 'My Agent', description: 'An assistant' },
});

// Update
const updated = await sdk.updateInsight({
    where: { id: 'insight-id' },
    data: { name: 'Updated Name' },
});

// Delete
await sdk.deleteChat({ where: { id: 'chat-id' } });
```

突变自动以乐观更新和缓存规则更新本地商店.

## 反应查询( 监视)

使用 `.watch()` 改为 `.fetch()` 得到一个反应 `DvinaQueryRef` 当基础数据发生变化(通过本地变异、三角同步或缓存更新)时,会发出新值 :

```typescript
const ref = sdk.insights({ first: 20 }).watch();

// Vanilla JavaScript — AsyncIterable
for await (const insights of ref) {
    console.log('Updated:', insights.nodes.length);
}

// Clean up when done
ref.dispose();
```

`DvinaQueryRef` 属性 :

| 财产/方法 | 说明 |
| --- | --- |
| `current` | 最近发布的值( 或未定义) |
| `refetch()` | 强制从网络调试 |
| `fetchMore()` | 获取额外的页面并合并 |
| `dispose()` | 取消订阅和清理 |

## 聊天

聊天运行在AI SDK UI消息流上. `@dvina/sdk/ai` 提供运输 `useChat` 和信件类型 :

```tsx
import { useChat } from '@ai-sdk/react';
import { createDvinaChatTransport, stopDvinaChat, type DvinaUIMessage } from '@dvina/sdk/ai';

const chatOptions = { apiUrl: sdk.apiUrl, getToken: (options) => sdk.getToken(options) };
const transport = createDvinaChatTransport(chatOptions);

function Chat({ chatId }: { chatId: string }) {
    const { messages, sendMessage } = useChat<DvinaUIMessage>({ id: chatId, transport, resume: true });
    // render messages, call sendMessage({ text })
}

// Stop the running answer, on whichever API instance runs it
await stopDvinaChat(chatOptions, chatId);
```

传输只发送最新消息;服务器保存历史. 一个重新连接的客户端恢复了运行中的流.

## 实时活动

用户范围更新通过同步 SSE 连接作为快照到达 :

```typescript
const usage = sdk.events.tokenUsageStatus().watch(); // also activeChats(), devicePresence(), mcpAuth()
for await (const event of usage) {
    console.log(event.data);
}
```

`mcpAuth()` 列出等待用户授权的 MCP 服务器( 打开) `authorizationUrl`和最近的成果.

## 文件上传

```typescript
const file = new File(['content'], 'document.pdf', { type: 'application/pdf' });

const result = await sdk.uploadFile(file, 'document.pdf', {
    onProgress: (event) => {
        console.log(`${event.percent}% uploaded`);
    },
});

console.log('File ID:', result.id);
```

## 框架适应器

### 反应

```tsx
import { useLiveQuery } from '@dvina/sdk/react';

function InsightsPage() {
    const insights = useLiveQuery(() => sdk.insights({ first: 20 }).watch(), []);

    if (!insights) return <div>Loading...</div>;

    return (
        <ul>
            {insights.nodes.map((i) => (
                <li key={i.id}>{i.name}</li>
            ))}
        </ul>
    );
}
```

钩子是建立在 `useSyncExternalStore`。当依赖数组发生变化时,查询参考文件才会再次创建,所以内置 `.watch()` 电话是安全的.

```tsx
// Reactive query — ref recreated when `id` changes
function InsightDetail({ id }: { id: string }) {
    const insight = useLiveQuery(() => sdk.insight({ id }).watch(), [id]);

    if (!insight) return <div>Loading...</div>;
    return <h1>{insight.name}</h1>;
}
```

`useLiveQuery` 一旦没有组件使用就处理查询参考文件(不挂载或依赖性变化); 再次显示的组件获得新的参考文件.

## 处理错误

SDK 提供了打出的错误等级 :

```typescript
import { DvinaError, DvinaGraphQLError, DvinaNetworkError, DvinaAuthenticationError } from '@dvina/sdk';

try {
    await sdk.chat({ id: 'invalid' }).fetch();
} catch (error) {
    if (error instanceof DvinaAuthenticationError) {
        // 401/403 — redirect to login
    } else if (error instanceof DvinaGraphQLError) {
        // Server returned GraphQL errors
        console.error(error.errors);
    } else if (error instanceof DvinaNetworkError) {
        // Connection failure, timeout, etc.
        console.error(error.status);
    }
}
```

| 错误类 | 何时 |
| --- | --- |
| `DvinaError` | 所有 SDK 错误的基准类 |
| `DvinaGraphQLError` | 图QL 回复含有错误 |
| `DvinaNetworkError` | 网络失败、 超时、 非 OK HTTP |
| `DvinaAuthenticationError` | 401/403 认证失败 |

## 建筑

SDK使用一个 **离线第一, 普通商店** 结构 :

-   **查询** 经由 `SyncEngine`,将图形QL的回复规范化为索引数据库中的实体表格(通过Dexie).
-   **变异** 立即应用乐观的更新,然后与服务器的响应调和.
-   **Delta 同步** 保持源流实体改变的持续SSE连接,使本地商店实时更新.
-   **反应查询** (单位:千美元)`watch()`) 由德克西的后卫 `liveQuery` ——任何写入相关表格的自动重现.

```
DvinaSdk
├── Queries/Mutations → HTTP Transport → SyncEngine → IndexedDB (Dexie)
├── Delta Sync        → SSE Transport → IndexedDB (Dexie)
├── Realtime events   → SSE Transport → sdk.events
└── Chat              → AI SDK UI message stream (@dvina/sdk/ai)
```

## 清理

```typescript
// Stop delta sync
sdk.stopSync();

// Full teardown (stops sync and the billing stream, closes the local database)
sdk.destroy();
```

## 许可证

麻省理工学院

## 常见问题

### @dvina/sdk 是什么？

Dvina GraphQL API 的 SDK 类型安全

### 如何安装 @dvina/sdk？

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

### @dvina/sdk 支持 TypeScript 吗？

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

### @dvina/sdk 支持 ESM 还是 CommonJS？

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

### @dvina/sdk 可以商用吗？

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

### @dvina/sdk 的下载量有多少？

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

### @dvina/sdk 还在维护吗？

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

