@kubb/core 1.1.13 → 1.2.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.
package/dist/index.cjs CHANGED
@@ -6,8 +6,13 @@ var crypto = require('crypto');
6
6
  var fs = require('fs-extra');
7
7
  var pathParser2 = require('path');
8
8
  var changeCase = require('change-case');
9
+ var perf_hooks = require('perf_hooks');
9
10
  var rimraf = require('rimraf');
10
11
  var dirTree = require('directory-tree');
12
+ var mod = require('module');
13
+ var url = require('url');
14
+ var pc2 = require('picocolors');
15
+ var seedrandom = require('seedrandom');
11
16
  var tsCodegen = require('@kubb/ts-codegen');
12
17
 
13
18
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -16,6 +21,9 @@ var crypto__default = /*#__PURE__*/_interopDefault(crypto);
16
21
  var fs__default = /*#__PURE__*/_interopDefault(fs);
17
22
  var pathParser2__default = /*#__PURE__*/_interopDefault(pathParser2);
18
23
  var dirTree__default = /*#__PURE__*/_interopDefault(dirTree);
24
+ var mod__default = /*#__PURE__*/_interopDefault(mod);
25
+ var pc2__default = /*#__PURE__*/_interopDefault(pc2);
26
+ var seedrandom__default = /*#__PURE__*/_interopDefault(seedrandom);
19
27
 
20
28
  // src/managers/fileManager/FileManager.ts
21
29
 
@@ -23,6 +31,12 @@ var dirTree__default = /*#__PURE__*/_interopDefault(dirTree);
23
31
  function isPromise(result) {
24
32
  return typeof result?.then === "function";
25
33
  }
34
+ function isPromiseFulfilledResult(result) {
35
+ return result.status === "fulfilled";
36
+ }
37
+ function isPromiseRejectedResult(result) {
38
+ return result.status === "rejected";
39
+ }
26
40
  async function safeWriteFileToPath(path, data) {
27
41
  const passedPath = pathParser2__default.default.dirname(pathParser2__default.default.resolve(path));
28
42
  await fs__default.default.mkdir(passedPath, { recursive: true });
@@ -165,18 +179,18 @@ async function timeout(ms) {
165
179
  }, ms);
166
180
  });
167
181
  }
