@kubb/core 3.0.0-alpha.2 → 3.0.0-alpha.21

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 (107) hide show
  1. package/README.md +13 -4
  2. package/dist/{FileManager-Bw-FNS3q.d.cts → FileManager-4lbobkix.d.cts} +124 -84
  3. package/dist/{FileManager-BW--rO8q.d.ts → FileManager-CdXrquQt.d.ts} +124 -84
  4. package/dist/chunk-2EU7DMPM.js +96 -0
  5. package/dist/chunk-2EU7DMPM.js.map +1 -0
  6. package/dist/{chunk-LM2YQC3T.cjs → chunk-3MDDPVXB.cjs} +81 -51
  7. package/dist/chunk-3MDDPVXB.cjs.map +1 -0
  8. package/dist/chunk-4X5FFJPJ.js +8 -13
  9. package/dist/chunk-4X5FFJPJ.js.map +1 -1
  10. package/dist/{chunk-67C6RBGQ.cjs → chunk-6NKPFDXC.cjs} +28 -29
  11. package/dist/chunk-6NKPFDXC.cjs.map +1 -0
  12. package/dist/chunk-CLTNHSMO.js +895 -0
  13. package/dist/chunk-CLTNHSMO.js.map +1 -0
  14. package/dist/{chunk-3OXCZ5DJ.js → chunk-E6CN2CZC.js} +63 -54
  15. package/dist/chunk-E6CN2CZC.js.map +1 -0
  16. package/dist/chunk-HBQM723K.js +1049 -0
  17. package/dist/chunk-HBQM723K.js.map +1 -0
  18. package/dist/chunk-MHOAMP5V.cjs +1537 -0
  19. package/dist/chunk-MHOAMP5V.cjs.map +1 -0
  20. package/dist/chunk-PWFXUBH6.cjs +101 -0
  21. package/dist/chunk-PWFXUBH6.cjs.map +1 -0
  22. package/dist/chunk-RSTRL2FG.cjs +42 -0
  23. package/dist/chunk-RSTRL2FG.cjs.map +1 -0
  24. package/dist/chunk-SWGRKRKB.cjs +1088 -0
  25. package/dist/chunk-SWGRKRKB.cjs.map +1 -0
  26. package/dist/index.cjs +551 -599
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +7 -22
  29. package/dist/index.d.ts +7 -22
  30. package/dist/index.js +442 -512
  31. package/dist/index.js.map +1 -1
  32. package/dist/{logger-DChjnJMn.d.cts → logger-DvbHXjIO.d.cts} +29 -19
  33. package/dist/{logger-DChjnJMn.d.ts → logger-DvbHXjIO.d.ts} +29 -19
  34. package/dist/logger.cjs +25 -15
  35. package/dist/logger.cjs.map +1 -1
  36. package/dist/logger.d.cts +1 -2
  37. package/dist/logger.d.ts +1 -2
  38. package/dist/logger.js +3 -15
  39. package/dist/logger.js.map +1 -1
  40. package/dist/mocks.cjs +42 -31
  41. package/dist/mocks.cjs.map +1 -1
  42. package/dist/mocks.d.cts +7 -9
  43. package/dist/mocks.d.ts +7 -9
  44. package/dist/mocks.js +35 -33
  45. package/dist/mocks.js.map +1 -1
  46. package/dist/prompt-7BUJOOIL.cjs +760 -0
  47. package/dist/prompt-7BUJOOIL.cjs.map +1 -0
  48. package/dist/prompt-WQQUN22Z.js +749 -0
  49. package/dist/prompt-WQQUN22Z.js.map +1 -0
  50. package/dist/transformers.cjs +216 -49
  51. package/dist/transformers.cjs.map +1 -1
  52. package/dist/transformers.d.cts +1 -3
  53. package/dist/transformers.d.ts +1 -3
  54. package/dist/transformers.js +149 -35
  55. package/dist/transformers.js.map +1 -1
  56. package/dist/utils.cjs +65 -26
  57. package/dist/utils.cjs.map +1 -1
  58. package/dist/utils.d.cts +32 -3
  59. package/dist/utils.d.ts +32 -3
  60. package/dist/utils.js +3 -26
  61. package/dist/utils.js.map +1 -1
  62. package/package.json +11 -14
  63. package/src/BarrelManager.ts +95 -109
  64. package/src/{Generator.ts → BaseGenerator.ts} +1 -1
  65. package/src/FileManager.ts +190 -298
  66. package/src/PackageManager.ts +1 -1
  67. package/src/PluginManager.ts +149 -90
  68. package/src/PromiseManager.ts +1 -1
  69. package/src/__snapshots__/barrel.json +93 -0
  70. package/src/__snapshots__/grouped.json +120 -0
  71. package/src/__snapshots__/ordered.json +68 -0
  72. package/src/build.ts +87 -122
  73. package/src/config.ts +2 -4
  74. package/src/errors.ts +0 -11
  75. package/src/index.ts +2 -3
  76. package/src/logger.ts +76 -34
  77. package/src/plugin.ts +2 -5
  78. package/src/transformers/escape.ts +0 -10
  79. package/src/transformers/index.ts +2 -3
  80. package/src/transformers/trim.ts +0 -4
  81. package/src/types.ts +48 -17
  82. package/src/utils/TreeNode.ts +132 -50
  83. package/src/utils/executeStrategies.ts +3 -3
  84. package/src/utils/index.ts +2 -1
  85. package/src/utils/parser.ts +166 -0
  86. package/dist/chunk-3OXCZ5DJ.js.map +0 -1
  87. package/dist/chunk-5JZNFPUP.js +0 -309
  88. package/dist/chunk-5JZNFPUP.js.map +0 -1
  89. package/dist/chunk-67C6RBGQ.cjs.map +0 -1
  90. package/dist/chunk-ADC5UNZ5.cjs +0 -1227
  91. package/dist/chunk-ADC5UNZ5.cjs.map +0 -1
  92. package/dist/chunk-HMLY7DHA.js +0 -16
  93. package/dist/chunk-HMLY7DHA.js.map +0 -1
  94. package/dist/chunk-JKZG2IJR.js +0 -283
  95. package/dist/chunk-JKZG2IJR.js.map +0 -1
  96. package/dist/chunk-LM2YQC3T.cjs.map +0 -1
  97. package/dist/chunk-PZT4CTBV.cjs +0 -299
  98. package/dist/chunk-PZT4CTBV.cjs.map +0 -1
  99. package/dist/chunk-SA2GZKXS.js +0 -596
  100. package/dist/chunk-SA2GZKXS.js.map +0 -1
  101. package/dist/chunk-XCPFG6DO.cjs +0 -66
  102. package/dist/chunk-XCPFG6DO.cjs.map +0 -1
  103. package/dist/chunk-YTSNYMHW.cjs +0 -320
  104. package/dist/chunk-YTSNYMHW.cjs.map +0 -1
  105. package/schema.json +0 -86
  106. package/src/utils/cache.ts +0 -35
  107. package/src/utils/getParser.ts +0 -17
