@rspress/core 2.0.8 → 2.0.10

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