@loaders.gl/worker-utils 4.0.0-alpha.23 → 4.0.0-alpha.25

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.
Files changed (45) hide show
  1. package/dist/es5/lib/env-utils/version.js +17 -6
  2. package/dist/es5/lib/env-utils/version.js.map +1 -1
  3. package/dist/es5/lib/library-utils/library-utils.js +1 -3
  4. package/dist/es5/lib/library-utils/library-utils.js.map +1 -1
  5. package/dist/es5/lib/worker-api/get-worker-url.js +2 -4
  6. package/dist/es5/lib/worker-api/get-worker-url.js.map +1 -1
  7. package/dist/esm/lib/env-utils/version.js +14 -4
  8. package/dist/esm/lib/env-utils/version.js.map +1 -1
  9. package/dist/esm/lib/library-utils/library-utils.js +1 -3
  10. package/dist/esm/lib/library-utils/library-utils.js.map +1 -1
  11. package/dist/esm/lib/worker-api/get-worker-url.js +1 -3
  12. package/dist/esm/lib/worker-api/get-worker-url.js.map +1 -1
  13. package/dist/lib/env-utils/version.d.ts +6 -1
  14. package/dist/lib/env-utils/version.d.ts.map +1 -1
  15. package/dist/lib/library-utils/library-utils.d.ts.map +1 -1
  16. package/dist/lib/worker-api/get-worker-url.d.ts.map +1 -1
  17. package/package.json +4 -5
  18. package/src/lib/env-utils/version.ts +25 -9
  19. package/src/lib/library-utils/library-utils.ts +1 -8
  20. package/src/lib/worker-api/get-worker-url.ts +1 -4
  21. package/dist/index.js +0 -59
  22. package/dist/lib/async-queue/async-queue.js +0 -87
  23. package/dist/lib/env-utils/assert.js +0 -13
  24. package/dist/lib/env-utils/globals.js +0 -32
  25. package/dist/lib/env-utils/version.js +0 -12
  26. package/dist/lib/library-utils/library-utils.js +0 -188
  27. package/dist/lib/node/require-utils.node.js +0 -89
  28. package/dist/lib/node/worker_threads-browser.js +0 -15
  29. package/dist/lib/node/worker_threads.js +0 -33
  30. package/dist/lib/process-utils/child-process-proxy.js +0 -136
  31. package/dist/lib/process-utils/process-utils.js +0 -35
  32. package/dist/lib/worker-api/create-worker.js +0 -91
  33. package/dist/lib/worker-api/get-worker-url.js +0 -59
  34. package/dist/lib/worker-api/process-on-worker.js +0 -83
  35. package/dist/lib/worker-api/validate-worker-version.js +0 -35
  36. package/dist/lib/worker-farm/worker-body.js +0 -111
  37. package/dist/lib/worker-farm/worker-farm.js +0 -89
  38. package/dist/lib/worker-farm/worker-job.js +0 -47
  39. package/dist/lib/worker-farm/worker-pool.js +0 -164
  40. package/dist/lib/worker-farm/worker-thread.js +0 -131
  41. package/dist/lib/worker-utils/get-loadable-worker-url.js +0 -72
  42. package/dist/lib/worker-utils/get-transfer-list.js +0 -87
  43. package/dist/lib/worker-utils/remove-nontransferable-options.js +0 -27
  44. package/dist/types.js +0 -2
  45. package/dist/workers/null-worker.js +0 -7
