@olegkuibar/plunk 0.2.0-canary.04ff96f

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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +95 -0
  3. package/dist/add-5ZRFUL6Z.mjs +258 -0
  4. package/dist/chokidar-XGAEDN45.mjs +1746 -0
  5. package/dist/chunk-34UXZ622.mjs +98 -0
  6. package/dist/chunk-4O2QOKVO.mjs +1958 -0
  7. package/dist/chunk-CSMZ6DZA.mjs +367 -0
  8. package/dist/chunk-CZM4TNAI.mjs +292 -0
  9. package/dist/chunk-EDUXIQ5W.mjs +1729 -0
  10. package/dist/chunk-GAAB2TLH.mjs +160 -0
  11. package/dist/chunk-HKNM3UWU.mjs +496 -0
  12. package/dist/chunk-I6SN7BBN.mjs +1131 -0
  13. package/dist/chunk-KYDBD2KQ.mjs +39 -0
  14. package/dist/chunk-LKQINKH4.mjs +130 -0
  15. package/dist/chunk-PUSXMPOF.mjs +82 -0
  16. package/dist/chunk-S4HJSJ32.mjs +69 -0
  17. package/dist/chunk-W3C72UKC.mjs +113 -0
  18. package/dist/chunk-WSECI6M7.mjs +85 -0
  19. package/dist/chunk-XMIZ7OUZ.mjs +26 -0
  20. package/dist/chunk-XZK5T4GK.mjs +23 -0
  21. package/dist/chunk-ZOYNYK5Y.mjs +23 -0
  22. package/dist/chunk-ZQCGJUBJ.mjs +92 -0
  23. package/dist/clean-LTR5MZTY.mjs +84 -0
  24. package/dist/cli.mjs +57 -0
  25. package/dist/dev-LFXQP6SA.mjs +194 -0
  26. package/dist/dist-DUFCZSIL.mjs +813 -0
  27. package/dist/doctor-R7ZVR7PY.mjs +230 -0
  28. package/dist/hash-worker.mjs +65 -0
  29. package/dist/index.d.ts +194 -0
  30. package/dist/index.mjs +9486 -0
  31. package/dist/init-SWCNRISY.mjs +310 -0
  32. package/dist/list-B77L2F34.mjs +119 -0
  33. package/dist/migrate-X5TIC5SS.mjs +124 -0
  34. package/dist/prompt-HTPH6HQ7.mjs +756 -0
  35. package/dist/publish-UXCLPNM6.mjs +63 -0
  36. package/dist/push-JI6HGCFG.mjs +197 -0
  37. package/dist/remove-DCR7KKD5.mjs +149 -0
  38. package/dist/restore-SUN3WGSW.mjs +124 -0
  39. package/dist/status-MESRBH54.mjs +103 -0
  40. package/dist/tailwind-source-JBBEIXIJ.mjs +89 -0
  41. package/dist/update-SKDSA673.mjs +100 -0
  42. package/dist/vite-config-BAK67JHB.mjs +128 -0
  43. package/dist/vite-plugin.d.ts +5 -0
  44. package/dist/vite-plugin.mjs +42 -0
  45. package/dist/workspace-76HJPAK2.mjs +97 -0
  46. package/package.json +96 -0
