
# SDK

::note
Written by `node site/scripts/reference.ts` from the code's documentation; do not edit it by
hand.
::

## Runtime

`import { createRuntime } from 'untainer'` (Node and browsers).

### createRuntime

```ts
function createRuntime(options: RuntimeOptions = {}): Promise<Runtime>
```

Boot a VM and return a runtime for containers in it.

| Parameter | |
| --- | --- |
| `options` | Images to know up front, memory, network, logging. |

**Returns** The runtime.

**Throws** `ERR_VM` when the VM cannot boot, `ERR_MANIFEST` for an image whose layer sources do not match its manifest.

```ts
import { createRuntime, loadImage } from 'untainer';
const rt = await createRuntime({ images: [loadImage('./images/hello')] });
```

### RuntimeOptions

Options for `createRuntime()`.

| Field | Type | |
| --- | --- | --- |
| `images?` | `Array<Image \| Promise<Image> \| string>` | Images to load before the first `run()`: images, or references (`gh:user/repo/path#v1`, a URL, on Node a directory). `run()` also takes images and references that are not listed here. |
| `resolvers?` | `ImageResolver[]` | Resolvers for references, tried before the built-in ones (`gh:`, `gh-pages:`, `jsdelivr:`, `npm:`). |
| `store?` | `ChunkStore` | The store for images this runtime loads by reference. Default: as `loadImage()`'s. |
| `cache?` | `ChunkCache` | The cache of decompressed chunks for images this runtime loads by reference. Default: the shared one. |
| `onWarning?` | `(message: string) => void` | Gets what a resolver warns about for images loaded by reference. Default: `console.warn`. |
| `auth?` | `{ token: string }` | A token for private images this runtime loads by reference (Node only; see `LoadImageOptions.auth`). |
| `memoryMiB?` | `number` | Guest memory in MiB. The guest's page cache fills what it reads and the host never gets a page back, so in a browser this is in effect the bound of the tab's memory for the VM. Default: the sum of `profile.memoryMiB` of the images given in `images`, when every one of them has it; else 1024. |
| `worker?` | `boolean` | Run the VM in a worker (a Web Worker in browsers, a worker thread on Node), so a busy guest, or a guest kernel that loops, never blocks this thread; the layers are still served from this thread. Default: in a worker, except with a network that lives on this thread (a `policyBackend()` network or an unkernel backend object), where the VM runs on this thread instead; `worker: true` with such a network is `ERR_UNSUPPORTED`. On Node, `UNTAINER_WORKER=0` in the environment makes this thread the default. |
| `net?` | `VmNet` | Outbound network for the guest, an unkernel network backend such as `directBackend()`. Default: none. |
| `log?` | `(message: string) => void` | Diagnostics from the VM. Default: ignored. |
| `disk?` | `{ name: string }` | A persistent disk for `diskVolume()`s: an ext4 file system that outlives the runtime. In a browser it is kept in the origin's IndexedDB, on Node in a file under `~/.cache/untainer/disks/`. One runtime at a time has a disk (`ERR_UNSUPPORTED` for another). |
| `memoryGuard?` | `false \| { belowKiB?: number; forMs?: number }` | The memory guard in the guest (a small program started with the VM), as earlyoom on a Linux host: when the guest's MemAvailable stays under `belowKiB` for `forMs` while tasks stall on memory, it has the kernel kill the largest process at once, instead of letting the kernel reclaim memory for minutes before it gives up. Its heartbeat also tells the runtime that the guest still runs. The kill is reported as the kernel's own (`oomKilled`, `ERR_OOM`). Default: on, with `{ belowKiB: 8192, forMs: 1000 }`; `false` turns it off (for tests). |
| `plugins?` | `UntainerPlugin[]` | Plugins (`definePlugin()` of `untainer/kit`): their resolvers come after `resolvers`, the last one's store is used unless `store` is given, and their runtime hooks apply in this order. |

### Runtime

Containers in one unkernel VM. Containers share the VM's network: each reaches the others by name.

#### runtime.worker

```ts
get worker(): boolean
```

Whether the VM runs in a worker, as `createRuntime()` chose it (`RuntimeOptions.worker`).

**Returns** True in a worker, false on the thread that created the runtime.

#### runtime.vm

```ts
get vm(): Vm['kernel']
```

The unkernel instance, for what untainer does not cover. Not covered by semver: it changes with unkernel.

**Returns** The kernel handle from unkernel's `createKernel()`.

#### runtime.containers

```ts
containers(): Container[]
```

The containers that have not exited yet.

**Returns** A new array, in start order.

#### runtime.run

```ts
async run(image: string | Image, options: RunOptions = {}): Promise<Container>
```

