@rushstack/worker-pool 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ @rushstack/worker-pool
2
+
3
+ Copyright (c) Microsoft Corporation. All rights reserved.
4
+
5
+ MIT License
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining
8
+ a copy of this software and associated documentation files (the
9
+ "Software"), to deal in the Software without restriction, including
10
+ without limitation the rights to use, copy, modify, merge, publish,
11
+ distribute, sublicense, and/or sell copies of the Software, and to
12
+ permit persons to whom the Software is furnished to do so, subject to
13
+ the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be
16
+ included in all copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,12 @@
1
+ # @rushstack/worker-pool
2
+
3
+ This library contains a lightweight worker pool using the NodeJS worker_threads API.
4
+
5
+ ## Links
6
+
7
+ - [CHANGELOG.md](
8
+ https://github.com/microsoft/rushstack/blob/main/libraries/worker-pool/CHANGELOG.md) - Find
9
+ out what's new in the latest version
10
+ - [API Reference](https://rushstack.io/pages/api/worker-pool/)
11
+
12
+ `@rushstack/worker-pool` is part of the [Rush Stack](https://rushstack.io/) family of projects.
@@ -0,0 +1,11 @@
1
+ // This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2
+ // It should be published with your NPM package. It should not be tracked by Git.
3
+ {
4
+ "tsdocVersion": "0.12",
5
+ "toolPackages": [
6
+ {
7
+ "packageName": "@microsoft/api-extractor",
8
+ "packageVersion": "7.24.1"
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,107 @@
1
+ /// <reference types="node" />
2
+
3
+ import { Worker } from 'worker_threads';
4
+
5
+ /**
6
+ * @internal
7
+ */
8
+ export declare interface IWorkerPoolOptions {
9
+ /**
10
+ * Identifier for this pool, to assign to its workers for tracking
11
+ */
12
+ id: string;
13
+ /**
14
+ * Maximum number of concurrent workers this WorkerPool may spawn.
15
+ */
16
+ maxWorkers: number;
17
+ /**
18
+ * Optional callback invoked when a worker is destroyed.
19
+ */
20
+ onWorkerDestroyed?: () => void;
21
+ /**
22
+ * Optional callback invoked on a newly created worker.
23
+ */
24
+ prepareWorker?: (worker: Worker) => void;
25
+ /**
26
+ * Optional data to pass to workers when they are initialized.
27
+ * Will be subjected to the Structured Clone algorithm.
28
+ */
29
+ workerData?: unknown;
30
+ /**
31
+ * Absolute path to the worker script.
32
+ */
33
+ workerScriptPath: string;
34
+ }
35
+
36
+ /**
37
+ * Symbol to read the ID off of a worker
38
+ * @internal
39
+ */
40
+ export declare const WORKER_ID_SYMBOL: unique symbol;
41
+
42
+ /**
43
+ * Manages a pool of workers.
44
+ * Workers will be shutdown by sending them the boolean value `false` in a postMessage.
45
+ * @internal
46
+ */
47
+ export declare class WorkerPool {
48
+ id: string;
49
+ maxWorkers: number;
50
+ private readonly _alive;
51
+ private _error;
52
+ private _finishing;
53
+ private readonly _idle;
54
+ private _nextId;
55
+ private readonly _onComplete;
56
+ private readonly _onWorkerDestroyed;
57
+ private readonly _pending;
58
+ private readonly _prepare;
59
+ private readonly _workerData;
60
+ private readonly _workerScript;
61
+ constructor(options: IWorkerPoolOptions);
62
+ /**
63
+ * Gets the count of active workers.
64
+ */
65
+ getActiveCount(): number;
66
+ /**
67
+ * Gets the count of idle workers.
68
+ */
69
+ getIdleCount(): number;
70
+ /**
71
+ * Gets the count of live workers.
72
+ */
73
+ getLiveCount(): number;
74
+ /**
75
+ * Tells the pool to shut down when all workers are done.
76
+ * Returns a promise that will be fulfilled if all workers finish successfully, or reject with the first error.
77
+ */
78
+ finishAsync(): Promise<void>;
79
+ /**
80
+ * Resets the pool and allows more work
81
+ */
82
+ reset(): void;
83
+ /**
84
+ * Returns a worker to the pool. If the pool is finishing, deallocates the worker.
85
+ * @param worker - The worker to free
86
+ */
87
+ checkinWorker(worker: Worker): void;
88
+ /**
89
+ * Checks out a currently available worker or waits for the next free worker.
90
+ * @param allowCreate - If creating new workers is allowed (subject to maxSize)
91
+ */
92
+ checkoutWorkerAsync(allowCreate: boolean): Promise<Worker>;
93
+ /**
94
+ * Creates a new worker if allowed by maxSize.
95
+ */
96
+ private _createWorker;
97
+ /**
98
+ * Cleans up a worker
99
+ */
100
+ private _destroyWorker;
101
+ /**
102
+ * Notifies all pending callbacks that an error has occurred and switches this pool into error state.
103
+ */
104
+ private _onError;
105
+ }
106
+
107
+ export { }
@@ -0,0 +1,102 @@
1
+ /// <reference types="node" />
2
+ import { Worker } from 'worker_threads';
3
+ /**
4
+ * Symbol to read the ID off of a worker
5
+ * @internal
6
+ */
7
+ export declare const WORKER_ID_SYMBOL: unique symbol;
8
+ /**
9
+ * @internal
10
+ */
11
+ export interface IWorkerPoolOptions {
12
+ /**
13
+ * Identifier for this pool, to assign to its workers for tracking
14
+ */
15
+ id: string;
16
+ /**
17
+ * Maximum number of concurrent workers this WorkerPool may spawn.
18
+ */
19
+ maxWorkers: number;
20
+ /**
21
+ * Optional callback invoked when a worker is destroyed.
22
+ */
23
+ onWorkerDestroyed?: () => void;
24
+ /**
25
+ * Optional callback invoked on a newly created worker.
26
+ */
27
+ prepareWorker?: (worker: Worker) => void;
28
+ /**
29
+ * Optional data to pass to workers when they are initialized.
30
+ * Will be subjected to the Structured Clone algorithm.
31
+ */
32
+ workerData?: unknown;
33
+ /**
34
+ * Absolute path to the worker script.
35
+ */
36
+ workerScriptPath: string;
37
+ }
38
+ /**
39
+ * Manages a pool of workers.
40
+ * Workers will be shutdown by sending them the boolean value `false` in a postMessage.
41
+ * @internal
42
+ */
43
+ export declare class WorkerPool {
44
+ id: string;
45
+ maxWorkers: number;
46
+ private readonly _alive;
47
+ private _error;
48
+ private _finishing;
49
+ private readonly _idle;
50
+ private _nextId;
51
+ private readonly _onComplete;
52
+ private readonly _onWorkerDestroyed;
53
+ private readonly _pending;
54
+ private readonly _prepare;
55
+ private readonly _workerData;
56
+ private readonly _workerScript;
57
+ constructor(options: IWorkerPoolOptions);
58
+ /**
59
+ * Gets the count of active workers.
60
+ */
61
+ getActiveCount(): number;
62
+ /**
63
+ * Gets the count of idle workers.
64
+ */
65
+ getIdleCount(): number;
66
+ /**
67
+ * Gets the count of live workers.
68
+ */
69
+ getLiveCount(): number;
70
+ /**
71
+ * Tells the pool to shut down when all workers are done.
72
+ * Returns a promise that will be fulfilled if all workers finish successfully, or reject with the first error.
73
+ */
74
+ finishAsync(): Promise<void>;
75
+ /**
76
+ * Resets the pool and allows more work
77
+ */
78
+ reset(): void;
79
+ /**
80
+ * Returns a worker to the pool. If the pool is finishing, deallocates the worker.
81
+ * @param worker - The worker to free
82
+ */
83
+ checkinWorker(worker: Worker): void;
84
+ /**
85
+ * Checks out a currently available worker or waits for the next free worker.
86
+ * @param allowCreate - If creating new workers is allowed (subject to maxSize)
87
+ */
88
+ checkoutWorkerAsync(allowCreate: boolean): Promise<Worker>;
89
+ /**
90
+ * Creates a new worker if allowed by maxSize.
91
+ */
92
+ private _createWorker;
93
+ /**
94
+ * Cleans up a worker
95
+ */
96
+ private _destroyWorker;
97
+ /**
98
+ * Notifies all pending callbacks that an error has occurred and switches this pool into error state.
99
+ */
100
+ private _onError;
101
+ }
102
+ //# sourceMappingURL=WorkerPool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WorkerPool.d.ts","sourceR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AAO,CAAC,IAAI,CAAC;IAqBzC;;OAEG;IACI,KAAK,IAAI,IAAI;IAKpB;;;OAGG;IACI,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAqB1C;;;OAGG;IACU,mBAAmB,CAAC,WAAW,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IAmBvE;;OAEG;IACH,OAAO,CAAC,aAAa;IAoCrB;;OAEG;IACH,OAAO,CAAC,cAAc;IAwBtB;;OAEG;IACH,OAAO,CAAC,QAAQ;CAWjB"}
@@ -0,0 +1,187 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
3
+ // See LICENSE in the project root for license information.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.WorkerPool = exports.WORKER_ID_SYMBOL = void 0;
6
+ const worker_threads_1 = require("worker_threads");
7
+ /**
8
+ * Symbol to read the ID off of a worker
9
+ * @internal
10
+ */
11
+ exports.WORKER_ID_SYMBOL = Symbol('workerId');
12
+ /**
13
+ * Manages a pool of workers.
14
+ * Workers will be shutdown by sending them the boolean value `false` in a postMessage.
15
+ * @internal
16
+ */
17
+ class WorkerPool {
18
+ constructor(options) {
19
+ const { id, maxWorkers, onWorkerDestroyed, prepareWorker, workerData, workerScriptPath } = options;
20
+ this.id = id;
21
+ this.maxWorkers = maxWorkers;
22
+ this._alive = [];
23
+ this._error = undefined;
24
+ this._finishing = false;
25
+ this._idle = [];
26
+ this._nextId = 0;
27
+ this._onComplete = [];
28
+ this._onWorkerDestroyed = onWorkerDestroyed;
29
+ this._pending = [];
30
+ this._prepare = prepareWorker;
31
+ this._workerData = workerData;
32
+ this._workerScript = workerScriptPath;
33
+ }
34
+ /**
35
+ * Gets the count of active workers.
36
+ */
37
+ getActiveCount() {
38
+ return this._alive.length - this._idle.length;
39
+ }
40
+ /**
41
+ * Gets the count of idle workers.
42
+ */
43
+ getIdleCount() {
44
+ return this._idle.length;
45
+ }
46
+ /**
47
+ * Gets the count of live workers.
48
+ */
49
+ getLiveCount() {
50
+ return this._alive.length;
51
+ }
52
+ /**
53
+ * Tells the pool to shut down when all workers are done.
54
+ * Returns a promise that will be fulfilled if all workers finish successfully, or reject with the first error.
55
+ */
56
+ async finishAsync() {
57
+ this._finishing = true;
58
+ if (this._error) {
59
+ throw this._error;
60
+ }
61
+ if (!this._alive.length) {
62
+ // The pool has no live workers, this is a no-op
63
+ return;
64
+ }
65
+ // Clean up all idle workers
66
+ for (const worker of this._idle.splice(0)) {
67
+ worker.postMessage(false);
68
+ }
69
+ // There are still active workers, wait for them to clean up.
70
+ await new Promise((resolve, reject) => this._onComplete.push([resolve, reject]));
71
+ }
72
+ /**
73
+ * Resets the pool and allows more work
74
+ */
75
+ reset() {
76
+ this._finishing = false;
77
+ this._error = undefined;
78
+ }
79
+ /**
80
+ * Returns a worker to the pool. If the pool is finishing, deallocates the worker.
81
+ * @param worker - The worker to free
82
+ */
83
+ checkinWorker(worker) {
84
+ if (this._error) {
85
+ // Shut down the worker (failure)
86
+ worker.postMessage(false);
87
+ return;
88
+ }
89
+ const next = this._pending.shift();
90
+ if (next) {
91
+ // Perform the next unit of work;
92
+ next[0](worker);
93
+ }
94
+ else if (this._finishing) {
95
+ // Shut down the worker (success)
96
+ worker.postMessage(false);
97
+ }
98
+ else {
99
+ // No pending work, idle the workers
100
+ this._idle.push(worker);
101
+ }
102
+ }
103
+ /**
104
+ * Checks out a currently available worker or waits for the next free worker.
105
+ * @param allowCreate - If creating new workers is allowed (subject to maxSize)
106
+ */
107
+ async checkoutWorkerAsync(allowCreate) {
108
+ if (this._error) {
109
+ throw this._error;
110
+ }
111
+ let worker = this._idle.shift();
112
+ if (!worker && allowCreate) {
113
+ worker = this._createWorker();
114
+ }
115
+ if (worker) {
116
+ return worker;
117
+ }
118
+ return await new Promise((resolve, reject) => {
119
+ this._pending.push([resolve, reject]);
120
+ });
121
+ }
122
+ /**
123
+ * Creates a new worker if allowed by maxSize.
124
+ */
125
+ _createWorker() {
126
+ if (this._alive.length >= this.maxWorkers) {
127
+ return;
128
+ }
129
+ const worker = new worker_threads_1.Worker(this._workerScript, {
130
+ eval: false,
131
+ workerData: this._workerData
132
+ });
133
+ const id = `${this.id}#${++this._nextId}`;
134
+ worker[exports.WORKER_ID_SYMBOL] = id;
135
+ this._alive.push(worker);
136
+ worker.on('error', (err) => {
137
+ this._onError(err);
138
+ this._destroyWorker(worker);
139
+ });
140
+ worker.on('exit', (exitCode) => {
141
+ if (exitCode !== 0) {
142
+ this._onError(new Error(`Worker ${id} exited with code ${exitCode}`));
143
+ }
144
+ this._destroyWorker(worker);
145
+ });
146
+ if (this._prepare) {
147
+ this._prepare(worker);
148
+ }
149
+ return worker;
150
+ }
151
+ /**
152
+ * Cleans up a worker
153
+ */
154
+ _destroyWorker(worker) {
155
+ const aliveIndex = this._alive.indexOf(worker);
156
+ if (aliveIndex >= 0) {
157
+ this._alive.splice(aliveIndex, 1);
158
+ }
159
+ const freeIndex = this._idle.indexOf(worker);
160
+ if (freeIndex >= 0) {
161
+ this._idle.splice(freeIndex, 1);
162
+ }
163
+ worker.unref();
164
+ if (this._onWorkerDestroyed) {
165
+ this._onWorkerDestroyed();
166
+ }
167
+ if (!this._alive.length && !this._error) {
168
+ for (const [resolve] of this._onComplete.splice(0)) {
169
+ resolve();
170
+ }
171
+ }
172
+ }
173
+ /**
174
+ * Notifies all pending callbacks that an error has occurred and switches this pool into error state.
175
+ */
176
+ _onError(error) {
177
+ this._error = error;
178
+ for (const [, reject] of this._pending.splice(0)) {
179
+ reject(this._error);
180
+ }
181
+ for (const [, reject] of this._onComplete.splice(0)) {
182
+ reject(this._error);
183
+ }
184
+ }
185
+ }
186
+ exports.WorkerPool = WorkerPool;
187
+ //# sourceMappingURL=WorkerPool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WorkerPool.js","sourceRoot":"","sources":["../src/WorkerPool.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAE3D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ACrB;QAED,KAAK,MAAM,CAAC,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE;YACnD,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;SACrB;IACH,CAAC;CACF;AAxND,gCAwNC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport { Worker } from 'worker_threads';\n\n/**\n * Symbol to read the ID off of a worker\n * @internal\n */\nexport const WORKER_ID_SYMBOL: unique symbol = Symbol('workerId');\n\n/**\n * @internal\n */\nexport interface IWorkerPoolOptions {\n /**\n * Identifier for this pool, to assign to its workers for tracking\n */\n id: string;\n /**\n * Maximum number of concurrent workers this WorkerPool may spawn.\n */\n maxWorkers: number;\n /**\n * Optional callback invoked when a worker is destroyed.\n */\n onWorkerDestroyed?: () => void;\n /**\n * Optional callback invoked on a newly created worker.\n */\n prepareWorker?: (worker: Worker) => void;\n /**\n * Optional data to pass to workers when they are initialized.\n * Will be subjected to the Structured Clone algorithm.\n */\n workerData?: unknown;\n /**\n * Absolute path to the worker script.\n */\n workerScriptPath: string;\n}\n\n/**\n * Manages a pool of workers.\n * Workers will be shutdown by sending them the boolean value `false` in a postMessage.\n * @internal\n */\nexport class WorkerPool {\n public id: string;\n public maxWorkers: number;\n\n private readonly _alive: Worker[];\n private _error: Error | undefined;\n private _finishing: boolean;\n private readonly _idle: Worker[];\n private _nextId: number;\n private readonly _onComplete: [() => void, (error: Error) => void][];\n private readonly _onWorkerDestroyed: (() => void) | undefined;\n private readonly _pending: [(worker: Worker) => void, (error: Error) => void][];\n private readonly _prepare: ((worker: Worker) => void) | undefined;\n private readonly _workerData: unknown;\n private readonly _workerScript: string;\n\n public constructor(options: IWorkerPoolOptions) {\n const { id, maxWorkers, onWorkerDestroyed, prepareWorker, workerData, workerScriptPath } = options;\n\n this.id = id;\n this.maxWorkers = maxWorkers;\n this._alive = [];\n this._error = undefined;\n this._finishing = false;\n this._idle = [];\n this._nextId = 0;\n this._onComplete = [];\n this._onWorkerDestroyed = onWorkerDestroyed;\n this._pending = [];\n this._prepare = prepareWorker;\n this._workerData = workerData;\n this._workerScript = workerScriptPath;\n }\n\n /**\n * Gets the count of active workers.\n */\n public getActiveCount(): number {\n return this._alive.length - this._idle.length;\n }\n\n /**\n * Gets the count of idle workers.\n */\n public getIdleCount(): number {\n return this._idle.length;\n }\n\n /**\n * Gets the count of live workers.\n */\n public getLiveCount(): number {\n return this._alive.length;\n }\n\n /**\n * Tells the pool to shut down when all workers are done.\n * Returns a promise that will be fulfilled if all workers finish successfully, or reject with the first error.\n */\n public async finishAsync(): Promise<void> {\n this._finishing = true;\n\n if (this._error) {\n throw this._error;\n }\n\n if (!this._alive.length) {\n // The pool has no live workers, this is a no-op\n return;\n }\n\n // Clean up all idle workers\n for (const worker of this._idle.splice(0)) {\n worker.postMessage(false);\n }\n\n // There are still active workers, wait for them to clean up.\n await new Promise<void>((resolve, reject) => this._onComplete.push([resolve, reject]));\n }\n\n /**\n * Resets the pool and allows more work\n */\n public reset(): void {\n this._finishing = false;\n this._error = undefined;\n }\n\n /**\n * Returns a worker to the pool. If the pool is finishing, deallocates the worker.\n * @param worker - The worker to free\n */\n public checkinWorker(worker: Worker): void {\n if (this._error) {\n // Shut down the worker (failure)\n worker.postMessage(false);\n return;\n }\n\n const next: [(worker: Worker) => void, unknown] | undefined = this._pending.shift();\n\n if (next) {\n // Perform the next unit of work;\n next[0](worker);\n } else if (this._finishing) {\n // Shut down the worker (success)\n worker.postMessage(false);\n } else {\n // No pending work, idle the workers\n this._idle.push(worker);\n }\n }\n\n /**\n * Checks out a currently available worker or waits for the next free worker.\n * @param allowCreate - If creating new workers is allowed (subject to maxSize)\n */\n public async checkoutWorkerAsync(allowCreate: boolean): Promise<Worker> {\n if (this._error) {\n throw this._error;\n }\n\n let worker: Worker | undefined = this._idle.shift();\n if (!worker && allowCreate) {\n worker = this._createWorker();\n }\n\n if (worker) {\n return worker;\n }\n\n return await new Promise((resolve: (worker: Worker) => void, reject: (error: Error) => void) => {\n this._pending.push([resolve, reject]);\n });\n }\n\n /**\n * Creates a new worker if allowed by maxSize.\n */\n private _createWorker(): Worker | undefined {\n if (this._alive.length >= this.maxWorkers) {\n return;\n }\n\n const worker: Worker & {\n [WORKER_ID_SYMBOL]?: string;\n } = new Worker(this._workerScript, {\n eval: false,\n workerData: this._workerData\n });\n\n const id: string = `${this.id}#${++this._nextId}`;\n worker[WORKER_ID_SYMBOL] = id;\n\n this._alive.push(worker);\n\n worker.on('error', (err) => {\n this._onError(err);\n this._destroyWorker(worker);\n });\n\n worker.on('exit', (exitCode) => {\n if (exitCode !== 0) {\n this._onError(new Error(`Worker ${id} exited with code ${exitCode}`));\n }\n this._destroyWorker(worker);\n });\n\n if (this._prepare) {\n this._prepare(worker);\n }\n\n return worker;\n }\n\n /**\n * Cleans up a worker\n */\n private _destroyWorker(worker: Worker): void {\n const aliveIndex: number = this._alive.indexOf(worker);\n if (aliveIndex >= 0) {\n this._alive.splice(aliveIndex, 1);\n }\n\n const freeIndex: number = this._idle.indexOf(worker);\n if (freeIndex >= 0) {\n this._idle.splice(freeIndex, 1);\n }\n\n worker.unref();\n\n if (this._onWorkerDestroyed) {\n this._onWorkerDestroyed();\n }\n\n if (!this._alive.length && !this._error) {\n for (const [resolve] of this._onComplete.splice(0)) {\n resolve();\n }\n }\n }\n\n /**\n * Notifies all pending callbacks that an error has occurred and switches this pool into error state.\n */\n private _onError(error: Error): void {\n this._error = error;\n\n for (const [, reject] of this._pending.splice(0)) {\n reject(this._error);\n }\n\n for (const [, reject] of this._onComplete.splice(0)) {\n reject(this._error);\n }\n }\n}\n"]}
package/lib/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export type { IWorkerPoolOptions } from './WorkerPool';
2
+ export { WORKER_ID_SYMBOL, WorkerPool } from './WorkerPool';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,YAAY,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC"}
package/lib/index.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
3
+ // See LICENSE in the project root for license information.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.WorkerPool = exports.WORKER_ID_SYMBOL = void 0;
6
+ var WorkerPool_1 = require("./WorkerPool");
7
+ Object.defineProperty(exports, "WORKER_ID_SYMBOL", { enumerable: true, get: function () { return WorkerPool_1.WORKER_ID_SYMBOL; } });
8
+ Object.defineProperty(exports, "WorkerPool", { enumerable: true, get: function () { return WorkerPool_1.WorkerPool; } });
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;AAG3D,2CAA4D;AAAnD,8GAAA,gBAAgB,OAAA;AAAE,wGAAA,UAAU,OAAA","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nexport type { IWorkerPoolOptions } from './WorkerPool';\nexport { WORKER_ID_SYMBOL, WorkerPool } from './WorkerPool';\n"]}
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@rushstack/worker-pool",
3
+ "version": "0.1.0",
4
+ "description": "Lightweight worker pool using NodeJS worker_threads",
5
+ "main": "lib/index.js",
6
+ "typings": "dist/worker-pool.d.ts",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "url": "https://github.com/microsoft/rushstack.git",
10
+ "type": "git",
11
+ "directory": "libraries/worker-pool"
12
+ },
13
+ "dependencies": {
14
+ "@types/node": "12.20.24"
15
+ },
16
+ "devDependencies": {
17
+ "@rushstack/eslint-config": "2.6.0",
18
+ "@rushstack/heft": "0.45.4",
19
+ "@rushstack/heft-node-rig": "1.9.5",
20
+ "@types/heft-jest": "1.0.1"
21
+ },
22
+ "scripts": {
23
+ "build": "heft build --clean",
24
+ "_phase:build": "heft build --clean",
25
+ "_phase:test": "heft test --no-build"
26
+ },
27
+ "readme": "# @rushstack/worker-pool\n\nThis library contains a lightweight worker pool using the NodeJS worker_threads API.\n\n## Links\n\n- [CHANGELOG.md](\n https://github.com/microsoft/rushstack/blob/main/libraries/worker-pool/CHANGELOG.md) - Find\n out what's new in the latest version\n- [API Reference](https://rushstack.io/pages/api/worker-pool/)\n\n`@rushstack/worker-pool` is part of the [Rush Stack](https://rushstack.io/) family of projects.\n"
28
+ }