# @computesdk/upstash 中文文档

规范地址：https://npmcn.com/package/%40computesdk/upstash/

版本：0\.3\.28
npm 元数据更新时间：2026-11-06T13:39:59.396Z
中文译文更新时间：2026-11-10T14:25:10.040Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：101 kB，9 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：3 个
- 首次发布：2026-03-25T16:48:31.609Z
- 最新版本发布：2026-11-06T13:39:59.029Z
- 近 30 天下载量：10388（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：33（近 12 个月 33 个）

## 中文简介

计算SDK的 Upstash Box 提供者 - 有代码执行、文件系统访问和 AI 代理支持的云沙盒

## 安装

```sh
npm install @computesdk/upstash
```

也可以使用：`pnpm add @computesdk/upstash`、`yarn add @computesdk/upstash`、`bun add @computesdk/upstash`

## README

# @computesdk/upstash (帮助)

计算SDK的 Upstash Box 提供商 - 在云沙盒中执行代码,并拥有完整的文件系统访问, shell 命令,快照,并预览 URL.

## 安装

```bash
npm install @computesdk/upstash
```

## 设置

1.  获取您的 Upstash Box API 密钥 [控制台.upstash.com](https://console.upstash.com/)
2.  设置环境变量 :

```bash
export UPSTASH_BOX_API_KEY=your_api_key_here
```

## 快速启动

```typescript
import { upstash } from '@computesdk/upstash';

const compute = upstash({ apiKey: process.env.UPSTASH_BOX_API_KEY });

const sandbox = await compute.instances.create();

const result = await sandbox.runCommand(`python - <<'PY'
import pandas as pd
print(pd.__version__)
PY`);

console.log(result.stdout);
await sandbox.destroy();
```

## 配置

### 环境变量

```bash
export UPSTASH_BOX_API_KEY=your_api_key_here
```

### 配置选项

```typescript
interface UpstashConfig {
  /** Upstash Box API key - if not provided, will use UPSTASH_BOX_API_KEY env var */
  apiKey?: string;
  /** Default runtime environment (e.g. 'node', 'python') */
  runtime?: string;
  /** Execution timeout in milliseconds (default: 600000) */
  timeout?: number;
}
```

## 特征

-   **命令执行** - 在沙盒中运行 shell 命令( Python/ Node.js 可用)
-   **文件系统操作** - 完整文件系统访问
-   **预览 URL** - 为运行服务获取可公开获取的URL
-   **抓图** - 保存并恢复沙盒状态

## API 参考

### 命令执行

````typescript
// Run Python code via heredoc
const result = await sandbox.runCommand(`python - <<'PY'
import json
data = {"message": "Hello from Python"}
print(json.dumps(data))
PY`);

// Run Node.js code via heredoc
const result = await sandbox.runCommand(`node - <<'JS'
const data = { message: "Hello from Node.js" };
console.log(JSON.stringify(data));
JS`);

```typescript
// List files
const result = await sandbox.runCommand('ls -la');

// Install packages
const result = await sandbox.runCommand('pip install requests');

// Run with environment variables
const result = await sandbox.runCommand('echo $MY_VAR', {
  env: { MY_VAR: 'hello' },
});

// Run with working directory
const result = await sandbox.runCommand('ls', { cwd: '/workspace/home/myproject' });

// Run in background
const result = await sandbox.runCommand('node server.js', { background: true });
````

### 文件系统操作

```typescript
// Write file
await sandbox.filesystem.writeFile('/tmp/hello.py', 'print("Hello World")');

// Read file
const content = await sandbox.filesystem.readFile('/tmp/hello.py');

// Create directory
await sandbox.filesystem.mkdir('/tmp/data');

// List directory contents
const files = await sandbox.filesystem.readdir('/tmp');

// Check if file exists
const exists = await sandbox.filesystem.exists('/tmp/hello.py');

// Remove file or directory
await sandbox.filesystem.remove('/tmp/hello.py');
```

### 预览 URL

```typescript
// Get a publicly accessible URL for a running service
const url = await sandbox.getUrl({ port: 3000 });
console.log(url); // https://<box-id>-3000.box.upstash.io
```

### 抓图

```typescript
import { upstash } from '@computesdk/upstash';

const compute = upstash({ apiKey: process.env.UPSTASH_BOX_API_KEY });

// Create a snapshot of a running sandbox
const snapshot = await compute.snapshot.create(sandbox.id, {
  name: 'my-checkpoint',
});

console.log(snapshot.id, snapshot.metadata);

// Restore from a snapshot
const restored = await compute.instances.create({
  snapshotId: snapshot.id,
});
```

### 沙盒管理

```typescript
// Get sandbox info
const info = await sandbox.getInfo();
console.log(info.id, info.status, info.createdAt);

// Reconnect to existing sandbox
const existing = await compute.instances.getById('box-id');

// List all sandboxes
const sandboxes = await compute.instances.list();

// Destroy sandbox
await sandbox.destroy();
```

## 处理错误

```typescript
import { upstash } from '@computesdk/upstash';

try {
  const compute = upstash({ apiKey: process.env.UPSTASH_BOX_API_KEY });
  const sandbox = await compute.instances.create();

  const result = await sandbox.runCommand('invalid code');
} catch (error) {
  if (error.message.includes('Missing Upstash Box API key')) {
    console.error('Set UPSTASH_BOX_API_KEY environment variable');
  } else if (error.message.includes('authentication failed')) {
    console.error('Check your Upstash Box API key');
  } else if (error.message.includes('quota exceeded')) {
    console.error('Upstash usage limits reached');
  }
}
```

## 实例

### 数据科学工作流程

```typescript
import { upstash } from '@computesdk/upstash';

const compute = upstash({ apiKey: process.env.UPSTASH_BOX_API_KEY });
const sandbox = await compute.instances.create();

// Create project structure
await sandbox.filesystem.mkdir('/analysis/data');
await sandbox.filesystem.mkdir('/analysis/output');

// Write input data
const csvData = `name,age,city
Alice,25,New York
Bob,30,San Francisco
Charlie,35,Chicago`;

await sandbox.filesystem.writeFile('/analysis/data/people.csv', csvData);

// Process data with Python
const result = await sandbox.runCommand(`python - <<'PY'
import pandas as pd
import matplotlib.pyplot as plt

# Read data
df = pd.read_csv('/analysis/data/people.csv')
print("Data loaded:")
print(df)

# Calculate statistics
avg_age = df['age'].mean()
print(f"\\nAverage age: {avg_age}")

# Create visualization
plt.figure(figsize=(8, 6))
plt.bar(df['name'], df['age'])
plt.title('Age by Person')
plt.savefig('/analysis/output/age_chart.png')
print("\\nChart saved!")
PY`);

console.log(result.stdout);

await sandbox.destroy();
```

### 带预览 URL 的 Web 服务器

```typescript
import { upstash } from '@computesdk/upstash';

const compute = upstash({ apiKey: process.env.UPSTASH_BOX_API_KEY });
const sandbox = await compute.instances.create();

// Write a simple server
await sandbox.filesystem.writeFile('/server.js', `
const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ status: 'ok' }));
});
server.listen(3000, () => console.log('Server running on port 3000'));
`);

// Start server in background
await sandbox.runCommand('node /server.js', { background: true });

// Get the public URL
const url = await sandbox.getUrl({ port: 3000 });
console.log('Server available at:', url);

await sandbox.destroy();
```

## 最佳做法

1.  **资源管理**: 完成释放资源时总是销毁沙盒
2.  **处理错误**: 使用试捕取区块进行稳健的错误处理
3.  **超时**: 为长期任务设定适当的超时( 默认为10分钟)
4.  **文件路径**: 所有路径都相对 `/workspace/home`
5.  **抓图**: 使用快照保存并恢复可复制环境的沙盒状态
6.  **API 密钥安全**: 从不向版本控制输入 API 密钥

## 限制

-   **文件路径**: 所有文件系统操作范围都在 `/workspace/home`
-   **内存限制**: 受Upstash Box资源限制
-   **抓图删除**: 快照删除需要框上下文
-   **模板支持**: 使用快照而不是模板来保存框状态

## 支助

-   [上层文档](https://upstash.com/docs)
-   [计算SDK问题](https://github.com/computesdk/computesdk/issues)
-   [上层控制台](https://console.upstash.com/)

## 许可证

麻省理工学院

## 常见问题

### @computesdk/upstash 是什么？

计算SDK的 Upstash Box 提供者 - 有代码执行、文件系统访问和 AI 代理支持的云沙盒

### 如何安装 @computesdk/upstash？

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

### @computesdk/upstash 支持 TypeScript 吗？

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

### @computesdk/upstash 支持 ESM 还是 CommonJS？

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

### @computesdk/upstash 可以商用吗？

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

### @computesdk/upstash 的下载量有多少？

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

### @computesdk/upstash 还在维护吗？

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

