@kubb/core 4.33.0 → 4.33.1

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 (85) hide show
  1. package/dist/hooks.d.ts +1 -1
  2. package/dist/index.cjs +1695 -82
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.ts +150 -20
  5. package/dist/index.js +1673 -65
  6. package/dist/index.js.map +1 -1
  7. package/dist/{types-f_no0d7G.d.ts → types-DfjjJb2r.d.ts} +70 -27
  8. package/package.json +3 -24
  9. package/src/BarrelManager.ts +10 -31
  10. package/src/PackageManager.ts +13 -21
  11. package/src/PluginManager.ts +65 -87
  12. package/src/PromiseManager.ts +3 -5
  13. package/src/build.ts +61 -47
  14. package/src/config.ts +1 -1
  15. package/src/constants.ts +60 -0
  16. package/src/errors.ts +1 -14
  17. package/src/index.ts +6 -3
  18. package/src/types.ts +5 -14
  19. package/src/utils/FunctionParams.ts +7 -8
  20. package/src/utils/TreeNode.ts +12 -23
  21. package/src/utils/executeStrategies.ts +5 -3
  22. package/src/utils/formatters.ts +3 -20
  23. package/src/utils/getBarrelFiles.ts +8 -2
  24. package/src/utils/getConfigs.ts +6 -15
  25. package/src/utils/getPlugins.ts +7 -7
  26. package/src/utils/linters.ts +3 -20
  27. package/dist/fs-D4eqq6bR.cjs +0 -103
  28. package/dist/fs-D4eqq6bR.cjs.map +0 -1
  29. package/dist/fs-TVBCPkE-.js +0 -67
  30. package/dist/fs-TVBCPkE-.js.map +0 -1
  31. package/dist/fs.cjs +0 -8
  32. package/dist/fs.d.ts +0 -23
  33. package/dist/fs.js +0 -2
  34. package/dist/packageManager-_7I0WFQU.d.ts +0 -82
  35. package/dist/packageManager-jzjuEj2U.cjs +0 -1103
  36. package/dist/packageManager-jzjuEj2U.cjs.map +0 -1
  37. package/dist/packageManager-wMCQlgd6.js +0 -1024
  38. package/dist/packageManager-wMCQlgd6.js.map +0 -1
  39. package/dist/transformers-BwSpAhvT.js +0 -267
  40. package/dist/transformers-BwSpAhvT.js.map +0 -1
  41. package/dist/transformers-BweFhqh-.cjs +0 -380
  42. package/dist/transformers-BweFhqh-.cjs.map +0 -1
  43. package/dist/transformers.cjs +0 -24
  44. package/dist/transformers.d.ts +0 -108
  45. package/dist/transformers.js +0 -2
  46. package/dist/utils.cjs +0 -430
  47. package/dist/utils.cjs.map +0 -1
  48. package/dist/utils.d.ts +0 -290
  49. package/dist/utils.js +0 -402
  50. package/dist/utils.js.map +0 -1
  51. package/src/BaseGenerator.ts +0 -34
  52. package/src/fs/clean.ts +0 -5
  53. package/src/fs/exists.ts +0 -16
  54. package/src/fs/index.ts +0 -5
  55. package/src/fs/read.ts +0 -13
  56. package/src/fs/utils.ts +0 -32
  57. package/src/fs/write.ts +0 -46
  58. package/src/transformers/casing.ts +0 -62
  59. package/src/transformers/combineCodes.ts +0 -3
  60. package/src/transformers/createJSDocBlockText.ts +0 -9
  61. package/src/transformers/escape.ts +0 -31
  62. package/src/transformers/indent.ts +0 -3
  63. package/src/transformers/index.ts +0 -46
  64. package/src/transformers/nameSorter.ts +0 -9
  65. package/src/transformers/searchAndReplace.ts +0 -25
  66. package/src/transformers/stringify.ts +0 -25
  67. package/src/transformers/toRegExp.ts +0 -22
  68. package/src/transformers/transformReservedWord.ts +0 -106
  69. package/src/transformers/trim.ts +0 -18
  70. package/src/utils/AsyncEventEmitter.ts +0 -48
  71. package/src/utils/Cache.ts +0 -31
  72. package/src/utils/URLPath.ts +0 -146
  73. package/src/utils/buildJSDoc.ts +0 -34
  74. package/src/utils/checkOnlineStatus.ts +0 -40
  75. package/src/utils/formatHrtime.ts +0 -33
  76. package/src/utils/getNestedAccessor.ts +0 -25
  77. package/src/utils/index.ts +0 -26
  78. package/src/utils/packageManager.ts +0 -58
  79. package/src/utils/promise.ts +0 -13
  80. package/src/utils/renderTemplate.ts +0 -31
  81. package/src/utils/serializePluginOptions.ts +0 -29
  82. package/src/utils/timeout.ts +0 -11
  83. package/src/utils/tokenize.ts +0 -23
  84. package/src/utils/types.ts +0 -1
  85. package/src/utils/uniqueName.ts +0 -20