Start a container from an image: a name or `name:tag` known to the runtime, or an `Image` (which the runtime then knows too). Resolves once the container's first process runs; call `ready()` to wait for its probe.

| Parameter | |
| --- | --- |
| `image` | The image, or its name. |
| `options` | Name, command, environment, user, init, probe; the plugins' `run` hooks may change them. |

**Returns** The running container.

**Throws** `ERR_IMAGE_NOT_FOUND` for an unknown name, `ERR_NAME_IN_USE` when a container of that name exists, `ERR_UNSUPPORTED` when the image has no command or the name is invalid or the runtime is shut down, `ERR_PROBE` for an invalid probe, `ERR_PORT_IN_USE` when another container listens on one of its ports, `ERR_VM` when the guest cannot set the container up.

#### runtime.up

```ts
async up(services: Record<string, ServiceOptions>, opts: { timeout?: number; onStart?: (name: string, container: Container) => void } = {}): Promise<Record<string, Container>>
```

Start a set of services, as `compose up` does: each container named after its service (the others reach it under that host name), started once every service it depends on is ready (its probe passed), the independent ones at once. When one fails to start or to get ready, the ones already started are stopped again.

| Parameter | |
| --- | --- |
| `services` | Services by name. |
| `opts` | `timeout`: how long each service may take to get ready, in ms (default 60 s); `onStart`: called with each container as soon as it runs, before it is ready (to follow its logs while the others start). |

**Returns** The containers, by service name, all ready.

**Throws** `ERR_UNSUPPORTED` for a dependency on an unknown service or a cycle, and what `run()` and `ready()` throw for the service that failed.

```ts
const { db, api } = await rt.up({
  db: { image: 'postgres', env: { POSTGRES_PASSWORD: 'dev' } },
  api: { image: 'api', dependsOn: ['db'] },
});
```

#### runtime.shutdown

```ts
async shutdown(opts: { timeout?: number } = {}): Promise<void>
```

Stop every container, then flush the guest and power the VM off. Calling it again does nothing.

| Parameter | |
| --- | --- |
| `opts` | `timeout`: milliseconds each container gets between SIGTERM and SIGKILL. |

**Returns** A promise that settles once the VM is gone.

### RunOptions

Options for `rt.run()`.

| Field | Type | |
| --- | --- | --- |
| `name?` | `string` | Container name, unique in the runtime; other containers reach it under this host name. Default: from the image. |
| `env?` | `Record<string, string>` | Added to the image's environment. |
| `entrypoint?` | `string[]` | Replaces the image's entrypoint. |
| `cmd?` | `string[]` | Replaces the image's command. |
| `workdir?` | `string` | Working directory. Default: the image's. Created for the container's user if the image lacks it. |
| `user?` | `string` | user, uid, user:group or uid:gid, looked up in the container's /etc/passwd and /etc/group. Default: the image's. |
| `init?` | `boolean` | Run a small init as PID 1 that forwards signals to the command and reaps orphaned processes. Default true, unlike Docker: without it, a command that installs no SIGTERM handler ignores `stop()` until the timeout. Pass false for images that bring their own init. |
| `probe?` | `Probe \| string` | Readiness probe for `ready()`. Default, when the image's own command runs: the image's, else TCP on its first port; with `cmd` or `entrypoint`: none (ready once started). |
| `volumes?` | `Record<string, Volume>` | Volumes, by the absolute path they appear at in the container: `tmpfsVolume()`, `memoryVolume()`, or on Node `hostVolume(dir)`. Each is owned by the container's user (read-only ones as they are). |
| `ports?` | `number[]` | The TCP ports the container listens on. Containers share the VM's network, so a port one container holds is refused to another (`ERR_PORT_IN_USE`, before it starts). Default: the image's exposed ports when it runs its own command, none when `cmd` or `entrypoint` replaces it. |

### ServiceOptions

One service of `rt.up()`: an image, how to run it, and the services it needs first.

| Field | Type | |
| --- | --- | --- |
| `image` | `string \| Image` | The image: a name the runtime knows, a reference, or an `Image`. |
| `dependsOn?` | `string[]` | Services that must be ready (their probes passed) before this one starts. |

## Containers

`rt.run()` returns a `Container`.

### Container

A running image. Created by `rt.run()`.

#### container.state

```ts
get state(): ContainerState
```

Where the container is in its life: `created`, `starting`, `running` or `exited`.

**Returns** The current state.

#### container.ready

```ts
async ready(opts: { probe?: Probe | string; timeout?: number } = {}): Promise<void>
```

Wait until the container answers its probe: `opts.probe`, else the image's, else a TCP connection to its first port. Without any of those it resolves once the container runs. The probe is retried every 100 ms.

