1
import { Worker } from "node:worker_threads";2
import type { CodemodeSandboxOptions } from "../types.ts";3
import { type CodemodeWasmModule, loadQuickJSWasm } from "../wasm.ts";4
import { CodemodeSandboxBase, errorMessage, type VmLauncher } from "./execution.ts";5
import type { WorkerData } from "./protocol.ts";7
function defaultWorkerUrl(): URL {8
// `.ts` when running from source (tests, tsx), `.js` from the published dist.9
return new URL(import.meta.url.endsWith(".ts") ? "./worker.ts" : "./worker.js", import.meta.url);10
}12
/**13
* Each execution gets its own worker thread and QuickJS VM. A fresh worker per run keeps14
* termination simple: a runaway script, including one that only spins the microtask queue, is15
* killed with `terminate()` and cannot poison a later run. Before terminating, the host sets a16
* shared interrupt flag that the VM polls, because Bun's `terminate()` cannot stop a thread that17
* is spinning in wasm. Stopping requests termination without waiting for exit: some built-ins do18
* not poll the flag, so on Bun a worker can outlive the script's result.19
*/20
function workerLauncher(options: CodemodeSandboxOptions): VmLauncher {21
return async (data, events) => {22
let module: CodemodeWasmModule;23
try {24
module = await (options.wasm ?? loadQuickJSWasm());25
} catch (error) {26
throw new Error(`Failed to load QuickJS: ${errorMessage(error)}`);27
}28
const interrupt = new SharedArrayBuffer(4);29
const workerData: WorkerData = { ...data, wasm: module, interrupt };30
const releaseWorker = options.acquireWorker?.();31
let worker: Worker;32
try {33
worker = new Worker(options.workerUrl ?? defaultWorkerUrl(), { workerData });34
} catch (error) {35
releaseWorker?.();36
throw new Error(`Failed to start worker: ${errorMessage(error)}`);37
}38
if (releaseWorker) worker.once("exit", releaseWorker);39
worker.on("message", (message: unknown) => {40
// Node 24/26 --watch leaks dependency reports onto the worker channel (nodejs/node#65044).41
if (42
typeof message === "object" &&43
message !== null &&44
("watch:import" in message || "watch:require" in message)45
)46
return;47
events.message(message);48
});49
worker.on("error", (error: unknown) => {50
events.failure({51
kind: "sandbox",52
name: error instanceof Error ? error.name : undefined,53
message: errorMessage(error),54
});55
});56
worker.on("exit", (code) => {57
events.failure({ kind: "sandbox", message: `Worker exited with code ${code} before the script settled` });58
});59
const stop = async (): Promise<void> => {60
Atomics.store(new Int32Array(interrupt), 0, 1);61
// A non-interruptible built-in can delay Bun's terminate() until it returns (#10748).62
// Do not hold up the result while that worker exits.63
void worker.terminate().catch(() => undefined);64
// terminate() refs the worker internally; unref it after requesting termination.65
worker.unref();66
};67
try {68
options.onWorkerStarted?.(new Promise<void>((resolve) => worker.once("exit", () => resolve())));69
} catch (error) {70
void stop();71
throw error;72
}73
return { post: (message) => worker.postMessage(message), stop };74
};75
}77
/**78
* Runs JavaScript in a QuickJS VM (a separate wasm instance) inside a worker thread. The worker79
* keeps script execution off the host thread: QuickJS runs synchronously, so a spinning script on80
* the host thread would block its event loop. Requires `node:worker_threads` (Node or Bun); see81
* `InlineCodemodeSandbox` and `RemoteCodemodeSandbox` in `@earendil-works/pi-codemode/portable`82
* for other runtimes.83
*/84
export class CodemodeSandbox extends CodemodeSandboxBase {85
constructor(options: CodemodeSandboxOptions = {}) {86
super(options, workerLauncher(options));87
}88
}