# 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)