@@ -1,13 +0,0 @@
1
- "use strict";
2
- // Replacement for the external assert method to reduce bundle size
3
- // Note: We don't use the second "message" argument in calling code,
4
- // so no need to support it here
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.assert = void 0;
7
- /** Throws an `Error` with the optional `message` if `condition` is falsy */
8
- function assert(condition, message) {
9
- if (!condition) {
10
- throw new Error(message || 'loaders.gl assertion failed.');
11
- }
12
- }
13
- exports.assert = assert;
@@ -1,32 +0,0 @@
1
- "use strict";
2
- // Purpose: include this in your module to avoids adding dependencies on
3
- // micro modules like 'global' and 'is-browser';
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.nodeVersion = exports.isMobile = exports.isWorker = exports.isBrowser = exports.document = exports.global = exports.window = exports.self = void 0;
6
- /* eslint-disable no-restricted-globals */
7
- const globals = {
8
- self: typeof self !== 'undefined' && self,
9
- window: typeof window !== 'undefined' && window,
10
- global: typeof global !== 'undefined' && global,
11
- document: typeof document !== 'undefined' && document
12
- };
13
- const self_ = globals.self || globals.window || globals.global || {};
14
- exports.self = self_;
15
- const window_ = globals.window || globals.self || globals.global || {};
16
- exports.window = window_;
17
- const global_ = globals.global || globals.self || globals.window || {};
18
- exports.global = global_;
19
- const document_ = globals.document || {};
20
- exports.document = document_;
21
- /** true if running in the browser, false if running in Node.js */
22
- exports.isBrowser =
23
- // @ts-ignore process.browser
24
- typeof process !== 'object' || String(process) !== '[object process]' || process.browser;
25
- /** true if running on a worker thread */
26
- exports.isWorker = typeof importScripts === 'function';
27
- /** true if running on a mobile device */
28
- exports.isMobile = typeof window !== 'undefined' && typeof window.orientation !== 'undefined';
29
- // Extract node major version
30
- const matches = typeof process !== 'undefined' && process.version && /v([0-9]*)/.exec(process.version);
31
- /** Version of Node.js if running under Node, otherwise 0 */
32
- exports.nodeVersion = (matches && parseFloat(matches[1])) || 0;
@@ -1,12 +0,0 @@
1
- "use strict";
2
- // Version constant cannot be imported, it needs to correspond to the build version of **this** module.
3
- // __VERSION__ is injected by babel-plugin-version-inline
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.VERSION = void 0;
6
- // Change to `latest` on production branches
7
- const DEFAULT_VERSION = 'beta';
8
- exports.VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : DEFAULT_VERSION;
9
- if (typeof __VERSION__ === 'undefined') {
10
- // eslint-disable-next-line
11
- console.error('loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN.');
12
- }
@@ -1,188 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.getLibraryUrl = exports.loadLibrary = void 0;
27
- /* global importScripts */
28
- const globals_1 = require("../env-utils/globals");
29
- const node = __importStar(require("../node/require-utils.node"));
30
- const assert_1 = require("../env-utils/assert");
31
- const version_1 = require("../env-utils/version");
32
- /**
33
- * TODO - unpkg.com doesn't seem to have a `latest` specifier for alpha releases...
34
- * 'beta' on beta branch, 'latest' on prod branch
35
- */
36
- const LATEST = 'beta';
37
- const VERSION = typeof version_1.VERSION !== 'undefined' ? version_1.VERSION : LATEST;
38
- const loadLibraryPromises = {}; // promises
39
- /**
40
- * Dynamically loads a library ("module")
41
- *
42
- * - wasm library: Array buffer is returned
43
- * - js library: Parse JS is returned
44
- *
45
- * Method depends on environment
46
- * - browser - script element is created and installed on document
47
- * - worker - eval is called on global context
48
- * - node - file is required
49
- *
50
- * @param libraryUrl
51
- * @param moduleName
52
- * @param options
53
- */
54
- async function loadLibrary(libraryUrl, moduleName = null, options = {}, libraryName = null) {
55
- if (moduleName) {
56
- libraryUrl = getLibraryUrl(libraryUrl, moduleName, options, libraryName);
57
- }
58
- // Ensure libraries are only loaded once
59
- loadLibraryPromises[libraryUrl] =
60
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
61
- loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
62
- return await loadLibraryPromises[libraryUrl];
63
- }
64
- exports.loadLibrary = loadLibrary;
65
- // TODO - sort out how to resolve paths for main/worker and dev/prod
66
- function getLibraryUrl(library, moduleName, options = {}, libraryName = null) {
67
- // Check if already a URL
68
- if (!options.useLocalLibraries && library.startsWith('http')) {
69
- return library;
70
- }
71
- libraryName = libraryName || library;
72
- // Allow application to import and supply libraries through `options.modules`
73
- const modules = options.modules || {};
74
- if (modules[libraryName]) {
75
- return modules[libraryName];
76
- }
77
- // Load from local files, not from CDN scripts in Node.js
78
- // TODO - needs to locate the modules directory when installed!
79
- if (!globals_1.isBrowser) {
80
- return `modules/${moduleName}/dist/libs/${libraryName}`;
81
- }
82
- // In browser, load from external scripts
83
- if (options.CDN) {
84
- (0, assert_1.assert)(options.CDN.startsWith('http'));
85
- return `${options.CDN}/${moduleName}@${VERSION}/dist/libs/${libraryName}`;
86
- }
87
- // TODO - loading inside workers requires paths relative to worker script location...
88
- if (globals_1.isWorker) {
89
- return `../src/libs/${libraryName}`;
90
- }
91
- return `modules/${moduleName}/src/libs/${libraryName}`;
92
- }
93
- exports.getLibraryUrl = getLibraryUrl;
94
- async function loadLibraryFromFile(libraryUrl) {
95
- if (libraryUrl.endsWith('wasm')) {
96
- return await loadAsArrayBuffer(libraryUrl);
97
- }
98
- if (!globals_1.isBrowser) {
99
- try {
100
- return node && node.requireFromFile && (await node.requireFromFile(libraryUrl));
101
- }
102
- catch {
103
- return null;
104
- }
105
- }
106
- if (globals_1.isWorker) {
107
- return importScripts(libraryUrl);
108
- }
109
- // TODO - fix - should be more secure than string parsing since observes CORS
110
- // if (isBrowser) {
111
- // return await loadScriptFromFile(libraryUrl);
112
- // }
113
- const scriptSource = await loadAsText(libraryUrl);
114
- return loadLibraryFromString(scriptSource, libraryUrl);
115
- }
116
- /*
117
- async function loadScriptFromFile(libraryUrl) {
118
- const script = document.createElement('script');
119
- script.src = libraryUrl;
120
- return await new Promise((resolve, reject) => {
121
- script.onload = data => {
122
- resolve(data);
123
- };
124
- script.onerror = reject;
125
- });
126
- }
127
- */
128
- // TODO - Needs security audit...
129
- // - Raw eval call
130
- // - Potentially bypasses CORS
131
- // Upside is that this separates fetching and parsing
132
- // we could create a`LibraryLoader` or`ModuleLoader`
133
- function loadLibraryFromString(scriptSource, id) {
134
- if (!globals_1.isBrowser) {
135
- return node.requireFromString && node.requireFromString(scriptSource, id);
136
- }
137
- if (globals_1.isWorker) {
138
- // Use lvalue trick to make eval run in global scope
139
- eval.call(globals_1.global, scriptSource); // eslint-disable-line no-eval
140
- // https://stackoverflow.com/questions/9107240/1-evalthis-vs-evalthis-in-javascript
141
- // http://perfectionkills.com/global-eval-what-are-the-options/
142
- return null;
143
- }
144
- const script = document.createElement('script');
145
- script.id = id;
146
- // most browsers like a separate text node but some throw an error. The second method covers those.
147
- try {
148
- script.appendChild(document.createTextNode(scriptSource));
149
- }
150
- catch (e) {
151
- script.text = scriptSource;
152
- }
153
- document.body.appendChild(script);
154
- return null;
155
- }
156
- // TODO - technique for module injection into worker, from THREE.DracoLoader...
157
- /*
158
- function combineWorkerWithLibrary(worker, jsContent) {
159
- var fn = wWorker.toString();
160
- var body = [
161
- '// injected',
162
- jsContent,
163
- '',
164
- '// worker',
165
- fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))
166
- ].join('\n');
167
- this.workerSourceURL = URL.createObjectURL(new Blob([body]));
168
- }
169
- */
170
- async function loadAsArrayBuffer(url) {
171
- if (!node.readFileAsArrayBuffer || url.startsWith('http')) {
172
- const response = await fetch(url);
173
- return await response.arrayBuffer();
174
- }
175
- return await node.readFileAsArrayBuffer(url);
176
- }
177
- /**
178
- * Load a file from local file system
179
- * @param filename
180
- * @returns
181
- */
182
- async function loadAsText(url) {
183
- if (!node.readFileAsText || url.startsWith('http')) {
184
- const response = await fetch(url);
185
- return await response.text();
186
- }
187
- return await node.readFileAsText(url);
188
- }
@@ -1,89 +0,0 @@
1
- "use strict";
2
- // Fork of https://github.com/floatdrop/require-from-string/blob/master/index.js
3
- // Copyright (c) Vsevolod Strukchinsky <floatdrop@gmail.com> (github.com/floatdrop)
4
- // MIT license
5
- var __importDefault = (this && this.__importDefault) || function (mod) {
6
- return (mod && mod.__esModule) ? mod : { "default": mod };
7
- };
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.requireFromString = exports.requireFromFile = exports.readFileAsText = exports.readFileAsArrayBuffer = void 0;
10
- // this file is not visible to webpack (it is excluded in the package.json "browser" field).
11
- const module_1 = __importDefault(require("module"));
12
- const path_1 = __importDefault(require("path"));
13
- const fs_1 = __importDefault(require("fs"));
14
- /**
15
- * Load a file from local file system
16
- * @param filename
17
- * @returns
18
- */
19
- async function readFileAsArrayBuffer(filename) {
20
- if (filename.startsWith('http')) {
21
- const response = await fetch(filename);
22
- return await response.arrayBuffer();
23
- }
24
- const buffer = fs_1.default.readFileSync(filename);
25
- return buffer.buffer;
26
- }
27
- exports.readFileAsArrayBuffer = readFileAsArrayBuffer;
28
- /**
29
- * Load a file from local file system
30
- * @param filename
31
- * @returns
32
- */
33
- async function readFileAsText(filename) {
34
- if (filename.startsWith('http')) {
35
- const response = await fetch(filename);
36
- return await response.text();
37
- }
38
- const text = fs_1.default.readFileSync(filename, 'utf8');
39
- return text;
40
- }
41
- exports.readFileAsText = readFileAsText;
42
- // Node.js Dynamically require from file
43
- // Relative names are resolved relative to cwd
44
- // This indirect function is provided because webpack will try to bundle `module.require`.
45
- // this file is not visible to webpack (it is excluded in the package.json "browser" field).
46
- async function requireFromFile(filename) {
47
- if (filename.startsWith('http')) {
48
- const response = await fetch(filename);
49
- const code = await response.text();
50
- return requireFromString(code);
51
- }
52
- if (!filename.startsWith('/')) {
53
- filename = `${process.cwd()}/${filename}`;
54
- }
55
- return require(filename);
56
- }
57
- exports.requireFromFile = requireFromFile;
58
- // Dynamically require from string
59
- // - `code` - Required - Type: string - Module code.
60
- // - `filename` - Type: string - Default: '' - Optional filename.
61
- // - `options.appendPaths` Type: Array List of paths, that will be appended to module paths.
62
- // Useful, when you want to be able require modules from these paths.
63
- // - `options.prependPaths` Type: Array Same as appendPaths, but paths will be prepended.
64
- function requireFromString(code, filename = '', options) {
65
- if (typeof filename === 'object') {
66
- options = filename;
67
- filename = '';
68
- }
69
- if (typeof code !== 'string') {
70
- throw new Error(`code must be a string, not ${typeof code}`);
71
- }
72
- // @ts-ignore
73
- const paths = module_1.default._nodeModulePaths(path_1.default.dirname(filename));
74
- const parent = module.parent;
75
- // @ts-ignore
76
- const newModule = new module_1.default(filename, parent);
77
- newModule.filename = filename;
78
- newModule.paths = []
79
- .concat(options?.prependPaths || [])
80
- .concat(paths)
81
- .concat(options?.appendPaths || []);
82
- // @ts-ignore
83
- newModule._compile(code, filename);
84
- if (parent && parent.children) {
85
- parent.children.splice(parent.children.indexOf(newModule), 1);
86
- }
87
- return newModule.exports;
88
- }
89
- exports.requireFromString = requireFromString;
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parentPort = exports.NodeWorkerType = exports.NodeWorker = exports.Worker = void 0;
4
- // Browser fills for Node.js built-in `worker_threads` module.
5
- // These fills are non-functional, and just intended to ensure that
6
- // `import 'worker_threads` doesn't break browser builds.
7
- // The replacement is done in package.json browser field
8
- class Worker {
9
- // eslint-disable-next-line @typescript-eslint/no-empty-function
10
- terminate() { }
11
- }
12
- exports.Worker = Worker;
13
- exports.NodeWorker = Worker;
14
- exports.NodeWorkerType = Worker;
15
- exports.parentPort = null;
@@ -1,33 +0,0 @@
1
- "use strict";
2
- // loaders.gl, MIT license
3
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
- if (k2 === undefined) k2 = k;
5
- var desc = Object.getOwnPropertyDescriptor(m, k);
6
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
- desc = { enumerable: true, get: function() { return m[k]; } };
8
- }
9
- Object.defineProperty(o, k2, desc);
10
- }) : (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- o[k2] = m[k];
13
- }));
14
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
- Object.defineProperty(o, "default", { enumerable: true, value: v });
16
- }) : function(o, v) {
17
- o["default"] = v;
18
- });
19
- var __importStar = (this && this.__importStar) || function (mod) {
20
- if (mod && mod.__esModule) return mod;
21
- var result = {};
22
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
23
- __setModuleDefault(result, mod);
24
- return result;
25
- };
26
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
27
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
28
- };
29
- Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.NodeWorker = void 0;
31
- const WorkerThreads = __importStar(require("worker_threads"));
32
- __exportStar(require("worker_threads"), exports);
33
- exports.NodeWorker = WorkerThreads.Worker;
@@ -1,136 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- /* eslint-disable no-console */
27
- // Avoid using named imports for Node builtins to help with "empty" resolution
28
- // for bundlers targeting browser environments. Access imports & types
29
- // through the `ChildProcess` object (e.g. `ChildProcess.spawn`, `ChildProcess.ChildProcess`).
30
- const ChildProcess = __importStar(require("child_process"));
31
- const process_utils_1 = require("./process-utils");
32
- const DEFAULT_PROPS = {
33
- command: '',
34
- arguments: [],
35
- port: 5000,
36
- autoPort: true,
37
- wait: 2000,
38
- onSuccess: (processProxy) => {
39
- console.log(`Started ${processProxy.props.command}`);
40
- }
41
- };
42
- /**
43
- * Manager for a Node.js child process
44
- * Prepares arguments, starts, stops and tracks output
45
- */
46
- class ChildProcessProxy {
47
- // constructor(props?: {id?: string});
48
- constructor({ id = 'browser-driver' } = {}) {
49
- this.props = { ...DEFAULT_PROPS };
50
- this.childProcess = null;
51
- this.port = 0;
52
- this.id = id;
53
- }
54
- /** Starts a child process with the provided props */
55
- async start(props) {
56
- props = { ...DEFAULT_PROPS, ...props };
57
- this.props = props;
58
- const args = [...props.arguments];
59
- // If portArg is set, we can look up an available port
60
- this.port = Number(props.port);
61
- if (props.portArg) {
62
- if (props.autoPort) {
63
- this.port = await (0, process_utils_1.getAvailablePort)(props.port);
64
- }
65
- args.push(props.portArg, String(this.port));
66
- }
67
- return await new Promise((resolve, reject) => {
68
- try {
69
- this._setTimeout(() => {
70
- if (props.onSuccess) {
71
- props.onSuccess(this);
72
- }
73
- resolve({});
74
- });
75
- console.log(`Spawning ${props.command} ${props.arguments.join(' ')}`);
76
- const childProcess = ChildProcess.spawn(props.command, args, props.spawn);
77
- this.childProcess = childProcess;
78
- childProcess.stdout.on('data', (data) => {
79
- console.log(data.toString());
80
- });
81
- childProcess.stderr.on('data', (data) => {
82
- console.log(`Child process wrote to stderr: "${data}".`);
83
- if (!props.ignoreStderr) {
84
- this._clearTimeout();
85
- reject(new Error(data));
86
- }
87
- });
88
- childProcess.on('error', (error) => {
89
- console.log(`Child process errored with ${error}`);
90
- this._clearTimeout();
91
- reject(error);
92
- });
93
- childProcess.on('close', (code) => {
94
- console.log(`Child process exited with ${code}`);
95
- this.childProcess = null;
96
- this._clearTimeout();
97
- resolve({});
98
- });
99
- }
100
- catch (error) {
101
- reject(error);
102
- }
103
- });
104
- }
105
- /** Stops a running child process */
106
- async stop() {
107
- if (this.childProcess) {
108
- this.childProcess.kill();
109
- this.childProcess = null;
110
- }
111
- }
112
- /** Exits this process */
113
- async exit(statusCode = 0) {
114
- try {
115
- await this.stop();
116
- // eslint-disable-next-line no-process-exit
117
- process.exit(statusCode);
118
- }
119
- catch (error) {
120
- console.error(error.message || error);
121
- // eslint-disable-next-line no-process-exit
122
- process.exit(1);
123
- }
124
- }
125
- _setTimeout(callback) {
126
- if (Number(this.props.wait) > 0) {
127
- this.successTimer = setTimeout(callback, this.props.wait);
128
- }
129
- }
130
- _clearTimeout() {
131
- if (this.successTimer) {
132
- clearTimeout(this.successTimer);
133
- }
134
- }
135
- }
136
- exports.default = ChildProcessProxy;
@@ -1,35 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getAvailablePort = void 0;
7
- const child_process_1 = __importDefault(require("child_process"));
8
- // Get an available port
9
- // Works on Unix systems
10
- function getAvailablePort(defaultPort = 3000) {
11
- return new Promise((resolve) => {
12
- // Get a list of all ports in use
13
- child_process_1.default.exec('lsof -i -P -n | grep LISTEN', (error, stdout) => {
14
- if (error) {
15
- // likely no permission, e.g. CI
16
- resolve(defaultPort);
17
- return;
18
- }
19
- const portsInUse = [];
20
- const regex = /:(\d+) \(LISTEN\)/;
21
- stdout.split('\n').forEach((line) => {
22
- const match = regex.exec(line);
23
- if (match) {
24
- portsInUse.push(Number(match[1]));
25
- }
26
- });
27
- let port = defaultPort;
28
- while (portsInUse.includes(port)) {
29
- port++;
30
- }
31
- resolve(port);
32
- });
33
- });
34
- }
35
- exports.getAvailablePort = getAvailablePort;
@@ -1,91 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.createWorker = void 0;
7
- const async_queue_1 = __importDefault(require("../async-queue/async-queue"));
8
- const worker_body_1 = __importDefault(require("../worker-farm/worker-body"));
9
- // import {validateWorkerVersion} from './validate-worker-version';
10
- /** Counter for jobs */
11
- let requestId = 0;
12
- let inputBatches;
13
- let options;
14
- /**
15
- * Set up a WebWorkerGlobalScope to talk with the main thread
16
- */
17
- function createWorker(process, processInBatches) {
18
- if (!worker_body_1.default.inWorkerThread()) {
19
- return;
20
- }
21
- const context = {
22
- process: processOnMainThread
23
- };
24
- // eslint-disable-next-line complexity
25
- worker_body_1.default.onmessage = async (type, payload) => {
26
- try {
27
- switch (type) {
28
- case 'process':
29
- if (!process) {
30
- throw new Error('Worker does not support atomic processing');
31
- }
32
- const result = await process(payload.input, payload.options || {}, context);
33
- worker_body_1.default.postMessage('done', { result });
34
- break;
35
- case 'process-in-batches':
36
- if (!processInBatches) {
37
- throw new Error('Worker does not support batched processing');
38
- }
39
- inputBatches = new async_queue_1.default();
40
- options = payload.options || {};
41
- const resultIterator = processInBatches(inputBatches, options, context);
42
- for await (const batch of resultIterator) {
43
- worker_body_1.default.postMessage('output-batch', { result: batch });
44
- }
45
- worker_body_1.default.postMessage('done', {});
46
- break;
47
- case 'input-batch':
48
- inputBatches.push(payload.input);
49
- break;
50
- case 'input-done':
51
- inputBatches.close();
52
- break;
53
- default:
54
- }
55
- }
56
- catch (error) {
57
- const message = error instanceof Error ? error.message : '';
58
- worker_body_1.default.postMessage('error', { error: message });
59
- }
60
- };
61
- }
62
- exports.createWorker = createWorker;
63
- function processOnMainThread(arrayBuffer, options = {}) {
64
- return new Promise((resolve, reject) => {
65
- const id = requestId++;
66
- /**
67
- */
68
- const onMessage = (type, payload) => {
69
- if (payload.id !== id) {
70
- // not ours
71
- return;
72
- }
73
- switch (type) {
74
- case 'done':
75
- worker_body_1.default.removeEventListener(onMessage);
76
- resolve(payload.result);
77
- break;
78
- case 'error':
79
- worker_body_1.default.removeEventListener(onMessage);
80
- reject(payload.error);
81
- break;
82
- default:
83
- // ignore
84
- }
85
- };
86
- worker_body_1.default.addEventListener(onMessage);
87
- // Ask the main thread to decode data
88
- const payload = { id, input: arrayBuffer, options };
89
- worker_body_1.default.postMessage('process', payload);
90
- });
91
- }