@kubb/core 4.5.1 → 4.5.2

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