@kubb/core 0.37.8 → 0.37.10

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.mjs CHANGED
@@ -2,7 +2,7 @@ import { createRequire } from 'module';
2
2
  import pathParser from 'path';
3
3
  import fse from 'fs-extra';
4
4
  import { format as format$1 } from 'prettier';
5
- import EventEmitter from 'events';
5
+ import EventEmitter from 'eventemitter3';
6
6
  import { v4 } from 'uuid';
7
7
  import dirTree from 'directory-tree';
8
8
 
@@ -621,6 +621,549 @@ var SchemaGenerator = class extends Generator {
621
621
  // src/index.ts
622
622
  var src_default = build;
623
623
 
624
+ export { FileManager, Generator, PluginManager, SchemaGenerator, TreeNode, ValidationPluginError, build, clean, createPlugin, createPluginCache, src_default as default, defineConfig, format, getPathMode, getRelativePath, hooks, isPromise, read, validatePlugins, write };
625
+ //# sourceMappingURL=out.js.map
626
+ //# sourceMappingURL=index.mjs.map;
627
+ if (Array.isArray(plugin)) {
628
+ throw new Error("Not implemented");
629
+ }
630
+ if (!plugin.transform) {
631
+ plugin.transform = function transform(code) {
632
+ return code;
633
+ };
634
+ }
635
+ return plugin;
636
+ };
637
+ }
638
+ var name = "core";
639
+ var isEmittedFile = (result) => {
640
+ return !!result.id;
641
+ };
642
+ var definePlugin = createPlugin((options) => {
643
+ const { fileManager, resolveId, load } = options;
644
+ const api = {
645
+ get config() {
646
+ return options.config;
647
+ },
648
+ fileManager,
649
+ async addFile(file, options2) {
650
+ if (isEmittedFile(file)) {
651
+ const resolvedId = await resolveId({ fileName: file.id, directory: file.importer, options: file.options });
652
+ const path2 = resolvedId || file.importer || file.id;
653
+ return fileManager.add({
654
+ path: path2,
655
+ fileName: file.name || file.id,
656
+ source: file.source || ""
657
+ });
658
+ }
659
+ if (options2?.root) ;
660
+ return fileManager.addOrAppend(file);
661
+ },
662
+ resolveId,
663
+ load,
664
+ cache: createPluginCache(/* @__PURE__ */ Object.create(null))
665
+ };
666
+ return {
667
+ name,
668
+ api,
669
+ resolveId(fileName, directory) {
670
+ if (!directory) {
671
+ return null;
672
+ }
673
+ return import_path3.default.resolve(directory, fileName);
674
+ }
675
+ };
676
+ });
677
+
678
+ // src/managers/fileManager/FileManager.ts
679
+ init_esm_shims();
680
+
681
+ // src/managers/fileManager/events.ts
682
+ init_esm_shims();
683
+ var keys = {
684
+ getFileKey: () => `file`,
685
+ getStatusChangeKey: () => `status-change`,
686
+ getStatusChangeByIdKey: (id) => `${id}-status-change`,
687
+ getSuccessKey: () => `success`,
688
+ getRemoveKey: (id) => `${id}remove`
689
+ };
690
+ var getFileManagerEvents = (emitter) => {
691
+ return {
692
+ emitFile: (id, file) => {
693
+ emitter.emit(keys.getFileKey(), id, file);
694
+ },
695
+ emitStatusChange: (file) => {
696
+ emitter.emit(keys.getStatusChangeKey(), file);
697
+ },
698
+ emitStatusChangeById: (id, status) => {
699
+ emitter.emit(keys.getStatusChangeByIdKey(id), status);
700
+ },
701
+ emitSuccess: () => {
702
+ emitter.emit(keys.getSuccessKey());
703
+ },
704
+ emitRemove: (id, file) => {
705
+ emitter.emit(keys.getRemoveKey(id), file);
706
+ },
707
+ onAdd: (callback) => {
708
+ emitter.on(keys.getFileKey(), callback);
709
+ return () => emitter.removeListener(keys.getFileKey(), callback);
710
+ },
711
+ onStatusChange: (callback) => {
712
+ emitter.on(keys.getStatusChangeKey(), callback);
713
+ return () => emitter.removeListener(keys.getStatusChangeKey(), callback);
714
+ },
715
+ onStatusChangeById: (id, callback) => {
716
+ emitter.on(keys.getStatusChangeByIdKey(id), callback);
717
+ return () => emitter.removeListener(keys.getStatusChangeByIdKey(id), callback);
718
+ },
719
+ onSuccess: (callback) => {
720
+ emitter.on(keys.getSuccessKey(), callback);
721
+ return () => emitter.removeListener(keys.getSuccessKey(), callback);
722
+ },
723
+ onRemove: (id, callback) => {
724
+ emitter.on(keys.getRemoveKey(id), callback);
725
+ return () => emitter.removeListener(keys.getRemoveKey(id), callback);
726
+ }
727
+ };
728
+ };
729
+
730
+ // src/managers/fileManager/FileManager.ts
731
+ var FileManager = class {
732
+ cache = /* @__PURE__ */ new Map();
733
+ emitter = new EventEmitter();
734
+ events = getFileManagerEvents(this.emitter);
735
+ constructor() {
736
+ this.events.onStatusChange(() => {
737
+ if (this.getCountByStatus("removed") === this.cache.size) {
738
+ this.events.emitSuccess();
739
+ }
740
+ });
741
+ }
742
+ getCache(id) {
743
+ return this.cache.get(id);
744
+ }
745
+ getCacheByPath(path2) {
746
+ let cache;
747
+ this.cache.forEach((item) => {
748
+ if (item.file.path === path2) {
749
+ cache = item;
750
+ }
751
+ });
752
+ return cache;
753
+ }
754
+ getCountByStatus(status) {
755
+ let count = 0;
756
+ this.cache.forEach((item) => {
757
+ if (item.status === status) {
758
+ count++;
759
+ }
760
+ });
761
+ return count;
762
+ }
763
+ get files() {
764
+ const files = [];
765
+ this.cache.forEach((item) => {
766
+ files.push(item.file);
767
+ });
768
+ return files;
769
+ }
770
+ add(file) {
771
+ const cacheItem = { id: v4(), file, status: "new" };
772
+ this.cache.set(cacheItem.id, cacheItem);
773
+ this.events.emitFile(cacheItem.id, file);
774
+ return new Promise((resolve) => {
775
+ const unsubscribe = this.events.onRemove(cacheItem.id, (file2) => {
776
+ resolve(file2);
777
+ unsubscribe();
778
+ });
779
+ });
780
+ }
781
+ addOrAppend(file) {
782
+ const previousCache = this.getCacheByPath(file.path);
783
+ if (previousCache) {
784
+ this.remove(previousCache.id);
785
+ return this.add({
786
+ ...file,
787
+ source: `${previousCache.file.source}
788
+ ${file.source}`
789
+ });
790
+ }
791
+ return this.add(file);
792
+ }
793
+ setStatus(id, status) {
794
+ const cacheItem = this.getCache(id);
795
+ if (!cacheItem) {
796
+ return;
797
+ }
798
+ cacheItem.status = status;
799
+ this.cache.set(id, cacheItem);
800
+ this.events.emitStatusChange(cacheItem.file);
801
+ this.events.emitStatusChangeById(id, status);
802
+ }
803
+ get(id) {
804
+ const cacheItem = this.getCache(id);
805
+ return cacheItem?.file;
806
+ }
807
+ remove(id) {
808
+ const cacheItem = this.getCache(id);
809
+ if (!cacheItem) {
810
+ return;
811
+ }
812
+ this.setStatus(id, "removed");
813
+ this.events.emitRemove(id, cacheItem.file);
814
+ }
815
+ async write(...params) {
816
+ return write(...params);
817
+ }
818
+ async read(...params) {
819
+ return read(...params);
820
+ }
821
+ };
822
+
823
+ // src/managers/fileManager/TreeNode.ts
824
+ init_esm_shims();
825
+ var TreeNode = class {
826
+ data;
827
+ parent;
828
+ children;
829
+ constructor(data, parent) {
830
+ this.data = data;
831
+ this.parent = parent;
832
+ return this;
833
+ }
834
+ addChild(data) {
835
+ const child = new TreeNode(data, this);
836
+ if (!this.children) {
837
+ this.children = [];
838
+ }
839
+ this.children.push(child);
840
+ return child;
841
+ }
842
+ find(data) {
843
+ if (data === this.data) {
844
+ return this;
845
+ }
846
+ if (this.children) {
847
+ for (let i = 0, { length } = this.children, target = null; i < length; i++) {
848
+ target = this.children[i].find(data);
849
+ if (target) {
850
+ return target;
851
+ }
852
+ }
853
+ }
854
+ return null;
855
+ }
856
+ leaves() {
857
+ if (!this.children || this.children.length === 0) {
858
+ return [this];
859
+ }
860
+ const leaves = [];
861
+ if (this.children) {
862
+ for (let i = 0, { length } = this.children; i < length; i++) {
863
+ leaves.push.apply(leaves, this.children[i].leaves());
864
+ }
865
+ }
866
+ return leaves;
867
+ }
868
+ root() {
869
+ if (!this.parent) {
870
+ return this;
871
+ }
872
+ return this.parent.root();
873
+ }
874
+ forEach(callback) {
875
+ if (typeof callback !== "function") {
876
+ throw new TypeError("forEach() callback must be a function");
877
+ }
878
+ callback(this);
879
+ if (this.children) {
880
+ for (let i = 0, { length } = this.children; i < length; i++) {
881
+ this.children[i].forEach(callback);
882
+ }
883
+ }
884
+ return this;
885
+ }
886
+ static build(path2, options = {}) {
887
+ const filteredTree = dirTree(path2, { extensions: options?.extensions, exclude: options.exclude });
888
+ if (!filteredTree) {
889
+ return;
890
+ }
891
+ const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type });
892
+ const recurse = (node, item) => {
893
+ const subNode = node.addChild({ name: item.name, path: item.path, type: item.type });
894
+ if (item.children?.length) {
895
+ item.children?.forEach((child) => {
896
+ recurse(subNode, child);
897
+ });
898
+ }
899
+ };
900
+ filteredTree.children?.forEach((child) => recurse(treeNode, child));
901
+ return treeNode;
902
+ }
903
+ };
904
+
905
+ // src/managers/pluginManager/PluginManager.ts
906
+ var hookNames = {
907
+ validate: 1,
908
+ buildStart: 1,
909
+ resolveId: 1,
910
+ load: 1,
911
+ transform: 1,
912
+ writeFile: 1,
913
+ buildEnd: 1
914
+ };
915
+ var hooks = Object.keys(hookNames);
916
+ var PluginManager = class {
917
+ plugins;
918
+ fileManager;
919
+ logger;
920
+ config;
921
+ core;
922
+ constructor(config, options) {
923
+ this.logger = options.logger;
924
+ this.config = config;
925
+ this.fileManager = new FileManager();
926
+ this.core = definePlugin({
927
+ config,
928
+ fileManager: this.fileManager,
929
+ load: this.load,
930
+ resolveId: this.resolveId
931
+ });
932
+ this.plugins = [this.core, ...config.plugins || []];
933
+ }
934
+ resolveId = (params) => {
935
+ if (params.pluginName) {
936
+ return this.hookForPlugin(params.pluginName, "resolveId", [params.fileName, params.directory, params.options]);
937
+ }
938
+ return this.hookFirst("resolveId", [params.fileName, params.directory, params.options]);
939
+ };
940
+ load = async (id) => {
941
+ return this.hookFirst("load", [id]);
942
+ };
943
+ hookForPlugin(pluginName, hookName, parameters, skipped) {
944
+ let promise = Promise.resolve(null);
945
+ for (const plugin of this.getSortedPlugins(hookName, pluginName)) {
946
+ if (skipped && skipped.has(plugin))
947
+ continue;
948
+ promise = promise.then((result) => {
949
+ if (result != null)
950
+ return result;
951
+ return this.run("hookFirst", hookName, parameters, plugin);
952
+ });
953
+ }
954
+ return promise;
955
+ }
956
+ hookFirst(hookName, parameters, skipped) {
957
+ let promise = Promise.resolve(null);
958
+ for (const plugin of this.getSortedPlugins(hookName)) {
959
+ if (skipped && skipped.has(plugin))
960
+ continue;
961
+ promise = promise.then((result) => {
962
+ if (result != null)
963
+ return result;
964
+ return this.run("hookFirst", hookName, parameters, plugin);
965
+ });
966
+ }
967
+ return promise;
968
+ }
969
+ async hookParallel(hookName, parameters) {
970
+ const parallelPromises = [];
971
+ for (const plugin of this.getSortedPlugins(hookName)) {
972
+ if (plugin[hookName]?.sequential) {
973
+ await Promise.all(parallelPromises);
974
+ parallelPromises.length = 0;
975
+ await this.run("hookParallel", hookName, parameters, plugin);
976
+ } else {
977
+ const promise = this.run("hookParallel", hookName, parameters, plugin);
978
+ parallelPromises.push(promise);
979
+ }
980
+ }
981
+ return Promise.all(parallelPromises);
982
+ }
983
+ hookReduceArg0(hookName, [argument0, ...rest], reduce) {
984
+ let promise = Promise.resolve(argument0);
985
+ for (const plugin of this.getSortedPlugins(hookName)) {
986
+ promise = promise.then(
987
+ (argument02) => this.run("hookReduceArg0", hookName, [argument02, ...rest], plugin).then(
988
+ (result) => reduce.call(this.core.api, argument02, result, plugin)
989
+ )
990
+ );
991
+ }
992
+ return promise;
993
+ }
994
+ hookSeq(hookName, parameters) {
995
+ let promise = Promise.resolve();
996
+ for (const plugin of this.getSortedPlugins(hookName)) {
997
+ promise = promise.then(() => this.run("hookSeq", hookName, parameters, plugin));
998
+ }
999
+ return promise.then(noReturn);
1000
+ }
1001
+ getSortedPlugins(hookName, pluginName) {
1002
+ const plugins = [...this.plugins];
1003
+ if (pluginName) {
1004
+ const pluginsByPluginName = plugins.filter((item) => item.name === pluginName && item[hookName]);
1005
+ if (pluginsByPluginName.length === 0) {
1006
+ if (this.config.logLevel === "warn" && this.logger?.spinner) {
1007
+ this.logger.spinner.info(`Plugin hook with ${hookName} not found for plugin ${pluginName}`);
1008
+ }
1009
+ return [this.core];
1010
+ }
1011
+ return pluginsByPluginName;
1012
+ }
1013
+ return plugins;
1014
+ }
1015
+ run(strategy, hookName, parameters, plugin) {
1016
+ const hook = plugin[hookName];
1017
+ return Promise.resolve().then(() => {
1018
+ if (typeof hook !== "function") {
1019
+ return hook;
1020
+ }
1021
+ if (this.config.logLevel === "info" && this.logger?.spinner) {
1022
+ this.logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name}
1023
+ `;
1024
+ }
1025
+ const hookResult = hook.apply(this.core.api, parameters);
1026
+ if (!hookResult?.then) {
1027
+ if (this.config.logLevel === "info" && this.logger?.spinner) {
1028
+ this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name}
1029
+ `);
1030
+ }
1031
+ return hookResult;
1032
+ }
1033
+ return Promise.resolve(hookResult).then((result) => {
1034
+ if (this.config.logLevel === "info" && this.logger?.spinner) {
1035
+ this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name}
1036
+ `);
1037
+ }
1038
+ return result;
1039
+ });
1040
+ }).catch((e) => this.catcher(e, plugin, hookName));
1041
+ }
1042
+ runSync(hookName, parameters, plugin) {
1043
+ const hook = plugin[hookName];
1044
+ try {
1045
+ return hook.apply(this.core.api, parameters);
1046
+ } catch (error) {
1047
+ return error;
1048
+ }
1049
+ }
1050
+ catcher(e, plugin, hookName) {
1051
+ const text = `${e.message} (plugin: ${plugin.name}, hook: ${hookName})
1052
+ `;
1053
+ if (this.logger?.spinner) {
1054
+ this.logger.spinner.fail(text);
1055
+ throw e;
1056
+ }
1057
+ }
1058
+ };
1059
+ function noReturn() {
1060
+ }
1061
+
1062
+ // src/managers/pluginManager/validate.ts
1063
+ init_esm_shims();
1064
+ var ValidationPluginError = class extends Error {
1065
+ };
1066
+ var validatePlugins = (plugins, dependedPluginNames) => {
1067
+ let pluginNames = [];
1068
+ if (typeof dependedPluginNames === "string") {
1069
+ pluginNames = [dependedPluginNames];
1070
+ } else {
1071
+ pluginNames = dependedPluginNames;
1072
+ }
1073
+ pluginNames.forEach((pluginName) => {
1074
+ const exists = plugins.some((plugin) => plugin.name === pluginName);
1075
+ if (!exists) {
1076
+ throw new ValidationPluginError(`This plugin depends on the ${pluginName} plugin.`);
1077
+ }
1078
+ });
1079
+ return true;
1080
+ };
1081
+
1082
+ // src/build.ts
1083
+ async function transformReducer(_previousCode, result, _plugin) {
1084
+ if (result === null) {
1085
+ return null;
1086
+ }
1087
+ return result;
1088
+ }
1089
+ async function buildImplementation(options, done) {
1090
+ const { config, logger } = options;
1091
+ if (config.output.clean) {
1092
+ await clean(config.output.path);
1093
+ }
1094
+ const pluginManager = new PluginManager(config, { logger });
1095
+ const { plugins, fileManager } = pluginManager;
1096
+ try {
1097
+ await pluginManager.hookParallel("validate", [plugins]);
1098
+ } catch (e) {
1099
+ return;
1100
+ }
1101
+ fileManager.events.onSuccess(async () => {
1102
+ await pluginManager.hookParallel("buildEnd");
1103
+ setTimeout(() => {
1104
+ done({ fileManager });
1105
+ }, 1e3);
1106
+ });
1107
+ fileManager.events.onAdd(async (id, file) => {
1108
+ const { path: path2 } = file;
1109
+ let { source: code } = file;
1110
+ const loadedResult = await pluginManager.hookFirst("load", [path2]);
1111
+ if (loadedResult) {
1112
+ code = loadedResult;
1113
+ }
1114
+ if (code) {
1115
+ const transformedCode = await pluginManager.hookReduceArg0("transform", [code, path2], transformReducer);
1116
+ if (typeof config.input === "object") {
1117
+ await pluginManager.hookParallel("writeFile", [transformedCode, path2]);
1118
+ }
1119
+ fileManager.setStatus(id, "success");
1120
+ fileManager.remove(id);
1121
+ }
1122
+ });
1123
+ await pluginManager.hookParallel("buildStart", [config]);
1124
+ }
1125
+ function build(options) {
1126
+ return new Promise((resolve, reject) => {
1127
+ try {
1128
+ buildImplementation(options, resolve);
1129
+ } catch (e) {
1130
+ reject(e);
1131
+ }
1132
+ });
1133
+ }
1134
+
1135
+ // src/config.ts
1136
+ init_esm_shims();
1137
+ var defineConfig = (options) => options;
1138
+
1139
+ // src/generators/SchemaGenerator.ts
1140
+ init_esm_shims();
1141
+
1142
+ // src/generators/Generator.ts
1143
+ init_esm_shims();
1144
+ var Generator = class {
1145
+ _options = {};
1146
+ constructor(options = {}) {
1147
+ if (options) {
1148
+ this._options = {
1149
+ ...this._options,
1150
+ ...options
1151
+ };
1152
+ }
1153
+ return this;
1154
+ }
1155
+ get options() {
1156
+ return this._options;
1157
+ }
1158
+ };
1159
+
1160
+ // src/generators/SchemaGenerator.ts
1161
+ var SchemaGenerator = class extends Generator {
1162
+ };
1163
+
1164
+ // src/index.ts
1165
+ var src_default = build;
1166
+
624
1167
  export { FileManager, Generator, PluginManager, SchemaGenerator, TreeNode, ValidationPluginError, build, clean, createPlugin, createPluginCache, src_default as default, defineConfig, format, getPathMode, getRelativePath, hooks, isPromise, read, validatePlugins, write };
625
1168
  //# sourceMappingURL=out.js.map
626
1169
  //# sourceMappingURL=index.mjs.map