andywer / threads.js

🧵 Make web workers & worker threads as simple as a function call.
https://threads.js.org/
MIT License
3.04k stars 161 forks source link

added support to spawn threads from electron asar bundles #469

Open biw opened 1 year ago

biw commented 1 year ago

Hey @andywer, thanks for the great repo. As described in https://github.com/andywer/threads.js/issues/425, electron now supports spawning threads from asar bundles. This PR adds support for asar bundles.

In order to keep the default behavior the same (no breaking changes), I added an opt-in value electronAsarUnpacked to the worker constructor, which when set to false passes the raw value to NativeWorker.

For anyone reading this (other than @andywer) who needs this behavior before the PR is merged in, here is a patch (for use with patch-package):

diff --git a/node_modules/threads/dist/master/implementation.node.js b/node_modules/threads/dist/master/implementation.node.js
index df93ca1..218f4fd 100644
--- a/node_modules/threads/dist/master/implementation.node.js
+++ b/node_modules/threads/dist/master/implementation.node.js
@@ -108,8 +108,15 @@ function initWorkerThreadsWorker() {
                 super(createTsNodeModule(resolvedScriptPath), Object.assign(Object.assign({}, options), { eval: true }));
             }
             else if (resolvedScriptPath.match(/\.asar[\/\\]/)) {
+              const electronPath =
+              options?.electronAsarUnpacked === false
+                ? resolvedScriptPath
                 // See <https://github.com/andywer/threads-plugin/issues/17>
-                super(resolvedScriptPath.replace(/\.asar([\/\\])/, ".asar.unpacked$1"), options);
+                : resolvedScriptPath.replace(/\.asar([\/\\])/, ".asar.unpacked$1")
+
+              super(electronPath, options)
+                // See <https://github.com/andywer/threads-plugin/issues/17>
+                // super(resolvedScriptPath.replace(/\.asar([\/\\])/, ".asar.unpacked$1"), options);
             }
             else {
                 super(resolvedScriptPath, options);
diff --git a/node_modules/threads/dist/types/master.d.ts b/node_modules/threads/dist/types/master.d.ts
index a9c9044..768c302 100644
--- a/node_modules/threads/dist/types/master.d.ts
+++ b/node_modules/threads/dist/types/master.d.ts
@@ -62,6 +62,9 @@ export interface ThreadsWorkerOptions extends WorkerOptions {
     workerData?: any;
     /** Whether to apply CORS protection workaround. Defaults to true. */
     CORSWorkaround?: boolean;
+    /** If Electron workers should use the asar.unpacked path. Defaults to true.
+     *  See <https://github.com/andywer/threads-plugin/issues/17> */
+    electronAsarUnpacked?: boolean
 }
 /** Worker implementation. Either web worker or a node.js Worker class. */
 export declare class WorkerImplementation extends EventTarget implements Worker {