| Parameter | |
| --- | --- |
| `opts` | `probe`: a probe to use instead; `timeout`: milliseconds, 60 s by default. |

**Returns** A promise that settles once the probe passed.

**Throws** `ERR_PROBE_TIMEOUT` when the probe does not pass in time (`ERR_OOM` when the guest ran out of memory just before), `ERR_CONTAINER_EXITED` when the container exits first, `ERR_PROBE` for an invalid probe.

#### container.exec

```ts
async exec(file: string, args: string[] = [], opts: ExecOptions = {}): Promise<ExecResult>
```

**It ends after 5 minutes by default** (`ERR_TIMEOUT`, and the command is killed): give a long command (`pg_dump`, a build, a test suite) a `timeout` in milliseconds, or `timeout: 0` for none.

Run a command inside the container (its namespaces, root, user and environment) and collect its output. A non-zero exit code is a result, not an error.

| Parameter | |
| --- | --- |
| `file` | The program, looked up on the container's PATH. |
| `args` | Its arguments. |
| `opts` | Another user, extra environment, working directory, or stdin; `timeout` (milliseconds for the whole command, 5 min by default, 0 for none) and `signal`. |

**Returns** The output and how the command ended. Exit code 125 means untainer could not start it (for example an unknown user), 127 that the program was not found.

**Throws** `ERR_CONTAINER_EXITED` when the container is not running, `ERR_TIMEOUT` at the timeout (the command is killed; the runtime goes on), `ERR_VM` or `ERR_OOM` when the VM stops answering meanwhile; the signal's reason when it aborts.

#### container.spawn

```ts
async spawn(file: string, args: string[] = [], opts: Omit<ExecOptions, 'input'> = {}): Promise<Process>
```

Start a command inside the container on pipes and return at once. Read both stdout and stderr, or cancel the one you do not need: the command blocks once its output is not read.

| Parameter | |
| --- | --- |
| `file` | The program, looked up on the container's PATH. |
| `args` | Its arguments. |
| `opts` | Another user, extra environment or working directory; `timeout` (milliseconds for the command to start, 30 s by default) and `signal` (aborts the start, and kills the command once it runs). |

**Returns** The running process.

**Throws** `ERR_CONTAINER_EXITED` when the container is not running, `ERR_TIMEOUT` when it does not start in time, `ERR_VM` or `ERR_OOM` when the VM stops answering; the signal's reason when it aborts first.

#### container.fetch

```ts
async fetch(input: string | URL, init: RequestInit & { port?: number } = {}): Promise<Response>
```

Send an HTTP request to a server in the container. A relative URL goes to the container's first port; `init.port` or a port in the URL picks another.

| Parameter | |
| --- | --- |
| `input` | A path such as `/health`, or a URL. |
| `init` | As for `fetch()`, plus `port`. |

**Returns** The response, with a streaming body.

**Throws** `ERR_CONTAINER_EXITED` when the container is not running, `ERR_UNSUPPORTED` when neither the image nor the call names a port.

```ts
const res = await api.fetch('/health');
```

#### container.connect

```ts
async connect(port: number): Promise<VmSocket>
```

Open a TCP connection to a port in the container.

| Parameter | |
| --- | --- |
| `port` | The port. |

**Returns** The connection.

**Throws** `ERR_CONTAINER_EXITED` when the container is not running.

#### container.logs

```ts
logs(opts: { stream?: LogStream | 'both' } = {}): AsyncIterable<string>
```

The container's output line by line: what it printed so far (the last 10,000 lines), then new lines as they come, until it exits.

| Parameter | |
| --- | --- |
| `opts` | `stream`: `stdout`, `stderr` or `both` (the default). |

**Returns** An async iterable of lines without their line endings.

#### container.stop

```ts
async stop(opts: { signal?: string; timeout?: number } = {}): Promise<ExitStatus>
```

Stop the container: `signal` (SIGTERM by default) to its PID 1, then SIGKILL to every process in it after `timeout`. With init (the default), the signal reaches the command itself. With `init: false`, a command that has no handler for it ignores it, as any PID 1 does, and is killed only after the timeout.

| Parameter | |
| --- | --- |
| `opts` | `signal`: name such as `TERM` or `SIGINT`; `timeout`: milliseconds, 10 s by default. |

**Returns** How the container ended, once its mounts are released.

**Throws** `ERR_UNSUPPORTED` when the container was never started; `ERR_OOM` or `ERR_VM` when the VM stopped answering.

#### container.wait

```ts
wait(): Promise<ExitStatus>
```

Wait until the container has exited and its mounts are released.

**Returns** How the main process ended: exit code, or the signal that killed it.

