# TypeScript SDK

@foxdeploy/sdk for Node 22.18 or newer: start a computer, run commands, move files, open a preview and pause it. No runtime dependencies.

## Install and set the key

```sh
npm install @foxdeploy/sdk
export FOXDEPLOY_API_KEY=YOUR_KEY
```

The SDK reads `FOXDEPLOY_API_KEY`, or takes `apiKey` in its options. The key goes in a header only. No error, log line or printed object ever carries it.

## Start, run, pause

```ts
import { Computer } from '@foxdeploy/sdk';

const sb = await Computer.create({ size: 'small', region: 'sgp' });
const result = await sb.exec('uname -a');
console.log(result.stdout, result.exit_code);
await sb.pause();
```

`exec` takes a string, which runs in `/bin/sh -c` inside the computer, or a list, which runs as it is. It waits for the command and returns `exit_code`, `stdout` and `stderr`.

## Output as it comes

```ts
await sb.exec('npm test', {
  timeoutS: 900,
  onStdout: (text) => process.stdout.write(text),
  onStderr: (text) => process.stderr.write(text),
});

for await (const event of sb.execStream(['python3', 'train.py'])) {
  if (event.type === 'stdout') process.stdout.write(event.data);
  if (event.type === 'exit') console.log('exit code', event.exitCode);
}
```

## Files

```ts
import { Computer } from '@foxdeploy/sdk';

const sb = await Computer.create({ size: 'small', region: 'sgp' });
await sb.files.write('/root/app/hello.txt', 'Hello\n');
console.log(await sb.files.read('/root/app/hello.txt'));
console.log(await sb.files.list('/root/app'));
const zip = await sb.files.downloadZip('/root/app');
console.log('zip bytes', zip.byteLength);
await sb.files.remove('/root/app/hello.txt');
await sb.destroy();
```

`files.writeBytes(folder, name, bytes)` uploads binary content. A single file may be up to 100 MiB.

## Ports and preview links

```ts
import { Computer } from '@foxdeploy/sdk';

const sb = await Computer.create({ size: 'small', region: 'sgp' });
await sb.exec('nohup python3 -m http.server 8000 >/dev/null 2>&1 &');
console.log(await sb.ports());
const preview = await sb.openPreview(8000);
console.log(preview.url);
await sb.closePreview();
await sb.destroy();
```

A preview link is private by default: it carries a token, so share it only with people who should see the page. `{ private: false }` makes a link anyone can open, and `{ requireSignIn: true }` asks visitors to sign in to your organisation first.

## Pause, resume, snapshots

```ts
import { Computer } from '@foxdeploy/sdk';

const sb = await Computer.create({ size: 'small', region: 'sgp' });
await sb.pause();
await sb.resume();
const snap = await sb.snapshot({ name: 'after-install' });
const { items } = await sb.snapshots();
console.log(items.map((s) => s.name));
await sb.pause();
await sb.resume({ snapshotId: snap.id });
await sb.destroy();
```

`stop()` and `start()` stop the computer and start it again from its disk. `destroy()` removes the computer and its snapshots and cannot be undone. `Computer.deleteSnapshot(id)` deletes one snapshot.

## A terminal

```ts
const term = await sb.terminal({ cols: 120, rows: 30 });
term.onData((text) => process.stdout.write(text));
term.write('ls -la\n');
term.resize(100, 40);
term.close();
```

## An existing computer

```ts
const sb = await Computer.connect('cm_8f2k7q');
const { items } = await Computer.list({ state: 'running' });
```

## Errors

Every error is a `ComputerError` with `code`, `status` and `message`. The class says what kind:

| Class | When |
|---|---|
| `AuthenticationError` | 401: no key, a wrong key or a revoked one |
| `PermissionDeniedError` | 403: the key's scope does not allow this |
| `NotFoundError` | 404: no computer with that id in your organisation |
| `InvalidStateError` | 409: not now, for example a command while paused |
| `ValidationError` | 400 or 422: see `fields` |
| `LimitError` | credit empty, the monthly or concurrent limit, the largest size |
| `RateLimitError` | 429, with `retryAfterMs` |
| `ServerError`, `TimeoutError`, `ConnectionError` | the service, the clock or the network |

```ts
import { InvalidStateError } from '@foxdeploy/sdk';

try {
  await sb.exec('make');
} catch (err) {
  if (err instanceof InvalidStateError) await sb.resume();
  else throw err;
}
```

## Retries and timeouts

A call answered 429, or 503 when nothing was started, is tried again up to 3 times, after the time in `Retry-After` or a growing pause. Other server errors are tried again only for calls that are safe to repeat: reads, writes of a whole file, deletes, and creates, which carry an `Idempotency-Key` so a repeated create starts one computer. A command is never run twice by a retry. A call times out after 60 seconds; `exec` adds its `timeoutS`.

```ts
import { Client, Computer } from '@foxdeploy/sdk';

const client = new Client({ apiKey: process.env.MY_KEY, timeoutMs: 30_000, maxRetries: 5 });
const sb = await Computer.create({ client, size: 'medium' });
```

## Not in the SDK yet

Changing a computer's settings, its logs, the desktop, the image and region lists and the events stream are in the [HTTP API](https://docs.foxdeploy.ai/api-reference.md) only for now.

Source: https://docs.foxdeploy.ai/typescript/
