///
/**
* Web Worker that owns a numbl instance. One run at a time; the host cancels
* a run by terminating the worker, which is why nothing here needs to be
* interruptible. The modes of stage 1 travel back to the host and return as
* an input of stage 2, so a cancelled or crashed worker loses nothing kept.
*/
import { executeBundle, numblVersion } from "./execute";
import { collectBuffers } from "./plain";
import type { FromWorker, ToWorker } from "./protocol";
import type { BackendInfo } from "./types";
const backend: BackendInfo = {
engine: "numbl",
version: numblVersion(),
optimization: "1",
host: "web-worker",
};
const post = (msg: FromWorker, transfer: ArrayBuffer[] = []) => self.postMessage(msg, transfer);
self.onmessage = (e: MessageEvent) => {
const msg = e.data;
if (msg.type === "info") {
post({ type: "info", id: msg.id, backend });
return;
}
const result = executeBundle({ bundle: msg.bundle, inputs: msg.inputs }, backend, (text) =>
post({ type: "output", id: msg.id, text }),
);
const transfer = result.ok ? collectBuffers(result.value) : [];
post({ type: "done", id: msg.id, result }, transfer);
};