**Throws** `ERR_UNSUPPORTED` when the container was never started; `ERR_OOM` or `ERR_VM` when the VM stopped answering first (the end is then not known).

### ExitStatus

How a container or a process ended: an exit code, or the number of the signal that killed it.

| Field | Type | |
| --- | --- | --- |
| `exitCode` | `number \| null` |  |
| `signal` | `number \| null` |  |
| `oomKilled?` | `boolean` | The guest ran out of memory and its kernel killed a process of the container (the main process ended with SIGKILL, or 137 under init, without a `stop()`). |
| `oomMessage?` | `string` | The kernel's line about the kill, such as `Out of memory: Killed process 119 (awk) ...`. |
| `slimMissing?` | `string[]` | While the container ran, reads asked for content that `--slim` removed from its image (the guest got an I/O error, a program that maps the file a SIGBUS): the files it was in, absolute paths. Empty when the image does not name them. |
| `fetchFailed?` | `Array<{ url?: string; status?: number; message: string; files: string[] }>` | While the container ran, chunks of its image could not be fetched (after their tries): the guest got an I/O error, a program that maps the file a SIGBUS. For each, the URL, the host's status and message, and the files of the image with data in it. |

### ExecOptions

Options for a command run inside a container.

| Field | Type | |
| --- | --- | --- |
| `user?` | `string` | user, uid, user:group or uid:gid. Default: the container's user. |
| `env?` | `Record<string, string>` | Added to the container's environment. |
| `cwd?` | `string` | Working directory inside the container. Default: the container's. |
| `input?` | `string \| Uint8Array` | Bytes for stdin (strings are UTF-8), then end of file. |

### GuestCallOptions

Bounds of a call into the guest.

| Field | Type | |
| --- | --- | --- |
| `timeout?` | `number` | Milliseconds. For `exec()`: for the whole command, 300000 (5 min) by default; for `spawn()`: for the command to start, 30000 by default. 0: no limit. At the limit the call fails with `ERR_TIMEOUT` and the command is killed; the runtime goes on working. |
| `signal?` | `AbortSignal` | Aborts the call (it rejects with the signal's reason) and kills the command (SIGKILL). |

### Process

A command running inside a container, on pipes.

| Field | Type | |
| --- | --- | --- |
| `stdin` | `WritableStream<Uint8Array \| string>` |  |
| `stdout` | `ReadableStream<Uint8Array>` |  |
| `stderr` | `ReadableStream<Uint8Array>` |  |
| `ended` | `Promise<ExitStatus>` |  |
| `kill` | `(signal?: string): void` |  |

### publishPort

```ts
async function publishPort(container: Container, options: PublishOptions): Promise<PublishedPort>
```

Publish a container's port on this machine: listen on a host port and pass each connection to the container's port through the VM (the guest has no network of its own the host could reach). Node only; a browser cannot listen.

| Parameter | |
| --- | --- |
| `container` | The container. |
| `options` | Host port (0 for any free one), container port, and the host address (default `127.0.0.1`). |

**Returns** The published port; `close()` stops it.

**Throws** `ERR_PORT_IN_USE` when the host port is taken, `ERR_UNSUPPORTED` for an address that cannot be listened on.

```ts
const web = await rt.run('hello');
const port = await publishPort(web, { hostPort: 8080, containerPort: 8080 });
console.log(port.url); // http://127.0.0.1:8080/
```

### PublishOptions

What to publish: a host port for a container port.

| Field | Type | |
| --- | --- | --- |
| `hostPort` | `number` | The host's port; 0 picks a free one. |
| `containerPort` | `number` | The container's port. |
| `host?` | `string` | The host address to listen on. Default `127.0.0.1`: only this machine reaches it. |

### PublishedPort

A container port published on the host (Node only).

| Field | Type | |
| --- | --- | --- |
| `url` | `string` | `http://127.0.0.1:<hostPort>/` (the scheme only names the address; any TCP protocol works). |
| `hostPort` | `number` | The host's port, as bound (useful with a requested port of 0). |
| `containerPort` | `number` | The container's port. |
| `close` | `(): Promise<void>` | Stop listening and close every connection passed so far. |

## Volumes

For `RunOptions.volumes`.

### tmpfsVolume

```ts
function tmpfsVolume(options: { sizeMiB?: number } = {}): Volume
```

A tmpfs for a container path: in the guest's memory, empty at each start, gone when the container exits. Owned by the container's user.

| Parameter | |
| --- | --- |
| `options` | `sizeMiB`: the most it may hold (default: half the guest's memory). |

**Returns** The volume.

### memoryVolume

```ts
function memoryVolume(options: { readOnly?: boolean } = {}): Volume
```

A file system in this process's memory (in a browser, the tab's): it outlives the containers it is given to, which share it, and is gone with the process. Owned by the container's user.

| Parameter | |
| --- | --- |
| `options` | `readOnly`: the containers cannot write it. |

**Returns** The volume.

### diskVolume

```ts
function diskVolume(name: string, options: { readOnly?: boolean } = {}): Volume
```

A directory of the runtime's persistent disk (`createRuntime({ disk })`), kept by name: what a container writes there is there for the next container and the next runtime with the disk. In a browser it lives in the origin's IndexedDB, on Node in the disk's file. Owned by the container's user, as Linux keeps owners there.

| Parameter | |
| --- | --- |
| `name` | Its name on the disk: letters, digits, `.`, `_` and `-`. |
| `options` | `readOnly`: the containers cannot write it. |

**Returns** The volume.

**Throws** `ERR_UNSUPPORTED` for another name.

### hostVolume

```ts
function hostVolume(path: string, options: { readOnly?: boolean } = {}): Volume
```

A directory of the host as a container volume (Node only): the container reads and writes the host's files there. The container sees every file in it owned by its own user (the host's owners mean nothing in the guest); permission bits go through.

