@kubb/core 1.0.0-beta.9 → 1.0.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 (36) hide show
  1. package/dist/index.cjs +526 -244
  2. package/dist/index.d.ts +296 -231
  3. package/dist/index.js +521 -245
  4. package/package.json +8 -10
  5. package/src/build.ts +30 -47
  6. package/src/config.ts +2 -2
  7. package/src/generators/SchemaGenerator.ts +1 -1
  8. package/src/generators/index.ts +2 -2
  9. package/src/index.ts +9 -8
  10. package/src/managers/fileManager/FileManager.ts +19 -6
  11. package/src/managers/fileManager/index.ts +3 -4
  12. package/src/managers/fileManager/types.ts +17 -1
  13. package/src/managers/fileManager/utils.ts +111 -11
  14. package/src/managers/index.ts +2 -2
  15. package/src/managers/pluginManager/ParallelPluginError.ts +15 -0
  16. package/src/managers/pluginManager/PluginError.ts +11 -0
  17. package/src/managers/pluginManager/PluginManager.ts +133 -68
  18. package/src/managers/pluginManager/index.ts +5 -3
  19. package/src/managers/pluginManager/types.ts +10 -1
  20. package/src/managers/pluginManager/validate.ts +1 -1
  21. package/src/plugin.ts +44 -12
  22. package/src/types.ts +35 -8
  23. package/src/utils/clean.ts +5 -0
  24. package/src/utils/getEncodedText.ts +3 -0
  25. package/src/utils/getStackTrace.ts +19 -0
  26. package/src/utils/index.ts +17 -11
  27. package/src/utils/isPromise.ts +1 -1
  28. package/src/utils/objectToParameters.ts +6 -4
  29. package/src/utils/read.ts +3 -3
  30. package/src/utils/renderTemplate.ts +11 -0
  31. package/src/utils/transformReservedWord.ts +97 -0
  32. package/src/utils/write.ts +2 -16
  33. package/dist/index.cjs.map +0 -1
  34. package/dist/index.js.map +0 -1
  35. /package/src/utils/{queue.ts → Queue.ts} +0 -0
  36. /package/src/{managers/fileManager → utils}/TreeNode.ts +0 -0
package/dist/index.cjs CHANGED
@@ -6,31 +6,37 @@ var module$1 = require('module');
6
6
  var pathParser2 = require('path');
7
7
  var fs = require('fs');
8
8
  var rimraf = require('rimraf');
9
- var uuid = require('uuid');
10
9
  var dirTree = require('directory-tree');
11
- var uniq = require('lodash.uniq');
10
+ var crypto = require('crypto');
11
+ var tsCodegen = require('@kubb/ts-codegen');
12
12
 
13
13
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
14
 
15
15
  var pathParser2__default = /*#__PURE__*/_interopDefault(pathParser2);
16
- var rimraf__default = /*#__PURE__*/_interopDefault(rimraf);
17
16
  var dirTree__default = /*#__PURE__*/_interopDefault(dirTree);
18
- var uniq__default = /*#__PURE__*/_interopDefault(uniq);
17
+ var crypto__default = /*#__PURE__*/_interopDefault(crypto);
19
18
 
20
- module$1.createRequire((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('out.js', document.baseURI).href)));
19
+ module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('out.js', document.baseURI).href)));
21
20
 
