compiler-worker.ts (6147B)
1 // Test-only JS evaluator driver; excluded from the production site. 2 import { compileExpression } from './expression.js'; 3 import { environmentProfile } from '../packages.js'; 4 import { BROWSER_BUDGET, collectionPolicy } from '../execution.js'; 5 import { contractEnvironment } from '../contracts.js'; 6 import { Graph, type NodeId } from '../graph.js'; 7 import { COMPILER_BUNDLE_LIMIT, fetchBundle, fetchBytes, loadBundle } from '../bundle.js'; 8 import { literals, makeLiteral, outputType, view, list, text } from '../codecs.js'; 9 import { COMPILER_EXPORT, compilerDescriptor, sourceLiteral, sourceText, compiledDefinitions } from '../compiler.js'; 10 import type { CompilerClient, CompilerMessage } from './compiler-protocol.js'; 11 const scope = globalThis as unknown as { postMessage(message: CompilerMessage): void; onmessage: ((event: MessageEvent<unknown>) => void) | null }; 12 const base = new URL('../../', import.meta.url); 13 const send = (message: CompilerMessage): void => scope.postMessage(message); 14 const running = (): void => send({ type: 'state', state: 'running' }); 15 let phase: 'empty' | 'compiling' | 'ready' | 'running' | 'done' = 'empty'; 16 let graph: Graph | undefined, exports: Map<string, NodeId> | undefined; 17 async function compile(source: unknown, profileName?: string): Promise<void> { 18 phase = 'compiling'; running(); const start = performance.now(); 19 const budget = BROWSER_BUDGET; 20 graph = new Graph(budget, collectionPolicy(budget)); 21 const input = sourceLiteral(graph, source); // Validate before downloading a compiler. 22 const bytes = await fetchBytes(new URL('compiler.json', base), 4096); 23 const raw: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); 24 const { hash } = compilerDescriptor(raw); 25 const bundle = await fetchBundle(new URL(`/_arboricx/bundle/hash/${hash}`, base), hash, COMPILER_BUNDLE_LIMIT); 26 const library = loadBundle(graph, bundle), compiler = library.get(COMPILER_EXPORT); 27 if (compiler === undefined) throw new Error('Missing stable compiler entrypoint'); 28 let environment: NodeId; 29 if (profileName === undefined) environment = contractEnvironment(graph, library); 30 else { 31 const bytes = await fetchBytes(new URL('environments.json', base), 32_768); 32 const selected = environmentProfile(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as unknown, profileName); 33 if (selected.compiler !== hash) throw new Error('Demo environment/compiler pin mismatch'); 34 const bindings: NodeId[] = []; 35 if (selected.profile) { 36 const support = await fetchBundle(new URL(`/_arboricx/bundle/hash/${selected.profile.hash}`, base), selected.profile.hash); 37 const values = loadBundle(graph, support); 38 for (const name of selected.profile.names) { 39 const tree = values.get(name); 40 if (tree === undefined) throw new Error(`Missing demo environment binding ${name}`); 41 bindings.push(graph.fork(text(graph, name), tree)); 42 } 43 } 44 environment = list(graph, bindings); 45 } 46 exports = compiledDefinitions(graph, graph.apply(compiler, [environment, input])); 47 graph.collect(exports.values()); // Safe phase boundary; compiler/input temporaries are no longer caller roots. 48 phase = 'ready'; send({ type: 'compiled', names: [...exports.keys()], draft: { graph: graph.checkpoint(), exports: [...exports] }, stats: graph.stats, milliseconds: performance.now() - start }); 49 } 50 async function run(message: Extract<CompilerClient, { type: 'run' }>): Promise<void> { 51 if (!graph || !exports) throw new Error('Compile a unit first'); 52 phase = 'running'; running(); 53 const fn = message.expression === undefined ? exports.get(message.export) : await compileExpression(graph, exports, message.expression); 54 if (fn === undefined) throw new Error('Unknown compiled definition'); 55 if (message.mode !== 'pure' && message.mode !== 'io') throw new Error('Unsupported execution mode'); 56 const type = outputType(message.output), args = literals(message.arguments).map(value => makeLiteral(graph!, value)); 57 let result = message.expression === undefined ? graph.apply(fn, args) : fn; 58 if (message.mode === 'io') throw new Error('Reference graph IO execution is retired; use a native runtime'); 59 const displayed = view(graph, result, type); 60 graph.collect(exports.values()); // Drop this run's temporaries, retaining every definition. 61 phase = 'ready'; send({ type: 'done', result: displayed, stats: graph.stats }); 62 } 63 scope.onmessage = ({ data }) => { 64 if (!data || typeof data !== 'object' || Array.isArray(data)) return; 65 const message = data as Record<string, unknown>; 66 67 let operation: Promise<void>; 68 try { 69 if (message['type'] === 'restore' && phase === 'empty') { 70 // Only the owning conformance harness supplies this trusted in-memory checkpoint. 71 const restored = data as Extract<CompilerClient, { type: 'restore' }>; 72 const budget = BROWSER_BUDGET; 73 graph = Graph.restore(restored.draft.graph, budget, collectionPolicy(budget)); 74 exports = new Map(restored.draft.exports); phase = 'ready'; return; 75 } else if (message['type'] === 'compile' && phase === 'empty') { 76 if (message['environment'] !== undefined && (typeof message['environment'] !== 'string' || message['environment'].length > 128)) throw new Error('Invalid demo environment'); 77 operation = compile(message['source'], message['environment'] as string | undefined); 78 } else if (message['type'] === 'run' && phase === 'ready') { 79 if (typeof message['export'] !== 'string' || message['export'].length > 128) throw new Error('Invalid compiled selection'); 80 operation = run({ type: 'run', export: message['export'], arguments: message['arguments'], 81 ...(message['expression'] === undefined ? {} : { expression: sourceText(message['expression']) }), 82 output: outputType(message['output']), mode: message['mode'] as 'pure' | 'io', step: message['step'] === true }); 83 } else return; 84 } catch (error) { operation = Promise.reject(error); } 85 operation.catch((error: unknown) => { phase = 'done'; send({ type: 'error', message: error instanceof Error ? error.message : String(error) }); }); 86 };