# @typstream/core

> The contracts every typstream package shares, with text edits and position mapping, diagnostics, the plugin contract, telemetry events and the engine protocol.

Source: https://typstream.vercel.app/docs/reference/core

`@typstream/core` holds the types and small pure helpers the other packages agree on: text edits and source maps,
the `Diagnostic` shape, the plugin contract (`TypstreamPlugin`), the telemetry events, and the protocol between the
engine client and its worker. It has no dependencies and runs anywhere. All offsets are **UTF-16 code unit indices**
(JavaScript string indices).

## When to use it

You rarely install it on its own: the packages you use re-export the types you need (the event types come with
`typstream` and `@typstream/react`). Import from it directly when you write a [plugin](/docs/guides/writing-a-plugin)
(`definePlugin`, `DiagnosticFixer`, `HealHandler`), handle diagnostics (`formatDiagnostic`, `mapDiagnostic`), or
implement an engine transport or server ([remote engine](/docs/guides/remote-engine): the protocol types and
`serializeMessage`).

## Install

```npm
npm install @typstream/core
```

## Example

A plugin is a plain object; `definePlugin` type-checks it and keeps its literal type:

```ts title="acme-plugin.ts"
import { definePlugin } from "@typstream/core";

export const acme = definePlugin({
  key: "acme/branding",
  engine: {
    preamble: '#set text(font: "Libertinus Serif", size: 11pt)',
  },
  templates: [
    { name: "letter", title: "Letter", preamble: '#set page(paper: "us-letter")', inputs: { logo: "true" } },
  ],
  prompt: { rules: ["Start every document with a level-1 heading."] },
  stylesheets: [".typstream h1 { color: #0b5394; }"],
});
```

Pass it in `plugins` to `<Typstream>`, `mountTypstream` or `engine.open()`. [Writing a plugin](/docs/guides/writing-a-plugin)
covers every facet.

## API

The exports fall into six groups:

