@kubb/core 2.17.0 → 2.18.0

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 (74) hide show
  1. package/dist/{chunk-C6JPLJPT.cjs → chunk-2H4XNW5D.cjs} +351 -267
  2. package/dist/chunk-2H4XNW5D.cjs.map +1 -0
  3. package/dist/{chunk-PVJACA4A.js → chunk-4X5FFJPJ.js} +35 -2
  4. package/dist/chunk-4X5FFJPJ.js.map +1 -0
  5. package/dist/{chunk-6V72PGTE.cjs → chunk-5T2QA53B.cjs} +139 -3
  6. package/dist/chunk-5T2QA53B.cjs.map +1 -0
  7. package/dist/{chunk-CWXJJLZF.cjs → chunk-7HFYOZ7F.cjs} +12 -4
  8. package/dist/chunk-7HFYOZ7F.cjs.map +1 -0
  9. package/dist/chunk-ECWTIHD5.js +311 -0
  10. package/dist/chunk-ECWTIHD5.js.map +1 -0
  11. package/dist/{chunk-NLZ2T737.js → chunk-MDO6MCFJ.js} +9 -2
  12. package/dist/chunk-MDO6MCFJ.js.map +1 -0
  13. package/dist/{chunk-JFESCSNU.cjs → chunk-OCUNVJPQ.cjs} +6 -8
  14. package/dist/chunk-OCUNVJPQ.cjs.map +1 -0
  15. package/dist/chunk-PXP5K73S.js +1599 -0
  16. package/dist/chunk-PXP5K73S.js.map +1 -0
  17. package/dist/{chunk-PQ7P6QX5.cjs → chunk-SU2W2A6V.cjs} +3 -3
  18. package/dist/chunk-T6TAUAYN.cjs +2586 -0
  19. package/dist/chunk-T6TAUAYN.cjs.map +1 -0
  20. package/dist/{chunk-YQ5ZU5PV.js → chunk-UCKFXEKM.js} +3 -5
  21. package/dist/{chunk-YQ5ZU5PV.js.map → chunk-UCKFXEKM.js.map} +1 -1
  22. package/dist/chunk-XF35HUZ2.cjs +322 -0
  23. package/dist/chunk-XF35HUZ2.cjs.map +1 -0
  24. package/dist/fs.cjs +3 -6
  25. package/dist/fs.cjs.map +1 -1
  26. package/dist/fs.js +5 -7
  27. package/dist/index.cjs +10 -2550
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +1 -1
  30. package/dist/index.d.ts +1 -1
  31. package/dist/index.js +22 -1574
  32. package/dist/index.js.map +1 -1
  33. package/dist/logger.cjs +3 -4
  34. package/dist/mocks.cjs +19 -6
  35. package/dist/mocks.cjs.map +1 -1
  36. package/dist/mocks.d.cts +3 -2
  37. package/dist/mocks.d.ts +3 -2
  38. package/dist/mocks.js +16 -2
  39. package/dist/mocks.js.map +1 -1
  40. package/dist/transformers.cjs +3 -5
  41. package/dist/transformers.js +3 -5
  42. package/dist/utils.cjs +26 -194
  43. package/dist/utils.cjs.map +1 -1
  44. package/dist/utils.d.cts +4 -1
  45. package/dist/utils.d.ts +4 -1
  46. package/dist/utils.js +12 -172
  47. package/dist/utils.js.map +1 -1
  48. package/package.json +3 -3
  49. package/src/BarrelManager.ts +1 -1
  50. package/src/FileManager.ts +9 -9
  51. package/src/build.ts +22 -10
  52. package/src/utils/getParser.ts +17 -0
  53. package/src/utils/index.ts +1 -0
  54. package/dist/chunk-4ARKZPSY.js +0 -36
  55. package/dist/chunk-4ARKZPSY.js.map +0 -1
  56. package/dist/chunk-5PLDNXZK.js +0 -10
  57. package/dist/chunk-5PLDNXZK.js.map +0 -1
  58. package/dist/chunk-6V72PGTE.cjs.map +0 -1
  59. package/dist/chunk-C6JPLJPT.cjs.map +0 -1
  60. package/dist/chunk-CFHVVM3A.cjs +0 -132
  61. package/dist/chunk-CFHVVM3A.cjs.map +0 -1
  62. package/dist/chunk-CWXJJLZF.cjs.map +0 -1
  63. package/dist/chunk-FU3AZXHF.cjs +0 -19
  64. package/dist/chunk-FU3AZXHF.cjs.map +0 -1
  65. package/dist/chunk-GBVPADCA.js +0 -127
  66. package/dist/chunk-GBVPADCA.js.map +0 -1
  67. package/dist/chunk-JFESCSNU.cjs.map +0 -1
  68. package/dist/chunk-LEPKPXA4.cjs +0 -143
  69. package/dist/chunk-LEPKPXA4.cjs.map +0 -1
  70. package/dist/chunk-NLZ2T737.js.map +0 -1
  71. package/dist/chunk-PVJACA4A.js.map +0 -1
  72. package/dist/chunk-T7WVNL7N.cjs +0 -94
  73. package/dist/chunk-T7WVNL7N.cjs.map +0 -1
  74. /package/dist/{chunk-PQ7P6QX5.cjs.map → chunk-SU2W2A6V.cjs.map} +0 -0