@@ -1,1024 +0,0 @@
1
- import "./chunk--u3MIqq1.js";
2
- import { n as getRelativePath } from "./fs-TVBCPkE-.js";
3
- import { f as camelCase, g as trim, v as isValidVarName, y as transformReservedWord } from "./transformers-BwSpAhvT.js";
4
- import path, { join } from "node:path";
5
- import fs from "node:fs";
6
- import { performance } from "node:perf_hooks";
7
- import { EventEmitter } from "node:events";
8
- //#region src/errors.ts
9
- var ValidationPluginError = class extends Error {};
10
- var BuildError = class extends Error {
11
- cause;
12
- errors;
13
- constructor(message, options) {
14
- super(message, { cause: options.cause });
15
- this.name = "BuildError";
16
- this.cause = options.cause;
17
- this.errors = options.errors;
18
- }
19
- };
20
- //#endregion
21
- //#region ../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js
22
- var Node = class {
23
- value;
24
- next;
25
- constructor(value) {
26
- this.value = value;
27
- }
28
- };
29
- var Queue = class {
30
- #head;
31
- #tail;
32
- #size;
33
- constructor() {
34
- this.clear();
35
- }
36
- enqueue(value) {
37
- const node = new Node(value);
38
- if (this.#head) {
39
- this.#tail.next = node;
40
- this.#tail = node;
41
- } else {
42
- this.#head = node;
43
- this.#tail = node;
44
- }
45
- this.#size++;
46
- }
47
- dequeue() {
48
- const current = this.#head;
49
- if (!current) return;
50
- this.#head = this.#head.next;
51
- this.#size--;
52
- if (!this.#head) this.#tail = void 0;
53
- return current.value;
54
- }
55
- peek() {
56
- if (!this.#head) return;
57
- return this.#head.value;
58
- }
59
- clear() {
60
- this.#head = void 0;
61
- this.#tail = void 0;
62
- this.#size = 0;
63
- }
64
- get size() {
65
- return this.#size;
66
- }
67
- *[Symbol.iterator]() {
68
- let current = this.#head;
69
- while (current) {
70
- yield current.value;
71
- current = current.next;
72
- }
73
- }
74
- *drain() {
75
- while (this.#head) yield this.dequeue();
76
- }
77
- };
78
- //#endregion
79
- //#region ../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js
80
- function pLimit(concurrency) {
81
- let rejectOnClear = false;
82
- if (typeof concurrency === "object") ({concurrency, rejectOnClear = false} = concurrency);
83
- validateConcurrency(concurrency);
84
- if (typeof rejectOnClear !== "boolean") throw new TypeError("Expected `rejectOnClear` to be a boolean");
85
- const queue = new Queue();
86
- let activeCount = 0;
87
- const resumeNext = () => {
88
- if (activeCount < concurrency && queue.size > 0) {
89
- activeCount++;
90
- queue.dequeue().run();
91
- }
92
- };
93
- const next = () => {
94
- activeCount--;
95
- resumeNext();
96
- };
97
- const run = async (function_, resolve, arguments_) => {
98
- const result = (async () => function_(...arguments_))();
99
- resolve(result);
100
- try {
101
- await result;
102
- } catch {}
103
- next();
104
- };
105
- const enqueue = (function_, resolve, reject, arguments_) => {
106
- const queueItem = { reject };
107
- new Promise((internalResolve) => {
108
- queueItem.run = internalResolve;
109
- queue.enqueue(queueItem);
110
- }).then(run.bind(void 0, function_, resolve, arguments_));
111
- if (activeCount < concurrency) resumeNext();
112
- };
113
- const generator = (function_, ...arguments_) => new Promise((resolve, reject) => {
114
- enqueue(function_, resolve, reject, arguments_);
115
- });
116
- Object.defineProperties(generator, {
117
- activeCount: { get: () => activeCount },
118
- pendingCount: { get: () => queue.size },
119
- clearQueue: { value() {
120
- if (!rejectOnClear) {
121
- queue.clear();
122
- return;
123
- }
124
- const abortError = AbortSignal.abort().reason;
125
- while (queue.size > 0) queue.dequeue().reject(abortError);
126
- } },
127
- concurrency: {
128
- get: () => concurrency,
129
- set(newConcurrency) {
130
- validateConcurrency(newConcurrency);
131
- concurrency = newConcurrency;
132
- queueMicrotask(() => {
133
- while (activeCount < concurrency && queue.size > 0) resumeNext();
134
- });
135
- }
136
- },
137
- map: { async value(iterable, function_) {
138
- const promises = Array.from(iterable, (value, index) => this(function_, value, index));
139
- return Promise.all(promises);
140
- } }
141
- });
142
- return generator;
143
- }
144
- function validateConcurrency(concurrency) {
145
- if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) throw new TypeError("Expected `concurrency` to be a number from 1 and up");
146
- }
147
- //#endregion
148
- //#region src/utils/executeStrategies.ts
149
- /**
150
- * Chains promises
151
- */
152
- function hookSeq(promises) {
153
- return promises.filter(Boolean).reduce((promise, func) => {
154
- if (typeof func !== "function") throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
155
- return promise.then((state) => {
156
- const calledFunc = func(state);
157
- if (calledFunc) return calledFunc.then(Array.prototype.concat.bind(state));
158
- });
159
- }, Promise.resolve([]));
160
- }
161
- /**
162
- * Chains promises, first non-null result stops and returns
163
- */
164
- function hookFirst(promises, nullCheck = (state) => state !== null) {
165
- let promise = Promise.resolve(null);
166
- for (const func of promises.filter(Boolean)) promise = promise.then((state) => {
167
- if (nullCheck(state)) return state;
168
- return func(state);
169
- });
170
- return promise;
171
- }
172
- /**
173
- * Runs an array of promise functions with optional concurrency limit.
174
- */
175
- function hookParallel(promises, concurrency = Number.POSITIVE_INFINITY) {
176
- const limit = pLimit(concurrency);
177
- const tasks = promises.filter(Boolean).map((promise) => limit(() => promise()));
178
- return Promise.allSettled(tasks);
179
- }
180
- //#endregion
181
- //#region src/PromiseManager.ts
182
- var PromiseManager = class {
183
- #options = {};
184
- constructor(options = {}) {
185
- this.#options = options;
186
- return this;
187
- }
188
- run(strategy, promises, { concurrency = Number.POSITIVE_INFINITY } = {}) {
189
- if (strategy === "seq") return hookSeq(promises);
190
- if (strategy === "first") return hookFirst(promises, this.#options.nullCheck);
191
- if (strategy === "parallel") return hookParallel(promises, concurrency);
192
- throw new Error(`${strategy} not implemented`);
193
- }
194
- };
195
- function isPromiseRejectedResult(result) {
196
- return result.status === "rejected";
197
- }
198
- //#endregion
199
- //#region src/utils/uniqueName.ts
200
- function getUniqueName(originalName, data) {
201
- let used = data[originalName] || 0;
202
- if (used) {
203
- data[originalName] = ++used;
204
- originalName += used;
205
- }
206
- data[originalName] = 1;
207
- return originalName;
208
- }
209
- function setUniqueName(originalName, data) {
210
- let used = data[originalName] || 0;
211
- if (used) {
212
- data[originalName] = ++used;
213
- return originalName;
214
- }
215
- data[originalName] = 1;
216
- return originalName;
217
- }
218
- //#endregion
219
- //#region src/PluginManager.ts
220
- function getMode(fileOrFolder) {
221
- if (!fileOrFolder) return "split";
222
- return path.extname(fileOrFolder) ? "single" : "split";
223
- }
224
- var PluginManager = class {
225
- config;
226
- options;
227
- #plugins = /* @__PURE__ */ new Set();
228
- #usedPluginNames = {};
229
- #promiseManager;
230
- constructor(config, options) {
231
- this.config = config;
232
- this.options = options;
233
- this.#promiseManager = new PromiseManager({ nullCheck: (state) => !!state?.result });
234
- [...config.plugins || []].forEach((plugin) => {
235
- const parsedPlugin = this.#parse(plugin);
236
- this.#plugins.add(parsedPlugin);
237
- });
238
- return this;
239
- }
240
- get events() {
241
- return this.options.events;
242
- }
243
- getContext(plugin) {
244
- const plugins = [...this.#plugins];
245
- const baseContext = {
246
- fabric: this.options.fabric,
247
- config: this.config,
248
- plugin,
249
- events: this.options.events,
250
- pluginManager: this,
251
- mode: getMode(path.resolve(this.config.root, this.config.output.path)),
252
- addFile: async (...files) => {
253
- await this.options.fabric.addFile(...files);
254
- },
255
- upsertFile: async (...files) => {
256
- await this.options.fabric.upsertFile(...files);
257
- }
258
- };
259
- const mergedExtras = {};
260
- for (const p of plugins) if (typeof p.inject === "function") {
261
- const result = p.inject.bind(baseContext)(baseContext);
262
- if (result && typeof result === "object") Object.assign(mergedExtras, result);
263
- }
264
- return {
265
- ...baseContext,
266
- ...mergedExtras
267
- };
268
- }
269
- get plugins() {
270
- return this.#getSortedPlugins();
271
- }
272
- getFile({ name, mode, extname, pluginKey, options }) {
273
- const baseName = `${name}${extname}`;
274
- const path = this.resolvePath({
275
- baseName,
276
- mode,
277
- pluginKey,
278
- options
279
- });
280
- if (!path) throw new Error(`Filepath should be defined for resolvedName "${name}" and pluginKey [${JSON.stringify(pluginKey)}]`);
281
- return {
282
- path,
283
- baseName,
284
- meta: { pluginKey },
285
- sources: [],
286
- imports: [],
287
- exports: []
288
- };
289
- }
290
- resolvePath = (params) => {
291
- const root = path.resolve(this.config.root, this.config.output.path);
292
- const defaultPath = path.resolve(root, params.baseName);
293
- if (params.pluginKey) return this.hookForPluginSync({
294
- pluginKey: params.pluginKey,
295
- hookName: "resolvePath",
296
- parameters: [
297
- params.baseName,
298
- params.mode,
299
- params.options
300
- ]
301
- })?.at(0) || defaultPath;
302
- return this.hookFirstSync({
303
- hookName: "resolvePath",
304
- parameters: [
305
- params.baseName,
306
- params.mode,
307
- params.options
308
- ]
309
- })?.result || defaultPath;
310
- };
311
- resolveName = (params) => {
312
- if (params.pluginKey) {
313
- const names = this.hookForPluginSync({
314
- pluginKey: params.pluginKey,
315
- hookName: "resolveName",
316
- parameters: [trim(params.name), params.type]
317
- });
318
- return transformReservedWord([...new Set(names)].at(0) || params.name);
319
- }
320
- const name = this.hookFirstSync({
321
- hookName: "resolveName",
322
- parameters: [trim(params.name), params.type]
323
- }).result;
324
- return transformReservedWord(name);
325
- };
326
- /**
327
- * Run a specific hookName for plugin x.
328
- */
329
- async hookForPlugin({ pluginKey, hookName, parameters }) {
330
- const plugins = this.getPluginsByKey(hookName, pluginKey);
331
- this.events.emit("plugins:hook:progress:start", {
332
- hookName,
333
- plugins
334
- });
335
- const items = [];
336
- for (const plugin of plugins) {
337
- const result = await this.#execute({
338
- strategy: "hookFirst",
339
- hookName,
340
- parameters,
341
- plugin
342
- });
343
- if (result !== void 0 && result !== null) items.push(result);
344
- }
345
- this.events.emit("plugins:hook:progress:end", { hookName });
346
- return items;
347
- }
348
- /**
349
- * Run a specific hookName for plugin x.
350
- */
351
- hookForPluginSync({ pluginKey, hookName, parameters }) {
352
- return this.getPluginsByKey(hookName, pluginKey).map((plugin) => {
353
- return this.#executeSync({
354
- strategy: "hookFirst",
355
- hookName,
356
- parameters,
357
- plugin
358
- });
359
- }).filter(Boolean);
360
- }
361
- /**
362
- * Returns the first non-null result.
363
- */
364
- async hookFirst({ hookName, parameters, skipped }) {
365
- const plugins = this.#getSortedPlugins(hookName).filter((plugin) => {
366
- return skipped ? skipped.has(plugin) : true;
367
- });
368
- this.events.emit("plugins:hook:progress:start", {
369
- hookName,
370
- plugins
371
- });
372
- const promises = plugins.map((plugin) => {
373
- return async () => {
374
- const value = await this.#execute({
375
- strategy: "hookFirst",
376
- hookName,
377
- parameters,
378
- plugin
379
- });
380
- return Promise.resolve({
381
- plugin,
382
- result: value
383
- });
384
- };
385
- });
386
- const result = await this.#promiseManager.run("first", promises);
387
- this.events.emit("plugins:hook:progress:end", { hookName });
388
- return result;
389
- }
390
- /**
391
- * Returns the first non-null result.
392
- */
393
- hookFirstSync({ hookName, parameters, skipped }) {
394
- let parseResult = null;
395
- const plugins = this.#getSortedPlugins(hookName).filter((plugin) => {
396
- return skipped ? skipped.has(plugin) : true;
397
- });
398
- for (const plugin of plugins) {
399
- parseResult = {
400
- result: this.#executeSync({
401
- strategy: "hookFirst",
402
- hookName,
403
- parameters,
404
- plugin
405
- }),
406
- plugin
407
- };
408
- if (parseResult?.result != null) break;
409
- }
410
- return parseResult;
411
- }
412
- /**
413
- * Runs all plugins in parallel based on `this.plugin` order and `pre`/`post` settings.
414
- */
415
- async hookParallel({ hookName, parameters }) {
416
- const plugins = this.#getSortedPlugins(hookName);
417
- this.events.emit("plugins:hook:progress:start", {
418
- hookName,
419
- plugins
420
- });
421
- const promises = plugins.map((plugin) => {
422
- return () => this.#execute({
423
- strategy: "hookParallel",
424
- hookName,
425
- parameters,
426
- plugin
427
- });
428
- });
429
- const results = await this.#promiseManager.run("parallel", promises, { concurrency: this.options.concurrency });
430
- results.forEach((result, index) => {
431
- if (isPromiseRejectedResult(result)) {
432
- const plugin = this.#getSortedPlugins(hookName)[index];
433
- if (plugin) this.events.emit("error", result.reason, {
434
- plugin,
435
- hookName,
436
- strategy: "hookParallel",
437
- duration: 0,
438
- parameters
439
- });
440
- }
441
- });
442
- this.events.emit("plugins:hook:progress:end", { hookName });
443
- return results.reduce((acc, result) => {
444
- if (result.status === "fulfilled") acc.push(result.value);
445
- return acc;
446
- }, []);
447
- }
448
- /**
449
- * Chains plugins
450
- */
451
- async hookSeq({ hookName, parameters }) {
452
- const plugins = this.#getSortedPlugins(hookName);
453
- this.events.emit("plugins:hook:progress:start", {
454
- hookName,
455
- plugins
456
- });
457
- const promises = plugins.map((plugin) => {
458
- return () => this.#execute({
459
- strategy: "hookSeq",
460
- hookName,
461
- parameters,
462
- plugin
463
- });
464
- });
465
- await this.#promiseManager.run("seq", promises);
466
- this.events.emit("plugins:hook:progress:end", { hookName });
467
- }
468
- #getSortedPlugins(hookName) {
469
- const plugins = [...this.#plugins];
470
- if (hookName) return plugins.filter((plugin) => hookName in plugin);
471
- return plugins.map((plugin) => {
472
- if (plugin.pre) {
473
- const missingPlugins = plugin.pre.filter((pluginName) => !plugins.find((pluginToFind) => pluginToFind.name === pluginName));
474
- if (missingPlugins.length > 0) throw new ValidationPluginError(`The plugin '${plugin.name}' has a pre set that references missing plugins for '${missingPlugins.join(", ")}'`);
475
- }
476
- return plugin;
477
- }).sort((a, b) => {
478
- if (b.pre?.includes(a.name)) return 1;
479
- if (b.post?.includes(a.name)) return -1;
480
- return 0;
481
- });
482
- }
483
- getPluginByKey(pluginKey) {
484
- const plugins = [...this.#plugins];
485
- const [searchPluginName] = pluginKey;
486
- return plugins.find((item) => {
487
- const [name] = item.key;
488
- return name === searchPluginName;
489
- });
490
- }
491
- getPluginsByKey(hookName, pluginKey) {
492
- const plugins = [...this.plugins];
493
- const [searchPluginName, searchIdentifier] = pluginKey;
494
- const pluginByPluginName = plugins.filter((plugin) => hookName in plugin).filter((item) => {
495
- const [name, identifier] = item.key;
496
- const identifierCheck = identifier?.toString() === searchIdentifier?.toString();
497
- const nameCheck = name === searchPluginName;
498
- if (searchIdentifier) return identifierCheck && nameCheck;
499
- return nameCheck;
500
- });
501
- if (!pluginByPluginName?.length) {
502
- const corePlugin = plugins.find((plugin) => plugin.name === "core" && hookName in plugin);
503
- return corePlugin ? [corePlugin] : [];
504
- }
505
- return pluginByPluginName;
506
- }
507
- /**
508
- * Run an async plugin hook and return the result.
509
- * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.
510
- * @param args Arguments passed to the plugin hook.
511
- * @param plugin The actual pluginObject to run.
512
- */
513
- #execute({ strategy, hookName, parameters, plugin }) {
514
- const hook = plugin[hookName];
515
- let output;
516
- if (!hook) return null;
517
- this.events.emit("plugins:hook:processing:start", {
518
- strategy,
519
- hookName,
520
- parameters,
521
- plugin
522
- });
523
- const startTime = performance.now();
524
- return (async () => {
525
- try {
526
- if (typeof hook === "function") {
527
- const context = this.getContext(plugin);
528
- const result = await Promise.resolve(hook.apply(context, parameters));
529
- output = result;
530
- this.events.emit("plugins:hook:processing:end", {
531
- duration: Math.round(performance.now() - startTime),
532
- parameters,
533
- output,
534
- strategy,
535
- hookName,
536
- plugin
537
- });
538
- return result;
539
- }
540
- output = hook;
541
- this.events.emit("plugins:hook:processing:end", {
542
- duration: Math.round(performance.now() - startTime),
543
- parameters,
544
- output,
545
- strategy,
546
- hookName,
547
- plugin
548
- });
549
- return hook;
550
- } catch (error) {
551
- this.events.emit("error", error, {
552
- plugin,
553
- hookName,
554
- strategy,
555
- duration: Math.round(performance.now() - startTime)
556
- });
557
- return null;
558
- }
559
- })();
560
- }
561
- /**
562
- * Run a sync plugin hook and return the result.
563
- * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
564
- * @param args Arguments passed to the plugin hook.
565
- * @param plugin The actual plugin
566
- * @param replaceContext When passed, the plugin context can be overridden.
567
- */
568
- #executeSync({ strategy, hookName, parameters, plugin }) {
569
- const hook = plugin[hookName];
570
- let output;
571
- if (!hook) return null;
572
- this.events.emit("plugins:hook:processing:start", {
573
- strategy,
574
- hookName,
575
- parameters,
576
- plugin
577
- });
578
- const startTime = performance.now();
579
- try {
580
- if (typeof hook === "function") {
581
- const context = this.getContext(plugin);
582
- const fn = hook.apply(context, parameters);
583
- output = fn;
584
- this.events.emit("plugins:hook:processing:end", {
585
- duration: Math.round(performance.now() - startTime),
586
- parameters,
587
- output,
588
- strategy,
589
- hookName,
590
- plugin
591
- });
592
- return fn;
593
- }
594
- output = hook;
595
- this.events.emit("plugins:hook:processing:end", {
596
- duration: Math.round(performance.now() - startTime),
597
- parameters,
598
- output,
599
- strategy,
600
- hookName,
601
- plugin
602
- });
603
- return hook;
604
- } catch (error) {
605
- this.events.emit("error", error, {
606
- plugin,
607
- hookName,
608
- strategy,
609
- duration: Math.round(performance.now() - startTime)
610
- });
611
- return null;
612
- }
613
- }
614
- #parse(plugin) {
615
- const usedPluginNames = this.#usedPluginNames;
616
- setUniqueName(plugin.name, usedPluginNames);
617
- const usageCount = usedPluginNames[plugin.name];
618
- if (usageCount && usageCount > 1) this.events.emit("warn", `Multiple instances of plugin "${plugin.name}" detected. This behavior is deprecated and will be removed in v5.`, `Plugin key: [${plugin.name}, ${usageCount}]`);
619
- return {
620
- install() {},
621
- ...plugin,
622
- key: [plugin.name, usedPluginNames[plugin.name]].filter(Boolean)
623
- };
624
- }
625
- };
626
- //#endregion
627
- //#region src/utils/AsyncEventEmitter.ts
628
- var AsyncEventEmitter = class {
629
- constructor(maxListener = 100) {
630
- this.#emitter.setMaxListeners(maxListener);
631
- }
632
- #emitter = new EventEmitter();
633
- async emit(eventName, ...eventArgs) {
634
- const listeners = this.#emitter.listeners(eventName);
635
- if (listeners.length === 0) return;
636
- await Promise.all(listeners.map(async (listener) => {
637
- try {
638
- return await listener(...eventArgs);
639
- } catch (err) {
640
- const causedError = err;
641
- throw new Error(`Error in async listener for "${eventName}" with eventArgs "${eventArgs}"`, { cause: causedError });
642
- }
643
- }));
644
- }
645
- on(eventName, handler) {
646
- this.#emitter.on(eventName, handler);
647
- }
648
- onOnce(eventName, handler) {
649
- const wrapper = (...args) => {
650
- this.off(eventName, wrapper);
651
- handler(...args);
652
- };
653
- this.on(eventName, wrapper);
654
- }
655
- off(eventName, handler) {
656
- this.#emitter.off(eventName, handler);
657
- }
658
- removeAll() {
659
- this.#emitter.removeAllListeners();
660
- }
661
- };
662
- //#endregion
663
- //#region src/utils/formatHrtime.ts
664
- /**
665
- * Calculates elapsed time in milliseconds from a high-resolution start time.
666
- * Rounds to 2 decimal places to provide sub-millisecond precision without noise.
667
- */
668
- function getElapsedMs(hrStart) {
669
- const [seconds, nanoseconds] = process.hrtime(hrStart);
670
- const ms = seconds * 1e3 + nanoseconds / 1e6;
671
- return Math.round(ms * 100) / 100;
672
- }
673
- /**
674
- * Converts a millisecond duration into a human-readable string.
675
- * Adjusts units (ms, s, m s) based on the magnitude of the duration.
676
- */
677
- function formatMs(ms) {
678
- if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
679
- if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
680
- return `${Math.round(ms).toFixed(0)}ms`;
681
- }
682
- /**
683
- * Convenience helper to get and format elapsed time in one step.
684
- */
685
- function formatHrtime(hrStart) {
686
- return formatMs(getElapsedMs(hrStart));
687
- }
688
- //#endregion
689
- //#region src/utils/URLPath.ts
690
- var URLPath = class {
691
- path;
692
- #options;
693
- constructor(path, options = {}) {
694
- this.path = path;
695
- this.#options = options;
696
- return this;
697
- }
698
- /**
699
- * Convert Swagger path to URLPath(syntax of Express)
700
- * @example /pet/{petId} => /pet/:petId
701
- */
702
- get URL() {
703
- return this.toURLPath();
704
- }
705
- get isURL() {
706
- try {
707
- if (new URL(this.path)?.href) return true;
708
- } catch (_error) {
709
- return false;
710
- }
711
- return false;
712
- }
713
- /**
714
- * Convert Swagger path to template literals/ template strings(camelcase)
715
- * @example /pet/{petId} => `/pet/${petId}`
716
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
717
- * @example /account/userID => `/account/${userId}`
718
- */
719
- get template() {
720
- return this.toTemplateString();
721
- }
722
- get object() {
723
- return this.toObject();
724
- }
725
- get params() {
726
- return this.getParams();
727
- }
728
- toObject({ type = "path", replacer, stringify } = {}) {
729
- const object = {
730
- url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
731
- params: this.getParams()
732
- };
733
- if (stringify) {
734
- if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
735
- if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
736
- return `{ url: '${object.url}' }`;
737
- }
738
- return object;
739
- }
740
- /**
741
- * Convert Swagger path to template literals/ template strings(camelcase)
742
- * @example /pet/{petId} => `/pet/${petId}`
743
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
744
- * @example /account/userID => `/account/${userId}`
745
- */
746
- toTemplateString({ prefix = "", replacer } = {}) {
747
- const found = this.path.match(/{(\w|-)*}/g);
748
- let newPath = this.path.replaceAll("{", "${");
749
- if (found) newPath = found.reduce((prev, path) => {
750
- const pathWithoutBrackets = path.replaceAll("{", "").replaceAll("}", "");
751
- let param = isValidVarName(pathWithoutBrackets) ? pathWithoutBrackets : camelCase(pathWithoutBrackets);
752
- if (this.#options.casing === "camelcase") param = camelCase(param);
753
- return prev.replace(path, `\${${replacer ? replacer(param) : param}}`);
754
- }, this.path);
755
- return `\`${prefix}${newPath}\``;
756
- }
757
- getParams(replacer) {
758
- const found = this.path.match(/{(\w|-)*}/g);
759
- if (!found) return;
760
- const params = {};
761
- found.forEach((item) => {
762
- item = item.replaceAll("{", "").replaceAll("}", "");
763
- let param = isValidVarName(item) ? item : camelCase(item);
764
- if (this.#options.casing === "camelcase") param = camelCase(param);
765
- const key = replacer ? replacer(param) : param;
766
- params[key] = key;
767
- }, this.path);
768
- return params;
769
- }
770
- /**
771
- * Convert Swagger path to URLPath(syntax of Express)
772
- * @example /pet/{petId} => /pet/:petId
773
- */
774
- toURLPath() {
775
- return this.path.replaceAll("{", ":").replaceAll("}", "");
776
- }
777
- };
778
- //#endregion
779
- //#region src/utils/TreeNode.ts
780
- var TreeNode = class TreeNode {
781
- data;
782
- parent;
783
- children = [];
784
- #cachedLeaves = void 0;
785
- constructor(data, parent) {
786
- this.data = data;
787
- this.parent = parent;
788
- return this;
789
- }
790
- addChild(data) {
791
- const child = new TreeNode(data, this);
792
- if (!this.children) this.children = [];
793
- this.children.push(child);
794
- return child;
795
- }
796
- get root() {
797
- if (!this.parent) return this;
798
- return this.parent.root;
799
- }
800
- get leaves() {
801
- if (!this.children || this.children.length === 0) return [this];
802
- if (this.#cachedLeaves) return this.#cachedLeaves;
803
- const leaves = [];
804
- if (this.children) for (let childIndex = 0, { length } = this.children; childIndex < length; childIndex++) leaves.push.apply(leaves, this.children[childIndex].leaves);
805
- this.#cachedLeaves = leaves;
806
- return leaves;
807
- }
808
- forEach(callback) {
809
- if (typeof callback !== "function") throw new TypeError("forEach() callback must be a function");
810
- callback(this);
811
- if (this.children) for (let childIndex = 0, { length } = this.children; childIndex < length; childIndex++) this.children[childIndex]?.forEach(callback);
812
- return this;
813
- }
814
- findDeep(predicate) {
815
- if (typeof predicate !== "function") throw new TypeError("find() predicate must be a function");
816
- return this.leaves.find(predicate);
817
- }
818
- forEachDeep(callback) {
819
- if (typeof callback !== "function") throw new TypeError("forEach() callback must be a function");
820
- this.leaves.forEach(callback);
821
- }
822
- filterDeep(callback) {
823
- if (typeof callback !== "function") throw new TypeError("filter() callback must be a function");
824
- return this.leaves.filter(callback);
825
- }
826
- mapDeep(callback) {
827
- if (typeof callback !== "function") throw new TypeError("map() callback must be a function");
828
- return this.leaves.map(callback);
829
- }
830
- static build(files, root) {
831
- try {
832
- const filteredTree = buildDirectoryTree(files, root);
833
- if (!filteredTree) return null;
834
- const treeNode = new TreeNode({
835
- name: filteredTree.name,
836
- path: filteredTree.path,
837
- file: filteredTree.file,
838
- type: getMode(filteredTree.path)
839
- });
840
- const recurse = (node, item) => {
841
- const subNode = node.addChild({
842
- name: item.name,
843
- path: item.path,
844
- file: item.file,
845
- type: getMode(item.path)
846
- });
847
- if (item.children?.length) item.children?.forEach((child) => {
848
- recurse(subNode, child);
849
- });
850
- };
851
- filteredTree.children?.forEach((child) => {
852
- recurse(treeNode, child);
853
- });
854
- return treeNode;
855
- } catch (error) {
856
- throw new Error("Something went wrong with creating barrel files with the TreeNode class", { cause: error });
857
- }
858
- }
859
- };
860
- const normalizePath = (p) => p.replace(/\\/g, "/");
861
- function buildDirectoryTree(files, rootFolder = "") {
862
- const normalizedRootFolder = normalizePath(rootFolder);
863
- const rootPrefix = normalizedRootFolder.endsWith("/") ? normalizedRootFolder : `${normalizedRootFolder}/`;
864
- const filteredFiles = files.filter((file) => {
865
- const normalizedFilePath = normalizePath(file.path);
866
- return rootFolder ? normalizedFilePath.startsWith(rootPrefix) && !normalizedFilePath.endsWith(".json") : !normalizedFilePath.endsWith(".json");
867
- });
868
- if (filteredFiles.length === 0) return null;
869
- const root = {
870
- name: rootFolder || "",
871
- path: rootFolder || "",
872
- children: []
873
- };
874
- filteredFiles.forEach((file) => {
875
- const parts = file.path.slice(rootFolder.length).split("/");
876
- let currentLevel = root.children;
877
- let currentPath = rootFolder;
878
- parts.forEach((part, index) => {
879
- if (index !== 0) currentPath += `/${part}`;
880
- else currentPath += `${part}`;
881
- let existingNode = currentLevel.find((node) => node.name === part);
882
- if (!existingNode) {
883
- if (index === parts.length - 1) existingNode = {
884
- name: part,
885
- file,
886
- path: currentPath
887
- };
888
- else existingNode = {
889
- name: part,
890
- path: currentPath,
891
- children: []
892
- };
893
- currentLevel.push(existingNode);
894
- }
895
- if (!existingNode.file) currentLevel = existingNode.children;
896
- });
897
- });
898
- return root;
899
- }
900
- //#endregion
901
- //#region src/BarrelManager.ts
902
- /** biome-ignore-all lint/suspicious/useIterableCallbackReturn: not needed */
903
- var BarrelManager = class {
904
- constructor(_options = {}) {
905
- return this;
906
- }
907
- getFiles({ files: generatedFiles, root }) {
908
- const cachedFiles = /* @__PURE__ */ new Map();
909
- TreeNode.build(generatedFiles, root)?.forEach((treeNode) => {
910
- if (!treeNode || !treeNode.children || !treeNode.parent?.data.path) return;
911
- const barrelFile = {
912
- path: join(treeNode.parent?.data.path, "index.ts"),
913
- baseName: "index.ts",
914
- exports: [],
915
- imports: [],
916
- sources: []
917
- };
918
- const previousBarrelFile = cachedFiles.get(barrelFile.path);
919
- treeNode.leaves.forEach((item) => {
920
- if (!item.data.name) return;
921
- (item.data.file?.sources || []).forEach((source) => {
922
- if (!item.data.file?.path || !source.isIndexable || !source.name) return;
923
- if (previousBarrelFile?.sources.some((item) => item.name === source.name && item.isTypeOnly === source.isTypeOnly)) return;
924
- if (!barrelFile.exports) barrelFile.exports = [];
925
- if (!!treeNode.parent?.data.path?.split?.("/")?.length) barrelFile.exports.push({
926
- name: [source.name],
927
- path: getRelativePath(treeNode.parent?.data.path, item.data.path),
928
- isTypeOnly: source.isTypeOnly
929
- });
930
- else barrelFile.exports.push({
931
- name: [source.name],
932
- path: `./${item.data.file.baseName}`,
933
- isTypeOnly: source.isTypeOnly
934
- });
935
- barrelFile.sources.push({
936
- name: source.name,
937
- isTypeOnly: source.isTypeOnly,
938
- value: "",
939
- isExportable: false,
940
- isIndexable: false
941
- });
942
- });
943
- });
944
- if (previousBarrelFile) {
945
- previousBarrelFile.sources.push(...barrelFile.sources);
946
- previousBarrelFile.exports?.push(...barrelFile.exports || []);
947
- } else cachedFiles.set(barrelFile.path, barrelFile);
948
- });
949
- return [...cachedFiles.values()];
950
- }
951
- };
952
- //#endregion
953
- //#region src/utils/getBarrelFiles.ts
954
- function trimExtName(text) {
955
- return text.replace(/\.[^/.]+$/, "");
956
- }
957
- async function getBarrelFiles(files, { type, meta = {}, root, output }) {
958
- if (!type || type === "propagate") return [];
959
- const barrelManager = new BarrelManager({});
960
- const pathToBuildFrom = join(root, output.path);
961
- if (trimExtName(pathToBuildFrom).endsWith("index")) return [];
962
- const barrelFiles = barrelManager.getFiles({
963
- files,
964
- root: pathToBuildFrom,
965
- meta
966
- });
967
- if (type === "all") return barrelFiles.map((file) => {
968
- return {
969
- ...file,
970
- exports: file.exports?.map((exportItem) => {
971
- return {
972
- ...exportItem,
973
- name: void 0
974
- };
975
- })
976
- };
977
- });
978
- return barrelFiles.map((indexFile) => {
979
- return {
980
- ...indexFile,
981
- meta
982
- };
983
- });
984
- }
985
- //#endregion
986
- //#region src/utils/packageManager.ts
987
- const packageManagers = {
988
- pnpm: {
989
- name: "pnpm",
990
- lockFile: "pnpm-lock.yaml",
991
- installCommand: ["add", "-D"]
992
- },
993
- yarn: {
994
- name: "yarn",
995
- lockFile: "yarn.lock",
996
- installCommand: ["add", "-D"]
997
- },
998
- bun: {
999
- name: "bun",
1000
- lockFile: "bun.lockb",
1001
- installCommand: ["add", "-d"]
1002
- },
1003
- npm: {
1004
- name: "npm",
1005
- lockFile: "package-lock.json",
1006
- installCommand: ["install", "--save-dev"]
1007
- }
1008
- };
1009
- function detectPackageManager(cwd = process.cwd()) {
1010
- const packageJsonPath = path.join(cwd, "package.json");
1011
- if (fs.existsSync(packageJsonPath)) try {
1012
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
1013
- if (packageJson.packageManager) {
1014
- const [name] = packageJson.packageManager.split("@");
1015
- if (name in packageManagers) return packageManagers[name];
1016
- }
1017
- } catch {}
1018
- for (const pm of Object.values(packageManagers)) if (fs.existsSync(path.join(cwd, pm.lockFile))) return pm;
1019
- return packageManagers.npm;
1020
- }
1021
- //#endregion
1022
- export { formatMs as a, PluginManager as c, setUniqueName as d, PromiseManager as f, formatHrtime as i, getMode as l, getBarrelFiles as n, getElapsedMs as o, BuildError as p, URLPath as r, AsyncEventEmitter as s, detectPackageManager as t, getUniqueName as u };
1023
-
1024
- //# sourceMappingURL=packageManager-wMCQlgd6.js.map