import 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 { 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) => { 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); } })(); });