| Parameter | |
| --- | --- |
| `path` | The directory; relative to the working directory, created if missing. |
| `options` | `readOnly`: the container cannot write it. |

**Returns** The volume.

```ts
await rt.run('postgres', { volumes: { '/var/lib/postgresql/data': hostVolume('./pgdata') } });
```

## Network

For `RuntimeOptions.net` (Node). Without it the guest has no network.

### directBackend

```ts
function directBackend(): DirectNet
```

A network for the guest that makes its connections from this process, to wherever this process can connect: the internet, and also this host's own services and its local network. Wrap it in `policyBackend()` to keep the guest to the internet. It is unkernel's direct network as a spec, so it works with `worker: true` too.

**Returns** The network, for `createRuntime({ net })`.

### policyBackend

```ts
function policyBackend<T extends DirectNet | NetBackend>(inner: T, options: NetPolicyOptions = {}): T | PolicyNet
```

Keep the guest's connections to the internet: each TCP connection and UDP flow is checked when it is made, on the address it goes to, and refused when that is the host's loopback, one of its own addresses, a private, shared or link-local range (with cloud metadata at 169.254.169.254), multicast, reserved, or the IPv6 equivalents. A name a backend would dial is resolved first and dialled at the address that was checked. The policy runs on this thread: a runtime given it runs the VM on this thread unless told otherwise, and refuses `worker: true` (`ERR_UNSUPPORTED`).

| Parameter | |
| --- | --- |
| `inner` | What makes the connections: `directBackend()`, or an unkernel backend object. |
| `options` | `private: false` lets everything through; `onBlocked` hears of refusals. |

**Returns** The network, for `createRuntime({ net })`.

```ts
createRuntime({ net: policyBackend(directBackend()) });                    // the internet only
createRuntime({ net: policyBackend(directBackend(), { private: false }) }); // everything
```

### NetPolicyOptions

Options for `policyBackend()`.

| Field | Type | |
| --- | --- | --- |
| `private?` | `boolean` | Block what is not the internet: loopback, this host's own addresses, private, shared (100.64.0.0/10), link-local (169.254.0.0/16, cloud metadata at 169.254.169.254) and the IPv6 equivalents, multicast and reserved ranges. Default true; false lets everything through. |
| `onBlocked?` | `(blocked: BlockedConnection) => void` | Gets every connection the policy refuses. |

### BlockedConnection

A guest connection or UDP flow the policy refused.

| Field | Type | |
| --- | --- | --- |
| `transport` | `'tcp' \| 'udp'` |  |
| `host` | `string` | The address the guest asked for (a name only from a backend that dials names). |
| `port` | `number` |  |
| `address` | `string` | The address that was blocked: `host`, or what the name resolved to. |
| `reason` | `BlockedClass` | Why. |

## Images

Loading images, where their chunks are kept, and references.

### loadImage

```ts
async function loadImage(location: string, options: LoadImageOptions = {}): Promise<Image>
```

Load an image: from a local image directory, as `untainer build` writes it (`manifest.json`, `layers/<hex>.json` and `chunks/`), or over HTTP from a URL. Chunks are read only when the guest touches them. Over HTTP, fetched chunks and layer indexes are kept in a store, by default in the cache directory, so a second start fetches only the manifest.

| Parameter | |
| --- | --- |
| `location` | The image directory (or `file:` URL), an `http:` or `https:` URL of the image's directory or of its `manifest.json`, or a reference such as `gh:user/repo/path#v1` (see `resolveReference()`). |
| `options` | Store, cache of decompressed chunks, and for URLs headers and fetch. |

