@kubb/core 3.15.1 → 3.16.1

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