Something went wrong. Try again.
Local-first knowledge base made for Typst and the Atmosphere. typbase.at
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import init, { takePanicGlobal, TypstState } from "@typbase/engine";
import type { PluginCompileRequest, PluginCompileResponse } from "~/lib/plugins/protocol";
import { compileSurface } from "~/lib/plugins/compile";
import { BUNDLED_FONT_URLS } from "./bundledFonts";
/** * Worker entry: runs one TypstState for plugin surfaces. The host posts every * source and the JSON context with each request. Compiles never touch the * editor's wasm instance. Crashes are reported back with a stack before the * worker dies, so the host can fall back and the plugin lab can show why. */
let state: TypstState | undefined;
async function ensureState(url: string): Promise<TypstState> { if (state) return state;
// The explicit asset URL avoids Vite 8's wasm-module plugin, because loading the // default `new URL(..., import.meta.url)` path in a worker corrupts the heap. await init({ module_or_path: url }); const typstState = new TypstState(); for (const fontUrl of BUNDLED_FONT_URLS) { const response = await fetch(fontUrl); typstState.installFont(new Uint8Array(await response.arrayBuffer())); } state = typstState;
return state;}
function reportCrash(message: string, stack?: string): void { try { self.postMessage({ type: "crash", message, stack } satisfies PluginCompileResponse); } catch { // The worker is already gone. The host's error handler takes over. }}
self.addEventListener("error", (event) => { reportCrash( event.message || "plugin worker error", event.error instanceof Error ? event.error.stack : undefined, );});
self.addEventListener("unhandledrejection", (event) => { const reason = event.reason as unknown; reportCrash( reason instanceof Error ? reason.message : String(reason), reason instanceof Error ? reason.stack : undefined, );});
self.addEventListener("message", (event: MessageEvent<PluginCompileRequest>) => { const message = event.data; if (message.type !== "compile") return;
void (async () => { const id = message.id;
try { const typstState = await ensureState(message.wasmUrl); const result = compileSurface(typstState, message);
self.postMessage({ type: "result", id, ok: true, html: result.html, diagnostics: result.diagnostics, requests: result.requests, } satisfies PluginCompileResponse); } catch (error) { const panic = takePanicGlobal() ?? ""; const reason = error instanceof Error ? error : new Error(String(error));
self.postMessage({ type: "result", id, ok: false, error: [reason.message, panic].filter(Boolean).join(" | "), } satisfies PluginCompileResponse); } })();});