Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@
/src/content/docs/workers/observability/ @irvinebroque @mikenomitch @rohinlohe @kodster28 @cloudflare/pcx-technical-writing
/src/content/docs/workers/static-assets @irvinebroque @GregBrimble @WalshyDev @kodster28 @cloudflare/deploy-config @cloudflare/pcx-technical-writing
/src/content/docs/workflows/ @elithrar @celso @cloudflare/pcx-technical-writing
/src/content/docs/sandbox/ @whoiskatrin @ghostwriternr @cloudflare/pcx-technical-writing @ai-agents

# DDoS Protection

Expand Down
219 changes: 219 additions & 0 deletions src/content/docs/sandbox/api/commands.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
---
title: Commands
pcx_content_type: concept
sidebar:
order: 1
---

import { Details, TypeScriptExample } from "~/components";

Execute commands and manage background processes in the sandbox's isolated container environment.

## Methods

### `exec()`

Execute a command and return the complete result.

```ts
const result = await sandbox.exec(command: string, options?: ExecOptions): Promise<ExecuteResponse>
```

**Parameters**:
- `command` - The command to execute (can include arguments)
- `options` (optional):
- `stream` - Enable streaming callbacks (default: `false`)
- `onOutput` - Callback for real-time output: `(stream: 'stdout' | 'stderr', data: string) => void`
- `timeout` - Maximum execution time in milliseconds

**Returns**: `Promise<ExecuteResponse>` with `success`, `stdout`, `stderr`, `exitCode`

<TypeScriptExample>
```
const result = await sandbox.exec('npm run build');

if (result.success) {
console.log('Build output:', result.stdout);
} else {
console.error('Build failed:', result.stderr);
}

// With streaming
await sandbox.exec('npm install', {
stream: true,
onOutput: (stream, data) => console.log(`[${stream}] ${data}`)
});
```
</TypeScriptExample>

### `execStream()`

Execute a command and return a Server-Sent Events stream for real-time processing.

```ts
const stream = await sandbox.execStream(command: string, options?: ExecOptions): Promise<ReadableStream>
```

**Parameters**:
- `command` - The command to execute
- `options` - Same as `exec()`

**Returns**: `Promise<ReadableStream>` emitting `ExecEvent` objects (`start`, `stdout`, `stderr`, `complete`, `error`)

<TypeScriptExample>
```
import { parseSSEStream, type ExecEvent } from '@cloudflare/sandbox';

const stream = await sandbox.execStream('npm run build');

for await (const event of parseSSEStream<ExecEvent>(stream)) {
switch (event.type) {
case 'stdout':
console.log('Output:', event.data);
break;
case 'complete':
console.log('Exit code:', event.exitCode);
break;
case 'error':
console.error('Failed:', event.error);
break;
}
}
```
</TypeScriptExample>

### `startProcess()`

Start a long-running background process.

```ts
const process = await sandbox.startProcess(command: string, options?: ProcessOptions): Promise<ProcessInfo>
```

**Parameters**:
- `command` - The command to start as a background process
- `options` (optional):
- `cwd` - Working directory
- `env` - Environment variables

**Returns**: `Promise<ProcessInfo>` with `id`, `pid`, `command`, `status`

<TypeScriptExample>
```
const server = await sandbox.startProcess('python -m http.server 8000');
console.log('Started with PID:', server.pid);

// With custom environment
const app = await sandbox.startProcess('node app.js', {
cwd: '/workspace/my-app',
env: { NODE_ENV: 'production', PORT: '3000' }
});
```
</TypeScriptExample>

### `listProcesses()`

List all running processes.

```ts
const processes = await sandbox.listProcesses(): Promise<ProcessInfo[]>
```

<TypeScriptExample>
```
const processes = await sandbox.listProcesses();

for (const proc of processes) {
console.log(`${proc.id}: ${proc.command} (PID ${proc.pid})`);
}
```
</TypeScriptExample>

### `killProcess()`

Terminate a specific process.

```ts
await sandbox.killProcess(processId: string, signal?: string): Promise<void>
```

**Parameters**:
- `processId` - The process ID (from `startProcess()` or `listProcesses()`)
- `signal` - Signal to send (default: `"SIGTERM"`)

<TypeScriptExample>
```
const server = await sandbox.startProcess('python -m http.server 8000');
await sandbox.killProcess(server.id);
```
</TypeScriptExample>

### `killAllProcesses()`

Terminate all running processes.

```ts
await sandbox.killAllProcesses(): Promise<void>
```

<TypeScriptExample>
```
await sandbox.killAllProcesses();
```
</TypeScriptExample>

### `streamProcessLogs()`

Stream logs from a running process in real-time.

```ts
const stream = await sandbox.streamProcessLogs(processId: string): Promise<ReadableStream>
```

**Parameters**:
- `processId` - The process ID

**Returns**: `Promise<ReadableStream>` emitting `LogEvent` objects

