# @gigadrive/sdk 中文文档

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

版本：0\.16\.0
npm 元数据更新时间：2026-11-01T04:40:28.680Z
中文译文更新时间：2026-11-01T05:55:13.978Z
软件包许可：Apache-2\.0

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

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

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

- 包体积（解压后）：2 MB，9 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=18\.0\.0
- 运行依赖：2 个
- 首次发布：2025-03-15T19:15:19.685Z
- 最新版本发布：2026-11-01T04:40:28.382Z
- 已发布版本数：61（近 12 个月 57 个）

## 中文简介

的官方TypeScript SDK [Gigadrive网络](https://gigadrive.de/) 云平台——组织、应用、部署、可恢复文件上传的存储，以及兼容openai的AI网关。

## 安装

```sh
npm install @gigadrive/sdk
```

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

## README

# @gigadrive / sdk

的官方TypeScript SDK [Gigadrive网络](https://gigadrive.de/) 云 平台-组织、应用程序、部署、具有可恢复文件的存储 以及兼容openai的AI网关。

可在Node.js 18+、浏览器和edge运行时(任何带有 `fetch`）。

## 安装

```bash
npm install @gigadrive/sdk
# or: pnpm add @gigadrive/sdk
```

## 快速启动

```ts
import { GigadriveClient } from '@gigadrive/sdk';

// Credentials are auto-detected from the environment (see below),
// or pass them explicitly.
const client = new GigadriveClient({
  clientId: process.env.GIGADRIVE_CLIENT_ID,
  clientSecret: process.env.GIGADRIVE_CLIENT_SECRET,
});

const { items: organizations } = await client.organizations.list();
const { items: applications } = await client.applications.list();
```

## 组织和产品权利

组织是Gigadrive产品的顶级帐户容器。 除了列出组织之外，SDK还可以创建组织、检查成员以及 检查产品授权（只读，SDK不会激活或更改计划）：

```ts
// Create an organization (user-backed token + platform:organizations:write)
const org = await client.organizations.create({ name: 'Acme Corp' });

// Fetch one organization and its members
const details = await client.organizations.get(org.id);
const { items: members } = await client.organizations.members.list(org.id);

// Inspect product access / entitlements (read-only)
const { items: products } = await client.organizations.products.list(org.id);
const office = await client.organizations.products.get(org.id, 'office');
const check = await client.organizations.products.checkEntitlement(org.id, 'office');

console.log(details.name, members.length, office.hasAccess, check.hasAccess, products.length);
```

## 身份验证

身份验证是为您处理的——令牌被获取、缓存和刷新 在幕后。通过构造函数或环境提供凭据 变量（构造函数值优先）：

| 方法 | 构造函数 | 环境 |
| --- | --- | --- |
| API密钥（机器对机器） | `clientId` + `clientSecret` | `GIGADRIVE_CLIENT_ID` + `GIGADRIVE_CLIENT_SECRET` |
| 预先取得的不记名令牌 | `bearerToken` | `GIGADRIVE_BEARER_TOKEN` |
| 刷新令牌 | `clientId` + `refreshToken` | `GIGADRIVE_CLIENT_ID` + `GIGADRIVE_REFRESH_TOKEN` |
| 授权码+ PKCE | `clientId` + `onAuthorizationUrl` | \- - - - - - |

上下文绑定存储调用还解析来自的应用程序UUID `applicationId` 在构造函数或 `GIGADRIVE_APPLICATION_ID`． Gigadrive 向后者注入工作负载凭据，因此可以正常部署服务器代码 不需要配置SDK。

```ts
// Custom fetch / base URL (e.g. for tests or non-standard runtimes)
const client = new GigadriveClient({ bearerToken: 'eyJ...', fetch: myFetch });
```

## 粘性的会话

已部署的MicroVM函数可以创建一个保持相同不透明的路由URL 一个函数实例上的应用程序键。注入工作负载凭据 平台，因此部署中不需要SDK配置：

```ts
import { GigadriveClient } from '@gigadrive/sdk';

const gigadrive = new GigadriveClient();
const { url, expiresAt } = await gigadrive.stickySessions.createUrl({
  key: gameId,
  endpoint: '/socket',
  expiresInSeconds: 14_400,
});

const socket = new WebSocket(url);
```

URL是路由权限，而不是用户身份验证。应用程序仍然拥有 授权和房间成员。状态保存在一个MicroVM的内存，url 过期，并且部署不会将该内存状态迁移到新版本。

## 文件存储

桶 `name` 是规范的REST和IaC标识符。名字是不可变的， 小写，url安全，并且在环境中是唯一的。返回的桶 `slug` 仍然是全局CDN/S3标识符，不应该传递给这些 其他的帮手。

为下的每个部署环境声明桶 `services.storage` 在 `gigadrive.yaml`． 映射键是规范的桶名； `null` 或者一个 空对象使用私有可见性。部署决定环境 并生成每个全局CDN/S3段塞。

```yaml
version: 4
services:
  storage:
    buckets:
      assets:
        visibility: public
      uploads: null
```

在部署的工作负载中，应用程序和环境上下文是推断出来的：

```ts
import { GigadriveClient } from '@gigadrive/sdk';

const client = new GigadriveClient();
const { items } = await client.storage.objects.list('assets');
```

管理调用方可以配置应用程序并选择环境 段塞或UUID：

```ts
const client = new GigadriveClient({ applicationId, clientId, clientSecret });
const bucket = await client.storage.buckets.create({
  name: 'assets',
  environment: 'production',
  visibility: 'public',
});

const { items } = await client.storage.objects.list(bucket.name, {
  environment: 'production',
});
```

现有的 `client.applications.storage` 电话,明确 `applicationId` 参数和桶uuid作为已弃用的兼容性仍然可用 路径。

### 文件上传

高级 `upload()` 计算所需的SHA-256校验和，推断出 内容类型，创建上传会话，并上传字节 与恢复转移-在一个呼叫。

```ts
// Node.js — upload straight from a file path (size, checksum, type inferred)
const { url } = await client.storage.upload({
  bucket: 'reports',
  key: 'reports/q1.pdf',
  path: './q1-report.pdf',
});

// Browser — upload a File with progress and cancellation
const controller = new AbortController();
const { url } = await client.storage.upload({
  bucket: 'uploads',
  key: `uploads/${file.name}`,
  data: file,
  onProgress: (sent, total) => console.log(`${Math.round((sent / total) * 100)}%`),
  signal: controller.signal,
});

// Wait until the object is finalized server-side, then read it back
const { object } = await client.storage.upload({
  bucket: 'avatars',
  key: 'avatars/user-1.png',
  data: bytes,
  waitForCompletion: true,
});
console.log(object?.contentLength, 'bytes stored');
```

可接受的输入：浏览器 `File`/`Blob`、节点 `Buffer`/`Uint8Array`/`ArrayBuffer`， a Node文件系统 `path`，或Node可读 `stream` (与 `contentLength` 和 `checksumSha256`）。

空文件，例如 `.gitkeep` 或者 `__init__.py` 处理各种输入类型。这个 API在创建上传会话时存储一个零字节对象，因此没有存储任何东西 转移, `waitForCompletion` 返回而不轮询，结果总是 包括 `object`． 为了一个空的 `stream`,通过 `contentLength: 0`;空 SHA-256已为您填写。

#### 同时处理多个文件

```ts
const results = await client.storage.uploadBatch(
  files.map((f) => ({ bucket: 'uploads', key: f.name, data: f })),
  { concurrency: 6, onProgress: (done, total) => console.log(`${done}/${total}`) }
);
const failed = results.filter((r) => r.error);
```

### 处理物品和垃圾

```ts
// List a "folder" one level deep
const { items, commonPrefixes } = await client.storage.objects.list('assets', {
  prefix: 'images/',
  limit: 100,
});

// Signed download URL for a private object
const { url } = await client.storage.objects.getAccessUrl('assets', objectId, {
  expiresInSeconds: 3600,
});

// Delete moves an object to trash; restore or permanently purge it later
await client.storage.objects.delete('assets', objectId);
await client.storage.trash.restore('assets', objectId);
await client.storage.trash.purge('assets', objectId);

// Permanently purge every trashed object in the bucket
const { purgedCount } = await client.storage.trash.empty('assets');
```

## 人工智能网关

openai兼容聊天完成，响应，音频，视频和模型发现。

```ts
// Chat completion
const res = await client.aiGateway.chatCompletions({
  model: 'openai/gpt-4o',
  messages: [{ role: 'user', content: 'Hello!' }],
});
console.log(res.choices[0].message.content);

// Streaming
for await (const chunk of client.aiGateway.chatCompletionsStream({
  model: 'openai/gpt-4o',
  messages: [{ role: 'user', content: 'Write a haiku about the sea.' }],
})) {
  process.stdout.write(chunk.choices[0]?.delta.content ?? '');
}

// Models
const { items: models } = await client.aiGateway.listModels();
```

组织范围的治理（使用分析、预算、策略）生活在下面 `client.organizations.aiGateway`.

## 定制域

将您拥有的主机名附加到应用程序。响应列出要发布的DNS记录；Gigadrive 然后网络验证所有权，检查DNS并自行颁发证书。

```ts
import { DomainNotActiveError } from '@gigadrive/sdk';

const domain = await client.applications.domains.add('app-id', { hostname: 'shop.example.com' });
for (const record of domain.requiredRecords) {
  console.log(record.type, record.host, record.value);
}

try {
  await client.applications.domains.waitUntilActive('app-id', domain.id, {
    timeoutMs: 15 * 60_000,
    onState: (current) => console.log(current.state),
  });
} catch (error) {
  if (!(error instanceof DomainNotActiveError)) throw error;
  // `reason` is `timeout`, `failed`, `suspended` or `removing`; `domain.error` explains what to fix.
  console.error(error.reason, error.domain.error?.message);
}
```

重定向一个域，或者服务于分支而不是生产：

```ts
await client.applications.domains.update('app-id', domain.id, {
  target: { type: 'redirect', to: 'www.example.com', statusCode: 308 },
});
```

验证一次可注册域，让组织的每个应用程序附加主机名 下面没有另一个TXT记录：

```ts
const claim = await client.organizations.domains.add('org-id', 'example.com');
console.log(claim.record.host, claim.record.value); // publish this TXT record
await client.organizations.domains.verify('org-id', claim.id);
```

## 队列

队列在后台将工作交付给你的应用程序，现在或以后。具有使用者路径的队列是推送队列：Gigadrive Network将每条消息发送到部署中的该路径。没有一个，它是一个拉队列，你消耗 `receive()`.

```ts
import { NonRetryableError, queue, RetryLaterError } from '@gigadrive/sdk';

export const emails = queue<{ to: string; template: string }>('emails');

// Send now, after a delay, or at a time (up to a year ahead).
await emails.send({ to: 'jane@example.com', template: 'welcome' });
await emails.send({ to: 'jane@example.com', template: 'nudge' }, { delay: '3d', deduplicationKey: 'nudge:jane' });

// app/api/queues/emails/route.ts: the push consumer. Signatures are verified for you.
export const POST = emails.handler(async (email, { attempt }) => {
  if (!templates.has(email.template)) throw new NonRetryableError('Unknown template'); // dead-letter now
  if (await mailer.isThrottled()) throw new RetryLaterError('1m'); // defer without spending an attempt
  await mailer.send(email); // returning acknowledges the message
});
```

声明推送消费者和任何cron调度 `gigadrive.yaml`，或从代码中创建 `emails.ensure({ consumerPath: '/api/queues/emails' })` 和 `emails.schedule(...)`.

拉消费者租赁信息并解决它们：

```ts
const jobs = queue<{ id: string }>('jobs');

await jobs.consume(async (job) => processJob(job.id), { maxMessages: 10, stopWhenEmpty: true });
```

`client.queues` 公开完整的REST表面（队列、消息、死信、调度），并且 `createWorkflowQueue()` 运行 [工作流SDK](https://workflow-sdk.dev/) 在gigdrive Network队列上。

## microVMs

microvm是您根据需要创建的隔离的Linux机器：运行命令，移动 文件输入和输出，并在公共预览url上公开端口。将它们用于代码 执行，代理沙箱，CI步骤和预览。

```ts
import { MicroVM } from '@gigadrive/sdk';

await using vm = await MicroVM.create({ image: 'node22', ports: [3000], timeout: '10m' });

await vm.files.write('server.js', 'require("http").createServer((_, r) => r.end("hi")).listen(3000)');
const { exitCode, stdout } = await vm.run('node --version');
const server = await vm.spawn('node', ['server.js']);
console.log(await vm.waitForPort(3000)); // https://3000-<slug>.vm.gigadrive.app
// Leaving the block stops the microVM.
```

`MicroVM.create` 解析它的客户端 `GigadriveClient` (通过 `client` 使用 你自己的)和它的应用程序 `applicationId`，客户的 `applicationId` 或者 `GIGADRIVE_APPLICATION_ID`． 在千兆驱动器部署中 不需要任何配置。内置的图片: `node22`， `node24`， `python3.13`， `python3.12`， `bun1`， `debian12`， `ubuntu24.04`.

| 任务 | 呼叫 |
| --- | --- |
| 创建，连接，列表 | `MicroVM.create({ image, vcpus, memoryMb, diskMb, timeout, ports, env, metadata, network })`， `MicroVM.get(id)`， `for await (const vm of MicroVM.list())` |
| 跑啊，等啊 | `vm.run('ls -la')`， `vm.run('npm', ['test'], { cwd, env, user, sudo, timeout, onStdout, onStderr, stdin, throwOnError, signal })` → `{ exitCode, signal, timedOut, stdout, stderr, truncated, durationMs }` |
| 在后台运行 | `vm.spawn(cmd, args, { stdin, pty, onStdout })` → `Command`： `logs()`， `output()`， `stdout()`， `stderr()`， `wait()`， `kill(signal)`， `write(data)`， `end()`， `resize(cols, rows)` |
| 重新接上 | `vm.commands.get(commandId)`， `vm.commands.list()` |
| 文件 | `vm.files.write(path, string | Uint8Array | Blob | ReadableStream)`， `writeMany`， `read`， `readText`， `readStream`， `list(path, { recursive })`， `stat`， `exists`， `mkdir`， `remove`， `move` |
| 港口 | `vm.url(port)`， `vm.waitForPort(port)` |
| 一生 | `vm.extendTimeout('30m')`， `vm.stop()`， `vm.delete()`， `await using vm = ...` |
| 网络 | `vm.updateNetwork('deny')`， `vm.updateNetwork({ egress: 'allow', allow: ['registry.npmjs.org', '*.github.com'] })`：改变它运行时可能到达的位置 |
| 指标 | `vm.getMetrics({ windowMinutes: 60 })` → `{ cpu: [{ time, cpuPercent }], current: { memoryUsedBytes, memoryTotalBytes, diskUsedBytes, diskTotalBytes } | null }` |
| 人则 | `client.microvms.webhooks.create({ url, events: ['microvm.stopped'] })` → `{ id, secret }`， `.list()`， `.update(id, { enabled })`， `.rotateSecret(id)`， `.listDeliveries(id)`;验证请求 `verifyMicroVmWebhook({ body, headers, secret })` |
| 图片 | `client.microvms.images.create({ name, from: 'python:3.13' | { dockerfile } })`， `.waitUntilReady(id)`， `.list()`， `.get(id)`， `.delete(id)` |

命令输出保留在microVM中，因此 `command.logs()` 可以从 另一个过程是 `vm.commands.get(id)`，并恢复断开的连接 在下一个未读字节。非零退出码是正常结果；通过 `throwOnError: true` 为了得到一个 `CommandFailedError`． 其他输入错误： `MicroVmNotRunningError`， `MicroVmNotFoundError`， `MicroVmFileNotFoundError`， `MicroVmQuotaExceededError`， `MicroVmBusyError`， `MicroVmUnreachableError`， `MicroVmImageNotReadyError`， `MicroVmPortNotExposedError`， `MicroVmTimeoutError`， `MicroVmStartError` 和 `MicroVmImageBuildError`. 当microVM应答时，读取和日志流将以backoff方式重试 `microvm_busy`． microVM最多存活24小时(`MICROVM_MAX_TIMEOUT_MS`)， 或者在你的计划中更少。

`client.microvms` 底层REST表面是每个路由一个方法吗 （`create`， `list`， `listAll`， `get`， `getMetrics`， `extendTimeout`， `updateNetwork`， `stop`， `delete`， `commands.*`， `files.*`， `images.*`， `webhooks.*`）. SDK只使用 `fetch`，所以它运行 Node.js 18+, Bun, Deno， edge运行时和Gigadrive函数。

## 分页

接受列表端点 `page` / `perPage` / `cursor` 并返回 `{ items, total }` (游标分页的端点也会返回 `nextCursor`）. 迭代所有内容 这个 `paginate` 助手:

```ts
import { paginate } from '@gigadrive/sdk';

for await (const object of paginate((cursor) => client.storage.objects.list('assets', { cursor }))) {
  console.log(object.key);
}
```

## 错误

所有错误扩展 `GigadriveError`． 明显的子类: `ApiError` (与 `status` 和可选的 `code`)， `AuthenticationError`， `ConfigurationError`， `UploadError`, `UploadSessionExpiredError`.

```ts
import { ApiError } from '@gigadrive/sdk';

try {
  await client.deployments.get('missing');
} catch (err) {
  if (err instanceof ApiError) console.error(err.status, err.message);
}
```

## 许可证

apache - 2.0

## 常见问题

### @gigadrive/sdk 是什么？

的官方TypeScript SDK Gigadrive网络 云平台——组织、应用、部署、可恢复文件上传的存储，以及兼容openai的AI网关。

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

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

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

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

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

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

### @gigadrive/sdk 需要什么版本的 Node\.js？

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

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

@gigadrive/sdk 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

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

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

