@kubb/core 1.2.3 → 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.d.ts CHANGED
@@ -34,8 +34,6 @@ type PathMode = 'file' | 'directory';
34
34
  declare function getPathMode(path: string | undefined | null): PathMode;
35
35
  declare function read(path: string): Promise<string>;
36
36
 
37
- declare function isURL(data: string): boolean;
38
-
39
37
  type Data = string[][];
40
38
  type Options$2 = {
41
39
  typed?: boolean;
@@ -146,6 +144,7 @@ declare class URLPath {
146
144
  * @example /pet/{petId} => /pet/:petId
147
145
  */
148
146
  get URL(): string;
147
+ get isUrl(): boolean;
149
148
  /**
150
149
  * Convert Swagger path to template literals/ template strings(camelcase)
151
150
  * @example /pet/{petId} => `/pet/${petId}`
@@ -173,6 +172,7 @@ declare class URLPath {
173
172
  */
174
173
  toURLPath(): string;
175
174
  static toURLPath(path: string): string;
175
+ static isURL(path: string): boolean;
176
176
  }
177
177
 
178
178
  type Import = {
@@ -247,6 +247,22 @@ declare class FileManager {
247
247
  read(...params: Parameters<typeof read>): Promise<string>;
248
248
  }
249
249
 
250
+ declare class PluginError extends Error {
251
+ pluginManager: PluginManager;
252
+ cause: Error;
253
+ constructor(message: string, options: {
254
+ cause: Error;
255
+ pluginManager: PluginManager;
256
+ });
257
+ }
258
+
259
+ declare class EventEmitter<TEvents extends Record<string, any>> {
260
+ private emitter;
261
+ emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArg: TEvents[TEventName]): void;
262
+ on<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: (...eventArg: TEvents[TEventName]) => void): void;
263
+ off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: (...eventArg: TEvents[TEventName]) => void): void;
264
+ }
265
+
250
266
  /**
251
267
  * Get the type of the first argument in a function.
252
268
  * @example Arg0<(a: string, b: number) => void> -> string
@@ -257,10 +273,9 @@ type Executer<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
257
273
  strategy: Strategy;
258
274
  hookName: H;
259
275
  plugin: KubbPlugin;
260
- input?: unknown[] | undefined;
276
+ parameters?: unknown[] | undefined;
261
277
  output?: unknown;
262
278
  };
263
- type OnExecute<H extends PluginLifecycleHooks = PluginLifecycleHooks> = (this: PluginManager, executer: Executer<H> | undefined, pluginManager: PluginManager) => void;
264
279
  type ParseResult<H extends PluginLifecycleHooks> = PluginLifecycle[H];
265
280
  type SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseResult<H>>> = {
266
281
  result: Result;
@@ -272,20 +287,24 @@ type Options$1 = {
272
287
  debug?: boolean;
273
288
  task: QueueTask<ResolvedFile>;
274
289
  logger: Logger;
275
- onExecute?: OnExecute<PluginLifecycleHooks>;
290
+ };
291
+ type Events = {
292
+ execute: [executer: Executer];
293
+ executed: [executer: Executer];
294
+ error: [pluginError: PluginError];
276
295
  };
277
296
  declare class PluginManager {
278
297
  plugins: KubbPlugin[];
279
298
  readonly fileManager: FileManager;
280
- private readonly onExecute?;
281
299
  private readonly core;
282
300
  queue: Queue;
283
301
  executed: Executer[];
284
302
  logger: Logger;
303
+ eventEmitter: EventEmitter<Events>;
285
304
  constructor(config: KubbConfig, options: Options$1);
286
305
  resolvePath: (params: ResolvePathParams) => OptionalPath;
287
306
  resolveName: (params: ResolveNameParams) => string;
288
- load: (id: string) => Promise<SafeParseResult<'load'>>;
307
+ on<TEventName extends keyof Events & string>(eventName: TEventName, handler: (...eventArg: Events[TEventName]) => void): void;
289
308
  /**
290
309
  *
291
310
  * Run only hook for a specific plugin name
@@ -367,15 +386,6 @@ declare class ValidationPluginError extends Error {
367
386
  }
368
387
  declare function validatePlugins(plugins: KubbPlugin[], dependedPluginNames: string | string[]): true;
369
388
 
370
- declare class PluginError extends Error {
371
- pluginManager: PluginManager;
372
- cause: Error;
373
- constructor(message: string, options: {
374
- cause: Error;
375
- pluginManager: PluginManager;
376
- });
377
- }
378
-
379
389
  declare class ParallelPluginError extends Error {
380
390
  errors: PluginError[];
381
391
  pluginManager: PluginManager;
@@ -384,7 +394,7 @@ declare class ParallelPluginError extends Error {
384
394
  errors: PluginError[];
385
395
  pluginManager: PluginManager;
386
396
  });
387
- findError<T extends Error = Error>(searchError: T): T | undefined;
397
+ findError<T extends Error = Error>(searchError: T | undefined): T | undefined;
388
398
  }
389
399
 
390
400
  interface Register {
@@ -629,7 +639,6 @@ type PluginContext<TOptions = Record<string, unknown>> = {
629
639
  addFile: (...file: File[]) => Promise<File[]>;
630
640
  resolvePath: (params: ResolvePathParams<TOptions>) => OptionalPath;
631
641
  resolveName: (params: ResolveNameParams) => string;
632
- load: (id: string) => Promise<SafeParseResult<'load'>>;
633
642
  logger: Logger;
634
643
  };
635
644
  type TransformResult = string | null;
@@ -672,7 +681,6 @@ type Options = {
672
681
  fileManager: FileManager;
673
682
  resolvePath: PluginContext['resolvePath'];
674
683
  resolveName: PluginContext['resolveName'];
675
- load: PluginContext['load'];
676
684
  logger: PluginContext['logger'];
677
685
  };
678
686
  type CorePluginOptions = PluginFactoryOptions<'core', Options, false, PluginContext>;
@@ -696,4 +704,4 @@ declare abstract class SchemaGenerator<TOptions extends object, TInput, TOutput>
696
704
  abstract build(schema: TInput, name: string, description?: string): TOutput;
697
705
  }
698
706
 
699
- export { Argument0, BuildOutput, CLIOptions, Cache, CorePluginOptions, Executer, Extension, File, FileManager, FileName, Generator, KubbConfig, KubbJSONPlugins, KubbObjectPlugin, KubbObjectPlugins, KubbPlugin, KubbPluginKind, KubbUserConfig, KubbUserPlugin, LogLevel, LogLevels, LogType, Logger, OnExecute, OptionalPath, ParallelPluginError, ParseResult, Path, PathMode, PluginCache, PluginContext, PluginError, PluginFactoryOptions, PluginLifecycle, PluginLifecycleHooks, PluginManager, PossiblePromise, Queue, QueueTask, Register, ResolveNameParams, ResolvePathParams, ResolvedFile, SafeParseResult, SchemaGenerator, Source, Status, Strategy, SummaryError, TransformResult, TreeNode, TreeNodeOptions, URLPath, UUID, ValidationPluginError, Warning, build, canLogHierarchy, clean, combineFiles, createJSDocBlockText, createLogger, createPlugin, createPluginCache, build as default, defaultColours, defineConfig, extensions, getEncodedText, getFileSource, getLocation, getPathMode, getRelativePath, getStackTrace, getUniqueName, hooks, importModule, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, isURL, pluginName as name, nameSorter, normalizeDirectory, objectToParameters, pluginName, randomColour, randomPicoColour, read, renderTemplate, throttle, timeout, transformReservedWord, uniqueId, validatePlugins, write, writeIndexes };
707
+ export { Argument0, BuildOutput, CLIOptions, Cache, CorePluginOptions, Executer, Extension, File, FileManager, FileName, Generator, KubbConfig, KubbJSONPlugins, KubbObjectPlugin, KubbObjectPlugins, KubbPlugin, KubbPluginKind, KubbUserConfig, KubbUserPlugin, LogLevel, LogLevels, LogType, Logger, OptionalPath, ParallelPluginError, ParseResult, Path, PathMode, PluginCache, PluginContext, PluginError, PluginFactoryOptions, PluginLifecycle, PluginLifecycleHooks, PluginManager, PossiblePromise, Queue, QueueTask, Register, ResolveNameParams, ResolvePathParams, ResolvedFile, SafeParseResult, SchemaGenerator, Source, Status, Strategy, SummaryError, TransformResult, TreeNode, TreeNodeOptions, URLPath, UUID, ValidationPluginError, Warning, build, canLogHierarchy, clean, combineFiles, createJSDocBlockText, createLogger, createPlugin, createPluginCache, build as default, defaultColours, defineConfig, extensions, getEncodedText, getFileSource, getLocation, getPathMode, getRelativePath, getStackTrace, getUniqueName, hooks, importModule, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, pluginName as name, nameSorter, normalizeDirectory, objectToParameters, pluginName, randomColour, randomPicoColour, read, renderTemplate, throttle, timeout, transformReservedWord, uniqueId, validatePlugins, write, writeIndexes };
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ import pc3 from 'picocolors';
12
12
  export { default as pc } from 'picocolors';
13
13
  import seedrandom from 'seedrandom';
14
14
  import { createImportDeclaration, print, createExportDeclaration } from '@kubb/ts-codegen';
15
+ import { EventEmitter as EventEmitter$1 } from 'node:events';
15
16
 
16
17
  createRequire(import.meta.url);
17
18
 
@@ -97,19 +98,6 @@ function getPathMode(path) {
97
98
  async function read(path) {
98
99
  return fs.readFile(path, { encoding: "utf8" });
99
100
  }
100
-
101
- // src/utils/isURL.ts
102
- function isURL(data) {
103
- try {
104
- const url = new URL(data);
105
- if (url?.href) {
106
- return true;
107
- }
108
- } catch (error) {
109
- return false;
110
- }
111
- return false;
112
- }
113
101
  function objectToParameters(data, options = {}) {
114
102
  const { typed } = options;
115
103
  return data.reduce((acc, [key, value]) => {
@@ -399,7 +387,7 @@ var reservedWords = [
399
387
  "valueOf"
400
388
  ];
401
389
  function transformReservedWord(word) {
402
- if (word && reservedWords.includes(word)) {
390
+ if (word && reservedWords.includes(word) || word?.match(/^\d/)) {
403
391
  return `_${word}`;
404
392
  }
405
393
  return word;
@@ -567,6 +555,9 @@ var URLPath = class {
567
555
  get URL() {
568
556
  return this.toURLPath();
569
557
  }
558
+ get isUrl() {
559
+ return URLPath.isURL(this.path);
560
+ }
570
561
  /**
571
562
  * Convert Swagger path to template literals/ template strings(camelcase)
572
563
  * @example /pet/{petId} => `/pet/${petId}`
@@ -613,6 +604,17 @@ var URLPath = class {
613
604
  static toURLPath(path) {
614
605
  return path.replaceAll("{", ":").replaceAll("}", "");
615
606
  }
607
+ static isURL(path) {
608
+ try {
609
+ const url = new URL(path);
610
+ if (url?.href) {
611
+ return true;
612
+ }
613
+ } catch (error) {
614
+ return false;
615
+ }
616
+ return false;
617
+ }
616
618
  };
617
619
  function writeIndexes(root, options = {}) {
618
620
  const tree = TreeNode.build(root, { extensions: /\.ts/, ...options });
@@ -884,7 +886,7 @@ function createPlugin(factory) {
884
886
  }
885
887
  var pluginName = "core";
886
888
  var definePlugin = createPlugin((options) => {
887
- const { fileManager, resolvePath, resolveName, load, logger } = options;
889
+ const { fileManager, resolvePath, resolveName, logger } = options;
888
890
  return {
889
891
  name: pluginName,
890
892
  options,
@@ -928,7 +930,6 @@ var definePlugin = createPlugin((options) => {
928
930
  const name = resolveName(params);
929
931
  return transformReservedWord(name);
930
932
  },
931
- load,
932
933
  cache: createPluginCache()
933
934
  };
934
935
  },
@@ -953,6 +954,9 @@ var ParallelPluginError = class extends Error {
953
954
  this.pluginManager = options.pluginManager;
954
955
  }
955
956
  findError(searchError) {
957
+ if (!searchError) {
958
+ return void 0;
959
+ }
956
960
  return this.errors.find((error) => {
957
961
  if (error.cause) {
958
962
  if (error.cause.name == searchError.name) {
@@ -976,6 +980,30 @@ var PluginError = class extends Error {
976
980
  this.pluginManager = options.pluginManager;
977
981
  }
978
982
  };
983
+ var EventEmitter = class {
984
+ emitter = new EventEmitter$1();
985
+ emit(eventName, ...eventArg) {
986
+ this.emitter.emit(eventName, ...eventArg);
987
+ }
988
+ on(eventName, handler) {
989
+ this.emitter.on(eventName, handler);
990
+ }
991
+ off(eventName, handler) {
992
+ this.emitter.off(eventName, handler);
993
+ }
994
+ };
995
+
996
+ // src/managers/pluginManager/pluginParser.ts
997
+ function pluginParser(plugin, context) {
998
+ if (plugin.api && typeof plugin.api === "function") {
999
+ const api = plugin.api.call(context);
1000
+ return {
1001
+ ...plugin,
1002
+ api
1003
+ };
1004
+ }
1005
+ return null;
1006
+ }
979
1007
 
980
1008
  // src/managers/pluginManager/PluginManager.ts
981
1009
  var hookNames = {
@@ -989,26 +1017,15 @@ var hookNames = {
989
1017
  buildEnd: 1
990
1018
  };
991
1019
  var hooks = Object.keys(hookNames);
992
- var convertKubbUserPluginToKubbPlugin = (plugin, context) => {
993
- if (plugin.api && typeof plugin.api === "function") {
994
- const api = plugin.api.call(context);
995
- return {
996
- ...plugin,
997
- api
998
- };
999
- }
1000
- return null;
1001
- };
1002
1020
  var PluginManager = class {
1003
1021
  plugins;
1004
1022
  fileManager;
1005
- onExecute;
1006
1023
  core;
1007
1024
  queue;
1008
1025
  executed = [];
1009
1026
  logger;
1027
+ eventEmitter = new EventEmitter();
1010
1028
  constructor(config, options) {
1011
- this.onExecute = options.onExecute?.bind(this);
1012
1029
  this.logger = options.logger;
1013
1030
  this.queue = new Queue(100, options.debug);
1014
1031
  this.fileManager = new FileManager({ task: options.task, queue: this.queue });
@@ -1016,14 +1033,12 @@ var PluginManager = class {
1016
1033
  config,
1017
1034
  logger: this.logger,
1018
1035
  fileManager: this.fileManager,
1019
- load: this.load,
1020
1036
  resolvePath: this.resolvePath,
1021
1037
  resolveName: this.resolveName
1022
1038
  });
1023
- const convertedCore = convertKubbUserPluginToKubbPlugin(core, core.api.call(null));
1024
- this.core = convertedCore;
1039
+ this.core = pluginParser(core, core.api.call(null));
1025
1040
  this.plugins = [this.core, ...config.plugins || []].reduce((prev, plugin) => {
1026
- const convertedApi = convertKubbUserPluginToKubbPlugin(plugin, convertedCore?.api);
1041
+ const convertedApi = pluginParser(plugin, this.core?.api);
1027
1042
  if (convertedApi) {
1028
1043
  return [...prev, convertedApi];
1029
1044
  }
@@ -1056,12 +1071,9 @@ var PluginManager = class {
1056
1071
  parameters: [params.name]
1057
1072
  }).result;
1058
1073
  };
1059
- load = async (id) => {
1060
- return this.hookFirst({
1061
- hookName: "load",
1062
- parameters: [id]
1063
- });
1064
- };
1074
+ on(eventName, handler) {
1075
+ this.eventEmitter.on(eventName, handler);
1076
+ }
1065
1077
  /**
1066
1078
  *
1067
1079
  * Run only hook for a specific plugin name
@@ -1234,8 +1246,8 @@ var PluginManager = class {
1234
1246
  return pluginByPluginName;
1235
1247
  }
1236
1248
  addExecutedToCallStack(executer) {
1237
- this.onExecute?.call(this, executer, this);
1238
1249
  if (executer) {
1250
+ this.eventEmitter.emit("execute", executer);
1239
1251
  this.executed.push(executer);
1240
1252
  }
1241
1253
  }
@@ -1257,6 +1269,7 @@ var PluginManager = class {
1257
1269
  if (!hook) {
1258
1270
  return null;
1259
1271
  }
1272
+ this.eventEmitter.emit("execute", { strategy, hookName, parameters, plugin });
1260
1273
  const task = Promise.resolve().then(() => {
1261
1274
  if (typeof hook === "function") {
1262
1275
  const possiblePromiseResult = hook.apply(this.core.api, parameters);
@@ -1274,7 +1287,7 @@ var PluginManager = class {
1274
1287
  return null;
1275
1288
  }).finally(() => {
1276
1289
  this.addExecutedToCallStack({
1277
- input: parameters,
1290
+ parameters,
1278
1291
  output,
1279
1292
  strategy,
1280
1293
  hookName,
@@ -1301,6 +1314,7 @@ var PluginManager = class {
1301
1314
  if (!hook) {
1302
1315
  return null;
1303
1316
  }
1317
+ this.eventEmitter.emit("execute", { strategy, hookName, parameters, plugin });
1304
1318
  try {
1305
1319
  if (typeof hook === "function") {
1306
1320
  const fn = hook.apply(this.core.api, parameters);
@@ -1314,7 +1328,7 @@ var PluginManager = class {
1314
1328
  return null;
1315
1329
  } finally {
1316
1330
  this.addExecutedToCallStack({
1317
- input: parameters,
1331
+ parameters,
1318
1332
  output,
1319
1333
  strategy,
1320
1334
  hookName,
@@ -1325,7 +1339,9 @@ var PluginManager = class {
1325
1339
  catcher(e, plugin, hookName) {
1326
1340
  const text = `${e.message} (plugin: ${plugin.name}, hook: ${hookName})
1327
1341
  `;
1328
- throw new PluginError(text, { cause: e, pluginManager: this });
1342
+ const pluginError = new PluginError(text, { cause: e, pluginManager: this });
1343
+ this.eventEmitter.emit("error", pluginError);
1344
+ throw pluginError;
1329
1345
  }
1330
1346
  };
1331
1347
  function noReturn() {
@@ -1364,7 +1380,7 @@ async function transformReducer(_previousCode, result, _plugin) {
1364
1380
  async function build(options) {
1365
1381
  const { config, debug, logger = createLogger() } = options;
1366
1382
  try {
1367
- if (!isURL(config.input.path)) {
1383
+ if (!URLPath.isURL(config.input.path)) {
1368
1384
  await read(config.input.path);
1369
1385
  }
1370
1386
  } catch (e) {
@@ -1405,32 +1421,29 @@ async function build(options) {
1405
1421
  }
1406
1422
  }
1407
1423
  };
1408
- const onExecute = (executer) => {
1409
- if (!executer) {
1410
- return;
1411
- }
1412
- const { hookName, plugin, output, input } = executer;
1424
+ const pluginManager = new PluginManager(config, { debug, logger, task: queueTask });
1425
+ const { plugins, fileManager } = pluginManager;
1426
+ pluginManager.on("execute", (executer) => {
1427
+ const { hookName, plugin, output, parameters } = executer;
1413
1428
  const messsage = `${randomPicoColour(plugin.name)} Executing ${hookName}`;
1414
- if (config.logLevel === LogLevel.info && logger?.spinner && input) {
1429
+ if (config.logLevel === LogLevel.info && logger?.spinner && parameters) {
1415
1430
  if (debug) {
1416
1431
  logger.info(messsage);
1417
1432
  } else {
1418
1433
  logger.spinner.suffixText = messsage;
1419
1434
  }
1420
1435
  }
1421
- if (config.logLevel === LogLevel.stacktrace && logger?.spinner && input) {
1436
+ if (config.logLevel === LogLevel.stacktrace && logger?.spinner && parameters) {
1422
1437
  logger.info(messsage);
1423
1438
  const logs = [
1424
- input && `${pc3.bgWhite(`Input`)} ${randomPicoColour(plugin.name)} ${hookName}`,
1425
- JSON.stringify(input, void 0, 2),
1439
+ parameters && `${pc3.bgWhite(`Parameters`)} ${randomPicoColour(plugin.name)} ${hookName}`,
1440
+ JSON.stringify(parameters, void 0, 2),
1426
1441
  output && `${pc3.bgWhite("Output")} ${randomPicoColour(plugin.name)} ${hookName}`,
1427
1442
  output
1428
1443
  ].filter(Boolean);
1429
1444
  console.log(logs.join("\n"));
1430
1445
  }
1431
- };
1432
- const pluginManager = new PluginManager(config, { debug, logger, task: queueTask, onExecute });
1433
- const { plugins, fileManager } = pluginManager;
1446
+ });
1434
1447
  await pluginManager.hookParallel({
1435
1448
  hookName: "validate",
1436
1449
  parameters: [plugins]
@@ -1472,6 +1485,6 @@ var SchemaGenerator = class extends Generator {
1472
1485
  // src/index.ts
1473
1486
  var src_default = build;
1474
1487
 
1475
- export { FileManager, Generator, LogLevel, ParallelPluginError, PluginError, PluginManager, Queue, SchemaGenerator, SummaryError, TreeNode, URLPath, ValidationPluginError, Warning, build, canLogHierarchy, clean, combineFiles, createJSDocBlockText, createLogger, createPlugin, createPluginCache, src_default as default, defaultColours, defineConfig, extensions, getEncodedText, getFileSource, getLocation, getPathMode, getRelativePath, getStackTrace, getUniqueName, hooks, importModule, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, isURL, pluginName as name, nameSorter, normalizeDirectory, objectToParameters, pluginName, randomColour, randomPicoColour, read, renderTemplate, throttle, timeout, transformReservedWord, uniqueId, validatePlugins, write, writeIndexes };
1488
+ export { FileManager, Generator, LogLevel, ParallelPluginError, PluginError, PluginManager, Queue, SchemaGenerator, SummaryError, TreeNode, URLPath, ValidationPluginError, Warning, build, canLogHierarchy, clean, combineFiles, createJSDocBlockText, createLogger, createPlugin, createPluginCache, src_default as default, defaultColours, defineConfig, extensions, getEncodedText, getFileSource, getLocation, getPathMode, getRelativePath, getStackTrace, getUniqueName, hooks, importModule, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, pluginName as name, nameSorter, normalizeDirectory, objectToParameters, pluginName, randomColour, randomPicoColour, read, renderTemplate, throttle, timeout, transformReservedWord, uniqueId, validatePlugins, write, writeIndexes };
1476
1489
  //# sourceMappingURL=out.js.map
1477
1490
  //# sourceMappingURL=index.js.map