168
-
169
- // src/utils/Queue.ts
170
182
  var Queue = class {
171
183
  queue = [];
172
184
  workerCount = 0;
173
185
  maxParallel;
174
- constructor(maxParallel) {
186
+ debug = false;
187
+ constructor(maxParallel, debug = false) {
175
188
  this.maxParallel = maxParallel;
189
+ this.debug = debug;
176
190
  }
177
- run(task) {
191
+ run(task, options = { name: crypto__default.default.randomUUID(), description: "" }) {
178
192
  return new Promise((resolve, reject) => {
179
- const item = { reject, resolve, task };
193
+ const item = { reject, resolve, task, name: options.name, description: options.description || options.name };
180
194
  this.queue.push(item);
181
195
  this.work();
182
196
  });
@@ -188,8 +202,17 @@ var Queue = class {
188
202
  this.workerCount++;
189
203
  let entry;
190
204
  while (entry = this.queue.shift()) {
191
- const { reject, resolve, task } = entry;
192
- task().then((result) => resolve(result)).catch((err) => reject(err));
205
+ const { reject, resolve, task, name, description } = entry;
206
+ if (this.debug) {
207
+ perf_hooks.performance.mark(name + "_start");
208
+ }
209
+ task().then((result) => {
210
+ resolve(result);
211
+ if (this.debug) {
212
+ perf_hooks.performance.mark(name + "_stop");
213
+ perf_hooks.performance.measure(description, name + "_start", name + "_stop");
214
+ }
215
+ }).catch((err) => reject(err));
193
216
  }
194
217
  this.workerCount--;
195
218
  }
@@ -412,6 +435,31 @@ function getStackTrace(belowFn) {
412
435
 
413
436
  // src/utils/uniqueId.ts
414
437
  var uniqueId = ((counter) => (str = "") => `${str}${++counter}`)(0);
438
+ var SLASHES = /* @__PURE__ */ new Set(["/", "\\"]);
439
+ function normalizeDirectory(directory) {
440
+ if (!SLASHES.has(directory[directory.length - 1])) {
441
+ return `${directory}/`;
442
+ }
443
+ return directory;
444
+ }
445
+ function getLocation(path, cwd) {
446
+ let location = path;
447
+ if (cwd) {
448
+ const require2 = mod__default.default.createRequire(normalizeDirectory(cwd));
449
+ location = require2.resolve(path);
450
+ }
451
+ return location;
452
+ }
453
+ async function importModule(path, cwd) {
454
+ try {
455
+ const location = getLocation(path, cwd);
456
+ const module = await import(url.pathToFileURL(location).href);
457
+ return module?.default ?? module;
458
+ } catch (e) {
459
+ console.log(e);
460
+ return void 0;
461
+ }
462
+ }
415
463
 
416
464
  // src/utils/throttle.ts
417
465
  var throttle = (fn, delay) => {
@@ -440,108 +488,85 @@ var throttle = (fn, delay) => {
440
488
  ];
441
489
  };
442
490
 
443
- // src/managers/fileManager/FileManager.ts
444
- var FileManager = class {
445
- cache = /* @__PURE__ */ new Map();
446
- task;
447
- queue;
448
- constructor(options) {
449
- if (options) {
450
- this.task = options.task;
451
- this.queue = options.queue;
452
- }
453
- }
454
- getCache(id) {
455
- return this.cache.get(id);
456
- }
457
- getCacheByPath(path) {
458
- let cache;
459
- this.cache.forEach((item) => {
460
- if (item.file.path === path) {
461
- cache = item;
462
- }
463
- });
464
- return cache;
465
- }
466
- get files() {
467
- const files = [];
468
- this.cache.forEach((item) => {
469
- files.push(item.file);
470
- });
471
- return files;
491
+ // src/utils/SummaryError.ts
492
+ var SummaryError = class extends Error {
493
+ summary;
494
+ constructor(message, options) {
495
+ super(message, { cause: options.cause });
496
+ this.name = "SummaryError";
497
+ this.summary = options.summary || [];
472
498
  }
473
- get cachedFiles() {
474
- const files = [];
475
- this.cache.forEach((item) => {
476
- files.push(item);
477
- });
478
- return files;
499
+ };
500
+
501
+ // src/utils/Warning.ts
502
+ var Warning = class extends Error {
503
+ constructor(message, options) {
504
+ super(message, { cause: options?.cause });
505
+ this.name = "Warning";
479
506
  }
480
- async add(file) {
481
- const cacheItem = { id: crypto__default.default.randomUUID(), file, status: "new" };
482
- this.cache.set(cacheItem.id, cacheItem);
483
- if (this.queue) {
484
- await this.queue.run(async () => {
485
- await this.task?.(cacheItem.id, file);
486
- });
507
+ };
508
+ function createLogger(spinner) {
509
+ const log = (message) => {
510
+ if (message && spinner) {
511
+ spinner.text = message;
487
512
  }
488
- return file;
489
- }
490
- addOrAppend(file) {
491
- if (!file.path.endsWith(file.fileName)) ;
492
- const previousCache = this.getCacheByPath(file.path);
493
- if (previousCache) {
494
- const sourceAlreadyExists = file.source && previousCache.file.source.includes(file.source);
495
- if (sourceAlreadyExists) {
496
- return Promise.resolve(file);
497
- }
498
- this.cache.delete(previousCache.id);
499
- return this.add({
500
- ...file,
501
- source: `${previousCache.file.source}
502
- ${file.source}`,
503
- imports: [...previousCache.file.imports || [], ...file.imports || []],
504
- exports: [...previousCache.file.exports || [], ...file.exports || []]
505
- });
513
+ };
514
+ const error = (message) => {
515
+ if (message) {
516
+ throw new Error(message || "Something went wrong");
506
517
  }
507
- return this.add(file);
508
- }
509
- setStatus(id, status) {
510
- const cacheItem = this.getCache(id);
511
- if (!cacheItem) {
512
- return;
518
+ };
519
+ const warn = (message) => {
520
+ if (message && spinner) {
521
+ spinner.warn(pc2__default.default.yellow(message));
522
+ }
523
+ };
524
+ const info = (message) => {
525
+ if (message && spinner) {
526
+ spinner.info(message);
513
527
  }
514
- cacheItem.status = status;
515
- this.cache.set(id, cacheItem);
528
+ };
529
+ const logger = {
530
+ log,
531
+ error,
532
+ warn,
533
+ info,
534
+ spinner
535
+ };
536
+ return logger;
537
+ }
538
+ function canLogHierarchy(input, compareTo) {
539
+ if (input === "stacktrace") {
540
+ return canLogHierarchy("info", compareTo);
516
541
  }
517
- get(id) {
518
- const cacheItem = this.getCache(id);
519
- return cacheItem?.file;
542
+ return input === compareTo;
543
+ }
544
+ var defaultColours = ["black", "blue", "darkBlue", "cyan", "gray", "green", "darkGreen", "magenta", "red", "darkRed", "yellow", "darkYellow"];
545
+ function randomColour(text, colours = defaultColours) {
546
+ if (!text) {
547
+ return "white";
520
548
  }
521
- remove(id) {
522
- const cacheItem = this.getCache(id);
523
- if (!cacheItem) {
524
- return;
525
- }
526
- this.setStatus(id, "removed");
549
+ const random = seedrandom__default.default(text);
550
+ const colour = colours.at(Math.floor(random() * colours.length)) || "white";
551
+ return colour;
552
+ }
553
+ function randomPicoColour(text, colors = defaultColours) {
554
+ const colours = pc2__default.default.createColors(true);
555
+ if (!text) {
556
+ return colours.white(text);
527
557
  }
528
- async write(...params) {
529
- if (this.queue) {
530
- return this.queue.run(async () => {
531
- return write(...params);
532
- });
533
- }
534
- return write(...params);
558
+ const colour = randomColour(text, colors);
559
+ const isDark = colour.includes("dark");
560
+ const key = colour.replace("dark", "").toLowerCase();
561
+ const formatter = colours[key];
562
+ if (isDark) {
563
+ return pc2__default.default.bold(formatter(text));
535
564
  }
536
- async read(...params) {
537
- if (this.queue) {
538
- return this.queue.run(async () => {
539
- return read(...params);
540
- });
541
- }
542
- return read(...params);
565
+ if (typeof formatter !== "function") {
566
+ throw new Error("Formatter for picoColor is not of type function/Formatter");
543
567
  }
544
- };
568
+ return formatter(text);
569
+ }
545
570
  function writeIndexes(root, options = {}) {
546
571
  const tree = TreeNode.build(root, { extensions: /\.ts/, ...options });
547
572
  if (!tree) {
@@ -597,9 +622,10 @@ function combineFiles(files) {
597
622
  acc[prevIndex] = {
598
623
  ...curr,
599
624
  source: prev.source && curr.source ? `${prev.source}
600
- ${curr.source}` : "'",
625
+ ${curr.source}` : "",
601
626
  imports: [...prev.imports || [], ...curr.imports || []],
602
- exports: [...prev.exports || [], ...curr.exports || []]
627
+ exports: [...prev.exports || [], ...curr.exports || []],
628
+ env: { ...prev.env || {}, ...curr.env || {} }
603
629
  };
604
630
  } else {
605
631
  acc.push(curr);
@@ -607,9 +633,10 @@ ${curr.source}` : "'",
607
633
  return acc;
608
634
  }, []);
609
635
  }
636
+ var extensions = [".js", ".ts"];
610
637
  function getFileSource(file) {
611
638
  let { source } = file;
612
- if (!file.fileName.endsWith(".ts")) {
639
+ if (!extensions.some((extension) => file.fileName.endsWith(extension))) {
613
640
  return file.source;
614
641
  }
615
642
  const imports = [];
@@ -656,6 +683,7 @@ function getFileSource(file) {
656
683
  return [...prev, tsCodegen.createExportDeclaration({ name: curr.name, path: curr.path, isTypeOnly: curr.isTypeOnly, asAlias: curr.asAlias })];
657
684
  }, []);
658
685
  const exportSource = tsCodegen.print(exportNodes);
686
+ source = getEnvSource(source, file.env);
659
687
  if (importSource) {
660
688
  source = `${importSource}
661
689
  ${source}`;
@@ -666,6 +694,133 @@ ${source}`;
666
694
  }
667
695
  return source;
668
696
  }
697
+ function searchAndReplace(options) {
698
+ const { text, replaceBy, prefix = "", key } = options;
699
+ const searchValues = options.searchValues?.(prefix, key) || [
700
+ `${prefix}["${key}"]`,
701
+ `${prefix}['${key}']`,
702
+ `${prefix}[\`${key}\`]`,
703
+ `${prefix}"${key}"`,
704
+ `${prefix}'${key}'`,
705
+ `${prefix}\`${key}\``,
706
+ new RegExp(`${prefix}${key}`, "g")
707
+ ];
708
+ return searchValues.reduce((prev, searchValue) => {
709
+ return prev.toString().replaceAll(searchValue, replaceBy);
710
+ }, text);
711
+ }
712
+ function getEnvSource(source, env) {
713
+ if (!env) {
714
+ return source;
715
+ }
716
+ const keys = Object.keys(env);
717
+ if (!keys.length) {
718
+ return source;
719
+ }
720
+ return keys.reduce((prev, key) => {
721
+ const environmentValue = env[key];
722
+ const replaceBy = environmentValue ? `'${environmentValue.replaceAll('"', "")?.replaceAll("'", "")}'` : "undefined";
723
+ if (key.toUpperCase() !== key) {
724
+ throw new TypeError(`Environment should be in upperCase for ${key}`);
725
+ }
726
+ if (typeof replaceBy === "string") {
727
+ prev = searchAndReplace({ text: prev.replaceAll(`process.env.${key}`, replaceBy), replaceBy, prefix: "process.env", key });
728
+ prev = searchAndReplace({ text: prev.replaceAll(new RegExp(`(declare const).*
729
+ `, "ig"), ""), replaceBy, key });
730
+ }
731
+ return prev;
732
+ }, source);
733
+ }
734
+
735
+ // src/managers/fileManager/FileManager.ts
736
+ var FileManager = class {
737
+ cache = /* @__PURE__ */ new Map();
738
+ task;
739
+ queue;
740
+ constructor(options) {
741
+ if (options) {
742
+ this.task = options.task;
743
+ this.queue = options.queue;
744
+ }
745
+ }
746
+ get extensions() {
747
+ return extensions;
748
+ }
749
+ get files() {
750
+ const files = [];
751
+ this.cache.forEach((item) => {
752
+ files.push(...item.flat(1));
753
+ });
754
+ return files;
755
+ }
756
+ async add(file) {
757
+ const resolvedFile = { id: crypto__default.default.randomUUID(), ...file };
758
+ this.cache.set(resolvedFile.path, [resolvedFile]);
759
+ if (this.queue) {
760
+ await this.queue.run(async () => {
761
+ await this.task?.(resolvedFile);
762
+ });
763
+ }
764
+ return resolvedFile;
765
+ }
766
+ addOrAppend(file) {
767
+ const previousCaches = this.cache.get(file.path);
768
+ const previousCache = previousCaches ? previousCaches.at(previousCaches.length - 1) : void 0;
769
+ if (previousCache) {
770
+ const sourceAlreadyExists = file.source && previousCache.source.includes(file.source);
771
+ if (sourceAlreadyExists) {
772
+ return Promise.resolve(previousCache);
773
+ }
774
+ this.cache.delete(previousCache.path);
775
+ return this.add({
776
+ ...file,
777
+ source: previousCache.source && file.source ? `${previousCache.source}
778
+ ${file.source}` : "",
779
+ imports: [...previousCache.imports || [], ...file.imports || []],
780
+ exports: [...previousCache.exports || [], ...file.exports || []],
781
+ env: { ...previousCache.env || {}, ...file.env || {} }
782
+ });
783
+ }
784
+ return this.add(file);
785
+ }
786
+ append(path, file) {
787
+ const previousFiles = this.cache.get(path) || [];
788
+ this.cache.set(path, [...previousFiles, file]);
789
+ }
790
+ getCacheByUUID(UUID) {
791
+ let cache;
792
+ this.cache.forEach((files) => {
793
+ cache = files.find((item) => item.id === UUID);
794
+ });
795
+ return cache;
796
+ }
797
+ get(path) {
798
+ return this.cache.get(path);
799
+ }
800
+ remove(path) {
801
+ const cacheItem = this.get(path);
802
+ if (!cacheItem) {
803
+ return;
804
+ }
805
+ this.cache.delete(path);
806
+ }
807
+ async write(...params) {
808
+ if (this.queue) {
809
+ return this.queue.run(async () => {
810
+ return write(...params);
811
+ });
812
+ }
813
+ return write(...params);
814
+ }
815
+ async read(...params) {
816
+ if (this.queue) {
817
+ return this.queue.run(async () => {
818
+ return read(...params);
819
+ });
820
+ }
821
+ return read(...params);
822
+ }
823
+ };
669
824
  function createPlugin(factory) {
670
825
  return (options) => {
671
826
  const plugin = factory(options);
@@ -680,67 +835,69 @@ function createPlugin(factory) {
680
835
  return plugin;
681
836
  };
682
837
  }
683
- var name = "core";
838
+ var pluginName = "core";
684
839
  var definePlugin = createPlugin((options) => {
685
- const { fileManager, resolvePath, resolveName, load } = options;
686
- const api = {
687
- get config() {
688
- return options.config;
689
- },
690
- fileManager,
691
- async addFile(...files) {
692
- const trace = getStackTrace();
693
- const plugins = options.config.plugins?.filter((plugin) => trace[1].getFileName()?.includes(plugin.name)).sort((a, b) => {
694
- if (a.name.length < b.name.length) {
695
- return 1;
696
- }
697
- if (a.name.length > b.name.length) {
698
- return -1;
699
- }
700
- return 0;
701
- });
702
- const pluginName = plugins?.[0]?.name;
703
- return Promise.all(
704
- files.map((file) => {
705
- const fileWithMeta = {
706
- ...file,
707
- meta: {
708
- ...file.meta || {},
709
- pluginName
710
- }
711
- };
712
- if (file.override) {
713
- return fileManager.add(fileWithMeta);
714
- }
715
- return fileManager.addOrAppend(fileWithMeta);
716
- })
717
- );
718
- },
719
- resolvePath,
720
- resolveName: (params) => {
721
- const name2 = resolveName(params);
722
- return transformReservedWord(name2);
723
- },
724
- load,
725
- cache: createPluginCache(/* @__PURE__ */ Object.create(null))
726
- };
840
+ const { fileManager, resolvePath, resolveName, load, logger } = options;
727
841
  return {
728
- name,
842
+ name: pluginName,
729
843
  options,
730
- api,
844
+ api() {
845
+ return {
846
+ get config() {
847
+ return options.config;
848
+ },
849
+ logger,
850
+ fileManager,
851
+ async addFile(...files) {
852
+ const trace = getStackTrace();
853
+ const plugins = options.config.plugins?.filter((plugin) => trace[1].getFileName()?.includes(plugin.name)).sort((a, b) => {
854
+ if (a.name.length < b.name.length) {
855
+ return 1;
856
+ }
857
+ if (a.name.length > b.name.length) {
858
+ return -1;
859
+ }
860
+ return 0;
861
+ });
862
+ const pluginName2 = plugins?.[0]?.name;
863
+ return Promise.all(
864
+ files.map((file) => {
865
+ const fileWithMeta = {
866
+ ...file,
867
+ meta: {
868
+ ...file.meta || {},
869
+ pluginName: pluginName2
870
+ }
871
+ };
872
+ if (file.override) {
873
+ return fileManager.add(fileWithMeta);
874
+ }
875
+ return fileManager.addOrAppend(fileWithMeta);
876
+ })
877
+ );
878
+ },
879
+ resolvePath,
880
+ resolveName: (params) => {
881
+ const name = resolveName(params);
882
+ return transformReservedWord(name);
883
+ },
884
+ load,
885
+ cache: createPluginCache(/* @__PURE__ */ Object.create(null))
886
+ };
887
+ },
731
888
  resolvePath(fileName) {
732
889
  const root = pathParser2__default.default.resolve(this.config.root, this.config.output.path);
733
890
  return pathParser2__default.default.resolve(root, fileName);
734
891
  },
735
- resolveName(name2) {
736
- return name2;
892
+ resolveName(name) {
893
+ return name;
737
894
  }
738
895
  };
739
896
  });
740
897
 
741
898
  // src/managers/pluginManager/ParallelPluginError.ts
742
899
  var ParallelPluginError = class extends Error {
743
- errors;
900
+ errors = [];
744
901
  pluginManager;
745
902
  constructor(message, options) {
746
903
  super(message, { cause: options.cause });
@@ -748,14 +905,27 @@ var ParallelPluginError = class extends Error {
748
905
  this.errors = options.errors;
749
906
  this.pluginManager = options.pluginManager;
750
907
  }
908
+ findError(searchError) {
909
+ return this.errors.find((error) => {
910
+ if (error.cause) {
911
+ if (error.cause.name == searchError.name) {
912
+ return true;
913
+ }
914
+ return !!this.findError(error.cause);
915
+ }
916
+ return error.name === searchError.name;
917
+ })?.cause;
918
+ }
751
919
  };
752
920
 
753
921
  // src/managers/pluginManager/PluginError.ts
754
922
  var PluginError = class extends Error {
755
923
  pluginManager;
924
+ cause;
756
925
  constructor(message, options) {
757
926
  super(message, { cause: options.cause });
758
927
  this.name = "PluginError";
928
+ this.cause = options.cause;
759
929
  this.pluginManager = options.pluginManager;
760
930
  }
761
931
  };
@@ -772,30 +942,46 @@ var hookNames = {
772
942
  buildEnd: 1
773
943
  };
774
944
  var hooks = Object.keys(hookNames);
945
+ var convertKubbUserPluginToKubbPlugin = (plugin, context) => {
946
+ if (plugin.api && typeof plugin.api === "function") {
947
+ const api = plugin.api.call(context);
948
+ return {
949
+ ...plugin,
950
+ api
951
+ };
952
+ }
953
+ return null;
954
+ };
775
955
  var PluginManager = class {
776
956
  plugins;
777
957
  fileManager;
778
958
  onExecute;
779
959
  core;
780
960
  queue;
781
- executer;
782
961
  executed = [];
962
+ logger;
783
963
  constructor(config, options) {
784
964
  this.onExecute = options.onExecute?.bind(this);
785
- this.queue = new Queue(10);
965
+ this.logger = options.logger;
966
+ this.queue = new Queue(100, options.debug);
786
967
  this.fileManager = new FileManager({ task: options.task, queue: this.queue });
787
- this.core = definePlugin({
968
+ const core = definePlugin({
788
969
  config,
970
+ logger: this.logger,
789
971
  fileManager: this.fileManager,
790
972
  load: this.load,
791
973
  resolvePath: this.resolvePath,
792
- resolveName: this.resolveName,
793
- getExecuter: this.getExecuter.bind(this)
974
+ resolveName: this.resolveName
794
975
  });
795
- this.plugins = [this.core, ...config.plugins || []];
796
- }
797
- getExecuter() {
798
- return this.executer;
976
+ const convertedCore = convertKubbUserPluginToKubbPlugin(core, core.api.call(null));
977
+ this.core = convertedCore;
978
+ this.plugins = [this.core, ...config.plugins || []].reduce((prev, plugin) => {
979
+ const convertedApi = convertKubbUserPluginToKubbPlugin(plugin, convertedCore?.api);
980
+ if (convertedApi) {
981
+ return [...prev, convertedApi];
982
+ }
983
+ return [...prev, plugin];
984
+ }, []);
799
985
  }
800
986
  resolvePath = (params) => {
801
987
  if (params.pluginName) {
@@ -834,11 +1020,11 @@ var PluginManager = class {
834
1020
  * Run only hook for a specific plugin name
835
1021
  */
836
1022
  hookForPlugin({
837
- pluginName,
1023
+ pluginName: pluginName2,
838
1024
  hookName,
839
1025
  parameters
840
1026
  }) {
841
- const plugin = this.getPlugin(hookName, pluginName);
1027
+ const plugin = this.getPlugin(hookName, pluginName2);
842
1028
  return this.execute({
843
1029
  strategy: "hookFirst",
844
1030
  hookName,
@@ -847,11 +1033,11 @@ var PluginManager = class {
847
1033
  });
848
1034
  }
849
1035
  hookForPluginSync({
850
- pluginName,
1036
+ pluginName: pluginName2,
851
1037
  hookName,
852
1038
  parameters
853
1039
  }) {
854
- const plugin = this.getPlugin(hookName, pluginName);
1040
+ const plugin = this.getPlugin(hookName, pluginName2);
855
1041
  return this.executeSync({
856
1042
  strategy: "hookFirst",
857
1043
  hookName,
@@ -936,7 +1122,12 @@ var PluginManager = class {
936
1122
  }
937
1123
  }
938
1124
  const results = await Promise.allSettled(parallelPromises);
939
- const errors = results.filter((result) => result.status === "rejected").map((result) => result.reason);
1125
+ const errors = results.map((result) => {
1126
+ if (isPromiseRejectedResult(result) && result.reason instanceof PluginError) {
1127
+ return result.reason;
1128
+ }
1129
+ return void 0;
1130
+ }).filter(Boolean);
940
1131
  if (errors.length) {
941
1132
  throw new ParallelPluginError("Error", { errors, pluginManager: this });
942
1133
  }
@@ -987,15 +1178,15 @@ var PluginManager = class {
987
1178
  const plugins = [...this.plugins].filter((plugin) => plugin.name !== "core");
988
1179
  return plugins;
989
1180
  }
990
- getPlugin(hookName, pluginName) {
1181
+ getPlugin(hookName, pluginName2) {
991
1182
  const plugins = [...this.plugins];
992
- const pluginByPluginName = plugins.find((item) => item.name === pluginName && item[hookName]);
1183
+ const pluginByPluginName = plugins.find((item) => item.name === pluginName2 && item[hookName]);
993
1184
  if (!pluginByPluginName) {
994
1185
  return this.core;
995
1186
  }
996
1187
  return pluginByPluginName;
997
1188
  }
998
- addExecuter(executer) {
1189
+ addExecutedToCallStack(executer) {
999
1190
  this.onExecute?.call(this, executer, this);
1000
1191
  if (executer) {
1001
1192
  this.executed.push(executer);
@@ -1015,38 +1206,35 @@ var PluginManager = class {
1015
1206
  plugin
1016
1207
  }) {
1017
1208
  const hook = plugin[hookName];
1209
+ let output;
1018
1210
  if (!hook) {
1019
1211
  return null;
1020
1212
  }
1021
- return Promise.resolve().then(() => {
1022
- this.executer = {
1023
- strategy,
1024
- hookName,
1025
- plugin
1026
- };
1213
+ const task = Promise.resolve().then(() => {
1027
1214
  if (typeof hook === "function") {
1028
- const hookResult = hook.apply(this.core.api, parameters);
1029
- if (isPromise(hookResult)) {
1030
- return Promise.resolve(hookResult).then((result) => {
1031
- this.addExecuter({
1032
- strategy,
1033
- hookName,
1034
- plugin
1035
- });
1036
- return result;
1037
- });
1215
+ const possiblePromiseResult = hook.apply(this.core.api, parameters);
1216
+ if (isPromise(possiblePromiseResult)) {
1217
+ return Promise.resolve(possiblePromiseResult);
1038
1218
  }
1039
- return hookResult;
1219
+ return possiblePromiseResult;
1040
1220
  }
1041
- this.addExecuter({
1221
+ return hook;
1222
+ }).then((result) => {
1223
+ output = result;
1224
+ return result;
1225
+ }).catch((e) => {
1226
+ this.catcher(e, plugin, hookName);
1227
+ return null;
1228
+ }).finally(() => {
1229
+ this.addExecutedToCallStack({
1230
+ input: parameters,
1231
+ output,
1042
1232
  strategy,
1043
1233
  hookName,
1044
1234
  plugin
1045
1235
  });
1046
- return hook;
1047
- }).catch((e) => {
1048
- this.catcher(e, plugin, hookName);
1049
1236
  });
1237
+ return this.queue.run(() => task);
1050
1238
  }
1051
1239
  /**
1052
1240
  * Run a sync plugin hook and return the result.
@@ -1062,33 +1250,29 @@ var PluginManager = class {
1062
1250
  plugin
1063
1251
  }) {
1064
1252
  const hook = plugin[hookName];
1253
+ let output;
1065
1254
  if (!hook) {
1066
1255
  return null;
1067
1256
  }
1068
1257
  try {
1069
- this.executer = {
1070
- strategy,
1071
- hookName,
1072
- plugin
1073
- };
1074
1258
  if (typeof hook === "function") {
1075
1259
  const fn = hook.apply(this.core.api, parameters);
1076
- this.addExecuter({
1077
- strategy,
1078
- hookName,
1079
- plugin
1080
- });
1260
+ output = fn;
1081
1261
  return fn;
1082
1262
  }
1083
- this.addExecuter({
1084
- strategy,
1085
- hookName,
1086
- plugin
1087
- });
1263
+ output = hook;
1088
1264
  return hook;
1089
1265
  } catch (e) {
1090
1266
  this.catcher(e, plugin, hookName);
1091
1267
  return null;
1268
+ } finally {
1269
+ this.addExecutedToCallStack({
1270
+ input: parameters,
1271
+ output,
1272
+ strategy,
1273
+ hookName,
1274
+ plugin
1275
+ });
1092
1276
  }
1093
1277
  }
1094
1278
  catcher(e, plugin, hookName) {
@@ -1110,23 +1294,20 @@ function validatePlugins(plugins, dependedPluginNames) {
1110
1294
  } else {
1111
1295
  pluginNames = dependedPluginNames;
1112
1296
  }
1113
- pluginNames.forEach((pluginName) => {
1114
- const exists = plugins.some((plugin) => plugin.name === pluginName);
1297
+ pluginNames.forEach((pluginName2) => {
1298
+ const exists = plugins.some((plugin) => plugin.name === pluginName2);
1115
1299
  if (!exists) {
1116
- throw new ValidationPluginError(`This plugin depends on the ${pluginName} plugin.`);
1300
+ throw new ValidationPluginError(`This plugin depends on the ${pluginName2} plugin.`);
1117
1301
  }
1118
1302
  });
1119
1303
  return true;
1120
1304
  }
1121
1305
 
1122
- // src/managers/pluginManager/SummaryError.ts
1123
- var SummaryError = class extends Error {
1124
- summary;
1125
- constructor(message, options) {
1126
- super(message, { cause: options.cause });
1127
- this.name = "SummaryError";
1128
- this.summary = options.summary || [];
1129
- }
1306
+ // src/types.ts
1307
+ var LogLevel = {
1308
+ silent: "silent",
1309
+ info: "info",
1310
+ stacktrace: "stacktrace"
1130
1311
  };
1131
1312
 
1132
1313
  // src/build.ts
@@ -1134,7 +1315,7 @@ async function transformReducer(_previousCode, result, _plugin) {
1134
1315
  return result;
1135
1316
  }
1136
1317
  async function build(options) {
1137
- const { config, logger } = options;
1318
+ const { config, debug, logger = createLogger() } = options;
1138
1319
  try {
1139
1320
  if (!isURL(config.input.path)) {
1140
1321
  await read(config.input.path);
@@ -1145,7 +1326,7 @@ async function build(options) {
1145
1326
  if (config.output.clean) {
1146
1327
  await clean(config.output.path);
1147
1328
  }
1148
- const queueTask = async (id, file) => {
1329
+ const queueTask = async (file) => {
1149
1330
  const { path } = file;
1150
1331
  let code = getFileSource(file);
1151
1332
  const { result: loadedResult } = await pluginManager.hookFirst({
@@ -1176,12 +1357,27 @@ async function build(options) {
1176
1357
  if (!executer) {
1177
1358
  return;
1178
1359
  }
1179
- const { hookName, plugin } = executer;
1180
- if (config.logLevel === "info" && logger) {
1181
- logger.log(null, { logLevel: config.logLevel, params: { hookName, pluginName: plugin.name } });
1360
+ const { hookName, plugin, output, input } = executer;
1361
+ const messsage = `${randomPicoColour(plugin.name)} Executing ${hookName}`;
1362
+ if (config.logLevel === LogLevel.info && logger?.spinner && input) {
1363
+ if (debug) {
1364
+ logger.info(messsage);
1365
+ } else {
1366
+ logger.spinner.suffixText = messsage;
1367
+ }
1368
+ }
1369
+ if (config.logLevel === LogLevel.stacktrace && logger?.spinner && input) {
1370
+ logger.info(messsage);
1371
+ const logs = [
1372
+ input && `${pc2__default.default.bgWhite(`Input`)} ${randomPicoColour(plugin.name)} ${hookName}`,
1373
+ JSON.stringify(input, void 0, 2),
1374
+ output && `${pc2__default.default.bgWhite("Output")} ${randomPicoColour(plugin.name)} ${hookName}`,
1375
+ output
1376
+ ].filter(Boolean);
1377
+ console.log(logs.join("\n"));
1182
1378
  }
1183
1379
  };
1184
- const pluginManager = new PluginManager(config, { task: queueTask, onExecute });
1380
+ const pluginManager = new PluginManager(config, { debug, logger, task: queueTask, onExecute });
1185
1381
  const { plugins, fileManager } = pluginManager;
1186
1382
  await pluginManager.hookParallel({
1187
1383
  hookName: "validate",
@@ -1222,8 +1418,13 @@ var SchemaGenerator = class extends Generator {
1222
1418
  // src/index.ts
1223
1419
  var src_default = build;
1224
1420
 
1421
+ Object.defineProperty(exports, 'pc', {
1422
+ enumerable: true,
1423
+ get: function () { return pc2__default.default; }
1424
+ });
1225
1425
  exports.FileManager = FileManager;
1226
1426
  exports.Generator = Generator;
1427
+ exports.LogLevel = LogLevel;
1227
1428
  exports.ParallelPluginError = ParallelPluginError;
1228
1429
  exports.PluginError = PluginError;
1229
1430
  exports.PluginManager = PluginManager;
@@ -1232,26 +1433,39 @@ exports.SchemaGenerator = SchemaGenerator;
1232
1433
  exports.SummaryError = SummaryError;
1233
1434
  exports.TreeNode = TreeNode;
1234
1435
  exports.ValidationPluginError = ValidationPluginError;
1436
+ exports.Warning = Warning;
1235
1437
  exports.build = build;
1438
+ exports.canLogHierarchy = canLogHierarchy;
1236
1439
  exports.clean = clean;
1237
1440
  exports.combineFiles = combineFiles;
1238
1441
  exports.createJSDocBlockText = createJSDocBlockText;
1442
+ exports.createLogger = createLogger;
1239
1443
  exports.createPlugin = createPlugin;
1240
1444
  exports.createPluginCache = createPluginCache;
1241
1445
  exports.default = src_default;
1446
+ exports.defaultColours = defaultColours;
1242
1447
  exports.defineConfig = defineConfig;
1448
+ exports.extensions = extensions;
1243
1449
  exports.getEncodedText = getEncodedText;
1244
1450
  exports.getFileSource = getFileSource;
1451
+ exports.getLocation = getLocation;
1245
1452
  exports.getPathMode = getPathMode;
1246
1453
  exports.getRelativePath = getRelativePath;
1247
1454
  exports.getStackTrace = getStackTrace;
1248
1455
  exports.getUniqueName = getUniqueName;
1249
1456
  exports.hooks = hooks;
1457
+ exports.importModule = importModule;
1250
1458
  exports.isPromise = isPromise;
1459
+ exports.isPromiseFulfilledResult = isPromiseFulfilledResult;
1460
+ exports.isPromiseRejectedResult = isPromiseRejectedResult;
1251
1461
  exports.isURL = isURL;
1252
- exports.name = name;
1462
+ exports.name = pluginName;
1253
1463
  exports.nameSorter = nameSorter;
1464
+ exports.normalizeDirectory = normalizeDirectory;
1254
1465
  exports.objectToParameters = objectToParameters;
1466
+ exports.pluginName = pluginName;
1467
+ exports.randomColour = randomColour;
1468
+ exports.randomPicoColour = randomPicoColour;
1255
1469
  exports.read = read;
1256
1470
  exports.renderTemplate = renderTemplate;
1257
1471
  exports.throttle = throttle;