@kubb/core 1.2.1 → 1.2.3

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
@@ -27,7 +27,7 @@ interface Cache<TStore extends object = object> {
27
27
  has(id: keyof TStore): boolean;
28
28
  set(id: keyof TStore, value: unknown): void;
29
29
  }
30
- declare function createPluginCache<TStore extends Record<string, [number, unknown]>>(Store: TStore): Cache<TStore>;
30
+ declare function createPluginCache<TStore extends PluginCache>(Store?: TStore): Cache<TStore>;
31
31
 
32
32
  declare function getRelativePath(rootDir?: string | null, filePath?: string | null, platform?: 'windows' | 'mac' | 'linux'): string;
33
33
  type PathMode = 'file' | 'directory';
@@ -48,7 +48,7 @@ declare function objectToParameters(data: Data, options?: Options$2): string;
48
48
 
49
49
  declare function nameSorter<T extends {
50
50
  name: string;
51
- }>(a: T, b: T): 1 | -1 | 0;
51
+ }>(a: T, b: T): 0 | 1 | -1;
52
52
 
53
53
  declare function createJSDocBlockText({ comments }: {
54
54
  comments: Array<string>;
@@ -95,7 +95,7 @@ declare class TreeNode<T = unknown> {
95
95
  static build<T = unknown>(path: string, options?: TreeNodeOptions): TreeNode<T> | null;
96
96
  }
97
97
 
98
- declare function transformReservedWord(word?: string | null): string | null | undefined;
98
+ declare function transformReservedWord(word: string): string;
99
99
 
100
100
  declare function getStackTrace(belowFn?: Function): NodeJS.CallSite[];
101
101
 
@@ -138,6 +138,43 @@ declare const defaultColours: readonly ["black", "blue", "darkBlue", "cyan", "gr
138
138
  declare function randomColour(text?: string, colours?: readonly ["black", "blue", "darkBlue", "cyan", "gray", "green", "darkGreen", "magenta", "red", "darkRed", "yellow", "darkYellow"]): string;
139
139
  declare function randomPicoColour(text?: string, colors?: readonly ["black", "blue", "darkBlue", "cyan", "gray", "green", "darkGreen", "magenta", "red", "darkRed", "yellow", "darkYellow"]): string;
140
140
 
141
+ declare class URLPath {
142
+ path: string;
143
+ constructor(path: string);
144
+ /**
145
+ * Convert Swagger path to URLPath(syntax of Express)
146
+ * @example /pet/{petId} => /pet/:petId
147
+ */
148
+ get URL(): string;
149
+ /**
150
+ * Convert Swagger path to template literals/ template strings(camelcase)
151
+ * @example /pet/{petId} => `/pet/${petId}`
152
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
153
+ * @example /account/userID => `/account/${userId}`
154
+ */
155
+ get template(): string;
156
+ /**
157
+ * Convert Swagger path to template literals/ template strings(camelcase)
158
+ * @example /pet/{petId} => `/pet/${petId}`
159
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
160
+ * @example /account/userID => `/account/${userId}`
161
+ */
162
+ toTemplateString(): string;
163
+ /**
164
+ * Convert Swagger path to template literals/ template strings(camelcase)
165
+ * @example /pet/{petId} => `/pet/${petId}`
166
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
167
+ * @example /account/userID => `/account/${userId}`
168
+ */
169
+ static toTemplateString(path: string): string;
170
+ /**
171
+ * Convert Swagger path to URLPath(syntax of Express)
172
+ * @example /pet/{petId} => /pet/:petId
173
+ */
174
+ toURLPath(): string;
175
+ static toURLPath(path: string): string;
176
+ }
177
+
141
178
  type Import = {
142
179
  name: string | string[];
143
180
  path: string;
@@ -230,7 +267,7 @@ type SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseRe
230
267
  plugin: KubbPlugin;
231
268
  };
232
269
 
233
- declare const hooks: [keyof PluginLifecycle<PluginFactoryOptions<string, unknown, false, any, Record<string, any>>>];
270
+ declare const hooks: [keyof PluginLifecycle<PluginFactoryOptions<string, unknown, false, any, Record<string, unknown>>>];
234
271
  type Options$1 = {
235
272
  debug?: boolean;
236
273
  task: QueueTask<ResolvedFile>;
@@ -247,8 +284,8 @@ declare class PluginManager {
247
284
  logger: Logger;
248
285
  constructor(config: KubbConfig, options: Options$1);
249
286
  resolvePath: (params: ResolvePathParams) => OptionalPath;
250
- resolveName: (params: ResolveNameParams) => string | null;
251
- load: (id: string) => Promise<SafeParseResult<"load">>;
287
+ resolveName: (params: ResolveNameParams) => string;
288
+ load: (id: string) => Promise<SafeParseResult<'load'>>;
252
289
  /**
253
290
  *
254
291
  * Run only hook for a specific plugin name
@@ -448,10 +485,6 @@ type CLIOptions = {
448
485
  * Watch changes on input
449
486
  */
450
487
  watch?: string;
451
- /**
452
- * Override `input` defined in `kubb.config.js`
453
- */
454
- input?: string;
455
488
  /**
456
489
  * Override `logLevel` defined in `kubb.config.js`
457
490
  * @default `'silent'`
@@ -513,7 +546,7 @@ type KubbPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> =
513
546
  */
514
547
  api?: TOptions['api'];
515
548
  } & Partial<PluginLifecycle<TOptions>>;
516
- type PluginFactoryOptions<Name = string, Options = unknown, Nested extends boolean = false, API = any, resolvePathOptions = Record<string, any>> = {
549
+ type PluginFactoryOptions<Name = string, Options = unknown, Nested extends boolean = false, API = any, resolvePathOptions = Record<string, unknown>> = {
517
550
  name: Name;
518
551
  options: Options;
519
552
  nested: Nested;
@@ -567,7 +600,8 @@ type PluginLifecycle<TOptions extends PluginFactoryOptions = PluginFactoryOption
567
600
  buildEnd: (this: PluginContext) => PossiblePromise<void>;
568
601
  };
569
602
  type PluginLifecycleHooks = keyof PluginLifecycle;
570
- type ResolvePathParams<TOptions = Record<string, any>> = {
603
+ type PluginCache = Record<string, [number, unknown]>;
604
+ type ResolvePathParams<TOptions = Record<string, unknown>> = {
571
605
  /**
572
606
  * When set, resolvePath will only call resolvePath of the name of the plugin set here.
573
607
  * If not defined it will fall back on the resolvePath of the core plugin.
@@ -588,13 +622,13 @@ type ResolveNameParams = {
588
622
  pluginName?: string;
589
623
  name: string;
590
624
  };
591
- type PluginContext<TOptions = Record<string, any>> = {
625
+ type PluginContext<TOptions = Record<string, unknown>> = {
592
626
  config: KubbConfig;
593
- cache: Cache;
627
+ cache: Cache<PluginCache>;
594
628
  fileManager: FileManager;
595
629
  addFile: (...file: File[]) => Promise<File[]>;
596
630
  resolvePath: (params: ResolvePathParams<TOptions>) => OptionalPath;
597
- resolveName: (params: ResolveNameParams) => string | null | undefined;
631
+ resolveName: (params: ResolveNameParams) => string;
598
632
  load: (id: string) => Promise<SafeParseResult<'load'>>;
599
633
  logger: Logger;
600
634
  };
@@ -627,10 +661,12 @@ declare function build(options: BuildOptions): Promise<BuildOutput>;
627
661
  * accepts a direct {@link KubbConfig} object, or a function that returns it.
628
662
  * The function receives a {@link ConfigEnv} object that exposes two properties:
629
663
  */
630
- declare const defineConfig: (options: PossiblePromise<KubbUserConfig> | ((cliOptions: CLIOptions) => PossiblePromise<KubbUserConfig>)) => PossiblePromise<KubbUserConfig> | ((cliOptions: CLIOptions) => PossiblePromise<KubbUserConfig>);
664
+ declare function defineConfig(options: PossiblePromise<KubbUserConfig> | ((
665
+ /** The options derived from the CLI flags */
666
+ cliOptions: CLIOptions) => PossiblePromise<KubbUserConfig>)): typeof options;
631
667
 
632
668
  type KubbPluginFactory<T extends PluginFactoryOptions = PluginFactoryOptions> = (options: T['options']) => T['nested'] extends true ? Array<KubbUserPlugin<T>> : KubbUserPlugin<T>;
633
- declare function createPlugin<T extends PluginFactoryOptions = PluginFactoryOptions>(factory: KubbPluginFactory<T>): (options: T['options']) => T["nested"] extends true ? KubbUserPlugin<T>[] : KubbUserPlugin<T>;
669
+ declare function createPlugin<T extends PluginFactoryOptions = PluginFactoryOptions>(factory: KubbPluginFactory<T>): (options: T['options']) => ReturnType<KubbPluginFactory<T>>;
634
670
  type Options = {
635
671
  config: PluginContext['config'];
636
672
  fileManager: FileManager;
@@ -660,4 +696,4 @@ declare abstract class SchemaGenerator<TOptions extends object, TInput, TOutput>
660
696
  abstract build(schema: TInput, name: string, description?: string): TOutput;
661
697
  }
662
698
 
663
- 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, PluginContext, PluginError, PluginFactoryOptions, PluginLifecycle, PluginLifecycleHooks, PluginManager, PossiblePromise, Queue, QueueTask, Register, ResolveNameParams, ResolvePathParams, ResolvedFile, SafeParseResult, SchemaGenerator, Source, Status, Strategy, SummaryError, TransformResult, TreeNode, TreeNodeOptions, 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 };
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 };
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { rimraf } from 'rimraf';
8
8
  import dirTree from 'directory-tree';
9
9
  import mod from 'node:module';
10
10
  import { pathToFileURL } from 'node:url';
11
- import pc2 from 'picocolors';
11
+ 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';
@@ -44,7 +44,7 @@ async function write(data, path) {
44
44
  }
45
45
 
46
46
  // src/utils/cache.ts
47
- function createPluginCache(Store) {
47
+ function createPluginCache(Store = /* @__PURE__ */ Object.create(null)) {
48
48
  return {
49
49
  set(id, value) {
50
50
  Store[id] = [0, value];
@@ -506,7 +506,7 @@ function createLogger(spinner) {
506
506
  };
507
507
  const warn = (message) => {
508
508
  if (message && spinner) {
509
- spinner.warn(pc2.yellow(message));
509
+ spinner.warn(pc3.yellow(message));
510
510
  }
511
511
  };
512
512
  const info = (message) => {
@@ -539,7 +539,7 @@ function randomColour(text, colours = defaultColours) {
539
539
  return colour;
540
540
  }
541
541
  function randomPicoColour(text, colors = defaultColours) {
542
- const colours = pc2.createColors(true);
542
+ const colours = pc3.createColors(true);
543
543
  if (!text) {
544
544
  return colours.white(text);
545
545
  }
@@ -548,13 +548,72 @@ function randomPicoColour(text, colors = defaultColours) {
548
548
  const key = colour.replace("dark", "").toLowerCase();
549
549
  const formatter = colours[key];
550
550
  if (isDark) {
551
- return pc2.bold(formatter(text));
551
+ return pc3.bold(formatter(text));
552
552
  }
553
553
  if (typeof formatter !== "function") {
554
554
  throw new Error("Formatter for picoColor is not of type function/Formatter");
555
555
  }
556
556
  return formatter(text);
557
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
+ /**
571
+ * Convert Swagger path to template literals/ template strings(camelcase)
572
+ * @example /pet/{petId} => `/pet/${petId}`
573
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
574
+ * @example /account/userID => `/account/${userId}`
575
+ */
576
+ get template() {
577
+ return this.toTemplateString();
578
+ }
579
+ /**
580
+ * Convert Swagger path to template literals/ template strings(camelcase)
581
+ * @example /pet/{petId} => `/pet/${petId}`
582
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
583
+ * @example /account/userID => `/account/${userId}`
584
+ */
585
+ toTemplateString() {
586
+ return URLPath.toTemplateString(this.path);
587
+ }
588
+ /**
589
+ * Convert Swagger path to template literals/ template strings(camelcase)
590
+ * @example /pet/{petId} => `/pet/${petId}`
591
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
592
+ * @example /account/userID => `/account/${userId}`
593
+ */
594
+ static toTemplateString(path) {
595
+ const regex = /{(\w|-)*}/g;
596
+ const found = path.match(regex);
597
+ let newPath = path.replaceAll("{", "${");
598
+ if (found) {
599
+ newPath = found.reduce((prev, curr) => {
600
+ const replacement = `\${${camelCase(curr, { delimiter: "", transform: camelCaseTransformMerge })}}`;
601
+ return prev.replace(curr, replacement);
602
+ }, path);
603
+ }
604
+ return `\`${newPath}\``;
605
+ }
606
+ /**
607
+ * Convert Swagger path to URLPath(syntax of Express)
608
+ * @example /pet/{petId} => /pet/:petId
609
+ */
610
+ toURLPath() {
611
+ return URLPath.toURLPath(this.path);
612
+ }
613
+ static toURLPath(path) {
614
+ return path.replaceAll("{", ":").replaceAll("}", "");
615
+ }
616
+ };
558
617
  function writeIndexes(root, options = {}) {
559
618
  const tree = TreeNode.build(root, { extensions: /\.ts/, ...options });
560
619
  if (!tree) {
@@ -870,7 +929,7 @@ var definePlugin = createPlugin((options) => {
870
929
  return transformReservedWord(name);
871
930
  },
872
931
  load,
873
- cache: createPluginCache(/* @__PURE__ */ Object.create(null))
932
+ cache: createPluginCache()
874
933
  };
875
934
  },
876
935
  resolvePath(fileName) {
@@ -990,7 +1049,7 @@ var PluginManager = class {
990
1049
  pluginName: params.pluginName,
991
1050
  hookName: "resolveName",
992
1051
  parameters: [params.name]
993
- });
1052
+ }) || params.name;
994
1053
  }
995
1054
  return this.hookFirstSync({
996
1055
  hookName: "resolveName",
@@ -1309,7 +1368,12 @@ async function build(options) {
1309
1368
  await read(config.input.path);
1310
1369
  }
1311
1370
  } catch (e) {
1312
- throw new Error("Cannot read file/URL defined in `input.path` or set with --input in the CLI of your Kubb config", { cause: e });
1371
+ throw new Error(
1372
+ "Cannot read file/URL defined in `input.path` or set with `kubb generate PATH` in the CLI of your Kubb config " + pc3.dim(config.input.path),
1373
+ {
1374
+ cause: e
1375
+ }
1376
+ );
1313
1377
  }
1314
1378
  if (config.output.clean) {
1315
1379
  await clean(config.output.path);
@@ -1357,9 +1421,9 @@ async function build(options) {
1357
1421
  if (config.logLevel === LogLevel.stacktrace && logger?.spinner && input) {
1358
1422
  logger.info(messsage);
1359
1423
  const logs = [
1360
- input && `${pc2.bgWhite(`Input`)} ${randomPicoColour(plugin.name)} ${hookName}`,
1424
+ input && `${pc3.bgWhite(`Input`)} ${randomPicoColour(plugin.name)} ${hookName}`,
1361
1425
  JSON.stringify(input, void 0, 2),
1362
- output && `${pc2.bgWhite("Output")} ${randomPicoColour(plugin.name)} ${hookName}`,
1426
+ output && `${pc3.bgWhite("Output")} ${randomPicoColour(plugin.name)} ${hookName}`,
1363
1427
  output
1364
1428
  ].filter(Boolean);
1365
1429
  console.log(logs.join("\n"));
@@ -1380,7 +1444,9 @@ async function build(options) {
1380
1444
  }
1381
1445
 
1382
1446
  // src/config.ts
1383
- var defineConfig = (options) => options;
1447
+ function defineConfig(options) {
1448
+ return options;
1449
+ }
1384
1450
 
1385
1451
  // src/generators/Generator.ts
1386
1452
  var Generator = class {
@@ -1406,6 +1472,6 @@ var SchemaGenerator = class extends Generator {
1406
1472
  // src/index.ts
1407
1473
  var src_default = build;
1408
1474
 
1409
- export { FileManager, Generator, LogLevel, ParallelPluginError, PluginError, PluginManager, Queue, SchemaGenerator, SummaryError, TreeNode, 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 };
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 };
1410
1476
  //# sourceMappingURL=out.js.map
1411
1477
  //# sourceMappingURL=index.js.map