@dvina/ sdk (英语)
Dvina GraphQL API 的 SDK 类型安全 。 离线第一架构具有正版本地商店(IndexedDB),实时同步,一个回放适配器和一个AI SDK聊天传输.
安装
npm i @dvina/sdk
工作空间发展
从寄存器根 :
pnpm bootstrap
pnpm --filter @dvina/sdk run generate:workspace
pnpm --filter @dvina/sdk run build
或使用根快捷键 :
pnpm build:sdk
generate:workspace 首先构建编码器帮助包,再再生成SDK源. build:workspace 在一个命令中运行完整的生成+构建流.
同伴依赖 :
npm i graphql
框架适配器( 可选) :
# React
npm i react
# Chat (AI SDK)
npm i ai
快速启动
import { DvinaSdk } from '@dvina/sdk';
const sdk = new DvinaSdk({ token: 'your-auth-token' });
用于制作带符号刷新的应用程序 :
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 回复的首选语言 |
查询
获取单个实体
const chat = await sdk.chat({ id: 'chat-id' }).fetch();
console.log(chat.id);
console.log(chat.title);
获取连接( 列表)
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() 将相关数据纳入一项请求:
// 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);
包含变量:
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, 关系通过方法调用按需获取 :
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 帮助连接遵循中继光标的规格 :
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();
}
工具函数 :
import { extractNodes, mergeConnections } from '@dvina/sdk/pagination';
const allNodes = extractNodes(insights);
// Returns a new connection without modifying the originals
const merged = mergeConnections(firstPage, secondPage);
变异
// 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 当基础数据发生变化(通过本地变异、三角同步或缓存更新)时,会发出新值 :
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 和信件类型 :
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 连接作为快照到达 :
const usage = sdk.events.tokenUsageStatus().watch(); // also activeChats(), devicePresence(), mcpAuth()
for await (const event of usage) {
console.log(event.data);
}
mcpAuth() 列出等待用户授权的 MCP 服务器( 打开) authorizationUrl和最近的成果.
文件上传
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);
框架适应器
反应
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() 电话是安全的.
// 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 提供了打出的错误等级 :
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)
清理
// Stop delta sync
sdk.stopSync();
// Full teardown (stops sync and the billing stream, closes the local database)
sdk.destroy();
许可证
麻省理工学院