package/dist/index.js CHANGED
@@ -1,1578 +1,26 @@
1
1
  import {
2
- searchAndReplace,
3
- transformReservedWord,
4
- transformers_default,
5
- trimExtName
6
- } from "./chunk-YQ5ZU5PV.js";
7
- import {
8
- URLPath,
9
- setUniqueName
10
- } from "./chunk-GBVPADCA.js";
11
- import {
12
- orderBy
13
- } from "./chunk-PVJACA4A.js";
14
- import {
15
- EventEmitter,
16
- LogLevel,
17
- createLogger,
18
- p,
19
- randomCliColour
20
- } from "./chunk-JLT7YQF5.js";
21
- import {
22
- clean
23
- } from "./chunk-5PLDNXZK.js";
24
- import {
25
- write
26
- } from "./chunk-2F7E62RD.js";
27
- import "./chunk-4ARKZPSY.js";
28
- import {
29
- getRelativePath,
30
- read,
31
- readSync
32
- } from "./chunk-NLZ2T737.js";
33
- import {
34
- __privateAdd,
35
- __privateGet,
36
- __privateMethod,
37
- __privateSet
38
- } from "./chunk-Z4BLTVTB.js";
39
-
40
- // src/FileManager.ts
41
- import crypto from "crypto";
42
- import { extname, resolve } from "path";
43
- import { print } from "@kubb/parser";
44
- import * as factory from "@kubb/parser/factory";
45
- import PQueue from "p-queue";
46
- import { isDeepEqual } from "remeda";
47
-
48
- // src/BarrelManager.ts
49
- import { getExports } from "@kubb/parser";
50
- import path from "path";
51
-
52
- // src/utils/TreeNode.ts
53
- import dirTree from "directory-tree";
54
- var TreeNode = class _TreeNode {
55
- constructor(data, parent) {
56
- this.children = [];
57
- this.data = data;
58
- this.parent = parent;
59
- return this;
60
- }
61
- addChild(data) {
62
- const child = new _TreeNode(data, this);
63
- if (!this.children) {
64
- this.children = [];
65
- }
66
- this.children.push(child);
67
- return child;
68
- }
69
- find(data) {
70
- if (!data) {
71
- return null;
72
- }
73
- if (data === this.data) {
74
- return this;
75
- }
76
- if (this.children?.length) {
77
- for (let i = 0, { length } = this.children, target = null; i < length; i++) {
78
- target = this.children[i].find(data);
79
- if (target) {
80
- return target;
81
- }
82
- }
83
- }
84
- return null;
85
- }
86
- get leaves() {
87
- if (!this.children || this.children.length === 0) {
88
- return [this];
89
- }
90
- const leaves = [];
91
- if (this.children) {
92
- for (let i = 0, { length } = this.children; i < length; i++) {
93
- leaves.push.apply(leaves, this.children[i].leaves);
94
- }
95
- }
96
- return leaves;
97
- }
98
- get root() {
99
- if (!this.parent) {
100
- return this;
101
- }
102
- return this.parent.root;
103
- }
104
- forEach(callback) {
105
- if (typeof callback !== "function") {
106
- throw new TypeError("forEach() callback must be a function");
107
- }
108
- callback(this);
109
- if (this.children) {
110
- for (let i = 0, { length } = this.children; i < length; i++) {
111
- this.children[i]?.forEach(callback);
112
- }
113
- }
114
- return this;
115
- }
116
- static build(path3, options = {}) {
117
- try {
118
- const exclude = Array.isArray(options.exclude) ? options.exclude : [options.exclude].filter(Boolean);
119
- const filteredTree = dirTree(path3, {
120
- extensions: options.extensions,
121
- exclude: [/node_modules/, ...exclude]
122
- });
123
- if (!filteredTree) {
124
- return null;
125
- }
126
- const treeNode = new _TreeNode({
127
- name: filteredTree.name,
128
- path: filteredTree.path,
129
- type: FileManager.getMode(filteredTree.path)
130
- });
131
- const recurse = (node, item) => {
132
- const subNode = node.addChild({
133
- name: item.name,
134
- path: item.path,
135
- type: FileManager.getMode(item.path)
136
- });
137
- if (item.children?.length) {
138
- item.children?.forEach((child) => {
139
- recurse(subNode, child);
140
- });
141
- }
142
- };
143
- filteredTree.children?.forEach((child) => recurse(treeNode, child));
144
- return treeNode;
145
- } catch (e) {
146
- throw new Error("Something went wrong with creating index files with the TreehNode class", { cause: e });
147
- }
148
- }
149
- };
150
-
151
- // src/BarrelManager.ts
152
- var _options;
153
- var BarrelManager = class {
154
- constructor(options = {}) {
155
- __privateAdd(this, _options, void 0);
156
- __privateSet(this, _options, options);
157
- return this;
158
- }
159
- getNamedExport(root, item) {
160
- const exportedNames = getExports(path.resolve(root, item.path));
161
- if (!exportedNames) {
162
- return [item];
163
- }
164
- return exportedNames.reduce(
165
- (prev, curr) => {
166
- if (!prev[0]?.name || !prev[1]?.name) {
167
- return prev;
168
- }
169
- if (curr.isTypeOnly) {
170
- prev[1] = { ...prev[1], name: [...prev[1].name, curr.name] };
171
- } else {
172
- prev[0] = { ...prev[0], name: [...prev[0].name, curr.name] };
173
- }
174
- return prev;
175
- },
176
- [
177
- {
178
- ...item,
179
- name: [],
180
- isTypeOnly: false
181
- },
182
- {
183
- ...item,
184
- name: [],
185
- isTypeOnly: true
186
- }
187
- ]
188
- );
189
- }
190
- getNamedExports(root, exports) {
191
- return exports?.flatMap((item) => {
192
- return this.getNamedExport(root, item);
193
- });
194
- }
195
- getIndexes(root) {
196
- const { treeNode = {}, isTypeOnly, extName } = __privateGet(this, _options);
197
- const tree = TreeNode.build(root, treeNode);
198
- if (!tree) {
199
- return null;
200
- }
201
- const fileReducer = (files, treeNode2) => {
202
- if (!treeNode2.children) {
203
- return [];
204
- }
205
- if (treeNode2.children.length > 1) {
206
- const indexPath = path.resolve(treeNode2.data.path, "index.ts");
207
- const exports = treeNode2.children.filter(Boolean).map((file) => {
208
- const importPath = file.data.type === "split" ? `./${file.data.name}/index` : `./${trimExtName(file.data.name)}`;
209
- if (importPath.endsWith("index") && file.data.type === "single") {
210
- return void 0;
211
- }
212
- return {
213
- path: extName ? `${importPath}${extName}` : importPath,
214
- isTypeOnly
215
- };
216
- }).filter(Boolean);
217
- files.push({
218
- path: indexPath,
219
- baseName: "index.ts",
220
- source: "",
221
- exports,
222
- exportable: true
223
- });
224
- } else if (treeNode2.children.length === 1) {
225
- const [treeNodeChild] = treeNode2.children;
226
- const indexPath = path.resolve(treeNode2.data.path, "index.ts");
227
- const importPath = treeNodeChild.data.type === "split" ? `./${treeNodeChild.data.name}/index` : `./${trimExtName(treeNodeChild.data.name)}`;
228
- const exports = [
229
- {
230
- path: extName ? `${importPath}${extName}` : importPath,
231
- isTypeOnly
232
- }
233
- ];
234
- files.push({
235
- path: indexPath,
236
- baseName: "index.ts",
237
- source: "",
238
- exports,
239
- exportable: true
240
- });
241
- }
242
- treeNode2.children.forEach((childItem) => {
243
- fileReducer(files, childItem);
244
- });
245
- return files;
246
- };
247
- return fileReducer([], tree).reverse();
248
- }
249
- };
250
- _options = new WeakMap();
251
-
252
- // src/FileManager.ts
253
- var KubbFile;
254
- ((KubbFile2) => {
255
- })(KubbFile || (KubbFile = {}));
256
- var _cache, _task, _queue, _add, add_fn, _addOrAppend, addOrAppend_fn;
257
- var _FileManager = class _FileManager {
258
- constructor({ task = async (file) => file, queue = new PQueue() } = {}) {
259
- __privateAdd(this, _add);
260
- __privateAdd(this, _addOrAppend);
261
- __privateAdd(this, _cache, /* @__PURE__ */ new Map());
262
- __privateAdd(this, _task, void 0);
263
- __privateAdd(this, _queue, void 0);
264
- __privateSet(this, _task, task);
265
- __privateSet(this, _queue, queue);
266
- return this;
267
- }
268
- get files() {
269
- const files = [];
270
- __privateGet(this, _cache).forEach((item) => {
271
- files.push(...item.flat(1));
272
- });
273
- return files;
274
- }
275
- get isExecuting() {
276
- return __privateGet(this, _queue).size !== 0 && __privateGet(this, _queue).pending !== 0;
277
- }
278
- async add(...files) {
279
- const promises = combineFiles(files).map((file) => {
280
- if (file.override) {
281
- return __privateMethod(this, _add, add_fn).call(this, file);
282
- }
283
- return __privateMethod(this, _addOrAppend, addOrAppend_fn).call(this, file);
284
- });
285
- const resolvedFiles = await Promise.all(promises);
286
- if (files.length > 1) {
287
- return resolvedFiles;
288
- }
289
- return resolvedFiles[0];
290
- }
291
- async addIndexes({ root, output, meta, logger, options = {} }) {
292
- const { exportType = "barrel" } = output;
293
- if (exportType === false) {
294
- return void 0;
295
- }
296
- const pathToBuildFrom = resolve(root, output.path);
297
- if (transformers_default.trimExtName(pathToBuildFrom).endsWith("index")) {
298
- logger.emit("warning", "Output has the same fileName as the barrelFiles, please disable barrel generation");
299
- return;
300
- }
301
- const exportPath = output.path.startsWith("./") ? trimExtName(output.path) : `./${trimExtName(output.path)}`;
302
- const mode = _FileManager.getMode(output.path);
303
- const barrelManager = new BarrelManager({
304
- extName: output.extName,
305
- ...options
306
- });
307
- let files = barrelManager.getIndexes(pathToBuildFrom);
308
- if (!files) {
309
- return void 0;
310
- }
311
- if (exportType === "barrelNamed") {
312
- files = files.map((file) => {
313
- if (file.exports) {
314
- return {
315
- ...file,
316
- exports: barrelManager.getNamedExports(pathToBuildFrom, file.exports)
317
- };
318
- }
319
- return file;
320
- });
321
- }
322
- await Promise.all(
323
- files.map((file) => {
324
- return __privateMethod(this, _addOrAppend, addOrAppend_fn).call(this, {
325
- ...file,
326
- meta: meta ? meta : file.meta
327
- });
328
- })
329
- );
330
- const rootPath = mode === "split" ? `${exportPath}/index${output.extName || ""}` : `${exportPath}${output.extName || ""}`;
331
- const rootFile = {
332
- path: resolve(root, "index.ts"),
333
- baseName: "index.ts",
334
- source: "",
335
- exports: [
336
- output.exportAs ? {
337
- name: output.exportAs,
338
- asAlias: true,
339
- path: rootPath,
340
- isTypeOnly: options.isTypeOnly
341
- } : {
342
- path: rootPath,
343
- isTypeOnly: options.isTypeOnly
344
- }
345
- ],
346
- exportable: true
347
- };
348
- if (exportType === "barrelNamed" && !output.exportAs && rootFile.exports?.[0]) {
349
- rootFile.exports = barrelManager.getNamedExport(root, rootFile.exports[0]);
350
- }
351
- await __privateMethod(this, _addOrAppend, addOrAppend_fn).call(this, {
352
- ...rootFile,
353
- meta: meta ? meta : rootFile.meta
354
- });
355
- }
356
- getCacheByUUID(UUID) {
357
- let cache;
358
- __privateGet(this, _cache).forEach((files) => {
359
- cache = files.find((item) => item.id === UUID);
360
- });
361
- return cache;
362
- }
363
- get(path3) {
364
- return __privateGet(this, _cache).get(path3);
365
- }
366
- remove(path3) {
367
- const cacheItem = this.get(path3);
368
- if (!cacheItem) {
369
- return;
370
- }
371
- __privateGet(this, _cache).delete(path3);
372
- }
373
- async write(...params) {
374
- return write(...params);
375
- }
376
- async read(...params) {
377
- return read(...params);
378
- }
379
- // statics
380
- static getSource(file) {
381
- return getSource(file);
382
- }
383
- static combineFiles(files) {
384
- return combineFiles(files);
385
- }
386
- static getMode(path3) {
387
- if (!path3) {
388
- return "split";
389
- }
390
- return extname(path3) ? "single" : "split";
391
- }
392
- static get extensions() {
393
- return [".js", ".ts", ".tsx"];
394
- }
395
- static isJavascript(baseName) {
396
- return _FileManager.extensions.some((extension) => baseName.endsWith(extension));
397
- }
398
- };
399
- _cache = new WeakMap();
400
- _task = new WeakMap();
401
- _queue = new WeakMap();
402
- _add = new WeakSet();
403
- add_fn = async function(file) {
404
- const controller = new AbortController();
405
- const resolvedFile = {
406
- id: crypto.randomUUID(),
407
- name: trimExtName(file.baseName),
408
- ...file
409
- };
410
- if (resolvedFile.exports?.length) {
411
- const folder = resolvedFile.path.replace(resolvedFile.baseName, "");
412
- resolvedFile.exports = resolvedFile.exports.filter((exportItem) => {
413
- const exportedFile = this.files.find((file2) => file2.path.includes(resolve(folder, exportItem.path)));
414
- if (exportedFile) {
415
- return exportedFile.exportable;
416
- }
417
- return true;
418
- });
419
- }
420
- __privateGet(this, _cache).set(resolvedFile.path, [{ cancel: () => controller.abort(), ...resolvedFile }]);
421
- return __privateGet(this, _queue).add(
422
- async () => {
423
- var _a;
424
- return (_a = __privateGet(this, _task)) == null ? void 0 : _a.call(this, resolvedFile);
425
- },
426
- { signal: controller.signal }
427
- );
428
- };
429
- _addOrAppend = new WeakSet();
430
- addOrAppend_fn = async function(file) {
431
- const previousCaches = __privateGet(this, _cache).get(file.path);
432
- const previousCache = previousCaches ? previousCaches.at(previousCaches.length - 1) : void 0;
433
- if (previousCache) {
434
- __privateGet(this, _cache).delete(previousCache.path);
435
- return __privateMethod(this, _add, add_fn).call(this, {
436
- ...file,
437
- source: previousCache.source && file.source ? `${previousCache.source}
438
- ${file.source}` : "",
439
- imports: [...previousCache.imports || [], ...file.imports || []],
440
- exports: [...previousCache.exports || [], ...file.exports || []],
441
- env: { ...previousCache.env || {}, ...file.env || {} }
442
- });
443
- }
444
- return __privateMethod(this, _add, add_fn).call(this, file);
445
- };
446
- var FileManager = _FileManager;
447
- function combineFiles(files) {
448
- return files.filter(Boolean).reduce(
449
- (acc, file) => {
450
- const prevIndex = acc.findIndex((item) => item.path === file.path);
451
- if (prevIndex === -1) {
452
- return [...acc, file];
453
- }
454
- const prev = acc[prevIndex];
455
- if (prev && file.override) {
456
- acc[prevIndex] = {
457
- imports: [],
458
- exports: [],
459
- ...file
460
- };
461
- return acc;
462
- }
463
- if (prev) {
464
- acc[prevIndex] = {
465
- ...file,
466
- source: prev.source && file.source ? `${prev.source}
467
- ${file.source}` : "",
468
- imports: [...prev.imports || [], ...file.imports || []],
469
- exports: [...prev.exports || [], ...file.exports || []],
470
- env: { ...prev.env || {}, ...file.env || {} }
471
- };
472
- }
473
- return acc;
474
- },
475
- []
476
- );
477
- }
478
- function getSource(file) {
479
- if (file.language ? !["typescript", "javascript"].includes(file.language) : !FileManager.isJavascript(file.baseName)) {
480
- return file.source;
481
- }
482
- const exports = file.exports ? combineExports(file.exports) : [];
483
- const imports = file.imports && file.source ? combineImports(file.imports, exports, file.source) : [];
484
- const importNodes = imports.filter((item) => {
485
- const path3 = item.root ? getRelativePath(item.root, item.path) : item.path;
486
- return path3 !== trimExtName(file.path);
487
- }).map((item) => {
488
- return factory.createImportDeclaration({
489
- name: item.name,
490
- path: item.root ? getRelativePath(item.root, item.path) : item.path,
491
- isTypeOnly: item.isTypeOnly
492
- });
493
- });
494
- const exportNodes = exports.map(
495
- (item) => factory.createExportDeclaration({
496
- name: item.name,
497
- path: item.path,
498
- isTypeOnly: item.isTypeOnly,
499
- asAlias: item.asAlias
500
- })
501
- );
502
- const source = [print([...importNodes, ...exportNodes]), getEnvSource(file.source, file.env)].join("\n");
503
- return print([], { source, noEmitHelpers: false });
504
- }
505
- function combineExports(exports) {
506
- const combinedExports = orderBy(exports, [(v) => !v.isTypeOnly], ["asc"]).reduce(
507
- (prev, curr) => {
508
- const name = curr.name;
509
- const prevByPath = prev.findLast((imp) => imp.path === curr.path);
510
- const prevByPathAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly);
511
- if (prevByPathAndIsTypeOnly) {
512
- return prev;
513
- }
514
- const uniquePrev = prev.findLast(
515
- (imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly && imp.asAlias === curr.asAlias
516
- );
517
- if (uniquePrev || Array.isArray(name) && !name.length || prevByPath?.asAlias && !curr.asAlias) {
518
- return prev;
519
- }
520
- if (!prevByPath) {
521
- return [
522
- ...prev,
523
- {
524
- ...curr,
525
- name: Array.isArray(name) ? [...new Set(name)] : name
526
- }
527
- ];
528
- }
529
- if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(curr.name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
530
- prevByPath.name = [.../* @__PURE__ */ new Set([...prevByPath.name, ...curr.name])];
531
- return prev;
532
- }
533
- return [...prev, curr];
534
- },
535
- []
536
- );
537
- return orderBy(combinedExports, [(v) => !v.isTypeOnly, (v) => v.asAlias], ["desc", "desc"]);
538
- }
539
- function combineImports(imports, exports, source) {
540
- const combinedImports = orderBy(imports, [(v) => !v.isTypeOnly], ["asc"]).reduce(
541
- (prev, curr) => {
542
- let name = Array.isArray(curr.name) ? [...new Set(curr.name)] : curr.name;
543
- const hasImportInSource = (importName) => {
544
- if (!source) {
545
- return true;
546
- }
547
- const checker = (name2) => name2 && !!source.includes(name2);
548
- return checker(importName) || exports.some(({ name: name2 }) => Array.isArray(name2) ? name2.some(checker) : checker(name2));
549
- };
550
- if (curr.path === curr.root) {
551
- return prev;
552
- }
553
- if (Array.isArray(name)) {
554
- name = name.filter((item) => typeof item === "string" ? hasImportInSource(item) : hasImportInSource(item.propertyName));
555
- }
556
- const prevByPath = prev.findLast((imp) => imp.path === curr.path && imp.isTypeOnly === curr.isTypeOnly);
557
- const uniquePrev = prev.findLast((imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly);
558
- const prevByPathNameAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly);
559
- if (prevByPathNameAndIsTypeOnly) {
560
- return prev;
561
- }
562
- if (uniquePrev || Array.isArray(name) && !name.length) {
563
- return prev;
564
- }
565
- if (!prevByPath) {
566
- return [
567
- ...prev,
568
- {
569
- ...curr,
570
- name
571
- }
572
- ];
573
- }
574
- if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
575
- prevByPath.name = [.../* @__PURE__ */ new Set([...prevByPath.name, ...name])];
576
- return prev;
577
- }
578
- if (!Array.isArray(name) && name && !hasImportInSource(name)) {
579
- return prev;
580
- }
581
- return [...prev, curr];
582
- },
583
- []
584
- );
585
- return orderBy(combinedImports, [(v) => !v.isTypeOnly], ["desc"]);
586
- }
587
- function getEnvSource(source, env) {
588
- if (!env) {
589
- return source;
590
- }
591
- const keys = Object.keys(env);
592
- if (!keys.length) {
593
- return source;
594
- }
595
- return keys.reduce((prev, key) => {
596
- const environmentValue = env[key];
597
- const replaceBy = environmentValue ? `'${environmentValue.replaceAll('"', "")?.replaceAll("'", "")}'` : "undefined";
598
- if (key.toUpperCase() !== key) {
599
- throw new TypeError(`Environment should be in upperCase for ${key}`);
600
- }
601
- if (typeof replaceBy === "string") {
602
- prev = searchAndReplace({
603
- text: prev.replaceAll(`process.env.${key}`, replaceBy),
604
- replaceBy,
605
- prefix: "process.env",
606
- key
607
- });
608
- prev = searchAndReplace({
609
- text: prev.replaceAll(/(declare const).*\n/gi, ""),
610
- replaceBy,
611
- key
612
- });
613
- }
614
- return prev;
615
- }, source);
616
- }
617
-
618
- // src/PluginManager.ts
619
- import PQueue2 from "p-queue";
620
-
621
- // src/utils/executeStrategies.ts
622
- function hookSeq(promises) {
623
- return promises.filter(Boolean).reduce(
624
- (promise, func) => {
625
- if (typeof func !== "function") {
626
- throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
627
- }
628
- return promise.then((state) => {
629
- const calledFunc = func(state);
630
- if (calledFunc) {
631
- return calledFunc.then(Array.prototype.concat.bind(state));
632
- }
633
- });
634
- },
635
- Promise.resolve([])
636
- );
637
- }
638
- function hookFirst(promises, nullCheck = (state) => state !== null) {
639
- let promise = Promise.resolve(null);
640
- for (const func of promises.filter(Boolean)) {
641
- promise = promise.then((state) => {
642
- if (nullCheck(state)) {
643
- return state;
644
- }
645
- const calledFunc = func(state);
646
- return calledFunc;
647
- });
648
- }
649
- return promise;
650
- }
651
- function hookParallel(promises) {
652
- return Promise.allSettled(promises.filter(Boolean).map((promise) => promise()));
653
- }
654
-
655
- // src/PromiseManager.ts
656
- var _options2;
657
- var PromiseManager = class {
658
- constructor(options = {}) {
659
- __privateAdd(this, _options2, {});
660
- __privateSet(this, _options2, options);
661
- return this;
662
- }
663
- run(strategy, promises) {
664
- if (strategy === "seq") {
665
- return hookSeq(promises);
666
- }
667
- if (strategy === "first") {
668
- return hookFirst(promises, __privateGet(this, _options2).nullCheck);
669
- }
670
- if (strategy === "parallel") {
671
- return hookParallel(promises);
672
- }
673
- throw new Error(`${strategy} not implemented`);
674
- }
675
- };
676
- _options2 = new WeakMap();
677
- function isPromise(result) {
678
- return !!result && typeof result?.then === "function";
679
- }
680
- function isPromiseRejectedResult(result) {
681
- return result.status === "rejected";
682
- }
683
-
684
- // src/errors.ts
685
- var Warning = class extends Error {
686
- constructor(message, options) {
687
- super(message, { cause: options?.cause });
688
- this.name = "Warning";
689
- }
690
- };
691
- var ValidationPluginError = class extends Error {
692
- };
693
-
694
- // src/plugin.ts
695
- import path2 from "path";
696
-
697
- // src/utils/cache.ts
698
- function createPluginCache(Store = /* @__PURE__ */ Object.create(null)) {
699
- return {
700
- set(id, value) {
701
- Store[id] = [0, value];
702
- },
703
- get(id) {
704
- const item = Store[id];
705
- if (!item) {
706
- return null;
707
- }
708
- item[0] = 0;
709
- return item[1];
710
- },
711
- has(id) {
712
- const item = Store[id];
713
- if (!item) {
714
- return false;
715
- }
716
- item[0] = 0;
717
- return true;
718
- },
719
- delete(id) {
720
- return delete Store[id];
721
- }
722
- };
723
- }
724
-
725
- // src/plugin.ts
726
- function createPlugin(factory2) {
727
- return (options) => {
728
- return factory2(options);
729
- };
730
- }
731
- var pluginName = "core";
732
- var definePlugin = createPlugin((options) => {
733
- const { fileManager, pluginManager, resolvePath, resolveName, logger } = options;
734
- return {
735
- name: pluginName,
736
- options,
737
- key: ["core"],
738
- api() {
739
- return {
740
- get config() {
741
- return options.config;
742
- },
743
- get plugins() {
744
- return options.getPlugins();
745
- },
746
- get plugin() {
747
- return options.plugin;
748
- },
749
- logger,
750
- fileManager,
751
- pluginManager,
752
- async addFile(...files) {
753
- const resolvedFiles = await fileManager.add(...files);
754
- if (!Array.isArray(resolvedFiles)) {
755
- return [resolvedFiles];
756
- }
757
- return resolvedFiles;
758
- },
759
- resolvePath,
760
- resolveName,
761
- cache: createPluginCache()
762
- };
763
- },
764
- resolvePath(baseName) {
765
- const root = path2.resolve(this.config.root, this.config.output.path);
766
- return path2.resolve(root, baseName);
767
- },
768
- resolveName(name) {
769
- return name;
770
- }
771
- };
772
- });
773
-
774
- // src/PluginManager.ts
775
- var _core, _usedPluginNames, _promiseManager, _getSortedPlugins, getSortedPlugins_fn, _addExecutedToCallStack, addExecutedToCallStack_fn, _execute, execute_fn, _executeSync, executeSync_fn, _catcher, catcher_fn, _parse, parse_fn;
776
- var PluginManager = class {
777
- constructor(config, options) {
778
- __privateAdd(this, _getSortedPlugins);
779
- __privateAdd(this, _addExecutedToCallStack);
780
- /**
781
- * Run an async plugin hook and return the result.
782
- * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.
783
- * @param args Arguments passed to the plugin hook.
784
- * @param plugin The actual pluginObject to run.
785
- */
786
- // Implementation signature
787
- __privateAdd(this, _execute);
788
- /**
789
- * Run a sync plugin hook and return the result.
790
- * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
791
- * @param args Arguments passed to the plugin hook.
792
- * @param plugin The acutal plugin
793
- * @param replaceContext When passed, the plugin context can be overridden.
794
- */
795
- __privateAdd(this, _executeSync);
796
- __privateAdd(this, _catcher);
797
- __privateAdd(this, _parse);
798
- this.events = new EventEmitter();
799
- this.executed = [];
800
- __privateAdd(this, _core, void 0);
801
- __privateAdd(this, _usedPluginNames, {});
802
- __privateAdd(this, _promiseManager, void 0);
803
- this.resolvePath = (params) => {
804
- if (params.pluginKey) {
805
- const paths = this.hookForPluginSync({
806
- pluginKey: params.pluginKey,
807
- hookName: "resolvePath",
808
- parameters: [params.baseName, params.mode, params.options]
809
- });
810
- if (paths && paths?.length > 1) {
811
- this.logger.emit("debug", [
812
- `Cannot return a path where the 'pluginKey' ${params.pluginKey ? JSON.stringify(params.pluginKey) : '"'} is not unique enough
813
-
814
- Paths: ${JSON.stringify(paths, void 0, 2)}
815
-
816
- Falling back on the first item.
817
- `
818
- ]);
819
- }
820
- return paths?.at(0);
821
- }
822
- return this.hookFirstSync({
823
- hookName: "resolvePath",
824
- parameters: [params.baseName, params.mode, params.options]
825
- }).result;
826
- };
827
- this.resolveName = (params) => {
828
- if (params.pluginKey) {
829
- const names = this.hookForPluginSync({
830
- pluginKey: params.pluginKey,
831
- hookName: "resolveName",
832
- parameters: [params.name, params.type]
833
- });
834
- if (names && names?.length > 1) {
835
- this.logger.emit("debug", [
836
- `Cannot return a name where the 'pluginKey' ${params.pluginKey ? JSON.stringify(params.pluginKey) : '"'} is not unique enough
837
-
838
- Names: ${JSON.stringify(names, void 0, 2)}
839
-
840
- Falling back on the first item.
841
- `
842
- ]);
843
- }
844
- return transformReservedWord(names?.at(0) || params.name);
845
- }
846
- const name = this.hookFirstSync({
847
- hookName: "resolveName",
848
- parameters: [params.name, params.type]
849
- }).result;
850
- return transformReservedWord(name);
851
- };
852
- this.config = config;
853
- this.logger = options.logger;
854
- this.queue = new PQueue2({ concurrency: 1 });
855
- this.fileManager = new FileManager({
856
- task: options.task,
857
- queue: this.queue
858
- });
859
- __privateSet(this, _promiseManager, new PromiseManager({
860
- nullCheck: (state) => !!state?.result
861
- }));
862
- const plugins = config.plugins || [];
863
- const core = definePlugin({
864
- config,
865
- logger: this.logger,
866
- pluginManager: this,
867
- fileManager: this.fileManager,
868
- resolvePath: this.resolvePath.bind(this),
869
- resolveName: this.resolveName.bind(this),
870
- getPlugins: __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).bind(this)
871
- });
872
- __privateSet(this, _core, __privateMethod(this, _parse, parse_fn).call(this, core, this, core.api.call(null)));
873
- this.plugins = [__privateGet(this, _core), ...plugins].map((plugin) => {
874
- return __privateMethod(this, _parse, parse_fn).call(this, plugin, this, __privateGet(this, _core).api);
875
- });
876
- return this;
877
- }
878
- getFile({ name, mode, extName, pluginKey, options }) {
879
- let source = "";
880
- const baseName = `${name}${extName}`;
881
- const path3 = this.resolvePath({ baseName, mode, pluginKey, options });
882
- if (!path3) {
883
- throw new Error(`Filepath should be defined for resolvedName "${name}" and pluginKey [${JSON.stringify(pluginKey)}]`);
884
- }
885
- try {
886
- source = readSync(path3);
887
- } catch (_e) {
888
- }
889
- return {
890
- path: path3,
891
- baseName,
892
- meta: {
893
- pluginKey
894
- },
895
- source
896
- };
897
- }
898
- /**
899
- * Instead of calling `pluginManager.events.on` you can use `pluginManager.on`. This one also has better types.
900
- */
901
- on(eventName, handler) {
902
- this.events.on(eventName, handler);
903
- }
904
- /**
905
- * Run a specific hookName for plugin x.
906
- */
907
- hookForPlugin({
908
- pluginKey,
909
- hookName,
910
- parameters
911
- }) {
912
- const plugins = this.getPluginsByKey(hookName, pluginKey);
913
- const promises = plugins.map((plugin) => {
914
- return __privateMethod(this, _execute, execute_fn).call(this, {
915
- strategy: "hookFirst",
916
- hookName,
917
- parameters,
918
- plugin
919
- });
920
- }).filter(Boolean);
921
- return Promise.all(promises);
922
- }
923
- /**
924
- * Run a specific hookName for plugin x.
925
- */
926
- hookForPluginSync({
927
- pluginKey,
928
- hookName,
929
- parameters
930
- }) {
931
- const plugins = this.getPluginsByKey(hookName, pluginKey);
932
- return plugins.map((plugin) => {
933
- return __privateMethod(this, _executeSync, executeSync_fn).call(this, {
934
- strategy: "hookFirst",
935
- hookName,
936
- parameters,
937
- plugin
938
- });
939
- }).filter(Boolean);
940
- }
941
- /**
942
- * First non-null result stops and will return it's value.
943
- */
944
- async hookFirst({
945
- hookName,
946
- parameters,
947
- skipped
948
- }) {
949
- const promises = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this).filter((plugin) => {
950
- return skipped ? skipped.has(plugin) : true;
951
- }).map((plugin) => {
952
- return async () => {
953
- const value = await __privateMethod(this, _execute, execute_fn).call(this, {
954
- strategy: "hookFirst",
955
- hookName,
956
- parameters,
957
- plugin
958
- });
959
- return Promise.resolve({
960
- plugin,
961
- result: value
962
- });
963
- };
964
- });
965
- return __privateGet(this, _promiseManager).run("first", promises);
966
- }
967
- /**
968
- * First non-null result stops and will return it's value.
969
- */
970
- hookFirstSync({
971
- hookName,
972
- parameters,
973
- skipped
974
- }) {
975
- let parseResult = null;
976
- for (const plugin of __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this)) {
977
- if (skipped?.has(plugin)) {
978
- continue;
979
- }
980
- parseResult = {
981
- result: __privateMethod(this, _executeSync, executeSync_fn).call(this, {
982
- strategy: "hookFirst",
983
- hookName,
984
- parameters,
985
- plugin
986
- }),
987
- plugin
988
- };
989
- if (parseResult?.result != null) {
990
- break;
991
- }
992
- }
993
- return parseResult;
994
- }
995
- /**
996
- * Run all plugins in parallel(order will be based on `this.plugin` and if `pre` or `post` is set).
997
- */
998
- async hookParallel({
999
- hookName,
1000
- parameters
1001
- }) {
1002
- const promises = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this).map((plugin) => {
1003
- return () => __privateMethod(this, _execute, execute_fn).call(this, {
1004
- strategy: "hookParallel",
1005
- hookName,
1006
- parameters,
1007
- plugin
1008
- });
1009
- });
1010
- const results = await __privateGet(this, _promiseManager).run("parallel", promises);
1011
- results.forEach((result, index) => {
1012
- if (isPromiseRejectedResult(result)) {
1013
- const plugin = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this)[index];
1014
- __privateMethod(this, _catcher, catcher_fn).call(this, result.reason, plugin, hookName);
1015
- }
1016
- });
1017
- return results.filter((result) => result.status === "fulfilled").map((result) => result.value);
1018
- }
1019
- /**
1020
- * Chain all plugins, `reduce` can be passed through to handle every returned value. The return value of the first plugin will be used as the first parameter for the plugin after that.
1021
- */
1022
- hookReduceArg0({
1023
- hookName,
1024
- parameters,
1025
- reduce
1026
- }) {
1027
- const [argument0, ...rest] = parameters;
1028
- let promise = Promise.resolve(argument0);
1029
- for (const plugin of __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this)) {
1030
- promise = promise.then((arg0) => {
1031
- const value = __privateMethod(this, _execute, execute_fn).call(this, {
1032
- strategy: "hookReduceArg0",
1033
- hookName,
1034
- parameters: [arg0, ...rest],
1035
- plugin
1036
- });
1037
- return value;
1038
- }).then((result) => reduce.call(__privateGet(this, _core).api, argument0, result, plugin));
1039
- }
1040
- return promise;
1041
- }
1042
- /**
1043
- * Chains plugins
1044
- */
1045
- async hookSeq({ hookName, parameters }) {
1046
- const promises = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this).map((plugin) => {
1047
- return () => __privateMethod(this, _execute, execute_fn).call(this, {
1048
- strategy: "hookSeq",
1049
- hookName,
1050
- parameters,
1051
- plugin
1052
- });
1053
- });
1054
- return __privateGet(this, _promiseManager).run("seq", promises);
1055
- }
1056
- getPluginsByKey(hookName, pluginKey) {
1057
- const plugins = [...this.plugins];
1058
- const [searchPluginName, searchIdentifier] = pluginKey;
1059
- const pluginByPluginName = plugins.filter((plugin) => plugin[hookName]).filter((item) => {
1060
- const [name, identifier] = item.key;
1061
- const identifierCheck = identifier?.toString() === searchIdentifier?.toString();
1062
- const nameCheck = name === searchPluginName;
1063
- if (searchIdentifier) {
1064
- return identifierCheck && nameCheck;
1065
- }
1066
- return nameCheck;
1067
- });
1068
- if (!pluginByPluginName?.length) {
1069
- const corePlugin = plugins.find((plugin) => plugin.name === "core" && plugin[hookName]);
1070
- if (corePlugin) {
1071
- this.logger.emit("debug", [`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, falling back on the '@kubb/core' plugin`]);
1072
- } else {
1073
- this.logger.emit("debug", [`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, no fallback found in the '@kubb/core' plugin`]);
1074
- }
1075
- return corePlugin ? [corePlugin] : [];
1076
- }
1077
- return pluginByPluginName;
1078
- }
1079
- static getDependedPlugins(plugins, dependedPluginNames) {
1080
- let pluginNames = [];
1081
- if (typeof dependedPluginNames === "string") {
1082
- pluginNames = [dependedPluginNames];
1083
- } else {
1084
- pluginNames = dependedPluginNames;
1085
- }
1086
- return pluginNames.map((pluginName2) => {
1087
- const plugin = plugins.find((plugin2) => plugin2.name === pluginName2);
1088
- if (!plugin) {
1089
- throw new ValidationPluginError(`This plugin depends on the ${pluginName2} plugin.`);
1090
- }
1091
- return plugin;
1092
- });
1093
- }
1094
- static get hooks() {
1095
- return ["buildStart", "resolvePath", "resolveName", "load", "transform", "writeFile", "buildEnd"];
1096
- }
1097
- };
1098
- _core = new WeakMap();
1099
- _usedPluginNames = new WeakMap();
1100
- _promiseManager = new WeakMap();
1101
- _getSortedPlugins = new WeakSet();
1102
- getSortedPlugins_fn = function(hookName) {
1103
- const plugins = [...this.plugins].filter((plugin) => plugin.name !== "core");
1104
- if (hookName) {
1105
- if (this.logger.logLevel === LogLevel.info) {
1106
- const containsHookName = plugins.some((item) => item[hookName]);
1107
- if (!containsHookName) {
1108
- this.logger.emit("warning", `No hook ${hookName} found`);
1109
- }
1110
- }
1111
- return plugins.filter((item) => item[hookName]);
1112
- }
1113
- return plugins.map((plugin) => {
1114
- if (plugin.pre) {
1115
- const isValid = plugin.pre.every((pluginName2) => plugins.find((pluginToFind) => pluginToFind.name === pluginName2));
1116
- if (!isValid) {
1117
- throw new ValidationPluginError(`This plugin has a pre set that is not valid(${JSON.stringify(plugin.pre, void 0, 2)})`);
1118
- }
1119
- }
1120
- return plugin;
1121
- }).sort((a, b) => {
1122
- if (b.pre?.includes(a.name)) {
1123
- return 1;
1124
- }
1125
- if (b.post?.includes(a.name)) {
1126
- return -1;
1127
- }
1128
- return 0;
1129
- });
1130
- };
1131
- _addExecutedToCallStack = new WeakSet();
1132
- addExecutedToCallStack_fn = function(executer) {
1133
- if (executer) {
1134
- this.events.emit("executed", executer);
1135
- this.executed.push(executer);
1136
- }
1137
- };
1138
- _execute = new WeakSet();
1139
- execute_fn = function({
1140
- strategy,
1141
- hookName,
1142
- parameters,
1143
- plugin
1144
- }) {
1145
- const hook = plugin[hookName];
1146
- let output;
1147
- if (!hook) {
1148
- return null;
1149
- }
1150
- this.events.emit("execute", { strategy, hookName, parameters, plugin });
1151
- const task = Promise.resolve().then(() => {
1152
- if (typeof hook === "function") {
1153
- const possiblePromiseResult = hook.apply({ ...__privateGet(this, _core).api, plugin }, parameters);
1154
- if (isPromise(possiblePromiseResult)) {
1155
- return Promise.resolve(possiblePromiseResult);
1156
- }
1157
- return possiblePromiseResult;
1158
- }
1159
- return hook;
1160
- }).then((result) => {
1161
- output = result;
1162
- __privateMethod(this, _addExecutedToCallStack, addExecutedToCallStack_fn).call(this, {
1163
- parameters,
1164
- output,
1165
- strategy,
1166
- hookName,
1167
- plugin
1168
- });
1169
- return result;
1170
- }).catch((e) => {
1171
- __privateMethod(this, _catcher, catcher_fn).call(this, e, plugin, hookName);
1172
- return null;
1173
- });
1174
- return task;
1175
- };
1176
- _executeSync = new WeakSet();
1177
- executeSync_fn = function({
1178
- strategy,
1179
- hookName,
1180
- parameters,
1181
- plugin
1182
- }) {
1183
- const hook = plugin[hookName];
1184
- let output;
1185
- if (!hook) {
1186
- return null;
1187
- }
1188
- this.events.emit("execute", { strategy, hookName, parameters, plugin });
1189
- try {
1190
- if (typeof hook === "function") {
1191
- const fn = hook.apply({ ...__privateGet(this, _core).api, plugin }, parameters);
1192
- output = fn;
1193
- return fn;
1194
- }
1195
- output = hook;
1196
- __privateMethod(this, _addExecutedToCallStack, addExecutedToCallStack_fn).call(this, {
1197
- parameters,
1198
- output,
1199
- strategy,
1200
- hookName,
1201
- plugin
1202
- });
1203
- return hook;
1204
- } catch (e) {
1205
- __privateMethod(this, _catcher, catcher_fn).call(this, e, plugin, hookName);
1206
- return null;
1207
- }
1208
- };
1209
- _catcher = new WeakSet();
1210
- catcher_fn = function(cause, plugin, hookName) {
1211
- const text = `${cause.message} (plugin: ${plugin?.name || "unknown"}, hook: ${hookName || "unknown"})`;
1212
- this.logger.emit("error", text, cause);
1213
- this.events.emit("error", cause);
1214
- };
1215
- _parse = new WeakSet();
1216
- parse_fn = function(plugin, pluginManager, context) {
1217
- const usedPluginNames = __privateGet(pluginManager, _usedPluginNames);
1218
- setUniqueName(plugin.name, usedPluginNames);
1219
- const key = [plugin.name, usedPluginNames[plugin.name]].filter(Boolean);
1220
- if (!plugin.transform) {
1221
- plugin.transform = function transform(code) {
1222
- return code;
1223
- };
1224
- }
1225
- if (plugin.api && typeof plugin.api === "function") {
1226
- const api = plugin.api.call(context);
1227
- return {
1228
- ...plugin,
1229
- key,
1230
- api
1231
- };
1232
- }
1233
- return {
1234
- ...plugin,
1235
- key
1236
- };
1237
- };
1238
-
1239
- // src/config.ts
1240
- function defineConfig(options) {
1241
- return options;
1242
- }
1243
- function isInputPath(result) {
1244
- return !!result && "path" in result;
1245
- }
1246
-
1247
- // src/build.ts
1248
- async function transformReducer(_previousCode, result, _plugin) {
1249
- return result;
1250
- }
1251
- async function setup(options) {
1252
- const { config, logger = createLogger({ logLevel: LogLevel.silent }) } = options;
1253
- let count = 0;
1254
- try {
1255
- if (isInputPath(config) && !new URLPath(config.input.path).isURL) {
1256
- await read(config.input.path);
1257
- }
1258
- } catch (e) {
1259
- if (isInputPath(config)) {
1260
- throw new Error(
1261
- `Cannot read file/URL defined in \`input.path\` or set with \`kubb generate PATH\` in the CLI of your Kubb config ${p.dim(config.input.path)}`,
1262
- {
1263
- cause: e
1264
- }
1265
- );
1266
- }
1267
- }
1268
- if (config.output.clean) {
1269
- await clean(config.output.path);
1270
- }
1271
- const task = async (file) => {
1272
- const { path: path3 } = file;
1273
- let source = FileManager.getSource(file);
1274
- const { result: loadedResult } = await pluginManager.hookFirst({
1275
- hookName: "load",
1276
- parameters: [path3]
1277
- });
1278
- if (loadedResult && isPromise(loadedResult)) {
1279
- source = await loadedResult;
1280
- }
1281
- if (loadedResult && !isPromise(loadedResult)) {
1282
- source = loadedResult;
1283
- }
1284
- if (source) {
1285
- source = await pluginManager.hookReduceArg0({
1286
- hookName: "transform",
1287
- parameters: [source, path3],
1288
- reduce: transformReducer
1289
- });
1290
- if (config.output.write || config.output.write === void 0) {
1291
- if (file.meta?.pluginKey) {
1292
- await pluginManager.hookForPlugin({
1293
- pluginKey: file.meta?.pluginKey,
1294
- hookName: "writeFile",
1295
- parameters: [source, path3]
1296
- });
1297
- }
1298
- await pluginManager.hookFirst({
1299
- hookName: "writeFile",
1300
- parameters: [source, path3]
1301
- });
1302
- }
1303
- }
1304
- return {
1305
- ...file,
1306
- source: source || ""
1307
- };
1308
- };
1309
- const pluginManager = new PluginManager(config, { logger, task });
1310
- pluginManager.on("execute", (executer) => {
1311
- const { hookName, parameters, plugin } = executer;
1312
- if (hookName === "writeFile") {
1313
- const [code] = parameters;
1314
- logger.emit("debug", [`PluginKey ${p.dim(JSON.stringify(plugin.key))}
1315
- with source
1316
-
1317
- ${code}`]);
1318
- }
1319
- });
1320
- pluginManager.queue.on("add", () => {
1321
- if (logger.logLevel !== LogLevel.info) {
1322
- return;
1323
- }
1324
- if (count === 0) {
1325
- logger.emit("start", "\u{1F4BE} Writing");
1326
- }
1327
- });
1328
- pluginManager.queue.on("active", () => {
1329
- if (logger.logLevel !== LogLevel.info) {
1330
- return;
1331
- }
1332
- if (logger.spinner && pluginManager.queue.size > 0) {
1333
- const text = `Item: ${count} Size: ${pluginManager.queue.size} Pending: ${pluginManager.queue.pending}`;
1334
- logger.spinner.suffixText = p.dim(text);
1335
- }
1336
- ++count;
1337
- });
1338
- pluginManager.queue.on("completed", () => {
1339
- if (logger.logLevel !== LogLevel.info) {
1340
- return;
1341
- }
1342
- if (logger.spinner) {
1343
- const text = `Item: ${count} Size: ${pluginManager.queue.size} Pending: ${pluginManager.queue.pending}`;
1344
- logger.spinner.suffixText = p.dim(text);
1345
- }
1346
- });
1347
- pluginManager.on("executed", (executer) => {
1348
- const { hookName, plugin, output, parameters } = executer;
1349
- const logs = [
1350
- `${randomCliColour(plugin.name)} Executing ${hookName}`,
1351
- parameters && `${p.bgWhite("Parameters")} ${randomCliColour(plugin.name)} ${hookName}`,
1352
- JSON.stringify(parameters, void 0, 2),
1353
- output && `${p.bgWhite("Output")} ${randomCliColour(plugin.name)} ${hookName}`,
1354
- output
1355
- ].filter(Boolean);
1356
- logger.emit("debug", logs);
1357
- });
1358
- return pluginManager;
1359
- }
1360
- async function build(options) {
1361
- const pluginManager = await setup(options);
1362
- const { fileManager, logger } = pluginManager;
1363
- await pluginManager.hookParallel({
1364
- hookName: "buildStart",
1365
- parameters: [options.config]
1366
- });
1367
- await pluginManager.hookParallel({ hookName: "buildEnd" });
1368
- if (logger.logLevel === LogLevel.info) {
1369
- logger.emit("end", "\u{1F4BE} Writing completed");
1370
- }
1371
- return {
1372
- files: fileManager.files.map((file) => ({
1373
- ...file,
1374
- source: FileManager.getSource(file)
1375
- })),
1376
- pluginManager
1377
- };
1378
- }
1379
- async function safeBuild(options) {
1380
- const pluginManager = await setup(options);
1381
- const { fileManager, logger } = pluginManager;
1382
- try {
1383
- await pluginManager.hookParallel({
1384
- hookName: "buildStart",
1385
- parameters: [options.config]
1386
- });
1387
- await pluginManager.hookParallel({ hookName: "buildEnd" });
1388
- if (logger.logLevel === LogLevel.info) {
1389
- logger.emit("end", "\u{1F4BE} Writing completed");
1390
- }
1391
- } catch (e) {
1392
- return {
1393
- files: fileManager.files.map((file) => ({
1394
- ...file,
1395
- source: FileManager.getSource(file)
1396
- })),
1397
- pluginManager,
1398
- error: e
1399
- };
1400
- }
1401
- return {
1402
- files: fileManager.files.map((file) => ({
1403
- ...file,
1404
- source: FileManager.getSource(file)
1405
- })),
1406
- pluginManager
1407
- };
1408
- }
1409
-
1410
- // src/Generator.ts
1411
- var _options3, _context;
1412
- var Generator = class {
1413
- constructor(options, context) {
1414
- __privateAdd(this, _options3, {});
1415
- __privateAdd(this, _context, {});
1416
- if (context) {
1417
- __privateSet(this, _context, context);
1418
- }
1419
- if (options) {
1420
- __privateSet(this, _options3, options);
1421
- }
1422
- return this;
1423
- }
1424
- get options() {
1425
- return __privateGet(this, _options3);
1426
- }
1427
- get context() {
1428
- return __privateGet(this, _context);
1429
- }
1430
- set options(options) {
1431
- __privateSet(this, _options3, { ...__privateGet(this, _options3), ...options });
1432
- }
1433
- };
1434
- _options3 = new WeakMap();
1435
- _context = new WeakMap();
1436
-
1437
- // src/PackageManager.ts
1438
- import mod from "module";
1439
- import os from "os";
1440
- import { pathToFileURL } from "url";
1441
- import { findUp, findUpSync } from "find-up";
1442
- import { coerce, satisfies } from "semver";
1443
- var _cache2, _cwd, _SLASHES, _match, match_fn;
1444
- var _PackageManager = class _PackageManager {
1445
- constructor(workspace) {
1446
- __privateAdd(this, _match);
1447
- __privateAdd(this, _cwd, void 0);
1448
- __privateAdd(this, _SLASHES, /* @__PURE__ */ new Set(["/", "\\"]));
1449
- if (workspace) {
1450
- __privateSet(this, _cwd, workspace);
1451
- }
1452
- return this;
1453
- }
1454
- set workspace(workspace) {
1455
- __privateSet(this, _cwd, workspace);
1456
- }
1457
- get workspace() {
1458
- return __privateGet(this, _cwd);
1459
- }
1460
- normalizeDirectory(directory) {
1461
- if (!__privateGet(this, _SLASHES).has(directory[directory.length - 1])) {
1462
- return `${directory}/`;
1463
- }
1464
- return directory;
1465
- }
1466
- getLocation(path3) {
1467
- let location = path3;
1468
- if (__privateGet(this, _cwd)) {
1469
- const require2 = mod.createRequire(this.normalizeDirectory(__privateGet(this, _cwd)));
1470
- location = require2.resolve(path3);
1471
- }
1472
- return location;
1473
- }
1474
- async import(path3) {
1475
- try {
1476
- let location = this.getLocation(path3);
1477
- if (os.platform() === "win32") {
1478
- location = pathToFileURL(location).href;
1479
- }
1480
- const module = await import(location);
1481
- return module?.default ?? module;
1482
- } catch (e) {
1483
- console.log(e);
1484
- return void 0;
1485
- }
1486
- }
1487
- async getPackageJSON() {
1488
- const pkgPath = await findUp(["package.json"], {
1489
- cwd: __privateGet(this, _cwd)
1490
- });
1491
- if (!pkgPath) {
1492
- return void 0;
1493
- }
1494
- const json = await read(pkgPath);
1495
- return JSON.parse(json);
1496
- }
1497
- getPackageJSONSync() {
1498
- const pkgPath = findUpSync(["package.json"], {
1499
- cwd: __privateGet(this, _cwd)
1500
- });
1501
- if (!pkgPath) {
1502
- return void 0;
1503
- }
1504
- const json = readSync(pkgPath);
1505
- return JSON.parse(json);
1506
- }
1507
- static setVersion(dependency, version) {
1508
- __privateGet(_PackageManager, _cache2)[dependency] = version;
1509
- }
1510
- async getVersion(dependency) {
1511
- if (typeof dependency === "string" && __privateGet(_PackageManager, _cache2)[dependency]) {
1512
- return __privateGet(_PackageManager, _cache2)[dependency];
1513
- }
1514
- const packageJSON = await this.getPackageJSON();
1515
- if (!packageJSON) {
1516
- return void 0;
1517
- }
1518
- return __privateMethod(this, _match, match_fn).call(this, packageJSON, dependency);
1519
- }
1520
- getVersionSync(dependency) {
1521
- if (typeof dependency === "string" && __privateGet(_PackageManager, _cache2)[dependency]) {
1522
- return __privateGet(_PackageManager, _cache2)[dependency];
1523
- }
1524
- const packageJSON = this.getPackageJSONSync();
1525
- if (!packageJSON) {
1526
- return void 0;
1527
- }
1528
- return __privateMethod(this, _match, match_fn).call(this, packageJSON, dependency);
1529
- }
1530
- async isValid(dependency, version) {
1531
- const packageVersion = await this.getVersion(dependency);
1532
- if (!packageVersion) {
1533
- return false;
1534
- }
1535
- if (packageVersion === version) {
1536
- return true;
1537
- }
1538
- const semVer = coerce(packageVersion);
1539
- if (!semVer) {
1540
- throw new Error(`${packageVersion} is not valid`);
1541
- }
1542
- return satisfies(semVer, version);
1543
- }
1544
- isValidSync(dependency, version) {
1545
- const packageVersion = this.getVersionSync(dependency);
1546
- if (!packageVersion) {
1547
- return false;
1548
- }
1549
- const semVer = coerce(packageVersion);
1550
- if (!semVer) {
1551
- throw new Error(`${packageVersion} is not valid`);
1552
- }
1553
- return satisfies(semVer, version);
1554
- }
1555
- };
1556
- _cache2 = new WeakMap();
1557
- _cwd = new WeakMap();
1558
- _SLASHES = new WeakMap();
1559
- _match = new WeakSet();
1560
- match_fn = function(packageJSON, dependency) {
1561
- const dependencies = {
1562
- ...packageJSON["dependencies"] || {},
1563
- ...packageJSON["devDependencies"] || {}
1564
- };
1565
- if (typeof dependency === "string" && dependencies[dependency]) {
1566
- return dependencies[dependency];
1567
- }
1568
- const matchedDependency = Object.keys(dependencies).find((dep) => dep.match(dependency));
1569
- return matchedDependency ? dependencies[matchedDependency] : void 0;
1570
- };
1571
- __privateAdd(_PackageManager, _cache2, {});
1572
- var PackageManager = _PackageManager;
1573
-
1574
- // src/kubb.ts
1575
- var kubb_exports = {};
2
+ FileManager,
3
+ Generator,
4
+ KubbFile,
5
+ PackageManager,
6
+ PluginManager,
7
+ PromiseManager,
8
+ Warning,
9
+ build,
10
+ createPlugin,
11
+ defineConfig,
12
+ isInputPath,
13
+ kubb_exports,
14
+ pluginName,
15
+ safeBuild
16
+ } from "./chunk-PXP5K73S.js";
17
+ import "./chunk-UCKFXEKM.js";
18
+ import "./chunk-ECWTIHD5.js";
19
+ import "./chunk-4X5FFJPJ.js";
20
+ import "./chunk-JLT7YQF5.js";
21
+ import "./chunk-MDO6MCFJ.js";
22
+ import "./chunk-2F7E62RD.js";
23
+ import "./chunk-Z4BLTVTB.js";
1576
24
  export {
1577
25
  FileManager,
1578
26
  Generator,