@kubb/core 4.5.1 → 4.5.3

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