@manifest-configuration-language/browser 0.3.22 → 0.3.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,626 @@
1
+ import PQueue from "p-queue";
2
+ import * as Comlink from "comlink";
3
+ import { createProjectSnapshot, computeProjectDelta, isValidProjectPath, operationPriorities, latestOnlyOperations, requestPriorities, maxSourceBytes, } from "./project.js";
4
+ function isJSONValue(value, ancestors = new Set()) {
5
+ if (value === null || typeof value === "string" || typeof value === "boolean")
6
+ return true;
7
+ if (typeof value === "number")
8
+ return Number.isFinite(value);
9
+ if (typeof value !== "object" || ancestors.has(value))
10
+ return false;
11
+ if (!Array.isArray(value)) {
12
+ const prototype = Object.getPrototypeOf(value);
13
+ if (prototype !== Object.prototype && prototype !== null)
14
+ return false;
15
+ if (Object.getOwnPropertySymbols(value).length > 0)
16
+ return false;
17
+ }
18
+ ancestors.add(value);
19
+ const valid = Array.isArray(value)
20
+ ? value.every((item) => isJSONValue(item, ancestors))
21
+ : Object.values(value).every((item) => isJSONValue(item, ancestors));
22
+ ancestors.delete(value);
23
+ return valid;
24
+ }
25
+ // ---------------------------------------------------------------------------
26
+ // Error class
27
+ // ---------------------------------------------------------------------------
28
+ export class MclRuntimeError extends Error {
29
+ code;
30
+ path;
31
+ line;
32
+ column;
33
+ endLine;
34
+ endColumn;
35
+ related;
36
+ constructor(error) {
37
+ super(error.message);
38
+ this.name = "MclRuntimeError";
39
+ this.code = error.code;
40
+ this.path = error.path;
41
+ this.line = error.line;
42
+ this.column = error.column;
43
+ this.endLine = error.endLine;
44
+ this.endColumn = error.endColumn;
45
+ this.related = error.related;
46
+ }
47
+ }
48
+ // ---------------------------------------------------------------------------
49
+ // Timing helpers
50
+ // ---------------------------------------------------------------------------
51
+ const defaultInitializationTimeoutMs = 30_000;
52
+ const defaultOperationTimeoutMs = 10_000;
53
+ const wasmURL = new URL("../dist/mcl.wasm", import.meta.url).href;
54
+ const wasmExecURL = new URL("../dist/wasm_exec.js", import.meta.url).href;
55
+ // ---------------------------------------------------------------------------
56
+ // Runtime factory
57
+ // ---------------------------------------------------------------------------
58
+ export function createMclRuntime(options = {}) {
59
+ const workerFactory = options.workerFactory ??
60
+ (() => new Worker(new URL("./worker.js", import.meta.url), { type: "module" }));
61
+ const initializationTimeoutMs = options.initializationTimeoutMs ?? defaultInitializationTimeoutMs;
62
+ let rawWorker;
63
+ let workerApi;
64
+ let cleanupWorkerListeners;
65
+ let initializationPromise;
66
+ let disposed = false;
67
+ const queue = new PQueue({ concurrency: 1 });
68
+ queue.on("error", () => { });
69
+ const queueSignals = new Set();
70
+ const latestPending = new Map();
71
+ let sequence = 0;
72
+ let workerGeneration = 0;
73
+ // The snapshot currently synced inside the Worker session.
74
+ let workerProjectId;
75
+ let workerSnapshot;
76
+ // Callbacks for aborting the currently-executing step.
77
+ let stopCurrent;
78
+ let stopInitialization;
79
+ // -------------------------------------------------------------------------
80
+ // Observability
81
+ // -------------------------------------------------------------------------
82
+ function emitStatus(status, extra = {}) {
83
+ try {
84
+ Promise.resolve(options.onStatus?.({ status, workerGeneration, ...extra })).catch(() => { });
85
+ }
86
+ catch {
87
+ // Observability callbacks must not affect runtime behavior.
88
+ }
89
+ }
90
+ function emitOperation(operation, startedAt, outcome, details = {}) {
91
+ try {
92
+ const durationMs = Math.max(0, performance.now() - startedAt);
93
+ Promise.resolve(options.onOperation?.({
94
+ operation,
95
+ durationMs,
96
+ queueWaitMs: details.executionStartedAt !== undefined
97
+ ? Math.max(0, details.executionStartedAt - startedAt)
98
+ : durationMs,
99
+ executionDurationMs: details.executionDurationMs ?? 0,
100
+ ...(details.wasmDurationMs === undefined
101
+ ? {}
102
+ : { wasmDurationMs: details.wasmDurationMs }),
103
+ ...(details.workerGeneration === undefined
104
+ ? {}
105
+ : { workerGeneration: details.workerGeneration }),
106
+ outcome,
107
+ })).catch(() => { });
108
+ }
109
+ catch {
110
+ // Observability callbacks must not affect runtime behavior.
111
+ }
112
+ }
113
+ // -------------------------------------------------------------------------
114
+ // Queue management
115
+ // -------------------------------------------------------------------------
116
+ function abortError() {
117
+ return new DOMException("The operation was aborted", "AbortError");
118
+ }
119
+ function enqueue(operation, run, signal, scope, requestedPriority, timing = {}) {
120
+ if (signal?.aborted)
121
+ return Promise.reject(signal.reason ?? abortError());
122
+ const priority = requestPriorities[requestedPriority ?? ""] ??
123
+ operationPriorities[operation] ??
124
+ 0;
125
+ const key = (name) => JSON.stringify([scope, name]);
126
+ const pendingKey = key(operation);
127
+ const pendingGroup = () => {
128
+ let group = latestPending.get(pendingKey);
129
+ if (!group) {
130
+ group = new Map();
131
+ latestPending.set(pendingKey, group);
132
+ }
133
+ return group;
134
+ };
135
+ const removePending = (pendingPriority, pending) => {
136
+ const group = latestPending.get(pendingKey);
137
+ if (group?.get(pendingPriority) !== pending)
138
+ return;
139
+ group.delete(pendingPriority);
140
+ if (group.size === 0)
141
+ latestPending.delete(pendingKey);
142
+ };
143
+ const supersedePending = (name, maximumPriority, message) => {
144
+ const groupKey = key(name);
145
+ const group = latestPending.get(groupKey);
146
+ if (!group)
147
+ return;
148
+ for (const [pendingPriority, pending] of group) {
149
+ if (pendingPriority > maximumPriority)
150
+ continue;
151
+ group.delete(pendingPriority);
152
+ pending.controller.abort(new DOMException(message, "AbortError"));
153
+ }
154
+ if (group.size === 0)
155
+ latestPending.delete(groupKey);
156
+ };
157
+ if (["render", "evaluate", "check"].includes(operation)) {
158
+ supersedePending("lint", priority, "An explicit run replaced this pending lint");
159
+ }
160
+ else if (priority > requestPriorities.background && operation !== "lint") {
161
+ supersedePending("lint", requestPriorities.background, "An interactive operation replaced this pending background lint");
162
+ }
163
+ const queueController = new AbortController();
164
+ const pending = { controller: queueController, started: false };
165
+ if (latestOnlyOperations.has(operation)) {
166
+ supersedePending(operation, priority, "A newer operation replaced this request");
167
+ pendingGroup().set(priority, pending);
168
+ }
169
+ queueSignals.add(queueController);
170
+ const abortWhileQueued = () => {
171
+ if (!pending.started)
172
+ queueController.abort(signal?.reason ?? abortError());
173
+ };
174
+ signal?.addEventListener("abort", abortWhileQueued, { once: true });
175
+ return queue
176
+ .add(async () => {
177
+ pending.started = true;
178
+ if (latestOnlyOperations.has(operation))
179
+ removePending(priority, pending);
180
+ timing.executionStartedAt = performance.now();
181
+ try {
182
+ return (await run());
183
+ }
184
+ finally {
185
+ timing.executionDurationMs = Math.max(0, performance.now() - timing.executionStartedAt);
186
+ }
187
+ }, { priority, signal: queueController.signal })
188
+ .finally(() => {
189
+ signal?.removeEventListener("abort", abortWhileQueued);
190
+ queueSignals.delete(queueController);
191
+ if (latestOnlyOperations.has(operation))
192
+ removePending(priority, pending);
193
+ });
194
+ }
195
+ // -------------------------------------------------------------------------
196
+ // Worker lifecycle
197
+ // -------------------------------------------------------------------------
198
+ function startWorker() {
199
+ if (disposed)
200
+ return Promise.reject(new Error("MCL runtime has been disposed"));
201
+ if (initializationPromise)
202
+ return initializationPromise;
203
+ const initializationStartedAt = performance.now();
204
+ const currentRawWorker = workerFactory();
205
+ rawWorker = currentRawWorker;
206
+ const currentApi = Comlink.wrap(currentRawWorker);
207
+ workerApi = currentApi;
208
+ workerGeneration++;
209
+ workerProjectId = undefined;
210
+ workerSnapshot = undefined;
211
+ let lastStatus;
212
+ const reportStatus = (status) => {
213
+ if (lastStatus === status)
214
+ return;
215
+ lastStatus = status;
216
+ if (status === "ready" || status === "error") {
217
+ emitStatus(status, {
218
+ initializationDurationMs: Math.max(0, performance.now() - initializationStartedAt),
219
+ });
220
+ }
221
+ else {
222
+ emitStatus(status);
223
+ }
224
+ };
225
+ let resolveReady;
226
+ let rejectReady;
227
+ const initialization = new Promise((resolve, reject) => {
228
+ resolveReady = resolve;
229
+ rejectReady = reject;
230
+ });
231
+ initializationPromise = initialization;
232
+ // Status messages from the worker arrive via standard message events.
233
+ // (Comlink forwards non-Comlink messages transparently.)
234
+ const onStatusMessage = (event) => {
235
+ if (rawWorker !== currentRawWorker)
236
+ return;
237
+ const data = event.data;
238
+ if (data?.type === "status" && typeof data.status === "string") {
239
+ reportStatus(data.status);
240
+ }
241
+ else if (data?.type === "fatal") {
242
+ const error = new Error(typeof data.message === "string" ? data.message : "MCL WebAssembly exited unexpectedly");
243
+ if (initialized) {
244
+ emitStatus("error");
245
+ terminateWorker(error);
246
+ }
247
+ else
248
+ fail(error);
249
+ }
250
+ };
251
+ currentRawWorker.addEventListener("message", onStatusMessage);
252
+ // Worker-level error (uncaught exception or load failure).
253
+ const onWorkerError = (event) => {
254
+ if (rawWorker !== currentRawWorker)
255
+ return;
256
+ const error = new Error(event.message || "MCL worker failed");
257
+ if (initialized) {
258
+ emitStatus("error");
259
+ terminateWorker(error);
260
+ }
261
+ else
262
+ fail(error);
263
+ };
264
+ currentRawWorker.addEventListener("error", onWorkerError);
265
+ // Malformed message from worker.
266
+ const onMessageError = (event) => {
267
+ if (rawWorker !== currentRawWorker)
268
+ return;
269
+ const error = new Error("MCL worker sent a malformed message");
270
+ if (initialized) {
271
+ emitStatus("error");
272
+ terminateWorker(error);
273
+ }
274
+ else
275
+ fail(error);
276
+ };
277
+ currentRawWorker.addEventListener("messageerror", onMessageError);
278
+ cleanupWorkerListeners = () => {
279
+ currentRawWorker.removeEventListener("message", onStatusMessage);
280
+ currentRawWorker.removeEventListener("error", onWorkerError);
281
+ currentRawWorker.removeEventListener("messageerror", onMessageError);
282
+ };
283
+ let initialized = false;
284
+ const timer = setTimeout(() => fail(new MclRuntimeError({
285
+ code: "MCL-WASM-TIMEOUT",
286
+ message: "MCL WebAssembly initialization timed out",
287
+ })), initializationTimeoutMs);
288
+ function fail(error) {
289
+ if (rawWorker !== currentRawWorker)
290
+ return;
291
+ if (!initialized)
292
+ reportStatus("error");
293
+ clearTimeout(timer);
294
+ if (stopInitialization === fail)
295
+ stopInitialization = undefined;
296
+ terminateWorker(error);
297
+ rejectReady(error);
298
+ }
299
+ stopInitialization = fail;
300
+ // Kick off WASM initialization via Comlink.
301
+ currentApi
302
+ .initialize({ wasmURL, wasmExecURL })
303
+ .then(() => {
304
+ if (rawWorker !== currentRawWorker)
305
+ return;
306
+ initialized = true;
307
+ reportStatus("ready");
308
+ clearTimeout(timer);
309
+ if (stopInitialization === fail)
310
+ stopInitialization = undefined;
311
+ resolveReady();
312
+ })
313
+ .catch((error) => {
314
+ fail(error instanceof Error ? error : new Error(String(error)));
315
+ });
316
+ return initialization;
317
+ }
318
+ function terminateWorker(error) {
319
+ const currentWorker = rawWorker;
320
+ const currentApi = workerApi;
321
+ const currentStop = stopCurrent;
322
+ const cleanup = cleanupWorkerListeners;
323
+ cleanupWorkerListeners = undefined;
324
+ rawWorker = undefined;
325
+ workerApi = undefined;
326
+ initializationPromise = undefined;
327
+ workerProjectId = undefined;
328
+ workerSnapshot = undefined;
329
+ stopCurrent = undefined;
330
+ cleanup?.();
331
+ currentWorker?.terminate();
332
+ currentApi?.[Comlink.releaseProxy]();
333
+ currentStop?.(error);
334
+ }
335
+ function runWorkerCall(signal, call) {
336
+ return new Promise((resolve, reject) => {
337
+ let settled = false;
338
+ const finish = (error, value) => {
339
+ if (settled)
340
+ return;
341
+ settled = true;
342
+ signal?.removeEventListener("abort", onAbort);
343
+ if (stopCurrent === stop)
344
+ stopCurrent = undefined;
345
+ if (error)
346
+ reject(error);
347
+ else
348
+ resolve(value);
349
+ };
350
+ const stop = (error) => {
351
+ finish(error);
352
+ terminateWorker(error);
353
+ };
354
+ const onAbort = () => stop(new DOMException("The operation was aborted", "AbortError"));
355
+ stopCurrent = stop;
356
+ signal?.addEventListener("abort", onAbort, { once: true });
357
+ if (signal?.aborted) {
358
+ onAbort();
359
+ return;
360
+ }
361
+ try {
362
+ call().then((value) => finish(undefined, value), (error) => {
363
+ stop(error instanceof Error ? error : new Error(String(error)));
364
+ });
365
+ }
366
+ catch (error) {
367
+ stop(error instanceof Error ? error : new Error(String(error)));
368
+ }
369
+ });
370
+ }
371
+ async function waitUntilReady(signal) {
372
+ if (!signal)
373
+ return startWorker();
374
+ if (signal.aborted)
375
+ throw new DOMException("The operation was aborted", "AbortError");
376
+ let onAbort;
377
+ try {
378
+ await Promise.race([
379
+ startWorker(),
380
+ new Promise((_, reject) => {
381
+ onAbort = () => {
382
+ stopInitialization?.(new DOMException("The operation was aborted", "AbortError"));
383
+ reject(new DOMException("The operation was aborted", "AbortError"));
384
+ };
385
+ signal.addEventListener("abort", onAbort, { once: true });
386
+ }),
387
+ ]);
388
+ }
389
+ finally {
390
+ if (onAbort)
391
+ signal.removeEventListener("abort", onAbort);
392
+ }
393
+ }
394
+ // -------------------------------------------------------------------------
395
+ // Project sync
396
+ // -------------------------------------------------------------------------
397
+ async function syncProjectToWorker(projectId, snapshot, requestOptions) {
398
+ if (workerProjectId === projectId && workerSnapshot === snapshot)
399
+ return;
400
+ const api = workerApi;
401
+ const previousSnapshot = workerProjectId === projectId ? workerSnapshot : undefined;
402
+ const reset = workerProjectId !== projectId;
403
+ const result = computeProjectDelta(snapshot, previousSnapshot, reset);
404
+ if (result === null)
405
+ return; // nothing changed
406
+ const { delta, binaryFiles, transferables } = result;
407
+ const updateJSON = JSON.stringify(delta);
408
+ // Transfer binary buffers to avoid copying.
409
+ const transferableBinaries = Object.create(null);
410
+ for (const [path, bytes] of Object.entries(binaryFiles)) {
411
+ transferableBinaries[path] = bytes;
412
+ }
413
+ const response = await runWorkerCall(requestOptions.signal, () => api.updateProject(projectId, updateJSON, Comlink.transfer(transferableBinaries, transferables)));
414
+ if (!response.ok)
415
+ throw new MclRuntimeError(response.error ?? { code: "MCL-WASM-PROJECT", message: "Project update failed" });
416
+ workerProjectId = projectId;
417
+ workerSnapshot = snapshot;
418
+ }
419
+ // -------------------------------------------------------------------------
420
+ // Core execute function
421
+ // -------------------------------------------------------------------------
422
+ async function execute(operation, source, requestOptions, entrypoint, project) {
423
+ if (requestOptions.parameters !== undefined) {
424
+ if (!["check", "evaluate", "render"].includes(operation)) {
425
+ throw new TypeError("parameters are only valid for check, evaluate, and render operations");
426
+ }
427
+ const parameters = requestOptions.parameters;
428
+ if (parameters === null || typeof parameters !== "object" || Array.isArray(parameters)) {
429
+ throw new TypeError("parameters must be an object with JSON values");
430
+ }
431
+ for (const value of Object.values(parameters)) {
432
+ if (!isJSONValue(value)) {
433
+ throw new TypeError("parameters must be an object with JSON values");
434
+ }
435
+ }
436
+ }
437
+ // Validate renameFileImports paths eagerly so we never spin up a Worker.
438
+ if (operation === "renameFileImports") {
439
+ const { oldPath, newPath } = requestOptions;
440
+ if (!isValidProjectPath(oldPath) ||
441
+ !oldPath.endsWith(".mcl") ||
442
+ !isValidProjectPath(newPath) ||
443
+ !newPath.endsWith(".mcl")) {
444
+ throw new TypeError("oldPath and newPath must be valid project-relative MCL paths");
445
+ }
446
+ if (oldPath === newPath)
447
+ throw new TypeError("oldPath and newPath must be distinct");
448
+ }
449
+ const { signal } = requestOptions;
450
+ if (signal?.aborted)
451
+ throw new DOMException("The operation was aborted", "AbortError");
452
+ const startedAt = performance.now();
453
+ const timing = {};
454
+ let operationWorkerGeneration;
455
+ const run = async () => {
456
+ if (disposed)
457
+ throw new Error("MCL runtime has been disposed");
458
+ if (signal?.aborted)
459
+ throw new DOMException("The operation was aborted", "AbortError");
460
+ const timeoutMs = requestOptions.timeoutMs ?? options.operationTimeoutMs ?? defaultOperationTimeoutMs;
461
+ const timeoutError = new MclRuntimeError({
462
+ code: "MCL-WASM-TIMEOUT",
463
+ message: "MCL operation timed out",
464
+ });
465
+ let timer;
466
+ try {
467
+ if (timeoutMs <= 0)
468
+ throw timeoutError;
469
+ timer = setTimeout(() => {
470
+ if (stopCurrent)
471
+ stopCurrent(timeoutError);
472
+ else
473
+ stopInitialization?.(timeoutError);
474
+ }, timeoutMs);
475
+ await waitUntilReady(signal);
476
+ if (signal?.aborted)
477
+ throw new DOMException("The operation was aborted", "AbortError");
478
+ const currentApi = workerApi;
479
+ const currentGeneration = workerGeneration;
480
+ operationWorkerGeneration = currentGeneration;
481
+ if (project) {
482
+ await syncProjectToWorker(project.id, project.snapshot, requestOptions);
483
+ }
484
+ // Build the WASM request.
485
+ const requestId = ++sequence;
486
+ const request = {
487
+ requestId,
488
+ revision: requestId,
489
+ operation,
490
+ entrypoint,
491
+ source,
492
+ ...(requestOptions.parameters !== undefined
493
+ ? { parameters: { ...requestOptions.parameters } }
494
+ : {}),
495
+ ...(requestOptions.position ? { position: requestOptions.position } : {}),
496
+ ...(requestOptions.newName ? { newName: requestOptions.newName } : {}),
497
+ ...(requestOptions.oldPath ? { oldPath: requestOptions.oldPath } : {}),
498
+ ...(requestOptions.newPath ? { newPath: requestOptions.newPath } : {}),
499
+ };
500
+ timing.wasmStartedAt = performance.now();
501
+ let response;
502
+ try {
503
+ response = await runWorkerCall(signal, () => currentApi.run(JSON.stringify(request), project.id));
504
+ }
505
+ finally {
506
+ timing.wasmDurationMs = Math.max(0, performance.now() - timing.wasmStartedAt);
507
+ clearTimeout(timer);
508
+ }
509
+ if (!response.ok) {
510
+ throw new MclRuntimeError(response.error ?? { code: "MCL-WASM-RESPONSE", message: "Operation failed" });
511
+ }
512
+ if (operation === "lint") {
513
+ return { operation, diagnostics: (response.result ?? []) };
514
+ }
515
+ return { operation, ...response.result };
516
+ }
517
+ catch (error) {
518
+ clearTimeout(timer);
519
+ throw error;
520
+ }
521
+ };
522
+ try {
523
+ const result = await enqueue(operation, run, signal, project.id, requestOptions.priority, timing);
524
+ emitOperation(operation, startedAt, "success", {
525
+ ...timing,
526
+ workerGeneration: operationWorkerGeneration,
527
+ });
528
+ return result;
529
+ }
530
+ catch (error) {
531
+ emitOperation(operation, startedAt, error?.name === "AbortError" ? "aborted" : "error", { ...timing, workerGeneration: operationWorkerGeneration });
532
+ throw error;
533
+ }
534
+ }
535
+ // -------------------------------------------------------------------------
536
+ // Project handle factory
537
+ // -------------------------------------------------------------------------
538
+ function makeProject(id, snapshot) {
539
+ const runProjectOperation = async (operation, requestOptions = {}) => {
540
+ const entrypoint = requestOptions.entrypoint ?? snapshot.defaultEntrypoint;
541
+ if (!entrypoint)
542
+ throw new TypeError("Set entrypoint when the project has multiple MCL source files");
543
+ if (!isValidProjectPath(entrypoint) || !Object.hasOwn(snapshot.files, entrypoint))
544
+ throw new TypeError(`Project entrypoint does not exist: ${entrypoint}`);
545
+ const entry = snapshot.files[entrypoint];
546
+ const source = typeof entry === "string"
547
+ ? entry
548
+ : new TextDecoder("utf-8", { fatal: true }).decode(entry);
549
+ const sourceBytes = new TextEncoder().encode(source).byteLength;
550
+ if (sourceBytes > maxSourceBytes)
551
+ throw new RangeError(`Source exceeds the ${maxSourceBytes}-byte limit`);
552
+ return execute(operation, source, requestOptions, entrypoint, { id, snapshot });
553
+ };
554
+ const projectApi = Object.freeze({
555
+ patch(changes) {
556
+ // Build new file set from current snapshot + changes.
557
+ const merged = Object.create(null);
558
+ const deleted = new Set(changes.delete);
559
+ for (const [path, content] of Object.entries(snapshot.files)) {
560
+ if (!deleted.has(path))
561
+ merged[path] = content;
562
+ }
563
+ if (changes.set) {
564
+ for (const [path, content] of Object.entries(changes.set)) {
565
+ merged[path] = content;
566
+ }
567
+ }
568
+ return makeProject(id, createProjectSnapshot(merged, snapshot));
569
+ },
570
+ run: ((operation, opts) => runProjectOperation(operation, opts)),
571
+ });
572
+ return projectApi;
573
+ }
574
+ // -------------------------------------------------------------------------
575
+ // warmUp
576
+ // -------------------------------------------------------------------------
577
+ function warmUp(requestOptions = {}) {
578
+ const { signal } = requestOptions;
579
+ if (signal?.aborted)
580
+ return Promise.reject(new DOMException("The operation was aborted", "AbortError"));
581
+ const run = async () => {
582
+ if (disposed)
583
+ throw new Error("MCL runtime has been disposed");
584
+ if (signal?.aborted)
585
+ throw new DOMException("The operation was aborted", "AbortError");
586
+ const timeoutMs = requestOptions.timeoutMs ?? initializationTimeoutMs;
587
+ const timeoutError = new MclRuntimeError({
588
+ code: "MCL-WASM-TIMEOUT",
589
+ message: "MCL WebAssembly initialization timed out",
590
+ });
591
+ let timer;
592
+ try {
593
+ if (timeoutMs <= 0)
594
+ throw timeoutError;
595
+ timer = setTimeout(() => stopInitialization?.(timeoutError), timeoutMs);
596
+ await waitUntilReady(signal);
597
+ }
598
+ finally {
599
+ clearTimeout(timer);
600
+ }
601
+ };
602
+ return enqueue("warmUp", run, signal, "runtime", requestOptions.priority);
603
+ }
604
+ // -------------------------------------------------------------------------
605
+ // Public runtime object
606
+ // -------------------------------------------------------------------------
607
+ return {
608
+ openProject(files) {
609
+ const snapshot = createProjectSnapshot(files);
610
+ const id = `mcl-project-${++sequence}`;
611
+ return makeProject(id, snapshot);
612
+ },
613
+ warmUp,
614
+ dispose() {
615
+ if (disposed)
616
+ return;
617
+ disposed = true;
618
+ const error = new Error("MCL runtime has been disposed");
619
+ for (const controller of queueSignals)
620
+ controller.abort(error);
621
+ stopCurrent?.(error);
622
+ stopInitialization?.(error);
623
+ terminateWorker(error);
624
+ },
625
+ };
626
+ }
@@ -0,0 +1,41 @@
1
+ import type { Response } from "./protocol.js";
2
+ export type RuntimeStatus = "fetching" | "compiling" | "initializing" | "ready" | "error";
3
+ export interface RuntimeAssets {
4
+ wasmURL: string;
5
+ wasmExecURL: string;
6
+ }
7
+ /** Encoded file sent from the main thread. Binary files omit `content`. */
8
+ export interface EncodedFile {
9
+ encoding: "utf8" | "binary";
10
+ content?: string;
11
+ }
12
+ /** A project update delta serialised as JSON. */
13
+ export type ProjectUpdateJSON = string;
14
+ export interface WorkerApi {
15
+ /**
16
+ * Load the WASM binary and initialise the Go runtime.
17
+ * Must be called once before any other method.
18
+ */
19
+ initialize(assets: RuntimeAssets): Promise<void>;
20
+ /**
21
+ * Apply a project snapshot delta to the in-WASM session.
22
+ * Returns the WASM JSON response directly.
23
+ */
24
+ updateProject(projectId: string, updateJSON: ProjectUpdateJSON, binaryFiles: Record<string, Uint8Array>): Response;
25
+ /**
26
+ * Execute an MCL operation and return the WASM JSON response.
27
+ * Pass `projectId` to run inside a project session.
28
+ */
29
+ run(requestJSON: string, projectId?: string): Response;
30
+ }
31
+ declare global {
32
+ var mclWasmReady: boolean | undefined;
33
+ var mclWasm: {
34
+ updateProject(projectId: string, updateJSON: string, binaryFiles: Record<string, Uint8Array>): string;
35
+ run(requestJSON: string, binaryFiles: Record<string, Uint8Array>, projectId?: string): string;
36
+ };
37
+ var Go: new () => {
38
+ importObject: WebAssembly.Imports;
39
+ run(instance: WebAssembly.Instance): Promise<void>;
40
+ };
41
+ }