@@ -0,0 +1,1537 @@
1
+ 'use strict';
2
+
3
+ var chunk6NKPFDXC_cjs = require('./chunk-6NKPFDXC.cjs');
4
+ var chunkRSTRL2FG_cjs = require('./chunk-RSTRL2FG.cjs');
5
+ var path = require('path');
6
+ var fs = require('@kubb/fs');
7
+ var hash = require('object-hash');
8
+ var remeda = require('remeda');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
+
12
+ var hash__default = /*#__PURE__*/_interopDefault(hash);
13
+
14
+ // ../../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.js
15
+ var require_eventemitter3 = chunkRSTRL2FG_cjs.__commonJS({
16
+ "../../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.js"(exports, module) {
17
+ chunkRSTRL2FG_cjs.init_cjs_shims();
18
+ var has = Object.prototype.hasOwnProperty;
19
+ var prefix = "~";
20
+ function Events() {
21
+ }
22
+ if (Object.create) {
23
+ Events.prototype = /* @__PURE__ */ Object.create(null);
24
+ if (!new Events().__proto__) prefix = false;
25
+ }
26
+ function EE(fn, context, once) {
27
+ this.fn = fn;
28
+ this.context = context;
29
+ this.once = once || false;
30
+ }
31
+ function addListener(emitter, event, fn, context, once) {
32
+ if (typeof fn !== "function") {
33
+ throw new TypeError("The listener must be a function");
34
+ }
35
+ var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event;
36
+ if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
37
+ else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
38
+ else emitter._events[evt] = [emitter._events[evt], listener];
39
+ return emitter;
40
+ }
41
+ function clearEvent(emitter, evt) {
42
+ if (--emitter._eventsCount === 0) emitter._events = new Events();
43
+ else delete emitter._events[evt];
44
+ }
45
+ function EventEmitter2() {
46
+ this._events = new Events();
47
+ this._eventsCount = 0;
48
+ }
49
+ EventEmitter2.prototype.eventNames = function eventNames() {
50
+ var names = [], events, name;
51
+ if (this._eventsCount === 0) return names;
52
+ for (name in events = this._events) {
53
+ if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
54
+ }
55
+ if (Object.getOwnPropertySymbols) {
56
+ return names.concat(Object.getOwnPropertySymbols(events));
57
+ }
58
+ return names;
59
+ };
60
+ EventEmitter2.prototype.listeners = function listeners(event) {
61
+ var evt = prefix ? prefix + event : event, handlers = this._events[evt];
62
+ if (!handlers) return [];
63
+ if (handlers.fn) return [handlers.fn];
64
+ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
65
+ ee[i] = handlers[i].fn;
66
+ }
67
+ return ee;
68
+ };
69
+ EventEmitter2.prototype.listenerCount = function listenerCount(event) {
70
+ var evt = prefix ? prefix + event : event, listeners = this._events[evt];
71
+ if (!listeners) return 0;
72
+ if (listeners.fn) return 1;
73
+ return listeners.length;
74
+ };
75
+ EventEmitter2.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
76
+ var evt = prefix ? prefix + event : event;
77
+ if (!this._events[evt]) return false;
78
+ var listeners = this._events[evt], len = arguments.length, args, i;
79
+ if (listeners.fn) {
80
+ if (listeners.once) this.removeListener(event, listeners.fn, void 0, true);
81
+ switch (len) {
82
+ case 1:
83
+ return listeners.fn.call(listeners.context), true;
84
+ case 2:
85
+ return listeners.fn.call(listeners.context, a1), true;
86
+ case 3:
87
+ return listeners.fn.call(listeners.context, a1, a2), true;
88
+ case 4:
89
+ return listeners.fn.call(listeners.context, a1, a2, a3), true;
90
+ case 5:
91
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
92
+ case 6:
93
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
94
+ }
95
+ for (i = 1, args = new Array(len - 1); i < len; i++) {
96
+ args[i - 1] = arguments[i];
97
+ }
98
+ listeners.fn.apply(listeners.context, args);
99
+ } else {
100
+ var length = listeners.length, j;
101
+ for (i = 0; i < length; i++) {
102
+ if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true);
103
+ switch (len) {
104
+ case 1:
105
+ listeners[i].fn.call(listeners[i].context);
106
+ break;
107
+ case 2:
108
+ listeners[i].fn.call(listeners[i].context, a1);
109
+ break;
110
+ case 3:
111
+ listeners[i].fn.call(listeners[i].context, a1, a2);
112
+ break;
113
+ case 4:
114
+ listeners[i].fn.call(listeners[i].context, a1, a2, a3);
115
+ break;
116
+ default:
117
+ if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) {
118
+ args[j - 1] = arguments[j];
119
+ }
120
+ listeners[i].fn.apply(listeners[i].context, args);
121
+ }
122
+ }
123
+ }
124
+ return true;
125
+ };
126
+ EventEmitter2.prototype.on = function on(event, fn, context) {
127
+ return addListener(this, event, fn, context, false);
128
+ };
129
+ EventEmitter2.prototype.once = function once(event, fn, context) {
130
+ return addListener(this, event, fn, context, true);
131
+ };
132
+ EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once) {
133
+ var evt = prefix ? prefix + event : event;
134
+ if (!this._events[evt]) return this;
135
+ if (!fn) {
136
+ clearEvent(this, evt);
137
+ return this;
138
+ }
139
+ var listeners = this._events[evt];
140
+ if (listeners.fn) {
141
+ if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
142
+ clearEvent(this, evt);
143
+ }
144
+ } else {
145
+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {
146
+ if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
147
+ events.push(listeners[i]);
148
+ }
149
+ }
150
+ if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
151
+ else clearEvent(this, evt);
152
+ }
153
+ return this;
154
+ };
155
+ EventEmitter2.prototype.removeAllListeners = function removeAllListeners(event) {
156
+ var evt;
157
+ if (event) {
158
+ evt = prefix ? prefix + event : event;
159
+ if (this._events[evt]) clearEvent(this, evt);
160
+ } else {
161
+ this._events = new Events();
162
+ this._eventsCount = 0;
163
+ }
164
+ return this;
165
+ };
166
+ EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
167
+ EventEmitter2.prototype.addListener = EventEmitter2.prototype.on;
168
+ EventEmitter2.prefixed = prefix;
169
+ EventEmitter2.EventEmitter = EventEmitter2;
170
+ if ("undefined" !== typeof module) {
171
+ module.exports = EventEmitter2;
172
+ }
173
+ }
174
+ });
175
+
176
+ // src/utils/index.ts
177
+ chunkRSTRL2FG_cjs.init_cjs_shims();
178
+
179
+ // src/utils/FunctionParams.ts
180
+ chunkRSTRL2FG_cjs.init_cjs_shims();
181
+ var FunctionParams = class _FunctionParams {
182
+ #items = [];
183
+ constructor() {
184
+ return this;
185
+ }
186
+ get items() {
187
+ return this.#items.flat();
188
+ }
189
+ add(item) {
190
+ if (!item) {
191
+ return this;
192
+ }
193
+ if (Array.isArray(item)) {
194
+ item.filter(Boolean).forEach((it) => this.#items.push(it));
195
+ return this;
196
+ }
197
+ this.#items.push(item);
198
+ return this;
199
+ }
200
+ static #orderItems(items) {
201
+ return chunk6NKPFDXC_cjs.orderBy(
202
+ items.filter(Boolean),
203
+ [
204
+ (v) => {
205
+ if (Array.isArray(v)) {
206
+ return void 0;
207
+ }
208
+ return !v.default;
209
+ },
210
+ (v) => {
211
+ if (Array.isArray(v)) {
212
+ return void 0;
213
+ }
214
+ return v.required ?? true;
215
+ }
216
+ ],
217
+ ["desc", "desc"]
218
+ );
219
+ }
220
+ static #addParams(acc, item) {
221
+ const { enabled = true, name, type, required = true, ...rest } = item;
222
+ if (!enabled) {
223
+ return acc;
224
+ }
225
+ if (!name) {
226
+ acc.push(`${type}${rest.default ? ` = ${rest.default}` : ""}`);
227
+ return acc;
228
+ }
229
+ const parameterName = name.startsWith("{") ? name : chunk6NKPFDXC_cjs.camelCase(name);
230
+ if (type) {
231
+ if (required) {
232
+ acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ""}`);
233
+ } else {
234
+ acc.push(`${parameterName}?: ${type}`);
235
+ }
236
+ } else {
237
+ acc.push(`${parameterName}`);
238
+ }
239
+ return acc;
240
+ }
241
+ static toObject(items) {
242
+ let type = [];
243
+ let name = [];
244
+ const enabled = items.every((item) => item.enabled) ? items.at(0)?.enabled : true;
245
+ const required = items.every((item) => item.required) ?? true;
246
+ items.forEach((item) => {
247
+ name = _FunctionParams.#addParams(name, { ...item, type: void 0 });
248
+ if (items.some((item2) => item2.type)) {
249
+ type = _FunctionParams.#addParams(type, item);
250
+ }
251
+ });
252
+ return {
253
+ name: `{ ${name.join(", ")} }`,
254
+ type: type.length ? `{ ${type.join("; ")} }` : void 0,
255
+ enabled,
256
+ required
257
+ };
258
+ }
259
+ static toString(items) {
260
+ const sortedData = _FunctionParams.#orderItems(items);
261
+ return sortedData.reduce((acc, item) => {
262
+ if (Array.isArray(item)) {
263
+ if (item.length <= 0) {
264
+ return acc;
265
+ }
266
+ const subItems = _FunctionParams.#orderItems(item);
267
+ const objectItem = _FunctionParams.toObject(subItems);
268
+ return _FunctionParams.#addParams(acc, objectItem);
269
+ }
270
+ return _FunctionParams.#addParams(acc, item);
271
+ }, []).join(", ");
272
+ }
273
+ toObject() {
274
+ const items = _FunctionParams.#orderItems(this.#items).flat();
275
+ return _FunctionParams.toObject(items);
276
+ }
277
+ toString() {
278
+ const items = _FunctionParams.#orderItems(this.#items);
279
+ return _FunctionParams.toString(items);
280
+ }
281
+ };
282
+
283
+ // src/utils/promise.ts
284
+ chunkRSTRL2FG_cjs.init_cjs_shims();
285
+ function isPromise(result) {
286
+ return !!result && typeof result?.then === "function";
287
+ }
288
+ function isPromiseFulfilledResult(result) {
289
+ return result.status === "fulfilled";
290
+ }
291
+ function isPromiseRejectedResult(result) {
292
+ return result.status === "rejected";
293
+ }
294
+
295
+ // src/utils/renderTemplate.ts
296
+ chunkRSTRL2FG_cjs.init_cjs_shims();
297
+ function renderTemplate(template, data = void 0) {
298
+ if (!data || !Object.keys(data).length) {
299
+ return template.replace(/{{(.*?)}}/g, "");
300
+ }
301
+ const matches = template.match(/{{(.*?)}}/g);
302
+ return matches?.reduce((prev, curr) => {
303
+ const index = curr.split(/{{|}}/).filter(Boolean)[0]?.trim();
304
+ if (index === void 0) {
305
+ return prev;
306
+ }
307
+ const value = data[index];
308
+ if (value === void 0) {
309
+ return prev;
310
+ }
311
+ return prev.replace(curr, () => {
312
+ if (typeof value === "boolean") {
313
+ return `${value.toString()}` || "false";
314
+ }
315
+ return value || "";
316
+ }).trim();
317
+ }, template) || "";
318
+ }
319
+
320
+ // src/utils/timeout.ts
321
+ chunkRSTRL2FG_cjs.init_cjs_shims();
322
+ async function timeout(ms) {
323
+ return new Promise((resolve) => {
324
+ setTimeout(() => {
325
+ resolve(true);
326
+ }, ms);
327
+ });
328
+ }
329
+
330
+ // src/utils/uniqueName.ts
331
+ chunkRSTRL2FG_cjs.init_cjs_shims();
332
+ function getUniqueName(originalName, data) {
333
+ let used = data[originalName] || 0;
334
+ if (used) {
335
+ data[originalName] = ++used;
336
+ originalName += used;
337
+ }
338
+ data[originalName] = 1;
339
+ return originalName;
340
+ }
341
+ function setUniqueName(originalName, data) {
342
+ let used = data[originalName] || 0;
343
+ if (used) {
344
+ data[originalName] = ++used;
345
+ return originalName;
346
+ }
347
+ data[originalName] = 1;
348
+ return originalName;
349
+ }
350
+
351
+ // src/utils/URLPath.ts
352
+ chunkRSTRL2FG_cjs.init_cjs_shims();
353
+ var URLPath = class {
354
+ path;
355
+ constructor(path) {
356
+ this.path = path;
357
+ return this;
358
+ }
359
+ /**
360
+ * Convert Swagger path to URLPath(syntax of Express)
361
+ * @example /pet/{petId} => /pet/:petId
362
+ */
363
+ get URL() {
364
+ return this.toURLPath();
365
+ }
366
+ get isURL() {
367
+ try {
368
+ const url = new URL(this.path);
369
+ if (url?.href) {
370
+ return true;
371
+ }
372
+ } catch (error) {
373
+ return false;
374
+ }
375
+ return false;
376
+ }
377
+ /**
378
+ * Convert Swagger path to template literals/ template strings(camelcase)
379
+ * @example /pet/{petId} => `/pet/${petId}`
380
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
381
+ * @example /account/userID => `/account/${userId}`
382
+ */
383
+ get template() {
384
+ return this.toTemplateString();
385
+ }
386
+ get object() {
387
+ return this.toObject();
388
+ }
389
+ get params() {
390
+ return this.getParams();
391
+ }
392
+ toObject({ type = "path", replacer, stringify } = {}) {
393
+ const object = {
394
+ url: type === "path" ? this.toURLPath() : this.toTemplateString(replacer),
395
+ params: this.getParams()
396
+ };
397
+ if (stringify) {
398
+ if (type === "template") {
399
+ return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
400
+ }
401
+ if (object.params) {
402
+ return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
403
+ }
404
+ return `{ url: '${object.url}' }`;
405
+ }
406
+ return object;
407
+ }
408
+ /**
409
+ * Convert Swagger path to template literals/ template strings(camelcase)
410
+ * @example /pet/{petId} => `/pet/${petId}`
411
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
412
+ * @example /account/userID => `/account/${userId}`
413
+ */
414
+ toTemplateString(replacer) {
415
+ const regex = /{(\w|-)*}/g;
416
+ const found = this.path.match(regex);
417
+ let newPath = this.path.replaceAll("{", "${");
418
+ if (found) {
419
+ newPath = found.reduce((prev, curr) => {
420
+ const pathParam = replacer ? replacer(chunk6NKPFDXC_cjs.camelCase(curr)) : chunk6NKPFDXC_cjs.camelCase(curr);
421
+ const replacement = `\${${pathParam}}`;
422
+ return prev.replace(curr, replacement);
423
+ }, this.path);
424
+ }
425
+ return `\`${newPath}\``;
426
+ }
427
+ getParams(replacer) {
428
+ const regex = /{(\w|-)*}/g;
429
+ const found = this.path.match(regex);
430
+ if (!found) {
431
+ return void 0;
432
+ }
433
+ const params = {};
434
+ found.forEach((item) => {
435
+ item = item.replaceAll("{", "").replaceAll("}", "");
436
+ const pathParam = replacer ? replacer(chunk6NKPFDXC_cjs.camelCase(item)) : chunk6NKPFDXC_cjs.camelCase(item);
437
+ params[pathParam] = pathParam;
438
+ }, this.path);
439
+ return params;
440
+ }
441
+ /**
442
+ * Convert Swagger path to URLPath(syntax of Express)
443
+ * @example /pet/{petId} => /pet/:petId
444
+ */
445
+ toURLPath() {
446
+ return this.path.replaceAll("{", ":").replaceAll("}", "");
447
+ }
448
+ };
449
+
450
+ // src/utils/parser.ts
451
+ chunkRSTRL2FG_cjs.init_cjs_shims();
452
+
453
+ // src/FileManager.ts
454
+ chunkRSTRL2FG_cjs.init_cjs_shims();
455
+
456
+ // src/BarrelManager.ts
457
+ chunkRSTRL2FG_cjs.init_cjs_shims();
458
+
459
+ // src/utils/TreeNode.ts
460
+ chunkRSTRL2FG_cjs.init_cjs_shims();
461
+ var TreeNode = class _TreeNode {
462
+ data;
463
+ parent;
464
+ children = [];
465
+ #cachedLeaves = void 0;
466
+ constructor(data, parent) {
467
+ this.data = data;
468
+ this.parent = parent;
469
+ return this;
470
+ }
471
+ addChild(data) {
472
+ const child = new _TreeNode(data, this);
473
+ if (!this.children) {
474
+ this.children = [];
475
+ }
476
+ this.children.push(child);
477
+ return child;
478
+ }
479
+ get root() {
480
+ if (!this.parent) {
481
+ return this;
482
+ }
483
+ return this.parent.root;
484
+ }
485
+ get leaves() {
486
+ if (!this.children || this.children.length === 0) {
487
+ return [this];
488
+ }
489
+ if (this.#cachedLeaves) {
490
+ return this.#cachedLeaves;
491
+ }
492
+ const leaves = [];
493
+ if (this.children) {
494
+ for (let i = 0, { length } = this.children; i < length; i++) {
495
+ leaves.push.apply(leaves, this.children[i].leaves);
496
+ }
497
+ }
498
+ this.#cachedLeaves = leaves;
499
+ return leaves;
500
+ }
501
+ forEach(callback) {
502
+ if (typeof callback !== "function") {
503
+ throw new TypeError("forEach() callback must be a function");
504
+ }
505
+ callback(this);
506
+ if (this.children) {
507
+ for (let i = 0, { length } = this.children; i < length; i++) {
508
+ this.children[i]?.forEach(callback);
509
+ }
510
+ }
511
+ return this;
512
+ }
513
+ findDeep(predicate) {
514
+ if (typeof predicate !== "function") {
515
+ throw new TypeError("find() predicate must be a function");
516
+ }
517
+ return this.leaves.find(predicate);
518
+ }
519
+ forEachDeep(callback) {
520
+ if (typeof callback !== "function") {
521
+ throw new TypeError("forEach() callback must be a function");
522
+ }
523
+ this.leaves.forEach(callback);
524
+ }
525
+ filterDeep(callback) {
526
+ if (typeof callback !== "function") {
527
+ throw new TypeError("filter() callback must be a function");
528
+ }
529
+ return this.leaves.filter(callback);
530
+ }
531
+ mapDeep(callback) {
532
+ if (typeof callback !== "function") {
533
+ throw new TypeError("map() callback must be a function");
534
+ }
535
+ return this.leaves.map(callback);
536
+ }
537
+ static build(files, root) {
538
+ try {
539
+ const filteredTree = buildDirectoryTree(files, root);
540
+ if (!filteredTree) {
541
+ return null;
542
+ }
543
+ const treeNode = new _TreeNode({
544
+ name: filteredTree.name,
545
+ path: filteredTree.path,
546
+ file: filteredTree.file,
547
+ type: FileManager.getMode(filteredTree.path)
548
+ });
549
+ const recurse = (node, item) => {
550
+ const subNode = node.addChild({
551
+ name: item.name,
552
+ path: item.path,
553
+ file: item.file,
554
+ type: FileManager.getMode(item.path)
555
+ });
556
+ if (item.children?.length) {
557
+ item.children?.forEach((child) => {
558
+ recurse(subNode, child);
559
+ });
560
+ }
561
+ };
562
+ filteredTree.children?.forEach((child) => recurse(treeNode, child));
563
+ return treeNode;
564
+ } catch (e) {
565
+ throw new Error("Something went wrong with creating barrel files with the TreeNode class", { cause: e });
566
+ }
567
+ }
568
+ };
569
+ function buildDirectoryTree(files, rootFolder = "") {
570
+ const rootPrefix = rootFolder.endsWith("/") ? rootFolder : `${rootFolder}/`;
571
+ const filteredFiles = files.filter((file) => rootFolder ? file.path.startsWith(rootPrefix) && !file.path.endsWith(".json") : !file.path.endsWith(".json"));
572
+ if (filteredFiles.length === 0) {
573
+ return null;
574
+ }
575
+ const root = {
576
+ name: rootFolder || "",
577
+ path: rootFolder || "",
578
+ children: []
579
+ };
580
+ filteredFiles.forEach((file) => {
581
+ const path = file.path.slice(rootFolder.length);
582
+ const parts = path.split("/");
583
+ let currentLevel = root.children;
584
+ let currentPath = rootFolder;
585
+ parts.forEach((part, index) => {
586
+ if (index !== 0) {
587
+ currentPath += `/${part}`;
588
+ } else {
589
+ currentPath += `${part}`;
590
+ }
591
+ let existingNode = currentLevel.find((node) => node.name === part);
592
+ if (!existingNode) {
593
+ if (index === parts.length - 1) {
594
+ existingNode = {
595
+ name: part,
596
+ file,
597
+ path: currentPath
598
+ };
599
+ } else {
600
+ existingNode = {
601
+ name: part,
602
+ path: currentPath,
603
+ children: []
604
+ };
605
+ }
606
+ currentLevel.push(existingNode);
607
+ }
608
+ if (!existingNode.file) {
609
+ currentLevel = existingNode.children;
610
+ }
611
+ });
612
+ });
613
+ return root;
614
+ }
615
+ var BarrelManager = class {
616
+ #options;
617
+ constructor(options = {}) {
618
+ this.#options = options;
619
+ return this;
620
+ }
621
+ getFiles({ files: generatedFiles, root, meta }) {
622
+ const { logger } = this.#options;
623
+ const cachedFiles = /* @__PURE__ */ new Map();
624
+ logger?.emit("debug", { date: /* @__PURE__ */ new Date(), logs: [`Start barrel generation for pluginKey ${meta?.pluginKey?.join(".")} and root '${root}'`] });
625
+ TreeNode.build(generatedFiles, root)?.forEach((treeNode) => {
626
+ if (!treeNode || !treeNode.children || !treeNode.parent?.data.path) {
627
+ return void 0;
628
+ }
629
+ const barrelFile = {
630
+ path: path.join(treeNode.parent?.data.path, "index.ts"),
631
+ baseName: "index.ts",
632
+ exports: [],
633
+ sources: []
634
+ };
635
+ const previousBarrelFile = cachedFiles.get(barrelFile.path);
636
+ const leaves = treeNode.leaves;
637
+ leaves.forEach((item) => {
638
+ if (!item.data.name) {
639
+ return void 0;
640
+ }
641
+ const sources = item.data.file?.sources || [];
642
+ if (!sources.some((source) => source.isIndexable)) {
643
+ logger?.emit(
644
+ "warning",
645
+ `No isIndexable source found(source should have a name and isIndexable):
646
+ File: ${JSON.stringify(item.data.file, void 0, 2)}`
647
+ );
648
+ }
649
+ sources.forEach((source) => {
650
+ if (!item.data.file?.path || !source.isIndexable || !source.name) {
651
+ return void 0;
652
+ }
653
+ const alreadyContainInPreviousBarrelFile = previousBarrelFile?.sources.some((item2) => item2.name === source.name);
654
+ if (alreadyContainInPreviousBarrelFile) {
655
+ return void 0;
656
+ }
657
+ if (!barrelFile.exports) {
658
+ barrelFile.exports = [];
659
+ }
660
+ const isSubExport = !!treeNode.parent?.data.path?.split?.("/")?.length;
661
+ if (isSubExport) {
662
+ barrelFile.exports.push({
663
+ name: [source.name],
664
+ path: fs.getRelativePath(treeNode.parent?.data.path, item.data.path),
665
+ isTypeOnly: source.isTypeOnly
666
+ });
667
+ } else {
668
+ barrelFile.exports.push({
669
+ name: [source.name],
670
+ path: `./${item.data.file.baseName}`,
671
+ isTypeOnly: source.isTypeOnly
672
+ });
673
+ }
674
+ barrelFile.sources.push({
675
+ name: source.name,
676
+ isTypeOnly: source.isTypeOnly,
677
+ //TODO use parser to generate import
678
+ value: "",
679
+ isExportable: false,
680
+ isIndexable: false
681
+ });
682
+ });
683
+ });
684
+ logger?.emit("debug", {
685
+ date: /* @__PURE__ */ new Date(),
686
+ logs: [
687
+ `Generating barrelFile '${fs.getRelativePath(root, barrelFile.path)}' for '${fs.getRelativePath(root, treeNode.data?.path)}' with ${barrelFile.sources.length} indexable exports: '${barrelFile.sources?.map((source) => source.name).join(", ")}'`
688
+ ]
689
+ });
690
+ logger?.emit("debug", {
691
+ date: /* @__PURE__ */ new Date(),
692
+ logs: [
693
+ `Generated barrelFile '${fs.getRelativePath(root, barrelFile.path)}' for '${fs.getRelativePath(root, treeNode.data?.path)}' with exports: '${cachedFiles.get(barrelFile.path)?.sources?.map((source) => source.name).join(", ")}'`
694
+ ]
695
+ });
696
+ if (previousBarrelFile) {
697
+ previousBarrelFile.sources.push(...barrelFile.sources);
698
+ previousBarrelFile.exports?.push(...barrelFile.exports || []);
699
+ } else {
700
+ cachedFiles.set(barrelFile.path, barrelFile);
701
+ }
702
+ });
703
+ return [...cachedFiles.values()];
704
+ }
705
+ };
706
+
707
+ // ../../node_modules/.pnpm/p-queue@8.0.1/node_modules/p-queue/dist/index.js
708
+ chunkRSTRL2FG_cjs.init_cjs_shims();
709
+
710
+ // ../../node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.mjs
711
+ chunkRSTRL2FG_cjs.init_cjs_shims();
712
+ var import_index = chunkRSTRL2FG_cjs.__toESM(require_eventemitter3(), 1);
713
+
714
+ // ../../node_modules/.pnpm/p-timeout@6.1.2/node_modules/p-timeout/index.js
715
+ chunkRSTRL2FG_cjs.init_cjs_shims();
716
+ var TimeoutError = class extends Error {
717
+ constructor(message) {
718
+ super(message);
719
+ this.name = "TimeoutError";
720
+ }
721
+ };
722
+ var AbortError = class extends Error {
723
+ constructor(message) {
724
+ super();
725
+ this.name = "AbortError";
726
+ this.message = message;
727
+ }
728
+ };
729
+ var getDOMException = (errorMessage) => globalThis.DOMException === void 0 ? new AbortError(errorMessage) : new DOMException(errorMessage);
730
+ var getAbortedReason = (signal) => {
731
+ const reason = signal.reason === void 0 ? getDOMException("This operation was aborted.") : signal.reason;
732
+ return reason instanceof Error ? reason : getDOMException(reason);
733
+ };
734
+ function pTimeout(promise, options) {
735
+ const {
736
+ milliseconds,
737
+ fallback,
738
+ message,
739
+ customTimers = { setTimeout, clearTimeout }
740
+ } = options;
741
+ let timer;
742
+ const wrappedPromise = new Promise((resolve, reject) => {
743
+ if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) {
744
+ throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``);
745
+ }
746
+ if (options.signal) {
747
+ const { signal } = options;
748
+ if (signal.aborted) {
749
+ reject(getAbortedReason(signal));
750
+ }
751
+ signal.addEventListener("abort", () => {
752
+ reject(getAbortedReason(signal));
753
+ });
754
+ }
755
+ if (milliseconds === Number.POSITIVE_INFINITY) {
756
+ promise.then(resolve, reject);
757
+ return;
758
+ }
759
+ const timeoutError = new TimeoutError();
760
+ timer = customTimers.setTimeout.call(void 0, () => {
761
+ if (fallback) {
762
+ try {
763
+ resolve(fallback());
764
+ } catch (error) {
765
+ reject(error);
766
+ }
767
+ return;
768
+ }
769
+ if (typeof promise.cancel === "function") {
770
+ promise.cancel();
771
+ }
772
+ if (message === false) {
773
+ resolve();
774
+ } else if (message instanceof Error) {
775
+ reject(message);
776
+ } else {
777
+ timeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;
778
+ reject(timeoutError);
779
+ }
780
+ }, milliseconds);
781
+ (async () => {
782
+ try {
783
+ resolve(await promise);
784
+ } catch (error) {
785
+ reject(error);
786
+ }
787
+ })();
788
+ });
789
+ const cancelablePromise = wrappedPromise.finally(() => {
790
+ cancelablePromise.clear();
791
+ });
792
+ cancelablePromise.clear = () => {
793
+ customTimers.clearTimeout.call(void 0, timer);
794
+ timer = void 0;
795
+ };
796
+ return cancelablePromise;
797
+ }
798
+
799
+ // ../../node_modules/.pnpm/p-queue@8.0.1/node_modules/p-queue/dist/priority-queue.js
800
+ chunkRSTRL2FG_cjs.init_cjs_shims();
801
+
802
+ // ../../node_modules/.pnpm/p-queue@8.0.1/node_modules/p-queue/dist/lower-bound.js
803
+ chunkRSTRL2FG_cjs.init_cjs_shims();
804
+ function lowerBound(array, value, comparator) {
805
+ let first = 0;
806
+ let count = array.length;
807
+ while (count > 0) {
808
+ const step = Math.trunc(count / 2);
809
+ let it = first + step;
810
+ if (comparator(array[it], value) <= 0) {
811
+ first = ++it;
812
+ count -= step + 1;
813
+ } else {
814
+ count = step;
815
+ }
816
+ }
817
+ return first;
818
+ }
819
+
820
+ // ../../node_modules/.pnpm/p-queue@8.0.1/node_modules/p-queue/dist/priority-queue.js
821
+ var PriorityQueue = class {
822
+ #queue = [];
823
+ enqueue(run, options) {
824
+ options = {
825
+ priority: 0,
826
+ ...options
827
+ };
828
+ const element = {
829
+ priority: options.priority,
830
+ run
831
+ };
832
+ if (this.size && this.#queue[this.size - 1].priority >= options.priority) {
833
+ this.#queue.push(element);
834
+ return;
835
+ }
836
+ const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority);
837
+ this.#queue.splice(index, 0, element);
838
+ }
839
+ dequeue() {
840
+ const item = this.#queue.shift();
841
+ return item?.run;
842
+ }
843
+ filter(options) {
844
+ return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);
845
+ }
846
+ get size() {
847
+ return this.#queue.length;
848
+ }
849
+ };
850
+
851
+ // ../../node_modules/.pnpm/p-queue@8.0.1/node_modules/p-queue/dist/index.js
852
+ var PQueue = class extends import_index.default {
853
+ #carryoverConcurrencyCount;
854
+ #isIntervalIgnored;
855
+ #intervalCount = 0;
856
+ #intervalCap;
857
+ #interval;
858
+ #intervalEnd = 0;
859
+ #intervalId;
860
+ #timeoutId;
861
+ #queue;
862
+ #queueClass;
863
+ #pending = 0;
864
+ // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194
865
+ #concurrency;
866
+ #isPaused;
867
+ #throwOnTimeout;
868
+ /**
869
+ Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.
870
+
871
+ Applies to each future operation.
872
+ */
873
+ timeout;
874
+ // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`
875
+ constructor(options) {
876
+ super();
877
+ options = {
878
+ carryoverConcurrencyCount: false,
879
+ intervalCap: Number.POSITIVE_INFINITY,
880
+ interval: 0,
881
+ concurrency: Number.POSITIVE_INFINITY,
882
+ autoStart: true,
883
+ queueClass: PriorityQueue,
884
+ ...options
885
+ };
886
+ if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) {
887
+ throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${options.intervalCap?.toString() ?? ""}\` (${typeof options.intervalCap})`);
888
+ }
889
+ if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) {
890
+ throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${options.interval?.toString() ?? ""}\` (${typeof options.interval})`);
891
+ }
892
+ this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;
893
+ this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;
894
+ this.#intervalCap = options.intervalCap;
895
+ this.#interval = options.interval;
896
+ this.#queue = new options.queueClass();
897
+ this.#queueClass = options.queueClass;
898
+ this.concurrency = options.concurrency;
899
+ this.timeout = options.timeout;
900
+ this.#throwOnTimeout = options.throwOnTimeout === true;
901
+ this.#isPaused = options.autoStart === false;
902
+ }
903
+ get #doesIntervalAllowAnother() {
904
+ return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;
905
+ }
906
+ get #doesConcurrentAllowAnother() {
907
+ return this.#pending < this.#concurrency;
908
+ }
909
+ #next() {
910
+ this.#pending--;
911
+ this.#tryToStartAnother();
912
+ this.emit("next");
913
+ }
914
+ #onResumeInterval() {
915
+ this.#onInterval();
916
+ this.#initializeIntervalIfNeeded();
917
+ this.#timeoutId = void 0;
918
+ }
919
+ get #isIntervalPaused() {
920
+ const now = Date.now();
921
+ if (this.#intervalId === void 0) {
922
+ const delay = this.#intervalEnd - now;
923
+ if (delay < 0) {
924
+ this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;
925
+ } else {
926
+ if (this.#timeoutId === void 0) {
927
+ this.#timeoutId = setTimeout(() => {
928
+ this.#onResumeInterval();
929
+ }, delay);
930
+ }
931
+ return true;
932
+ }
933
+ }
934
+ return false;
935
+ }
936
+ #tryToStartAnother() {
937
+ if (this.#queue.size === 0) {
938
+ if (this.#intervalId) {
939
+ clearInterval(this.#intervalId);
940
+ }
941
+ this.#intervalId = void 0;
942
+ this.emit("empty");
943
+ if (this.#pending === 0) {
944
+ this.emit("idle");
945
+ }
946
+ return false;
947
+ }
948
+ if (!this.#isPaused) {
949
+ const canInitializeInterval = !this.#isIntervalPaused;
950
+ if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {
951
+ const job = this.#queue.dequeue();
952
+ if (!job) {
953
+ return false;
954
+ }
955
+ this.emit("active");
956
+ job();
957
+ if (canInitializeInterval) {
958
+ this.#initializeIntervalIfNeeded();
959
+ }
960
+ return true;
961
+ }
962
+ }
963
+ return false;
964
+ }
965
+ #initializeIntervalIfNeeded() {
966
+ if (this.#isIntervalIgnored || this.#intervalId !== void 0) {
967
+ return;
968
+ }
969
+ this.#intervalId = setInterval(() => {
970
+ this.#onInterval();
971
+ }, this.#interval);
972
+ this.#intervalEnd = Date.now() + this.#interval;
973
+ }
974
+ #onInterval() {
975
+ if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {
976
+ clearInterval(this.#intervalId);
977
+ this.#intervalId = void 0;
978
+ }
979
+ this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;
980
+ this.#processQueue();
981
+ }
982
+ /**
983
+ Executes all queued functions until it reaches the limit.
984
+ */
985
+ #processQueue() {
986
+ while (this.#tryToStartAnother()) {
987
+ }
988
+ }
989
+ get concurrency() {
990
+ return this.#concurrency;
991
+ }
992
+ set concurrency(newConcurrency) {
993
+ if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) {
994
+ throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`);
995
+ }
996
+ this.#concurrency = newConcurrency;
997
+ this.#processQueue();
998
+ }
999
+ async #throwOnAbort(signal) {
1000
+ return new Promise((_resolve, reject) => {
1001
+ signal.addEventListener("abort", () => {
1002
+ reject(signal.reason);
1003
+ }, { once: true });
1004
+ });
1005
+ }
1006
+ async add(function_, options = {}) {
1007
+ options = {
1008
+ timeout: this.timeout,
1009
+ throwOnTimeout: this.#throwOnTimeout,
1010
+ ...options
1011
+ };
1012
+ return new Promise((resolve, reject) => {
1013
+ this.#queue.enqueue(async () => {
1014
+ this.#pending++;
1015
+ this.#intervalCount++;
1016
+ try {
1017
+ options.signal?.throwIfAborted();
1018
+ let operation = function_({ signal: options.signal });
1019
+ if (options.timeout) {
1020
+ operation = pTimeout(Promise.resolve(operation), { milliseconds: options.timeout });
1021
+ }
1022
+ if (options.signal) {
1023
+ operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);
1024
+ }
1025
+ const result = await operation;
1026
+ resolve(result);
1027
+ this.emit("completed", result);
1028
+ } catch (error) {
1029
+ if (error instanceof TimeoutError && !options.throwOnTimeout) {
1030
+ resolve();
1031
+ return;
1032
+ }
1033
+ reject(error);
1034
+ this.emit("error", error);
1035
+ } finally {
1036
+ this.#next();
1037
+ }
1038
+ }, options);
1039
+ this.emit("add");
1040
+ this.#tryToStartAnother();
1041
+ });
1042
+ }
1043
+ async addAll(functions, options) {
1044
+ return Promise.all(functions.map(async (function_) => this.add(function_, options)));
1045
+ }
1046
+ /**
1047
+ Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)
1048
+ */
1049
+ start() {
1050
+ if (!this.#isPaused) {
1051
+ return this;
1052
+ }
1053
+ this.#isPaused = false;
1054
+ this.#processQueue();
1055
+ return this;
1056
+ }
1057
+ /**
1058
+ Put queue execution on hold.
1059
+ */
1060
+ pause() {
1061
+ this.#isPaused = true;
1062
+ }
1063
+ /**
1064
+ Clear the queue.
1065
+ */
1066
+ clear() {
1067
+ this.#queue = new this.#queueClass();
1068
+ }
1069
+ /**
1070
+ Can be called multiple times. Useful if you for example add additional items at a later time.
1071
+
1072
+ @returns A promise that settles when the queue becomes empty.
1073
+ */
1074
+ async onEmpty() {
1075
+ if (this.#queue.size === 0) {
1076
+ return;
1077
+ }
1078
+ await this.#onEvent("empty");
1079
+ }
1080
+ /**
1081
+ @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.
1082
+
1083
+ If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.
1084
+
1085
+ Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.
1086
+ */
1087
+ async onSizeLessThan(limit) {
1088
+ if (this.#queue.size < limit) {
1089
+ return;
1090
+ }
1091
+ await this.#onEvent("next", () => this.#queue.size < limit);
1092
+ }
1093
+ /**
1094
+ The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.
1095
+
1096
+ @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.
1097
+ */
1098
+ async onIdle() {
1099
+ if (this.#pending === 0 && this.#queue.size === 0) {
1100
+ return;
1101
+ }
1102
+ await this.#onEvent("idle");
1103
+ }
1104
+ async #onEvent(event, filter) {
1105
+ return new Promise((resolve) => {
1106
+ const listener = () => {
1107
+ if (filter && !filter()) {
1108
+ return;
1109
+ }
1110
+ this.off(event, listener);
1111
+ resolve();
1112
+ };
1113
+ this.on(event, listener);
1114
+ });
1115
+ }
1116
+ /**
1117
+ Size of the queue, the number of queued items waiting to run.
1118
+ */
1119
+ get size() {
1120
+ return this.#queue.size;
1121
+ }
1122
+ /**
1123
+ Size of the queue, filtered by the given options.
1124
+
1125
+ For example, this can be used to find the number of items remaining in the queue with a specific priority level.
1126
+ */
1127
+ sizeBy(options) {
1128
+ return this.#queue.filter(options).length;
1129
+ }
1130
+ /**
1131
+ Number of running items (no longer in the queue).
1132
+ */
1133
+ get pending() {
1134
+ return this.#pending;
1135
+ }
1136
+ /**
1137
+ Whether the queue is currently paused.
1138
+ */
1139
+ get isPaused() {
1140
+ return this.#isPaused;
1141
+ }
1142
+ };
1143
+
1144
+ // src/FileManager.ts
1145
+ var FileManager = class {
1146
+ #filesByPath = /* @__PURE__ */ new Map();
1147
+ constructor() {
1148
+ return this;
1149
+ }
1150
+ get files() {
1151
+ return [...this.#filesByPath.values()];
1152
+ }
1153
+ get orderedFiles() {
1154
+ return chunk6NKPFDXC_cjs.orderBy(
1155
+ [...this.#filesByPath.values()],
1156
+ [
1157
+ (v) => v?.meta && "pluginKey" in v.meta && !v.meta.pluginKey,
1158
+ (v) => v.path.length,
1159
+ (v) => fs.trimExtName(v.path).endsWith("index"),
1160
+ (v) => fs.trimExtName(v.baseName),
1161
+ (v) => v.path.split(".").pop()
1162
+ ]
1163
+ );
1164
+ }
1165
+ get groupedFiles() {
1166
+ return buildDirectoryTree([...this.#filesByPath.values()]);
1167
+ }
1168
+ get treeNode() {
1169
+ return TreeNode.build([...this.#filesByPath.values()]);
1170
+ }
1171
+ async add(...files) {
1172
+ const promises = files.map((file) => {
1173
+ if (file.override) {
1174
+ return this.#add(file);
1175
+ }
1176
+ return this.#addOrAppend(file);
1177
+ });
1178
+ const resolvedFiles = await Promise.all(promises);
1179
+ if (files.length > 1) {
1180
+ return resolvedFiles;
1181
+ }
1182
+ return resolvedFiles[0];
1183
+ }
1184
+ async #add(file) {
1185
+ const resolvedFile = createFile(file);
1186
+ this.#filesByPath.set(resolvedFile.path, resolvedFile);
1187
+ return resolvedFile;
1188
+ }
1189
+ clear() {
1190
+ this.#filesByPath.clear();
1191
+ }
1192
+ async #addOrAppend(file) {
1193
+ const previousFile = this.#filesByPath.get(file.path);
1194
+ if (previousFile) {
1195
+ this.#filesByPath.delete(previousFile.path);
1196
+ return this.#add(mergeFile(previousFile, file));
1197
+ }
1198
+ return this.#add(file);
1199
+ }
1200
+ getCacheById(id) {
1201
+ return [...this.#filesByPath.values()].find((file) => file.id === id);
1202
+ }
1203
+ getByPath(path) {
1204
+ return this.#filesByPath.get(path);
1205
+ }
1206
+ deleteByPath(path) {
1207
+ const cacheItem = this.getByPath(path);
1208
+ if (!cacheItem) {
1209
+ return;
1210
+ }
1211
+ this.#filesByPath.delete(path);
1212
+ }
1213
+ async getBarrelFiles({ files, meta = {}, root, output, logger }) {
1214
+ const { exportType = "barrelNamed" } = output;
1215
+ const barrelManager = new BarrelManager({ logger });
1216
+ if (exportType === false) {
1217
+ return [];
1218
+ }
1219
+ const pathToBuildFrom = path.join(root, output.path);
1220
+ if (fs.trimExtName(pathToBuildFrom).endsWith("index")) {
1221
+ logger?.emit("warning", "Output has the same fileName as the barrelFiles, please disable barrel generation");
1222
+ return [];
1223
+ }
1224
+ const barrelFiles = barrelManager.getFiles({ files, root: pathToBuildFrom, meta });
1225
+ if (exportType === "barrel") {
1226
+ return barrelFiles.map((file) => {
1227
+ return {
1228
+ ...file,
1229
+ exports: file.exports?.map((exportItem) => {
1230
+ return {
1231
+ ...exportItem,
1232
+ name: void 0
1233
+ };
1234
+ })
1235
+ };
1236
+ });
1237
+ }
1238
+ return barrelFiles.map((indexFile) => {
1239
+ return {
1240
+ ...indexFile,
1241
+ meta
1242
+ };
1243
+ });
1244
+ }
1245
+ async write(...params) {
1246
+ return fs.write(...params);
1247
+ }
1248
+ async read(...params) {
1249
+ return fs.read(...params);
1250
+ }
1251
+ // statics
1252
+ static getMode(path$1) {
1253
+ if (!path$1) {
1254
+ return "split";
1255
+ }
1256
+ return path.extname(path$1) ? "single" : "split";
1257
+ }
1258
+ };
1259
+ async function getSource(file, { logger } = {}) {
1260
+ const parser = await getFileParser(file.extName);
1261
+ const source = await parser.print(file, { logger });
1262
+ return parser.format(source);
1263
+ }
1264
+ function mergeFile(a, b) {
1265
+ return {
1266
+ ...a,
1267
+ sources: [...a.sources || [], ...b.sources || []],
1268
+ imports: [...a.imports || [], ...b.imports || []],
1269
+ exports: [...a.exports || [], ...b.exports || []]
1270
+ };
1271
+ }
1272
+ function combineSources(sources) {
1273
+ return sources.reduce(
1274
+ (prev, curr) => {
1275
+ const prevByName = prev.findLast((imp) => imp.name && imp.name === curr.name);
1276
+ const prevByPathAndIsExportable = prev.findLast((imp) => imp.name === curr.name && imp.isExportable);
1277
+ if (prevByPathAndIsExportable) {
1278
+ return [...prev, curr];
1279
+ }
1280
+ if (prevByName) {
1281
+ prevByName.value = curr.value;
1282
+ prevByName.isExportable = curr.isExportable;
1283
+ prevByName.isTypeOnly = curr.isTypeOnly;
1284
+ prevByName.isIndexable = curr.isIndexable;
1285
+ return prev;
1286
+ }
1287
+ return [...prev, curr];
1288
+ },
1289
+ []
1290
+ );
1291
+ }
1292
+ function combineExports(exports) {
1293
+ return chunk6NKPFDXC_cjs.orderBy(exports, [
1294
+ (v) => !!Array.isArray(v.name),
1295
+ (v) => !v.isTypeOnly,
1296
+ (v) => v.path,
1297
+ (v) => !!v.name,
1298
+ (v) => Array.isArray(v.name) ? chunk6NKPFDXC_cjs.orderBy(v.name) : v.name
1299
+ ]).reduce(
1300
+ (prev, curr) => {
1301
+ const name = curr.name;
1302
+ const prevByPath = prev.findLast((imp) => imp.path === curr.path);
1303
+ const prevByPathAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && remeda.isDeepEqual(imp.name, name) && imp.isTypeOnly);
1304
+ if (prevByPathAndIsTypeOnly) {
1305
+ return prev;
1306
+ }
1307
+ const uniquePrev = prev.findLast(
1308
+ (imp) => imp.path === curr.path && remeda.isDeepEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly && imp.asAlias === curr.asAlias
1309
+ );
1310
+ if (uniquePrev || Array.isArray(name) && !name.length || prevByPath?.asAlias && !curr.asAlias) {
1311
+ return prev;
1312
+ }
1313
+ if (!prevByPath) {
1314
+ return [
1315
+ ...prev,
1316
+ {
1317
+ ...curr,
1318
+ name: Array.isArray(name) ? [...new Set(name)] : name
1319
+ }
1320
+ ];
1321
+ }
1322
+ if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(curr.name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
1323
+ prevByPath.name = [.../* @__PURE__ */ new Set([...prevByPath.name, ...curr.name])];
1324
+ return prev;
1325
+ }
1326
+ return [...prev, curr];
1327
+ },
1328
+ []
1329
+ );
1330
+ }
1331
+ function combineImports(imports, exports, source) {
1332
+ return chunk6NKPFDXC_cjs.orderBy(imports, [
1333
+ (v) => !!Array.isArray(v.name),
1334
+ (v) => !v.isTypeOnly,
1335
+ (v) => v.path,
1336
+ (v) => !!v.name,
1337
+ (v) => Array.isArray(v.name) ? chunk6NKPFDXC_cjs.orderBy(v.name) : v.name
1338
+ ]).reduce(
1339
+ (prev, curr) => {
1340
+ let name = Array.isArray(curr.name) ? [...new Set(curr.name)] : curr.name;
1341
+ const hasImportInSource = (importName) => {
1342
+ if (!source) {
1343
+ return true;
1344
+ }
1345
+ const checker = (name2) => {
1346
+ return name2 && !!source.includes(name2);
1347
+ };
1348
+ return checker(importName) || exports.some(({ name: name2 }) => Array.isArray(name2) ? name2.some(checker) : checker(name2));
1349
+ };
1350
+ if (curr.path === curr.root) {
1351
+ return prev;
1352
+ }
1353
+ if (Array.isArray(name)) {
1354
+ name = name.filter((item) => typeof item === "string" ? hasImportInSource(item) : hasImportInSource(item.propertyName));
1355
+ }
1356
+ const prevByPath = prev.findLast((imp) => imp.path === curr.path && imp.isTypeOnly === curr.isTypeOnly);
1357
+ const uniquePrev = prev.findLast((imp) => imp.path === curr.path && remeda.isDeepEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly);
1358
+ const prevByPathNameAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && remeda.isDeepEqual(imp.name, name) && imp.isTypeOnly);
1359
+ if (prevByPathNameAndIsTypeOnly) {
1360
+ return prev;
1361
+ }
1362
+ if (uniquePrev || Array.isArray(name) && !name.length) {
1363
+ return prev;
1364
+ }
1365
+ if (!prevByPath) {
1366
+ return [
1367
+ ...prev,
1368
+ {
1369
+ ...curr,
1370
+ name
1371
+ }
1372
+ ];
1373
+ }
1374
+ if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
1375
+ prevByPath.name = [.../* @__PURE__ */ new Set([...prevByPath.name, ...name])];
1376
+ return prev;
1377
+ }
1378
+ if (!Array.isArray(name) && name && !hasImportInSource(name)) {
1379
+ return prev;
1380
+ }
1381
+ return [...prev, curr];
1382
+ },
1383
+ []
1384
+ );
1385
+ }
1386
+ var queue = new PQueue({ concurrency: 100 });
1387
+ async function processFiles({ dryRun, config, logger, files }) {
1388
+ const orderedFiles = chunk6NKPFDXC_cjs.orderBy(files, [
1389
+ (v) => v?.meta && "pluginKey" in v.meta && !v.meta.pluginKey,
1390
+ (v) => v.path.length,
1391
+ (v) => fs.trimExtName(v.path).endsWith("index")
1392
+ ]);
1393
+ logger.emit("debug", {
1394
+ date: /* @__PURE__ */ new Date(),
1395
+ logs: [JSON.stringify({ files: orderedFiles }, null, 2)],
1396
+ fileName: "kubb-files.log"
1397
+ });
1398
+ if (!dryRun) {
1399
+ const size = orderedFiles.length;
1400
+ logger.emit("progress_start", { id: "files", size, message: "Writing files ..." });
1401
+ const promises = orderedFiles.map(async (file) => {
1402
+ await queue.add(async () => {
1403
+ const message = file ? `Writing ${path.relative(config.root, file.path)}` : "";
1404
+ const source = await getSource(file, { logger });
1405
+ await fs.write(file.path, source, { sanity: false });
1406
+ logger.emit("progressed", { id: "files", message });
1407
+ });
1408
+ });
1409
+ await Promise.all(promises);
1410
+ logger.emit("progress_stop", { id: "files" });
1411
+ }
1412
+ return files;
1413
+ }
1414
+
1415
+ // src/utils/parser.ts
1416
+ function createFile(file) {
1417
+ const extName = path.extname(file.baseName);
1418
+ if (!extName) {
1419
+ throw new Error(`No extName found for ${file.baseName}`);
1420
+ }
1421
+ const source = file.sources.map((item) => item.value).join("\n\n");
1422
+ const exports = file.exports ? combineExports(file.exports) : [];
1423
+ const imports = file.imports && source ? combineImports(file.imports, exports, source) : [];
1424
+ const sources = file.sources ? combineSources(file.sources) : [];
1425
+ return {
1426
+ ...file,
1427
+ id: hash__default.default({ path: file.path }),
1428
+ name: trimExtName2(file.baseName),
1429
+ extName,
1430
+ imports: imports.map((item) => createFileImport(item)),
1431
+ exports: exports.map((item) => createFileExport(item)),
1432
+ sources: sources.map((item) => createFileSource(item)),
1433
+ meta: file.meta || {}
1434
+ };
1435
+ }
1436
+ function createFileSource(source) {
1437
+ return source;
1438
+ }
1439
+ function createFileImport(imp) {
1440
+ const extName = path.extname(imp.path);
1441
+ return {
1442
+ ...imp,
1443
+ extName: imp.extName ? imp.extName : extName
1444
+ };
1445
+ }
1446
+ function createFileExport(exp) {
1447
+ const extName = path.extname(exp.path);
1448
+ return {
1449
+ ...exp,
1450
+ extName: exp.extName ? exp.extName : extName
1451
+ };
1452
+ }
1453
+ function createFileParser(parser) {
1454
+ return parser;
1455
+ }
1456
+ var typeScriptParser = createFileParser({
1457
+ render() {
1458
+ return void 0;
1459
+ },
1460
+ async format(source) {
1461
+ const module = await import('@kubb/parser-ts');
1462
+ return module.format(source);
1463
+ },
1464
+ async print(file) {
1465
+ const module = await import('@kubb/parser-ts');
1466
+ const source = file.sources.map((item) => item.value).join("\n\n");
1467
+ const importNodes = file.imports.map((item) => {
1468
+ const path = item.root ? fs.getRelativePath(item.root, item.path) : item.path;
1469
+ return module.factory.createImportDeclaration({
1470
+ name: item.name,
1471
+ path,
1472
+ isTypeOnly: item.isTypeOnly
1473
+ });
1474
+ }).filter(Boolean);
1475
+ const exportNodes = file.exports.map((item) => {
1476
+ return module.factory.createExportDeclaration({
1477
+ name: item.name,
1478
+ path: item.path,
1479
+ isTypeOnly: item.isTypeOnly,
1480
+ asAlias: item.asAlias
1481
+ });
1482
+ }).filter(Boolean);
1483
+ return [file.banner, module.print([...importNodes, ...exportNodes]), source, file.footer].join("\n");
1484
+ }
1485
+ });
1486
+ var defaultParser = createFileParser({
1487
+ render() {
1488
+ return void 0;
1489
+ },
1490
+ async format(source) {
1491
+ return source;
1492
+ },
1493
+ async print(file, { logger }) {
1494
+ return file.sources.map((item) => item.value).join("\n\n");
1495
+ }
1496
+ });
1497
+ var parsers = {
1498
+ ".ts": typeScriptParser,
1499
+ ".js": typeScriptParser,
1500
+ ".jsx": typeScriptParser,
1501
+ ".tsx": typeScriptParser,
1502
+ ".json": defaultParser
1503
+ };
1504
+ async function getFileParser(extName) {
1505
+ if (!extName) {
1506
+ return defaultParser;
1507
+ }
1508
+ const parser = parsers[extName];
1509
+ if (!parser) {
1510
+ console.warn(`[parser] No parser found for ${extName}, default parser will be used`);
1511
+ }
1512
+ return parser || defaultParser;
1513
+ }
1514
+ function trimExtName2(text) {
1515
+ const extName = text.split(".").pop();
1516
+ return text.replace(`.${extName}`, "");
1517
+ }
1518
+
1519
+ exports.FileManager = FileManager;
1520
+ exports.FunctionParams = FunctionParams;
1521
+ exports.URLPath = URLPath;
1522
+ exports.createFile = createFile;
1523
+ exports.createFileExport = createFileExport;
1524
+ exports.createFileImport = createFileImport;
1525
+ exports.createFileParser = createFileParser;
1526
+ exports.getFileParser = getFileParser;
1527
+ exports.getSource = getSource;
1528
+ exports.getUniqueName = getUniqueName;
1529
+ exports.isPromise = isPromise;
1530
+ exports.isPromiseFulfilledResult = isPromiseFulfilledResult;
1531
+ exports.isPromiseRejectedResult = isPromiseRejectedResult;
1532
+ exports.processFiles = processFiles;
1533
+ exports.renderTemplate = renderTemplate;
1534
+ exports.setUniqueName = setUniqueName;
1535
+ exports.timeout = timeout;
1536
+ //# sourceMappingURL=chunk-MHOAMP5V.cjs.map
1537
+ //# sourceMappingURL=chunk-MHOAMP5V.cjs.map