From 483af7c33cce1688bb7b6f8f981c649278571180 Mon Sep 17 00:00:00 2001 From: Andrew Johnston Date: Sat, 3 Aug 2024 23:49:36 -0700 Subject: [PATCH] fix (worker-eval): fail worker with source when eval = false (#13062) Co-authored-by: Andrew Johnston Co-authored-by: Jarred Sumner --- src/js/node/worker_threads.ts | 10 ++++++++-- test/js/web/workers/worker.test.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/js/node/worker_threads.ts b/src/js/node/worker_threads.ts index 4de9fe81e8390c..4cd282398f67b4 100644 --- a/src/js/node/worker_threads.ts +++ b/src/js/node/worker_threads.ts @@ -216,9 +216,15 @@ class Worker extends EventEmitter { const builtinsGeneratorHatesEval = "ev" + "a" + "l"[0]; if (options && builtinsGeneratorHatesEval in options) { + if (options[builtinsGeneratorHatesEval]) { + const blob = new Blob([filename], { type: "" }); + this.#urlToRevoke = filename = URL.createObjectURL(blob); + } else { + // if options.eval = false, allow the constructor below to fail, if + // we convert the code to a blob, it will succeed. + this.#urlToRevoke = filename; + } delete options[builtinsGeneratorHatesEval]; - const blob = new Blob([filename], { type: "" }); - this.#urlToRevoke = filename = URL.createObjectURL(blob); } try { this.#worker = new WebWorker(filename, options); diff --git a/test/js/web/workers/worker.test.ts b/test/js/web/workers/worker.test.ts index 48f6d0f63624b1..210b26e8082ba3 100644 --- a/test/js/web/workers/worker.test.ts +++ b/test/js/web/workers/worker.test.ts @@ -293,4 +293,31 @@ describe("worker_threads", () => { expect(process.argv).toEqual(original_argv); expect(process.execArgv).toEqual(original_execArgv); }); + + test("worker with eval = false fails with code", async () => { + let has_error = false; + try { + const worker = new wt.Worker("console.log('this should not get printed')", { eval: false }); + } catch (err) { + expect(err.constructor.name).toEqual("TypeError"); + expect(err.message).toMatch(/BuildMessage: ModuleNotFound.+/); + has_error = true; + } + expect(has_error).toBe(true); + }); + + test("worker with eval = true succeeds with valid code", async () => { + let message; + const worker = new wt.Worker("postMessage('hello')", { eval: true }); + worker.on('message', e => { + message = e; + }); + const p = new Promise((resolve, reject) => { + worker.on('error', reject); + worker.on('exit', resolve); + }) + await p; + expect(message).toEqual("hello"); + }); + });