@kubb/core 5.14.2 → 5.14.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.
@@ -2286,9 +2286,9 @@ type Generator<TOptions extends PluginType = PluginType, TElement = unknown> = {
2286
2286
  */
2287
2287
  declare function defineGenerator<TOptions extends PluginType = PluginType, TElement = unknown>(generator: Generator<TOptions, TElement>): Generator<TOptions, TElement>;
2288
2288
  //#endregion
2289
- //#region src/Resolver.d.ts
2289
+ //#region src/resolveOptions.d.ts
2290
2290
  /**
2291
- * Context for resolving filtered options for a given operation or schema node.
2291
+ * Filters and overrides applied to an operation or schema's options.
2292
2292
  *
2293
2293
  * @internal
2294
2294
  */
@@ -2298,6 +2298,8 @@ type ResolveOptionsContext<TOptions> = {
2298
2298
  include?: Array<Filter>;
2299
2299
  override?: Array<Override<TOptions>>;
2300
2300
  };
2301
+ //#endregion
2302
+ //#region src/Resolver.d.ts
2301
2303
  /**
2302
2304
  * The built-in resolution machinery exposed on every resolver as `resolver.default`.
2303
2305
  * Plugins delegate to it via `this.default.*` and set their own conventions through
@@ -2520,6 +2522,17 @@ type ResolverBuildOptions = {
2520
2522
  name?: (name: string) => string;
2521
2523
  file?: ResolverFile;
2522
2524
  };
2525
+ /**
2526
+ * Reuse the declaration's key when resolving its references.
2527
+ */
2528
+ type ResolveNameOptions = {
2529
+ key: string | ReadonlyArray<string | undefined>;
2530
+ name: string;
2531
+ /**
2532
+ * Compares emitted identifiers while returning raw names. Keep numeric suffixes distinct.
2533
+ */
2534
+ normalize?: (name: string) => string;
2535
+ };
2523
2536
  /**
2524
2537
  * Partial resolver fields accepted by `Resolver.merge` and `setResolver`. Parameterize with a
2525
2538
  * concrete resolver type (e.g. `ResolverPatch<ResolverTs>`) to type-check overrides and bind
@@ -2572,6 +2585,30 @@ declare class Resolver {
2572
2585
  /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
2573
2586
  get [resolverOptions](): ResolverBuildOptions;
2574
2587
  name(name: string): string;
2588
+ /**
2589
+ * Reserves emitted identifiers before allocating other declarations. The driver reserves component
2590
+ * names. Reserve extra identifiers, such as enum type aliases, before calling `resolveName`.
2591
+ *
2592
+ * @example Reserve an enum's type and value names
2593
+ * ```ts
2594
+ * resolver.reserveNames(['petStatusEnum', 'PetStatusEnumKey'])
2595
+ * ```
2596
+ */
2597
+ reserveNames(names: Iterable<string>): void;
2598
+ /**
2599
+ * Returns the same name for repeated declaration keys. Adds numeric suffixes starting at `2`
2600
+ * when the preferred name is taken. Array segment order and boundaries matter. String and array
2601
+ * keys are distinct. Pass an already-cased name or use `normalize` to compare emitted identifiers
2602
+ * while returning raw names. `Resolver.merge` creates a resolver with no reservations.
2603
+ *
2604
+ * @example Resolve a request body that collides with a component
2605
+ * ```ts
2606
+ * resolver.reserveNames(['CreateContainerBody'])
2607
+ * resolver.resolveName({ key: ['operation', 'POST', '/containers', 'body'], name: 'CreateContainerBody' })
2608
+ * // 'CreateContainerBody2'
2609
+ * ```
2610
+ */
2611
+ resolveName({ key, name, normalize }: ResolveNameOptions): string;
2575
2612
  file(options: ResolveFileOptions): FileNode;
2576
2613
  /**
2577
2614
  * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
@@ -3253,5 +3290,5 @@ type AdapterFactory<T extends AdapterFactoryOptions = AdapterFactoryOptions> = E
3253
3290
  */
3254
3291
  declare function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(definition: AdapterDefinition<T>): AdapterFactory<T>;
3255
3292
  //#endregion
3256
- export { NodeCache as $, ReporterContext as $t, PluginFactory as A, KubbInfoContext as At, ResolveImportsOptions as B, RunHookOptions as Bt, NormalizedPlugin as C, KubbGenerationEndContext as Ct, Override as D, KubbHookLineContext as Dt, OutputOptions as E, KubbHookEndContext as Et, definePlugin as F, KubbWarnContext as Ft, ResolverFile as G, createOutputManifest as Gt, ResolvePathOptions as H, KubbDriver as Ht, BannerMeta as I, PossibleConfig as It, ResolverPatch as J, createRenderer as Jt, ResolverFileParams as K, Renderer as Kt, ResolveBannerContext as L, PostGenerateCommand as Lt, PluginType as M, KubbMessageContext as Mt, ResolvePluginOptions as N, KubbPluginsEndContext as Nt, Plugin as O, KubbHookStartContext as Ot, assertPluginOption as P, KubbSuccessContext as Pt, defineGenerator as Q, Reporter as Qt, ResolveBannerFile as R, UserConfig as Rt, KubbPluginStartContext as S, KubbFilesProcessingUpdateContext as St, OutputMode as T, KubbGenerationSummaryContext as Tt, Resolver as U, Hookable as Ut, ResolveOptionsContext as V, runHook as Vt, ResolverDefault as W, OutputManifest as Wt, Generator as X, createStorage as Xt, ResolverPathParams as Y, Storage as Yt, GeneratorContext as Z, GenerationResult as Zt, Filter as _, KubbDiagnosticContext as _t, AdapterSource as a, DiagnosticFormatOptions as an, Diagnostics as at, KubbPluginEndContext as b, KubbFilesProcessingEndContext as bt, ExtensionDependency as c, ParserDefinition as cn, ProblemDiagnostic as ct, ExtensionKind as d, CLIOptions as dt, ReporterName as en, Diagnostic as et, ExtensionMeta as f, Config as ft, Exclude$1 as g, KubbBuildStartContext as gt, resolveMeta as h, KubbBuildEndContext as ht, AdapterFactoryOptions as i, logLevel as in, DiagnosticSeverity as it, PluginName as j, KubbLifecycleStartContext as jt, PluginDefinition as k, KubbHooks as kt, ExtensionDependencyRecord as l, ParserFactory as ln, UpdateDiagnostic as lt, defineExtension as m, Input as mt, AdapterDefinition as n, UserReporter as nn, DiagnosticKind as nt, createAdapter as o, SerializedDiagnostic as on, PerformanceDiagnostic as ot, checkCompatibility as p, FilesContext as pt, ResolverFilePathParams as q, RendererFactory as qt, AdapterFactory as r, createReporter as rn, DiagnosticLocation as rt, ExtensionDependencies as s, Parser as sn, ProblemCode as st, Adapter as t, ReporterPluginFiles as tn, DiagnosticDoc as tt, ExtensionFactory as u, defineParser as un, BuildOutput as ut, Group as v, KubbErrorContext as vt, Output as w, KubbGenerationStartContext as wt, KubbPluginSetupContext as x, KubbFilesProcessingStartContext as xt, Include as y, KubbFileProcessingUpdate as yt, ResolveFileOptions as z, HookResult as zt };
3257
- //# sourceMappingURL=createAdapter-DwnjwKN0.d.ts.map
3293
+ export { defineGenerator as $, Reporter as $t, PluginFactory as A, KubbHooks as At, ResolveImportsOptions as B, HookResult as Bt, NormalizedPlugin as C, KubbFilesProcessingUpdateContext as Ct, Override as D, KubbHookEndContext as Dt, OutputOptions as E, KubbGenerationSummaryContext as Et, definePlugin as F, KubbSuccessContext as Ft, ResolverFile as G, OutputManifest as Gt, ResolvePathOptions as H, runHook as Ht, BannerMeta as I, KubbWarnContext as It, ResolverPatch as J, RendererFactory as Jt, ResolverFileParams as K, createOutputManifest as Kt, ResolveBannerContext as L, PossibleConfig as Lt, PluginType as M, KubbLifecycleStartContext as Mt, ResolvePluginOptions as N, KubbMessageContext as Nt, Plugin as O, KubbHookLineContext as Ot, assertPluginOption as P, KubbPluginsEndContext as Pt, GeneratorContext as Q, GenerationResult as Qt, ResolveBannerFile as R, PostGenerateCommand as Rt, KubbPluginStartContext as S, KubbFilesProcessingStartContext as St, OutputMode as T, KubbGenerationStartContext as Tt, Resolver as U, KubbDriver as Ut, ResolveNameOptions as V, RunHookOptions as Vt, ResolverDefault as W, Hookable as Wt, ResolveOptionsContext as X, Storage as Xt, ResolverPathParams as Y, createRenderer as Yt, Generator as Z, createStorage as Zt, Filter as _, KubbBuildStartContext as _t, AdapterSource as a, logLevel as an, DiagnosticSeverity as at, KubbPluginEndContext as b, KubbFileProcessingUpdate as bt, ExtensionDependency as c, Parser as cn, ProblemCode as ct, ExtensionKind as d, defineParser as dn, BuildOutput as dt, ReporterContext as en, NodeCache as et, ExtensionMeta as f, CLIOptions as ft, Exclude$1 as g, KubbBuildEndContext as gt, resolveMeta as h, Input as ht, AdapterFactoryOptions as i, createReporter as in, DiagnosticLocation as it, PluginName as j, KubbInfoContext as jt, PluginDefinition as k, KubbHookStartContext as kt, ExtensionDependencyRecord as l, ParserDefinition as ln, ProblemDiagnostic as lt, defineExtension as m, FilesContext as mt, AdapterDefinition as n, ReporterPluginFiles as nn, DiagnosticDoc as nt, createAdapter as o, DiagnosticFormatOptions as on, Diagnostics as ot, checkCompatibility as p, Config as pt, ResolverFilePathParams as q, Renderer as qt, AdapterFactory as r, UserReporter as rn, DiagnosticKind as rt, ExtensionDependencies as s, SerializedDiagnostic as sn, PerformanceDiagnostic as st, Adapter as t, ReporterName as tn, Diagnostic as tt, ExtensionFactory as u, ParserFactory as un, UpdateDiagnostic as ut, Group as v, KubbDiagnosticContext as vt, Output as w, KubbGenerationEndContext as wt, KubbPluginSetupContext as x, KubbFilesProcessingEndContext as xt, Include as y, KubbErrorContext as yt, ResolveFileOptions as z, UserConfig as zt };
3294
+ //# sourceMappingURL=createAdapter-y4ey5daI.d.ts.map
package/dist/index.cjs CHANGED
@@ -42,7 +42,7 @@ let node_readline = require("node:readline");
42
42
  let node_url = require("node:url");
43
43
  let node_module = require("node:module");
44
44
  //#region package.json
45
- var version = "5.14.2";
45
+ var version = "5.14.4";
46
46
  //#endregion
47
47
  //#region ../../internals/utils/src/casing.ts
48
48
  /**
@@ -1733,6 +1733,75 @@ function inputToAdapterSource(config) {
1733
1733
  };
1734
1734
  }
1735
1735
  //#endregion
1736
+ //#region src/resolveOptions.ts
1737
+ const patternCache = /* @__PURE__ */ new Map();
1738
+ const optionsCache = /* @__PURE__ */ new WeakMap();
1739
+ function testPattern(value, pattern) {
1740
+ if (typeof pattern === "string") {
1741
+ let regex = patternCache.get(pattern);
1742
+ regex ??= new RegExp(pattern);
1743
+ patternCache.set(pattern, regex);
1744
+ return regex.test(value);
1745
+ }
1746
+ return value.match(pattern) !== null;
1747
+ }
1748
+ function matchesOperation(node, filter) {
1749
+ if (filter.type === "extension") {
1750
+ const { extensions } = node;
1751
+ return extensions !== void 0 && Object.hasOwn(extensions, filter.key) && (filter.value === void 0 || extensions[filter.key] === filter.value);
1752
+ }
1753
+ const { type, pattern } = filter;
1754
+ if (type === "tag") return node.tags.some((tag) => testPattern(tag, pattern));
1755
+ if (type === "operationId") return testPattern(node.operationId, pattern);
1756
+ if (type === "path") return node.path !== void 0 && testPattern(node.path, pattern);
1757
+ if (type === "method") return node.method !== void 0 && testPattern(node.method.toLowerCase(), pattern);
1758
+ if (type === "contentType") return node.requestBody?.content?.some((c) => testPattern(c.contentType, pattern)) ?? false;
1759
+ return false;
1760
+ }
1761
+ function matchesSchema(node, filter) {
1762
+ if (filter.type === "schemaName") return node.name ? testPattern(node.name, filter.pattern) : false;
1763
+ return null;
1764
+ }
1765
+ function computeOptions(node, { options, exclude = [], include, override = [] }) {
1766
+ if (node.kind === _kubb_ast.ast.nodeKinds.operation) {
1767
+ if (exclude.some((filter) => matchesOperation(node, filter))) return null;
1768
+ if (include && !include.some((filter) => matchesOperation(node, filter))) return null;
1769
+ return {
1770
+ ...options,
1771
+ ...override.find((filter) => matchesOperation(node, filter))?.options
1772
+ };
1773
+ }
1774
+ if (node.kind === _kubb_ast.ast.nodeKinds.schema) {
1775
+ if (exclude.some((filter) => matchesSchema(node, filter) === true)) return null;
1776
+ if (include) {
1777
+ const applicable = include.map((filter) => matchesSchema(node, filter)).filter((result) => result !== null);
1778
+ if (applicable.length > 0 && !applicable.includes(true)) return null;
1779
+ }
1780
+ return {
1781
+ ...options,
1782
+ ...override.find((filter) => matchesSchema(node, filter) === true)?.options
1783
+ };
1784
+ }
1785
+ return options;
1786
+ }
1787
+ /**
1788
+ * Returns `null` for filtered nodes. Caches merged options per options object and node.
1789
+ */
1790
+ function resolveOptions(node, context) {
1791
+ const { options } = context;
1792
+ if (typeof options !== "object" || options === null) return computeOptions(node, context);
1793
+ let byOptions = optionsCache.get(options);
1794
+ if (!byOptions) {
1795
+ byOptions = /* @__PURE__ */ new WeakMap();
1796
+ optionsCache.set(options, byOptions);
1797
+ }
1798
+ const cached = byOptions.get(node);
1799
+ if (cached) return cached.value;
1800
+ const result = computeOptions(node, context);
1801
+ byOptions.set(node, { value: result });
1802
+ return result;
1803
+ }
1804
+ //#endregion
1736
1805
  //#region src/Resolver.ts
1737
1806
  function isNamespace(value) {
1738
1807
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -1803,12 +1872,12 @@ function toBaseName({ name, extname }) {
1803
1872
  * ```
1804
1873
  */
1805
1874
  var Resolver = class Resolver {
1806
- static #patternCache = /* @__PURE__ */ new Map();
1807
- static #optionsCache = /* @__PURE__ */ new WeakMap();
1808
1875
  pluginName;
1809
1876
  /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
1810
1877
  default;
1811
1878
  #options;
1879
+ #usedNames = /* @__PURE__ */ new Set();
1880
+ #resolvedNames = /* @__PURE__ */ new Map();
1812
1881
  #baseName;
1813
1882
  #filePath;
1814
1883
  constructor(options) {
@@ -1818,7 +1887,7 @@ var Resolver = class Resolver {
1818
1887
  this.#filePath = options.file?.path ? options.file.path.bind(this) : void 0;
1819
1888
  this.default = {
1820
1889
  name: camelCase,
1821
- options: this.#resolveOptions.bind(this),
1890
+ options: resolveOptions,
1822
1891
  path: this.#resolvePath.bind(this),
1823
1892
  file: this.#resolveFile.bind(this),
1824
1893
  banner: this.#resolveBanner.bind(this),
@@ -1833,6 +1902,41 @@ var Resolver = class Resolver {
1833
1902
  name(name) {
1834
1903
  return this.default.name(name);
1835
1904
  }
1905
+ /**
1906
+ * Reserves emitted identifiers before allocating other declarations. The driver reserves component
1907
+ * names. Reserve extra identifiers, such as enum type aliases, before calling `resolveName`.
1908
+ *
1909
+ * @example Reserve an enum's type and value names
1910
+ * ```ts
1911
+ * resolver.reserveNames(['petStatusEnum', 'PetStatusEnumKey'])
1912
+ * ```
1913
+ */
1914
+ reserveNames(names) {
1915
+ for (const name of names) this.#usedNames.add(name);
1916
+ }
1917
+ /**
1918
+ * Returns the same name for repeated declaration keys. Adds numeric suffixes starting at `2`
1919
+ * when the preferred name is taken. Array segment order and boundaries matter. String and array
1920
+ * keys are distinct. Pass an already-cased name or use `normalize` to compare emitted identifiers
1921
+ * while returning raw names. `Resolver.merge` creates a resolver with no reservations.
1922
+ *
1923
+ * @example Resolve a request body that collides with a component
1924
+ * ```ts
1925
+ * resolver.reserveNames(['CreateContainerBody'])
1926
+ * resolver.resolveName({ key: ['operation', 'POST', '/containers', 'body'], name: 'CreateContainerBody' })
1927
+ * // 'CreateContainerBody2'
1928
+ * ```
1929
+ */
1930
+ resolveName({ key, name, normalize = (name) => name }) {
1931
+ const cacheKey = JSON.stringify(key);
1932
+ const previous = this.#resolvedNames.get(cacheKey);
1933
+ if (previous !== void 0) return previous;
1934
+ let result = name;
1935
+ for (let suffix = 2; this.#usedNames.has(normalize(result)); suffix++) result = `${name}${suffix}`;
1936
+ this.#usedNames.add(normalize(result));
1937
+ this.#resolvedNames.set(cacheKey, result);
1938
+ return result;
1939
+ }
1836
1940
  file(options) {
1837
1941
  return this.#resolveFile(options);
1838
1942
  }
@@ -1903,76 +2007,6 @@ var Resolver = class Resolver {
1903
2007
  root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value);
1904
2008
  }
1905
2009
  }
1906
- static #testPattern(value, pattern) {
1907
- if (typeof pattern === "string") {
1908
- let regex = Resolver.#patternCache.get(pattern);
1909
- regex ??= new RegExp(pattern);
1910
- Resolver.#patternCache.set(pattern, regex);
1911
- return regex.test(value);
1912
- }
1913
- return value.match(pattern) !== null;
1914
- }
1915
- static #matchesOperation(node, filter) {
1916
- if (filter.type === "extension") {
1917
- const { extensions } = node;
1918
- return extensions !== void 0 && Object.hasOwn(extensions, filter.key) && (filter.value === void 0 || extensions[filter.key] === filter.value);
1919
- }
1920
- const { type, pattern } = filter;
1921
- if (type === "tag") return node.tags.some((tag) => Resolver.#testPattern(tag, pattern));
1922
- if (type === "operationId") return Resolver.#testPattern(node.operationId, pattern);
1923
- if (type === "path") return node.path !== void 0 && Resolver.#testPattern(node.path, pattern);
1924
- if (type === "method") return node.method !== void 0 && Resolver.#testPattern(node.method.toLowerCase(), pattern);
1925
- if (type === "contentType") return node.requestBody?.content?.some((c) => Resolver.#testPattern(c.contentType, pattern)) ?? false;
1926
- return false;
1927
- }
1928
- /**
1929
- * Returns `null` when the filter type doesn't apply to schemas, so include rules built
1930
- * from operation filters (e.g. `tag`) don't exclude every schema.
1931
- */
1932
- static #matchesSchema(node, filter) {
1933
- if (filter.type === "schemaName") return node.name ? Resolver.#testPattern(node.name, filter.pattern) : false;
1934
- return null;
1935
- }
1936
- static #computeOptions(node, { options, exclude = [], include, override = [] }) {
1937
- if (node.kind === _kubb_ast.ast.nodeKinds.operation) {
1938
- if (exclude.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
1939
- if (include && !include.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
1940
- return {
1941
- ...options,
1942
- ...override.find((filter) => Resolver.#matchesOperation(node, filter))?.options
1943
- };
1944
- }
1945
- if (node.kind === _kubb_ast.ast.nodeKinds.schema) {
1946
- if (exclude.some((filter) => Resolver.#matchesSchema(node, filter) === true)) return null;
1947
- if (include) {
1948
- const applicable = include.map((filter) => Resolver.#matchesSchema(node, filter)).filter((result) => result !== null);
1949
- if (applicable.length > 0 && !applicable.includes(true)) return null;
1950
- }
1951
- return {
1952
- ...options,
1953
- ...override.find((filter) => Resolver.#matchesSchema(node, filter) === true)?.options
1954
- };
1955
- }
1956
- return options;
1957
- }
1958
- /**
1959
- * Applies include/exclude filters and merges matching override options, caching the result
1960
- * per `(options, node)` pair. Returns `null` when the node is filtered out.
1961
- */
1962
- #resolveOptions(node, context) {
1963
- const { options } = context;
1964
- if (typeof options !== "object" || options === null) return Resolver.#computeOptions(node, context);
1965
- let byOptions = Resolver.#optionsCache.get(options);
1966
- if (!byOptions) {
1967
- byOptions = /* @__PURE__ */ new WeakMap();
1968
- Resolver.#optionsCache.set(options, byOptions);
1969
- }
1970
- const cached = byOptions.get(node);
1971
- if (cached) return cached.value;
1972
- const result = Resolver.#computeOptions(node, context);
1973
- byOptions.set(node, { value: result });
1974
- return result;
1975
- }
1976
2010
  /**
1977
2011
  * A custom `group.name` wins; otherwise `tag` groups use the camelCased tag and `path`
1978
2012
  * groups use the first non-traversal segment (`''` when none remain, placing the file in
@@ -3002,6 +3036,7 @@ var KubbDriver = class {
3002
3036
  optionsAreStatic: !exclude?.length && !include?.length && !override?.length,
3003
3037
  allowedSchemaNames: allowedSchemaNamesByPlugin.get(plugin.name) ?? null,
3004
3038
  schemaGenerators: generators.filter((generator) => generator.schema),
3039
+ schemas: /* @__PURE__ */ new Map(),
3005
3040
  operationGenerators: generators.filter((generator) => generator.operation),
3006
3041
  operationsGenerators: generators.filter((generator) => generator.operations),
3007
3042
  pluginOperations: [],
@@ -3027,15 +3062,29 @@ var KubbDriver = class {
3027
3062
  options
3028
3063
  };
3029
3064
  };
3065
+ for (const state of states) {
3066
+ if (!state.schemaGenerators.length) continue;
3067
+ for (const node of schemas) try {
3068
+ const resolved = resolveForPlugin(state, node);
3069
+ if (!resolved) continue;
3070
+ const name = resolved.transformedNode.name;
3071
+ if (state.allowedSchemaNames !== null && name && !state.allowedSchemaNames.has(name)) continue;
3072
+ state.schemas.set(node, resolved);
3073
+ if (name) state.generatorContext.resolver.reserveNames([state.generatorContext.resolver.name(name)]);
3074
+ } catch (caughtError) {
3075
+ state.schemas.set(node, toError(caughtError));
3076
+ break;
3077
+ }
3078
+ }
3030
3079
  for (const node of schemas) {
3031
3080
  const cache = createNodeCache();
3032
3081
  for (const state of states) {
3033
3082
  if (state.error || !state.schemaGenerators.length) continue;
3034
3083
  try {
3035
- const resolved = resolveForPlugin(state, node);
3084
+ const resolved = state.schemas.get(node);
3085
+ if (resolved instanceof Error) throw resolved;
3036
3086
  if (!resolved) continue;
3037
3087
  const { transformedNode, options } = resolved;
3038
- if (state.allowedSchemaNames !== null && transformedNode.name && !state.allowedSchemaNames.has(transformedNode.name)) continue;
3039
3088
  const ctx = {
3040
3089
  ...state.generatorContext,
3041
3090
  options,