@@ -0,0 +1,813 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
3
+ import "./chunk-KYDBD2KQ.mjs";
4
+
5
+ // node_modules/.pnpm/tinypool@2.1.0/node_modules/tinypool/dist/common-Qw-RoVFD.js
6
+ var kMovable = /* @__PURE__ */ Symbol("Tinypool.kMovable");
7
+ var kTransferable = /* @__PURE__ */ Symbol.for("Tinypool.transferable");
8
+ var kValue = /* @__PURE__ */ Symbol.for("Tinypool.valueOf");
9
+ var kQueueOptions = /* @__PURE__ */ Symbol.for("Tinypool.queueOptions");
10
+ function isTransferable(value) {
11
+ return value != null && typeof value === "object" && kTransferable in value && kValue in value;
12
+ }
13
+ function isMovable(value) {
14
+ return isTransferable(value) && value[kMovable] === true;
15
+ }
16
+ function markMovable(value) {
17
+ Object.defineProperty(value, kMovable, {
18
+ enumerable: false,
19
+ configurable: true,
20
+ writable: true,
21
+ value: true
22
+ });
23
+ }
24
+ function isTaskQueue(value) {
25
+ return typeof value === "object" && value !== null && "size" in value && typeof value.shift === "function" && typeof value.remove === "function" && typeof value.push === "function";
26
+ }
27
+ var kRequestCountField = 0;
28
+ var kResponseCountField = 1;
29
+ var kFieldCount = 2;
30
+
31
+ // node_modules/.pnpm/tinypool@2.1.0/node_modules/tinypool/dist/index.js
32
+ import { MessageChannel, MessagePort, Worker, receiveMessageOnPort } from "worker_threads";
33
+ import { EventEmitterAsyncResource, once } from "events";
34
+ import { AsyncResource } from "async_hooks";
35
+ import { URL, fileURLToPath } from "url";
36
+ import { join } from "path";
37
+ import { inspect, types } from "util";
38
+ import assert from "assert";
39
+ import { performance } from "perf_hooks";
40
+ import { readFileSync } from "fs";
41
+ import { availableParallelism } from "os";
42
+ import { fork } from "child_process";
43
+ var ThreadWorker = class {
44
+ name = "ThreadWorker";
45
+ runtime = "worker_threads";
46
+ initialize(options) {
47
+ this.thread = new Worker(fileURLToPath(import.meta.url + "/../entry/worker.js"), options);
48
+ this.threadId = this.thread.threadId;
49
+ }
50
+ async terminate() {
51
+ const output = await this.thread.terminate();
52
+ this.channel?.onClose?.();
53
+ return output;
54
+ }
55
+ postMessage(message, transferListItem) {
56
+ return this.thread.postMessage(message, transferListItem);
57
+ }
58
+ on(event, callback) {
59
+ return this.thread.on(event, callback);
60
+ }
61
+ once(event, callback) {
62
+ return this.thread.once(event, callback);
63
+ }
64
+ emit(event, ...data) {
65
+ return this.thread.emit(event, ...data);
66
+ }
67
+ ref() {
68
+ return this.thread.ref();
69
+ }
70
+ unref() {
71
+ return this.thread.unref();
72
+ }
73
+ setChannel(channel) {
74
+ if (channel.onMessage) throw new Error("{ runtime: 'worker_threads' } doesn't support channel.onMessage. Use transferListItem for listening to messages instead.");
75
+ if (channel.postMessage) throw new Error("{ runtime: 'worker_threads' } doesn't support channel.postMessage. Use transferListItem for sending to messages instead.");
76
+ if (this.channel && this.channel !== channel) this.channel.onClose?.();
77
+ this.channel = channel;
78
+ }
79
+ };
80
+ var __tinypool_worker_message__ = true;
81
+ var SIGKILL_TIMEOUT = 1e3;
82
+ var ProcessWorker = class {
83
+ name = "ProcessWorker";
84
+ runtime = "child_process";
85
+ isTerminating = false;
86
+ initialize(options) {
87
+ this.process = fork(fileURLToPath(import.meta.url + "/../entry/process.js"), options.argv, {
88
+ ...options,
89
+ stdio: "pipe",
90
+ env: {
91
+ ...options.env,
92
+ TINYPOOL_WORKER_ID: options.workerData[0].workerId.toString()
93
+ }
94
+ });
95
+ process.stdout.setMaxListeners(1 + process.stdout.getMaxListeners());
96
+ process.stderr.setMaxListeners(1 + process.stderr.getMaxListeners());
97
+ this.process.stdout?.pipe(process.stdout);
98
+ this.process.stderr?.pipe(process.stderr);
99
+ this.threadId = this.process.pid;
100
+ this.process.on("exit", this.onUnexpectedExit);
101
+ this.waitForExit = new Promise((r) => this.process.on("exit", r));
102
+ }
103
+ onUnexpectedExit = () => {
104
+ this.process.emit("error", new Error("Worker exited unexpectedly"));
105
+ };
106
+ async terminate() {
107
+ this.isTerminating = true;
108
+ this.process.off("exit", this.onUnexpectedExit);
109
+ const sigkillTimeout = setTimeout(() => this.process.kill("SIGKILL"), SIGKILL_TIMEOUT);
110
+ this.process.kill();
111
+ await this.waitForExit;
112
+ this.process.stdout?.unpipe(process.stdout);
113
+ this.process.stderr?.unpipe(process.stderr);
114
+ this.port?.close();
115
+ this.channel?.onClose?.();
116
+ clearTimeout(sigkillTimeout);
117
+ }
118
+ setChannel(channel) {
119
+ if (this.channel && this.channel !== channel) this.channel.onClose?.();
120
+ this.channel = channel;
121
+ this.channel.onMessage?.((message) => {
122
+ this.send(message);
123
+ });
124
+ }
125
+ send(message) {
126
+ if (!this.isTerminating) this.process.send(message);
127
+ }
128
+ postMessage(message, transferListItem) {
129
+ transferListItem?.forEach((item) => {
130
+ if (item instanceof MessagePort) {
131
+ this.port = item;
132
+ this.port.start();
133
+ }
134
+ });
135
+ if (this.port) this.port.on("message", (message$1) => this.send({
136
+ ...message$1,
137
+ source: "port",
138
+ __tinypool_worker_message__
139
+ }));
140
+ return this.send({
141
+ ...message,
142
+ source: "pool",
143
+ __tinypool_worker_message__
144
+ });
145
+ }
146
+ on(event, callback) {
147
+ return this.process.on(event, (data) => {
148
+ if (event === "error") return callback(data);
149
+ if (!data || !data.__tinypool_worker_message__) return this.channel?.postMessage?.(data);
150
+ if (data.source === "pool") callback(data);
151
+ else if (data.source === "port") this.port.postMessage(data);
152
+ });
153
+ }
154
+ once(event, callback) {
155
+ return this.process.once(event, callback);
156
+ }
157
+ emit(event, ...data) {
158
+ return this.process.emit(event, ...data);
159
+ }
160
+ ref() {
161
+ return this.process.ref();
162
+ }
163
+ unref() {
164
+ this.port?.unref();
165
+ this.process.channel?.unref?.();
166
+ if (hasUnref(this.process.stdout)) this.process.stdout.unref();
167
+ if (hasUnref(this.process.stderr)) this.process.stderr.unref();
168
+ return this.process.unref();
169
+ }
170
+ };
171
+ function hasUnref(stream) {
172
+ return stream != null && "unref" in stream && typeof stream.unref === "function";
173
+ }
174
+ var cpuCount = availableParallelism();
175
+ function onabort(abortSignal, listener) {
176
+ if ("addEventListener" in abortSignal) abortSignal.addEventListener("abort", listener, { once: true });
177
+ else abortSignal.once("abort", listener);
178
+ }
179
+ var AbortError = class extends Error {
180
+ constructor() {
181
+ super("The task has been aborted");
182
+ }
183
+ get name() {
184
+ return "AbortError";
185
+ }
186
+ };
187
+ var CancelError = class extends Error {
188
+ constructor() {
189
+ super("The task has been cancelled");
190
+ }
191
+ get name() {
192
+ return "CancelError";
193
+ }
194
+ };
195
+ var ArrayTaskQueue = class {
196
+ tasks = [];
197
+ get size() {
198
+ return this.tasks.length;
199
+ }
200
+ shift() {
201
+ return this.tasks.shift();
202
+ }
203
+ push(task) {
204
+ this.tasks.push(task);
205
+ }
206
+ remove(task) {
207
+ const index = this.tasks.indexOf(task);
208
+ assert.notStrictEqual(index, -1);
209
+ this.tasks.splice(index, 1);
210
+ }
211
+ cancel() {
212
+ while (this.tasks.length > 0) {
213
+ const task = this.tasks.pop();
214
+ task?.cancel();
215
+ }
216
+ }
217
+ };
218
+ var kDefaultOptions = {
219
+ filename: null,
220
+ name: "default",
221
+ runtime: "worker_threads",
222
+ minThreads: Math.max(cpuCount / 2, 1),
223
+ maxThreads: cpuCount,
224
+ idleTimeout: 0,
225
+ maxQueue: Infinity,
226
+ concurrentTasksPerWorker: 1,
227
+ useAtomics: true,
228
+ taskQueue: new ArrayTaskQueue(),
229
+ trackUnmanagedFds: true
230
+ };
231
+ var kDefaultRunOptions = {
232
+ transferList: void 0,
233
+ filename: null,
234
+ signal: null,
235
+ name: null
236
+ };
237
+ var DirectlyTransferable = class {
238
+ #value;
239
+ constructor(value) {
240
+ this.#value = value;
241
+ }
242
+ get [kTransferable]() {
243
+ return this.#value;
244
+ }
245
+ get [kValue]() {
246
+ return this.#value;
247
+ }
248
+ };
249
+ var ArrayBufferViewTransferable = class {
250
+ #view;
251
+ constructor(view) {
252
+ this.#view = view;
253
+ }
254
+ get [kTransferable]() {
255
+ return this.#view.buffer;
256
+ }
257
+ get [kValue]() {
258
+ return this.#view;
259
+ }
260
+ };
261
+ var taskIdCounter = 0;
262
+ function maybeFileURLToPath(filename) {
263
+ return filename.startsWith("file:") ? fileURLToPath(new URL(filename)) : filename;
264
+ }
265
+ var TaskInfo = class extends AsyncResource {
266
+ abortListener = null;
267
+ workerInfo = null;
268
+ constructor(task, transferList, filename, name, callback, abortSignal, triggerAsyncId, channel) {
269
+ super("Tinypool.Task", {
270
+ requireManualDestroy: true,
271
+ triggerAsyncId
272
+ });
273
+ this.callback = callback;
274
+ this.task = task;
275
+ this.transferList = transferList;
276
+ this.cancel = () => this.callback(new CancelError(), null);
277
+ this.channel = channel;
278
+ if (isMovable(task)) {
279
+ if (this.transferList == null) this.transferList = [];
280
+ this.transferList = this.transferList.concat(task[kTransferable]);
281
+ this.task = task[kValue];
282
+ }
283
+ this.filename = filename;
284
+ this.name = name;
285
+ this.taskId = taskIdCounter++;
286
+ this.abortSignal = abortSignal;
287
+ this.created = performance.now();
288
+ this.started = 0;
289
+ }
290
+ releaseTask() {
291
+ const ret = this.task;
292
+ this.task = null;
293
+ return ret;
294
+ }
295
+ done(err, result) {
296
+ this.emitDestroy();
297
+ this.runInAsyncScope(this.callback, null, err, result);
298
+ if (this.abortSignal && this.abortListener) if ("removeEventListener" in this.abortSignal && this.abortListener) this.abortSignal.removeEventListener("abort", this.abortListener);
299
+ else this.abortSignal.off("abort", this.abortListener);
300
+ }
301
+ get [kQueueOptions]() {
302
+ return kQueueOptions in this.task ? this.task[kQueueOptions] : null;
303
+ }
304
+ };
305
+ var AsynchronouslyCreatedResource = class {
306
+ onreadyListeners = [];
307
+ markAsReady() {
308
+ const listeners = this.onreadyListeners;
309
+ assert(listeners !== null);
310
+ this.onreadyListeners = null;
311
+ for (const listener of listeners) listener();
312
+ }
313
+ isReady() {
314
+ return this.onreadyListeners === null;
315
+ }
316
+ onReady(fn) {
317
+ if (this.onreadyListeners === null) {
318
+ fn();
319
+ return;
320
+ }
321
+ this.onreadyListeners.push(fn);
322
+ }
323
+ };
324
+ var AsynchronouslyCreatedResourcePool = class {
325
+ pendingItems = /* @__PURE__ */ new Set();
326
+ readyItems = /* @__PURE__ */ new Set();
327
+ constructor(maximumUsage) {
328
+ this.maximumUsage = maximumUsage;
329
+ this.onAvailableListeners = [];
330
+ }
331
+ add(item) {
332
+ this.pendingItems.add(item);
333
+ item.onReady(() => {
334
+ if (this.pendingItems.has(item)) {
335
+ this.pendingItems.delete(item);
336
+ this.readyItems.add(item);
337
+ this.maybeAvailable(item);
338
+ }
339
+ });
340
+ }
341
+ delete(item) {
342
+ this.pendingItems.delete(item);
343
+ this.readyItems.delete(item);
344
+ }
345
+ findAvailable() {
346
+ let minUsage = this.maximumUsage;
347
+ let candidate = null;
348
+ for (const item of this.readyItems) {
349
+ const usage = item.currentUsage();
350
+ if (usage === 0) return item;
351
+ if (usage < minUsage) {
352
+ candidate = item;
353
+ minUsage = usage;
354
+ }
355
+ }
356
+ return candidate;
357
+ }
358
+ *[Symbol.iterator]() {
359
+ yield* this.pendingItems;
360
+ yield* this.readyItems;
361
+ }
362
+ get size() {
363
+ return this.pendingItems.size + this.readyItems.size;
364
+ }
365
+ maybeAvailable(item) {
366
+ if (item.currentUsage() < this.maximumUsage) for (const listener of this.onAvailableListeners) listener(item);
367
+ }
368
+ onAvailable(fn) {
369
+ this.onAvailableListeners.push(fn);
370
+ }
371
+ };
372
+ var Errors = {
373
+ ThreadTermination: () => new Error("Terminating worker thread"),
374
+ FilenameNotProvided: () => new Error("filename must be provided to run() or in options object"),
375
+ TaskQueueAtLimit: () => new Error("Task queue is at limit"),
376
+ NoTaskQueueAvailable: () => new Error("No task queue available and all Workers are busy")
377
+ };
378
+ var WorkerInfo = class extends AsynchronouslyCreatedResource {
379
+ idleTimeout = null;
380
+ lastSeenResponseCount = 0;
381
+ constructor(worker, port, workerId, freeWorkerId, onMessage, filename, teardown) {
382
+ super();
383
+ this.worker = worker;
384
+ this.workerId = workerId;
385
+ this.freeWorkerId = freeWorkerId;
386
+ this.teardown = teardown;
387
+ this.filename = filename;
388
+ this.port = port;
389
+ this.port.on("message", (message) => this._handleResponse(message));
390
+ this.onMessage = onMessage;
391
+ this.taskInfos = /* @__PURE__ */ new Map();
392
+ this.sharedBuffer = new Int32Array(new SharedArrayBuffer(kFieldCount * Int32Array.BYTES_PER_ELEMENT));
393
+ }
394
+ async destroy(timeout) {
395
+ let resolve;
396
+ let reject;
397
+ const ret = new Promise((res, rej) => {
398
+ resolve = res;
399
+ reject = rej;
400
+ });
401
+ if (this.teardown && this.filename) {
402
+ const { teardown, filename } = this;
403
+ await new Promise((resolve$1, reject$1) => {
404
+ this.postTask(new TaskInfo({}, [], filename, teardown, (error, result) => error ? reject$1(error) : resolve$1(result), null, 1, void 0));
405
+ });
406
+ }
407
+ const timer = timeout ? setTimeout(() => reject(new Error("Failed to terminate worker")), timeout) : null;
408
+ this.worker.terminate().then(() => {
409
+ if (timer !== null) clearTimeout(timer);
410
+ this.port.close();
411
+ this.clearIdleTimeout();
412
+ for (const taskInfo of this.taskInfos.values()) taskInfo.done(Errors.ThreadTermination());
413
+ this.taskInfos.clear();
414
+ resolve();
415
+ });
416
+ return ret;
417
+ }
418
+ clearIdleTimeout() {
419
+ if (this.idleTimeout !== null) {
420
+ clearTimeout(this.idleTimeout);
421
+ this.idleTimeout = null;
422
+ }
423
+ }
424
+ ref() {
425
+ this.port.ref();
426
+ return this;
427
+ }
428
+ unref() {
429
+ this.port.unref();
430
+ return this;
431
+ }
432
+ _handleResponse(message) {
433
+ this.usedMemory = message.usedMemory;
434
+ this.onMessage(message);
435
+ if (this.taskInfos.size === 0) this.unref();
436
+ }
437
+ postTask(taskInfo) {
438
+ assert(!this.taskInfos.has(taskInfo.taskId));
439
+ const message = {
440
+ task: taskInfo.releaseTask(),
441
+ taskId: taskInfo.taskId,
442
+ filename: taskInfo.filename,
443
+ name: taskInfo.name
444
+ };
445
+ try {
446
+ if (taskInfo.channel) this.worker.setChannel?.(taskInfo.channel);
447
+ this.port.postMessage(message, taskInfo.transferList);
448
+ } catch (err) {
449
+ taskInfo.done(err);
450
+ return;
451
+ }
452
+ taskInfo.workerInfo = this;
453
+ this.taskInfos.set(taskInfo.taskId, taskInfo);
454
+ this.ref();
455
+ this.clearIdleTimeout();
456
+ Atomics.add(this.sharedBuffer, kRequestCountField, 1);
457
+ Atomics.notify(this.sharedBuffer, kRequestCountField, 1);
458
+ }
459
+ processPendingMessages() {
460
+ const actualResponseCount = Atomics.load(this.sharedBuffer, kResponseCountField);
461
+ if (actualResponseCount !== this.lastSeenResponseCount) {
462
+ this.lastSeenResponseCount = actualResponseCount;
463
+ let entry;
464
+ while ((entry = receiveMessageOnPort(this.port)) !== void 0) this._handleResponse(entry.message);
465
+ }
466
+ }
467
+ isRunningAbortableTask() {
468
+ if (this.taskInfos.size !== 1) return false;
469
+ const [first] = this.taskInfos;
470
+ const [, task] = first || [];
471
+ return task?.abortSignal !== null;
472
+ }
473
+ currentUsage() {
474
+ if (this.isRunningAbortableTask()) return Infinity;
475
+ return this.taskInfos.size;
476
+ }
477
+ };
478
+ var ThreadPool = class {
479
+ skipQueue = [];
480
+ completed = 0;
481
+ start = performance.now();
482
+ inProcessPendingMessages = false;
483
+ startingUp = false;
484
+ workerFailsDuringBootstrap = false;
485
+ constructor(publicInterface, options) {
486
+ this.publicInterface = publicInterface;
487
+ this.taskQueue = options.taskQueue || new ArrayTaskQueue();
488
+ const filename = options.filename ? maybeFileURLToPath(options.filename) : null;
489
+ this.options = {
490
+ ...kDefaultOptions,
491
+ ...options,
492
+ filename,
493
+ maxQueue: 0
494
+ };
495
+ if (options.maxThreads !== void 0 && this.options.minThreads >= options.maxThreads) this.options.minThreads = options.maxThreads;
496
+ if (options.minThreads !== void 0 && this.options.maxThreads <= options.minThreads) this.options.maxThreads = options.minThreads;
497
+ if (options.maxQueue === "auto") this.options.maxQueue = this.options.maxThreads ** 2;
498
+ else this.options.maxQueue = options.maxQueue ?? kDefaultOptions.maxQueue;
499
+ this.workerIds = new Map(new Array(this.options.maxThreads).fill(0).map((_, i) => [i + 1, true]));
500
+ this.workers = new AsynchronouslyCreatedResourcePool(this.options.concurrentTasksPerWorker);
501
+ this.workers.onAvailable((w) => this._onWorkerAvailable(w));
502
+ this.startingUp = true;
503
+ this._ensureMinimumWorkers();
504
+ this.startingUp = false;
505
+ }
506
+ _ensureEnoughWorkersForTaskQueue() {
507
+ while (this.workers.size < this.taskQueue.size && this.workers.size < this.options.maxThreads) this._addNewWorker();
508
+ }
509
+ _ensureMaximumWorkers() {
510
+ while (this.workers.size < this.options.maxThreads) this._addNewWorker();
511
+ }
512
+ _ensureMinimumWorkers() {
513
+ while (this.workers.size < this.options.minThreads) this._addNewWorker();
514
+ }
515
+ _addNewWorker() {
516
+ const workerIds = this.workerIds;
517
+ let workerId;
518
+ workerIds.forEach((isIdAvailable, _workerId$1) => {
519
+ if (isIdAvailable && !workerId) {
520
+ workerId = _workerId$1;
521
+ workerIds.set(_workerId$1, false);
522
+ }
523
+ });
524
+ const tinypoolPrivateData = { workerId };
525
+ const worker = this.options.runtime === "child_process" ? new ProcessWorker() : new ThreadWorker();
526
+ worker.initialize({
527
+ env: this.options.env,
528
+ argv: this.options.argv,
529
+ execArgv: this.options.execArgv,
530
+ resourceLimits: this.options.resourceLimits,
531
+ workerData: [tinypoolPrivateData, this.options.workerData],
532
+ trackUnmanagedFds: this.options.trackUnmanagedFds,
533
+ serialization: this.options.serialization
534
+ });
535
+ const onMessage = (message$1) => {
536
+ const { taskId, result } = message$1;
537
+ const taskInfo = workerInfo.taskInfos.get(taskId);
538
+ workerInfo.taskInfos.delete(taskId);
539
+ if (!this.shouldRecycleWorker(taskInfo)) this.workers.maybeAvailable(workerInfo);
540
+ if (taskInfo === void 0) {
541
+ const err = new Error(`Unexpected message from Worker: ${inspect(message$1)}`);
542
+ this.publicInterface.emit("error", err);
543
+ } else taskInfo.done(message$1.error, result);
544
+ this._processPendingMessages();
545
+ };
546
+ const { port1, port2 } = new MessageChannel();
547
+ const workerInfo = new WorkerInfo(worker, port1, workerId, () => workerIds.set(workerId, true), onMessage, this.options.filename, this.options.teardown);
548
+ if (this.startingUp) workerInfo.markAsReady();
549
+ const message = {
550
+ filename: this.options.filename,
551
+ name: this.options.name,
552
+ port: port2,
553
+ sharedBuffer: workerInfo.sharedBuffer,
554
+ useAtomics: this.options.useAtomics
555
+ };
556
+ worker.postMessage(message, [port2]);
557
+ worker.on("message", (message$1) => {
558
+ if (message$1.ready === true) {
559
+ port1.start();
560
+ if (workerInfo.currentUsage() === 0) workerInfo.unref();
561
+ if (!workerInfo.isReady()) workerInfo.markAsReady();
562
+ return;
563
+ }
564
+ worker.emit("error", new Error(`Unexpected message on Worker: ${inspect(message$1)}`));
565
+ });
566
+ worker.on("error", (err) => {
567
+ worker.ref = () => {
568
+ };
569
+ const taskInfos = [...workerInfo.taskInfos.values()];
570
+ workerInfo.taskInfos.clear();
571
+ this._removeWorker(workerInfo);
572
+ if (workerInfo.isReady() && !this.workerFailsDuringBootstrap) this._ensureMinimumWorkers();
573
+ else this.workerFailsDuringBootstrap = true;
574
+ if (taskInfos.length > 0) for (const taskInfo of taskInfos) taskInfo.done(err, null);
575
+ else this.publicInterface.emit("error", err);
576
+ });
577
+ worker.unref();
578
+ port1.on("close", () => {
579
+ worker.ref();
580
+ });
581
+ this.workers.add(workerInfo);
582
+ }
583
+ _processPendingMessages() {
584
+ if (this.inProcessPendingMessages || !this.options.useAtomics) return;
585
+ this.inProcessPendingMessages = true;
586
+ try {
587
+ for (const workerInfo of this.workers) workerInfo.processPendingMessages();
588
+ } finally {
589
+ this.inProcessPendingMessages = false;
590
+ }
591
+ }
592
+ _removeWorker(workerInfo) {
593
+ workerInfo.freeWorkerId();
594
+ this.workers.delete(workerInfo);
595
+ return workerInfo.destroy(this.options.terminateTimeout);
596
+ }
597
+ _onWorkerAvailable(workerInfo) {
598
+ while ((this.taskQueue.size > 0 || this.skipQueue.length > 0) && workerInfo.currentUsage() < this.options.concurrentTasksPerWorker) {
599
+ const taskInfo = this.skipQueue.shift() || this.taskQueue.shift();
600
+ if (taskInfo.abortSignal && workerInfo.taskInfos.size > 0) {
601
+ this.skipQueue.push(taskInfo);
602
+ break;
603
+ }
604
+ const now = performance.now();
605
+ taskInfo.started = now;
606
+ workerInfo.postTask(taskInfo);
607
+ this._maybeDrain();
608
+ return;
609
+ }
610
+ if (workerInfo.taskInfos.size === 0 && this.workers.size > this.options.minThreads) workerInfo.idleTimeout = setTimeout(() => {
611
+ assert.strictEqual(workerInfo.taskInfos.size, 0);
612
+ if (this.workers.size > this.options.minThreads) this._removeWorker(workerInfo);
613
+ }, this.options.idleTimeout).unref();
614
+ }
615
+ runTask(task, options) {
616
+ let { filename, name } = options;
617
+ const { transferList = [], signal = null, channel } = options;
618
+ if (filename == null) filename = this.options.filename;
619
+ if (name == null) name = this.options.name;
620
+ if (typeof filename !== "string") return Promise.reject(Errors.FilenameNotProvided());
621
+ filename = maybeFileURLToPath(filename);
622
+ let resolve;
623
+ let reject;
624
+ const ret = new Promise((res, rej) => {
625
+ resolve = res;
626
+ reject = rej;
627
+ });
628
+ const taskInfo = new TaskInfo(task, transferList, filename, name, (err, result) => {
629
+ this.completed++;
630
+ if (err !== null) reject(err);
631
+ if (this.shouldRecycleWorker(taskInfo)) this._removeWorker(taskInfo.workerInfo).then(() => this._ensureMinimumWorkers()).then(() => this._ensureEnoughWorkersForTaskQueue()).then(() => resolve(result)).catch(reject);
632
+ else resolve(result);
633
+ }, signal, this.publicInterface.asyncResource.asyncId(), channel);
634
+ if (signal !== null) {
635
+ if (signal.aborted) return Promise.reject(new AbortError());
636
+ taskInfo.abortListener = () => {
637
+ reject(new AbortError());
638
+ if (taskInfo.workerInfo !== null) {
639
+ this._removeWorker(taskInfo.workerInfo);
640
+ this._ensureMinimumWorkers();
641
+ } else this.taskQueue.remove(taskInfo);
642
+ };
643
+ onabort(signal, taskInfo.abortListener);
644
+ }
645
+ if (this.taskQueue.size > 0) {
646
+ const totalCapacity = this.options.maxQueue + this.pendingCapacity();
647
+ if (this.taskQueue.size >= totalCapacity) if (this.options.maxQueue === 0) return Promise.reject(Errors.NoTaskQueueAvailable());
648
+ else return Promise.reject(Errors.TaskQueueAtLimit());
649
+ else {
650
+ if (this.workers.size < this.options.maxThreads) this._addNewWorker();
651
+ this.taskQueue.push(taskInfo);
652
+ }
653
+ return ret;
654
+ }
655
+ let workerInfo = this.workers.findAvailable();
656
+ if (workerInfo !== null && workerInfo.currentUsage() > 0 && signal) workerInfo = null;
657
+ let waitingForNewWorker = false;
658
+ if ((workerInfo === null || workerInfo.currentUsage() > 0) && this.workers.size < this.options.maxThreads) {
659
+ this._addNewWorker();
660
+ waitingForNewWorker = true;
661
+ }
662
+ if (workerInfo === null) {
663
+ if (this.options.maxQueue <= 0 && !waitingForNewWorker) return Promise.reject(Errors.NoTaskQueueAvailable());
664
+ else this.taskQueue.push(taskInfo);
665
+ return ret;
666
+ }
667
+ const now = performance.now();
668
+ taskInfo.started = now;
669
+ workerInfo.postTask(taskInfo);
670
+ this._maybeDrain();
671
+ return ret;
672
+ }
673
+ shouldRecycleWorker(taskInfo) {
674
+ if (taskInfo?.workerInfo?.shouldRecycle) return true;
675
+ if (this.options.isolateWorkers && taskInfo?.workerInfo) return true;
676
+ if (!this.options.isolateWorkers && this.options.maxMemoryLimitBeforeRecycle !== void 0 && (taskInfo?.workerInfo?.usedMemory || 0) > this.options.maxMemoryLimitBeforeRecycle) return true;
677
+ return false;
678
+ }
679
+ pendingCapacity() {
680
+ return this.workers.pendingItems.size * this.options.concurrentTasksPerWorker;
681
+ }
682
+ _maybeDrain() {
683
+ if (this.taskQueue.size === 0 && this.skipQueue.length === 0) this.publicInterface.emit("drain");
684
+ }
685
+ async destroy() {
686
+ while (this.skipQueue.length > 0) {
687
+ const taskInfo = this.skipQueue.shift();
688
+ taskInfo.done(new Error("Terminating worker thread"));
689
+ }
690
+ while (this.taskQueue.size > 0) {
691
+ const taskInfo = this.taskQueue.shift();
692
+ taskInfo.done(new Error("Terminating worker thread"));
693
+ }
694
+ const exitEvents = [];
695
+ while (this.workers.size > 0) {
696
+ const [workerInfo] = this.workers;
697
+ exitEvents.push(once(workerInfo.worker, "exit"));
698
+ this._removeWorker(workerInfo);
699
+ }
700
+ await Promise.all(exitEvents);
701
+ }
702
+ async recycleWorkers(options = {}) {
703
+ const runtimeChanged = options?.runtime && options.runtime !== this.options.runtime;
704
+ if (options?.runtime) this.options.runtime = options.runtime;
705
+ if (this.options.isolateWorkers && !runtimeChanged) return;
706
+ const exitEvents = [];
707
+ Array.from(this.workers).filter((workerInfo) => {
708
+ if (workerInfo.currentUsage() === 0) {
709
+ exitEvents.push(once(workerInfo.worker, "exit"));
710
+ this._removeWorker(workerInfo);
711
+ } else workerInfo.shouldRecycle = true;
712
+ });
713
+ await Promise.all(exitEvents);
714
+ this._ensureMinimumWorkers();
715
+ }
716
+ };
717
+ var Tinypool = class extends EventEmitterAsyncResource {
718
+ #pool;
719
+ constructor(options = {}) {
720
+ if (options.minThreads !== void 0 && options.minThreads > 0 && options.minThreads < 1) options.minThreads = Math.max(1, Math.floor(options.minThreads * cpuCount));
721
+ if (options.maxThreads !== void 0 && options.maxThreads > 0 && options.maxThreads < 1) options.maxThreads = Math.max(1, Math.floor(options.maxThreads * cpuCount));
722
+ super({
723
+ ...options,
724
+ name: "Tinypool"
725
+ });
726
+ if (options.minThreads !== void 0 && options.maxThreads !== void 0 && options.minThreads > options.maxThreads) throw new RangeError("options.minThreads and options.maxThreads must not conflict");
727
+ this.#pool = new ThreadPool(this, options);
728
+ }
729
+ run(task, options = kDefaultRunOptions) {
730
+ const { transferList, filename, name, signal, runtime, channel } = options;
731
+ return this.#pool.runTask(task, {
732
+ transferList,
733
+ filename,
734
+ name,
735
+ signal,
736
+ runtime,
737
+ channel
738
+ });
739
+ }
740
+ async destroy() {
741
+ await this.#pool.destroy();
742
+ this.emitDestroy();
743
+ }
744
+ get options() {
745
+ return this.#pool.options;
746
+ }
747
+ get threads() {
748
+ const ret = [];
749
+ for (const workerInfo of this.#pool.workers) ret.push(workerInfo.worker);
750
+ return ret;
751
+ }
752
+ get queueSize() {
753
+ const pool = this.#pool;
754
+ return Math.max(pool.taskQueue.size - pool.pendingCapacity(), 0);
755
+ }
756
+ cancelPendingTasks() {
757
+ const pool = this.#pool;
758
+ pool.taskQueue.cancel();
759
+ }
760
+ async recycleWorkers(options = {}) {
761
+ await this.#pool.recycleWorkers(options);
762
+ }
763
+ get completed() {
764
+ return this.#pool.completed;
765
+ }
766
+ get duration() {
767
+ return performance.now() - this.#pool.start;
768
+ }
769
+ static get isWorkerThread() {
770
+ return process.__tinypool_state__?.isWorkerThread || false;
771
+ }
772
+ static get workerData() {
773
+ return process.__tinypool_state__?.workerData || void 0;
774
+ }
775
+ static get version() {
776
+ const { version } = JSON.parse(readFileSync(join(__dirname, "../package.json"), "utf-8"));
777
+ return version;
778
+ }
779
+ static move(val) {
780
+ if (val != null && typeof val === "object" && typeof val !== "function") {
781
+ if (!isTransferable(val)) if (types.isArrayBufferView(val)) val = new ArrayBufferViewTransferable(val);
782
+ else val = new DirectlyTransferable(val);
783
+ markMovable(val);
784
+ }
785
+ return val;
786
+ }
787
+ static get transferableSymbol() {
788
+ return kTransferable;
789
+ }
790
+ static get valueSymbol() {
791
+ return kValue;
792
+ }
793
+ static get queueOptionsSymbol() {
794
+ return kQueueOptions;
795
+ }
796
+ };
797
+ var _workerId = process.__tinypool_state__?.workerId;
798
+ var src_default = Tinypool;
799
+ export {
800
+ Tinypool,
801
+ src_default as default,
802
+ isMovable,
803
+ isTaskQueue,
804
+ isTransferable,
805
+ kFieldCount,
806
+ kQueueOptions,
807
+ kRequestCountField,
808
+ kResponseCountField,
809
+ kTransferable,
810
+ kValue,
811
+ markMovable,
812
+ _workerId as workerId
813
+ };