| Group | Main exports |
| --- | --- |
| [Text edits and positions](#text-edits-and-positions) | `TextEdit`, `applyEdit`, `mapPosition`, `diffEdit`, `SourceMap`, `Patch`, `Range` |
| [Diagnostics](#diagnostics) | `Diagnostic`, `formatDiagnostic`, `mapDiagnostic`, `normalizeDiagnostics`, `lineColumn` |
| [Plugins](#plugins) | `TypstreamPlugin`, `definePlugin`, `resolvePlugins`, `HealHandler`, `DiagnosticFixer`, `FileGenerator`, `TemplateSpec` |
| [Telemetry events](#telemetry-events) | `DocumentEvent`, `CompiledEvent`, `RenderedEvent`, `FallbackEvent`, `WatchdogEvent`, `FallbackLevel` |
| [Protocol](#protocol) | `PROTOCOL_VERSION`, `RequestMap`, `CompileParams`, `CompileResult`, `Artifact`, `ProtocolError` |
| [Serialization](#serialization) | `serializeMessage`, `deserializeMessage` |

## Text edits and positions

Streaming is one kind of edit: the engine, the healer and (later) the editor all describe changes as `TextEdit`s and
map positions through them.

### `TextEdit`, `Range` and `EditOrigin`

```ts
interface Range {
  from: number;
  to: number;
}

type EditOrigin = "stream" | "user" | "ai" | "remote";

interface TextEdit {
  from: number;
  to: number;
  insert: string;
  origin?: EditOrigin;
}
```

A `Range` is half-open, `[from, to)`. A `TextEdit` replaces `[from, to)` with `insert`; an append is
`from = to = length`. `origin` says who made the edit.

### `applyEdit`

```ts
const applyEdit: (text: string, edit: TextEdit) => string;
```

Applies one edit to a string.

### `diffEdit`

```ts
const diffEdit: (prev: string, next: string) => TextEdit | null;
```

The smallest single edit that turns `prev` into `next` (common prefix and suffix), or `null` when they are equal. It
never splits a surrogate pair.

### `mapPosition`

```ts
const mapPosition: (pos: number, edit: TextEdit, assoc?: 1 | -1) => number;
```

Maps a position through an edit, for example a cursor or a diagnostic's offset to the next revision. Positions inside
the replaced range move to the end of the insertion when `assoc` is `1` (default), or to its start when `-1`.

```ts
mapPosition(10, { from: 0, to: 0, insert: "Hi " }); // 13
```

### `SourceMap` and `Patch`

```ts
class SourceMap {
  constructor(patches: readonly Patch[]);
  readonly patches: readonly Patch[];
  toResult(pos: number): number;
  toOriginal(pos: number, assoc?: 1 | -1): number;
}
```

Bidirectional position mapping between an input and the output of a transform (such as healing), built from
non-overlapping patches sorted by `original.from`.

- `toResult(pos)` maps an input position to the output. Positions inside deleted text map to the deletion point.
- `toOriginal(pos, assoc)` maps an output position to the input. Positions inside inserted text map to the insertion
  point. At a deletion, `assoc` `1` (default) maps past the deleted text, `-1` before it.

A `Patch` is one change a transform made: `original` is its range in the input, `result` its range in the output.
Deletions have an empty `result`, pure insertions an empty `original`.

### Patch

One change a transform made to a text. `original` is the range in the input,
`result` the range in the output; deletions have an empty `result`, pure
insertions an empty `original`.

| Prop       | Type     | Description                                                                                |
| ---------- | -------- | ------------------------------------------------------------------------------------------ |
| `original` | `Range`  | The changed range in the transform's input.                                                |
| `result`   | `Range`  | The range it became in the transform's output.                                             |
| `reason`   | `string` | Machine-readable cause, e.g. `"close:]"`, `"cut:incomplete-statement"`, `"lint:email-at"`. |

### `PositionMapper`

```ts
type PositionMapper = (pos: number, assoc: 1 | -1) => number;
```

Maps a position, as `SourceMap.toOriginal`, heal's `map.toInput` and `mapPosition` (curried over an edit) all do.
`assoc` says which side to stick to at a change: `1` after it, `-1` before it. `mapDiagnostic` takes one.

## Diagnostics

Problems from the compiler, the healer and the fixers all come in one shape, so nothing downstream parses
compiler-specific strings.

### `Diagnostic`

Positions are UTF-16 offsets into the document text. The engine converts Typst's UTF-8 byte spans at the wasm
boundary and undoes its own worker-side patches before reporting; the client then maps them to the raw stream through
heal's source map. `EngineDocument` states and `onDiagnostics` give you diagnostics already in input coordinates.

### Diagnostic

A problem with a document, from the compiler, the healer or a fixer.

All positions are UTF-16 offsets into the text the client sent for the
document (`document/open` + `document/edit`). Engines convert from Typst's
UTF-8 byte spans at the wasm boundary and undo their own worker-side patches
(Layer 3 fixers, injected anchors) before reporting. The client maps them on
to the raw stream through heal's source map (mapDiagnostic).

| Prop       | Type                                                  | Description                                                                                                                                                                                                                                                                                            |
| ---------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `severity` | `DiagnosticSeverity`                                  | How serious the problem is (see DiagnosticSeverity).                                                                                                                                                                                                                                                   |
| `span`     | `Range \| null`                                       | Where the problem is in the document text. When it originated in another file (preamble, package), this is the closest call site in the document (from the trace) and Diagnostic.file holds the original location. `null` when Typst attached no position the document contains (e.g. a missing font). |
| `message`  | `string`                                              | What is wrong, as one line of text (hints are in Diagnostic.hints).                                                                                                                                                                                                                                    |
| `hints`    | `string[]`                                            | Suggestions, one per entry (Typst's `hint:` lines, never folded into `message`).                                                                                                                                                                                                                       |
| `trace`    | `TraceItem[]`                                         | Call chain, innermost first. Empty when there is none.                                                                                                                                                                                                                                                 |
| `file?`    | `{ path: string; span: Range \| null; } \| undefined` | Original location when the problem is in a file other than the document.                                                                                                                                                                                                                               |
| `source?`  | `string \| undefined`                                 | Who reported it: `"typst"`, `"heal"`, a fixer name, …                                                                                                                                                                                                                                                  |
| `code?`    | `string \| undefined`                                 | Machine-readable kind when the source has one, e.g. a lint rule id. Typst has none.                                                                                                                                                                                                                    |

#### `DiagnosticSeverity`

```ts
type DiagnosticSeverity = "error" | "warning" | "info";
```

Typst itself reports only `error` and `warning`. `info` is for reports from typstream, such as an error a fixer fixed
while streaming.

#### `TraceItem`

One step of the call chain that led to a diagnostic, as Typst reports it ("error occurred in this call of function
`table`").

### TraceItem

One step of the call chain that led to a diagnostic, outermost last, as Typst
reports it ("error occurred in this call of function `table`").

| Prop      | Type            | Description                                                                              |
| --------- | --------------- | ---------------------------------------------------------------------------------------- |
| `message` | `string`        | Typst's description of the step, e.g. "error occurred in this call of function `table`". |
| `span`    | `Range \| null` | Where the step happened in the document text (UTF-16), or `null` if outside it.          |

### `formatDiagnostic`

```ts
const formatDiagnostic: (d: Diagnostic, text?: string) => string;
```

Plain text for logs and test failures: `error 3:5: unclosed delimiter`, followed by indented `hint:` lines. Pass the
document text to get one-based `line:column` instead of offsets.

### `lineColumn`

```ts
const lineColumn: (text: string, offset: number) => { line: number; column: number };
```

Zero-based line and UTF-16 column of `offset` in `text`. Lines end at `\n`.

### `mapDiagnostic`

```ts
const mapDiagnostic: (d: Diagnostic, map: PositionMapper) => Diagnostic;
```

Maps a diagnostic's document positions (`span` and trace spans; not `file`, which is in another file). Use it to carry
diagnostics from healed source to the raw stream, or across edits to a later revision. Range starts stick right and
ends stick left, so text inserted exactly at a boundary doesn't widen the range.

```ts
mapDiagnostic(d, (pos, assoc) => healed.map.toInput(pos, assoc));
mapDiagnostic(d, (pos, assoc) => mapPosition(pos, edit, assoc));
```

### `compareDiagnostics` and `normalizeDiagnostics`

```ts
const compareDiagnostics: (a: Diagnostic, b: Diagnostic) => number;
const normalizeDiagnostics: (ds: readonly Diagnostic[]) => Diagnostic[];
```

`compareDiagnostics` orders by position (diagnostics without a span last), then severity, then message: a total
order, so sorted lists compare equal across runs. `normalizeDiagnostics` sorts with it and drops repeats (same
severity, span, message, hints and file); Typst reports an error once per evaluation of a repeated call.

### `isError` and `hasErrors`

```ts
const isError: (d: Diagnostic) => boolean;
const hasErrors: (ds: readonly Diagnostic[]) => boolean;
```

Whether a diagnostic is an error, and whether a list has one.

## Plugins

One plugin contract for the whole toolkit. A plugin is a plain object with a key and optional facets; each package
reads only the facets it understands, so new facets never break old plugins. `@typstream/edu`,
`@typstream/html-compat` and `@typstream/universe` are plugins.

### `TypstreamPlugin`

Everything except `heal.handlers` and islands' `parse` is plain data. The `engine` facet is sent to the worker, which can't receive
functions, so worker-side code is referenced by module URL (`fixerModules`, `generatorModules`).

### TypstreamPlugin

A typstream plugin: a key plus any of the facets below. `@typstream/edu` is
one; so are a school's branded templates or a chemistry pack.

Everything except `heal.handlers` and islands' `parse` is plain data. The engine facet is
especially restricted because it is sent to the worker, which can't receive
functions: worker-side code is referenced by module URL (`fixerModules`).

| Prop            | Type                                                                                                                                                                                                                        | Description                                                                                                                                                                                                                                                                                                                                                                                                     |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`           | `string`                                                                                                                                                                                                                    | Unique, namespaced for third parties: `"edu"`, `"acme/chemistry"`.                                                                                                                                                                                                                                                                                                                                              |
| `version?`      | `string \| undefined`                                                                                                                                                                                                       | The plugin's version, e.g. its Typst package's. Informational: nothing in typstream reads it.                                                                                                                                                                                                                                                                                                                   |
| `dependencies?` | `string[] \| undefined`                                                                                                                                                                                                     | Keys of plugins that must be loaded too, before this one.                                                                                                                                                                                                                                                                                                                                                       |
| `heal?`         | `{ handlers?: HealHandler[]; lint?: Record<string, LintSetting \| boolean>; } \| undefined`                                                                                                                                 | Language (`@typstream/heal`).                                                                                                                                                                                                                                                                                                                                                                                   |
| `engine?`       | `{ fixerModules?: string[]; generatorModules?: string[]; files?: Record<string, string \| Uint8Array>; packages?: PackageSpec[]; fonts?: FontSource[]; fontCatalogues?: FontCatalogue[]; preamble?: string; } \| undefined` | Runtime (`@typstream/engine`, worker side).                                                                                                                                                                                                                                                                                                                                                                     |
| `templates?`    | `TemplateSpec[] \| undefined`                                                                                                                                                                                               | Content.                                                                                                                                                                                                                                                                                                                                                                                                        |
| `prompt?`       | `{ catalogue?: FunctionDoc[]; rules?: string[]; examples?: PromptExample[]; } \| undefined`                                                                                                                                 | Prompt kit: what the model is told about this plugin's Typst API.                                                                                                                                                                                                                                                                                                                                               |
| `islands?`      | `Record<string, IslandSpec<unknown>> \| undefined`                                                                                                                                                                          | Rendering. Islands by name.                                                                                                                                                                                                                                                                                                                                                                                     |
| `sanitize?`     | `{ allowTags?: string[]; allowAttrs?: Record<string, string[]>; allowClasses?: string[]; } \| undefined`                                                                                                                    | Extra tags, attributes (by tag, `"*"` for every HTML element) and classes the sanitizer lets through. Event handlers and loading attributes stay blocked, `"*"` can't allow `href` or `src`, and SVG and MathML keep their own lists. The HTML renderer drops every other class, so a document can't take on the page's own (#69): list the ones this plugin's Typst writes, by name or as a prefix (`"ts-*"`). |
| `stylesheets?`  | `string[] \| undefined`                                                                                                                                                                                                     | CSS for the HTML this plugin's Typst writes, added to the HTML renderer and to standalone HTML exports, after earlier plugins' and before the app's own.                                                                                                                                                                                                                                                        |
| `editor?`       | `EditorFacet \| undefined`                                                                                                                                                                                                  | Editor (future).                                                                                                                                                                                                                                                                                                                                                                                                |

| Facet | Read by | What it holds |
| --- | --- | --- |
| `heal` | `@typstream/heal` | Heal handlers, and overrides of built-in lint rules by id (`{ "currency-dollar": "fix" }`). |
| `engine` | `@typstream/engine` | Fixer and file generator (beta) module URLs, files (such as a local Typst package), allowed packages and fonts (beta), and a preamble. |
| `templates` | `mountTypstream` (`template` option) | Named document setups: a preamble and default `sys.inputs`. |
| `prompt` | Prompt builders (`@typstream/edu`'s `buildSystemPrompt`) | A function catalogue, rules and few-shot examples for the model. |
| `sanitize` | The HTML renderer | Extra tags, attributes (by tag, `"*"` for every HTML element) and classes to let through. |
| `stylesheets` | The HTML renderer, `standaloneHtml` | CSS for the HTML this plugin's Typst writes. |
| `islands` | The HTML renderer, `@typstream/react` | Render islands by name (beta): which island markers mount, and `parse`, which checks their data. See [Writing an island](/docs/guides/islands). |
| `editor` | Nothing yet | Reserved (beta) for the visual editor. |

A plugin's `engine.fonts` load only from `createEngine`'s `plugins`, since fonts belong to the worker; their other
facets apply to the documents that list them.

### `definePlugin`

```ts
const definePlugin: <P extends TypstreamPlugin>(plugin: P) => P;
```

Identity function that type-checks a plugin while keeping its literal type.

### `resolvePlugins`

```ts
const resolvePlugins: <P extends TypstreamPlugin>(plugins: readonly P[]) => P[];
```

The plugins to load, in the order their facets apply: each key once, and every plugin after the plugins it depends
on. The engine calls it when a document opens (`EngineDocument.plugins` is the result).

- A key given more than once is loaded once, as its last definition, at the place of its first (a provider's plugin
  overridden by a component's).
- Otherwise plugins keep the order they were given in; a dependency given later moves up to just before the first
  plugin that needs it.
- A dependency that isn't among `plugins`, a cycle of dependencies, or a plugin without a key throws.

### `HealHandler`

The extension point of `@typstream/heal`: product-specific fixes, run alongside the built-in lint rules (phase
`settled`, on text whose parse can no longer change) or on the final healed source (phase `output`). Returned edits
are against `ctx.text`, non-overlapping, inside `[ctx.from, ctx.to)`.

### HealHandler

Extension point of `@typstream/heal` (PLAN §8.1): product-specific fixes,
run alongside the built-in lint rules (`settled`, on text whose parse can no
longer change) or on the final healed source (`output`). Returned edits are
against `ctx.text`, non-overlapping, inside `[ctx.from, ctx.to)`.

| Prop        | Type                                      | Description                                                                                                                             |
| ----------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `name`      | `string`                                  | Identifies the handler. A `settled` handler's edits are reported as lint findings with this as their rule (patch reason `lint:<name>`). |
| `priority?` | `number \| undefined`                     | Lower runs first; the default is 100. The built-in lint rules run before every handler.                                                 |
| `phase`     | `"output" \| "settled"`                   | When it runs: `settled` on newly settled normalized text, like the lint rules; `output` on the whole healed source, after tail repair.  |
| `run`       | `(ctx: HealHandlerContext) => TextEdit[]` | The handler's edits to `ctx.text` (see above), or `[]` when it has none.                                                                |

#### `HealHandlerContext`

### HealHandlerContext

What a HealHandler sees.

| Prop     | Type                          | Description                                                                         |
| -------- | ----------------------------- | ----------------------------------------------------------------------------------- |
| `text`   | `string`                      | Normalized text (`settled`) or healed source (`output`).                            |
| `from`   | `number`                      | Range the handler may change (`settled`: newly settled text; `output`: everything). |
| `to`     | `number`                      | End of that range (exclusive).                                                      |
| `final`  | `boolean`                     | The document is complete (no tail repair runs).                                     |
| `modeAt` | `(pos: number) => SyntaxMode` | Lexical mode at a position (`settled` only; `output` handlers get `markup`).        |

#### `SyntaxMode`

```ts
type SyntaxMode = "markup" | "math" | "code" | "raw" | "comment";
```

Typst's lexical modes, plus the inside of raw blocks and comments, which handlers almost always need to leave alone.

#### `LintSetting`

```ts
type LintSetting = "fix" | "warn" | "off";
```

`fix` applies a lint rule's change, `warn` only reports it.

### `DiagnosticFixer`

Turns a compile error into edits that should make it go away; the worker applies them and recompiles, at most twice
per revision. For each error, fixers are tried in priority order and the first that returns edits fixes it. A round is
applied only when every error has a fix. Fixers run in the worker, so plugins ship them as ES modules
(`engine.fixerModules`) whose default export is a fixer or an array of them. Fixed compiles import typstream's runtime
library as `typstream`, so fixes can insert placeholders such as `#typstream.pending-ref("key");`.

### DiagnosticFixer

Layer 3 of healing (PLAN §5.5, §8.2): turns a compile error into edits that
should make it go away; the worker applies them and recompiles, at most twice
per revision. For each error, fixers are tried in priority order and the
first that returns edits fixes it. A round is applied only when every error
has a fix, since one left over fails the recompile anyway. Fixers run in the
worker, so plugins ship them as ES modules (`engine.fixerModules`) whose
default export is a fixer or an array of them.

Fixed compiles import typstream's runtime library as `typstream`
(`/@typstream/runtime.typ`), so fixes can insert placeholders such as
`#typstream.pending-ref("key");`.

| Prop        | Type                                                                                    | Description                                                                                                                                                                               |
| ----------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`      | `string`                                                                                | Unique. Reported as the `source` of the errors it fixed while streaming.                                                                                                                  |
| `priority?` | `number \| undefined`                                                                   | Lower runs first. Default 50; the built-in `pending-ref` runs at 10 and the catch-all `tail-cut` at 100.                                                                                  |
| `modes?`    | `readonly CompileMode[] \| undefined`                                                   | Compiles it runs in. Default: both.                                                                                                                                                       |
| `match?`    | `RegExp \| ((d: Diagnostic) => boolean) \| undefined`                                   | Errors it is tried on: a test of the message, or of the whole diagnostic. Default: every error.                                                                                           |
| `fix`       | `(d: Diagnostic, ctx: FixContext) => TextEdit[] \| null \| Promise<TextEdit[] \| null>` | Edits to `ctx.text` (non-overlapping, ascending) that should make `d` go away, or `null` when it can't fix it. May be async, e.g. to fetch a font or a package; the compile waits for it. |

```ts title="acme-fixers.js"
export default {
  name: "acme/old-macro",
  match: /^unknown variable: oldbox$/,
  fix: (d, { text }) => [{ from: d.span.from, to: d.span.to, insert: "box" }],
};
```

#### `FixContext`

### FixContext

What a DiagnosticFixer sees.

| Prop          | Type                    | Description                                                                                                                                                                                                         |
| ------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `text`        | `string`                | The document text that was compiled, without its preamble: the client's text in the first round, with earlier rounds' fixes after that.                                                                             |
| `settled`     | `number`                | Text before this offset is settled: streaming more can't change it. Fixes that drop or rewrite text still being typed belong after it. It is the end of the text in final compiles, and when the client didn't say. |
| `settledFrom` | `number`                | Text from this offset on is settled too: what is being typed is `[settled, settledFrom)`, a range streaming into the middle of the document (an edit). The end of the text otherwise. Fixes belong before it.       |
| `mode`        | `CompileMode`           | The compile's mode: fixers can stay out of final compiles with DiagnosticFixer.modes.                                                                                                                               |
| `round`       | `number`                | 0 for the client's text; 1 and 2 for recompiles after fixes.                                                                                                                                                        |
| `errors`      | `readonly Diagnostic[]` | Every error of the compile, the one being fixed included.                                                                                                                                                           |

### `FileGenerator`

Beta. Files a plugin makes from a document's source in the worker, before every compile and export: what Typst can't
compute itself, such as a diagram drawn by a JavaScript library (`@typstream/mermaid`'s), for the plugin's Typst to
read. Plugins ship them as ES modules (`engine.generatorModules`) whose default export is a generator or an array of
them; each document gets its own `DocumentFileGenerator` from `open()`. The worker writes only the files that changed
since the last run and removes those no longer returned, so returning the same files costs Typst nothing. A server
facing untrusted clients imports none of theirs (`ServerOptions.clientFixers: false`) but can run its own
(`ServerOptions.generators`).

### FileGenerator

Files a plugin makes from a document's source in the worker, before every
compile and export (PLAN §8.2): what Typst can't compute itself, such as a
diagram drawn by a JavaScript library, for the plugin's Typst to read. Like
fixers, generators run in the worker, so plugins ship them as ES modules
(`engine.generatorModules`) whose default export is a generator or an array
of them. A server facing untrusted clients imports none of theirs.

| Prop   | Type                          | Description                                                                      |
| ------ | ----------------------------- | -------------------------------------------------------------------------------- |
| `name` | `string`                      | Unique. Names it in the worker's logs.                                           |
| `open` | `() => DocumentFileGenerator` | A generator for one document, which may keep what it made for the next revision. |

#### `DocumentFileGenerator`

### DocumentFileGenerator

A FileGenerator's work for one document.

| Prop     | Type                                                                                                                   | Description                                                                                                                                                                                                                                                                                                                                                                                         |
| -------- | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `files`  | `(source: string, ctx: { mode: CompileMode; }) => Record<string, FileContent> \| Promise<Record<string, FileContent>>` | Every file it provides for `source` (the document's preamble and text), keyed by path as in `document/setFiles`. The worker writes what changed since the last call and removes what is no longer listed, so a generator can return the same value again cheaply: it runs before every compile, once per streamed token. May be async (to load a library the first time); the compile waits for it. |
| `close?` | `(() => void) \| undefined`                                                                                            | The document closed.                                                                                                                                                                                                                                                                                                                                                                                |

```ts title="acme-generator.js"
export default {
  name: "acme/word-count",
  open: () => ({
    // Runs before every compile, once per streamed token: keep it fast.
    files: (source) => ({ "acme/count.typ": `#let words = ${source.split(/\s+/).length}` }),
  }),
};
```

### `TemplateSpec`

A named document setup: page, fonts, header. Select one with the `template` option.

### TemplateSpec

A named document setup: page, fonts, header (PLAN §8.3).

| Prop           | Type                                  | Description                                                        |
| -------------- | ------------------------------------- | ------------------------------------------------------------------ |
| `name`         | `string`                              | Unique among templates, e.g. `"worksheet"`.                        |
| `title?`       | `string \| undefined`                 | Human-readable name, e.g. for a template picker: `"Worksheet"`.    |
| `description?` | `string \| undefined`                 | One line on what the template sets up, e.g. for a template picker. |
| `preamble`     | `string`                              | Typst evaluated before the document.                               |
| `inputs?`      | `Record<string, string> \| undefined` | Default `sys.inputs` the template understands.                     |

### `FunctionDoc` and `PromptExample`

What a plugin's `prompt` facet holds: the catalogue of its Typst functions (generated from doc comments, for
`@typstream/edu`) and few-shot examples. See [Prompting](/docs/guides/prompting).

### FunctionDoc

One Typst function in the prompt catalogue, generated from the package's doc comments.

| Prop          | Type                  | Description                                                            |
| ------------- | --------------------- | ---------------------------------------------------------------------- |
| `name`        | `string`              | The function's name as documents call it, e.g. `question`.             |
| `signature`   | `string`              | E.g. `question(points: int, body: content) -> content`.                |
| `description` | `string`              | What the function does and how to call it: its doc comment's prose.    |
| `example?`    | `string \| undefined` | Typst that calls the function, from the doc comment's `example` block. |

### PromptExample

A few-shot example for the system prompt.

| Prop       | Type                  | Description                                                               |
| ---------- | --------------------- | ------------------------------------------------------------------------- |
| `title?`   | `string \| undefined` | A label for the example (edu uses its file name). Not part of the prompt. |
| `request?` | `string \| undefined` | What the user asked for.                                                  |
| `output`   | `string`              | The Typst the model should write.                                         |

### `PackageSpec`, `FontSource` and font catalogues (beta)

<Callout type="warn" title="Beta">
`PackageSpec`, `FontSource`, the font catalogue types, `IslandSpec` and `EditorFacet` are beta and may change before
the first stable release.
</Callout>

A `PackageSpec` is an entry of the engine's package allowlist (`#import "@preview/cetz:0.5.3"`). The engine fetches it
only when a document imports it. Without `url`, the server resolves it from its configured registry, if it has one.

### PackageSpec

A Typst package the engine may load (`#import "@preview/cetz:0.5.3"`): an
entry of its allowlist (PLAN §6.4). The engine fetches it only when a
document imports it. A document asking for another version of an allowed
package gets the nearest allowed one, with a warning. Without `url`, the
server resolves it from its configured registry, if it has one.
`@typstream/universe` lists the packages typstream vendors.

| Prop         | Type                             | Description                                                                                                                                                                                                                                                          |
| ------------ | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `namespace`  | `string`                         | `preview` for Typst Universe packages.                                                                                                                                                                                                                               |
| `name`       | `string`                         | The package's name, e.g. `cetz`.                                                                                                                                                                                                                                     |
| `version`    | `string`                         | `major.minor.patch`.                                                                                                                                                                                                                                                 |
| `url?`       | `string \| undefined`            | Where to fetch the `.tar.gz` from, as packages.typst.org serves it.                                                                                                                                                                                                  |
| `integrity?` | `string \| undefined`            | Subresource-integrity hash (`sha256-…`, `sha384-…` or `sha512-…`), checked before use: of the `.tar.gz` as fetched, or of the `.tar` inside it. Prefer the tar's: servers often send `.gz` files with `Content-Encoding: gzip`, and browsers then hand over the tar. |
| `imports?`   | `readonly string[] \| undefined` | The packages its sources import (`@preview/oxifmt:1.0.0`), requested with it rather than found once it is unpacked, so they download at the same time. Optional: the engine finds them anyway.                                                                       |

A `FontSource` is a font for the engine: a URL the worker fetches, or the bytes. A URL with `info` is a lazy font,
registered from `info` and downloaded only when a document uses it. See
[Fonts and languages](/docs/guides/fonts-and-languages).

```ts
type FontSource = ({ kind: "url"; url: string } | { kind: "bytes"; data: Uint8Array }) & {
  family?: string;
  scripts?: string[]; // ISO 15924 codes the font is for, e.g. ["Beng"]
  info?: string; // the engine's metadata for the file's faces
};
```

A `FontCatalogue` (`{ index, maxBytes? }`, a plugin's `engine.fontCatalogues`) is an index of fonts the engine loads
by family, only when a document names one it doesn't have; `@typstream/google-fonts` is one. The index is a
`FontCatalogueIndex` served as JSON: its `families`, keyed by name lowercased, are `FontCatalogueFamily` entries
(`{ name, files }`), each file a `FontCatalogueFile` (`{ path, style, weight, bytes? }`, TTF or OTF). A family the
engine loaded is announced as a `LoadedFontFamily`, with the files' absolute URLs, so the HTML renderer can show it
with the same files. See [A catalogue of your own](/docs/guides/fonts-and-languages#a-catalogue-of-your-own).

### FontCatalogueIndex

The index of a FontCatalogue, served as JSON.

| Prop       | Type                                  | Description                                                               |
| ---------- | ------------------------------------- | ------------------------------------------------------------------------- |
| `version`  | `1`                                   | The format's version.                                                     |
| `base`     | `string`                              | The URL files' paths are relative to; itself relative to the index's URL. |
| `families` | `Record<string, FontCatalogueFamily>` | By family name lowercased, which is how Typst compares family names.      |

### LoadedFontFamily

A family the engine loaded from a font catalogue: what the HTML target needs
to show it with the same files, as web fonts. Typst draws the paged target
itself.

| Prop     | Type                                       | Description                                                       |
| -------- | ------------------------------------------ | ----------------------------------------------------------------- |
| `family` | `string`                                   | The family as documents name it, lowercased (Typst's comparison). |
| `name`   | `string`                                   | The family's name, as its font files name it.                     |
| `files`  | `(FontCatalogueFile & { url: string; })[]` | The files loaded, with absolute URLs.                             |

`EditorFacet` is reserved for the visual editor: typed loosely on purpose, and nothing reads it yet.

### Render islands (beta)

A render island is an interactive component mounted over a marker a document's Typst writes around its fallback
drawing ([Writing an island](/docs/guides/islands)). `ISLAND_MARKER` (`"typstream-island"`) names the marker: the
element the HTML target writes, and the label of the paged target's `metadata`. A plugin declares an island with an
`IslandSpec`; its component gets `IslandProps`.

### IslandSpec

An interactive component that renderers mount over a Typst marker (PLAN
§8.4). The marker wraps its own fallback, the Typst drawing, which is what
prints, exports and shows wherever nothing mounts. Framework-neutral: apps
register a renderer for the name (`@typstream/dom`'s `islands` option,
`@typstream/react`'s `islands` prop); a marker becomes an island only when a
loaded plugin declares its name and the app registered a renderer for it.

| Prop           | Type                                                  | Description                                                                                                                                                                                                                                                     |
| -------------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `description?` | `string \| undefined`                                 | What the island shows or lets the reader do, for people and tools reading the plugin.                                                                                                                                                                           |
| `parse?`       | `((data: unknown) => Data \| undefined) \| undefined` | Checks the marker's data, which the document wrote and is untrusted (parsed JSON in the HTML target, a Typst value in the paged one), and returns what the renderer gets as `data`. `undefined` keeps the fallback. Without it, the data is passed on as it is. |

### IslandProps

What an island's renderer gets: everything comes from the marker, except
`isIncomplete` and `file`, which come from the document.

| Prop           | Type                                    | Description                                                                                                                                                                                                      |
| -------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`         | `string`                                | The island's name, a key of a plugin's `islands`.                                                                                                                                                                |
| `data`         | `Data`                                  | The marker's data, through the spec's `parse`.                                                                                                                                                                   |
| `isIncomplete` | `boolean`                               | The document is streaming and the island's source is still being written: it starts at or after the stable offset, so text that can change it is still arriving.                                                 |
| `target`       | `CompileTarget`                         | The target the island is shown in.                                                                                                                                                                               |
| `index`        | `number`                                | The island's position among the document's islands of its name, from 0: its identity, which a renderer keeps across updates.                                                                                     |
| `file`         | `(path: string) => FileContent \| null` | A file the document has, by the path its Typst names it with: its own files and the images its `resolveImage` resolved (the bytes Typst drew). `null` for anything else; islands fetch nothing a document names. |

## Telemetry events

The library sends nothing anywhere: the engine client emits these per document, the renderers add what they drew, and
the app decides what to log or collect. Every field is plain data, so an event can be serialized as it is. You receive
them from `EngineDocument.onEvent`, `Engine.onEvent` (wrapped as `{ type: "document", event }`), and the `onRendered`,
`onFallback` and `onWatchdog` callbacks. See [Telemetry](/docs/guides/telemetry).

### `DocumentEvent`

```ts
type DocumentEvent = CompiledEvent | FallbackEvent | WatchdogEvent | DiagnosticsEvent;
```

Everything a document reports. For one compile: `diagnostics`, then `compiled`, then `fallback` if it fell back. A
watchdog stop reports `watchdog` instead.

### `DocumentEventBase`

What every document event says about the compile it is about.

### DocumentEventBase

What every document event says about the compile it is about.

| Prop     | Type            | Description                                                                                     |
| -------- | --------------- | ----------------------------------------------------------------------------------------------- |
| `uri`    | `string`        | The document's URI, which tells documents apart in `Engine.onEvent`.                            |
| `rev`    | `number`        | Revision compiled. Revisions count the worker's copies of the document, not the input's chunks. |
| `target` | `CompileTarget` | The target compiled to.                                                                         |
| `mode`   | `CompileMode`   | `final` once the input is complete (`finish()`).                                                |

### `CompileReport`

What a compile cost and what it took to make the text compile: the fields `compiled` and `rendered` events share.

### CompileReport

What a compile cost and what it took to make the text compile: the fields
`compiled` and `rendered` events share.

| Prop            | Type                     | Description                                                                                                                     |
| --------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| `timings`       | `CompileTimings`         | The worker's timings (`totalMs`: request to response).                                                                          |
| `compileMs`     | `number`                 | Typst's compilation, summed over fixer rounds and fallback compiles (`timings.compileMs`, 0 when absent).                       |
| `healMs`        | `number`                 | Main-thread time healing the input since the previous compile, ms: every push and edit that led to the compiled source, summed. |
| `patches`       | `number`                 | Heal patches (lint fixes, tail repair, output handlers) in the compiled source.                                                 |
| `patchReasons`  | `Record<string, number>` | The same patches counted by their reason (`"close:]"`, `"lint:email-at"`, …).                                                   |
| `fixersApplied` | `AppliedFix[]`           | Errors Layer 3's fixers fixed to make the output, in the order fixed (PLAN §5.5).                                               |
| `fallbackLevel` | `FallbackLevel`          | See FallbackLevel.                                                                                                              |
| `errors`        | `number`                 | Errors and warnings of the compile, in the document.                                                                            |
| `warnings`      | `number`                 | Warnings of the compile, counted as `errors` is.                                                                                |
| `pages?`        | `number \| undefined`    | Paged: the document's page count, when the compile published pages.                                                             |
| `sourceLength`  | `number`                 | Length of the compiled source (UTF-16), for latency by document size.                                                           |

### `CompiledEvent`

A compile finished, whether or not it published an artifact (`status`). Probe compiles of a hang search aren't
reported; the `watchdog` events that started the search are.

### CompiledEvent

A compile finished, whether or not it published an artifact. Probe compiles
of a hang search (PLAN §5.6) aren't reported; the `watchdog` events that
started the search are.

| Prop            | Type                     | Description                                                                                                                     |
| --------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| `type`          | `"compiled"`             | Discriminant: a compile finished.                                                                                               |
| `status`        | `"error" \| "ok"`        | `ok`: it published an artifact (perhaps from the fallback); `error`: the last good one stays.                                   |
| `uri`           | `string`                 | The document's URI, which tells documents apart in `Engine.onEvent`.                                                            |
| `rev`           | `number`                 | Revision compiled. Revisions count the worker's copies of the document, not the input's chunks.                                 |
| `target`        | `CompileTarget`          | The target compiled to.                                                                                                         |
| `mode`          | `CompileMode`            | `final` once the input is complete (`finish()`).                                                                                |
| `timings`       | `CompileTimings`         | The worker's timings (`totalMs`: request to response).                                                                          |
| `compileMs`     | `number`                 | Typst's compilation, summed over fixer rounds and fallback compiles (`timings.compileMs`, 0 when absent).                       |
| `healMs`        | `number`                 | Main-thread time healing the input since the previous compile, ms: every push and edit that led to the compiled source, summed. |
| `patches`       | `number`                 | Heal patches (lint fixes, tail repair, output handlers) in the compiled source.                                                 |
| `patchReasons`  | `Record<string, number>` | The same patches counted by their reason (`"close:]"`, `"lint:email-at"`, …).                                                   |
| `fixersApplied` | `AppliedFix[]`           | Errors Layer 3's fixers fixed to make the output, in the order fixed (PLAN §5.5).                                               |
| `fallbackLevel` | `FallbackLevel`          | See FallbackLevel.                                                                                                              |
| `errors`        | `number`                 | Errors and warnings of the compile, in the document.                                                                            |
| `warnings`      | `number`                 | Warnings of the compile, counted as `errors` is.                                                                                |
| `pages?`        | `number \| undefined`    | Paged: the document's page count, when the compile published pages.                                                             |
| `sourceLength`  | `number`                 | Length of the compiled source (UTF-16), for latency by document size.                                                           |

### `RenderedEvent`

The renderer showed an artifact: the report of the compile that made it, and what drawing it cost. What `onRendered`
receives.

### RenderedEvent

The renderer showed an artifact: the report of the compile that made it,
and what drawing it cost. What `onRendered` hooks receive.

| Prop            | Type                     | Description                                                                                                                     |
| --------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| `type`          | `"rendered"`             | Discriminant: the renderer showed an artifact.                                                                                  |
| `renderMs`      | `number`                 | Main-thread time handing the artifact to the renderer, ms (paged: offscreen pages draw later).                                  |
| `blocks?`       | `number \| undefined`    | HTML: top-level blocks shown.                                                                                                   |
| `uri`           | `string`                 | The document's URI, which tells documents apart in `Engine.onEvent`.                                                            |
| `rev`           | `number`                 | Revision compiled. Revisions count the worker's copies of the document, not the input's chunks.                                 |
| `target`        | `CompileTarget`          | The target compiled to.                                                                                                         |
| `mode`          | `CompileMode`            | `final` once the input is complete (`finish()`).                                                                                |
| `timings`       | `CompileTimings`         | The worker's timings (`totalMs`: request to response).                                                                          |
| `compileMs`     | `number`                 | Typst's compilation, summed over fixer rounds and fallback compiles (`timings.compileMs`, 0 when absent).                       |
| `healMs`        | `number`                 | Main-thread time healing the input since the previous compile, ms: every push and edit that led to the compiled source, summed. |
| `patches`       | `number`                 | Heal patches (lint fixes, tail repair, output handlers) in the compiled source.                                                 |
| `patchReasons`  | `Record<string, number>` | The same patches counted by their reason (`"close:]"`, `"lint:email-at"`, …).                                                   |
| `fixersApplied` | `AppliedFix[]`           | Errors Layer 3's fixers fixed to make the output, in the order fixed (PLAN §5.5).                                               |
| `fallbackLevel` | `FallbackLevel`          | See FallbackLevel.                                                                                                              |
| `errors`        | `number`                 | Errors and warnings of the compile, in the document.                                                                            |
| `warnings`      | `number`                 | Warnings of the compile, counted as `errors` is.                                                                                |
| `pages?`        | `number \| undefined`    | Paged: the document's page count, when the compile published pages.                                                             |
| `sourceLength`  | `number`                 | Length of the compiled source (UTF-16), for latency by document size.                                                           |

### `FallbackEvent`

The document's output isn't its text as it is: a candidate test case. Fired with every such compile, so a lasting
error in a stream fires once per revision; `consecutive` tells a new failure from a lasting one.

### FallbackEvent

The document's output isn't its text as it is (levels 1 to 4 of
FallbackLevel): a candidate corpus case (PLAN §11.2). Fired with
every such compile, so a lasting error in a stream fires once per revision;
`consecutive` tells a new failure from a lasting one.

| Prop          | Type               | Description                                                                                                                                                                                    |
| ------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type`        | `"fallback"`       | Discriminant: the output isn't the text as it is.                                                                                                                                              |
| `level`       | `1 \| 2 \| 3 \| 4` | The step of the ladder the output came from (see FallbackLevel).                                                                                                                               |
| `isolated`    | `Range[]`          | Ranges of the compiled source shown as error boxes (levels 3 and 4).                                                                                                                           |
| `plainFrom`   | `number \| null`   | Level 2: the compiled source from here on was shown as plain text.                                                                                                                             |
| `consecutive` | `number`           | Compiles in a row, this one included, whose output wasn't the text as it is.                                                                                                                   |
| `diagnostics` | `Diagnostic[]`     | The compile's diagnostics (input coordinates): the errors that failed it, or that the error boxes stand for; under the stable prefix, the tail's errors as `info` (`source: "stable-prefix"`). |
| `input`       | `string`           | The input the compiled source was healed from: what to replay to reproduce it.                                                                                                                 |
| `source`      | `string`           | The healed source the worker compiled. Ranges above are in it.                                                                                                                                 |
| `uri`         | `string`           | The document's URI, which tells documents apart in `Engine.onEvent`.                                                                                                                           |
| `rev`         | `number`           | Revision compiled. Revisions count the worker's copies of the document, not the input's chunks.                                                                                                |
| `target`      | `CompileTarget`    | The target compiled to.                                                                                                                                                                        |
| `mode`        | `CompileMode`      | `final` once the input is complete (`finish()`).                                                                                                                                               |

### `FallbackLevel`

```ts
type FallbackLevel = 0 | 1 | 2 | 3 | 4;
```

| Level | Output |
| --- | --- |
| `0` | The text itself (healed, and fixed by the worker's fixers if it needed it). |
| `1` | The compile failed; the last good artifact stays. |
| `2` | The settled text, with the unsettled tail as plain text (streaming). |
| `3` | Failing or hanging blocks shown as error boxes. |
| `4` | Nothing compiled: the whole document shown as its source (final mode). |

See [Fallback](/docs/concepts/fallback).

### `WatchdogEvent`

A compile of the document ran past its budget or crashed the worker, which was replaced.

### WatchdogEvent

A compile of the document ran past its budget or crashed the worker, which
was replaced (PLAN §6.3).

| Prop           | Type                   | Description                                                                                                          |
| -------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `type`         | `"watchdog"`           | Discriminant: the watchdog replaced the worker.                                                                      |
| `reason`       | `"crash" \| "timeout"` | The compile ran past `budgetMs` (`timeout`), or the worker died during it (`crash`).                                 |
| `budgetMs`     | `number`               | The compile's budget, ms.                                                                                            |
| `strikes`      | `number`               | Streaming timeouts and crashes so far; at the engine's limit live compiling stops.                                   |
| `live`         | `boolean`              | False once live compiling stopped (`too-complex`); the document compiles again when finished.                        |
| `searching`    | `boolean`              | Final mode: the engine is looking for the blocks that hang or crash it, to skip them, rather than counting a strike. |
| `sourceLength` | `number`               | Length of the compiled source (UTF-16).                                                                              |
| `uri`          | `string`               | The document's URI, which tells documents apart in `Engine.onEvent`.                                                 |
| `rev`          | `number`               | Revision compiled. Revisions count the worker's copies of the document, not the input's chunks.                      |
| `target`       | `CompileTarget`        | The target compiled to.                                                                                              |
| `mode`         | `CompileMode`          | `final` once the input is complete (`finish()`).                                                                     |

### `DiagnosticsEvent`

A compile replaced the document's diagnostics (in input coordinates, sorted). Fired with every compile that reports,
even when they didn't change.

### DiagnosticsEvent

A compile replaced the document's diagnostics (in input coordinates,
sorted). Fired with every compile that reports, even when they didn't change.

| Prop          | Type            | Description                                                                                     |
| ------------- | --------------- | ----------------------------------------------------------------------------------------------- |
| `type`        | `"diagnostics"` | Discriminant: the document's diagnostics were replaced.                                         |
| `diagnostics` | `Diagnostic[]`  | The new set, in input coordinates and sorted; empty when the compile reported none.             |
| `uri`         | `string`        | The document's URI, which tells documents apart in `Engine.onEvent`.                            |
| `rev`         | `number`        | Revision compiled. Revisions count the worker's copies of the document, not the input's chunks. |
| `target`      | `CompileTarget` | The target compiled to.                                                                         |
| `mode`        | `CompileMode`   | `final` once the input is complete (`finish()`).                                                |

### `AppliedFix`

An error a diagnostic fixer fixed to make a compile's output, as listed in `fixersApplied`.

### AppliedFix

An error a diagnostic fixer (Layer 3, PLAN §5.5) fixed to make a compile's
output, for telemetry ("fixer hits by error", PLAN §12).

| Prop      | Type     | Description                                |
| --------- | -------- | ------------------------------------------ |
| `fixer`   | `string` | The fixer's `name`.                        |
| `message` | `string` | The error's message, as Typst reported it. |

## Protocol

The engine client and its worker talk in LSP-shaped messages: `{ id, method, params }` requests answered by
`{ id, result }` or `{ id, error }`, plus `{ method, params }` notifications. Messages are plain structured-clonable
data, so they cross `postMessage` as they are, and a socket as JSON through `serializeMessage`. You need these types
only to write a transport, a server or an adapter; see [Remote engine](/docs/guides/remote-engine).

The lifecycle: `initialize` first, then any number of documents, each opened, edited, compiled and closed
independently; `shutdown` last. Documents share the worker's fonts, packages and Typst's memoization cache. Every
document-scoped message carries the document's `uri` and a `rev` (revision) the client chooses, increasing with every
change, so stale output can be dropped.

### `PROTOCOL_VERSION`

```ts
const PROTOCOL_VERSION = 1;
```

Bumped only for breaking changes. Additive changes (new methods, new optional fields) are announced through
capabilities instead. A server that doesn't speak the client's version answers `initialize` with a
`protocol-version-mismatch` error whose `data` is `VersionMismatchData` (`{ supported: number[] }`).

### Requests

`RequestMap` maps every request method to its params and result:

| Method | Params | Result |
| --- | --- | --- |
| `initialize` | `InitializeParams` | `InitializeResult` |
| `shutdown` | `null` | `null` |
| `document/open` | `DocumentOpenParams` | `null` |
| `document/edit` | `DocumentEditParams` | `null` |
| `document/setFiles` | `DocumentSetFilesParams` | `null` |
| `document/close` | `DocumentCloseParams` | `null` |
| `compile` | `CompileParams` | `CompileResult` |
| `export/pdf` | `ExportParams` | `ExportResult<Uint8Array>` |
| `export/html` | `ExportParams` | `ExportResult<string>` |
| `resolve/span` (beta) | `ResolveSpanParams` | `ResolveSpanResult` |
| `resolve/location` (beta) | `ResolveLocationParams` | `ResolveLocationResult` |

A compile's output arrives as notifications sent before its response: `document/diagnostics` always, then
`document/artifact` when the compile succeeded. The same notifications carry compiles the server starts itself, such
as when a lazily loaded font arrives.

Notifications:

| Direction | Method | Params |
| --- | --- | --- |
| Client to server | `$/cancel` | `CancelParams` (`{ id }`): drop a request that hasn't started. |
| Server to client | `document/diagnostics` | `DiagnosticsNotification`: the complete set for one compile, replacing earlier ones. |
| Server to client | `document/artifact` | `ArtifactNotification`: a successful compile's `artifact`. |
| Server to client | `fonts/loaded` | `FontsLoadedParams` (beta, a `LoadedFontFamily`): a family loaded from a font catalogue, sent once per family and worker. |
| Server to client | `$/log` | `LogParams` (`{ level, message }`): debugging only, never user-facing. |

Helper types: `RequestMethod`, `ClientNotificationMethod` and `ServerNotificationMethod` (the method names),
`ParamsOf<M>` and `ResultOf<M>`, `RequestId` (a number unique among pending requests), `Request<M>`,
`ClientNotification<M>`, `ServerNotification<M>`, `SuccessResponse<M>`, `ErrorResponse`, `Response<M>`, and the unions
`ClientMessage` (what the client posts) and `ServerMessage` (what the worker posts). `RequestMap`,
`ClientNotificationMap` and `ServerNotificationMap` are the tables they derive from. The guards `isRequest`,
`isClientNotification`, `isResponse`, `isServerNotification` and `isErrorResponse` tell messages apart.

### `initialize`

`InitializeParams` holds the client's `protocolVersion`, its `ClientCapabilities` (`pagedDiff`: it can apply
changed-page updates), optional `clientInfo`, and `options` (beta `InitializeOptions`: `fonts`, `packages` and
`fixerModules` shared by every document).

### InitializeResult

On a version the server doesn't speak, it answers with a
`protocol-version-mismatch` error whose `data` is VersionMismatchData.

| Prop              | Type                                                        | Description                                                                      |
| ----------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `protocolVersion` | `number`                                                    | The server's PROTOCOL_VERSION: the client's, since any other fails `initialize`. |
| `capabilities`    | `ServerCapabilities`                                        | What the server offers; clients use only what is listed.                         |
| `serverInfo`      | `{ name: string; version?: string; typstVersion: string; }` | Which engine answered, for logs and bug reports.                                 |

### ServerCapabilities

What the server offers. Clients must treat a missing field as unsupported,
so later protocol versions can add editor services (`completion`, `hover`,
`definition`, `signatureHelp`, `format`, `foldingRanges`) as new flags
without a version bump.

| Prop               | Type                                   | Description                                                                                            |
| ------------------ | -------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `targets`          | `CompileTarget[]`                      | The targets it compiles to; `compile` to another answers `unsupported`.                                |
| `exports`          | `ExportFormat[]`                       | The export formats it serves; the other `export/*` requests answer `unsupported`.                      |
| `pagedDiff?`       | `boolean \| undefined`                 | Paged compiles send only pages that changed. Requires the client's `pagedDiff`.                        |
| `resolveSpan?`     | `boolean \| undefined`                 | `resolve/span` is implemented.                                                                         |
| `resolveLocation?` | `boolean \| undefined`                 | `resolve/location` is implemented.                                                                     |
| `fontCatalogues?`  | `boolean \| undefined`                 | Families named in documents load from font catalogues (`fontCatalogues`), announced by `fonts/loaded`. |
| `experimental?`    | `Record<string, unknown> \| undefined` | Not yet standardized; keys should be namespaced.                                                       |

### Documents

`document/open` opens a document at revision `rev` with the text to compile (the healed source, in the streaming
pipeline). `document/edit` applies `edits: TextEdit[]` in order, each to the result of the previous one, and must
raise `rev`. `document/setFiles` writes (or, with `null`, deletes) files, as a new revision. `document/close` frees the
document.

### DocumentOpenParams

Opens a document at revision `rev`. `text` is what gets compiled: in the
streaming pipeline that's the healed source, not the raw stream.

| Prop                | Type                           | Description                                                                                                                                                                                                                                                                                                                                                                                                   |
| ------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `text`              | `string`                       | The document's text at `rev`, which later `document/edit`s change.                                                                                                                                                                                                                                                                                                                                            |
| `preamble?`         | `string \| undefined`          | Typst evaluated before `text` (theme, `@typstream/edu` imports). It is not part of the document's coordinates: diagnostics inside it report its path in `Diagnostic.file`, never offsets into `text`.                                                                                                                                                                                                         |
| `files?`            | `FileDelta \| undefined`       | Files the document can read (images, data), relative to its root. A key such as `@typstream/edu:0.1.0/lib.typ` is a file of that package (its spec, then the path inside it): files mounted this way make a local package importable, with no allowlist or download.                                                                                                                                          |
| `packages?`         | `PackageSpec[] \| undefined`   | Packages this document may import, in addition to `initialize`'s (plugins' `engine.packages`). The server fetches one only when the document imports it, and may ignore the list (a server facing untrusted clients).                                                                                                                                                                                         |
| `fixerModules?`     | `string[] \| undefined`        | Fixer modules for this document, in addition to `initialize`'s (plugins' `engine.fixerModules`, PLAN §8.2). The server imports each once; one that fails to load is reported with `$/log` and the document compiles without it.                                                                                                                                                                               |
| `generatorModules?` | `string[] \| undefined`        | File generator modules for this document (plugins' `engine.generatorModules`, PLAN §8.2): ES modules whose default export is a FileGenerator or an array of them. The server imports each once and runs the generators before every compile and export of the document; one that fails to load is reported with `$/log` and the document compiles without it. A server facing untrusted clients ignores them. |
| `fontCatalogues?`   | `FontCatalogue[] \| undefined` | Font catalogues this document loads families from, in addition to `initialize`'s. The fonts they load are the worker's, as every font is.                                                                                                                                                                                                                                                                     |
| `uri`               | `string`                       | The document the message is about.                                                                                                                                                                                                                                                                                                                                                                            |
| `rev`               | `number`                       | The revision of it the message is about (see Revision).                                                                                                                                                                                                                                                                                                                                                       |

Related types: `DocumentUri` (any string unique among the worker's open documents), `Revision` (a number),
`DocumentParams` (`{ uri, rev }`, the base of every document message), `FileContent` (`string | Uint8Array`; strings
are UTF-8 text) and `FileDelta` (`Record<string, FileContent | null>`, paths relative to the document root).

### `compile`

```ts
type CompileTarget = "html" | "paged";
type CompileMode = "streaming" | "final";
```

Compiles the document as of `rev`, which must be its current revision (otherwise `content-modified`). `streaming`
compiles may apply streaming-only fixers and are expected to be superseded; `final` compiles the finished document.

### CompileParams

Compiles the document as of revision `rev`, which must be its current
revision (otherwise `content-modified`: the client should compile the newer
one instead).

Output arrives as notifications, sent **before** the response, in this
order: `document/diagnostics` (always), then `document/artifact` (only when
the compile succeeded). The response then says the compile is over. This
keeps one rendering path for client-requested compiles and the ones the
server starts itself (e.g. when a lazily loaded font arrives).

| Prop           | Type                                  | Description                                                                                                                                                                                                                                                                    |
| -------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `target`       | `CompileTarget`                       | What to compile to: one of the server's `targets`.                                                                                                                                                                                                                             |
| `inputs?`      | `Record<string, string> \| undefined` | `sys.inputs` for this compile (answer-key toggle, reflow page size, theme).                                                                                                                                                                                                    |
| `mode?`        | `CompileMode \| undefined`            | Default `streaming`.                                                                                                                                                                                                                                                           |
| `settled?`     | `number \| undefined`                 | Streaming only: the text before this offset is settled (heal's `stableOffset`). Fixers may drop or rewrite only what comes after it, the text still being typed (PLAN §5.5). Without it, all of the text counts as settled.                                                    |
| `settledFrom?` | `number \| undefined`                 | Streaming only: the text from this offset on is settled too, when what is being typed is a range in the middle of the document (an edit streaming in, heal's `suffixOffset`, PLAN §5.2). Fixers and the fallback keep to `[settled, settledFrom)`. Default: the text's length. |
| `anchors?`     | `boolean \| undefined`                | HTML only: insert source anchors at top-level blocks (PLAN §10.2). Default true; exports contain them only when they ask (`ExportParams.anchors`).                                                                                                                             |
| `fullPages?`   | `boolean \| undefined`                | Paged only: send every page, not just changed ones (the client lost or dropped its pages, e.g. after remounting).                                                                                                                                                              |
| `pageFormat?`  | `PageFormat \| undefined`             | Paged only: how pages come. Default `svg`. With `drawing`, the server sends pages it can draw as PageDrawings for a canvas (their `svg` empty) and the others as SVG; a server without drawings sends SVG. Changing it sends every page.                                       |
| `fallback?`    | `FallbackParams \| undefined`         | What the server may show when the text doesn't compile even after its fixes (Layer 4, PLAN §5.6). Without it a failed compile publishes no artifact and the client keeps its last good one.                                                                                    |
| `uri`          | `string`                              | The document the message is about.                                                                                                                                                                                                                                             |
| `rev`          | `number`                              | The revision of it the message is about (see Revision).                                                                                                                                                                                                                        |

### FallbackParams

Layer 4 of a compile (PLAN §5.6): how the server turns a document that
doesn't compile into one that does, rather than publishing no artifact.

| Prop            | Type                          | Description                                                                                                                                                                                                                                                                                                                                       |
| --------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `isolate?`      | `boolean \| undefined`        | Show each top-level block that fails as an error box in place of the block (`typstream.error-block`, with the error and the block's source), found by compiling prefixes of the document (bisection). While streaming, only blocks of the settled text are isolated; the unsettled tail is left to the fixers and `stablePrefix`.                 |
| `stablePrefix?` | `boolean \| undefined`        | Streaming: when the unsettled tail fails, compile the settled text and show the tail as plain text below it (level 2). Clients ask for it once their last good render is too stale to keep showing.                                                                                                                                               |
| `restart?`      | `boolean \| undefined`        | The text being typed started over since the last artifact: a streaming range was set (an edit replacing part of the document), or the document was reset. Show this compile's output even if it shows less of that text than the last artifact did, which the server otherwise keeps instead (level 1). Clients send it until a compile succeeds. |
| `skip?`         | `SkippedRange[] \| undefined` | Parts of the text the client found the compiler can't get through: a compile ran past the watchdog budget or crashed the worker (PLAN §6.3). They are shown as error boxes without being compiled. Ranges are in the text, ascending and not overlapping, and should cover whole top-level blocks.                                                |

`SkippedRange` is a `Range` with a `reason` (`"timeout"` or `"crash"`): a part of the text the compiler can't get
through.

### CompileResult

The answer to `compile`, sent after its notifications: whether it published
an artifact, and what it cost.

| Prop           | Type                           | Description                                                                                            |
| -------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------ |
| `target`       | `CompileTarget`                | The target compiled to, as requested.                                                                  |
| `status`       | `"error" \| "ok"`              | `ok`: an artifact was published. `error`: only diagnostics; the client keeps its last good artifact.   |
| `timings`      | `CompileTimings`               | Where the worker's time went.                                                                          |
| `memoryBytes?` | `number \| undefined`          | Engine memory after the compile (e.g. wasm memory), for recycling decisions (PLAN §6.3).               |
| `fallback?`    | `CompileFallback \| undefined` | Set when the artifact came from the fallback (`CompileParams.fallback`) rather than the text as it is. |
| `fixes?`       | `AppliedFix[] \| undefined`    | The errors fixers fixed to make the artifact, in the order fixed. Absent when none were.               |
| `uri`          | `string`                       | The document the message is about.                                                                     |
| `rev`          | `number`                       | The revision of it the message is about (see Revision).                                                |

### CompileTimings

Wall-clock milliseconds measured in the worker.

| Prop          | Type                  | Description                                                        |
| ------------- | --------------------- | ------------------------------------------------------------------ |
| `totalMs`     | `number`              | From receiving the request to sending the response.                |
| `compileMs?`  | `number \| undefined` | Typst compilation (evaluation + layout), summed over fixer rounds. |
| `exportMs?`   | `number \| undefined` | Turning the document into HTML or SVG.                             |
| `fixMs?`      | `number \| undefined` | Diagnostic fixers (Layer 3), including the recompiles they caused. |
| `fallbackMs?` | `number \| undefined` | The fallback (Layer 4), including its compiles.                    |

### CompileFallback

How the artifact of a compile differs from the document, when Layer 4 made
it (PLAN §5.6). Ranges are in document coordinates.

| Prop        | Type             | Description                                                                                                                                                                                                       |
| ----------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `level`     | `2 \| 3 \| 4`    | Which step of the ladder made it: `2` the settled text with the tail as plain text (blocks of the settled text may be isolated too), `3` blocks isolated, `4` the whole document as one error block (final mode). |
| `isolated`  | `Range[]`        | Blocks shown as error boxes, ascending: blocks that failed, and `skip`ped ranges.                                                                                                                                 |
| `plainFrom` | `number \| null` | Streaming: the unsettled text from here on was shown as plain text (`stablePrefix`), or `null`.                                                                                                                   |

### Artifacts

```ts
type Artifact = HtmlArtifact | PagedArtifact;
```

An `HtmlArtifact` is `{ target: "html", html }`: the complete HTML document Typst exported. It is untrusted; the
renderer sanitizes it.

Compiled pages. With `base: null` a `PagedArtifact` holds every page. Otherwise it holds only the pages that changed
since the paged artifact of revision `base`; pages it doesn't list are unchanged, and pages at or past `pageCount` no
longer exist. A client whose displayed pages aren't from `base` must not apply it, and should recompile with
`fullPages`. The engine client merges them for you: `DocumentState.artifact` is always complete.

### PagedArtifact

Compiled pages. With `base === null` it holds every page. Otherwise it holds
only pages that changed since the paged artifact of revision `base` (the
previous one the server sent for this document); pages it doesn't list are
unchanged, and pages at or past `pageCount` no longer exist. A client whose
displayed pages aren't from `base` must not apply it and should recompile
with `fullPages`.

| Prop        | Type                         | Description                                                                                                                                                                               |
| ----------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `target`    | `"paged"`                    | Discriminant: the output of a paged compile.                                                                                                                                              |
| `base`      | `number \| null`             | The revision whose paged artifact this one updates, or `null` when it holds every page.                                                                                                   |
| `pageCount` | `number`                     | How many pages the document has now, whether or not they are in `pages`.                                                                                                                  |
| `pages`     | `PageUpdate[]`               | Ascending by index.                                                                                                                                                                       |
| `islands?`  | `PagedIsland[] \| undefined` | Every island marker of the document, in document order, whichever pages changed (PLAN §8.4). Optional: engines without introspection send none, and their islands show as their fallback. |

### PageUpdate

One rendered page of a paged artifact. Sizes in Typst points.

| Prop         | Type                          | Description                                                                                                                               |
| ------------ | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `index`      | `number`                      | Zero-based page index.                                                                                                                    |
| `hash`       | `string`                      | Hash of the page's frame. Equal hashes mean identical pages; use it as a key.                                                             |
| `width`      | `number`                      | Page width, in points.                                                                                                                    |
| `height`     | `number`                      | Page height, in points.                                                                                                                   |
| `svg`        | `string`                      | Untrusted SVG markup: the renderer sanitizes it. Empty when the page comes as a `drawing`.                                                |
| `drawing?`   | `PageDrawing \| undefined`    | The page as drawing operations for a canvas, when the compile asked for them (`pageFormat`).                                              |
| `text?`      | `TextRun[] \| undefined`      | The page's text runs in reading (logical) order. Optional: other engines may not provide them, nor the structure, language and direction. |
| `structure?` | `TextNode[] \| undefined`     | Headings, lists and tables around the runs, outermost first.                                                                              |
| `lang?`      | `string \| undefined`         | The document's language (`en`, `ar`, `zh-CN`).                                                                                            |
| `dir?`       | `"ltr" \| "rtl" \| undefined` | The document's direction.                                                                                                                 |

#### `PageFormat`, `PageDrawing` (beta) and `PageLink` (beta)

`PageFormat` is how a paged compile sends pages (`CompileParams.pageFormat`): `"svg"`, the default, or `"drawing"`,
operations for a canvas that `@typstream/dom`'s paged view paints. A server that can't draw a page sends it as SVG
either way. A `PageDrawing` holds the operations (32-bit floats, in the encoding engine-wasm's `src/draw.rs`
describes), the strings they name, the glyph outlines they draw and the page's `PageLink`s: the box around each link
to a URL, in points.

<Callout type="warn" title="Beta">
`PageDrawing` and `PageLink` are beta: the encoding may change before the first stable release.
</Callout>

### PageDrawing

A page as drawing operations for a canvas, what `@typstream/dom`'s paged
renderer paints (PLAN §6.5). The encoding is the one engine-wasm writes
(its `src/draw.rs`) and may change between versions.

| Prop      | Type                          | Description                                                                                                          |
| --------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `ops`     | `Uint8Array<ArrayBufferLike>` | The operations: little-endian 32-bit floats.                                                                         |
| `strings` | `string[]`                    | What the operations name by index: colours, SVG path data, image URLs.                                               |
| `glyphs`  | `[string, string][]`          | Glyph outlines the operations draw, as `[key, path]`: SVG path data in font units, the same for a key on every page. |
| `links`   | `PageLink[]`                  | Its links to URLs.                                                                                                   |

### PageLink

A link to a URL on a drawn page: the box around its area, in points from
the page's top left.

| Prop     | Type     | Description                                                     |
| -------- | -------- | --------------------------------------------------------------- |
| `url`    | `string` | As the document wrote it. Untrusted: the renderer sanitizes it. |
| `x`      | `number` | Left edge.                                                      |
| `y`      | `number` | Top edge.                                                       |
| `width`  | `number` | Across, so the link covers its text however the page is scaled. |
| `height` | `number` | Down, from `y`.                                                 |

#### `PagedIsland` (beta)

An island marker in a paged artifact: where on its page an island goes, from layout. Every paged artifact lists them
all, whichever pages it holds.

### PagedIsland

An island marker in the paged target: a `metadata` labelled
`<typstream-island>` (`ISLAND_MARKER`) at the top left of its block, found by
the engine in the laid-out document. Positions are in points from the page's
top left; they come from layout, however the page is drawn.

| Prop     | Type             | Description                                                                                                 |
| -------- | ---------------- | ----------------------------------------------------------------------------------------------------------- |
| `name`   | `string`         | The `name` of the marker's value.                                                                           |
| `data`   | `unknown`        | The `data` of the marker's value, untrusted.                                                                |
| `page`   | `number`         | Zero-based index of the page it's on.                                                                       |
| `x`      | `number`         | The block's left edge, in points from the page's left edge.                                                 |
| `y`      | `number`         | The block's top edge, in points from the page's top edge.                                                   |
| `width`  | `number`         | The `width` of the marker's value: the block's width, in points.                                            |
| `height` | `number`         | The `height` of the marker's value: the fallback's height, in points.                                       |
| `from`   | `number \| null` | Offset of the marker's call in the text the client sent (the healed source), or `null` when it isn't in it. |

#### `TextRun`

A run of text drawn on a page, for a selectable text layer. In points from the page's top left: `(x, y)` is the start
of the baseline (its left end, whatever the direction).

### TextRun

A run of text drawn on a page, for a selectable text layer (the SVG draws
glyphs as paths). In points from the page's top left: `(x, y)` is the start
of the baseline (its left end, whatever the direction), `width` the run's
advance, `size` its font size.

| Prop      | Type                                            | Description                                                                                            |
| --------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `text`    | `string`                                        | The run's characters, in reading order.                                                                |
| `x`       | `number`                                        | Left end of the baseline, in points from the page's left edge.                                         |
| `y`       | `number`                                        | The baseline, in points from the page's top edge.                                                      |
| `size`    | `number`                                        | Font size, in points.                                                                                  |
| `width`   | `number`                                        | The run's advance along the baseline, in points.                                                       |
| `matrix?` | `[number, number, number, number] \| undefined` | `[a, b, c, d]` of an SVG `matrix()` (translation is `x`/`y`); only for rotated, skewed or scaled text. |
| `lang?`   | `string \| undefined`                           | The run's language (`en`, `zh-CN`), only when it differs from the page's.                              |
| `dir?`    | `"ltr" \| "rtl" \| undefined`                   | The direction the run was set in, only when it differs from the page's (and is known).                 |

#### `TextNode`

A structure element around some of a page's text runs: a heading, a list or its item, a table, a row or a cell.

### TextNode

A structure element around some of a page's text runs: a heading, a list or
its item, a table, a row or a cell.

| Prop        | Type                                                                                | Description                                                                                                         |
| ----------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `role`      | `"cell" \| "columnheader" \| "heading" \| "list" \| "listitem" \| "row" \| "table"` | The ARIA role a text layer gives it.                                                                                |
| `level?`    | `number \| undefined`                                                               | A heading's `aria-level`: the document's title is 1 and a Typst heading of level n is n + 1, as in the HTML target. |
| `from`      | `number`                                                                            | Its runs are the page's `text[from..to)` (none for an empty cell).                                                  |
| `to`        | `number`                                                                            | End of its runs (exclusive).                                                                                        |
| `children?` | `TextNode[] \| undefined`                                                           | The elements inside it, in order.                                                                                   |

### Exports

```ts
type ExportFormat = "pdf" | "html";
type ExportResult<Data> = DocumentParams & { diagnostics: Diagnostic[] } & (
  | { status: "ok"; data: Data }
  | { status: "error" }
);
```

`export/pdf` and `export/html` take `ExportParams` (`uri`, `rev`, optional `inputs`) and export the current revision
in a final, anchor-free form. `error` means the document doesn't compile; diagnostics are included either way.

### Resolving positions (beta)

<Callout type="warn" title="Beta">
`resolve/span` and `resolve/location` are reserved for click-to-edit and cursor sync, and their types (`PagePoint`,
`ResolveSpanParams`, `ResolveSpanResult`, `ResolveLocationParams`, `ResolveLocationResult`) may change. Servers
announce them with `capabilities.resolveSpan` and `resolveLocation`.
</Callout>

`resolve/span` takes a `point` (`{ page, x, y }` in points) and returns the source `span` that produced it, or `null`.
`resolve/location` takes an `offset` and returns every `locations` point it was laid out at.

### Errors

```ts
type ErrorCode =
  | "not-initialized"
  | "protocol-version-mismatch"
  | "method-not-found"
  | "invalid-params"
  | "document-not-open"
  | "document-already-open"
  | "stale-revision"
  | "content-modified"
  | "request-cancelled"
  | "unsupported"
  | "internal";

interface ResponseError {
  code: ErrorCode;
  message: string;
  data?: unknown;
}
```

Protocol failures only: a document that doesn't compile is a successful `compile` with `status: "error"`.
`stale-revision` is an edit whose `rev` doesn't exceed the current one; `content-modified` is a compile, export or
resolve for a revision that is no longer current.

#### `ProtocolError`

```ts
class ProtocolError extends Error {
  constructor(code: ErrorCode, message: string, data?: unknown);
  readonly code: ErrorCode;
  readonly data: unknown;
  static from(e: ResponseError): ProtocolError;
  toJSON(): ResponseError;
}
```

A protocol failure as a throwable. Errors lose their class when posted, so the wire carries a `ResponseError`; convert
with `ProtocolError.from()` and `toJSON()`.

## Serialization

### `serializeMessage`

```ts
const serializeMessage: (message: unknown) => string;
```

Writes a protocol message (or any plain data holding `Uint8Array`s) as JSON text, for transports that can't
structured-clone, such as a WebSocket. Bytes (files, PDF exports) are written as `{ "$bytes": "<base64>" }`.

### `deserializeMessage`

```ts
const deserializeMessage: (text: string) => unknown;
```

Parses text written by `serializeMessage`, restoring the `Uint8Array`s. It only parses: validate the result before
trusting it.

```ts
socket.send(serializeMessage(message));
socket.onmessage = (e) => server.receive(deserializeMessage(e.data) as ClientMessage);
```

## See also

- [Writing a plugin](/docs/guides/writing-a-plugin)
- [Plugins](/docs/concepts/plugins)
- [Telemetry](/docs/guides/telemetry)
- [Remote engine](/docs/guides/remote-engine)
- [`@typstream/engine`](/docs/reference/engine), the client and server that speak the protocol
