@kubb/core 1.2.2 → 1.2.4

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]) => {
@@ -411,7 +399,7 @@ var reservedWords = [
411
399
  "valueOf"
412
400
  ];
413
401
  function transformReservedWord(word) {
414
- if (word && reservedWords.includes(word)) {
402
+ if (word && reservedWords.includes(word) || word?.match(/^\d/)) {
415
403
  return `_${word}`;
416
404
  }
417
405
  return word;
@@ -567,6 +555,79 @@ function randomPicoColour(text, colors = defaultColours) {
567
555
  }
568
556
  return formatter(text);
569
557
  }
558
+ var URLPath = class {
559
+ path;
560
+ constructor(path) {
561
+ this.path = path;
562
+ }
563
+ /**
564
+ * Convert Swagger path to URLPath(syntax of Express)
565
+ * @example /pet/{petId} => /pet/:petId
566
+ */
567
+ get URL() {
568
+ return this.toURLPath();
569
+ }
570
+ get isUrl() {
571
+ return URLPath.isURL(this.path);
572
+ }
573
+ /**
574
+ * Convert Swagger path to template literals/ template strings(camelcase)
575
+ * @example /pet/{petId} => `/pet/${petId}`
576
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
577
+ * @example /account/userID => `/account/${userId}`
578
+ */
579
+ get template() {
580
+ return this.toTemplateString();
581
+ }
582
+ /**
583
+ * Convert Swagger path to template literals/ template strings(camelcase)
584
+ * @example /pet/{petId} => `/pet/${petId}`
585
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
586
+ * @example /account/userID => `/account/${userId}`
587
+ */
588
+ toTemplateString() {
589
+ return URLPath.toTemplateString(this.path);
590
+ }
591
+ /**
592
+ * Convert Swagger path to template literals/ template strings(camelcase)
593
+ * @example /pet/{petId} => `/pet/${petId}`
594
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
595
+ * @example /account/userID => `/account/${userId}`
596
+ */
597
+ static toTemplateString(path) {
598
+ const regex = /{(\w|-)*}/g;
599
+ const found = path.match(regex);
600
+ let newPath = path.replaceAll("{", "${");
601
+ if (found) {
602
+ newPath = found.reduce((prev, curr) => {
603
+ const replacement = `\${${changeCase.camelCase(curr, { delimiter: "", transform: changeCase.camelCaseTransformMerge })}}`;
604
+ return prev.replace(curr, replacement);
605
+ }, path);
606
+ }
607
+ return `\`${newPath}\``;
608
+ }
609
+ /**
610
+ * Convert Swagger path to URLPath(syntax of Express)
611
+ * @example /pet/{petId} => /pet/:petId
612
+ */
613
+ toURLPath() {
614
+ return URLPath.toURLPath(this.path);
615
+ }
616
+ static toURLPath(path) {
617
+ return path.replaceAll("{", ":").replaceAll("}", "");
618
+ }
619
+ static isURL(path) {
620
+ try {
621
+ const url = new URL(path);
622
+ if (url?.href) {
623
+ return true;
624
+ }
625
+ } catch (error) {
626
+ return false;
627
+ }
628
+ return false;
629
+ }
630
+ };
570
631
  function writeIndexes(root, options = {}) {
571
632
  const tree = TreeNode.build(root, { extensions: /\.ts/, ...options });
572
633
  if (!tree) {
@@ -837,7 +898,7 @@ function createPlugin(factory) {
837
898
  }
838
899
  var pluginName = "core";
839
900
  var definePlugin = createPlugin((options) => {
840
- const { fileManager, resolvePath, resolveName, load, logger } = options;
901
+ const { fileManager, resolvePath, resolveName, logger } = options;
841
902
  return {
842
903
  name: pluginName,
843
904
  options,
@@ -881,7 +942,6 @@ var definePlugin = createPlugin((options) => {
881
942
  const name = resolveName(params);
882
943
  return transformReservedWord(name);
883
944
  },
884
- load,
885
945
  cache: createPluginCache()
886
946
  };
887
947
  },
@@ -906,6 +966,9 @@ var ParallelPluginError = class extends Error {
906
966
  this.pluginManager = options.pluginManager;
907
967
  }
908
968
  findError(searchError) {
969
+ if (!searchError) {
970
+ return void 0;
971
+ }
909
972
  return this.errors.find((error) => {
910
973
  if (error.cause) {
911
974
  if (error.cause.name == searchError.name) {
@@ -929,6 +992,30 @@ var PluginError = class extends Error {
929
992
  this.pluginManager = options.pluginManager;
930
993
  }
931
994
  };
995
+ var EventEmitter = class {
996
+ emitter = new events.EventEmitter();
997
+ emit(eventName, ...eventArg) {
998
+ this.emitter.emit(eventName, ...eventArg);
999
+ }
1000
+ on(eventName, handler) {
1001
+ this.emitter.on(eventName, handler);
1002
+ }
1003
+ off(eventName, handler) {
1004
+ this.emitter.off(eventName, handler);
1005
+ }
1006
+ };
1007
+
1008
+ // src/managers/pluginManager/pluginParser.ts
1009
+ function pluginParser(plugin, context) {
1010
+ if (plugin.api && typeof plugin.api === "function") {
1011
+ const api = plugin.api.call(context);
1012
+ return {
1013
+ ...plugin,
1014
+ api
1015
+ };
1016
+ }
1017
+ return null;
1018
+ }
932
1019
 
933
1020
  // src/managers/pluginManager/PluginManager.ts
934
1021
  var hookNames = {
@@ -942,26 +1029,15 @@ var hookNames = {
942
1029
  buildEnd: 1
943
1030
  };
944
1031
  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
- };
955
1032
  var PluginManager = class {
956
1033
  plugins;
957
1034
  fileManager;
958
- onExecute;
959
1035
  core;
960
1036
  queue;
961
1037
  executed = [];
962
1038
  logger;
1039
+ eventEmitter = new EventEmitter();
963
1040
  constructor(config, options) {
964
- this.onExecute = options.onExecute?.bind(this);
965
1041
  this.logger = options.logger;
966
1042
  this.queue = new Queue(100, options.debug);
967
1043
  this.fileManager = new FileManager({ task: options.task, queue: this.queue });
@@ -969,14 +1045,12 @@ var PluginManager = class {
969
1045
  config,
970
1046
  logger: this.logger,
971
1047
  fileManager: this.fileManager,
972
- load: this.load,
973
1048
  resolvePath: this.resolvePath,
974
1049
  resolveName: this.resolveName
975
1050
  });
976
- const convertedCore = convertKubbUserPluginToKubbPlugin(core, core.api.call(null));
977
- this.core = convertedCore;
1051
+ this.core = pluginParser(core, core.api.call(null));
978
1052
  this.plugins = [this.core, ...config.plugins || []].reduce((prev, plugin) => {
979
- const convertedApi = convertKubbUserPluginToKubbPlugin(plugin, convertedCore?.api);
1053
+ const convertedApi = pluginParser(plugin, this.core?.api);
980
1054
  if (convertedApi) {
981
1055
  return [...prev, convertedApi];
982
1056
  }
@@ -1009,12 +1083,9 @@ var PluginManager = class {
1009
1083
  parameters: [params.name]
1010
1084
  }).result;
1011
1085
  };
1012
- load = async (id) => {
1013
- return this.hookFirst({
1014
- hookName: "load",
1015
- parameters: [id]
1016
- });
1017
- };
1086
+ on(eventName, handler) {
1087
+ this.eventEmitter.on(eventName, handler);
1088
+ }
1018
1089
  /**
1019
1090
  *
1020
1091
  * Run only hook for a specific plugin name
@@ -1187,8 +1258,8 @@ var PluginManager = class {
1187
1258
  return pluginByPluginName;
1188
1259
  }
1189
1260
  addExecutedToCallStack(executer) {
1190
- this.onExecute?.call(this, executer, this);
1191
1261
  if (executer) {
1262
+ this.eventEmitter.emit("execute", executer);
1192
1263
  this.executed.push(executer);
1193
1264
  }
1194
1265
  }
@@ -1210,6 +1281,7 @@ var PluginManager = class {
1210
1281
  if (!hook) {
1211
1282
  return null;
1212
1283
  }
1284
+ this.eventEmitter.emit("execute", { strategy, hookName, parameters, plugin });
1213
1285
  const task = Promise.resolve().then(() => {
1214
1286
  if (typeof hook === "function") {
1215
1287
  const possiblePromiseResult = hook.apply(this.core.api, parameters);
@@ -1227,7 +1299,7 @@ var PluginManager = class {
1227
1299
  return null;
1228
1300
  }).finally(() => {
1229
1301
  this.addExecutedToCallStack({
1230
- input: parameters,
1302
+ parameters,
1231
1303
  output,
1232
1304
  strategy,
1233
1305
  hookName,
@@ -1254,6 +1326,7 @@ var PluginManager = class {
1254
1326
  if (!hook) {
1255
1327
  return null;
1256
1328
  }
1329
+ this.eventEmitter.emit("execute", { strategy, hookName, parameters, plugin });
1257
1330
  try {
1258
1331
  if (typeof hook === "function") {
1259
1332
  const fn = hook.apply(this.core.api, parameters);
@@ -1267,7 +1340,7 @@ var PluginManager = class {
1267
1340
  return null;
1268
1341
  } finally {
1269
1342
  this.addExecutedToCallStack({
1270
- input: parameters,
1343
+ parameters,
1271
1344
  output,
1272
1345
  strategy,
1273
1346
  hookName,
@@ -1278,7 +1351,9 @@ var PluginManager = class {
1278
1351
  catcher(e, plugin, hookName) {
1279
1352
  const text = `${e.message} (plugin: ${plugin.name}, hook: ${hookName})
1280
1353
  `;
1281
- throw new PluginError(text, { cause: e, pluginManager: this });
1354
+ const pluginError = new PluginError(text, { cause: e, pluginManager: this });
1355
+ this.eventEmitter.emit("error", pluginError);
1356
+ throw pluginError;
1282
1357
  }
1283
1358
  };
1284
1359
  function noReturn() {
@@ -1317,7 +1392,7 @@ async function transformReducer(_previousCode, result, _plugin) {
1317
1392
  async function build(options) {
1318
1393
  const { config, debug, logger = createLogger() } = options;
1319
1394
  try {
1320
- if (!isURL(config.input.path)) {
1395
+ if (!URLPath.isURL(config.input.path)) {
1321
1396
  await read(config.input.path);
1322
1397
  }
1323
1398
  } catch (e) {
@@ -1358,32 +1433,29 @@ async function build(options) {
1358
1433
  }
1359
1434
  }
1360
1435
  };
1361
- const onExecute = (executer) => {
1362
- if (!executer) {
1363
- return;
1364
- }
1365
- const { hookName, plugin, output, input } = executer;
1436
+ const pluginManager = new PluginManager(config, { debug, logger, task: queueTask });
1437
+ const { plugins, fileManager } = pluginManager;
1438
+ pluginManager.on("execute", (executer) => {
1439
+ const { hookName, plugin, output, parameters } = executer;
1366
1440
  const messsage = `${randomPicoColour(plugin.name)} Executing ${hookName}`;
1367
- if (config.logLevel === LogLevel.info && logger?.spinner && input) {
1441
+ if (config.logLevel === LogLevel.info && logger?.spinner && parameters) {
1368
1442
  if (debug) {
1369
1443
  logger.info(messsage);
1370
1444
  } else {
1371
1445
  logger.spinner.suffixText = messsage;
1372
1446
  }
1373
1447
  }
1374
- if (config.logLevel === LogLevel.stacktrace && logger?.spinner && input) {
1448
+ if (config.logLevel === LogLevel.stacktrace && logger?.spinner && parameters) {
1375
1449
  logger.info(messsage);
1376
1450
  const logs = [
1377
- input && `${pc3__default.default.bgWhite(`Input`)} ${randomPicoColour(plugin.name)} ${hookName}`,
1378
- JSON.stringify(input, void 0, 2),
1451
+ parameters && `${pc3__default.default.bgWhite(`Parameters`)} ${randomPicoColour(plugin.name)} ${hookName}`,
1452
+ JSON.stringify(parameters, void 0, 2),
1379
1453
  output && `${pc3__default.default.bgWhite("Output")} ${randomPicoColour(plugin.name)} ${hookName}`,
1380
1454
  output
1381
1455
  ].filter(Boolean);
1382
1456
  console.log(logs.join("\n"));
1383
1457
  }
1384
- };
1385
- const pluginManager = new PluginManager(config, { debug, logger, task: queueTask, onExecute });
1386
- const { plugins, fileManager } = pluginManager;
1458
+ });
1387
1459
  await pluginManager.hookParallel({
1388
1460
  hookName: "validate",
1389
1461
  parameters: [plugins]
@@ -1439,6 +1511,7 @@ exports.Queue = Queue;
1439
1511
  exports.SchemaGenerator = SchemaGenerator;
1440
1512
  exports.SummaryError = SummaryError;
1441
1513
  exports.TreeNode = TreeNode;
1514
+ exports.URLPath = URLPath;
1442
1515
  exports.ValidationPluginError = ValidationPluginError;
1443
1516
  exports.Warning = Warning;
1444
1517
  exports.build = build;
@@ -1465,7 +1538,6 @@ exports.importModule = importModule;
1465
1538
  exports.isPromise = isPromise;
1466
1539
  exports.isPromiseFulfilledResult = isPromiseFulfilledResult;
1467
1540
  exports.isPromiseRejectedResult = isPromiseRejectedResult;
1468
- exports.isURL = isURL;
1469
1541
  exports.name = pluginName;
1470
1542
  exports.nameSorter = nameSorter;
1471
1543
  exports.normalizeDirectory = normalizeDirectory;