@bastani/atomic-codemode 0.10.1-alpha.1 → 0.10.2-alpha.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../../src/runtime/host.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAE1D,OAAO,EAAE,mBAAmB,EAAiC,MAAM,gBAAgB,CAAC;AA6FpF;;;;;;GAMG;AACH,qBAAa,eAAgB,SAAQ,mBAAmB;IACvD,YAAY,OAAO,GAAE,sBAA2B,EAE/C;CACD"}
1
+ {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../../src/runtime/host.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAE1D,OAAO,EAAE,mBAAmB,EAAiC,MAAM,gBAAgB,CAAC;AAiHpF;;;;;;GAMG;AACH,qBAAa,eAAgB,SAAQ,mBAAmB;IACvD,YAAY,OAAO,GAAE,sBAA2B,EAE/C;CACD"}
@@ -5,6 +5,24 @@ function defaultWorkerUrl() {
5
5
  // `.ts` when running from source (tests, tsx), `.js` from the published dist.
6
6
  return new URL(import.meta.url.endsWith(".ts") ? "./worker.ts" : "./worker.js", import.meta.url);
7
7
  }
8
+ /** Whether the process was started with `--input-type`, on its command line or in `NODE_OPTIONS`. */
9
+ function startedWithInputType() {
10
+ return [...process.execArgv, ...(process.env.NODE_OPTIONS ?? "").split(/\s+/)].some((flag) => flag === "--input-type" || flag.startsWith("--input-type="));
11
+ }
12
+ /**
13
+ * Starts the worker with the process's flags, which can include the loaders its module needs. Node refuses
14
+ * `--input-type` for an ES module given as a worker's entry, and a worker inherits it from a process started with it
15
+ * (`node --input-type=module --eval ...`), so there this package's own worker is imported from evaluated source. A
16
+ * `workerUrl` given in the options starts as given.
17
+ */
18
+ function startWorker(workerUrl, workerData) {
19
+ if (workerUrl !== undefined)
20
+ return new Worker(workerUrl, { workerData });
21
+ const url = defaultWorkerUrl();
22
+ if (!startedWithInputType())
23
+ return new Worker(url, { workerData });
24
+ return new Worker(`import(${JSON.stringify(url.href)});`, { eval: true, workerData });
25
+ }
8
26
  /**
9
27
  * An error a stopping worker reports, or its termination's failure, reaches no run; it is only kept from being thrown.
10
28
  * A module function, so a worker still exiting holds nothing of the run through it.
@@ -36,7 +54,7 @@ function workerLauncher(options) {
36
54
  const releaseWorker = options.acquireWorker?.();
37
55
  let worker;
38
56
  try {
39
- worker = new Worker(options.workerUrl ?? defaultWorkerUrl(), { workerData });
57
+ worker = startWorker(options.workerUrl, workerData);
40
58
  }
41
59
  catch (error) {
42
60
  releaseWorker?.();
@@ -1 +1 @@
1
- {"version":3,"file":"host.js","sourceRoot":"","sources":["../../src/runtime/host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAA2B,eAAe,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAmB,MAAM,gBAAgB,CAAC;AAGpF,SAAS,gBAAgB;IACxB,8EAA8E;IAC9E,OAAO,IAAI,GAAG,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,aAAa,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;AAClG,CAAC;AAED;;;GAGG;AACH,SAAS,iBAAiB,KAAU,CAAC;AAErC,+EAA+E;AAC/E,SAAS,UAAU,CAAC,MAAc;IACjC,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;AAC7E,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,cAAc,CAAC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e,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;QAC/C,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,KAAK,IAAI,EAAE,CAAC;YACZ,MAAM,KAAK,CAAC;QACb,CAAC;QACD,OAAO,EAAE,IAAI,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,CAAC;IACjE,CAAC,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,OAAO,eAAgB,SAAQ,mBAAmB;IACvD,YAAY,OAAO,GAA2B,EAAE;QAC/C,KAAK,CAAC,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;IACzC,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport type { CodemodeSandboxOptions } from \"../types.ts\";\nimport { type CodemodeWasmModule, loadQuickJSWasm } from \"../wasm.ts\";\nimport { CodemodeSandboxBase, errorMessage, type VmLauncher } from \"./execution.ts\";\nimport type { WorkerData } from \"./protocol.ts\";\n\nfunction defaultWorkerUrl(): URL {\n\t// `.ts` when running from source (tests, tsx), `.js` from the published dist.\n\treturn new URL(import.meta.url.endsWith(\".ts\") ? \"./worker.ts\" : \"./worker.js\", import.meta.url);\n}\n\n/**\n * An error a stopping worker reports, or its termination's failure, reaches no run; it is only kept from being thrown.\n * A module function, so a worker still exiting holds nothing of the run through it.\n */\nfunction ignoreWorkerError(): void {}\n\n/** Settles when `worker` exits, holding nothing of the run that started it. */\nfunction workerExit(worker: Worker): Promise<void> {\n\treturn new Promise<void>((resolve) => worker.once(\"exit\", () => resolve()));\n}\n\n/**\n * Each execution gets its own worker thread and QuickJS VM. A fresh worker per run keeps\n * termination simple: a runaway script, including one that only spins the microtask queue, is\n * killed with `terminate()` and cannot poison a later run. Before terminating, the host sets a\n * shared interrupt flag that the VM polls, because Bun's `terminate()` cannot stop a thread that\n * is spinning in wasm. Stopping requests termination without waiting for exit: some built-ins do\n * not poll the flag, so on Bun a worker can outlive the script's result.\n */\nfunction workerLauncher(options: CodemodeSandboxOptions): VmLauncher {\n\treturn async (data, events) => {\n\t\tlet module: CodemodeWasmModule;\n\t\ttry {\n\t\t\tmodule = await (options.wasm ?? loadQuickJSWasm());\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Failed to load QuickJS: ${errorMessage(error)}`);\n\t\t}\n\t\tconst interrupt = new SharedArrayBuffer(4);\n\t\tconst workerData: WorkerData = { ...data, wasm: module, interrupt };\n\t\tconst releaseWorker = options.acquireWorker?.();\n\t\tlet worker: Worker;\n\t\ttry {\n\t\t\tworker = new Worker(options.workerUrl ?? defaultWorkerUrl(), { workerData });\n\t\t} catch (error) {\n\t\t\treleaseWorker?.();\n\t\t\tthrow new Error(`Failed to start worker: ${errorMessage(error)}`);\n\t\t}\n\t\tif (releaseWorker) worker.once(\"exit\", releaseWorker);\n\t\tconst onMessage = (message: unknown) => {\n\t\t\t// Node 24/26 --watch leaks dependency reports onto the worker channel (nodejs/node#65044).\n\t\t\tif (\n\t\t\t\ttypeof message === \"object\" &&\n\t\t\t\tmessage !== null &&\n\t\t\t\t(\"watch:import\" in message || \"watch:require\" in message)\n\t\t\t)\n\t\t\t\treturn;\n\t\t\tevents.message(message);\n\t\t};\n\t\tconst onError = (error: unknown) => {\n\t\t\tevents.failure({\n\t\t\t\tkind: \"sandbox\",\n\t\t\t\tname: error instanceof Error ? error.name : undefined,\n\t\t\t\tmessage: errorMessage(error),\n\t\t\t});\n\t\t};\n\t\tconst onExit = (code: number) => {\n\t\t\tevents.failure({ kind: \"sandbox\", message: `Worker exited with code ${code} before the script settled` });\n\t\t};\n\t\tworker.on(\"message\", onMessage);\n\t\tworker.on(\"error\", onError);\n\t\tworker.on(\"exit\", onExit);\n\t\tconst stop = async (): Promise<void> => {\n\t\t\tAtomics.store(new Int32Array(interrupt), 0, 1);\n\t\t\t// A stopped run hears nothing more from its worker. The listeners reach the run's options and, through\n\t\t\t// them, whatever the caller gave the run, so a worker still exiting must not keep them (or that) alive.\n\t\t\tworker.off(\"message\", onMessage);\n\t\t\tworker.off(\"exit\", onExit);\n\t\t\tworker.off(\"error\", onError);\n\t\t\tworker.on(\"error\", ignoreWorkerError);\n\t\t\t// A non-interruptible built-in can delay Bun's terminate() until it returns (#10748).\n\t\t\t// Do not hold up the result while that worker exits.\n\t\t\tvoid worker.terminate().catch(ignoreWorkerError);\n\t\t\t// terminate() refs the worker internally; unref it after requesting termination.\n\t\t\tworker.unref();\n\t\t};\n\t\ttry {\n\t\t\toptions.onWorkerStarted?.(workerExit(worker));\n\t\t} catch (error) {\n\t\t\tvoid stop();\n\t\t\tthrow error;\n\t\t}\n\t\treturn { post: (message) => worker.postMessage(message), stop };\n\t};\n}\n\n/**\n * Runs JavaScript in a QuickJS VM (a separate wasm instance) inside a worker thread. The worker\n * keeps script execution off the host thread: QuickJS runs synchronously, so a spinning script on\n * the host thread would block its event loop. Requires `node:worker_threads` (Node or Bun); see\n * `InlineCodemodeSandbox` and `RemoteCodemodeSandbox` in `@bastani/atomic-codemode/portable`\n * for other runtimes.\n */\nexport class CodemodeSandbox extends CodemodeSandboxBase {\n\tconstructor(options: CodemodeSandboxOptions = {}) {\n\t\tsuper(options, workerLauncher(options));\n\t}\n}\n"]}
1
+ {"version":3,"file":"host.js","sourceRoot":"","sources":["../../src/runtime/host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAA2B,eAAe,EAAE,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAmB,MAAM,gBAAgB,CAAC;AAGpF,SAAS,gBAAgB;IACxB,8EAA8E;IAC9E,OAAO,IAAI,GAAG,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,aAAa,EAAE,OAAO,IAAI,CAAC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AAO,EAAE,IAAI,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,CAAC;IACjE,CAAC,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,OAAO,eAAgB,SAAQ,mBAAmB;IACvD,YAAY,OAAO,GAA2B,EAAE;QAC/C,KAAK,CAAC,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;IACzC,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport type { CodemodeSandboxOptions } from \"../types.ts\";\nimport { type CodemodeWasmModule, loadQuickJSWasm } from \"../wasm.ts\";\nimport { CodemodeSandboxBase, errorMessage, type VmLauncher } from \"./execution.ts\";\nimport type { WorkerData } from \"./protocol.ts\";\n\nfunction defaultWorkerUrl(): URL {\n\t// `.ts` when running from source (tests, tsx), `.js` from the published dist.\n\treturn new URL(import.meta.url.endsWith(\".ts\") ? \"./worker.ts\" : \"./worker.js\", import.meta.url);\n}\n\n/** Whether the process was started with `--input-type`, on its command line or in `NODE_OPTIONS`. */\nfunction startedWithInputType(): boolean {\n\treturn [...process.execArgv, ...(process.env.NODE_OPTIONS ?? \"\").split(/\\s+/)].some(\n\t\t(flag) => flag === \"--input-type\" || flag.startsWith(\"--input-type=\"),\n\t);\n}\n\n/**\n * Starts the worker with the process's flags, which can include the loaders its module needs. Node refuses\n * `--input-type` for an ES module given as a worker's entry, and a worker inherits it from a process started with it\n * (`node --input-type=module --eval ...`), so there this package's own worker is imported from evaluated source. A\n * `workerUrl` given in the options starts as given.\n */\nfunction startWorker(workerUrl: string | URL | undefined, workerData: WorkerData): Worker {\n\tif (workerUrl !== undefined) return new Worker(workerUrl, { workerData });\n\tconst url = defaultWorkerUrl();\n\tif (!startedWithInputType()) return new Worker(url, { workerData });\n\treturn new Worker(`import(${JSON.stringify(url.href)});`, { eval: true, workerData });\n}\n\n/**\n * An error a stopping worker reports, or its termination's failure, reaches no run; it is only kept from being thrown.\n * A module function, so a worker still exiting holds nothing of the run through it.\n */\nfunction ignoreWorkerError(): void {}\n\n/** Settles when `worker` exits, holding nothing of the run that started it. */\nfunction workerExit(worker: Worker): Promise<void> {\n\treturn new Promise<void>((resolve) => worker.once(\"exit\", () => resolve()));\n}\n\n/**\n * Each execution gets its own worker thread and QuickJS VM. A fresh worker per run keeps\n * termination simple: a runaway script, including one that only spins the microtask queue, is\n * killed with `terminate()` and cannot poison a later run. Before terminating, the host sets a\n * shared interrupt flag that the VM polls, because Bun's `terminate()` cannot stop a thread that\n * is spinning in wasm. Stopping requests termination without waiting for exit: some built-ins do\n * not poll the flag, so on Bun a worker can outlive the script's result.\n */\nfunction workerLauncher(options: CodemodeSandboxOptions): VmLauncher {\n\treturn async (data, events) => {\n\t\tlet module: CodemodeWasmModule;\n\t\ttry {\n\t\t\tmodule = await (options.wasm ?? loadQuickJSWasm());\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Failed to load QuickJS: ${errorMessage(error)}`);\n\t\t}\n\t\tconst interrupt = new SharedArrayBuffer(4);\n\t\tconst workerData: WorkerData = { ...data, wasm: module, interrupt };\n\t\tconst releaseWorker = options.acquireWorker?.();\n\t\tlet worker: Worker;\n\t\ttry {\n\t\t\tworker = startWorker(options.workerUrl, workerData);\n\t\t} catch (error) {\n\t\t\treleaseWorker?.();\n\t\t\tthrow new Error(`Failed to start worker: ${errorMessage(error)}`);\n\t\t}\n\t\tif (releaseWorker) worker.once(\"exit\", releaseWorker);\n\t\tconst onMessage = (message: unknown) => {\n\t\t\t// Node 24/26 --watch leaks dependency reports onto the worker channel (nodejs/node#65044).\n\t\t\tif (\n\t\t\t\ttypeof message === \"object\" &&\n\t\t\t\tmessage !== null &&\n\t\t\t\t(\"watch:import\" in message || \"watch:require\" in message)\n\t\t\t)\n\t\t\t\treturn;\n\t\t\tevents.message(message);\n\t\t};\n\t\tconst onError = (error: unknown) => {\n\t\t\tevents.failure({\n\t\t\t\tkind: \"sandbox\",\n\t\t\t\tname: error instanceof Error ? error.name : undefined,\n\t\t\t\tmessage: errorMessage(error),\n\t\t\t});\n\t\t};\n\t\tconst onExit = (code: number) => {\n\t\t\tevents.failure({ kind: \"sandbox\", message: `Worker exited with code ${code} before the script settled` });\n\t\t};\n\t\tworker.on(\"message\", onMessage);\n\t\tworker.on(\"error\", onError);\n\t\tworker.on(\"exit\", onExit);\n\t\tconst stop = async (): Promise<void> => {\n\t\t\tAtomics.store(new Int32Array(interrupt), 0, 1);\n\t\t\t// A stopped run hears nothing more from its worker. The listeners reach the run's options and, through\n\t\t\t// them, whatever the caller gave the run, so a worker still exiting must not keep them (or that) alive.\n\t\t\tworker.off(\"message\", onMessage);\n\t\t\tworker.off(\"exit\", onExit);\n\t\t\tworker.off(\"error\", onError);\n\t\t\tworker.on(\"error\", ignoreWorkerError);\n\t\t\t// A non-interruptible built-in can delay Bun's terminate() until it returns (#10748).\n\t\t\t// Do not hold up the result while that worker exits.\n\t\t\tvoid worker.terminate().catch(ignoreWorkerError);\n\t\t\t// terminate() refs the worker internally; unref it after requesting termination.\n\t\t\tworker.unref();\n\t\t};\n\t\ttry {\n\t\t\toptions.onWorkerStarted?.(workerExit(worker));\n\t\t} catch (error) {\n\t\t\tvoid stop();\n\t\t\tthrow error;\n\t\t}\n\t\treturn { post: (message) => worker.postMessage(message), stop };\n\t};\n}\n\n/**\n * Runs JavaScript in a QuickJS VM (a separate wasm instance) inside a worker thread. The worker\n * keeps script execution off the host thread: QuickJS runs synchronously, so a spinning script on\n * the host thread would block its event loop. Requires `node:worker_threads` (Node or Bun); see\n * `InlineCodemodeSandbox` and `RemoteCodemodeSandbox` in `@bastani/atomic-codemode/portable`\n * for other runtimes.\n */\nexport class CodemodeSandbox extends CodemodeSandboxBase {\n\tconstructor(options: CodemodeSandboxOptions = {}) {\n\t\tsuper(options, workerLauncher(options));\n\t}\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/atomic-codemode",
3
- "version": "0.10.1-alpha.1",
3
+ "version": "0.10.2-alpha.1",
4
4
  "description": "Atomic's sandboxed JavaScript execution where the only capability is calling injected tools",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",