**Returns** The image.

**Throws** `ERR_IMAGE_NOT_FOUND` when the manifest or a layer index is missing, `ERR_SCHEMA` or `ERR_MANIFEST` when the manifest is invalid.

```ts
const local = await loadImage('./dist/postgres-17-alpine');
const remote = await loadImage('https://cdn.example/postgres-17-alpine/');
```

### LoadImageOptions

Options for loading an image.

| Field | Type | |
| --- | --- | --- |
| `store?` | `ChunkStore` | Where fetched chunks and layer indexes are kept. Default: none for a directory, a store in the cache directory (Node) or the browser's storage (browser) for a URL. |
| `headers?` | `Record<string, string>` | Headers for every request of an image loaded over HTTP. |
| `fetch?` | `typeof fetch` | Replaces the global fetch for an image loaded over HTTP. |
| `cache?` | `ChunkCache` | Decompressed chunks. Default: the shared cache (`defaultChunkCache()`). |
| `resolvers?` | `readonly ImageResolver[]` | Resolvers for references, tried before the built-in ones. |
| `onWarning?` | `(message: string) => void` | Gets what a resolver warns about (a branch a CDN keeps stale). Default: `console.warn`. |
| `auth?` | `{ token: string }` | A token for a private image (Node only): sent as `Authorization: token <token>` to the image's own origin, never to another host a manifest points at. For a private GitHub repository, a token that can read it. A browser refuses it (`ERR_UNSUPPORTED`): whatever a page holds, its visitors can read. Take it from the environment, never from code. |

### ChunkStore

Where fetched chunks are kept, compressed as they came, so that a later start does not fetch them again. Keys are a chunk's hash (hex), or `index-<layer hex>` for a layer index.

| Field | Type | |
| --- | --- | --- |
| `get` | `(key: string): Promise<Uint8Array \| undefined>` | The bytes stored under a key. |
| `put` | `(key: string, data: Uint8Array): Promise<void>` | Keep bytes under a key. Storing a key twice keeps either copy: content under one key never changes. |
| `has` | `(key: string): Promise<boolean>` | Whether the store has a key. |

### memoryStore

```ts
function memoryStore(options: { maxBytes?: number } = {}): ChunkStore
```

A chunk store in memory: compressed chunks and layer indexes, least recently used first out once `maxBytes` is reached. Lost when the process or the page ends.

| Parameter | |
| --- | --- |
| `options` | `maxBytes`: the bound (default 256 MiB). |

**Returns** The store.

```ts
const image = await loadImage('https://cdn.example/app/', { store: memoryStore() });
```

### dirStore

```ts
function dirStore(dir: string): ChunkStore
```

A chunk store in a directory: one file per key, in subdirectories named after the key's first two characters. Writes go through a temporary file, so a reader never sees half a chunk.

| Parameter | |
| --- | --- |
| `dir` | The directory; created when needed. |

**Returns** The store.

```ts
const image = await loadImage('https://cdn.example/app/', { store: dirStore('./chunks') });
```

### browserStore

```ts
function browserStore(): BrowserStore
```

The browser's persistent store: OPFS where a test write there works (some browsers have the API but refuse writes, for example in a private window), else IndexedDB, else memory. The backend is chosen on first use.

**Returns** The store.

### ImageResolver

Turns a short reference such as `gh:user/repo/path#v1` into the URL of an image.

| Field | Type | |
| --- | --- | --- |
| `name` | `string` | The prefix it handles, without the colon, such as `gh`. |
| `match` | `(ref: string): boolean` | Whether this resolver handles a reference. |
| `resolve` | `(ref: string, context?: ResolveContext): Promise<ResolvedReference>` | Resolve a reference. |

### ResolvedReference

Where a reference points: the base URL of the image's `manifest.json`.

| Field | Type | |
| --- | --- | --- |
| `baseUrl` | `string` | The image's base URL, ending with a slash. |
| `headers?` | `Record<string, string>` | Headers for every request of the image (Node only; see `LoadImageOptions.headers`). |
| `warnings?` | `string[]` | What the caller should know about the reference, such as a branch that a CDN keeps stale. |

## Building images

`import { build } from 'untainer/build'` (Node).

### build

```ts
async function build(ref: string, options: BuildOptions): Promise<BuildResult>
```

Build a micro-image from an image in a registry: resolve linux/arm64, download and verify the layers into the cache, merge them into one erofs image in the builder VM, and write the image directory (manifest, layer index, chunks).

| Parameter | |
| --- | --- |
| `ref` | An image reference, such as `postgres:17-alpine`. |
| `options` | Output directory, cache, chunk size, registry settings. |

**Returns** The manifest, the step timings and the sizes.