22
- // src/utils/isURL.ts
23
- function isURL(data) {
24
- try {
25
- const url = new URL(data);
26
- if (url?.href) {
27
- return true;
28
- }
29
- } catch (error) {
30
- return false;
21
+ // src/managers/pluginManager/PluginError.ts
22
+ var PluginError = class extends Error {
23
+ pluginManager;
24
+ constructor(message, options) {
25
+ super(message, { cause: options.cause });
26
+ this.pluginManager = options.pluginManager;
31
27
  }
32
- return false;
33
- }
28
+ };
29
+
30
+ // src/managers/pluginManager/ParallelPluginError.ts
31
+ var ParallelPluginError = class extends Error {
32
+ errors;
33
+ pluginManager;
34
+ constructor(message, options) {
35
+ super(message, { cause: options.cause });
36
+ this.errors = options.errors;
37
+ this.pluginManager = options.pluginManager;
38
+ }
39
+ };
34
40
 
35
41
  // src/utils/isPromise.ts
36
42
  function isPromise(result) {
@@ -53,17 +59,6 @@ async function write(data, path) {
53
59
  }
54
60
  return safeWriteFileToPath(path, data);
55
61
  }
56
- async function clean(path) {
57
- return new Promise((resolve, reject) => {
58
- rimraf__default.default(path, (err) => {
59
- if (err) {
60
- reject(err);
61
- } else {
62
- resolve(true);
63
- }
64
- });
65
- });
66
- }
67
62
 
68
63
  // src/utils/cache.ts
69
64
  function createPluginCache(cache) {
@@ -99,7 +94,7 @@ function slash(path) {
99
94
  }
100
95
  function getRelativePath(rootDir, filePath) {
101
96
  if (!rootDir || !filePath) {
102
- throw new Error("Root and file should be filled in when retrieving the relativePath");
97
+ throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir} ${filePath}`);
103
98
  }
104
99
  const relativePath = pathParser2__default.default.relative(rootDir, filePath);
105
100
  const path = slash(relativePath).replace("../", "").trimEnd();
@@ -123,16 +118,30 @@ async function read(path) {
123
118
  }
124
119
  }
125
120
 
121
+ // src/utils/isURL.ts
122
+ function isURL(data) {
123
+ try {
124
+ const url = new URL(data);
125
+ if (url?.href) {
126
+ return true;
127
+ }
128
+ } catch (error) {
129
+ return false;
130
+ }
131
+ return false;
132
+ }
133
+
126
134
  // src/utils/objectToParameters.ts
127
135
  function objectToParameters(data, options = {}) {
136
+ const { typed } = options;
128
137
  return data.reduce((acc, [key, value]) => {
129
- if (options.typed) {
130
- acc.push(`${key}: ${value}["${key}"], `);
138
+ if (typed) {
139
+ acc.push(`${key}: ${value}["${key}"]`);
131
140
  } else {
132
- acc.push(`${key},`);
141
+ acc.push(`${key}`);
133
142
  }
134
143
  return acc;
135
- }, []).join("");
144
+ }, []).join(", ");
136
145
  }
137
146
 
138
147
  // src/utils/nameSorter.ts
@@ -180,7 +189,7 @@ async function timeout(ms) {
180
189
  });
181
190
  }
182
191
 
183
- // src/utils/queue.ts
192
+ // src/utils/Queue.ts
184
193
  var Queue = class {
185
194
  queue = [];
186
195
  workerCount = 0;
@@ -208,6 +217,213 @@ var Queue = class {
208
217
  }
209
218
  };
210
219
 
220
+ // src/utils/getEncodedText.ts
221
+ function getEncodedText(text) {
222
+ return text ? text.replaceAll("`", "\\`") : "";
223
+ }
224
+
225
+ // src/utils/renderTemplate.ts
226
+ function renderTemplate(template, data = void 0) {
227
+ if (!data) {
228
+ return template.replace(/{{(.*?)}}/g, "");
229
+ }
230
+ return template.replace(/{{(.*?)}}/g, (match) => {
231
+ const value = data[match.split(/{{|}}/).filter(Boolean)[0].trim()];
232
+ return value || "";
233
+ });
234
+ }
235
+ async function clean(path) {
236
+ return rimraf.rimraf(path);
237
+ }
238
+ var TreeNode = class {
239
+ data;
240
+ parent;
241
+ children = [];
242
+ constructor(data, parent) {
243
+ this.data = data;
244
+ this.parent = parent;
245
+ return this;
246
+ }
247
+ addChild(data) {
248
+ const child = new TreeNode(data, this);
249
+ if (!this.children) {
250
+ this.children = [];
251
+ }
252
+ this.children.push(child);
253
+ return child;
254
+ }
255
+ find(data) {
256
+ if (data === this.data) {
257
+ return this;
258
+ }
259
+ if (this.children) {
260
+ for (let i = 0, { length } = this.children, target = null; i < length; i++) {
261
+ target = this.children[i].find(data);
262
+ if (target) {
263
+ return target;
264
+ }
265
+ }
266
+ }
267
+ return null;
268
+ }
269
+ leaves() {
270
+ if (!this.children || this.children.length === 0) {
271
+ return [this];
272
+ }
273
+ const leaves = [];
274
+ if (this.children) {
275
+ for (let i = 0, { length } = this.children; i < length; i++) {
276
+ leaves.push.apply(leaves, this.children[i].leaves());
277
+ }
278
+ }
279
+ return leaves;
280
+ }
281
+ root() {
282
+ if (!this.parent) {
283
+ return this;
284
+ }
285
+ return this.parent.root();
286
+ }
287
+ forEach(callback) {
288
+ if (typeof callback !== "function") {
289
+ throw new TypeError("forEach() callback must be a function");
290
+ }
291
+ callback(this);
292
+ if (this.children) {
293
+ for (let i = 0, { length } = this.children; i < length; i++) {
294
+ this.children[i].forEach(callback);
295
+ }
296
+ }
297
+ return this;
298
+ }
299
+ static build(path, options = {}) {
300
+ const filteredTree = dirTree__default.default(path, { extensions: options?.extensions, exclude: options.exclude });
301
+ if (!filteredTree) {
302
+ return null;
303
+ }
304
+ const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type });
305
+ const recurse = (node, item) => {
306
+ const subNode = node.addChild({ name: item.name, path: item.path, type: item.type });
307
+ if (item.children?.length) {
308
+ item.children?.forEach((child) => {
309
+ recurse(subNode, child);
310
+ });
311
+ }
312
+ };
313
+ filteredTree.children?.forEach((child) => recurse(treeNode, child));
314
+ return treeNode;
315
+ }
316
+ };
317
+
318
+ // src/utils/transformReservedWord.ts
319
+ var reservedWords = [
320
+ "abstract",
321
+ "arguments",
322
+ "boolean",
323
+ "break",
324
+ "byte",
325
+ "case",
326
+ "catch",
327
+ "char",
328
+ "class",
329
+ "const",
330
+ "continue",
331
+ "debugger",
332
+ "default",
333
+ "delete",
334
+ "do",
335
+ "double",
336
+ "else",
337
+ "enum",
338
+ "eval",
339
+ "export",
340
+ "extends",
341
+ "false",
342
+ "final",
343
+ "finally",
344
+ "float",
345
+ "for",
346
+ "function",
347
+ "goto",
348
+ "if",
349
+ "implements",
350
+ "import",
351
+ "in",
352
+ "instanceof",
353
+ "int",
354
+ "interface",
355
+ "let",
356
+ "long",
357
+ "native",
358
+ "new",
359
+ "null",
360
+ "package",
361
+ "private",
362
+ "protected",
363
+ "public",
364
+ "return",
365
+ "short",
366
+ "static",
367
+ "super",
368
+ "switch",
369
+ "synchronized",
370
+ "this",
371
+ "throw",
372
+ "throws",
373
+ "transient",
374
+ "true",
375
+ "try",
376
+ "typeof",
377
+ "var",
378
+ "void",
379
+ "volatile",
380
+ "while",
381
+ "with",
382
+ "yield",
383
+ "Array",
384
+ "Date",
385
+ "eval",
386
+ "function",
387
+ "hasOwnProperty",
388
+ "Infinity",
389
+ "isFinite",
390
+ "isNaN",
391
+ "isPrototypeOf",
392
+ "length",
393
+ "Math",
394
+ "name",
395
+ "NaN",
396
+ "Number",
397
+ "Object",
398
+ "prototype",
399
+ "String",
400
+ "toString",
401
+ "undefined",
402
+ "valueOf"
403
+ ];
404
+ function transformReservedWord(word) {
405
+ if (word && reservedWords.includes(word)) {
406
+ return `_${word}`;
407
+ }
408
+ return word;
409
+ }
410
+
411
+ // src/utils/getStackTrace.ts
412
+ function getStackTrace(belowFn) {
413
+ const oldLimit = Error.stackTraceLimit;
414
+ Error.stackTraceLimit = Infinity;
415
+ const dummyObject = {};
416
+ const v8Handler = Error.prepareStackTrace;
417
+ Error.prepareStackTrace = function prepareStackTrace(dummyObject2, v8StackTrace2) {
418
+ return v8StackTrace2;
419
+ };
420
+ Error.captureStackTrace(dummyObject, belowFn || getStackTrace);
421
+ const v8StackTrace = dummyObject.stack;
422
+ Error.prepareStackTrace = v8Handler;
423
+ Error.stackTraceLimit = oldLimit;
424
+ return v8StackTrace;
425
+ }
426
+
211
427
  // src/plugin.ts
212
428
  function createPlugin(factory) {
213
429
  return (options) => {
@@ -231,11 +447,37 @@ var definePlugin = createPlugin((options) => {
231
447
  return options.config;
232
448
  },
233
449
  fileManager,
234
- async addFile(file) {
235
- return fileManager.addOrAppend(file);
450
+ async addFile(...files) {
451
+ const trace = getStackTrace();
452
+ const plugins = options.config.plugins?.filter((plugin) => trace[1].getFileName()?.includes(plugin.name)).sort((a, b) => {
453
+ if (a.name.length < b.name.length)
454
+ return 1;
455
+ if (a.name.length > b.name.length)
456
+ return -1;
457
+ return 0;
458
+ });
459
+ const pluginName = plugins?.[0].name;
460
+ return Promise.all(
461
+ files.map((file) => {
462
+ const fileWithMeta = {
463
+ ...file,
464
+ meta: {
465
+ ...file.meta || {},
466
+ pluginName
467
+ }
468
+ };
469
+ if (file.override) {
470
+ return fileManager.add(fileWithMeta);
471
+ }
472
+ return fileManager.addOrAppend(fileWithMeta);
473
+ })
474
+ );
236
475
  },
237
476
  resolvePath,
238
- resolveName,
477
+ resolveName: (params) => {
478
+ const name2 = resolveName(params);
479
+ return transformReservedWord(name2);
480
+ },
239
481
  load,
240
482
  cache: createPluginCache(/* @__PURE__ */ Object.create(null))
241
483
  };
@@ -243,11 +485,9 @@ var definePlugin = createPlugin((options) => {
243
485
  name,
244
486
  options,
245
487
  api,
246
- resolvePath(fileName, directory) {
247
- if (!directory) {
248
- return null;
249
- }
250
- return pathParser2__default.default.resolve(directory, fileName);
488
+ resolvePath(fileName) {
489
+ const root = pathParser2__default.default.resolve(this.config.root, this.config.output.path);
490
+ return pathParser2__default.default.resolve(root, fileName);
251
491
  },
252
492
  resolveName(name2) {
253
493
  return name2;
@@ -284,7 +524,7 @@ var FileManager = class {
284
524
  return files;
285
525
  }
286
526
  async add(file) {
287
- const cacheItem = { id: uuid.v4(), file, status: "new" };
527
+ const cacheItem = { id: crypto__default.default.randomUUID(), file, status: "new" };
288
528
  this.cache.set(cacheItem.id, cacheItem);
289
529
  if (this.queue) {
290
530
  await this.queue.run(async () => {
@@ -294,14 +534,20 @@ var FileManager = class {
294
534
  return file;
295
535
  }
296
536
  addOrAppend(file) {
537
+ if (!file.path.endsWith(file.fileName)) ;
297
538
  const previousCache = this.getCacheByPath(file.path);
298
539
  if (previousCache) {
540
+ const sourceAlreadyExists = file.source && previousCache.file.source.includes(file.source);
541
+ if (sourceAlreadyExists) {
542
+ return Promise.resolve(file);
543
+ }
299
544
  this.cache.delete(previousCache.id);
300
545
  return this.add({
301
546
  ...file,
302
547
  source: `${previousCache.file.source}
303
548
  ${file.source}`,
304
- imports: [...previousCache.file.imports || [], ...file.imports || []]
549
+ imports: [...previousCache.file.imports || [], ...file.imports || []],
550
+ exports: [...previousCache.file.exports || [], ...file.exports || []]
305
551
  });
306
552
  }
307
553
  return this.add(file);
@@ -332,141 +578,6 @@ ${file.source}`,
332
578
  return read(...params);
333
579
  }
334
580
  };
335
- var TreeNode = class {
336
- data;
337
- parent;
338
- children = [];
339
- constructor(data, parent) {
340
- this.data = data;
341
- this.parent = parent;
342
- return this;
343
- }
344
- addChild(data) {
345
- const child = new TreeNode(data, this);
346
- if (!this.children) {
347
- this.children = [];
348
- }
349
- this.children.push(child);
350
- return child;
351
- }
352
- find(data) {
353
- if (data === this.data) {
354
- return this;
355
- }
356
- if (this.children) {
357
- for (let i = 0, { length } = this.children, target = null; i < length; i++) {
358
- target = this.children[i].find(data);
359
- if (target) {
360
- return target;
361
- }
362
- }
363
- }
364
- return null;
365
- }
366
- leaves() {
367
- if (!this.children || this.children.length === 0) {
368
- return [this];
369
- }
370
- const leaves = [];
371
- if (this.children) {
372
- for (let i = 0, { length } = this.children; i < length; i++) {
373
- leaves.push.apply(leaves, this.children[i].leaves());
374
- }
375
- }
376
- return leaves;
377
- }
378
- root() {
379
- if (!this.parent) {
380
- return this;
381
- }
382
- return this.parent.root();
383
- }
384
- forEach(callback) {
385
- if (typeof callback !== "function") {
386
- throw new TypeError("forEach() callback must be a function");
387
- }
388
- callback(this);
389
- if (this.children) {
390
- for (let i = 0, { length } = this.children; i < length; i++) {
391
- this.children[i].forEach(callback);
392
- }
393
- }
394
- return this;
395
- }
396
- static build(path, options = {}) {
397
- const filteredTree = dirTree__default.default(path, { extensions: options?.extensions, exclude: options.exclude });
398
- if (!filteredTree) {
399
- return null;
400
- }
401
- const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type });
402
- const recurse = (node, item) => {
403
- const subNode = node.addChild({ name: item.name, path: item.path, type: item.type });
404
- if (item.children?.length) {
405
- item.children?.forEach((child) => {
406
- recurse(subNode, child);
407
- });
408
- }
409
- };
410
- filteredTree.children?.forEach((child) => recurse(treeNode, child));
411
- return treeNode;
412
- }
413
- };
414
- function combineFiles(files) {
415
- return files.filter(Boolean).reduce((acc, curr) => {
416
- if (!curr) {
417
- return acc;
418
- }
419
- const prevIndex = acc.findIndex((item) => item.path === curr.path);
420
- if (prevIndex !== -1) {
421
- const prev = acc[prevIndex];
422
- acc[prevIndex] = {
423
- ...curr,
424
- source: `${prev.source}
425
- ${curr.source}`,
426
- imports: [...prev.imports || [], ...curr.imports || []]
427
- };
428
- } else {
429
- acc.push(curr);
430
- }
431
- return acc;
432
- }, []);
433
- }
434
- function getFileSource(file) {
435
- if (!file.fileName.endsWith(".ts")) {
436
- return file.source;
437
- }
438
- const imports = [];
439
- file.imports?.forEach((curr) => {
440
- const exists = imports.find((imp) => imp.path === curr.path);
441
- if (!exists) {
442
- imports.push({
443
- ...curr,
444
- name: Array.isArray(curr.name) ? uniq__default.default(curr.name) : curr.name
445
- });
446
- }
447
- if (exists && !Array.isArray(exists.name) && exists.name !== curr.name) {
448
- imports.push(curr);
449
- }
450
- if (exists && Array.isArray(exists.name)) {
451
- if (Array.isArray(curr.name)) {
452
- exists.name = uniq__default.default([...exists.name, ...curr.name]);
453
- }
454
- }
455
- });
456
- const importSource = imports.reduce((prev, curr) => {
457
- if (Array.isArray(curr.name)) {
458
- return `${prev}
459
- import ${curr.isTypeOnly ? "type " : ""}{ ${curr.name.join(", ")} } from "${curr.path}";`;
460
- }
461
- return `${prev}
462
- import ${curr.isTypeOnly ? "type " : ""}${curr.name} from "${curr.path}";`;
463
- }, "");
464
- if (importSource) {
465
- return `${importSource}
466
- ${file.source}`;
467
- }
468
- return file.source;
469
- }
470
581
 
