| 1 | // markdown.worker — off-main-thread Markdown parse (Phase E). Receives the |
| 2 | // raw answer text, runs the isomorphic pipeline (normalizeMath → remark → |
| 3 | // rehype → react-markdown transforms → block slicing), and posts back |
| 4 | // JSON-serializable HAST blocks. The worker never cancels in-flight work; the |
| 5 | // client drops stale responses by request id. |
| 6 | |
| 7 | import { parseMarkdown } from "../lib/markdownPipeline"; |
| 8 | import type { MarkdownParseResponse, MarkdownWorkerRequest } from "../lib/markdownWorkerProtocol"; |
| 9 | |
| 10 | const workerScope = globalThis as unknown as { |
| 11 | onmessage: ((event: MessageEvent<MarkdownWorkerRequest>) => void) | null; |
| 12 | postMessage: (response: MarkdownParseResponse) => void; |
| 13 | }; |
| 14 | |
| 15 | const documents = new Map<string, string>(); |
| 16 | |
| 17 | workerScope.onmessage = (event) => { |
| 18 | const request = event.data; |
| 19 | if (request.op === "release") { |
| 20 | documents.delete(request.documentId); |
| 21 | return; |
| 22 | } |
| 23 | let text = request.text; |
| 24 | if (request.op === "open" || request.op === "replace" || request.op === "finalize") { |
| 25 | documents.set(request.documentId, text); |
| 26 | } else if (request.op === "append") { |
| 27 | text = (documents.get(request.documentId) ?? "") + text; |
| 28 | documents.set(request.documentId, text); |
| 29 | } |
| 30 | try { |
| 31 | workerScope.postMessage({ id: request.id, result: parseMarkdown(text) }); |
| 32 | } catch (error) { |
| 33 | workerScope.postMessage({ |
| 34 | id: request.id, |
| 35 | error: error instanceof Error ? error.message : String(error), |
| 36 | }); |
| 37 | } |
| 38 | }; |
| 39 |