**Throws** `ERR_UNSUPPORTED` for a bad reference or no linux/arm64 image, `ERR_REGISTRY`, `ERR_RATE_LIMIT` or `ERR_DIGEST` from the registry, `ERR_VM` from the builder.

```ts
const result = await build('node:24-alpine', { outDir: './images/node' });
```

### BuildOptions

Options of `build()` and `buildFromLayers()`.

| Field | Type | |
| --- | --- | --- |
| `outDir` | `string` | Directory to write the image to (created; an existing image there is replaced). |
| `plugins?` | `UntainerPlugin[]` | Plugins whose build hooks apply, in this order (`definePlugin()` of `untainer/kit`). |
| `cacheDir?` | `string` | Cache for blobs, layer tars and toolbox packages. Default `$XDG_CACHE_HOME/untainer` or ~/.cache/untainer. |
| `chunkSize?` | `number` | Bytes per chunk. Default 256 KiB. |
| `zstdLevel?` | `number` | zstd level of the chunks, 1 to 22. Default 3: fast to build. 19 makes chunks about 14% smaller (postgres:17-alpine) for about 50 times the compression time; worth it for images that are published and fetched many times. Readers do not care: any level decodes the same way. |
| `probe?` | `string` | Readiness probe to record in the manifest, such as `tcp:5432`. |
| `memoryMiB?` | `number` | Guest memory the image needs, in MiB, to record in the manifest (`profile.memoryMiB`). Default, when there is a probe: measured by starting the image (see `profile`). |
| `profile?` | `boolean` | With a probe and no `memoryMiB`: start the built image once until the probe passes and record the memory its start needed (`memoryFor()` of the peak of MemTotal - MemAvailable). Default true; false skips it. |
| `layout?` | `boolean` | With a probe and the profiling start: lay the image out by that start (`layoutByReads()`): the image is written chunk-based, started once to see which blocks it reads, and those blocks move to the front of its data, so the start needs as few chunks as it can. Default true; false keeps mkfs.erofs' flat layout. |
| `onWarning?` | `(message: string) => void` | Called with what the build did not do as asked but could do without, such as the layout. Default `console.warn`. |
| `profileEnv?` | `Record<string, string>` | Environment for that start, such as a password the image requires. Not recorded. |
| `profileCmd?` | `string[]` | The command for that start instead of the image's (a server in a runtime image). Not recorded. |
| `profileScript?` | `string` | A shell script run in the container once its probe passes, in every start of the build (a profile under load: queries, requests). What it makes the application read goes into the layout, the boot bundle and what `slim` keeps, the memory it takes into `memoryMiB`. It must exit 0. Not recorded: the runtime's readiness check stays the probe. |
| `bootPartSize?` | `number` | The largest a boot bundle part may be, in bytes; 0 makes none. Boot bundles are made from the profiling start (so only with a probe). Default 4 MiB. |
| `bases?` | `string[]` | Base images to build over, as image directories (`untainer base` writes them). The one whose source layers (`source.layers`) the image's layers start with, the longest such, becomes the image's bottom layer as it is, and the image keeps only what it adds to it. Default: the images in `<cacheDir>/bases/`; `[]` builds over none. |
| `slim?` | `{ mode?: SlimMode; keep?: string[]; trace?: boolean }` | With a probe and the profiling start: remove the content of files the image does not need. `mode` `files` (the default) keeps whole every file the start read (`trace`, default true) and every path in `keep`; `chunks` keeps only the chunks the start read, so the image can do what its start did and little else. The tree stays whole; reading removed content is `ERR_SLIM`. The image is started once more and must get ready without it. |
| `fromProfile?` | `BuildProfile` | Take what the starts found from a saved profile (`profile.json` of an earlier build) instead of starting the image: the same image again, without running its probe. The profile fits only the image it was made from; another one is `ERR_DIGEST`. |
| `asBase?` | `boolean` | Mark the image's layer as a base (`role: 'base'`), for `untainer base`. |
| `mirrors?` | `string[]` | Docker Hub mirrors, used when Docker Hub answers 429. |
| `credentials?` | `{ username: string; password: string }` | Registry credentials. |
| `toolboxMirrors?` | `string[]` | Mirrors for the toolbox packages. |
| `builder?` | `Builder` | A running builder to reuse; otherwise one is started and stopped. |
| `log?` | `(message: string) => void` | Diagnostics. |
| `onProgress?` | `(event: BuildProgress) => void` | Called when a step starts and when it ends. |

### BuildResult

What a build produced, and how long each step took.

