@cloudflare/sandbox 0.0.0-c5bd973 โ†’ 0.0.0-c87db11

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/README.md CHANGED
@@ -1,10 +1,86 @@
1
- ## @cloudflare/sandbox
1
+ <div align="center">
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>
2
9
 
3
- > **โš ๏ธ Experimental** - This library is currently experimental and we're actively seeking feedback. Please try it out and let us know what you think!
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 -->
4
12
 
5
- A library to spin up a sandboxed environment.
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)
6
41
 
7
- First, setup your wrangler.json to use the sandbox:
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
65
+
66
+ ```bash
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.2
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.
8
84
 
9
85
  ```jsonc
10
86
  {
@@ -12,8 +88,8 @@ First, setup your wrangler.json to use the sandbox:
12
88
  "containers": [
13
89
  {
14
90
  "class_name": "Sandbox",
15
- "image": "./node_modules/@cloudflare/sandbox/Dockerfile",
16
- "name": "sandbox"
91
+ "image": "./Dockerfile",
92
+ "max_instances": 1
17
93
  }
18
94
  ],
19
95
  "durable_objects": {
@@ -33,33 +109,676 @@ First, setup your wrangler.json to use the sandbox:
33
109
  }
34
110
  ```
35
111
 
36
- Then, export the Sandbox class in your worker:
112
+ 3. **Create your Worker**:
113
+
114
+ ```typescript
115
+ import { getSandbox } from "@cloudflare/sandbox";
37
116
 
38
- ```ts
117
+ // Export the Sandbox class in your Worker
39
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
+ };
40
129
  ```
41
130
 
42
- You can then use the Sandbox class in your worker:
131
+ <h2 id="api-reference">๐Ÿ“š API Reference</h2>
43
132
 
44
- ```ts
45
- import { getSandbox } from "@cloudflare/sandbox";
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
152
+
153
+ ```typescript
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
+ ```
181
+
182
+ #### `writeFile(path, content, options?)`
183
+
184
+ Write content to a file.
185
+
186
+ ```typescript
187
+ await sandbox.writeFile("/workspace/app.js", "console.log('Hello!');");
188
+ ```
189
+
190
+ #### `readFile(path, options?)`
191
+
192
+ Read a file from the sandbox.
193
+
194
+ ```typescript
195
+ const file = await sandbox.readFile("/package.json");
196
+ console.log(file.content);
197
+ ```
198
+
199
+ #### `gitCheckout(repoUrl, options?)`
200
+
201
+ Clone a git repository.
202
+
203
+ ```typescript
204
+ await sandbox.gitCheckout("https://github.com/user/repo", {
205
+ branch: "main",
206
+ targetDir: "my-project",
207
+ });
208
+ ```
209
+
210
+ #### `setEnvVars(envVars)`
211
+
212
+ Set environment variables dynamically in the sandbox.
213
+
214
+ > **Important**: This method must be called immediately after `getSandbox()` and before any other operations. Once a sandbox instance starts up, environment variables cannot be changed
215
+ for that instance.
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"
230
+ ```
231
+
232
+ #### Process Management
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
252
+
253
+ - `exposePort(port, options?)` - Expose a port and get a public URL
254
+ - `unexposePort(port)` - Remove port exposure
255
+ - `getExposedPorts()` - List all exposed ports with their URLs
256
+
257
+ <h2 id="code-interpreter">๐Ÿงช Code Interpreter</h2>
258
+
259
+ The Sandbox SDK includes powerful code interpreter capabilities, allowing you to execute Python and JavaScript code with rich outputs including charts, tables, and formatted data.
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' });
270
+
271
+ // Create a JavaScript context
272
+ const jsCtx = await sandbox.createCodeContext({ language: 'javascript' });
273
+ ```
274
+
275
+ **Options:**
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?)`
281
+
282
+ Executes code with optional streaming callbacks.
283
+
284
+ ```typescript
285
+ // Simple execution
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
+ });
300
+ ```
301
+
302
+ **Options:**
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
309
+
310
+ #### `runCodeStream(code, options?)`
311
+
312
+ Returns a streaming response for real-time processing.
313
+
314
+ ```typescript
315
+ const stream = await sandbox.runCodeStream('import time; [print(i) for i in range(10)]');
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
366
+
367
+ Check available formats with `result.formats()`.
368
+
369
+ #### Additional Code Interpreter Methods
370
+
371
+ - `listCodeContexts()` - List all active code contexts
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";
46
380
 
47
381
  export default {
48
- async fetch(request: Request, env: Env) {
49
- const sandbox = getSandbox(env.Sandbox, "my-sandbox");
50
- return sandbox.exec("ls", ["-la"]);
382
+ async fetch(request, env) {
383
+ // Route requests to exposed container ports via their preview URLs
384
+ const proxyResponse = await proxyToSandbox(request, env);
385
+ if (proxyResponse) return proxyResponse;
386
+
387
+ // Your custom routes here
388
+ // ...
51
389
  },
52
390
  };
53
391
  ```
54
392
 
55
- ### Methods:
393
+ When you expose a port, the SDK returns a preview URL that automatically routes to your service:
394
+
395
+ ```typescript
396
+ const preview = await sandbox.exposePort(3000);
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!");
518
+ }
519
+ });`
520
+ );
521
+
522
+ const server = await sandbox.startProcess("bun run /server.js");
523
+
524
+ // Expose the port - returns a public URL
525
+ const preview = await sandbox.exposePort(8080);
526
+ console.log(`Service available at: ${preview.url}`);
527
+
528
+ // Note: Your Worker needs to handle preview URL routing.
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) + '...');
582
+ }
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
+
620
+ - **Durable Objects**: Manages sandbox lifecycle and state
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;
652
+ }
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
+ }
686
+ ```
687
+
688
+ **System Monitoring:**
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
+ ```
703
+
704
+ ### Session Management
705
+
706
+ Maintain context across commands:
707
+
708
+ ```typescript
709
+ const sessionId = crypto.randomUUID();
710
+
711
+ // Commands in the same session share working directory
712
+ await sandbox.exec("cd /workspace", { sessionId });
713
+ await sandbox.exec("npm install", { sessionId });
714
+ const app = await sandbox.startProcess("npm start", { sessionId });
715
+ ```
716
+
717
+ <h2 id="debugging">๐Ÿ” Debugging</h2>
718
+
719
+ Enable verbose logging:
720
+
721
+ ```typescript
722
+ const sandbox = getSandbox(env.Sandbox, "debug-sandbox");
723
+ sandbox.client.onCommandStart = (cmd, args) =>
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>
731
+
732
+ - Maximum container runtime is limited by Durable Object constraints
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)
738
+
739
+ <h2 id="contributing">๐Ÿค Contributing</h2>
740
+
741
+ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
742
+
743
+ ```bash
744
+ # Clone the repo
745
+ git clone https://github.com/cloudflare/sandbox-sdk
746
+ cd sandbox-sdk
747
+
748
+ # Install dependencies
749
+ npm install
750
+
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
+ # Run tests
759
+ npm test
760
+
761
+ # Build the project
762
+ npm run build
763
+
764
+ # Run type checking and linting
765
+ npm run check
766
+ ```
767
+
768
+ <h2 id="license">๐Ÿ“„ License</h2>
769
+
770
+ [MIT License](LICENSE)
771
+
772
+ <h2 id="acknowledgments">๐Ÿ™Œ Acknowledgments</h2>
773
+
774
+ Built with โค๏ธ by the Cloudflare team. Special thanks to all early adopters and contributors.
775
+
776
+ ---
56
777
 
57
- - `exec(command: string, args: string[], options?: { stream?: boolean })`: Execute a command in the sandbox.
58
- - `gitCheckout(repoUrl: string, options: { branch?: string; targetDir?: string; stream?: boolean })`: Checkout a git repository in the sandbox.
59
- - `mkdir(path: string, options: { recursive?: boolean; stream?: boolean })`: Create a directory in the sandbox.
60
- - `writeFile(path: string, content: string, options: { encoding?: string; stream?: boolean })`: Write content to a file in the sandbox.
61
- - `readFile(path: string, options: { encoding?: string; stream?: boolean })`: Read content from a file in the sandbox.
62
- - `deleteFile(path: string, options?: { stream?: boolean })`: Delete a file from the sandbox.
63
- - `renameFile(oldPath: string, newPath: string, options?: { stream?: boolean })`: Rename a file in the sandbox.
64
- - `moveFile(sourcePath: string, destinationPath: string, options?: { stream?: boolean })`: Move a file from one location to another in the sandbox.
65
- - `ping()`: Ping the sandbox.
778
+ <div align="center">
779
+ <p>
780
+ <a href="https://github.com/cloudflare/sandbox-sdk/issues">Issues</a> โ€ข
781
+ <a href="https://discord.gg/cloudflaredev">Discord</a> โ€ข
782
+ <a href="https://twitter.com/CloudflareDev">Twitter</a>
783
+ </p>
784
+ </div>