@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
@@ -0,0 +1,943 @@
1
+ 'use strict';
2
+
3
+ var chunkBHSTNFNQ_cjs = require('./chunk-BHSTNFNQ.cjs');
4
+ var chunkE4XLCCPK_cjs = require('./chunk-E4XLCCPK.cjs');
5
+ var path = require('path');
6
+ var hash = require('object-hash');
7
+ var remeda = require('remeda');
8
+ var pLimit = require('p-limit');
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
+ var pLimit__default = /*#__PURE__*/_interopDefault(pLimit);
15
+
16
+ // src/utils/FunctionParams.ts
17
+ var FunctionParams = class _FunctionParams {
18
+ #items = [];
19
+ constructor() {
20
+ return this;
21
+ }
22
+ get items() {
23
+ return this.#items.flat();
24
+ }
25
+ add(item) {
26
+ if (!item) {
27
+ return this;
28
+ }
29
+ if (Array.isArray(item)) {
30
+ item.filter(Boolean).forEach((it) => this.#items.push(it));
31
+ return this;
32
+ }
33
+ this.#items.push(item);
34
+ return this;
35
+ }
36
+ static #orderItems(items) {
37
+ return chunkBHSTNFNQ_cjs.orderBy(
38
+ items.filter(Boolean),
39
+ [
40
+ (v) => {
41
+ if (Array.isArray(v)) {
42
+ return void 0;
43
+ }
44
+ return !v.default;
45
+ },
46
+ (v) => {
47
+ if (Array.isArray(v)) {
48
+ return void 0;
49
+ }
50
+ return v.required ?? true;
51
+ }
52
+ ],
53
+ ["desc", "desc"]
54
+ );
55
+ }
56
+ static #addParams(acc, item) {
57
+ const { enabled = true, name, type, required = true, ...rest } = item;
58
+ if (!enabled) {
59
+ return acc;
60
+ }
61
+ if (!name) {
62
+ acc.push(`${type}${rest.default ? ` = ${rest.default}` : ""}`);
63
+ return acc;
64
+ }
65
+ const parameterName = name.startsWith("{") ? name : chunkBHSTNFNQ_cjs.camelCase(name);
66
+ if (type) {
67
+ if (required) {
68
+ acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ""}`);
69
+ } else {
70
+ acc.push(`${parameterName}?: ${type}`);
71
+ }
72
+ } else {
73
+ acc.push(`${parameterName}`);
74
+ }
75
+ return acc;
76
+ }
77
+ static toObject(items) {
78
+ let type = [];
79
+ let name = [];
80
+ const enabled = items.every((item) => item.enabled) ? items.at(0)?.enabled : true;
81
+ const required = items.every((item) => item.required) ?? true;
82
+ items.forEach((item) => {
83
+ name = _FunctionParams.#addParams(name, { ...item, type: void 0 });
84
+ if (items.some((item2) => item2.type)) {
85
+ type = _FunctionParams.#addParams(type, item);
86
+ }
87
+ });
88
+ return {
89
+ name: `{ ${name.join(", ")} }`,
90
+ type: type.length ? `{ ${type.join("; ")} }` : void 0,
91
+ enabled,
92
+ required
93
+ };
94
+ }
95
+ static toString(items) {
96
+ const sortedData = _FunctionParams.#orderItems(items);
97
+ return sortedData.reduce((acc, item) => {
98
+ if (Array.isArray(item)) {
99
+ if (item.length <= 0) {
100
+ return acc;
101
+ }
102
+ const subItems = _FunctionParams.#orderItems(item);
103
+ const objectItem = _FunctionParams.toObject(subItems);
104
+ return _FunctionParams.#addParams(acc, objectItem);
105
+ }
106
+ return _FunctionParams.#addParams(acc, item);
107
+ }, []).join(", ");
108
+ }
109
+ toObject() {
110
+ const items = _FunctionParams.#orderItems(this.#items).flat();
111
+ return _FunctionParams.toObject(items);
112
+ }
113
+ toString() {
114
+ const items = _FunctionParams.#orderItems(this.#items);
115
+ return _FunctionParams.toString(items);
116
+ }
117
+ };
118
+
119
+ // src/utils/promise.ts
120
+ function isPromise(result) {
121
+ return !!result && typeof result?.then === "function";
122
+ }
123
+ function isPromiseFulfilledResult(result) {
124
+ return result.status === "fulfilled";
125
+ }
126
+ function isPromiseRejectedResult(result) {
127
+ return result.status === "rejected";
128
+ }
129
+
130
+ // src/utils/renderTemplate.ts
131
+ function renderTemplate(template, data = void 0) {
132
+ if (!data || !Object.keys(data).length) {
133
+ return template.replace(/{{(.*?)}}/g, "");
134
+ }
135
+ const matches = template.match(/{{(.*?)}}/g);
136
+ return matches?.reduce((prev, curr) => {
137
+ const index = curr.split(/{{|}}/).filter(Boolean)[0]?.trim();
138
+ if (index === void 0) {
139
+ return prev;
140
+ }
141
+ const value = data[index];
142
+ if (value === void 0) {
143
+ return prev;
144
+ }
145
+ return prev.replace(curr, () => {
146
+ if (typeof value === "boolean") {
147
+ return `${value.toString()}` || "false";
148
+ }
149
+ return value || "";
150
+ }).trim();
151
+ }, template) || "";
152
+ }
153
+
154
+ // src/utils/timeout.ts
155
+ async function timeout(ms) {
156
+ return new Promise((resolve) => {
157
+ setTimeout(() => {
158
+ resolve(true);
159
+ }, ms);
160
+ });
161
+ }
162
+
163
+ // src/utils/uniqueName.ts
164
+ function getUniqueName(originalName, data) {
165
+ let used = data[originalName] || 0;
166
+ if (used) {
167
+ data[originalName] = ++used;
168
+ originalName += used;
169
+ }
170
+ data[originalName] = 1;
171
+ return originalName;
172
+ }
173
+ function setUniqueName(originalName, data) {
174
+ let used = data[originalName] || 0;
175
+ if (used) {
176
+ data[originalName] = ++used;
177
+ return originalName;
178
+ }
179
+ data[originalName] = 1;
180
+ return originalName;
181
+ }
182
+
183
+ // src/utils/URLPath.ts
184
+ var URLPath = class {
185
+ path;
186
+ #options;
187
+ constructor(path2, options = {}) {
188
+ this.path = path2;
189
+ this.#options = options;
190
+ return this;
191
+ }
192
+ /**
193
+ * Convert Swagger path to URLPath(syntax of Express)
194
+ * @example /pet/{petId} => /pet/:petId
195
+ */
196
+ get URL() {
197
+ return this.toURLPath();
198
+ }
199
+ get isURL() {
200
+ try {
201
+ const url = new URL(this.path);
202
+ if (url?.href) {
203
+ return true;
204
+ }
205
+ } catch (_error) {
206
+ return false;
207
+ }
208
+ return false;
209
+ }
210
+ /**
211
+ * Convert Swagger path to template literals/ template strings(camelcase)
212
+ * @example /pet/{petId} => `/pet/${petId}`
213
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
214
+ * @example /account/userID => `/account/${userId}`
215
+ */
216
+ get template() {
217
+ return this.toTemplateString();
218
+ }
219
+ get object() {
220
+ return this.toObject();
221
+ }
222
+ get params() {
223
+ return this.getParams();
224
+ }
225
+ toObject({ type = "path", replacer, stringify } = {}) {
226
+ const object = {
227
+ url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
228
+ params: this.getParams()
229
+ };
230
+ if (stringify) {
231
+ if (type === "template") {
232
+ return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
233
+ }
234
+ if (object.params) {
235
+ return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
236
+ }
237
+ return `{ url: '${object.url}' }`;
238
+ }
239
+ return object;
240
+ }
241
+ /**
242
+ * Convert Swagger path to template literals/ template strings(camelcase)
243
+ * @example /pet/{petId} => `/pet/${petId}`
244
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
245
+ * @example /account/userID => `/account/${userId}`
246
+ */
247
+ toTemplateString({ prefix = "", replacer } = {}) {
248
+ const regex = /{(\w|-)*}/g;
249
+ const found = this.path.match(regex);
250
+ let newPath = this.path.replaceAll("{", "${");
251
+ if (found) {
252
+ newPath = found.reduce((prev, path2) => {
253
+ const pathWithoutBrackets = path2.replaceAll("{", "").replaceAll("}", "");
254
+ let param = chunkBHSTNFNQ_cjs.isValidVarName(pathWithoutBrackets) ? pathWithoutBrackets : chunkBHSTNFNQ_cjs.camelCase(pathWithoutBrackets);
255
+ if (this.#options.casing === "camelcase") {
256
+ param = chunkBHSTNFNQ_cjs.camelCase(param);
257
+ }
258
+ return prev.replace(path2, `\${${replacer ? replacer(param) : param}}`);
259
+ }, this.path);
260
+ }
261
+ return `\`${prefix}${newPath}\``;
262
+ }
263
+ getParams(replacer) {
264
+ const regex = /{(\w|-)*}/g;
265
+ const found = this.path.match(regex);
266
+ if (!found) {
267
+ return void 0;
268
+ }
269
+ const params = {};
270
+ found.forEach((item) => {
271
+ item = item.replaceAll("{", "").replaceAll("}", "");
272
+ let param = chunkBHSTNFNQ_cjs.isValidVarName(item) ? item : chunkBHSTNFNQ_cjs.camelCase(item);
273
+ if (this.#options.casing === "camelcase") {
274
+ param = chunkBHSTNFNQ_cjs.camelCase(param);
275
+ }
276
+ const key = replacer ? replacer(param) : param;
277
+ params[key] = key;
278
+ }, this.path);
279
+ return params;
280
+ }
281
+ /**
282
+ * Convert Swagger path to URLPath(syntax of Express)
283
+ * @example /pet/{petId} => /pet/:petId
284
+ */
285
+ toURLPath() {
286
+ return this.path.replaceAll("{", ":").replaceAll("}", "");
287
+ }
288
+ };
289
+
290
+ // src/utils/TreeNode.ts
291
+ var TreeNode = class _TreeNode {
292
+ data;
293
+ parent;
294
+ children = [];
295
+ #cachedLeaves = void 0;
296
+ constructor(data, parent) {
297
+ this.data = data;
298
+ this.parent = parent;
299
+ return this;
300
+ }
301
+ addChild(data) {
302
+ const child = new _TreeNode(data, this);
303
+ if (!this.children) {
304
+ this.children = [];
305
+ }
306
+ this.children.push(child);
307
+ return child;
308
+ }
309
+ get root() {
310
+ if (!this.parent) {
311
+ return this;
312
+ }
313
+ return this.parent.root;
314
+ }
315
+ get leaves() {
316
+ if (!this.children || this.children.length === 0) {
317
+ return [this];
318
+ }
319
+ if (this.#cachedLeaves) {
320
+ return this.#cachedLeaves;
321
+ }
322
+ const leaves = [];
323
+ if (this.children) {
324
+ for (let i = 0, { length } = this.children; i < length; i++) {
325
+ leaves.push.apply(leaves, this.children[i].leaves);
326
+ }
327
+ }
328
+ this.#cachedLeaves = leaves;
329
+ return leaves;
330
+ }
331
+ forEach(callback) {
332
+ if (typeof callback !== "function") {
333
+ throw new TypeError("forEach() callback must be a function");
334
+ }
335
+ callback(this);
336
+ if (this.children) {
337
+ for (let i = 0, { length } = this.children; i < length; i++) {
338
+ this.children[i]?.forEach(callback);
339
+ }
340
+ }
341
+ return this;
342
+ }
343
+ findDeep(predicate) {
344
+ if (typeof predicate !== "function") {
345
+ throw new TypeError("find() predicate must be a function");
346
+ }
347
+ return this.leaves.find(predicate);
348
+ }
349
+ forEachDeep(callback) {
350
+ if (typeof callback !== "function") {
351
+ throw new TypeError("forEach() callback must be a function");
352
+ }
353
+ this.leaves.forEach(callback);
354
+ }
355
+ filterDeep(callback) {
356
+ if (typeof callback !== "function") {
357
+ throw new TypeError("filter() callback must be a function");
358
+ }
359
+ return this.leaves.filter(callback);
360
+ }
361
+ mapDeep(callback) {
362
+ if (typeof callback !== "function") {
363
+ throw new TypeError("map() callback must be a function");
364
+ }
365
+ return this.leaves.map(callback);
366
+ }
367
+ static build(files, root) {
368
+ try {
369
+ const filteredTree = buildDirectoryTree(files, root);
370
+ if (!filteredTree) {
371
+ return null;
372
+ }
373
+ const treeNode = new _TreeNode({
374
+ name: filteredTree.name,
375
+ path: filteredTree.path,
376
+ file: filteredTree.file,
377
+ type: FileManager.getMode(filteredTree.path)
378
+ });
379
+ const recurse = (node, item) => {
380
+ const subNode = node.addChild({
381
+ name: item.name,
382
+ path: item.path,
383
+ file: item.file,
384
+ type: FileManager.getMode(item.path)
385
+ });
386
+ if (item.children?.length) {
387
+ item.children?.forEach((child) => {
388
+ recurse(subNode, child);
389
+ });
390
+ }
391
+ };
392
+ filteredTree.children?.forEach((child) => recurse(treeNode, child));
393
+ return treeNode;
394
+ } catch (e) {
395
+ throw new Error("Something went wrong with creating barrel files with the TreeNode class", { cause: e });
396
+ }
397
+ }
398
+ };
399
+ var normalizePath = (p) => p.replace(/\\/g, "/");
400
+ function buildDirectoryTree(files, rootFolder = "") {
401
+ const normalizedRootFolder = normalizePath(rootFolder);
402
+ const rootPrefix = normalizedRootFolder.endsWith("/") ? normalizedRootFolder : `${normalizedRootFolder}/`;
403
+ const filteredFiles = files.filter((file) => {
404
+ const normalizedFilePath = normalizePath(file.path);
405
+ return rootFolder ? normalizedFilePath.startsWith(rootPrefix) && !normalizedFilePath.endsWith(".json") : !normalizedFilePath.endsWith(".json");
406
+ });
407
+ if (filteredFiles.length === 0) {
408
+ return null;
409
+ }
410
+ const root = {
411
+ name: rootFolder || "",
412
+ path: rootFolder || "",
413
+ children: []
414
+ };
415
+ filteredFiles.forEach((file) => {
416
+ const path2 = file.path.slice(rootFolder.length);
417
+ const parts = path2.split("/");
418
+ let currentLevel = root.children;
419
+ let currentPath = rootFolder;
420
+ parts.forEach((part, index) => {
421
+ if (index !== 0) {
422
+ currentPath += `/${part}`;
423
+ } else {
424
+ currentPath += `${part}`;
425
+ }
426
+ let existingNode = currentLevel.find((node) => node.name === part);
427
+ if (!existingNode) {
428
+ if (index === parts.length - 1) {
429
+ existingNode = {
430
+ name: part,
431
+ file,
432
+ path: currentPath
433
+ };
434
+ } else {
435
+ existingNode = {
436
+ name: part,
437
+ path: currentPath,
438
+ children: []
439
+ };
440
+ }
441
+ currentLevel.push(existingNode);
442
+ }
443
+ if (!existingNode.file) {
444
+ currentLevel = existingNode.children;
445
+ }
446
+ });
447
+ });
448
+ return root;
449
+ }
450
+
451
+ // src/BarrelManager.ts
452
+ var BarrelManager = class {
453
+ #options;
454
+ constructor(options = {}) {
455
+ this.#options = options;
456
+ return this;
457
+ }
458
+ getFiles({ files: generatedFiles, root }) {
459
+ const { logger } = this.#options;
460
+ const cachedFiles = /* @__PURE__ */ new Map();
461
+ TreeNode.build(generatedFiles, root)?.forEach((treeNode) => {
462
+ if (!treeNode || !treeNode.children || !treeNode.parent?.data.path) {
463
+ return void 0;
464
+ }
465
+ const barrelFile = {
466
+ path: path.join(treeNode.parent?.data.path, "index.ts"),
467
+ baseName: "index.ts",
468
+ exports: [],
469
+ sources: []
470
+ };
471
+ const previousBarrelFile = cachedFiles.get(barrelFile.path);
472
+ const leaves = treeNode.leaves;
473
+ leaves.forEach((item) => {
474
+ if (!item.data.name) {
475
+ return void 0;
476
+ }
477
+ const sources = item.data.file?.sources || [];
478
+ if (!sources.some((source) => source.isIndexable)) {
479
+ logger?.emit(
480
+ "warning",
481
+ `No isIndexable source found(source should have a name and isIndexable):
482
+ File: ${JSON.stringify(item.data.file, void 0, 2)}`
483
+ );
484
+ }
485
+ sources.forEach((source) => {
486
+ if (!item.data.file?.path || !source.isIndexable || !source.name) {
487
+ return void 0;
488
+ }
489
+ const alreadyContainInPreviousBarrelFile = previousBarrelFile?.sources.some(
490
+ (item2) => item2.name === source.name && item2.isTypeOnly === source.isTypeOnly
491
+ );
492
+ if (alreadyContainInPreviousBarrelFile) {
493
+ return void 0;
494
+ }
495
+ if (!barrelFile.exports) {
496
+ barrelFile.exports = [];
497
+ }
498
+ const isSubExport = !!treeNode.parent?.data.path?.split?.("/")?.length;
499
+ if (isSubExport) {
500
+ barrelFile.exports.push({
501
+ name: [source.name],
502
+ path: chunkE4XLCCPK_cjs.getRelativePath(treeNode.parent?.data.path, item.data.path),
503
+ isTypeOnly: source.isTypeOnly
504
+ });
505
+ } else {
506
+ barrelFile.exports.push({
507
+ name: [source.name],
508
+ path: `./${item.data.file.baseName}`,
509
+ isTypeOnly: source.isTypeOnly
510
+ });
511
+ }
512
+ barrelFile.sources.push({
513
+ name: source.name,
514
+ isTypeOnly: source.isTypeOnly,
515
+ //TODO use parser to generate import
516
+ value: "",
517
+ isExportable: false,
518
+ isIndexable: false
519
+ });
520
+ });
521
+ });
522
+ if (previousBarrelFile) {
523
+ previousBarrelFile.sources.push(...barrelFile.sources);
524
+ previousBarrelFile.exports?.push(...barrelFile.exports || []);
525
+ } else {
526
+ cachedFiles.set(barrelFile.path, barrelFile);
527
+ }
528
+ });
529
+ return [...cachedFiles.values()];
530
+ }
531
+ };
532
+
533
+ // src/utils/Cache.ts
534
+ var Cache = class {
535
+ #buffer = /* @__PURE__ */ new Map();
536
+ async get(key) {
537
+ return this.#buffer.get(key) ?? null;
538
+ }
539
+ async set(key, value) {
540
+ this.#buffer.set(key, value);
541
+ }
542
+ async delete(key) {
543
+ this.#buffer.delete(key);
544
+ }
545
+ async clear() {
546
+ this.#buffer.clear();
547
+ }
548
+ async keys() {
549
+ return [...this.#buffer.keys()];
550
+ }
551
+ async values() {
552
+ return [...this.#buffer.values()];
553
+ }
554
+ async flush() {
555
+ }
556
+ };
557
+
558
+ // src/FileManager.ts
559
+ var FileManager = class {
560
+ #cache = new Cache();
561
+ #limit = pLimit__default.default(100);
562
+ constructor() {
563
+ return this;
564
+ }
565
+ async add(...files) {
566
+ const resolvedFiles = [];
567
+ const mergedFiles = /* @__PURE__ */ new Map();
568
+ files.forEach((file) => {
569
+ const existing = mergedFiles.get(file.path);
570
+ if (existing) {
571
+ mergedFiles.set(file.path, mergeFile(existing, file));
572
+ } else {
573
+ mergedFiles.set(file.path, file);
574
+ }
575
+ });
576
+ for (const file of mergedFiles.values()) {
577
+ const existing = await this.#cache.get(file.path);
578
+ const merged = existing ? mergeFile(existing, file) : file;
579
+ const resolvedFile = createFile(merged);
580
+ await this.#cache.set(resolvedFile.path, resolvedFile);
581
+ await this.#cache.flush();
582
+ resolvedFiles.push(resolvedFile);
583
+ }
584
+ if (files.length > 1) {
585
+ return resolvedFiles;
586
+ }
587
+ return resolvedFiles[0];
588
+ }
589
+ async getByPath(path2) {
590
+ return this.#cache.get(path2);
591
+ }
592
+ async deleteByPath(path2) {
593
+ await this.#cache.delete(path2);
594
+ }
595
+ async clear() {
596
+ await this.#cache.clear();
597
+ }
598
+ async getFiles() {
599
+ const cachedKeys = await this.#cache.keys();
600
+ const keys = chunkBHSTNFNQ_cjs.orderBy(cachedKeys, [(v) => v.length, (v) => chunkE4XLCCPK_cjs.trimExtName(v).endsWith("index")]);
601
+ const filesTasks = keys.map(
602
+ (key) => this.#limit(async () => {
603
+ const file = await this.#cache.get(key);
604
+ return file;
605
+ })
606
+ );
607
+ const files = await Promise.all(filesTasks);
608
+ return files.filter(Boolean);
609
+ }
610
+ async processFiles({ dryRun, root, extension, logger }) {
611
+ const files = await this.getFiles();
612
+ logger?.emit("progress_start", { id: "files", size: files.length, message: "Writing files ..." });
613
+ const promises = files.map((file) => {
614
+ return this.#limit(async () => {
615
+ const message = file ? `Writing ${path.relative(root, file.path)}` : "";
616
+ const extname2 = extension?.[file.extname] || void 0;
617
+ if (!dryRun) {
618
+ const source = await getSource(file, { logger, extname: extname2 });
619
+ await chunkE4XLCCPK_cjs.write(file.path, source, { sanity: false });
620
+ }
621
+ logger?.emit("progressed", { id: "files", message });
622
+ });
623
+ });
624
+ await Promise.all(promises);
625
+ logger?.emit("progress_stop", { id: "files" });
626
+ return files;
627
+ }
628
+ async getBarrelFiles({ type, meta = {}, root, output, logger }) {
629
+ if (!type || type === "propagate") {
630
+ return [];
631
+ }
632
+ const barrelManager = new BarrelManager({ logger });
633
+ const files = await this.getFiles();
634
+ const pathToBuildFrom = path.join(root, output.path);
635
+ if (chunkE4XLCCPK_cjs.trimExtName(pathToBuildFrom).endsWith("index")) {
636
+ logger?.emit("warning", "Output has the same fileName as the barrelFiles, please disable barrel generation");
637
+ return [];
638
+ }
639
+ const barrelFiles = barrelManager.getFiles({ files, root: pathToBuildFrom, meta });
640
+ if (type === "all") {
641
+ return barrelFiles.map((file) => {
642
+ return {
643
+ ...file,
644
+ exports: file.exports?.map((exportItem) => {
645
+ return {
646
+ ...exportItem,
647
+ name: void 0
648
+ };
649
+ })
650
+ };
651
+ });
652
+ }
653
+ return barrelFiles.map((indexFile) => {
654
+ return {
655
+ ...indexFile,
656
+ meta
657
+ };
658
+ });
659
+ }
660
+ // statics
661
+ static getMode(path2) {
662
+ if (!path2) {
663
+ return "split";
664
+ }
665
+ return path.extname(path2) ? "single" : "split";
666
+ }
667
+ };
668
+ async function getSource(file, { logger, extname: extname2 } = {}) {
669
+ const parser = await getFileParser(file.extname);
670
+ const source = await parser.print(file, { logger, extname: extname2 });
671
+ return parser.format(source).catch((err) => {
672
+ console.warn(err);
673
+ return source;
674
+ });
675
+ }
676
+ function mergeFile(a, b) {
677
+ return {
678
+ ...a,
679
+ sources: [...a.sources || [], ...b.sources || []],
680
+ imports: [...a.imports || [], ...b.imports || []],
681
+ exports: [...a.exports || [], ...b.exports || []]
682
+ };
683
+ }
684
+ function combineSources(sources) {
685
+ return remeda.uniqueBy(sources, (obj) => [obj.name, obj.isExportable, obj.isTypeOnly]);
686
+ }
687
+ function combineExports(exports) {
688
+ return chunkBHSTNFNQ_cjs.orderBy(exports, [
689
+ (v) => !!Array.isArray(v.name),
690
+ (v) => !v.isTypeOnly,
691
+ (v) => v.path,
692
+ (v) => !!v.name,
693
+ (v) => Array.isArray(v.name) ? chunkBHSTNFNQ_cjs.orderBy(v.name) : v.name
694
+ ]).reduce(
695
+ (prev, curr) => {
696
+ const name = curr.name;
697
+ const prevByPath = prev.findLast((imp) => imp.path === curr.path);
698
+ const prevByPathAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && remeda.isDeepEqual(imp.name, name) && imp.isTypeOnly);
699
+ if (prevByPathAndIsTypeOnly) {
700
+ return prev;
701
+ }
702
+ const uniquePrev = prev.findLast(
703
+ (imp) => imp.path === curr.path && remeda.isDeepEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly && imp.asAlias === curr.asAlias
704
+ );
705
+ if (uniquePrev || Array.isArray(name) && !name.length || prevByPath?.asAlias && !curr.asAlias) {
706
+ return prev;
707
+ }
708
+ if (!prevByPath) {
709
+ return [
710
+ ...prev,
711
+ {
712
+ ...curr,
713
+ name: Array.isArray(name) ? [...new Set(name)] : name
714
+ }
715
+ ];
716
+ }
717
+ if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(curr.name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
718
+ prevByPath.name = [.../* @__PURE__ */ new Set([...prevByPath.name, ...curr.name])];
719
+ return prev;
720
+ }
721
+ return [...prev, curr];
722
+ },
723
+ []
724
+ );
725
+ }
726
+ function combineImports(imports, exports, source) {
727
+ return chunkBHSTNFNQ_cjs.orderBy(imports, [
728
+ (v) => !!Array.isArray(v.name),
729
+ (v) => !v.isTypeOnly,
730
+ (v) => v.path,
731
+ (v) => !!v.name,
732
+ (v) => Array.isArray(v.name) ? chunkBHSTNFNQ_cjs.orderBy(v.name) : v.name
733
+ ]).reduce(
734
+ (prev, curr) => {
735
+ let name = Array.isArray(curr.name) ? [...new Set(curr.name)] : curr.name;
736
+ const hasImportInSource = (importName) => {
737
+ if (!source) {
738
+ return true;
739
+ }
740
+ const checker = (name2) => {
741
+ return name2 && source.includes(name2);
742
+ };
743
+ return checker(importName) || exports.some(({ name: name2 }) => Array.isArray(name2) ? name2.some(checker) : checker(name2));
744
+ };
745
+ if (curr.path === curr.root) {
746
+ return prev;
747
+ }
748
+ if (Array.isArray(name)) {
749
+ name = name.filter((item) => typeof item === "string" ? hasImportInSource(item) : hasImportInSource(item.propertyName));
750
+ }
751
+ const prevByPath = prev.findLast((imp) => imp.path === curr.path && imp.isTypeOnly === curr.isTypeOnly);
752
+ const uniquePrev = prev.findLast((imp) => imp.path === curr.path && remeda.isDeepEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly);
753
+ const prevByPathNameAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && remeda.isDeepEqual(imp.name, name) && imp.isTypeOnly);
754
+ if (prevByPathNameAndIsTypeOnly) {
755
+ return prev;
756
+ }
757
+ if (uniquePrev || Array.isArray(name) && !name.length) {
758
+ return prev;
759
+ }
760
+ if (!prevByPath) {
761
+ return [
762
+ ...prev,
763
+ {
764
+ ...curr,
765
+ name
766
+ }
767
+ ];
768
+ }
769
+ if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
770
+ prevByPath.name = [.../* @__PURE__ */ new Set([...prevByPath.name, ...name])];
771
+ return prev;
772
+ }
773
+ if (!Array.isArray(name) && name && !hasImportInSource(name)) {
774
+ return prev;
775
+ }
776
+ return [...prev, curr];
777
+ },
778
+ []
779
+ );
780
+ }
781
+
782
+ // src/utils/parser.ts
783
+ function getDefaultBanner({ title, description, version, config }) {
784
+ try {
785
+ let source = "";
786
+ if ("path" in config.input) {
787
+ source = path__default.default.basename(config.input.path);
788
+ } else if ("data" in config.input) {
789
+ source = "text content";
790
+ }
791
+ let banner = "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n";
792
+ if (config.output.defaultBanner === "simple") {
793
+ banner += "*/\n";
794
+ return banner;
795
+ }
796
+ if (source) {
797
+ banner += `* Source: ${source}
798
+ `;
799
+ }
800
+ if (title) {
801
+ banner += `* Title: ${title}
802
+ `;
803
+ }
804
+ if (description) {
805
+ const formattedDescription = description.replace(/\n/gm, "\n* ");
806
+ banner += `* Description: ${formattedDescription}
807
+ `;
808
+ }
809
+ if (version) {
810
+ banner += `* OpenAPI spec version: ${version}
811
+ `;
812
+ }
813
+ banner += "*/\n";
814
+ return banner;
815
+ } catch (_error) {
816
+ return "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n*/";
817
+ }
818
+ }
819
+ function createFile(file) {
820
+ const extname2 = path__default.default.extname(file.baseName);
821
+ if (!extname2) {
822
+ throw new Error(`No extname found for ${file.baseName}`);
823
+ }
824
+ const source = file.sources.map((item) => item.value).join("\n\n");
825
+ const exports = file.exports?.length ? combineExports(file.exports) : [];
826
+ const imports = file.imports?.length && source ? combineImports(file.imports, exports, source) : [];
827
+ const sources = file.sources?.length ? combineSources(file.sources) : [];
828
+ return {
829
+ ...file,
830
+ id: hash__default.default({ path: file.path }),
831
+ name: trimExtName2(file.baseName),
832
+ extname: extname2,
833
+ imports: imports.map(createFileImport),
834
+ exports: exports.map(createFileExport),
835
+ sources: sources.map(createFileSource),
836
+ meta: file.meta || {}
837
+ };
838
+ }
839
+ function createFileSource(source) {
840
+ return source;
841
+ }
842
+ function createFileImport(imp) {
843
+ return {
844
+ ...imp
845
+ };
846
+ }
847
+ function createFileExport(exp) {
848
+ return {
849
+ ...exp
850
+ };
851
+ }
852
+ function createFileParser(parser) {
853
+ return parser;
854
+ }
855
+ var typeScriptParser = createFileParser({
856
+ async format(source) {
857
+ const module = await import('@kubb/parser-ts');
858
+ return module.format(source);
859
+ },
860
+ async print(file, options = { extname: ".ts" }) {
861
+ const module = await import('@kubb/parser-ts');
862
+ const source = file.sources.map((item) => item.value).join("\n\n");
863
+ const importNodes = file.imports.map((item) => {
864
+ const importPath = item.root ? chunkE4XLCCPK_cjs.getRelativePath(item.root, item.path) : item.path;
865
+ const hasExtname = !!path__default.default.extname(importPath);
866
+ return module.factory.createImportDeclaration({
867
+ name: item.name,
868
+ path: options.extname && hasExtname ? `${trimExtName2(importPath)}${options.extname}` : item.root ? trimExtName2(importPath) : importPath,
869
+ isTypeOnly: item.isTypeOnly
870
+ });
871
+ }).filter(Boolean);
872
+ const exportNodes = file.exports.map((item) => {
873
+ const exportPath = item.path;
874
+ const hasExtname = !!path__default.default.extname(exportPath);
875
+ return module.factory.createExportDeclaration({
876
+ name: item.name,
877
+ path: options.extname && hasExtname ? `${trimExtName2(item.path)}${options.extname}` : trimExtName2(item.path),
878
+ isTypeOnly: item.isTypeOnly,
879
+ asAlias: item.asAlias
880
+ });
881
+ }).filter(Boolean);
882
+ return [file.banner, module.print([...importNodes, ...exportNodes]), source, file.footer].join("\n");
883
+ }
884
+ });
885
+ var tsxParser = createFileParser({
886
+ async format(source) {
887
+ const module = await import('@kubb/parser-ts');
888
+ return module.format(source);
889
+ },
890
+ async print(file, options = { extname: ".tsx" }) {
891
+ return typeScriptParser.print(file, options);
892
+ }
893
+ });
894
+ var defaultParser = createFileParser({
895
+ async format(source) {
896
+ return source;
897
+ },
898
+ async print(file) {
899
+ return file.sources.map((item) => item.value).join("\n\n");
900
+ }
901
+ });
902
+ var parsers = {
903
+ ".ts": typeScriptParser,
904
+ ".js": typeScriptParser,
905
+ ".jsx": tsxParser,
906
+ ".tsx": tsxParser,
907
+ ".json": defaultParser
908
+ };
909
+ async function getFileParser(extname2) {
910
+ if (!extname2) {
911
+ return defaultParser;
912
+ }
913
+ const parser = parsers[extname2];
914
+ if (!parser) {
915
+ console.warn(`[parser] No parser found for ${extname2}, default parser will be used`);
916
+ }
917
+ return parser || defaultParser;
918
+ }
919
+ function trimExtName2(text) {
920
+ const extname2 = text.split(".").pop();
921
+ return text.replace(`.${extname2}`, "");
922
+ }
923
+
924
+ exports.Cache = Cache;
925
+ exports.FileManager = FileManager;
926
+ exports.FunctionParams = FunctionParams;
927
+ exports.URLPath = URLPath;
928
+ exports.createFile = createFile;
929
+ exports.createFileExport = createFileExport;
930
+ exports.createFileImport = createFileImport;
931
+ exports.createFileParser = createFileParser;
932
+ exports.getDefaultBanner = getDefaultBanner;
933
+ exports.getFileParser = getFileParser;
934
+ exports.getSource = getSource;
935
+ exports.getUniqueName = getUniqueName;
936
+ exports.isPromise = isPromise;
937
+ exports.isPromiseFulfilledResult = isPromiseFulfilledResult;
938
+ exports.isPromiseRejectedResult = isPromiseRejectedResult;
939
+ exports.renderTemplate = renderTemplate;
940
+ exports.setUniqueName = setUniqueName;
941
+ exports.timeout = timeout;
942
+ //# sourceMappingURL=chunk-QR7CQIA3.cjs.map
943
+ //# sourceMappingURL=chunk-QR7CQIA3.cjs.map