<TypeScriptExample>
```
import { parseSSEStream, type LogEvent } from '@cloudflare/sandbox';

const server = await sandbox.startProcess('node server.js');
const logStream = await sandbox.streamProcessLogs(server.id);

for await (const log of parseSSEStream<LogEvent>(logStream)) {
console.log(`[${log.timestamp}] ${log.data}`);

if (log.data.includes('Server started')) break;
}
```
</TypeScriptExample>

### `getProcessLogs()`

Get accumulated logs from a process.

```ts
const logs = await sandbox.getProcessLogs(processId: string): Promise<string>
```

**Parameters**:
- `processId` - The process ID

**Returns**: `Promise<string>` with all accumulated output

<TypeScriptExample>
```
const server = await sandbox.startProcess('node server.js');
await new Promise(resolve => setTimeout(resolve, 5000));

const logs = await sandbox.getProcessLogs(server.id);
console.log('Server logs:', logs);
```
</TypeScriptExample>

## Related resources

- [Background processes guide](/sandbox/guides/background-processes/) - Managing long-running processes
- [Files API](/sandbox/api/files/) - File operations
167 changes: 167 additions & 0 deletions src/content/docs/sandbox/api/files.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
---
title: Files
pcx_content_type: concept
sidebar:
order: 2
---

import { TypeScriptExample } from "~/components";

Read, write, and manage files in the sandbox filesystem. All paths are absolute (e.g., `/workspace/app.js`).

## Methods

### `writeFile()`

Write content to a file.

```ts
await sandbox.writeFile(path: string, content: string, options?: WriteFileOptions): Promise<void>
```

**Parameters**:
- `path` - Absolute path to the file
- `content` - Content to write
- `options` (optional):
- `encoding` - File encoding (default: `"utf-8"`)

<TypeScriptExample>
```
await sandbox.writeFile('/workspace/app.js', `console.log('Hello!');`);

// Binary data
await sandbox.writeFile('/tmp/image.png', base64Data, { encoding: 'base64' });
```
</TypeScriptExample>

### `readFile()`

Read a file from the sandbox.

```ts
const file = await sandbox.readFile(path: string, options?: ReadFileOptions): Promise<FileInfo>
```

**Parameters**:
- `path` - Absolute path to the file
- `options` (optional):
- `encoding` - File encoding (default: `"utf-8"`)

**Returns**: `Promise<FileInfo>` with `content` and `encoding`

<TypeScriptExample>
```
const file = await sandbox.readFile('/workspace/package.json');
const pkg = JSON.parse(file.content);

// Binary data
const image = await sandbox.readFile('/tmp/image.png', { encoding: 'base64' });
```
</TypeScriptExample>

### `mkdir()`

Create a directory.

```ts
await sandbox.mkdir(path: string, options?: MkdirOptions): Promise<void>
```

**Parameters**:
- `path` - Absolute path to the directory
- `options` (optional):
- `recursive` - Create parent directories if needed (default: `false`)

<TypeScriptExample>
```
await sandbox.mkdir('/workspace/src');

// Nested directories
await sandbox.mkdir('/workspace/src/components/ui', { recursive: true });
```
</TypeScriptExample>

### `deleteFile()`

Delete a file.

```ts
await sandbox.deleteFile(path: string): Promise<void>
```

**Parameters**:
- `path` - Absolute path to the file

<TypeScriptExample>
```
await sandbox.deleteFile('/workspace/temp.txt');
```
</TypeScriptExample>

### `renameFile()`

Rename a file.

```ts
await sandbox.renameFile(oldPath: string, newPath: string): Promise<void>
```

**Parameters**:
- `oldPath` - Current file path
- `newPath` - New file path

<TypeScriptExample>
```
await sandbox.renameFile('/workspace/draft.txt', '/workspace/final.txt');
```
</TypeScriptExample>

### `moveFile()`

Move a file to a different directory.

```ts
await sandbox.moveFile(sourcePath: string, destinationPath: string): Promise<void>
```

**Parameters**:
- `sourcePath` - Current file path
- `destinationPath` - Destination path

<TypeScriptExample>
```
await sandbox.moveFile('/tmp/download.txt', '/workspace/data.txt');
```
</TypeScriptExample>

### `gitCheckout()`

Clone a git repository.

```ts
await sandbox.gitCheckout(repoUrl: string, options?: GitCheckoutOptions): Promise<void>
```

**Parameters**:
- `repoUrl` - Git repository URL
- `options` (optional):
- `branch` - Branch to checkout (default: main branch)
- `targetDir` - Directory to clone into (default: repo name)
- `depth` - Clone depth for shallow clone

<TypeScriptExample>
```
await sandbox.gitCheckout('https://github.com/user/repo');

// Specific branch
await sandbox.gitCheckout('https://github.com/user/repo', {
branch: 'develop',
targetDir: 'my-project'
});
```
</TypeScriptExample>

## Related resources

- [Manage files guide](/sandbox/guides/manage-files/) - Detailed guide with best practices
- [Commands API](/sandbox/api/commands/) - Execute commands
Loading
Loading