471
582
  // src/managers/pluginManager/PluginManager.ts
472
583
  var hookNames = {
@@ -483,13 +594,13 @@ var hooks = Object.keys(hookNames);
483
594
  var PluginManager = class {
484
595
  plugins;
485
596
  fileManager;
486
- logger;
487
- config;
597
+ onExecute;
488
598
  core;
489
599
  queue;
600
+ executer;
601
+ executed = [];
490
602
  constructor(config, options) {
491
- this.logger = options.logger;
492
- this.config = config;
603
+ this.onExecute = options.onExecute;
493
604
  this.queue = new Queue(10);
494
605
  this.fileManager = new FileManager({ task: options.task, queue: this.queue });
495
606
  this.core = definePlugin({
@@ -497,10 +608,14 @@ var PluginManager = class {
497
608
  fileManager: this.fileManager,
498
609
  load: this.load,
499
610
  resolvePath: this.resolvePath,
500
- resolveName: this.resolveName
611
+ resolveName: this.resolveName,
612
+ getExecuter: this.getExecuter.bind(this)
501
613
  });
502
614
  this.plugins = [this.core, ...config.plugins || []];
503
615
  }
616
+ getExecuter() {
617
+ return this.executer;
618
+ }
504
619
  resolvePath = (params) => {
505
620
  if (params.pluginName) {
506
621
  return this.hookForPluginSync({
@@ -543,7 +658,7 @@ var PluginManager = class {
543
658
  parameters
544
659
  }) {
545
660
  const plugin = this.getPlugin(hookName, pluginName);
546
- return this.run({
661
+ return this.execute({
547
662
  strategy: "hookFirst",
548
663
  hookName,
549
664
  parameters,
@@ -556,7 +671,7 @@ var PluginManager = class {
556
671
  parameters
557
672
  }) {
558
673
  const plugin = this.getPlugin(hookName, pluginName);
559
- return this.runSync({
674
+ return this.executeSync({
560
675
  strategy: "hookFirst",
561
676
  hookName,
562
677
  parameters,
@@ -579,7 +694,7 @@ var PluginManager = class {
579
694
  promise = promise.then((result) => {
580
695
  if (result != null)
581
696
  return result;
582
- return this.run({
697
+ return this.execute({
583
698
  strategy: "hookFirst",
584
699
  hookName,
585
700
  parameters,
@@ -602,7 +717,7 @@ var PluginManager = class {
602
717
  for (const plugin of this.getSortedPlugins(hookName)) {
603
718
  if (skipped && skipped.has(plugin))
604
719
  continue;
605
- result = this.runSync({
720
+ result = this.executeSync({
606
721
  strategy: "hookFirst",
607
722
  hookName,
608
723
  parameters,
@@ -624,18 +739,25 @@ var PluginManager = class {
624
739
  if (plugin[hookName]?.sequential) {
625
740
  await Promise.all(parallelPromises);
626
741
  parallelPromises.length = 0;
627
- await this.run({
742
+ await this.execute({
628
743
  strategy: "hookParallel",
629
744
  hookName,
630
745
  parameters,
631
746
  plugin
632
747
  });
633
748
  } else {
634
- const promise = this.run({ strategy: "hookParallel", hookName, parameters, plugin });
635
- parallelPromises.push(promise);
749
+ const promise = this.execute({ strategy: "hookParallel", hookName, parameters, plugin });
750
+ if (promise) {
751
+ parallelPromises.push(promise);
752
+ }
636
753
  }
637
754
  }
638
- return Promise.all(parallelPromises);
755
+ const results = await Promise.allSettled(parallelPromises);
756
+ const errors = results.filter((result) => result.status === "rejected").map((result) => result.reason);
757
+ if (errors.length) {
758
+ throw new ParallelPluginError("Error", { errors, pluginManager: this });
759
+ }
760
+ return results.filter((result) => result.status === "fulfilled").map((result) => result.value);
639
761
  }
640
762
  // chains, reduces returned value, handling the reduced value as the first hook argument
641
763
  hookReduceArg0({
@@ -646,14 +768,15 @@ var PluginManager = class {
646
768
  const [argument0, ...rest] = parameters;
647
769
  let promise = Promise.resolve(argument0);
648
770
  for (const plugin of this.getSortedPlugins(hookName)) {
649
- promise = promise.then(
650
- (argument02) => this.run({
771
+ promise = promise.then((argument02) => {
772
+ const value = this.execute({
651
773
  strategy: "hookReduceArg0",
652
774
  hookName,
653
775
  parameters: [argument02, ...rest],
654
776
  plugin
655
- }).then((result) => reduce.call(this.core.api, argument02, result, plugin))
656
- );
777
+ });
778
+ return value;
779
+ }).then((result) => reduce.call(this.core.api, argument0, result, plugin));
657
780
  }
658
781
  return promise;
659
782
  }
@@ -662,7 +785,7 @@ var PluginManager = class {
662
785
  let promise = Promise.resolve();
663
786
  for (const plugin of this.getSortedPlugins(hookName)) {
664
787
  promise = promise.then(
665
- () => this.run({
788
+ () => this.execute({
666
789
  strategy: "hookSeq",
667
790
  hookName,
668
791
  parameters,
@@ -680,13 +803,16 @@ var PluginManager = class {
680
803
  const plugins = [...this.plugins];
681
804
  const pluginByPluginName = plugins.find((item) => item.name === pluginName && item[hookName]);
682
805
  if (!pluginByPluginName) {
683
- if (this.config.logLevel === "warn" && this.logger?.spinner) {
684
- this.logger.spinner.info(`Plugin hook with ${hookName} not found for plugin ${pluginName}`);
685
- }
686
806
  return this.core;
687
807
  }
688
808
  return pluginByPluginName;
689
809
  }
810
+ addExecuter(executer) {
811
+ this.onExecute?.call(this, executer);
812
+ if (executer) {
813
+ this.executed.push(executer);
814
+ }
815
+ }
690
816
  /**
691
817
  * Run an async plugin hook and return the result.
692
818
  * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.
@@ -694,36 +820,42 @@ var PluginManager = class {
694
820
  * @param plugin The actual pluginObject to run.
695
821
  */
696
822
  // Implementation signature
697
- run({
823
+ execute({
698
824
  strategy,
699
825
  hookName,
700
826
  parameters,
701
827
  plugin
702
828
  }) {
703
829
  const hook = plugin[hookName];
830
+ if (!hook) {
831
+ return null;
832
+ }
704
833
  return Promise.resolve().then(() => {
705
- if (typeof hook !== "function") {
706
- return hook;
707
- }
708
- if (this.config.logLevel === "info" && this.logger?.spinner) {
709
- this.logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name}
710
- `;
711
- }
712
- const hookResult = hook.apply(this.core.api, parameters);
713
- if (!hookResult?.then) {
714
- if (this.config.logLevel === "info" && this.logger?.spinner) {
715
- this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name}
716
- `);
834
+ this.executer = {
835
+ strategy,
836
+ hookName,
837
+ plugin
838
+ };
839
+ if (typeof hook === "function") {
840
+ const hookResult = hook.apply(this.core.api, parameters);
841
+ if (isPromise(hookResult)) {
842
+ return Promise.resolve(hookResult).then((result) => {
843
+ this.addExecuter({
844
+ strategy,
845
+ hookName,
846
+ plugin
847
+ });
848
+ return result;
849
+ });
717
850
  }
718
851
  return hookResult;
719
852
  }
720
- return Promise.resolve(hookResult).then((result) => {
721
- if (this.config.logLevel === "info" && this.logger?.spinner) {
722
- this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name}
723
- `);
724
- }
725
- return result;
853
+ this.addExecuter({
854
+ strategy,
855
+ hookName,
856
+ plugin
726
857
  });
858
+ return hook;
727
859
  }).catch((e) => {
728
860
  this.catcher(e, plugin, hookName);
729
861
  });
@@ -735,18 +867,37 @@ var PluginManager = class {
735
867
  * @param plugin The acutal plugin
736
868
  * @param replaceContext When passed, the plugin context can be overridden.
737
869
  */
738
- runSync({
870
+ executeSync({
739
871
  strategy,
740
872
  hookName,
741
873
  parameters,
742
874
  plugin
743
875
  }) {
744
876
  const hook = plugin[hookName];
877
+ if (!hook) {
878
+ return null;
879
+ }
745
880
  try {
746
- if (typeof hook !== "function") {
747
- return hook;
881
+ this.executer = {
882
+ strategy,
883
+ hookName,
884
+ plugin
885
+ };
886
+ if (typeof hook === "function") {
887
+ const fn = hook.apply(this.core.api, parameters);
888
+ this.addExecuter({
889
+ strategy,
890
+ hookName,
891
+ plugin
892
+ });
893
+ return fn;
748
894
  }
749
- return hook.apply(this.core.api, parameters);
895
+ this.addExecuter({
896
+ strategy,
897
+ hookName,
898
+ plugin
899
+ });
900
+ return hook;
750
901
  } catch (e) {
751
902
  this.catcher(e, plugin, hookName);
752
903
  return null;
@@ -755,7 +906,7 @@ var PluginManager = class {
755
906
  catcher(e, plugin, hookName) {
756
907
  const text = `${e.message} (plugin: ${plugin.name}, hook: ${hookName})
757
908
  `;
758
- throw new Error(text, { cause: e });
909
+ throw new PluginError(text, { cause: e, pluginManager: this });
759
910
  }
760
911
  };
761
912
  function noReturn() {
@@ -779,6 +930,133 @@ function validatePlugins(plugins, dependedPluginNames) {
779
930
  });
780
931
  return true;
781
932
  }
933
+ function writeIndexes(root, options) {
934
+ const tree = TreeNode.build(root, { extensions: /\.ts/, ...options });
935
+ if (!tree) {
936
+ return void 0;
937
+ }
938
+ const fileReducer = (files2, item) => {
939
+ if (!item.children) {
940
+ return [];
941
+ }
942
+ if (item.children?.length > 1) {
943
+ const path = pathParser2__default.default.resolve(item.data.path, "index.ts");
944
+ const exports = item.children.map((file) => {
945
+ if (!file) {
946
+ return void 0;
947
+ }
948
+ const importPath = file.data.type === "directory" ? `./${file.data.name}` : `./${file.data.name.replace(/\.[^.]*$/, "")}`;
949
+ if (importPath.includes("index") && path.includes("index")) {
950
+ return void 0;
951
+ }
952
+ return { path: importPath };
953
+ }).filter(Boolean);
954
+ files2.push({
955
+ path,
956
+ fileName: "index.ts",
957
+ source: "",
958
+ exports
959
+ });
960
+ } else {
961
+ item.children?.forEach((child) => {
962
+ const path = pathParser2__default.default.resolve(item.data.path, "index.ts");
963
+ const importPath = child.data.type === "directory" ? `./${child.data.name}` : `./${child.data.name.replace(/\.[^.]*$/, "")}`;
964
+ files2.push({
965
+ path,
966
+ fileName: "index.ts",
967
+ source: "",
968
+ exports: [{ path: importPath }]
969
+ });
970
+ });
971
+ }
972
+ item.children.forEach((childItem) => {
973
+ fileReducer(files2, childItem);
974
+ });
975
+ return files2;
976
+ };
977
+ const files = fileReducer([], tree);
978
+ return files;
979
+ }
980
+ function combineFiles(files) {
981
+ return files.filter(Boolean).reduce((acc, curr) => {
982
+ if (!curr) {
983
+ return acc;
984
+ }
985
+ const prevIndex = acc.findIndex((item) => item.path === curr.path);
986
+ if (prevIndex !== -1) {
987
+ const prev = acc[prevIndex];
988
+ acc[prevIndex] = {
989
+ ...curr,
990
+ source: `${prev.source}
991
+ ${curr.source}`,
992
+ imports: [...prev.imports || [], ...curr.imports || []],
993
+ exports: [...prev.exports || [], ...curr.exports || []]
994
+ };
995
+ } else {
996
+ acc.push(curr);
997
+ }
998
+ return acc;
999
+ }, []);
1000
+ }
1001
+ function getFileSource(file) {
1002
+ let { source } = file;
1003
+ if (!file.fileName.endsWith(".ts")) {
1004
+ return file.source;
1005
+ }
1006
+ const imports = [];
1007
+ const exports = [];
1008
+ file.imports?.forEach((curr) => {
1009
+ const exists = imports.find((imp) => imp.path === curr.path);
1010
+ if (!exists) {
1011
+ imports.push({
1012
+ ...curr,
1013
+ name: Array.isArray(curr.name) ? [...new Set(curr.name)] : curr.name
1014
+ });
1015
+ }
1016
+ if (exists && !Array.isArray(exists.name) && exists.name !== curr.name) {
1017
+ imports.push(curr);
1018
+ }
1019
+ if (exists && Array.isArray(exists.name)) {
1020
+ if (Array.isArray(curr.name)) {
1021
+ exists.name = [.../* @__PURE__ */ new Set([...exists.name, ...curr.name])];
1022
+ }
1023
+ }
1024
+ });
1025
+ file.exports?.forEach((curr) => {
1026
+ const exists = exports.find((imp) => imp.path === curr.path);
1027
+ if (!exists) {
1028
+ exports.push({
1029
+ ...curr,
1030
+ name: Array.isArray(curr.name) ? [...new Set(curr.name)] : curr.name
1031
+ });
1032
+ }
1033
+ if (exists && !Array.isArray(exists.name) && exists.name !== curr.name && exists.asAlias === curr.asAlias) {
1034
+ exports.push(curr);
1035
+ }
1036
+ if (exists && Array.isArray(exists.name)) {
1037
+ if (Array.isArray(curr.name)) {
1038
+ exists.name = [.../* @__PURE__ */ new Set([...exists.name, ...curr.name])];
1039
+ }
1040
+ }
1041
+ });
1042
+ const importNodes = imports.reduce((prev, curr) => {
1043
+ return [...prev, tsCodegen.createImportDeclaration({ name: curr.name, path: curr.path, isTypeOnly: curr.isTypeOnly })];
1044
+ }, []);
1045
+ const importSource = tsCodegen.print(importNodes);
1046
+ const exportNodes = exports.reduce((prev, curr) => {
1047
+ return [...prev, tsCodegen.createExportDeclaration({ name: curr.name, path: curr.path, asAlias: curr.asAlias })];
1048
+ }, []);
1049
+ const exportSource = tsCodegen.print(exportNodes);
1050
+ if (importSource) {
1051
+ source = `${importSource}
1052
+ ${source}`;
1053
+ }
1054
+ if (exportSource) {
1055
+ source = `${exportSource}
1056
+ ${source}`;
1057
+ }
1058
+ return source;
1059
+ }
782
1060
 
783
1061
  // src/build.ts
784
1062
  async function transformReducer(_previousCode, result, _plugin) {
@@ -787,8 +1065,13 @@ async function transformReducer(_previousCode, result, _plugin) {
787
1065
  }
788
1066
  return result;
789
1067
  }
790
- async function buildImplementation(options, done) {
1068
+ async function build(options) {
791
1069
  const { config, logger } = options;
1070
+ try {
1071
+ await read(config.input.path);
1072
+ } catch (e) {
1073
+ throw new Error("Cannot read file defined in `input.path` or set with --input in the CLI of your Kubb config", { cause: e });
1074
+ }
792
1075
  if (config.output.clean) {
793
1076
  await clean(config.output.path);
794
1077
  }
@@ -816,7 +1099,17 @@ async function buildImplementation(options, done) {
816
1099
  }
817
1100
  }
818
1101
  };
819
- const pluginManager = new PluginManager(config, { logger, task: queueTask });
1102
+ const onExecute = (executer) => {
1103
+ if (!executer) {
1104
+ return;
1105
+ }
1106
+ const { strategy, hookName, plugin } = executer;
1107
+ if (config.logLevel === "info" && logger?.spinner) {
1108
+ logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name}
1109
+ `;
1110
+ }
1111
+ };
1112
+ const pluginManager = new PluginManager(config, { task: queueTask, onExecute });
820
1113
  const { plugins, fileManager } = pluginManager;
821
1114
  await pluginManager.hookParallel({
822
1115
  hookName: "validate",
@@ -827,23 +1120,7 @@ async function buildImplementation(options, done) {
827
1120
  parameters: [config]
828
1121
  });
829
1122
  await pluginManager.hookParallel({ hookName: "buildEnd" });
830
- setTimeout(() => {
831
- done({ files: fileManager.files.map((file) => ({ ...file, source: getFileSource(file) })) });
832
- }, 500);
833
- pluginManager.fileManager.add({
834
- path: isURL(config.input.path) ? config.input.path : pathParser2__default.default.resolve(config.root, config.input.path),
835
- fileName: isURL(config.input.path) ? "input" : config.input.path,
836
- source: isURL(config.input.path) ? config.input.path : await read(pathParser2__default.default.resolve(config.root, config.input.path))
837
- });
838
- }
839
- function build(options) {
840
- return new Promise(async (resolve, reject) => {
841
- try {
842
- await buildImplementation(options, resolve);
843
- } catch (e) {
844
- reject(e);
845
- }
846
- });
1123
+ return { files: fileManager.files.map((file) => ({ ...file, source: getFileSource(file) })), pluginManager };
847
1124
  }
848
1125
 
849
1126
  // src/config.ts
@@ -875,6 +1152,8 @@ var src_default = build;
875
1152
 
876
1153
  exports.FileManager = FileManager;
877
1154
  exports.Generator = Generator;
1155
+ exports.ParallelPluginError = ParallelPluginError;
1156
+ exports.PluginError = PluginError;
878
1157
  exports.PluginManager = PluginManager;
879
1158
  exports.Queue = Queue;
880
1159
  exports.SchemaGenerator = SchemaGenerator;
@@ -888,9 +1167,11 @@ exports.createPlugin = createPlugin;
888
1167
  exports.createPluginCache = createPluginCache;
889
1168
  exports.default = src_default;
890
1169
  exports.defineConfig = defineConfig;
1170
+ exports.getEncodedText = getEncodedText;
891
1171
  exports.getFileSource = getFileSource;
892
1172
  exports.getPathMode = getPathMode;
893
1173
  exports.getRelativePath = getRelativePath;
1174
+ exports.getStackTrace = getStackTrace;
894
1175
  exports.getUniqueName = getUniqueName;
895
1176
  exports.hooks = hooks;
896
1177
  exports.isPromise = isPromise;
@@ -899,8 +1180,9 @@ exports.name = name;
899
1180
  exports.nameSorter = nameSorter;
900
1181
  exports.objectToParameters = objectToParameters;
901
1182
  exports.read = read;
1183
+ exports.renderTemplate = renderTemplate;
902
1184
  exports.timeout = timeout;
1185
+ exports.transformReservedWord = transformReservedWord;
903
1186
  exports.validatePlugins = validatePlugins;
904
1187
  exports.write = write;
905
- //# sourceMappingURL=out.js.map
906
- //# sourceMappingURL=index.cjs.map
1188
+ exports.writeIndexes = writeIndexes;