@kubb/core 3.0.0-alpha.1 → 3.0.0-alpha.11

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