@cloudflare/sandbox 0.0.0-0dad837 โ 0.0.0-102fc4f
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +248 -0
- package/Dockerfile +173 -89
- package/LICENSE +176 -0
- package/README.md +92 -707
- package/dist/index.d.ts +1953 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3280 -0
- package/dist/index.js.map +1 -0
- package/package.json +16 -8
- package/src/clients/base-client.ts +295 -0
- package/src/clients/command-client.ts +115 -0
- package/src/clients/file-client.ts +300 -0
- package/src/clients/git-client.ts +98 -0
- package/src/clients/index.ts +64 -0
- package/src/clients/interpreter-client.ts +333 -0
- package/src/clients/port-client.ts +105 -0
- package/src/clients/process-client.ts +180 -0
- package/src/clients/sandbox-client.ts +39 -0
- package/src/clients/types.ts +88 -0
- package/src/clients/utility-client.ts +156 -0
- package/src/errors/adapter.ts +238 -0
- package/src/errors/classes.ts +594 -0
- package/src/errors/index.ts +109 -0
- package/src/file-stream.ts +169 -0
- package/src/index.ts +93 -45
- package/src/interpreter.ts +62 -44
- package/src/request-handler.ts +94 -55
- package/src/sandbox.ts +879 -399
- package/src/security.ts +34 -28
- package/src/sse-parser.ts +8 -11
- package/src/version.ts +6 -0
- package/startup.sh +3 -0
- package/tests/base-client.test.ts +364 -0
- package/tests/command-client.test.ts +444 -0
- package/tests/file-client.test.ts +831 -0
- package/tests/file-stream.test.ts +310 -0
- package/tests/get-sandbox.test.ts +149 -0
- package/tests/git-client.test.ts +487 -0
- package/tests/port-client.test.ts +293 -0
- package/tests/process-client.test.ts +683 -0
- package/tests/request-handler.test.ts +292 -0
- package/tests/sandbox.test.ts +739 -0
- package/tests/sse-parser.test.ts +291 -0
- package/tests/utility-client.test.ts +339 -0
- package/tests/version.test.ts +16 -0
- package/tests/wrangler.jsonc +35 -0
- package/tsconfig.json +9 -1
- package/tsdown.config.ts +12 -0
- package/vitest.config.ts +31 -0
- package/container_src/bun.lock +0 -122
- package/container_src/circuit-breaker.ts +0 -121
- package/container_src/handler/exec.ts +0 -340
- package/container_src/handler/file.ts +0 -1064
- package/container_src/handler/git.ts +0 -182
- package/container_src/handler/ports.ts +0 -314
- package/container_src/handler/process.ts +0 -640
- package/container_src/index.ts +0 -663
- package/container_src/jupyter-server.ts +0 -579
- package/container_src/jupyter-service.ts +0 -461
- package/container_src/jupyter_config.py +0 -48
- package/container_src/mime-processor.ts +0 -255
- package/container_src/package.json +0 -18
- package/container_src/startup.sh +0 -84
- package/container_src/types.ts +0 -117
- package/src/client.ts +0 -1024
- package/src/errors.ts +0 -218
- package/src/interpreter-types.ts +0 -383
- package/src/jupyter-client.ts +0 -349
- package/src/types.ts +0 -511
package/README.md
CHANGED
|
@@ -1,744 +1,132 @@
|
|
|
1
|
-
<
|
|
2
|
-
<h1>๐ฆ Cloudflare Sandbox SDK</h1>
|
|
3
|
-
<h3><strong>Run sandboxed code environments on Cloudflare's edge network</strong></h3>
|
|
4
|
-
<p>
|
|
5
|
-
<a href="https://www.npmjs.com/package/@cloudflare/sandbox"><img src="https://img.shields.io/npm/v/@cloudflare/sandbox.svg" alt="npm version"></a>
|
|
6
|
-
<a href="https://github.com/cloudflare/sandbox-sdk"><img src="https://img.shields.io/badge/status-experimental-orange.svg" alt="status"></a>
|
|
7
|
-
</p>
|
|
8
|
-
</div>
|
|
9
|
-
|
|
10
|
-
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
|
|
11
|
-
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
|
|
12
|
-
|
|
13
|
-
- [โจ Overview](#overview)
|
|
14
|
-
- [๐ฏ Features](#features)
|
|
15
|
-
- [๐ Quick Start](#quick-start)
|
|
16
|
-
- [Installation](#installation)
|
|
17
|
-
- [Basic Setup](#basic-setup)
|
|
18
|
-
- [๐ API Reference](#api-reference)
|
|
19
|
-
- [Core Methods](#core-methods)
|
|
20
|
-
- [๐งช Code Interpreter](#code-interpreter)
|
|
21
|
-
- [Code Execution](#code-execution)
|
|
22
|
-
- [Rich Outputs](#rich-outputs)
|
|
23
|
-
- [Output Formats](#output-formats)
|
|
24
|
-
- [๐ Port Forwarding](#port-forwarding)
|
|
25
|
-
- [Utility Methods](#utility-methods)
|
|
26
|
-
- [๐ก Examples](#examples)
|
|
27
|
-
- [Run a Node.js App](#run-a-nodejs-app)
|
|
28
|
-
- [Build and Test Code](#build-and-test-code)
|
|
29
|
-
- [Interactive Development Environment](#interactive-development-environment)
|
|
30
|
-
- [Expose Services with Preview URLs](#expose-services-with-preview-urls)
|
|
31
|
-
- [Data Analysis with Code Interpreter](#data-analysis-with-code-interpreter)
|
|
32
|
-
- [๐๏ธ Architecture](#architecture)
|
|
33
|
-
- [๐ ๏ธ Advanced Usage](#advanced-usage)
|
|
34
|
-
- [AsyncIterable Streaming Support](#asynciterable-streaming-support)
|
|
35
|
-
- [Session Management](#session-management)
|
|
36
|
-
- [๐ Debugging](#debugging)
|
|
37
|
-
- [๐ง Known Limitations](#known-limitations)
|
|
38
|
-
- [๐ค Contributing](#contributing)
|
|
39
|
-
- [๐ License](#license)
|
|
40
|
-
- [๐ Acknowledgments](#acknowledgments)
|
|
41
|
-
|
|
42
|
-
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
|
|
43
|
-
|
|
44
|
-
<h2 id="overview">โจ Overview</h2>
|
|
45
|
-
|
|
46
|
-
The Cloudflare Sandbox SDK enables you to run isolated code environments directly on Cloudflare's edge network using Durable Objects and the Cloudflare Containers. Execute commands, manage files, run services, and expose them via public URLs - all within secure, sandboxed containers.
|
|
47
|
-
|
|
48
|
-
<h2 id="features">๐ฏ Features</h2>
|
|
49
|
-
|
|
50
|
-
- **๐ Secure Isolation**: Each sandbox runs in its own container with full process isolation
|
|
51
|
-
- **โก Edge-Native**: Runs on Cloudflare's global network for low latency worldwide
|
|
52
|
-
- **๐ File System Access**: Read, write, and manage files within the sandbox
|
|
53
|
-
- **๐ง Command Execution**: Run any command or process inside the container
|
|
54
|
-
- **๐ Preview URLs**: Expose services running in your sandbox via public URLs
|
|
55
|
-
- **๐ Git Integration**: Clone repositories directly into sandboxes
|
|
56
|
-
- **๐ Streaming Support**: Real-time output streaming for long-running commands
|
|
57
|
-
- **๐ฎ Session Management**: Maintain state across multiple operations
|
|
58
|
-
- **๐งช Code Interpreter**: Execute Python and JavaScript with rich outputs (charts, tables, formatted data)
|
|
59
|
-
- **๐ Multi-Language Support**: Persistent execution contexts for Python and JavaScript/TypeScript
|
|
60
|
-
- **๐จ Rich MIME Types**: Automatic processing of images, HTML, charts, and structured data
|
|
61
|
-
|
|
62
|
-
<h2 id="quick-start">๐ Quick Start</h2>
|
|
63
|
-
|
|
64
|
-
### Installation
|
|
1
|
+
<img width="1362" height="450" alt="Image" src="https://github.com/user-attachments/assets/6f770ae3-0a14-4d2b-9aed-a304ee5446c5" />
|
|
65
2
|
|
|
66
|
-
|
|
67
|
-
npm install @cloudflare/sandbox
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
### Basic Setup
|
|
71
|
-
|
|
72
|
-
1. **Create a Dockerfile** (temporary requirement, will be removed in future releases):
|
|
73
|
-
|
|
74
|
-
```dockerfile
|
|
75
|
-
FROM docker.io/cloudflare/sandbox:0.2.4
|
|
76
|
-
|
|
77
|
-
# Expose the ports you want to expose
|
|
78
|
-
EXPOSE 3000
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
2. **Configure wrangler.json**:
|
|
82
|
-
|
|
83
|
-
> **NOTE**: In an upcoming release, this step will be removed entirely and you can reference a single Docker image published by us directly in your wrangler configuration below.
|
|
84
|
-
|
|
85
|
-
```jsonc
|
|
86
|
-
{
|
|
87
|
-
// ...
|
|
88
|
-
"containers": [
|
|
89
|
-
{
|
|
90
|
-
"class_name": "Sandbox",
|
|
91
|
-
"image": "./Dockerfile",
|
|
92
|
-
"max_instances": 1
|
|
93
|
-
}
|
|
94
|
-
],
|
|
95
|
-
"durable_objects": {
|
|
96
|
-
"bindings": [
|
|
97
|
-
{
|
|
98
|
-
"class_name": "Sandbox",
|
|
99
|
-
"name": "Sandbox"
|
|
100
|
-
}
|
|
101
|
-
]
|
|
102
|
-
},
|
|
103
|
-
"migrations": [
|
|
104
|
-
{
|
|
105
|
-
"new_sqlite_classes": ["Sandbox"],
|
|
106
|
-
"tag": "v1"
|
|
107
|
-
}
|
|
108
|
-
]
|
|
109
|
-
}
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
3. **Create your Worker**:
|
|
113
|
-
|
|
114
|
-
```typescript
|
|
115
|
-
import { getSandbox } from "@cloudflare/sandbox";
|
|
116
|
-
|
|
117
|
-
// Export the Sandbox class in your Worker
|
|
118
|
-
export { Sandbox } from "@cloudflare/sandbox";
|
|
119
|
-
|
|
120
|
-
export default {
|
|
121
|
-
async fetch(request: Request, env: Env) {
|
|
122
|
-
const sandbox = getSandbox(env.Sandbox, "my-sandbox");
|
|
123
|
-
|
|
124
|
-
// Execute a command
|
|
125
|
-
const result = await sandbox.exec("echo 'Hello from the edge!'");
|
|
126
|
-
return new Response(result.stdout);
|
|
127
|
-
},
|
|
128
|
-
};
|
|
129
|
-
```
|
|
130
|
-
|
|
131
|
-
<h2 id="api-reference">๐ API Reference</h2>
|
|
132
|
-
|
|
133
|
-
### Core Methods
|
|
134
|
-
|
|
135
|
-
#### Command Execution
|
|
136
|
-
|
|
137
|
-
**`exec(command, options?)`** - Enhanced command execution that always returns results
|
|
138
|
-
|
|
139
|
-
```typescript
|
|
140
|
-
// Simple execution
|
|
141
|
-
const result = await sandbox.exec("npm install express");
|
|
142
|
-
console.log(result.stdout, result.exitCode);
|
|
143
|
-
|
|
144
|
-
// With streaming callbacks
|
|
145
|
-
const result = await sandbox.exec("npm run build", {
|
|
146
|
-
stream: true,
|
|
147
|
-
onOutput: (stream, data) => console.log(`[${stream}] ${data}`)
|
|
148
|
-
});
|
|
149
|
-
```
|
|
150
|
-
|
|
151
|
-
**`execStream(command, options?)`** - Dedicated streaming method returning SSE stream
|
|
3
|
+
# Cloudflare Sandbox SDK
|
|
152
4
|
|
|
153
|
-
|
|
154
|
-
import { parseSSEStream, type ExecEvent } from '@cloudflare/sandbox';
|
|
155
|
-
|
|
156
|
-
const stream = await sandbox.execStream("npm run test");
|
|
157
|
-
for await (const event of parseSSEStream<ExecEvent>(stream)) {
|
|
158
|
-
switch (event.type) {
|
|
159
|
-
case 'stdout':
|
|
160
|
-
console.log(`Test output: ${event.data}`);
|
|
161
|
-
break;
|
|
162
|
-
case 'complete':
|
|
163
|
-
console.log(`Tests ${event.exitCode === 0 ? 'passed' : 'failed'}`);
|
|
164
|
-
break;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
```
|
|
168
|
-
|
|
169
|
-
**`startProcess(command, options?)`** - Start background processes with lifecycle management
|
|
170
|
-
|
|
171
|
-
```typescript
|
|
172
|
-
const process = await sandbox.startProcess("node server.js");
|
|
173
|
-
console.log(`Started process ${process.id} with PID ${process.pid}`);
|
|
174
|
-
|
|
175
|
-
// Monitor the process
|
|
176
|
-
const logStream = await sandbox.streamProcessLogs(process.id);
|
|
177
|
-
for await (const log of parseSSEStream<LogEvent>(logStream)) {
|
|
178
|
-
console.log(`Server: ${log.data}`);
|
|
179
|
-
}
|
|
180
|
-
```
|
|
5
|
+
[](https://www.npmjs.com/package/@cloudflare/sandbox)
|
|
181
6
|
|
|
182
|
-
|
|
7
|
+
**Build secure, isolated code execution environments on Cloudflare.**
|
|
183
8
|
|
|
184
|
-
|
|
9
|
+
The Sandbox SDK lets you run untrusted code safely in isolated containers. Execute commands, manage files, run background processes, and expose services โ all from your Workers applications.
|
|
185
10
|
|
|
186
|
-
|
|
187
|
-
await sandbox.writeFile("/workspace/app.js", "console.log('Hello!');");
|
|
188
|
-
```
|
|
11
|
+
Perfect for AI code execution, interactive development environments, data analysis platforms, CI/CD systems, and any application that needs secure code execution at the edge.
|
|
189
12
|
|
|
190
|
-
|
|
13
|
+
## Getting Started
|
|
191
14
|
|
|
192
|
-
|
|
15
|
+
### Prerequisites
|
|
193
16
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
```
|
|
17
|
+
1. Install [Node.js](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) (version 16.17.0 or later)
|
|
18
|
+
2. Ensure Docker is running locally
|
|
19
|
+
3. For deploying to production, sign up for a [Cloudflare account](https://dash.cloudflare.com/sign-up/workers-and-pages)
|
|
198
20
|
|
|
199
|
-
|
|
21
|
+
### 1. Create a new project
|
|
200
22
|
|
|
201
|
-
|
|
23
|
+
Create a new Sandbox SDK project using the minimal template:
|
|
202
24
|
|
|
203
|
-
```
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
targetDir: "my-project",
|
|
207
|
-
});
|
|
25
|
+
```bash
|
|
26
|
+
npm create cloudflare@latest -- my-sandbox --template=cloudflare/sandbox-sdk/examples/minimal
|
|
27
|
+
cd my-sandbox
|
|
208
28
|
```
|
|
209
29
|
|
|
210
|
-
|
|
30
|
+
### 2. Test locally
|
|
211
31
|
|
|
212
|
-
|
|
32
|
+
Start the development server:
|
|
213
33
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
```typescript
|
|
218
|
-
const sandbox = getSandbox(env.Sandbox, "my-sandbox");
|
|
219
|
-
|
|
220
|
-
// Set environment variables FIRST, before any other operations
|
|
221
|
-
await sandbox.setEnvVars({
|
|
222
|
-
NODE_ENV: "production",
|
|
223
|
-
API_KEY: "your-api-key",
|
|
224
|
-
DATABASE_URL: "postgresql://localhost:5432/mydb"
|
|
225
|
-
});
|
|
226
|
-
|
|
227
|
-
// Now you can run commands - environment variables are available
|
|
228
|
-
const result = await sandbox.exec("echo $NODE_ENV");
|
|
229
|
-
console.log(result.stdout); // "production"
|
|
34
|
+
```bash
|
|
35
|
+
npm run dev
|
|
230
36
|
```
|
|
231
37
|
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
- `listProcesses()` - List all running processes
|
|
235
|
-
- `getProcess(id)` - Get detailed process status
|
|
236
|
-
- `killProcess(id, signal?)` - Terminate specific processes
|
|
237
|
-
- `killAllProcesses()` - Kill all processes
|
|
238
|
-
- `streamProcessLogs(id, options?)` - Stream logs from running processes
|
|
239
|
-
- `getProcessLogs(id)` - Get accumulated process output
|
|
240
|
-
|
|
241
|
-
#### File System Methods
|
|
242
|
-
|
|
243
|
-
- `writeFile(path, content, options?)` - Write content to a file
|
|
244
|
-
- `readFile(path, options?)` - Read a file from the sandbox
|
|
245
|
-
- `mkdir(path, options?)` - Create a directory
|
|
246
|
-
- `deleteFile(path)` - Delete a file
|
|
247
|
-
- `renameFile(oldPath, newPath)` - Rename a file
|
|
248
|
-
- `moveFile(sourcePath, destinationPath)` - Move a file
|
|
249
|
-
- `gitCheckout(repoUrl, options?)` - Clone git repositories
|
|
250
|
-
|
|
251
|
-
#### Network Methods
|
|
38
|
+
> **Note:** First run builds the Docker container (2-3 minutes). Subsequent runs are much faster.
|
|
252
39
|
|
|
253
|
-
|
|
254
|
-
- `unexposePort(port)` - Remove port exposure
|
|
255
|
-
- `getExposedPorts()` - List all exposed ports with their URLs
|
|
40
|
+
Test the endpoints:
|
|
256
41
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
### Code Execution
|
|
262
|
-
|
|
263
|
-
#### `createCodeContext(options?)`
|
|
264
|
-
|
|
265
|
-
Creates a new code execution context with persistent state.
|
|
266
|
-
|
|
267
|
-
```typescript
|
|
268
|
-
// Create a Python context
|
|
269
|
-
const pythonCtx = await sandbox.createCodeContext({ language: 'python' });
|
|
42
|
+
```bash
|
|
43
|
+
# Execute Python code
|
|
44
|
+
curl http://localhost:8787/run
|
|
270
45
|
|
|
271
|
-
|
|
272
|
-
|
|
46
|
+
# File operations
|
|
47
|
+
curl http://localhost:8787/file
|
|
273
48
|
```
|
|
274
49
|
|
|
275
|
-
|
|
276
|
-
- `language`: Programming language (`'python'` | `'javascript'` | `'typescript'`)
|
|
277
|
-
- `cwd`: Working directory (default: `/workspace`)
|
|
278
|
-
- `envVars`: Environment variables for the context
|
|
279
|
-
|
|
280
|
-
#### `runCode(code, options?)`
|
|
50
|
+
### 3. Deploy to production
|
|
281
51
|
|
|
282
|
-
|
|
52
|
+
Deploy your Worker and container:
|
|
283
53
|
|
|
284
|
-
```
|
|
285
|
-
|
|
286
|
-
const execution = await sandbox.runCode('print("Hello World")', {
|
|
287
|
-
context: pythonCtx
|
|
288
|
-
});
|
|
289
|
-
|
|
290
|
-
// With streaming callbacks
|
|
291
|
-
await sandbox.runCode(`
|
|
292
|
-
for i in range(5):
|
|
293
|
-
print(f"Step {i}")
|
|
294
|
-
time.sleep(1)
|
|
295
|
-
`, {
|
|
296
|
-
context: pythonCtx,
|
|
297
|
-
onStdout: (output) => console.log('Real-time:', output.text),
|
|
298
|
-
onResult: (result) => console.log('Result:', result)
|
|
299
|
-
});
|
|
54
|
+
```bash
|
|
55
|
+
npx wrangler deploy
|
|
300
56
|
```
|
|
301
57
|
|
|
302
|
-
**
|
|
303
|
-
- `context`: Context to run the code in
|
|
304
|
-
- `language`: Language if no context provided
|
|
305
|
-
- `onStdout`: Callback for stdout output
|
|
306
|
-
- `onStderr`: Callback for stderr output
|
|
307
|
-
- `onResult`: Callback for execution results
|
|
308
|
-
- `onError`: Callback for errors
|
|
58
|
+
> **Wait for provisioning:** After first deployment, wait 2-3 minutes before making requests.
|
|
309
59
|
|
|
310
|
-
|
|
60
|
+
**๐ [View the complete getting started guide](https://developers.cloudflare.com/sandbox/get-started/)** for detailed instructions and explanations.
|
|
311
61
|
|
|
312
|
-
|
|
62
|
+
## Quick API Example
|
|
313
63
|
|
|
314
64
|
```typescript
|
|
315
|
-
|
|
316
|
-
// Process the stream as needed
|
|
317
|
-
```
|
|
318
|
-
|
|
319
|
-
### Rich Outputs
|
|
320
|
-
|
|
321
|
-
The code interpreter automatically detects and processes various output types:
|
|
322
|
-
|
|
323
|
-
```typescript
|
|
324
|
-
// Data visualization
|
|
325
|
-
const execution = await sandbox.runCode(`
|
|
326
|
-
import matplotlib.pyplot as plt
|
|
327
|
-
import numpy as np
|
|
328
|
-
|
|
329
|
-
x = np.linspace(0, 10, 100)
|
|
330
|
-
y = np.sin(x)
|
|
331
|
-
plt.plot(x, y)
|
|
332
|
-
plt.title('Sine Wave')
|
|
333
|
-
plt.show()
|
|
334
|
-
`, {
|
|
335
|
-
context: pythonCtx,
|
|
336
|
-
onResult: (result) => {
|
|
337
|
-
if (result.png) {
|
|
338
|
-
// Base64 encoded PNG image
|
|
339
|
-
console.log('Chart generated!');
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
});
|
|
343
|
-
|
|
344
|
-
// HTML tables with pandas
|
|
345
|
-
const tableExecution = await sandbox.runCode(`
|
|
346
|
-
import pandas as pd
|
|
347
|
-
df = pd.DataFrame({
|
|
348
|
-
'name': ['Alice', 'Bob', 'Charlie'],
|
|
349
|
-
'score': [92, 88, 95]
|
|
350
|
-
})
|
|
351
|
-
df
|
|
352
|
-
`, { context: pythonCtx });
|
|
353
|
-
|
|
354
|
-
// Access HTML table in execution.results[0].html
|
|
355
|
-
```
|
|
356
|
-
|
|
357
|
-
### Output Formats
|
|
358
|
-
|
|
359
|
-
Results can include multiple formats:
|
|
360
|
-
- `text`: Plain text representation
|
|
361
|
-
- `html`: HTML (often pandas DataFrames)
|
|
362
|
-
- `png`/`jpeg`: Base64 encoded images
|
|
363
|
-
- `svg`: Vector graphics
|
|
364
|
-
- `json`: Structured data
|
|
365
|
-
- `chart`: Parsed chart information
|
|
65
|
+
import { getSandbox, proxyToSandbox, type Sandbox } from '@cloudflare/sandbox';
|
|
366
66
|
|
|
367
|
-
|
|
67
|
+
export { Sandbox } from '@cloudflare/sandbox';
|
|
368
68
|
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
- `deleteCodeContext(contextId)` - Delete a specific context
|
|
373
|
-
|
|
374
|
-
<h2 id="port-forwarding">๐ Port Forwarding</h2>
|
|
375
|
-
|
|
376
|
-
The SDK automatically handles preview URL routing for exposed ports. Just add one line to your worker:
|
|
377
|
-
|
|
378
|
-
```typescript
|
|
379
|
-
import { proxyToSandbox, getSandbox } from "@cloudflare/sandbox";
|
|
69
|
+
type Env = {
|
|
70
|
+
Sandbox: DurableObjectNamespace<Sandbox>;
|
|
71
|
+
};
|
|
380
72
|
|
|
381
73
|
export default {
|
|
382
|
-
async fetch(request, env) {
|
|
383
|
-
//
|
|
74
|
+
async fetch(request: Request, env: Env): Promise<Response> {
|
|
75
|
+
// Required for preview URLs
|
|
384
76
|
const proxyResponse = await proxyToSandbox(request, env);
|
|
385
77
|
if (proxyResponse) return proxyResponse;
|
|
386
78
|
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
},
|
|
390
|
-
};
|
|
391
|
-
```
|
|
79
|
+
const url = new URL(request.url);
|
|
80
|
+
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
|
|
392
81
|
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
console.log(preview.url); // https://3000-sandbox-id.your-worker.dev
|
|
398
|
-
```
|
|
399
|
-
|
|
400
|
-
The SDK handles:
|
|
401
|
-
|
|
402
|
-
- Subdomain routing (`3000-sandbox-id.domain.com`) for both production and local development
|
|
403
|
-
- All localhost variants (127.0.0.1, ::1, etc.)
|
|
404
|
-
- Request forwarding with proper headers
|
|
405
|
-
|
|
406
|
-
> **Important for Local Development**: When developing locally with `wrangler dev`, you must explicitly expose ports in your Dockerfile using the `EXPOSE` instruction. This is **only required for local development** - in production, all container ports are automatically accessible.
|
|
407
|
-
|
|
408
|
-
```dockerfile
|
|
409
|
-
# In your Dockerfile (only needed for local dev)
|
|
410
|
-
FROM docker.io/cloudflare/sandbox:0.1.3
|
|
411
|
-
|
|
412
|
-
# Expose the ports you'll be using
|
|
413
|
-
EXPOSE 3000 # For a web server
|
|
414
|
-
EXPOSE 8080 # For an API server
|
|
415
|
-
EXPOSE 3001 # For any additional services
|
|
416
|
-
|
|
417
|
-
# Your container setup...
|
|
418
|
-
```
|
|
419
|
-
|
|
420
|
-
Without the `EXPOSE` instruction in local development, you'll see this error:
|
|
421
|
-
|
|
422
|
-
```
|
|
423
|
-
connect(): Connection refused: container port not found. Make sure you exposed the port in your container definition.
|
|
424
|
-
```
|
|
425
|
-
|
|
426
|
-
For more details, see the [Cloudflare Containers local development guide](https://developers.cloudflare.com/containers/local-dev/#exposing-ports).
|
|
427
|
-
|
|
428
|
-
### Utility Methods
|
|
429
|
-
|
|
430
|
-
- `ping()` - Health check for the sandbox
|
|
431
|
-
- `containerFetch(request)` - Direct container communication
|
|
432
|
-
|
|
433
|
-
<h2 id="examples">๐ก Examples</h2>
|
|
434
|
-
|
|
435
|
-
### Run a Node.js App
|
|
436
|
-
|
|
437
|
-
```typescript
|
|
438
|
-
const sandbox = getSandbox(env.Sandbox, "node-app");
|
|
439
|
-
|
|
440
|
-
// Write a simple Express server
|
|
441
|
-
await sandbox.writeFile(
|
|
442
|
-
"/workspace/app.js",
|
|
443
|
-
`
|
|
444
|
-
const express = require('express');
|
|
445
|
-
const app = express();
|
|
446
|
-
|
|
447
|
-
app.get('/', (req, res) => {
|
|
448
|
-
res.json({ message: 'Hello from Cloudflare!' });
|
|
449
|
-
});
|
|
450
|
-
|
|
451
|
-
app.listen(3000);
|
|
452
|
-
`
|
|
453
|
-
);
|
|
454
|
-
|
|
455
|
-
// Install dependencies and start the server
|
|
456
|
-
await sandbox.exec("npm init -y");
|
|
457
|
-
await sandbox.exec("npm install express");
|
|
458
|
-
const server = await sandbox.startProcess("node app.js");
|
|
459
|
-
|
|
460
|
-
// Expose it to the internet
|
|
461
|
-
const preview = await sandbox.exposePort(3000);
|
|
462
|
-
console.log(`API available at: ${preview.url}`);
|
|
463
|
-
```
|
|
464
|
-
|
|
465
|
-
### Build and Test Code
|
|
466
|
-
|
|
467
|
-
```typescript
|
|
468
|
-
const sandbox = getSandbox(env.Sandbox, "test-env");
|
|
469
|
-
|
|
470
|
-
// Clone a repository
|
|
471
|
-
await sandbox.gitCheckout("https://github.com/user/project");
|
|
472
|
-
|
|
473
|
-
// Run tests
|
|
474
|
-
const testResult = await sandbox.exec("npm test");
|
|
475
|
-
|
|
476
|
-
// Build the project
|
|
477
|
-
const buildResult = await sandbox.exec("npm run build");
|
|
478
|
-
|
|
479
|
-
return new Response(
|
|
480
|
-
JSON.stringify({
|
|
481
|
-
tests: testResult.exitCode === 0 ? "passed" : "failed",
|
|
482
|
-
build: buildResult.exitCode === 0 ? "success" : "failed",
|
|
483
|
-
output: testResult.stdout,
|
|
484
|
-
})
|
|
485
|
-
);
|
|
486
|
-
```
|
|
487
|
-
|
|
488
|
-
### Interactive Development Environment
|
|
489
|
-
|
|
490
|
-
```typescript
|
|
491
|
-
// Create a development sandbox with hot reload
|
|
492
|
-
const sandbox = getSandbox(env.Sandbox, "dev-env");
|
|
493
|
-
|
|
494
|
-
// Set up the project
|
|
495
|
-
await sandbox.gitCheckout("https://github.com/user/my-app");
|
|
496
|
-
await sandbox.exec("npm install");
|
|
497
|
-
|
|
498
|
-
// Start dev server
|
|
499
|
-
const devServer = await sandbox.startProcess("npm run dev");
|
|
500
|
-
|
|
501
|
-
// Expose the dev server
|
|
502
|
-
const preview = await sandbox.exposePort(3000, { name: "dev-server" });
|
|
503
|
-
|
|
504
|
-
// Make changes and see them live!
|
|
505
|
-
await sandbox.writeFile("/src/App.jsx", updatedCode);
|
|
506
|
-
```
|
|
507
|
-
|
|
508
|
-
### Expose Services with Preview URLs
|
|
509
|
-
|
|
510
|
-
```typescript
|
|
511
|
-
// Create and start a web server
|
|
512
|
-
await sandbox.writeFile(
|
|
513
|
-
"/server.js",
|
|
514
|
-
`Bun.serve({
|
|
515
|
-
port: 8080,
|
|
516
|
-
fetch(req) {
|
|
517
|
-
return new Response("Hello from sandbox!");
|
|
82
|
+
// Execute Python code
|
|
83
|
+
if (url.pathname === '/run') {
|
|
84
|
+
const result = await sandbox.exec('python3 -c "print(2 + 2)"');
|
|
85
|
+
return Response.json({ output: result.stdout, success: result.success });
|
|
518
86
|
}
|
|
519
|
-
});`
|
|
520
|
-
);
|
|
521
|
-
|
|
522
|
-
const server = await sandbox.startProcess("bun run /server.js");
|
|
523
87
|
|
|
524
|
-
//
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
// See the example in examples/basic/src/index.ts for the routing implementation.
|
|
530
|
-
```
|
|
531
|
-
|
|
532
|
-
### Data Analysis with Code Interpreter
|
|
533
|
-
|
|
534
|
-
```typescript
|
|
535
|
-
const sandbox = getSandbox(env.Sandbox, "analysis");
|
|
536
|
-
|
|
537
|
-
// Create a Python context for data analysis
|
|
538
|
-
const pythonCtx = await sandbox.createCodeContext({ language: 'python' });
|
|
539
|
-
|
|
540
|
-
// Load and analyze data
|
|
541
|
-
const analysis = await sandbox.runCode(`
|
|
542
|
-
import pandas as pd
|
|
543
|
-
import matplotlib.pyplot as plt
|
|
544
|
-
|
|
545
|
-
# Create sample data
|
|
546
|
-
data = {
|
|
547
|
-
'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
|
|
548
|
-
'Sales': [10000, 12000, 15000, 14000, 18000],
|
|
549
|
-
'Profit': [2000, 2500, 3200, 2800, 4000]
|
|
550
|
-
}
|
|
551
|
-
df = pd.DataFrame(data)
|
|
552
|
-
|
|
553
|
-
# Display summary statistics
|
|
554
|
-
print("Sales Summary:")
|
|
555
|
-
print(df.describe())
|
|
556
|
-
|
|
557
|
-
# Create visualization
|
|
558
|
-
plt.figure(figsize=(10, 6))
|
|
559
|
-
plt.subplot(1, 2, 1)
|
|
560
|
-
plt.bar(df['Month'], df['Sales'])
|
|
561
|
-
plt.title('Monthly Sales')
|
|
562
|
-
plt.xlabel('Month')
|
|
563
|
-
plt.ylabel('Sales ($)')
|
|
564
|
-
|
|
565
|
-
plt.subplot(1, 2, 2)
|
|
566
|
-
plt.plot(df['Month'], df['Profit'], marker='o', color='green')
|
|
567
|
-
plt.title('Monthly Profit')
|
|
568
|
-
plt.xlabel('Month')
|
|
569
|
-
plt.ylabel('Profit ($)')
|
|
570
|
-
|
|
571
|
-
plt.tight_layout()
|
|
572
|
-
plt.show()
|
|
573
|
-
|
|
574
|
-
# Return the data as JSON
|
|
575
|
-
df.to_dict('records')
|
|
576
|
-
`, {
|
|
577
|
-
context: pythonCtx,
|
|
578
|
-
onResult: (result) => {
|
|
579
|
-
if (result.png) {
|
|
580
|
-
// Handle the chart image
|
|
581
|
-
console.log('Chart generated:', result.png.substring(0, 50) + '...');
|
|
88
|
+
// Work with files
|
|
89
|
+
if (url.pathname === '/file') {
|
|
90
|
+
await sandbox.writeFile('/workspace/hello.txt', 'Hello, Sandbox!');
|
|
91
|
+
const file = await sandbox.readFile('/workspace/hello.txt');
|
|
92
|
+
return Response.json({ content: file.content });
|
|
582
93
|
}
|
|
583
|
-
if (result.json) {
|
|
584
|
-
// Handle the structured data
|
|
585
|
-
console.log('Data:', result.json);
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
});
|
|
589
|
-
|
|
590
|
-
// Multi-language workflow: Process in Python, analyze in JavaScript
|
|
591
|
-
await sandbox.runCode(`
|
|
592
|
-
# Save processed data
|
|
593
|
-
df.to_json('/tmp/sales_data.json', orient='records')
|
|
594
|
-
`, { context: pythonCtx });
|
|
595
|
-
|
|
596
|
-
const jsCtx = await sandbox.createCodeContext({ language: 'javascript' });
|
|
597
|
-
const jsAnalysis = await sandbox.runCode(`
|
|
598
|
-
const fs = require('fs');
|
|
599
|
-
const data = JSON.parse(fs.readFileSync('/tmp/sales_data.json', 'utf8'));
|
|
600
|
-
|
|
601
|
-
// Calculate growth rate
|
|
602
|
-
const growth = data.map((curr, idx) => {
|
|
603
|
-
if (idx === 0) return { ...curr, growth: 0 };
|
|
604
|
-
const prev = data[idx - 1];
|
|
605
|
-
return {
|
|
606
|
-
...curr,
|
|
607
|
-
growth: ((curr.Sales - prev.Sales) / prev.Sales * 100).toFixed(2) + '%'
|
|
608
|
-
};
|
|
609
|
-
});
|
|
610
|
-
|
|
611
|
-
console.log('Growth Analysis:', growth);
|
|
612
|
-
growth;
|
|
613
|
-
`, { context: jsCtx });
|
|
614
|
-
```
|
|
615
|
-
|
|
616
|
-
<h2 id="architecture">๐๏ธ Architecture</h2>
|
|
617
|
-
|
|
618
|
-
The SDK leverages Cloudflare's infrastructure:
|
|
619
94
|
|
|
620
|
-
|
|
621
|
-
- **Containers**: Provides isolated execution environments with Jupyter kernels
|
|
622
|
-
- **Workers**: Handles HTTP routing and API interface
|
|
623
|
-
- **Edge Network**: Enables global distribution and low latency
|
|
624
|
-
- **Jupyter Integration**: Python (IPython) and JavaScript (TSLab) kernels for code execution
|
|
625
|
-
- **MIME Processing**: Automatic detection and handling of rich output formats
|
|
626
|
-
|
|
627
|
-
<h2 id="advanced-usage">๐ ๏ธ Advanced Usage</h2>
|
|
628
|
-
|
|
629
|
-
### AsyncIterable Streaming Support
|
|
630
|
-
|
|
631
|
-
The SDK provides powerful streaming capabilities with typed AsyncIterable support:
|
|
632
|
-
|
|
633
|
-
```typescript
|
|
634
|
-
import { parseSSEStream, type ExecEvent } from '@cloudflare/sandbox';
|
|
635
|
-
|
|
636
|
-
// Stream command execution
|
|
637
|
-
const stream = await sandbox.execStream('npm run build');
|
|
638
|
-
for await (const event of parseSSEStream<ExecEvent>(stream)) {
|
|
639
|
-
switch (event.type) {
|
|
640
|
-
case 'start':
|
|
641
|
-
console.log(`Build started: ${event.command}`);
|
|
642
|
-
break;
|
|
643
|
-
case 'stdout':
|
|
644
|
-
console.log(`Build: ${event.data}`);
|
|
645
|
-
break;
|
|
646
|
-
case 'complete':
|
|
647
|
-
console.log(`Exit code: ${event.exitCode}`);
|
|
648
|
-
break;
|
|
649
|
-
case 'error':
|
|
650
|
-
console.error(`Error: ${event.error}`);
|
|
651
|
-
break;
|
|
95
|
+
return new Response('Try /run or /file');
|
|
652
96
|
}
|
|
653
|
-
}
|
|
654
|
-
```
|
|
655
|
-
|
|
656
|
-
#### Streaming Utilities
|
|
657
|
-
|
|
658
|
-
The SDK exports utilities for working with Server-Sent Event streams:
|
|
659
|
-
|
|
660
|
-
- **`parseSSEStream<T>(stream)`** - Convert ReadableStream to typed AsyncIterable
|
|
661
|
-
- **`responseToAsyncIterable<T>(response)`** - Convert SSE Response to AsyncIterable
|
|
662
|
-
- **`asyncIterableToSSEStream<T>(iterable)`** - Convert AsyncIterable back to SSE stream
|
|
663
|
-
|
|
664
|
-
#### Advanced Streaming Examples
|
|
665
|
-
|
|
666
|
-
**CI/CD Build System:**
|
|
667
|
-
```typescript
|
|
668
|
-
export async function runBuild(env: Env, buildId: string) {
|
|
669
|
-
const sandbox = getSandbox(env.SANDBOX, buildId);
|
|
670
|
-
const stream = await sandbox.execStream('npm run build');
|
|
671
|
-
|
|
672
|
-
for await (const event of parseSSEStream<ExecEvent>(stream)) {
|
|
673
|
-
switch (event.type) {
|
|
674
|
-
case 'start':
|
|
675
|
-
await env.BUILDS.put(buildId, { status: 'running' });
|
|
676
|
-
break;
|
|
677
|
-
case 'complete':
|
|
678
|
-
await env.BUILDS.put(buildId, {
|
|
679
|
-
status: event.exitCode === 0 ? 'success' : 'failed',
|
|
680
|
-
exitCode: event.exitCode
|
|
681
|
-
});
|
|
682
|
-
break;
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
}
|
|
97
|
+
};
|
|
686
98
|
```
|
|
687
99
|
|
|
688
|
-
|
|
689
|
-
```typescript
|
|
690
|
-
const monitor = await sandbox.startProcess('tail -f /var/log/system.log');
|
|
691
|
-
const logStream = await sandbox.streamProcessLogs(monitor.id);
|
|
692
|
-
|
|
693
|
-
for await (const log of parseSSEStream<LogEvent>(logStream)) {
|
|
694
|
-
if (log.type === 'stdout' && log.data.includes('ERROR')) {
|
|
695
|
-
await env.ALERTS.send({
|
|
696
|
-
severity: 'high',
|
|
697
|
-
message: log.data,
|
|
698
|
-
timestamp: log.timestamp
|
|
699
|
-
});
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
```
|
|
100
|
+
## Documentation
|
|
703
101
|
|
|
704
|
-
|
|
102
|
+
**๐ [Full Documentation](https://developers.cloudflare.com/sandbox/)**
|
|
705
103
|
|
|
706
|
-
|
|
104
|
+
- [Get Started Guide](https://developers.cloudflare.com/sandbox/get-started/) - Step-by-step tutorial
|
|
105
|
+
- [API Reference](https://developers.cloudflare.com/sandbox/api/) - Complete API docs
|
|
106
|
+
- [Guides](https://developers.cloudflare.com/sandbox/guides/) - Execute commands, manage files, expose services
|
|
107
|
+
- [Examples](https://developers.cloudflare.com/sandbox/tutorials/) - AI agents, data analysis, CI/CD pipelines
|
|
707
108
|
|
|
708
|
-
|
|
709
|
-
const sessionId = crypto.randomUUID();
|
|
109
|
+
## Key Features
|
|
710
110
|
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
111
|
+
- **Secure Isolation** - Each sandbox runs in its own container
|
|
112
|
+
- **Edge-Native** - Runs on Cloudflare's global network
|
|
113
|
+
- **Code Interpreter** - Execute Python and JavaScript with rich outputs
|
|
114
|
+
- **File System Access** - Read, write, and manage files
|
|
115
|
+
- **Command Execution** - Run any command with streaming support
|
|
116
|
+
- **Preview URLs** - Expose services with public URLs
|
|
117
|
+
- **Git Integration** - Clone repositories directly
|
|
716
118
|
|
|
717
|
-
|
|
119
|
+
## Contributing
|
|
718
120
|
|
|
719
|
-
|
|
121
|
+
We welcome contributions from the community! See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines on:
|
|
720
122
|
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
console.log(`Starting: ${cmd} ${args.join(" ")}`);
|
|
725
|
-
sandbox.client.onOutput = (stream, data) => console.log(`[${stream}] ${data}`);
|
|
726
|
-
sandbox.client.onCommandComplete = (success, code) =>
|
|
727
|
-
console.log(`Completed: ${success} (${code})`);
|
|
728
|
-
```
|
|
729
|
-
|
|
730
|
-
<h2 id="known-limitations">๐ง Known Limitations</h2>
|
|
123
|
+
- Setting up your development environment
|
|
124
|
+
- Creating pull requests
|
|
125
|
+
- Code style and testing requirements
|
|
731
126
|
|
|
732
|
-
|
|
733
|
-
- WebSocket support for preview URLs coming soon
|
|
734
|
-
- Some system calls may be restricted in the container environment
|
|
735
|
-
- Code interpreter has no internet access (sandbox restriction)
|
|
736
|
-
- Some Python/JavaScript packages may not be pre-installed
|
|
737
|
-
- Resource limits apply to code execution (CPU, memory)
|
|
127
|
+
## Development
|
|
738
128
|
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
|
|
129
|
+
This repository contains the SDK source code. Quick start:
|
|
742
130
|
|
|
743
131
|
```bash
|
|
744
132
|
# Clone the repo
|
|
@@ -748,37 +136,34 @@ cd sandbox-sdk
|
|
|
748
136
|
# Install dependencies
|
|
749
137
|
npm install
|
|
750
138
|
|
|
751
|
-
# Install Bun (if not already installed)
|
|
752
|
-
# Visit https://bun.sh for installation instructions
|
|
753
|
-
curl -fsSL https://bun.sh/install | bash
|
|
754
|
-
|
|
755
|
-
# Install container dependencies (required for TypeScript checking)
|
|
756
|
-
cd packages/sandbox/container_src && bun install && cd -
|
|
757
|
-
|
|
758
139
|
# Run tests
|
|
759
140
|
npm test
|
|
760
141
|
|
|
761
142
|
# Build the project
|
|
762
143
|
npm run build
|
|
763
144
|
|
|
764
|
-
#
|
|
145
|
+
# Type checking and linting
|
|
765
146
|
npm run check
|
|
766
147
|
```
|
|
767
148
|
|
|
768
|
-
|
|
149
|
+
## Examples
|
|
150
|
+
|
|
151
|
+
See the [examples directory](./examples) for complete working examples:
|
|
152
|
+
|
|
153
|
+
- [Minimal](./examples/minimal) - Basic sandbox setup
|
|
154
|
+
- [Code Interpreter](./examples/code-interpreter) - Use sandbox as an interpreter tool with gpt-oss
|
|
155
|
+
|
|
156
|
+
## Status
|
|
769
157
|
|
|
770
|
-
|
|
158
|
+
**Beta** - The SDK is in active development. APIs may change before v1.0.
|
|
771
159
|
|
|
772
|
-
|
|
160
|
+
## License
|
|
773
161
|
|
|
774
|
-
|
|
162
|
+
[Apache License 2.0](LICENSE)
|
|
775
163
|
|
|
776
|
-
|
|
164
|
+
## Links
|
|
777
165
|
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
<a href="https://twitter.com/CloudflareDev">Twitter</a>
|
|
783
|
-
</p>
|
|
784
|
-
</div>
|
|
166
|
+
- [Documentation](https://developers.cloudflare.com/sandbox/)
|
|
167
|
+
- [GitHub Issues](https://github.com/cloudflare/sandbox-sdk/issues)
|
|
168
|
+
- [Developer Discord](https://discord.cloudflare.com)
|
|
169
|
+
- [Cloudflare Developers](https://twitter.com/CloudflareDev)
|