@kubb/core 1.2.3 → 1.3.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.cjs CHANGED
@@ -14,6 +14,7 @@ var url = require('url');
14
14
  var pc3 = require('picocolors');
15
15
  var seedrandom = require('seedrandom');
16
16
  var tsCodegen = require('@kubb/ts-codegen');
17
+ var events = require('events');
17
18
 
18
19
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
19
20
 
@@ -109,19 +110,6 @@ function getPathMode(path) {
109
110
  async function read(path) {
110
111
  return fs__default.default.readFile(path, { encoding: "utf8" });
111
112
  }
112
-
113
- // src/utils/isURL.ts
114
- function isURL(data) {
115
- try {
116
- const url = new URL(data);
117
- if (url?.href) {
118
- return true;
119
- }
120
- } catch (error) {
121
- return false;
122
- }
123
- return false;
124
- }
125
113
  function objectToParameters(data, options = {}) {
126
114
  const { typed } = options;
127
115
  return data.reduce((acc, [key, value]) => {
@@ -188,13 +176,30 @@ var Queue = class {
188
176
  this.maxParallel = maxParallel;
189
177
  this.debug = debug;
190
178
  }
191
- run(task, options = { name: crypto__default.default.randomUUID(), description: "" }) {
179
+ run(job, options = { controller: new AbortController(), name: crypto__default.default.randomUUID(), description: "" }) {
192
180
  return new Promise((resolve, reject) => {
193
- const item = { reject, resolve, task, name: options.name, description: options.description || options.name };
181
+ const item = { reject, resolve, job, name: options.name, description: options.description || options.name };
182
+ options.controller?.signal.addEventListener("abort", () => {
183
+ this.queue = this.queue.filter((queueItem) => queueItem.name === item.name);
184
+ reject("Aborted");
185
+ });
194
186
  this.queue.push(item);
195
187
  this.work();
196
188
  });
197
189
  }
190
+ runSync(job, options = { controller: new AbortController(), name: crypto__default.default.randomUUID(), description: "" }) {
191
+ new Promise((resolve, reject) => {
192
+ const item = { reject, resolve, job, name: options.name, description: options.description || options.name };
193
+ options.controller?.signal.addEventListener("abort", () => {
194
+ this.queue = this.queue.filter((queueItem) => queueItem.name === item.name);
195
+ });
196
+ this.queue.push(item);
197
+ this.work();
198
+ });
199
+ }
200
+ get hasJobs() {
201
+ return this.workerCount > 0 || this.queue.length > 0;
202
+ }
198
203
  work() {
199
204
  if (this.workerCount >= this.maxParallel) {
200
205
  return;
@@ -202,11 +207,11 @@ var Queue = class {
202
207
  this.workerCount++;
203
208
  let entry;
204
209
  while (entry = this.queue.shift()) {
205
- const { reject, resolve, task, name, description } = entry;
210
+ const { reject, resolve, job, name, description } = entry;
206
211
  if (this.debug) {
207
212
  perf_hooks.performance.mark(name + "_start");
208
213
  }
209
- task().then((result) => {
214
+ job().then((result) => {
210
215
  resolve(result);
211
216
  if (this.debug) {
212
217
  perf_hooks.performance.mark(name + "_stop");
@@ -411,7 +416,7 @@ var reservedWords = [
411
416
  "valueOf"
412
417
  ];
413
418
  function transformReservedWord(word) {
414
- if (word && reservedWords.includes(word)) {
419
+ if (word && reservedWords.includes(word) || word?.match(/^\d/)) {
415
420
  return `_${word}`;
416
421
  }
417
422
  return word;
@@ -579,6 +584,9 @@ var URLPath = class {
579
584
  get URL() {
580
585
  return this.toURLPath();
581
586
  }
587
+ get isUrl() {
588
+ return URLPath.isURL(this.path);
589
+ }
582
590
  /**
583
591
  * Convert Swagger path to template literals/ template strings(camelcase)
584
592
  * @example /pet/{petId} => `/pet/${petId}`
@@ -625,8 +633,19 @@ var URLPath = class {
625
633
  static toURLPath(path) {
626
634
  return path.replaceAll("{", ":").replaceAll("}", "");
627
635
  }
636
+ static isURL(path) {
637
+ try {
638
+ const url = new URL(path);
639
+ if (url?.href) {
640
+ return true;
641
+ }
642
+ } catch (error) {
643
+ return false;
644
+ }
645
+ return false;
646
+ }
628
647
  };
629
- function writeIndexes(root, options = {}) {
648
+ function getIndexes(root, options = {}) {
630
649
  const tree = TreeNode.build(root, { extensions: /\.ts/, ...options });
631
650
  if (!tree) {
632
651
  return null;
@@ -812,13 +831,24 @@ var FileManager = class {
812
831
  });
813
832
  return files;
814
833
  }
834
+ get isExecuting() {
835
+ return this.queue?.hasJobs ?? false;
836
+ }
815
837
  async add(file) {
838
+ const controller = new AbortController();
816
839
  const resolvedFile = { id: crypto__default.default.randomUUID(), ...file };
817
- this.cache.set(resolvedFile.path, [resolvedFile]);
840
+ this.cache.set(resolvedFile.path, [{ cancel: () => controller.abort(), ...resolvedFile }]);
818
841
  if (this.queue) {
819
- await this.queue.run(async () => {
820
- await this.task?.(resolvedFile);
821
- });
842
+ try {
843
+ await this.queue.run(
844
+ async () => {
845
+ return this.task?.(resolvedFile);
846
+ },
847
+ { controller }
848
+ );
849
+ } catch {
850
+ return resolvedFile;
851
+ }
822
852
  }
823
853
  return resolvedFile;
824
854
  }
@@ -830,6 +860,7 @@ var FileManager = class {
830
860
  if (sourceAlreadyExists) {
831
861
  return Promise.resolve(previousCache);
832
862
  }
863
+ previousCache.cancel?.();
833
864
  this.cache.delete(previousCache.path);
834
865
  return this.add({
835
866
  ...file,
@@ -896,7 +927,7 @@ function createPlugin(factory) {
896
927
  }
897
928
  var pluginName = "core";
898
929
  var definePlugin = createPlugin((options) => {
899
- const { fileManager, resolvePath, resolveName, load, logger } = options;
930
+ const { fileManager, resolvePath, resolveName, logger } = options;
900
931
  return {
901
932
  name: pluginName,
902
933
  options,
@@ -940,7 +971,6 @@ var definePlugin = createPlugin((options) => {
940
971
  const name = resolveName(params);
941
972
  return transformReservedWord(name);
942
973
  },
943
- load,
944
974
  cache: createPluginCache()
945
975
  };
946
976
  },
@@ -965,6 +995,9 @@ var ParallelPluginError = class extends Error {
965
995
  this.pluginManager = options.pluginManager;
966
996
  }
967
997
  findError(searchError) {
998
+ if (!searchError) {
999
+ return void 0;
1000
+ }
968
1001
  return this.errors.find((error) => {
969
1002
  if (error.cause) {
970
1003
  if (error.cause.name == searchError.name) {
@@ -988,6 +1021,30 @@ var PluginError = class extends Error {
988
1021
  this.pluginManager = options.pluginManager;
989
1022
  }
990
1023
  };
1024
+ var EventEmitter = class {
1025
+ emitter = new events.EventEmitter();
1026
+ emit(eventName, ...eventArg) {
1027
+ this.emitter.emit(eventName, ...eventArg);
1028
+ }
1029
+ on(eventName, handler) {
1030
+ this.emitter.on(eventName, handler);
1031
+ }
1032
+ off(eventName, handler) {
1033
+ this.emitter.off(eventName, handler);
1034
+ }
1035
+ };
1036
+
1037
+ // src/managers/pluginManager/pluginParser.ts
1038
+ function pluginParser(plugin, context) {
1039
+ if (plugin.api && typeof plugin.api === "function") {
1040
+ const api = plugin.api.call(context);
1041
+ return {
1042
+ ...plugin,
1043
+ api
1044
+ };
1045
+ }
1046
+ return null;
1047
+ }
991
1048
 
992
1049
  // src/managers/pluginManager/PluginManager.ts
993
1050
  var hookNames = {
@@ -1001,41 +1058,28 @@ var hookNames = {
1001
1058
  buildEnd: 1
1002
1059
  };
1003
1060
  var hooks = Object.keys(hookNames);
1004
- var convertKubbUserPluginToKubbPlugin = (plugin, context) => {
1005
- if (plugin.api && typeof plugin.api === "function") {
1006
- const api = plugin.api.call(context);
1007
- return {
1008
- ...plugin,
1009
- api
1010
- };
1011
- }
1012
- return null;
1013
- };
1014
1061
  var PluginManager = class {
1015
1062
  plugins;
1016
1063
  fileManager;
1017
- onExecute;
1018
1064
  core;
1019
1065
  queue;
1020
1066
  executed = [];
1021
1067
  logger;
1068
+ eventEmitter = new EventEmitter();
1022
1069
  constructor(config, options) {
1023
- this.onExecute = options.onExecute?.bind(this);
1024
1070
  this.logger = options.logger;
1025
- this.queue = new Queue(100, options.debug);
1071
+ this.queue = new Queue(50, options.debug);
1026
1072
  this.fileManager = new FileManager({ task: options.task, queue: this.queue });
1027
1073
  const core = definePlugin({
1028
1074
  config,
1029
1075
  logger: this.logger,
1030
1076
  fileManager: this.fileManager,
1031
- load: this.load,
1032
1077
  resolvePath: this.resolvePath,
1033
1078
  resolveName: this.resolveName
1034
1079
  });
1035
- const convertedCore = convertKubbUserPluginToKubbPlugin(core, core.api.call(null));
1036
- this.core = convertedCore;
1080
+ this.core = pluginParser(core, core.api.call(null));
1037
1081
  this.plugins = [this.core, ...config.plugins || []].reduce((prev, plugin) => {
1038
- const convertedApi = convertKubbUserPluginToKubbPlugin(plugin, convertedCore?.api);
1082
+ const convertedApi = pluginParser(plugin, this.core?.api);
1039
1083
  if (convertedApi) {
1040
1084
  return [...prev, convertedApi];
1041
1085
  }
@@ -1068,12 +1112,9 @@ var PluginManager = class {
1068
1112
  parameters: [params.name]
1069
1113
  }).result;
1070
1114
  };
1071
- load = async (id) => {
1072
- return this.hookFirst({
1073
- hookName: "load",
1074
- parameters: [id]
1075
- });
1076
- };
1115
+ on(eventName, handler) {
1116
+ this.eventEmitter.on(eventName, handler);
1117
+ }
1077
1118
  /**
1078
1119
  *
1079
1120
  * Run only hook for a specific plugin name
@@ -1246,8 +1287,8 @@ var PluginManager = class {
1246
1287
  return pluginByPluginName;
1247
1288
  }
1248
1289
  addExecutedToCallStack(executer) {
1249
- this.onExecute?.call(this, executer, this);
1250
1290
  if (executer) {
1291
+ this.eventEmitter.emit("execute", executer);
1251
1292
  this.executed.push(executer);
1252
1293
  }
1253
1294
  }
@@ -1269,6 +1310,7 @@ var PluginManager = class {
1269
1310
  if (!hook) {
1270
1311
  return null;
1271
1312
  }
1313
+ this.eventEmitter.emit("execute", { strategy, hookName, parameters, plugin });
1272
1314
  const task = Promise.resolve().then(() => {
1273
1315
  if (typeof hook === "function") {
1274
1316
  const possiblePromiseResult = hook.apply(this.core.api, parameters);
@@ -1286,7 +1328,7 @@ var PluginManager = class {
1286
1328
  return null;
1287
1329
  }).finally(() => {
1288
1330
  this.addExecutedToCallStack({
1289
- input: parameters,
1331
+ parameters,
1290
1332
  output,
1291
1333
  strategy,
1292
1334
  hookName,
@@ -1313,6 +1355,7 @@ var PluginManager = class {
1313
1355
  if (!hook) {
1314
1356
  return null;
1315
1357
  }
1358
+ this.eventEmitter.emit("execute", { strategy, hookName, parameters, plugin });
1316
1359
  try {
1317
1360
  if (typeof hook === "function") {
1318
1361
  const fn = hook.apply(this.core.api, parameters);
@@ -1326,7 +1369,7 @@ var PluginManager = class {
1326
1369
  return null;
1327
1370
  } finally {
1328
1371
  this.addExecutedToCallStack({
1329
- input: parameters,
1372
+ parameters,
1330
1373
  output,
1331
1374
  strategy,
1332
1375
  hookName,
@@ -1337,7 +1380,9 @@ var PluginManager = class {
1337
1380
  catcher(e, plugin, hookName) {
1338
1381
  const text = `${e.message} (plugin: ${plugin.name}, hook: ${hookName})
1339
1382
  `;
1340
- throw new PluginError(text, { cause: e, pluginManager: this });
1383
+ const pluginError = new PluginError(text, { cause: e, pluginManager: this });
1384
+ this.eventEmitter.emit("error", pluginError);
1385
+ throw pluginError;
1341
1386
  }
1342
1387
  };
1343
1388
  function noReturn() {
@@ -1376,7 +1421,7 @@ async function transformReducer(_previousCode, result, _plugin) {
1376
1421
  async function build(options) {
1377
1422
  const { config, debug, logger = createLogger() } = options;
1378
1423
  try {
1379
- if (!isURL(config.input.path)) {
1424
+ if (!URLPath.isURL(config.input.path)) {
1380
1425
  await read(config.input.path);
1381
1426
  }
1382
1427
  } catch (e) {
@@ -1417,32 +1462,29 @@ async function build(options) {
1417
1462
  }
1418
1463
  }
1419
1464
  };
1420
- const onExecute = (executer) => {
1421
- if (!executer) {
1422
- return;
1423
- }
1424
- const { hookName, plugin, output, input } = executer;
1465
+ const pluginManager = new PluginManager(config, { debug, logger, task: queueTask });
1466
+ const { plugins, fileManager } = pluginManager;
1467
+ pluginManager.on("execute", (executer) => {
1468
+ const { hookName, plugin, output, parameters } = executer;
1425
1469
  const messsage = `${randomPicoColour(plugin.name)} Executing ${hookName}`;
1426
- if (config.logLevel === LogLevel.info && logger?.spinner && input) {
1470
+ if (config.logLevel === LogLevel.info && logger?.spinner && parameters) {
1427
1471
  if (debug) {
1428
1472
  logger.info(messsage);
1429
1473
  } else {
1430
1474
  logger.spinner.suffixText = messsage;
1431
1475
  }
1432
1476
  }
1433
- if (config.logLevel === LogLevel.stacktrace && logger?.spinner && input) {
1477
+ if (config.logLevel === LogLevel.stacktrace && logger?.spinner && parameters) {
1434
1478
  logger.info(messsage);
1435
1479
  const logs = [
1436
- input && `${pc3__default.default.bgWhite(`Input`)} ${randomPicoColour(plugin.name)} ${hookName}`,
1437
- JSON.stringify(input, void 0, 2),
1480
+ parameters && `${pc3__default.default.bgWhite(`Parameters`)} ${randomPicoColour(plugin.name)} ${hookName}`,
1481
+ JSON.stringify(parameters, void 0, 2),
1438
1482
  output && `${pc3__default.default.bgWhite("Output")} ${randomPicoColour(plugin.name)} ${hookName}`,
1439
1483
  output
1440
1484
  ].filter(Boolean);
1441
1485
  console.log(logs.join("\n"));
1442
1486
  }
1443
- };
1444
- const pluginManager = new PluginManager(config, { debug, logger, task: queueTask, onExecute });
1445
- const { plugins, fileManager } = pluginManager;
1487
+ });
1446
1488
  await pluginManager.hookParallel({
1447
1489
  hookName: "validate",
1448
1490
  parameters: [plugins]
@@ -1515,6 +1557,7 @@ exports.defineConfig = defineConfig;
1515
1557
  exports.extensions = extensions;
1516
1558
  exports.getEncodedText = getEncodedText;
1517
1559
  exports.getFileSource = getFileSource;
1560
+ exports.getIndexes = getIndexes;
1518
1561
  exports.getLocation = getLocation;
1519
1562
  exports.getPathMode = getPathMode;
1520
1563
  exports.getRelativePath = getRelativePath;
@@ -1525,7 +1568,6 @@ exports.importModule = importModule;
1525
1568
  exports.isPromise = isPromise;
1526
1569
  exports.isPromiseFulfilledResult = isPromiseFulfilledResult;
1527
1570
  exports.isPromiseRejectedResult = isPromiseRejectedResult;
1528
- exports.isURL = isURL;
1529
1571
  exports.name = pluginName;
1530
1572
  exports.nameSorter = nameSorter;
1531
1573
  exports.normalizeDirectory = normalizeDirectory;
@@ -1541,6 +1583,5 @@ exports.transformReservedWord = transformReservedWord;
1541
1583
  exports.uniqueId = uniqueId;
1542
1584
  exports.validatePlugins = validatePlugins;
1543
1585
  exports.write = write;
1544
- exports.writeIndexes = writeIndexes;
1545
1586
  //# sourceMappingURL=out.js.map
1546
1587
  //# sourceMappingURL=index.cjs.map