| Field | Type | |
| --- | --- | --- |
| `dir` | `string` |  |
| `manifest` | `Manifest` |  |
| `timings` | `Record<string, number>` | Milliseconds per step: resolve, download, build, pack. |
| `sizes` | `{ ociCompressed?: number; image: number; chunksCompressed: number }` | Bytes: the OCI image's compressed layers, the erofs image (over a base: of what the image adds), and its compressed chunks. |
| `base?` | `{ dir: string; name: string }` | The base image it was built over, if any. |
| `slim?` | `{ removed: number; chunks: number; keptBytes: number }` | With `slim`: chunks of the image's own layer removed, and the bytes of the chunk files left. |

## Plugins

`import { definePlugin } from 'untainer/kit'`.

### definePlugin

```ts
function definePlugin(plugin: UntainerPlugin): UntainerPlugin
```

Declare a plugin. It returns the plugin as it is: it exists for its type, so that an editor checks the hooks and their arguments.

| Parameter | |
| --- | --- |
| `plugin` | The plugin. |

**Returns** The same plugin.

```ts
import { definePlugin } from 'untainer/kit';
export default definePlugin({
  name: 'stamp',
  build: { files: () => [{ name: 'etc/stamp', mode: 0o644, data: new TextEncoder().encode('built\n') }] },
});
```

### UntainerPlugin

A plugin: a name and any of these. `createRuntime({ plugins })` and `build(ref, { plugins })` take a list; plugins apply in their order.

| Field | Type | |
| --- | --- | --- |
| `name` | `string` | A name for messages, such as `my-store`. |
| `resolvers?` | `ImageResolver[]` | Resolvers for references, tried after the runtime's `resolvers` and before the built-in ones. |
| `store?` | `ChunkStore` | The store for images loaded by reference, unless the runtime is given one (the last plugin's wins). |
| `build?` | `BuildHooks` | Build hooks. |
| `runtime?` | `RuntimeHooks` | Runtime hooks. |

### BuildHooks

What a plugin can change of a build (`build()` of `untainer/build`, Node).

| Field | Type | |
| --- | --- | --- |
| `files?` | `(context: { name: string; tag?: string }): TarEntryInput[] \| Promise<TarEntryInput[]>` | Files to add to the image, on top of its layers (a file of the image at the same path is replaced). Called once per build, before the image's file system is made. |
| `config?` | `(config: ImageConfig): ImageConfig \| Promise<ImageConfig>` | Change the image's config (command, environment, user, ports) before it is recorded. |
| `done?` | `(result: BuildResult): void \| Promise<void>` | Called once the image is written. |

### RuntimeHooks

What a plugin can change of a runtime.

| Field | Type | |
| --- | --- | --- |
| `run?` | `(image: Manifest, options: RunOptions): RunOptions \| void` | Called before a container is created: return options to use instead (more environment, other volumes...). |
| `exit?` | `(container: Container, status: ExitStatus): void` | Called once a container has exited (not when its VM stopped answering). |

## Errors

Every error untainer throws on purpose is an `UntainerError` with a `code`.

### UntainerErrorCode

| Code | Meaning |
| --- | --- |
| `ERR_SCHEMA` | a manifest with a `schema` this version does not know. |
| `ERR_MANIFEST` | a manifest that is not valid for its schema. |
| `ERR_IMAGE_NOT_FOUND` | `run()` was given an image the runtime cannot find. |
| `ERR_NAME_IN_USE` | a container with that name already exists in the runtime. |
| `ERR_PROBE` | a probe string that cannot be parsed. |
| `ERR_PROBE_TIMEOUT` | the readiness probe did not pass in time. |
| `ERR_CONTAINER_EXITED` | the container exited while something waited for it. |
| `ERR_UNSUPPORTED` | the image or option needs a feature this version lacks. |
| `ERR_VM` | the virtual machine failed (boot error, crash, a guest step that failed). |
| `ERR_REGISTRY` | a registry refused or failed a request (the message has the status). |
| `ERR_RATE_LIMIT` | a registry answered 429 and no mirror or credentials could take over. |
| `ERR_DIGEST` | downloaded or decompressed content does not match its digest. |
| `ERR_CHUNK_HASH` | a chunk of an image does not match its hash. |
| `ERR_FETCH` | a chunk could not be fetched (a failed request or a status other than 200). |
| `ERR_OOM` | the guest ran out of memory and its kernel killed a process of the container, or the guest stopped answering right after it ran out of memory. |
| `ERR_TIMEOUT` | a call into the guest (`exec()`, `spawn()`, a step of the runtime) did not finish within its timeout; the command was killed, and the runtime goes on working. |
| `ERR_PORT_IN_USE` | a host port to publish a container port on is taken, or another container of the runtime listens on a port the container would. |
| `ERR_SLIM` | a read needed a chunk that `--slim` removed from the image, or a `--keep` path the image does not have. |
