@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.
@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, 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) behind the protocol in@typstream/core, 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.
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's mountTypstream and the
React bindings (typstream, @typstream/react) drive an engine
for you. On a server, use @typstream/node.
Install
npm install @typstream/engineThe 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 to load them from elsewhere.
Example
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 or 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,setandapplyEditruns 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'sstableOffsetadvanced), the next compile is due afterminIntervalinstead. - 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 iserror. 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.reasonis"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 reportstoo-largeand keeps its last artifact untilset()orreset()brings it back under the limit. A streaming paged compile with more thanlivePages(100) pages stops live compiling;finish()compiles every page. - Paged output. The worker sends changed pages only; the client merges them, so
state.artifactalways 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 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. |
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.
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 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. See
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 downloads
URLs from the hosts you allow. See 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 lists the packages typstream allows by default; see
Typst packages.
API
Everything in this section is exported from @typstream/engine.
createEngine
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.
const engine = createEngine({
spawn: engineWorker(),
watchdog: { streamingMs: 5000 },
schedule: { minInterval: 50 },
});EngineOptions
Prop
Type
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.
Engine
Prop
Type
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.
const engine = createEngine({ spawn: engineWorker() }); // starts the worker: wasm and base fonts
await engine.preload({ plugins: [edu, mermaid] }); // warm-up compiles, before the first documentProp
Type
Beta
engine.preload() and PreloadOptions are beta.
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 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 DocumentStates. Calls after dispose() are ignored.
Prop
Type
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.
Prop
Type
Beta
packages is beta. Plugins' engine.packages are the usual way to allow packages for a document.
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
DocumentStatus
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.
Prop
Type
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 makes them a safe file. See
Exports.
doc.finish();
const pdf = await doc.exportPdf();
const html = await doc.exportHtml({ inputs: { showAnswers: "true" } });ExportOptions
Prop
Type
ExportError
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
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
const fromWorker: (create: () => WorkerLike) => SpawnEngine;A SpawnEngine for Web Workers, or anything shaped like one. Use it to spawn your own worker script:
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
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 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.
Prop
Type
WorkerLike
Prop
Type
EngineConnection
Prop
Type
EngineEvents
Prop
Type
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).
const DEFAULT_SCHEDULE: Readonly<ScheduleOptions>; // { minInterval: 33, maxInterval: 500, boundaryBias: true, staleMs: 1500 }Prop
Type
WatchdogOptions and DEFAULT_WATCHDOG
const DEFAULT_WATCHDOG: Readonly<WatchdogOptions>; // { streamingMs: 3000, finalMs: 10000, strikes: 3, probeMs: 5000 }Prop
Type
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.
const DEFAULT_LIMITS: Readonly<LimitOptions>; // { maxLength: 1048576, livePages: 100 }Prop
Type
DEFAULT_RECYCLE_BYTES
const DEFAULT_RECYCLE_BYTES: number; // 256 MiBThe 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.
Prop
Type
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:
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. 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
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.
serve(engineWasm(), undefined, { fixers: [pendingRef, myFixer, tailCut] });WorkerScope
Prop
Type
engineWasm
const engineWasm: (options?: EngineWasmOptions) => EngineAdapter;The default adapter: @typstream/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
Prop
Type
FontInput
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.
Prop
Type
TYPST_VERSION
const TYPST_VERSION = "0.15.1";The Typst version engine-wasm compiles with.
InitInput
Re-exported from @typstream/engine-wasm: what wasm accepts (a URL, a Response,
the bytes, or a compiled WebAssembly.Module).
inProcess (beta)
const inProcess: (
createAdapter: () => EngineAdapter,
options?: Pick<ServerOptions, "fixers" | "packages" | "fontCatalogues" | "generators" | "clientFixers">,
) => SpawnEngine;Beta
inProcess may change before the first stable release.
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.
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 packages this up.
createServer
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.
EngineServer
Prop
Type
ServerOptions
Prop
Type
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 sets all three. A server's own generators (ServerOptions.generators) still run.
PackageOptions (beta)
Beta
PackageOptions and the packages server option are beta.
Prop
Type
FontCatalogueOptions (beta)
Beta
FontCatalogueOptions and the fontCatalogues server option are beta.
The server's font catalogues (Fonts and languages): 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.
Prop
Type
Fixers
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, 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.
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
Prop
Type
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
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.
Prop
Type
AdapterHtmlResult
Prop
Type
AdapterPagedResult
Prop
Type
MaybePromise
type MaybePromise<T> = T | Promise<T>;Paths and coordinates
RUNTIME_PATH
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
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
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
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 (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
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.
@typstream/engine/websocket
The client's transport to an engine on a server, such as @typstream/node's. It is its
own entry point, so apps that compile in a worker don't download it (about 1 KB gzipped).
fromWebSocket (beta)
const fromWebSocket: (url: string | URL | (() => string | URL), options?: WebSocketOptions) => SpawnEngine;Beta
fromWebSocket may change before the first stable release.
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. Pass a function as url to
compute it for every connection, to sign each one afresh, say.
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/nodeserver 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
retriestimes (4), afterretryDelayMs(500 ms), doubled each time. When every attempt fails, the engine fails (an enginefailedevent), or the replacement does. - Dropped connections report
lost: the engine emitsdisconnect, 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'smaxPayload, say) stops. A connection that closes before it answersinitialize(a server that refuses it) fails the engine rather than reconnecting in a loop.
Prop
Type
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
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.
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 withintimeoutMs(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
Prop
Type
ImageResolver
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
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.
import { prefetchEngine } from "@typstream/engine/prefetch";
void prefetchEngine(); // at app start: a document may come laterBeta
prefetchEngine is beta.
@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
- Fallback
- Self-hosting the engine
- Remote engine
- Exports
- Telemetry
@typstream/core, for the protocol and event types
@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.
@typstream/heal
The self-healing parser that turns any prefix of streamed Typst into a source that parses, with lint fixes for Markdown habits.