@kubb/core 1.1.12 → 1.2.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.
package/dist/index.js CHANGED
@@ -5,6 +5,10 @@ import pathParser2 from 'node:path';
5
5
  import { camelCase, camelCaseTransformMerge } from 'change-case';
6
6
  import { rimraf } from 'rimraf';
7
7
  import dirTree from 'directory-tree';
8
+ import mod from 'node:module';
9
+ import { pathToFileURL } from 'node:url';
10
+ import pc from 'picocolors';
11
+ export { default as pc } from 'picocolors';
8
12
  import { createImportDeclaration, print, createExportDeclaration } from '@kubb/ts-codegen';
9
13
 
10
14
  createRequire(import.meta.url);
@@ -13,6 +17,12 @@ createRequire(import.meta.url);
13
17
  function isPromise(result) {
14
18
  return typeof result?.then === "function";
15
19
  }
20
+ function isPromiseFulfilledResult(result) {
21
+ return result.status === "fulfilled";
22
+ }
23
+ function isPromiseRejectedResult(result) {
24
+ return result.status === "rejected";
25
+ }
16
26
  async function safeWriteFileToPath(path, data) {
17
27
  const passedPath = pathParser2.dirname(pathParser2.resolve(path));
18
28
  await fs.mkdir(passedPath, { recursive: true });
@@ -402,6 +412,31 @@ function getStackTrace(belowFn) {
402
412
 
403
413
  // src/utils/uniqueId.ts
404
414
  var uniqueId = ((counter) => (str = "") => `${str}${++counter}`)(0);
415
+ var SLASHES = /* @__PURE__ */ new Set(["/", "\\"]);
416
+ function normalizeDirectory(directory) {
417
+ if (!SLASHES.has(directory[directory.length - 1])) {
418
+ return `${directory}/`;
419
+ }
420
+ return directory;
421
+ }
422
+ function getLocation(path, cwd) {
423
+ let location = path;
424
+ if (cwd) {
425
+ const require2 = mod.createRequire(normalizeDirectory(cwd));
426
+ location = require2.resolve(path);
427
+ }
428
+ return location;
429
+ }
430
+ async function importModule(path, cwd) {
431
+ try {
432
+ const location = getLocation(path, cwd);
433
+ const module = await import(pathToFileURL(location).href);
434
+ return module?.default ?? module;
435
+ } catch (e) {
436
+ console.log(e);
437
+ return void 0;
438
+ }
439
+ }
405
440
 
406
441
  // src/utils/throttle.ts
407
442
  var throttle = (fn, delay) => {
@@ -430,98 +465,53 @@ var throttle = (fn, delay) => {
430
465
  ];
431
466
  };
432
467
 
433
- // src/managers/fileManager/FileManager.ts
434
- var FileManager = class {
435
- cache = /* @__PURE__ */ new Map();
436
- task;
437
- queue;
438
- constructor(options) {
439
- if (options) {
440
- this.task = options.task;
441
- this.queue = options.queue;
442
- }
443
- }
444
- getCache(id) {
445
- return this.cache.get(id);
446
- }
447
- getCacheByPath(path) {
448
- let cache;
449
- this.cache.forEach((item) => {
450
- if (item.file.path === path) {
451
- cache = item;
452
- }
453
- });
454
- return cache;
455
- }
456
- get files() {
457
- const files = [];
458
- this.cache.forEach((item) => {
459
- files.push(item.file);
460
- });
461
- return files;
468
+ // src/utils/SummaryError.ts
469
+ var SummaryError = class extends Error {
470
+ summary;
471
+ constructor(message, options) {
472
+ super(message, { cause: options.cause });
473
+ this.name = "SummaryError";
474
+ this.summary = options.summary || [];
462
475
  }
463
- get cachedFiles() {
464
- const files = [];
465
- this.cache.forEach((item) => {
466
- files.push(item);
467
- });
468
- return files;
476
+ };
477
+
478
+ // src/utils/Warning.ts
479
+ var Warning = class extends Error {
480
+ constructor(message, options) {
481
+ super(message, { cause: options?.cause });
482
+ this.name = "Warning";
469
483
  }
470
- async add(file) {
471
- const cacheItem = { id: crypto.randomUUID(), file, status: "new" };
472
- this.cache.set(cacheItem.id, cacheItem);
473
- if (this.queue) {
474
- await this.queue.run(async () => {
475
- await this.task?.(cacheItem.id, file);
476
- });
484
+ };
485
+ function createLogger(spinner) {
486
+ const [log] = throttle((message) => {
487
+ if (message && spinner) {
488
+ spinner.text = message;
477
489
  }
478
- return file;
479
- }
480
- addOrAppend(file) {
481
- if (!file.path.endsWith(file.fileName)) ;
482
- const previousCache = this.getCacheByPath(file.path);
483
- if (previousCache) {
484
- const sourceAlreadyExists = file.source && previousCache.file.source.includes(file.source);
485
- if (sourceAlreadyExists) {
486
- return Promise.resolve(file);
487
- }
488
- this.cache.delete(previousCache.id);
489
- return this.add({
490
- ...file,
491
- source: `${previousCache.file.source}
492
- ${file.source}`,
493
- imports: [...previousCache.file.imports || [], ...file.imports || []],
494
- exports: [...previousCache.file.exports || [], ...file.exports || []]
495
- });
490
+ }, 100);
491
+ const [error] = throttle((message) => {
492
+ if (message) {
493
+ throw new Error(message || "Something went wrong");
496
494
  }
497
- return this.add(file);
498
- }
499
- setStatus(id, status) {
500
- const cacheItem = this.getCache(id);
501
- if (!cacheItem) {
502
- return;
495
+ }, 100);
496
+ const [warn] = throttle((message) => {
497
+ if (message && spinner) {
498
+ spinner.warn(pc.yellow(message));
503
499
  }
504
- cacheItem.status = status;
505
- this.cache.set(id, cacheItem);
506
- }
507
- get(id) {
508
- const cacheItem = this.getCache(id);
509
- return cacheItem?.file;
510
- }
511
- remove(id) {
512
- const cacheItem = this.getCache(id);
513
- if (!cacheItem) {
514
- return;
500
+ }, 100);
501
+ const [info] = throttle((message) => {
502
+ if (message && spinner) {
503
+ spinner.text = message;
515
504
  }
516
- this.setStatus(id, "removed");
517
- }
518
- async write(...params) {
519
- return write(...params);
520
- }
521
- async read(...params) {
522
- return read(...params);
523
- }
524
- };
505
+ }, 100);
506
+ const logger = {
507
+ log,
508
+ error,
509
+ warn,
510
+ info,
511
+ spinner
512
+ };
513
+ return logger;
514
+ }
525
515
  function writeIndexes(root, options = {}) {
526
516
  const tree = TreeNode.build(root, { extensions: /\.ts/, ...options });
527
517
  if (!tree) {
@@ -579,7 +569,8 @@ function combineFiles(files) {
579
569
  source: prev.source && curr.source ? `${prev.source}
580
570
  ${curr.source}` : "'",
581
571
  imports: [...prev.imports || [], ...curr.imports || []],
582
- exports: [...prev.exports || [], ...curr.exports || []]
572
+ exports: [...prev.exports || [], ...curr.exports || []],
573
+ env: { ...prev.env || {}, ...curr.env || {} }
583
574
  };
584
575
  } else {
585
576
  acc.push(curr);
@@ -587,9 +578,10 @@ ${curr.source}` : "'",
587
578
  return acc;
588
579
  }, []);
589
580
  }
581
+ var extensions = [".js", ".ts"];
590
582
  function getFileSource(file) {
591
583
  let { source } = file;
592
- if (!file.fileName.endsWith(".ts")) {
584
+ if (!extensions.some((extension) => file.fileName.endsWith(extension))) {
593
585
  return file.source;
594
586
  }
595
587
  const imports = [];
@@ -636,6 +628,7 @@ function getFileSource(file) {
636
628
  return [...prev, createExportDeclaration({ name: curr.name, path: curr.path, isTypeOnly: curr.isTypeOnly, asAlias: curr.asAlias })];
637
629
  }, []);
638
630
  const exportSource = print(exportNodes);
631
+ source = getEnvSource(source, file.env);
639
632
  if (importSource) {
640
633
  source = `${importSource}
641
634
  ${source}`;
@@ -646,6 +639,149 @@ ${source}`;
646
639
  }
647
640
  return source;
648
641
  }
642
+ function searchAndReplace(options) {
643
+ const { text, replaceBy, prefix = "", key } = options;
644
+ const searchValues = options.searchValues?.(prefix, key) || [
645
+ `${prefix}["${key}"]`,
646
+ `${prefix}['${key}']`,
647
+ `${prefix}[\`${key}\`]`,
648
+ `${prefix}"${key}"`,
649
+ `${prefix}'${key}'`,
650
+ `${prefix}\`${key}\``,
651
+ new RegExp(`${prefix}${key}`, "g")
652
+ ];
653
+ return searchValues.reduce((prev, searchValue) => {
654
+ return prev.toString().replaceAll(searchValue, replaceBy);
655
+ }, text);
656
+ }
657
+ function getEnvSource(source, env) {
658
+ if (!env) {
659
+ return source;
660
+ }
661
+ const keys = Object.keys(env);
662
+ if (!keys.length) {
663
+ return source;
664
+ }
665
+ return keys.reduce((prev, key) => {
666
+ const environmentValue = env[key];
667
+ const replaceBy = environmentValue ? `'${environmentValue.replaceAll('"', "")?.replaceAll("'", "")}'` : "undefined";
668
+ if (key.toUpperCase() !== key) {
669
+ throw new TypeError(`Environment should be in upperCase for ${key}`);
670
+ }
671
+ if (typeof replaceBy === "string") {
672
+ prev = searchAndReplace({ text: prev.replaceAll(`process.env.${key}`, replaceBy), replaceBy, prefix: "process.env", key });
673
+ prev = searchAndReplace({ text: prev.replaceAll(new RegExp(`(declare const).*
674
+ `, "ig"), ""), replaceBy, key });
675
+ }
676
+ return prev;
677
+ }, source);
678
+ }
679
+
680
+ // src/managers/fileManager/FileManager.ts
681
+ var FileManager = class {
682
+ cache = /* @__PURE__ */ new Map();
683
+ task;
684
+ queue;
685
+ constructor(options) {
686
+ if (options) {
687
+ this.task = options.task;
688
+ this.queue = options.queue;
689
+ }
690
+ }
691
+ getCache(id) {
692
+ return this.cache.get(id);
693
+ }
694
+ get extensions() {
695
+ return extensions;
696
+ }
697
+ getCacheByPath(path) {
698
+ let cache;
699
+ this.cache.forEach((item) => {
700
+ if (item.file.path === path) {
701
+ cache = item;
702
+ }
703
+ });
704
+ return cache;
705
+ }
706
+ get files() {
707
+ const files = [];
708
+ this.cache.forEach((item) => {
709
+ files.push(item.file);
710
+ });
711
+ return files;
712
+ }
713
+ get cachedFiles() {
714
+ const files = [];
715
+ this.cache.forEach((item) => {
716
+ files.push(item);
717
+ });
718
+ return files;
719
+ }
720
+ async add(file) {
721
+ const cacheItem = { id: crypto.randomUUID(), file, status: "new" };
722
+ this.cache.set(cacheItem.id, cacheItem);
723
+ if (this.queue) {
724
+ await this.queue.run(async () => {
725
+ await this.task?.(cacheItem.id, file);
726
+ });
727
+ }
728
+ return file;
729
+ }
730
+ addOrAppend(file) {
731
+ if (!file.path.endsWith(file.fileName)) ;
732
+ const previousCache = this.getCacheByPath(file.path);
733
+ if (previousCache) {
734
+ const sourceAlreadyExists = file.source && previousCache.file.source.includes(file.source);
735
+ if (sourceAlreadyExists) {
736
+ return Promise.resolve(file);
737
+ }
738
+ this.cache.delete(previousCache.id);
739
+ return this.add({
740
+ ...file,
741
+ source: `${previousCache.file.source}
742
+ ${file.source}`,
743
+ imports: [...previousCache.file.imports || [], ...file.imports || []],
744
+ exports: [...previousCache.file.exports || [], ...file.exports || []]
745
+ });
746
+ }
747
+ return this.add(file);
748
+ }
749
+ setStatus(id, status) {
750
+ const cacheItem = this.getCache(id);
751
+ if (!cacheItem) {
752
+ return;
753
+ }
754
+ cacheItem.status = status;
755
+ this.cache.set(id, cacheItem);
756
+ }
757
+ get(id) {
758
+ const cacheItem = this.getCache(id);
759
+ return cacheItem?.file;
760
+ }
761
+ remove(id) {
762
+ const cacheItem = this.getCache(id);
763
+ if (!cacheItem) {
764
+ return;
765
+ }
766
+ this.setStatus(id, "removed");
767
+ }
768
+ async write(...params) {
769
+ if (this.queue) {
770
+ return this.queue.run(async () => {
771
+ return write(...params);
772
+ });
773
+ }
774
+ return write(...params);
775
+ }
776
+ async read(...params) {
777
+ if (this.queue) {
778
+ return this.queue.run(async () => {
779
+ return read(...params);
780
+ });
781
+ }
782
+ return read(...params);
783
+ }
784
+ };
649
785
  function createPlugin(factory) {
650
786
  return (options) => {
651
787
  const plugin = factory(options);
@@ -660,9 +796,9 @@ function createPlugin(factory) {
660
796
  return plugin;
661
797
  };
662
798
  }
663
- var name = "core";
799
+ var pluginName = "core";
664
800
  var definePlugin = createPlugin((options) => {
665
- const { fileManager, resolvePath, resolveName, load } = options;
801
+ const { fileManager, resolvePath, resolveName, load, logger } = options;
666
802
  const api = {
667
803
  get config() {
668
804
  return options.config;
@@ -679,14 +815,14 @@ var definePlugin = createPlugin((options) => {
679
815
  }
680
816
  return 0;
681
817
  });
682
- const pluginName = plugins?.[0]?.name;
818
+ const pluginName2 = plugins?.[0]?.name;
683
819
  return Promise.all(
684
820
  files.map((file) => {
685
821
  const fileWithMeta = {
686
822
  ...file,
687
823
  meta: {
688
824
  ...file.meta || {},
689
- pluginName
825
+ pluginName: pluginName2
690
826
  }
691
827
  };
692
828
  if (file.override) {
@@ -698,42 +834,58 @@ var definePlugin = createPlugin((options) => {
698
834
  },
699
835
  resolvePath,
700
836
  resolveName: (params) => {
701
- const name2 = resolveName(params);
702
- return transformReservedWord(name2);
837
+ const name = resolveName(params);
838
+ return transformReservedWord(name);
703
839
  },
704
840
  load,
841
+ logger,
705
842
  cache: createPluginCache(/* @__PURE__ */ Object.create(null))
706
843
  };
707
844
  return {
708
- name,
845
+ name: pluginName,
709
846
  options,
710
847
  api,
711
848
  resolvePath(fileName) {
712
849
  const root = pathParser2.resolve(this.config.root, this.config.output.path);
713
850
  return pathParser2.resolve(root, fileName);
714
851
  },
715
- resolveName(name2) {
716
- return name2;
852
+ resolveName(name) {
853
+ return name;
717
854
  }
718
855
  };
719
856
  });
720
857
 
721
858
  // src/managers/pluginManager/ParallelPluginError.ts
722
859
  var ParallelPluginError = class extends Error {
723
- errors;
860
+ errors = [];
724
861
  pluginManager;
725
862
  constructor(message, options) {
726
863
  super(message, { cause: options.cause });
864
+ this.name = "ParallelPluginError";
727
865
  this.errors = options.errors;
728
866
  this.pluginManager = options.pluginManager;
729
867
  }
868
+ findError(searchError) {
869
+ return this.errors.find((error) => {
870
+ if (error.cause) {
871
+ if (error.cause.name == searchError.name) {
872
+ return true;
873
+ }
874
+ return !!this.findError(error.cause);
875
+ }
876
+ return error.name === searchError.name;
877
+ })?.cause;
878
+ }
730
879
  };
731
880
 
732
881
  // src/managers/pluginManager/PluginError.ts
733
882
  var PluginError = class extends Error {
734
883
  pluginManager;
884
+ cause;
735
885
  constructor(message, options) {
736
886
  super(message, { cause: options.cause });
887
+ this.name = "PluginError";
888
+ this.cause = options.cause;
737
889
  this.pluginManager = options.pluginManager;
738
890
  }
739
891
  };
@@ -758,12 +910,15 @@ var PluginManager = class {
758
910
  queue;
759
911
  executer;
760
912
  executed = [];
913
+ logger;
761
914
  constructor(config, options) {
762
915
  this.onExecute = options.onExecute?.bind(this);
916
+ this.logger = options.logger;
763
917
  this.queue = new Queue(10);
764
918
  this.fileManager = new FileManager({ task: options.task, queue: this.queue });
765
919
  this.core = definePlugin({
766
920
  config,
921
+ logger: this.logger,
767
922
  fileManager: this.fileManager,
768
923
  load: this.load,
769
924
  resolvePath: this.resolvePath,
@@ -812,11 +967,11 @@ var PluginManager = class {
812
967
  * Run only hook for a specific plugin name
813
968
  */
814
969
  hookForPlugin({
815
- pluginName,
970
+ pluginName: pluginName2,
816
971
  hookName,
817
972
  parameters
818
973
  }) {
819
- const plugin = this.getPlugin(hookName, pluginName);
974
+ const plugin = this.getPlugin(hookName, pluginName2);
820
975
  return this.execute({
821
976
  strategy: "hookFirst",
822
977
  hookName,
@@ -825,11 +980,11 @@ var PluginManager = class {
825
980
  });
826
981
  }
827
982
  hookForPluginSync({
828
- pluginName,
983
+ pluginName: pluginName2,
829
984
  hookName,
830
985
  parameters
831
986
  }) {
832
- const plugin = this.getPlugin(hookName, pluginName);
987
+ const plugin = this.getPlugin(hookName, pluginName2);
833
988
  return this.executeSync({
834
989
  strategy: "hookFirst",
835
990
  hookName,
@@ -914,9 +1069,13 @@ var PluginManager = class {
914
1069
  }
915
1070
  }
916
1071
  const results = await Promise.allSettled(parallelPromises);
917
- const errors = results.filter((result) => result.status === "rejected").map((result) => result.reason);
1072
+ const errors = results.map((result) => {
1073
+ if (isPromiseRejectedResult(result) && result.reason instanceof PluginError) {
1074
+ return result.reason;
1075
+ }
1076
+ return void 0;
1077
+ }).filter(Boolean);
918
1078
  if (errors.length) {
919
- console.log(errors);
920
1079
  throw new ParallelPluginError("Error", { errors, pluginManager: this });
921
1080
  }
922
1081
  return results.filter((result) => result.status === "fulfilled").map((result) => result.value);
@@ -966,9 +1125,9 @@ var PluginManager = class {
966
1125
  const plugins = [...this.plugins].filter((plugin) => plugin.name !== "core");
967
1126
  return plugins;
968
1127
  }
969
- getPlugin(hookName, pluginName) {
1128
+ getPlugin(hookName, pluginName2) {
970
1129
  const plugins = [...this.plugins];
971
- const pluginByPluginName = plugins.find((item) => item.name === pluginName && item[hookName]);
1130
+ const pluginByPluginName = plugins.find((item) => item.name === pluginName2 && item[hookName]);
972
1131
  if (!pluginByPluginName) {
973
1132
  return this.core;
974
1133
  }
@@ -1025,6 +1184,7 @@ var PluginManager = class {
1025
1184
  return hook;
1026
1185
  }).catch((e) => {
1027
1186
  this.catcher(e, plugin, hookName);
1187
+ return null;
1028
1188
  });
1029
1189
  }
1030
1190
  /**
@@ -1089,10 +1249,10 @@ function validatePlugins(plugins, dependedPluginNames) {
1089
1249
  } else {
1090
1250
  pluginNames = dependedPluginNames;
1091
1251
  }
1092
- pluginNames.forEach((pluginName) => {
1093
- const exists = plugins.some((plugin) => plugin.name === pluginName);
1252
+ pluginNames.forEach((pluginName2) => {
1253
+ const exists = plugins.some((plugin) => plugin.name === pluginName2);
1094
1254
  if (!exists) {
1095
- throw new ValidationPluginError(`This plugin depends on the ${pluginName} plugin.`);
1255
+ throw new ValidationPluginError(`This plugin depends on the ${pluginName2} plugin.`);
1096
1256
  }
1097
1257
  });
1098
1258
  return true;
@@ -1103,7 +1263,7 @@ async function transformReducer(_previousCode, result, _plugin) {
1103
1263
  return result;
1104
1264
  }
1105
1265
  async function build(options) {
1106
- const { config, logger } = options;
1266
+ const { config, logger = createLogger() } = options;
1107
1267
  try {
1108
1268
  if (!isURL(config.input.path)) {
1109
1269
  await read(config.input.path);
@@ -1146,11 +1306,12 @@ async function build(options) {
1146
1306
  return;
1147
1307
  }
1148
1308
  const { hookName, plugin } = executer;
1149
- if (config.logLevel === "info" && logger) {
1150
- logger.log(null, { logLevel: config.logLevel, params: { hookName, pluginName: plugin.name } });
1309
+ if (config.logLevel === "info") {
1310
+ const messsage = `\u{1FA82} Executing ${hookName || "unknown"}(${pc.yellow(plugin.name || "unknown")})`;
1311
+ logger.log(messsage);
1151
1312
  }
1152
1313
  };
1153
- const pluginManager = new PluginManager(config, { task: queueTask, onExecute });
1314
+ const pluginManager = new PluginManager(config, { logger, task: queueTask, onExecute });
1154
1315
  const { plugins, fileManager } = pluginManager;
1155
1316
  await pluginManager.hookParallel({
1156
1317
  hookName: "validate",
@@ -1191,4 +1352,6 @@ var SchemaGenerator = class extends Generator {
1191
1352
  // src/index.ts
1192
1353
  var src_default = build;
1193
1354
 
1194
- export { FileManager, Generator, ParallelPluginError, PluginError, PluginManager, Queue, SchemaGenerator, TreeNode, ValidationPluginError, build, clean, combineFiles, createJSDocBlockText, createPlugin, createPluginCache, src_default as default, defineConfig, getEncodedText, getFileSource, getPathMode, getRelativePath, getStackTrace, getUniqueName, hooks, isPromise, isURL, name, nameSorter, objectToParameters, read, renderTemplate, throttle, timeout, transformReservedWord, uniqueId, validatePlugins, write, writeIndexes };
1355
+ export { FileManager, Generator, ParallelPluginError, PluginError, PluginManager, Queue, SchemaGenerator, SummaryError, TreeNode, ValidationPluginError, Warning, build, clean, combineFiles, createJSDocBlockText, createLogger, createPlugin, createPluginCache, src_default as default, defineConfig, extensions, getEncodedText, getFileSource, getLocation, getPathMode, getRelativePath, getStackTrace, getUniqueName, hooks, importModule, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, isURL, pluginName as name, nameSorter, normalizeDirectory, objectToParameters, pluginName, read, renderTemplate, throttle, timeout, transformReservedWord, uniqueId, validatePlugins, write, writeIndexes };
1356
+ //# sourceMappingURL=out.js.map
1357
+ //# sourceMappingURL=index.js.map