@kubb/core 5.7.0 → 5.8.1

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.
@@ -1,4 +1,4 @@
1
- import { t as __name } from "./rolldown-runtime-C0LytTxp.js";
1
+ import { t as __name } from "./rolldown-runtime-CRm0XQPb.js";
2
2
  import { Enforce, FileNode, HttpMethod, ImportNode, InputMeta, InputNode, Macro, Node, OperationNode, SchemaNode, UserFileNode } from "@kubb/ast";
3
3
  //#region ../../internals/utils/src/promise.d.ts
4
4
  /** A value that may already be resolved or still pending.
@@ -26,118 +26,67 @@ type PossiblePromise<T> = Promise<T> | T;
26
26
  */
27
27
  type LiteralUnion<T extends Base, Base = string> = T | (Base & {});
28
28
  //#endregion
29
- //#region src/createAdapter.d.ts
30
- /**
31
- * Source data handed to an adapter's `parse` function. Mirrors the config
32
- * input shape with paths resolved to absolute.
33
- *
34
- * - `{ type: 'path' }`: single file on disk.
35
- * - `{ type: 'data' }`: raw string or parsed object provided inline.
36
- */
37
- type AdapterSource = {
38
- type: 'path';
39
- path: string;
40
- } | {
41
- type: 'data';
42
- data: string | unknown;
43
- };
44
- /**
45
- * Generic parameters used by `createAdapter` and the resulting `Adapter` type.
46
- *
47
- * - `TName`: unique adapter identifier (`'oas'`, `'asyncapi'`, ...).
48
- * - `TOptions`: user-facing options accepted by the adapter factory.
49
- * - `TResolvedOptions`: options after defaults are applied.
50
- * - `TDocument`: type of the parsed source document.
51
- */
52
- type AdapterFactoryOptions<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TDocument = unknown> = {
53
- name: TName;
54
- options: TOptions;
55
- resolvedOptions: TResolvedOptions;
56
- document: TDocument;
57
- };
29
+ //#region src/createRenderer.d.ts
58
30
  /**
59
- * Converts input files or inline data into Kubb's universal AST `InputNode`.
60
- *
61
- * Adapters live between the spec format and the plugins. The built-in
62
- * `@kubb/adapter-oas` handles OpenAPI 2.0, 3.0, and 3.1. A custom adapter can
63
- * support GraphQL, gRPC, or another schema language.
64
- *
65
- * @example
66
- * ```ts
67
- * import { defineConfig } from 'kubb'
68
- * import { adapterOas } from '@kubb/adapter-oas'
69
- * import { pluginTs } from '@kubb/plugin-ts'
31
+ * Minimal interface any Kubb renderer must satisfy.
70
32
  *
71
- * export default defineConfig({
72
- * input: './petStore.yaml',
73
- * output: { path: './src/gen' },
74
- * adapter: adapterOas(),
75
- * plugins: [pluginTs()],
76
- * })
77
- * ```
33
+ * `TElement` is the type the renderer accepts, for example `KubbReactElement`
34
+ * for `@kubb/renderer-jsx` or a custom type for your own renderer. Defaults to
35
+ * `unknown` so generators that don't care about the element type work without
36
+ * specifying it.
78
37
  */
79
- type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
80
- /**
81
- * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).
82
- */
83
- name: TOptions['name'];
84
- /**
85
- * Resolved adapter options after defaults have been applied.
86
- */
87
- options: TOptions['resolvedOptions'];
38
+ type Renderer<TElement = unknown> = {
88
39
  /**
89
- * Parsed source document after the first `parse()` call. `null` before parsing.
40
+ * Renders `element` and populates {@link files} with the resulting {@link FileNode} objects.
41
+ * Called once per render cycle. Must resolve before {@link files} is read.
90
42
  */
91
- document: TOptions['document'] | null;
43
+ render(element: TElement): Promise<void>;
92
44
  /**
93
- * Parse the source into a universal `InputNode`.
94
- *
95
- * An adapter that renames schemas (e.g. collision handling) must stamp `targetName` on
96
- * every ref node pointing at a renamed schema, so `resolveRefName` and `resolver.imports`
97
- * resolve a `$ref` to the file that is actually generated. Refs that keep their pointer's
98
- * last segment need no stamp.
45
+ * Accumulated {@link FileNode} results produced by the last {@link render} call.
99
46
  */
100
- parse: (source: AdapterSource, options?: {
101
- signal?: AbortSignal;
102
- }) => PossiblePromise<InputNode>;
47
+ readonly files: Array<FileNode>;
103
48
  /**
104
- * Validate the document at the given path or URL.
49
+ * Disposer hook so renderers participate in `using` blocks: `using r = rendererFactory()`
50
+ * runs cleanup on every exit path, including thrown errors.
105
51
  */
106
- validate: (input: string, options?: {
107
- throwOnError?: boolean;
108
- }) => Promise<void>;
52
+ [Symbol.dispose](): void;
109
53
  };
110
- type AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>;
111
54
  /**
112
- * Defines a custom adapter that translates a spec format into Kubb's universal
113
- * AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
114
- * handles OpenAPI/Swagger documents.
55
+ * A factory function that produces a fresh {@link Renderer} per render cycle.
115
56
  *
116
- * Adapters must return an `InputNode` from `parse`. That node is what every
117
- * plugin in the build consumes.
57
+ * Generators use this to declare which renderer handles their output.
58
+ */
59
+ type RendererFactory<TElement = unknown> = () => Renderer<TElement>;
60
+ /**
61
+ * Defines a renderer factory. Renderers turn the generator's return value
62
+ * (JSX, a template string, a tree of any shape) into `FileNode`s that get
63
+ * written to disk.
118
64
  *
119
- * @example
120
- * ```ts
121
- * import { createAdapter, type AdapterFactoryOptions } from '@kubb/core'
122
- * import { ast } from '@kubb/ast'
65
+ * A renderer can target output formats beyond JSX, for instance a Handlebars
66
+ * renderer or one that writes binary files. Plugins and generators pick the
67
+ * renderer to use via the `renderer` field on `defineGenerator`.
123
68
  *
124
- * type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }>
69
+ * @example A minimal renderer that wraps a custom runtime
70
+ * ```ts
71
+ * import { createRenderer } from '@kubb/core'
125
72
  *
126
- * export const myAdapter = createAdapter<MyAdapter>((options) => ({
127
- * name: 'my-adapter',
128
- * options,
129
- * document: null,
130
- * async parse(_source) {
131
- * // Convert the source (path or inline data) into an InputNode.
132
- * return ast.factory.createInput()
133
- * },
134
- * async validate() {
135
- * // Throw here when the spec is invalid.
136
- * },
137
- * }))
73
+ * export const myRenderer = createRenderer(() => {
74
+ * const runtime = new MyRuntime()
75
+ * return {
76
+ * async render(element) {
77
+ * await runtime.render(element)
78
+ * },
79
+ * get files() {
80
+ * return runtime.files
81
+ * },
82
+ * [Symbol.dispose]() {
83
+ * runtime.dispose()
84
+ * },
85
+ * }
86
+ * })
138
87
  * ```
139
88
  */
140
- declare function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T>;
89
+ declare function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement>;
141
90
  //#endregion
142
91
  //#region src/constants.d.ts
143
92
  /**
@@ -926,1212 +875,1048 @@ type Storage = {
926
875
  */
927
876
  declare function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage;
928
877
  //#endregion
929
- //#region src/createRenderer.d.ts
878
+ //#region src/defineParser.d.ts
930
879
  /**
931
- * Minimal interface any Kubb renderer must satisfy.
932
- *
933
- * `TElement` is the type the renderer accepts, for example `KubbReactElement`
934
- * for `@kubb/renderer-jsx` or a custom type for your own renderer. Defaults to
935
- * `unknown` so generators that don't care about the element type work without
936
- * specifying it.
880
+ * Converts a resolved {@link FileNode} into the final source string that gets
881
+ * written to disk. Kubb ships with TypeScript and TSX parsers. Add your own
882
+ * for new file types (JSON, Markdown, ...).
937
883
  */
938
- type Renderer<TElement = unknown> = {
884
+ type Parser<TMeta extends object = object, TNode = unknown, TOptions extends object = object> = ExtensionNamed & {
939
885
  /**
940
- * Renders `element` and populates {@link files} with the resulting {@link FileNode} objects.
941
- * Called once per render cycle. Must resolve before {@link files} is read.
886
+ * The options passed to the parser factory.
942
887
  */
943
- render(element: TElement): Promise<void>;
888
+ options?: TOptions;
944
889
  /**
945
- * Accumulated {@link FileNode} results produced by the last {@link render} call.
890
+ * File extensions this parser handles. The driver registers the parser for each
891
+ * extension in this list. A parser with `undefined` here is not registered, so
892
+ * files of an unclaimed extension fall back to joining their sources verbatim.
893
+ *
894
+ * @example
895
+ * `['.ts', '.js']`
946
896
  */
947
- readonly files: Array<FileNode>;
897
+ extNames: Array<FileNode['extname']> | undefined;
948
898
  /**
949
- * Disposer hook so renderers participate in `using` blocks: `using r = rendererFactory()`
950
- * runs cleanup on every exit path, including thrown errors.
899
+ * Serialize the file's AST into source code.
951
900
  */
952
- [Symbol.dispose](): void;
901
+ parse(file: FileNode<TMeta>): string;
902
+ /**
903
+ * Turn the content of a `copy` file into a file node that `parse` prints. Omit to copy the file verbatim.
904
+ */
905
+ copy?(file: FileNode<TMeta>, source: string): UserFileNode<TMeta>;
906
+ /**
907
+ * Render compiler AST nodes for this parser's language into source text.
908
+ * Plugins call this to format the nodes they assemble before handing them
909
+ * back to the parser as `FileNode.sources`.
910
+ */
911
+ print(...nodes: Array<TNode>): string;
953
912
  };
913
+ type ParserBuild<TOptions extends object, TMeta extends object, TNode> = (options: TOptions) => Omit<Parser<TMeta, TNode>, 'name' | 'meta' | 'options'>;
954
914
  /**
955
- * A factory function that produces a fresh {@link Renderer} per render cycle.
956
- *
957
- * Generators use this to declare which renderer handles their output.
915
+ * The object passed to `defineParser`. `build` receives the user's options and returns the parser methods.
958
916
  */
959
- type RendererFactory<TElement = unknown> = () => Renderer<TElement>;
917
+ type ParserDefinition<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = {
918
+ meta: ExtensionMeta;
919
+ } & ({
920
+ build: ParserBuild<TOptions, TMeta, TNode>;
921
+ } | {
922
+ /**
923
+ * @deprecated Renamed to `build`.
924
+ */
925
+ setup: ParserBuild<TOptions, TMeta, TNode>;
926
+ });
960
927
  /**
961
- * Defines a renderer factory. Renderers turn the generator's return value
962
- * (JSX, a template string, a tree of any shape) into `FileNode`s that get
963
- * written to disk.
964
- *
965
- * A renderer can target output formats beyond JSX, for instance a Handlebars
966
- * renderer or one that writes binary files. Plugins and generators pick the
967
- * renderer to use via the `renderer` field on `defineGenerator`.
968
- *
969
- * @example A minimal renderer that wraps a custom runtime
970
- * ```ts
971
- * import { createRenderer } from '@kubb/core'
972
- *
973
- * export const myRenderer = createRenderer(() => {
974
- * const runtime = new MyRuntime()
975
- * return {
976
- * async render(element) {
977
- * await runtime.render(element)
978
- * },
979
- * get files() {
980
- * return runtime.files
981
- * },
982
- * [Symbol.dispose]() {
983
- * runtime.dispose()
984
- * },
985
- * }
986
- * })
987
- * ```
928
+ * The function `defineParser` returns. Call it with user options to get a `Parser`.
988
929
  */
989
- declare function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement>;
990
- //#endregion
991
- //#region src/defineExtension.d.ts
930
+ type ParserFactory<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = ExtensionFactory<'parser', TOptions, Parser<TMeta, TNode, TOptions>>;
992
931
  /**
993
- * What an extension extends: a plugin generates code, an adapter reads the input, a parser prints files.
932
+ * Defines a parser from one object and returns a factory that takes the user's options.
933
+ * Register the result in the `parsers` array on `defineConfig`.
994
934
  */
995
- type ExtensionKind = 'plugin' | 'adapter' | 'parser';
935
+ declare function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(definition: ParserDefinition<TOptions, TMeta, TNode>): ParserFactory<TOptions, TMeta, TNode>;
996
936
  /**
997
- * Identity and registry data for an extension. Kubb reads `name` and `compatibility` at runtime.
998
- * Studio, the kubb.dev registry, and the docs read the rest.
937
+ * Wraps a factory function that returns a `Parser`. Without `meta`, the parser gets `{ name }`.
938
+ *
939
+ * @deprecated Pass a definition object with `meta` and `build` instead. The factory form is removed in the next major.
999
940
  */
1000
- type ExtensionMeta<TName extends string = string> = {
941
+ declare function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(factory: (options: TOptions) => Parser<TMeta, TNode>): ((options?: TOptions) => Parser<TMeta, TNode>) & {
942
+ kind: 'parser';
943
+ };
944
+ //#endregion
945
+ //#region src/outputManifest.d.ts
946
+ /**
947
+ * Remembers what the output passes did to each generated file, so the next run can tell "the
948
+ * formatter already turned this exact source into what is stored" apart from a real change.
949
+ * Without it the storage compares Kubb's bytes against the formatter's, never matches, and
950
+ * rewrites the whole output tree on every build.
951
+ */
952
+ type OutputManifest = {
1001
953
  /**
1002
- * Unique name, such as `'plugin-ts'`. Becomes the plugin's `name`.
954
+ * `true` when `source` is known to come out of the output passes as exactly the content stored,
955
+ * meaning the write can be skipped.
1003
956
  */
1004
- name: TName;
957
+ isUpToDate(options: {
958
+ key: string;
959
+ source: string;
960
+ disk: string;
961
+ }): boolean;
1005
962
  /**
1006
- * Package version. Dependents check their `version` range against it.
963
+ * Records the source Kubb wrote for `key`, marking it as the only kind of file the output passes
964
+ * can have changed and so the only kind `commit` has to re-read.
1007
965
  */
1008
- version?: string;
1009
- displayName?: string;
966
+ track(options: {
967
+ key: string;
968
+ source: string;
969
+ }): void;
1010
970
  /**
1011
- * One-sentence summary of what the extension generates or does.
971
+ * Re-reads the files written this run and persists their source/output pairs on top of what is
972
+ * stored. Nothing is pruned: a run generating a different set of files, or writing to a different
973
+ * storage in the same root, must not evict what another run recorded.
1012
974
  */
1013
- description?: string;
1014
- category?: string;
1015
- icon?: {
1016
- light: string;
1017
- dark?: string;
1018
- };
1019
- tags?: Array<string>;
1020
- /**
1021
- * Semver ranges the extension supports. A mismatch fails the run with `KUBB_INCOMPATIBLE_EXTENSION`.
1022
- */
1023
- compatibility?: {
1024
- kubb?: string;
1025
- node?: string;
1026
- };
1027
- docs?: string;
1028
- };
1029
- /**
1030
- * An extension's identity: `meta`, a `name`, or both. `name` is deprecated in favor of `meta.name`.
1031
- */
1032
- type ExtensionNamed = {
1033
- name?: string;
1034
- meta?: ExtensionMeta;
1035
- };
1036
- /**
1037
- * Returns `meta`, or `{ name }` for an extension that only sets the deprecated `name`. Throws `KUBB_INVALID_PLUGIN_OPTIONS` when it has neither.
1038
- */
1039
- declare function resolveMeta({ name, meta }: ExtensionNamed): ExtensionMeta;
1040
- /**
1041
- * Sets how Kubb checks one entry in a `dependencies` record.
1042
- */
1043
- type ExtensionDependency = {
1044
- /**
1045
- * Semver range the dependency's `meta.version` must satisfy. Skipped when the dependency has no `meta.version`.
1046
- */
1047
- version?: string;
1048
- /**
1049
- * When `true`, Kubb skips the entry if the plugin is missing, but still checks `version` on an installed one.
1050
- * Otherwise a missing plugin fails the run with `KUBB_MISSING_DEPENDENCY`.
1051
- */
1052
- optional?: boolean;
1053
- };
1054
- /**
1055
- * Plugins an extension builds on, keyed by name, or a function that picks them from the user's options.
1056
- */
1057
- type ExtensionDependencies<TOptions = object> = ExtensionDependencyRecord | {
1058
- resolve(options: TOptions, kubb: {
1059
- config: Config;
1060
- }): ExtensionDependencyRecord;
1061
- }['resolve'];
1062
- /**
1063
- * Maps each dependency's plugin name to how Kubb checks it.
1064
- */
1065
- type ExtensionDependencyRecord = Partial<Record<PluginName, ExtensionDependency>>;
1066
- /**
1067
- * The function an extension definition returns. Call it with user options to get the extension.
1068
- */
1069
- type ExtensionFactory<TKind extends ExtensionKind, TOptions, TExtension, TName extends string = string> = {
1070
- (options?: TOptions): TExtension;
1071
- kind: TKind;
1072
- meta: ExtensionMeta<TName>;
975
+ commit(): Promise<void>;
1073
976
  };
1074
977
  //#endregion
1075
- //#region src/Resolver.d.ts
978
+ //#region src/FileManager.d.ts
1076
979
  /**
1077
- * Context for resolving filtered options for a given operation or schema node.
1078
- *
1079
- * @internal
980
+ * Hooks fired around a `FileManager#write` batch: `start` before it, `update` per file, `end` after.
1080
981
  */
1081
- type ResolveOptionsContext<TOptions> = {
1082
- options: TOptions;
1083
- exclude?: Array<Filter>;
1084
- include?: Array<Filter>;
1085
- override?: Array<Override<TOptions>>;
982
+ type FileManagerHooks = {
983
+ start: [files: Array<FileNode>];
984
+ update: [params: {
985
+ file: FileNode;
986
+ source?: string;
987
+ processed: number;
988
+ total: number;
989
+ percentage: number;
990
+ }];
991
+ end: [files: Array<FileNode>];
1086
992
  };
1087
- /**
1088
- * The built-in resolution machinery exposed on every resolver as `resolver.default`.
1089
- * Plugins delegate to it via `this.default.*` and set their own conventions through
1090
- * the top-level `name` and `file` entries.
1091
- */
1092
- type ResolverDefault = {
993
+ type ParseOptions = {
994
+ parsers?: Map<FileNode['extname'], Parser>;
995
+ };
996
+ type WriteOptions = ParseOptions & {
997
+ storage: Storage;
998
+ signal?: AbortSignal;
1093
999
  /**
1094
- * Built-in camelCase casing for a generated identifier.
1000
+ * Consulted before each write so a file the output passes already normalized is recognized as
1001
+ * unchanged. Omitted when no formatter, linter, or `postGenerate` step is configured.
1095
1002
  */
1096
- name(name: string): string;
1097
- options<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null;
1098
- path(options: ResolvePathOptions): string;
1099
- file(options: ResolveFileOptions): FileNode;
1100
- banner(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
1101
- footer(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
1102
- };
1103
- /**
1104
- * The name request for `resolver.default.path`: a `baseName` plus the optional `tag`/`path` that
1105
- * grouping keys off.
1106
- */
1107
- type ResolverPathParams = Omit<ResolverFileParams, 'name' | 'extname'> & {
1108
- baseName: FileNode['baseName'];
1003
+ manifest?: OutputManifest;
1109
1004
  };
1110
1005
  /**
1111
- * Options for `resolver.default.path`: the name request (`baseName`, `tag`, `path`) plus where the
1112
- * output goes (`root`, `output`, `group`).
1006
+ * In-memory file store for generated files, and the writer that turns them into source
1007
+ * strings on `storage`. Files sharing a `path` are merged (sources/imports/exports
1008
+ * concatenated). The `files` getter is sorted by path length (barrel `index.ts` last
1009
+ * within a bucket).
1113
1010
  *
1114
1011
  * @example
1115
1012
  * ```ts
1116
- * resolver.default.path({ baseName: 'petTypes.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })
1117
- * // → '/src/types/pets/petTypes.ts'
1013
+ * const manager = new FileManager()
1014
+ * manager.upsert(myFile)
1015
+ * manager.files // sorted view
1016
+ * await manager.write(manager.files, { storage: fsStorage() })
1118
1017
  * ```
1119
1018
  */
1120
- type ResolvePathOptions = ResolverPathParams & {
1121
- /**
1122
- * Absolute project root that the output path is resolved against.
1123
- */
1124
- root: string;
1019
+ declare class FileManager {
1020
+ #private;
1021
+ readonly hooks: Hookable<FileManagerHooks>;
1022
+ add(...files: Array<FileNode>): Array<FileNode>;
1023
+ upsert(...files: Array<FileNode>): Array<FileNode>;
1024
+ /** Stores a generator result: a file array is upserted as is, an element renders through `renderer` first, falsy is a no-op. */
1025
+ dispatch<TElement = unknown>({ result, renderer }: {
1026
+ result: TElement | Array<FileNode> | undefined | null;
1027
+ renderer?: RendererFactory<TElement> | null;
1028
+ }): Promise<void>;
1125
1029
  /**
1126
- * Active output config; `output.path` is the base directory.
1030
+ * Releases all stored files and clears every `hooks` listener. Called by the core after
1031
+ * `kubb:build:end`.
1127
1032
  */
1128
- output: Output;
1033
+ dispose(): void;
1129
1034
  /**
1130
- * Optional grouping strategy applied to `tag` (tag grouping) or `path` (path grouping).
1035
+ * All stored files in stable sort order (shortest path first, barrel files
1036
+ * last within a length bucket). Returns a cached view, do not mutate.
1131
1037
  */
1132
- group?: Group;
1133
- };
1134
- /**
1135
- * The file request for `resolver.file` and `resolver.default.file`: the `name` and `extname` plus
1136
- * the optional `tag`/`path` that grouping keys off.
1137
- */
1138
- type ResolverFileParams = {
1139
- name: string;
1140
- extname: FileNode['extname'];
1038
+ get files(): Array<FileNode>;
1141
1039
  /**
1142
- * Tag value used when `group.type === 'tag'`.
1040
+ * Converts a file's AST sources (or its `copy` source) into the final on-disk string.
1143
1041
  */
1144
- tag?: string;
1042
+ parse(file: FileNode, { parsers }?: ParseOptions): Promise<string>;
1145
1043
  /**
1146
- * Path value used when `group.type === 'path'`.
1044
+ * Parses and writes every file through a bounded pool of workers. A small spec runs all its files
1045
+ * at once; a spec with thousands of files keeps at most {@link FILE_CONCURRENCY} parsed sources in
1046
+ * memory rather than holding every source, while still overlapping each file's write with the
1047
+ * next file's parse. Each `update` carries the file's input position, so a consumer can present
1048
+ * the files in generation order even though they finish in whatever order they parse.
1049
+ *
1050
+ * A file the storage already holds is skipped, so a rebuild that generates identical output
1051
+ * writes nothing and leaves every mtime where it was.
1147
1052
  */
1148
- path?: string;
1149
- };
1150
- /**
1151
- * Options for `resolver.file` and `resolver.default.file`: the file request (`name`, `extname`,
1152
- * `tag`, `path`) plus where the output goes (`root`, `output`, `group`).
1153
- *
1154
- * @example
1155
- * ```ts
1156
- * resolver.default.file({ name: 'listPets', extname: '.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })
1157
- * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }
1158
- * ```
1159
- */
1160
- type ResolveFileOptions = ResolverFileParams & {
1161
- root: string;
1162
- output: Output;
1163
- group?: Group;
1164
- };
1165
- /**
1166
- * Options for `resolver.imports`: the schema tree to scan (`node`) and where the generated
1167
- * files live (`root`, `output`, `group`). Pass `name` to override how a referenced schema
1168
- * name becomes the imported identifier; it defaults to the resolver's top-level `name`.
1169
- *
1170
- * @example
1171
- * ```ts
1172
- * resolver.imports({ node, root, output, group })
1173
- * // → [{ kind: 'Import', name: ['pet'], path: '/src/types/pet.ts' }]
1174
- * ```
1175
- */
1176
- type ResolveImportsOptions = {
1053
+ write(files: Array<FileNode>, { storage, parsers, manifest, signal }: WriteOptions): Promise<void>;
1054
+ }
1055
+ //#endregion
1056
+ //#region src/KubbDriver.d.ts
1057
+ type Options = {
1058
+ hooks: Hookable<KubbHooks>;
1059
+ signal?: AbortSignal;
1177
1060
  /**
1178
- * Schema tree scanned for `$ref` occurrences. Each ref contributes one import entry.
1061
+ * Passed to `fileManager.write` so files the output passes already normalized are left alone.
1179
1062
  */
1180
- node: SchemaNode;
1181
- root: string;
1182
- output: Output;
1183
- group?: Group;
1063
+ manifest?: OutputManifest;
1184
1064
  /**
1185
- * Extension of the generated files the imports point at.
1186
- *
1187
- * @default '.ts'
1065
+ * The output directory `output.clean` empties. Emptied right before the files are written, so a
1066
+ * run that fails earlier leaves the previous output in place.
1188
1067
  */
1189
- extname?: FileNode['extname'];
1068
+ cleanPath?: string;
1069
+ };
1070
+ type RequirePluginContext = {
1190
1071
  /**
1191
- * Overrides how a referenced schema name becomes the imported identifier, for example to
1192
- * point enum refs at a suffixed type name. Defaults to the resolver's top-level `name`.
1072
+ * Name of the plugin that declared the dependency, included in the error so users can
1073
+ * trace which plugin needs the missing one.
1193
1074
  */
1194
- name?: (schemaName: string) => string;
1075
+ requiredBy?: string;
1195
1076
  };
1196
- /**
1197
- * The `file` field of a resolver: decides what a generated file is called and, optionally, where
1198
- * it lives. This is how a resolver renames or relocates its files, replacing the older per-call
1199
- * `resolveName` hook.
1200
- *
1201
- * @example Suffix every generated file
1202
- * ```ts
1203
- * file: {
1204
- * baseName({ name, extname }) {
1205
- * return `${name}Faker${extname}`
1206
- * },
1207
- * }
1208
- * ```
1209
- *
1210
- * @example Own the full path
1211
- * ```ts
1212
- * file: {
1213
- * path({ baseName, output }) {
1214
- * return `${output.path}/mocks/${baseName}`
1215
- * },
1216
- * }
1217
- * ```
1218
- */
1219
- type ResolverFile = {
1077
+ declare class KubbDriver {
1078
+ #private;
1079
+ readonly config: Config;
1080
+ readonly options: Options;
1220
1081
  /**
1221
- * Builds the file's complete base name, extension included, from the identifier and the target
1222
- * `extname`. Defaults to `toFilePath(name)` with `extname` appended. Reaches sibling resolver
1223
- * helpers through `this`.
1082
+ * The `InputNode` produced by the adapter. Set after adapter setup.
1224
1083
  */
1225
- baseName?(params: Pick<ResolverFileParams, 'name' | 'extname'>): FileNode['baseName'];
1084
+ inputNode: InputNode | null;
1085
+ adapter: Adapter | null;
1226
1086
  /**
1227
- * Returns the file's complete path, resolved against the project `root`. Bypasses `output.path`
1228
- * and `group`, so the resolver owns the layout. The returned path may not escape `root`. Reaches
1229
- * sibling resolver helpers through `this`.
1230
- */
1231
- path?(params: ResolverFilePathParams): string;
1232
- };
1233
- /**
1234
- * The argument to a resolver's `file.path`: the resolved `baseName` (what `file.baseName` produced,
1235
- * with the extension already appended) and the active `output`. `tag`, `path`, and `group` are
1236
- * omitted because `file.path` owns the whole path and bypasses grouping, and `root` because the
1237
- * returned path is resolved against it.
1238
- */
1239
- type ResolverFilePathParams = {
1240
- baseName: FileNode['baseName'];
1241
- output: Output;
1242
- };
1243
- /**
1244
- * Per-file context describing the file a banner/footer is being resolved for, so a
1245
- * `banner`/`footer` function can branch on the file kind (e.g. skip a `'use server'`
1246
- * directive on re-export files).
1247
- */
1248
- type ResolveBannerFile = {
1249
- /**
1250
- * Full output path of the file being generated.
1251
- */
1252
- path: string;
1253
- /**
1254
- * File name only, e.g. `'stocks.ts'`.
1255
- */
1256
- baseName: string;
1257
- /**
1258
- * `true` for `index.ts` re-export barrels.
1087
+ * Central file store for all generated files.
1088
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
1089
+ * add files. This property gives direct read/write access when needed.
1259
1090
  */
1260
- isBarrel?: boolean;
1091
+ readonly fileManager: FileManager;
1092
+ readonly plugins: Map<string, NormalizedPlugin>;
1093
+ constructor(config: Config, options: Options);
1261
1094
  /**
1262
- * `true` for group `[dir]/[dir].ts` aggregation files.
1095
+ * Checks the adapter's and parsers' `meta.compatibility`, then normalizes and checks every configured plugin, orders them, and registers their lifecycle handlers.
1096
+ * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
1097
+ * `'post'`. When the config has an adapter, the adapter source is resolved from the input
1098
+ * so `run` can parse it later.
1263
1099
  */
1264
- isAggregation?: boolean;
1265
- };
1266
- /**
1267
- * Document metadata extended with per-file context, passed to a `banner`/`footer` function.
1268
- *
1269
- * @example Skip a directive on re-export files
1270
- * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
1271
- */
1272
- type BannerMeta = InputMeta & {
1100
+ setup(): Promise<void>;
1101
+ get hooks(): Hookable<Kubb.KubbHooksRegistry>;
1273
1102
  /**
1274
- * Full output path of the file being generated.
1103
+ * Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
1104
+ * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
1105
+ * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
1106
+ * plugins can configure generators, resolvers, macros, and options before `buildStart`.
1275
1107
  */
1276
- filePath: string;
1108
+ setupHooks(): Promise<void>;
1109
+ /** `true` once `addGenerator()` in `kubb:plugin:setup` registered a generator for the plugin. */
1110
+ hasHookGenerators(pluginName: string): boolean;
1277
1111
  /**
1278
- * File name only, e.g. `'stocks.ts'`.
1112
+ * Runs the full plugin pipeline. Returns the diagnostics collected so far even
1113
+ * when an outer hook throws, since the orchestrator preserves partial state by capturing
1114
+ * the failure as a {@link Diagnostic} instead of propagating. Each plugin also
1115
+ * contributes a `timing` diagnostic for the run summary.
1279
1116
  */
1280
- baseName: string;
1117
+ run(): Promise<{
1118
+ diagnostics: Array<Diagnostic>;
1119
+ }>;
1120
+ /** Stores whatever a generator method or `kubb:generate:*` hook returned, see {@link FileManager.dispatch}. */
1121
+ dispatch<TElement = unknown>(params: {
1122
+ result: TElement | Array<FileNode> | undefined | null;
1123
+ renderer?: RendererFactory<TElement> | null;
1124
+ }): Promise<void>;
1281
1125
  /**
1282
- * `true` for `index.ts` re-export barrels.
1126
+ * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
1127
+ * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
1128
+ *
1129
+ * @internal
1283
1130
  */
1284
- isBarrel: boolean;
1131
+ dispose(): void;
1132
+ [Symbol.dispose](): void;
1133
+ /** Reads `plugin.resolver`, falling back to a fresh default for a name that is not a registered plugin. */
1134
+ getResolver<TName extends PluginName>(pluginName: TName): ResolvePluginOptions<TName>['resolver'];
1135
+ getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): Omit<GeneratorContext<TOptions>, 'options' | 'cache'>;
1136
+ getPlugin<TName extends PluginName>(pluginName: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
1285
1137
  /**
1286
- * `true` for group `[dir]/[dir].ts` aggregation files.
1138
+ * Like `getPlugin` but throws a descriptive error when the plugin is not found.
1287
1139
  */
1288
- isAggregation: boolean;
1289
- };
1140
+ requirePlugin<TName extends PluginName>(pluginName: TName, context?: RequirePluginContext): Plugin<ResolvePluginOptions<TName>>;
1141
+ }
1142
+ //#endregion
1143
+ //#region src/output/runHook.d.ts
1290
1144
  /**
1291
- * Context passed to `resolver.default.banner` and `resolver.default.footer`.
1292
- * `output` is optional since not every plugin configures a banner/footer, and `config`
1293
- * carries the global Kubb config used to derive the default Kubb banner.
1145
+ * Outcome of one hook subprocess, also carried by the `kubb:hook:end` hook it emits.
1294
1146
  */
1295
- type ResolveBannerContext = {
1296
- output?: Pick<Output, 'banner' | 'footer'>;
1297
- config: Config;
1298
- file?: ResolveBannerFile;
1147
+ type HookResult = {
1148
+ success: true;
1149
+ error: null;
1150
+ } | {
1151
+ success: false;
1152
+ error: Error;
1153
+ stdout?: string;
1154
+ stderr?: string;
1299
1155
  };
1300
- /**
1301
- * Raw resolver fields passed to `createResolver` or patched through `Resolver.merge`.
1302
- * `default` is the built-in machinery and is not user-settable.
1303
- */
1304
- type ResolverBuildOptions = {
1305
- pluginName: string;
1306
- name?: (name: string) => string;
1307
- file?: ResolverFile;
1156
+ type RunHookOptions = {
1157
+ hooks: Hookable<KubbHooks>;
1158
+ /** Executable to run, resolved on `PATH` and in every `node_modules/.bin` above `cwd`. */
1159
+ command: string;
1160
+ args?: ReadonlyArray<string>;
1161
+ /** Label shown instead of the command line, for example a `postGenerate` step name. */
1162
+ name?: string;
1163
+ /** Working directory for the command. Defaults to the current process directory. */
1164
+ cwd?: string;
1165
+ signal?: AbortSignal;
1308
1166
  };
1309
1167
  /**
1310
- * Partial resolver fields accepted by `Resolver.merge` and `setResolver`. Parameterize with a
1311
- * concrete resolver type (e.g. `ResolverPatch<ResolverTs>`) to type-check overrides and bind
1312
- * `this` to the full resolver. Namespaces are partial, so a patch may override a single method
1313
- * (`query.name`) and the rest keep the plugin defaults. Overriding a whole resolver is not the
1314
- * job of this patch, that is what a custom plugin is for.
1315
- */
1316
- type ResolverPatch<T extends Resolver = Resolver> = { [K in keyof Omit<T, keyof Resolver>]?: T[K] extends ((...args: Array<never>) => unknown) ? T[K] : Partial<T[K]>; } & {
1317
- imports?: T['imports'];
1318
- name?: T['name'];
1319
- file?: ResolverFile;
1320
- } & ThisType<T>;
1321
- /**
1322
- * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
1323
- * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
1324
- * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
1325
- * reachable and a `file` override is never dropped.
1168
+ * Spawns a command and returns its outcome, announcing it through `kubb:hook:start`,
1169
+ * `kubb:hook:line` (one per stdout or stderr line, only while a listener is attached) and
1170
+ * `kubb:hook:end`. A non-zero exit, a spawn failure, an abort or a throwing line listener returns
1171
+ * `success: false` instead of throwing. The failure travels on the result and `kubb:hook:end`
1172
+ * only, and the caller emits `kubb:success` or a diagnostic, so nothing is reported twice.
1326
1173
  */
1327
- declare const resolverOptions: unique symbol;
1174
+ declare function runHook({ hooks, command, args, name, cwd, signal }: RunHookOptions): Promise<HookResult>;
1175
+ //#endregion
1176
+ //#region src/types.d.ts
1328
1177
  /**
1329
- * Base constraint for all plugin resolver objects.
1178
+ * Source to generate from. Kubb detects what it was given:
1330
1179
  *
1331
- * The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
1332
- * and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
1333
- * top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
1180
+ * - A string that is a local file path (absolute or relative to the config file) or a URL is
1181
+ * read and parsed by the adapter (e.g. an OpenAPI YAML or JSON spec).
1182
+ * - A string that is inline OpenAPI content (JSON or YAML) is parsed directly.
1183
+ * - A parsed object is used as-is, without touching the filesystem.
1334
1184
  *
1335
- * @example Top-level helper
1185
+ * @example
1336
1186
  * ```ts
1337
- * type MyResolver = Resolver & {
1338
- * typeName(name: string): string
1339
- * }
1187
+ * './petstore.yaml' // local path
1188
+ * 'https://example.com/openapi.json' // URL
1189
+ * '{ "openapi": "3.1.0", "info": {...} }' // inline JSON
1190
+ * { openapi: '3.1.0', info: { ... } } // parsed object
1340
1191
  * ```
1192
+ */
1193
+ type Input = string | Record<string, unknown>;
1194
+ /**
1195
+ * A post-generate step: a shell command string, or an object that pairs the command with a `name`
1196
+ * shown in the CLI output. Steps run in sequence after the generated files are formatted and linted.
1197
+ */
1198
+ type PostGenerateCommand = string | {
1199
+ name?: string;
1200
+ command: string;
1201
+ };
1202
+ /**
1203
+ * Resolved build configuration for a Kubb run: what to generate from (adapter, input), where to
1204
+ * write it (output), how (plugins), and the runtime pieces (parsers, storage). See
1205
+ * `UserConfig` for the relaxed form with defaults applied.
1341
1206
  *
1342
- * @example Grouped namespace
1343
- * ```ts
1344
- * type MyResolver = Resolver & {
1345
- * query: {
1346
- * name(node: OperationNode): string
1347
- * keyName(node: OperationNode): string
1348
- * }
1349
- * }
1350
- * ```
1207
+ * @private
1351
1208
  */
1352
- declare class Resolver {
1353
- #private;
1354
- readonly pluginName: string;
1355
- /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
1356
- readonly default: ResolverDefault;
1357
- constructor(options: ResolverBuildOptions);
1358
- /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
1359
- get [resolverOptions](): ResolverBuildOptions;
1360
- name(name: string): string;
1361
- file(options: ResolveFileOptions): FileNode;
1209
+ type Config<TInput = Input> = {
1362
1210
  /**
1363
- * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
1364
- * order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
1365
- * schemas (`targetName`) import the emitted name. Names and paths go through the top-level
1366
- * `name` and `file`, so import entries follow the plugin's conventions, and a per-call
1367
- * `name` override wins over both.
1211
+ * Display name for this configuration in CLI output and logs.
1212
+ * Useful when running multiple builds with `defineConfig` arrays.
1368
1213
  *
1369
- * The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a
1370
- * schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver
1371
- * reads the same ref set instead of re-scanning it per plugin.
1214
+ * @example
1215
+ * ```ts
1216
+ * name: 'api-client'
1217
+ * ```
1372
1218
  */
1373
- imports(options: ResolveImportsOptions): Array<ImportNode>;
1219
+ name?: string;
1374
1220
  /**
1375
- * Folds each `override` over `base`, left to right, and returns a new resolver with helpers
1376
- * re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding
1377
- * `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying
1378
- * `setResolver` partial overrides, and to compose shared resolver fragments without spreading each
1379
- * namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,
1380
- * so a `file` override survives even when `base` and `override` come from different `@kubb/core`
1381
- * copies.
1221
+ * Project root directory, absolute or relative to the config file. Already
1222
+ * resolved on the `Config` instance (see `UserConfig` for the optional
1223
+ * form that defaults to `process.cwd()`).
1224
+ */
1225
+ root: string;
1226
+ /**
1227
+ * Parsers that convert generated files into strings. Each parser handles a
1228
+ * set of file extensions, and a fallback parser handles anything else.
1382
1229
  *
1383
- * @example Fold several partial overrides onto a resolver
1230
+ * Already resolved on the `Config` instance (see `UserConfig` for the
1231
+ * optional form that defaults to `[parserTs(), parserTsx(), parserMd()]`).
1232
+ *
1233
+ * @example
1384
1234
  * ```ts
1385
- * const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })
1235
+ * import { defineConfig } from 'kubb'
1236
+ * import { parserTs, parserTsx } from '@kubb/parser-ts'
1237
+ *
1238
+ * export default defineConfig({
1239
+ * parsers: [parserTs(), parserTsx()],
1240
+ * })
1386
1241
  * ```
1387
1242
  */
1388
- static merge<T extends Resolver>(base: T, ...overrides: Array<ResolverPatch<T> | Resolver>): T;
1389
- }
1390
- //#endregion
1391
- //#region src/definePlugin.d.ts
1392
- /** Reads key `K` from a registry interface, or `{}` when no package has augmented it. @internal */
1393
- type ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {};
1394
- /**
1395
- * A plugin name as accepted by `getPlugin`/`requirePlugin`/`getResolver`. Registered names from
1396
- * `Kubb.PluginRegistry` autocomplete, and any other string is still allowed.
1397
- */
1398
- type PluginName = LiteralUnion<keyof Kubb.PluginRegistry>;
1399
- /**
1400
- * Resolves a plugin name to its `PluginFactoryOptions`. A name registered in `Kubb.PluginRegistry`
1401
- * maps to its exact factory options, any other string falls back to the generic options.
1402
- */
1403
- type ResolvePluginOptions<TName> = TName extends keyof Kubb.PluginRegistry ? Kubb.PluginRegistry[TName] : PluginFactoryOptions;
1404
- /**
1405
- * How a plugin consolidates its generated code into files.
1406
- * - `'file'` writes everything into a single file.
1407
- * - `'directory'` writes one file per operation or schema under `path`.
1408
- */
1409
- type OutputMode = 'directory' | 'file';
1410
- /**
1411
- * Output configuration shared by every plugin. Each plugin extends this with
1412
- * its own keys via the `Kubb.PluginOptionsRegistry.output` interface merge.
1413
- */
1414
- type Output = {
1243
+ parsers: Array<Parser>;
1415
1244
  /**
1416
- * Directory where the plugin writes its generated code, resolved against the global
1417
- * `output.path` set on `defineConfig`. With `mode: 'file'`, this is the full output file
1418
- * path and must include the extension (e.g. `'types.ts'`, `'models.py'`).
1245
+ * Adapter that parses input files into the universal AST representation.
1246
+ * Use `@kubb/adapter-oas` for OpenAPI/Swagger or `@kubb/adapter-asyncapi` for other formats.
1247
+ *
1248
+ * When omitted, Kubb runs in plugin-only mode: `kubb:plugin:setup` fires and files
1249
+ * injected via `injectFile` are written, but no AST walk occurs and generator hooks
1250
+ * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.
1251
+ *
1252
+ * @example
1253
+ * ```ts
1254
+ * import { adapterOas } from '@kubb/adapter-oas'
1255
+ * export default defineConfig({
1256
+ * adapter: adapterOas(),
1257
+ * input: './petstore.yaml',
1258
+ * })
1259
+ * ```
1419
1260
  */
1420
- path: string;
1261
+ adapter?: Adapter;
1421
1262
  /**
1422
- * How generated code is consolidated into files.
1423
- * - `'file'` writes everything into a single file. The `path` must include the file extension.
1424
- * - `'directory'` writes one file per operation or schema under `path`.
1425
- *
1426
- * Defaults to `'file'` when `path` carries an extension and `'directory'` when it does not.
1263
+ * Source to generate code from: a local file path, a URL, inline OpenAPI content
1264
+ * (JSON or YAML string), or a parsed spec object. Kubb detects which one it was given.
1265
+ * Required when an adapter is configured. Omit it when running in plugin-only mode.
1427
1266
  */
1428
- mode?: OutputMode;
1267
+ input?: TInput;
1268
+ output: {
1269
+ /**
1270
+ * Output directory for generated files, absolute or relative to `root`. Plugins can nest
1271
+ * subdirectories under it by grouping strategy (tag, path).
1272
+ *
1273
+ * @example
1274
+ * ```ts
1275
+ * output: {
1276
+ * path: './src/gen', // generates ./src/gen/api.ts, ./src/gen/types.ts, etc.
1277
+ * }
1278
+ * ```
1279
+ */
1280
+ path: string;
1281
+ /**
1282
+ * Remove every file in the output directory before the build, so stale output isn't mixed
1283
+ * with new files. Leave `false` to preserve manual edits in the output directory.
1284
+ *
1285
+ * clean only removes generated code. When `path` resolves to the project root or an ancestor
1286
+ * of it, the build throws instead of wiping `kubb.config` and your source files.
1287
+ *
1288
+ * @example
1289
+ * ```ts
1290
+ * clean: true // wipes ./src/gen/* before generating
1291
+ * ```
1292
+ */
1293
+ clean?: boolean;
1294
+ /**
1295
+ * Format the generated files after generation. `'auto'` runs the first formatter it finds
1296
+ * (oxfmt, biome, or prettier), a named tool forces that one, and `false` skips formatting.
1297
+ *
1298
+ * @example
1299
+ * ```ts
1300
+ * format: 'auto' // auto-detect oxfmt, biome, or prettier
1301
+ * format: 'prettier' // force prettier
1302
+ * format: false // skip formatting
1303
+ * ```
1304
+ */
1305
+ format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false;
1306
+ /**
1307
+ * Lint the generated files after generation. `'auto'` runs the first linter it finds
1308
+ * (oxlint, biome, or eslint), a named tool forces that one, and `false` skips linting.
1309
+ *
1310
+ * @example
1311
+ * ```ts
1312
+ * lint: 'auto' // auto-detect oxlint, biome, or eslint
1313
+ * lint: 'eslint' // force eslint
1314
+ * lint: false // skip linting
1315
+ * ```
1316
+ */
1317
+ lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false;
1318
+ /**
1319
+ * Shell commands to run after the generated files are formatted and linted, for post-processing
1320
+ * such as a type check or a custom script. Steps run in sequence from the `root` directory. Pass
1321
+ * a plain command string, or `{ name, command }` to label the step in the CLI output.
1322
+ *
1323
+ * @example
1324
+ * ```ts
1325
+ * postGenerate: ['npm run typecheck']
1326
+ * postGenerate: [{ name: 'types', command: 'npm run typecheck' }, 'biome check --write ./src/gen']
1327
+ * ```
1328
+ */
1329
+ postGenerate?: Array<PostGenerateCommand>;
1330
+ /**
1331
+ * Banner prepended to every generated file. `'simple'` is the basic Kubb notice, `'full'` adds
1332
+ * source, title, and OpenAPI spec version, and `false` omits it.
1333
+ *
1334
+ * @default 'simple'
1335
+ * @example
1336
+ * ```ts
1337
+ * defaultBanner: 'simple' // "Generated by Kubb (https://kubb.dev/). Do not edit manually."
1338
+ * defaultBanner: 'full' // adds source, title, and OpenAPI spec version
1339
+ * defaultBanner: false // no banner
1340
+ * ```
1341
+ */
1342
+ defaultBanner?: 'simple' | 'full' | false;
1343
+ } & ExtractRegistryKey<Kubb.ConfigOptionsRegistry, 'output'>;
1429
1344
  /**
1430
- * Text prepended to every generated file. Useful for license headers,
1431
- * lint disables, or `@ts-nocheck` directives.
1345
+ * Where generated files are persisted. Defaults to `fsStorage()` (disk). Pass `memoryStorage()`
1346
+ * to keep files in RAM, or implement `Storage` for a custom backend such as cloud or a database.
1432
1347
  *
1433
- * A string is applied to every file (including barrel and aggregation re-export files).
1434
- * Pass a function to compute the banner from the file's `BannerMeta` document metadata
1435
- * plus per-file context (`isBarrel`, `isAggregation`, `filePath`, `baseName`), so you can
1436
- * skip the banner on specific files.
1348
+ * @default fsStorage()
1349
+ * @example
1350
+ * ```ts
1351
+ * import { memoryStorage } from '@kubb/core'
1437
1352
  *
1438
- * @example Add a directive to source files but not re-export files
1439
- * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
1440
- */
1441
- banner?: string | ((meta: BannerMeta) => string);
1442
- /**
1443
- * Text appended at the end of every generated file. Mirror of `banner`.
1444
- * Pass a function to compute the footer from the file's `BannerMeta`.
1353
+ * // Keep generated files in memory (useful for testing, CI pipelines)
1354
+ * storage: memoryStorage()
1355
+ *
1356
+ * // Use custom S3 storage
1357
+ * storage: myS3Storage()
1358
+ * ```
1359
+ *
1360
+ * @see {@link Storage} interface for implementing custom backends.
1445
1361
  */
1446
- footer?: string | ((meta: BannerMeta) => string);
1447
- } & ExtractRegistryKey<Kubb.PluginOptionsRegistry, 'output'>;
1448
- /**
1449
- * Groups generated files into subdirectories based on an OpenAPI tag or path
1450
- * segment.
1451
- */
1452
- type Group = {
1362
+ storage: Storage;
1453
1363
  /**
1454
- * Property used to assign each operation to a group.
1455
- * - `'tag'` uses the first tag (`operation.getTags().at(0)?.name`).
1456
- * - `'path'` uses the first segment of the operation's URL.
1364
+ * Plugins that run during the build to generate code and transform the AST. Each one processes
1365
+ * the adapter's AST and can emit files for a different target (TypeScript, Zod, Faker). A plugin
1366
+ * that depends on another throws when that plugin isn't registered.
1367
+ *
1368
+ * @example
1369
+ * ```ts
1370
+ * import { pluginTs } from '@kubb/plugin-ts'
1371
+ * import { pluginZod } from '@kubb/plugin-zod'
1372
+ *
1373
+ * plugins: [
1374
+ * pluginTs({ output: { path: './src/gen' } }),
1375
+ * pluginZod({ output: { path: './src/gen' } }),
1376
+ * ]
1377
+ * ```
1457
1378
  */
1458
- type: 'tag' | 'path';
1379
+ plugins: Array<Plugin>;
1459
1380
  /**
1460
- * Returns the subdirectory name from the group key. Defaults to the camelCased tag for
1461
- * `tag` groups, or the first path segment as written in the spec for `path` groups.
1381
+ * The reporters available to the run, registered as instances. The host
1382
+ * (the CLI via `--reporter`) selects which ones to trigger by `name` with {@link selectReporters}.
1383
+ * `defineConfig` from the `kubb` package registers the built-in `cli`, `json`, `file`, and
1384
+ * `html` reporters by default.
1385
+ *
1386
+ * - `cli` writes the end-of-run summary to the terminal.
1387
+ * - `json` writes a machine-readable report to stdout, for CI.
1388
+ * - `file` writes a debug log to `.kubb/<name>-<timestamp>.log`.
1389
+ * - `html` writes a static HTML report; opt-in via `--reporter html`.
1390
+ *
1391
+ * @example
1392
+ * ```ts
1393
+ * import { cliReporter, jsonReporter } from '@kubb/core'
1394
+ *
1395
+ * reporters: [cliReporter, jsonReporter, myReporter]
1396
+ * ```
1462
1397
  */
1463
- name?: (context: {
1464
- group: string;
1465
- }) => string;
1398
+ reporters: Array<Reporter>;
1466
1399
  };
1467
1400
  /**
1468
- * Couples `output.mode` with the plugin's `group` option at the type level.
1469
- * - An explicit `mode: 'file'` forbids `group` (a single file has nothing to group).
1470
- * - Omitting `mode`, or setting it to `'directory'`, allows an optional `group`.
1471
- *
1472
- * `mode` is normally inferred from `output.path` (an extension means `'file'`, anything
1473
- * else `'directory'`), so `group` rarely needs `mode` spelled out alongside it. Set
1474
- * `mode: 'directory'` explicitly only to override that inference, such as a directory
1475
- * name that carries a dot (`path: 'clients.v2'`).
1401
+ * Partial `Config` for user-facing entry points with sensible defaults.
1476
1402
  *
1477
- * Intersect into a plugin's `Options` type instead of declaring `output` and
1478
- * `group` directly, since `mode` lives inside `output` while `group` is its sibling.
1479
- * The generic keeps a plugin's extended `Output` shape intact.
1403
+ * `UserConfig` is what you pass to `defineConfig()`. It has optional `root`, `plugins`, `parsers`, and `adapter`
1404
+ * fields (which fall back to sensible defaults). All other Config options are available, including `output`, `input`,
1405
+ * `storage`, and `hooks`.
1480
1406
  *
1481
1407
  * @example
1482
1408
  * ```ts
1483
- * export type Options = OutputOptions & {
1484
- * exclude?: Array<Exclude>
1485
- * }
1409
+ * export default defineConfig({
1410
+ * input: './petstore.yaml',
1411
+ * output: { path: './src/gen' },
1412
+ * plugins: [pluginTs(), pluginZod()],
1413
+ * })
1486
1414
  * ```
1487
1415
  */
1488
- type OutputOptions<TOutput extends Output = Output> = {
1489
- output?: TOutput & {
1490
- mode?: 'directory';
1491
- };
1492
- group?: Group;
1493
- } | {
1494
- output?: TOutput & {
1495
- mode: 'file';
1496
- };
1497
- group?: never;
1498
- };
1499
- /** Throws `KUBB_INVALID_PLUGIN_OPTIONS`, listing the allowed values, when `value` is not one of `allowed`. */
1500
- declare function assertPluginOption({ plugin, option, value, allowed }: {
1501
- plugin: string;
1502
- option: string;
1503
- value: unknown;
1504
- allowed: ReadonlyArray<unknown>;
1505
- }): void;
1506
- type ByTag = {
1416
+ type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter' | 'storage' | 'reporters'> & {
1507
1417
  /**
1508
- * Filter by OpenAPI `tags` field. Matches one or more tags assigned to operations.
1418
+ * Project root directory, absolute or relative to the config file location.
1419
+ * @default process.cwd()
1509
1420
  */
1510
- type: 'tag';
1421
+ root?: string;
1511
1422
  /**
1512
- * Tag name to match (case-sensitive). Can be a literal string or regex pattern.
1513
- */
1514
- pattern: string | RegExp;
1515
- };
1516
- type ByOperationId = {
1423
+ * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).
1424
+ * @default [parserTs(), parserTsx(), parserMd()] // applied by `defineConfig` from the `kubb` package
1425
+ */
1426
+ parsers?: Array<Parser>;
1517
1427
  /**
1518
- * Filter by OpenAPI `operationId` field. Each operation (GET, POST, etc.) has a unique identifier.
1428
+ * Adapter that parses your API specification into Kubb's universal AST.
1429
+ * When omitted, Kubb runs in plugin-only mode.
1519
1430
  */
1520
- type: 'operationId';
1431
+ adapter?: Adapter;
1521
1432
  /**
1522
- * Operation ID to match (case-sensitive). Can be a literal string or regex pattern.
1433
+ * Plugins that execute during the build to generate code and transform the AST.
1434
+ * @default []
1523
1435
  */
1524
- pattern: string | RegExp;
1525
- };
1526
- type ByPath = {
1436
+ plugins?: Array<Plugin>;
1527
1437
  /**
1528
- * Filter by OpenAPI `path` (URL endpoint). Useful to group or filter by service segments like `/pets`, `/users`, etc.
1438
+ * Storage backend that controls where and how generated files are persisted.
1439
+ * @default fsStorage()
1529
1440
  */
1530
- type: 'path';
1441
+ storage?: Storage;
1531
1442
  /**
1532
- * URL path to match (case-sensitive). Can be a literal string or regex pattern. Matches against the full path.
1443
+ * Reporters available to the run. `defineConfig` registers the built-in `cli`, `json`, `file`,
1444
+ * and `html` reporters when omitted.
1445
+ * @default [cliReporter, jsonReporter, fileReporter, htmlReporter] // applied by `defineConfig` from the `kubb` package
1533
1446
  */
1534
- pattern: string | RegExp;
1447
+ reporters?: Array<Reporter>;
1535
1448
  };
1536
- type ByMethod = {
1449
+ declare global {
1450
+ namespace Kubb {
1451
+ /**
1452
+ * Registry that maps plugin names to their `PluginFactoryOptions`.
1453
+ * Augment this interface in each plugin's `types.ts` to enable automatic
1454
+ * typing for `getPlugin` and `requirePlugin`.
1455
+ *
1456
+ * @example
1457
+ * ```ts
1458
+ * // packages/plugin-ts/src/types.ts
1459
+ * declare global {
1460
+ * namespace Kubb {
1461
+ * interface PluginRegistry {
1462
+ * 'plugin-ts': PluginTs
1463
+ * }
1464
+ * }
1465
+ * }
1466
+ * ```
1467
+ */
1468
+ interface PluginRegistry {}
1469
+ /**
1470
+ * Extension point for root `Config['output']` options.
1471
+ * Augment the `output` key in plugin packages to add extra fields
1472
+ * to the global output configuration without touching core types.
1473
+ *
1474
+ * @example
1475
+ * ```ts
1476
+ * // packages/plugin-barrel/src/plugin.ts
1477
+ * declare global {
1478
+ * namespace Kubb {
1479
+ * interface ConfigOptionsRegistry {
1480
+ * output: {
1481
+ * barrel?: import('./types.ts').BarrelConfig | false
1482
+ * }
1483
+ * }
1484
+ * }
1485
+ * }
1486
+ * ```
1487
+ */
1488
+ interface ConfigOptionsRegistry {}
1489
+ /**
1490
+ * Extension point for per-plugin `Output` options.
1491
+ * Augment the `output` key in plugin packages to add extra fields
1492
+ * to the per-plugin output configuration without touching core types.
1493
+ *
1494
+ * @example
1495
+ * ```ts
1496
+ * // packages/plugin-barrel/src/plugin.ts
1497
+ * declare global {
1498
+ * namespace Kubb {
1499
+ * interface PluginOptionsRegistry {
1500
+ * output: {
1501
+ * barrel?: import('./types.ts').PluginBarrelConfig | false
1502
+ * }
1503
+ * }
1504
+ * }
1505
+ * }
1506
+ * ```
1507
+ */
1508
+ interface PluginOptionsRegistry {}
1509
+ /**
1510
+ * Registry of hook names to their listener argument tuples.
1511
+ * Augment this interface to add hook events without touching core types.
1512
+ *
1513
+ * @example
1514
+ * ```ts
1515
+ * // packages/my-plugin/src/hooks.ts
1516
+ * declare global {
1517
+ * namespace Kubb {
1518
+ * interface KubbHooksRegistry {
1519
+ * 'my-plugin:ready': [ctx: { count: number }]
1520
+ * }
1521
+ * }
1522
+ * }
1523
+ * ```
1524
+ */
1525
+ interface KubbHooksRegistry {
1526
+ 'kubb:lifecycle:start': [ctx: KubbLifecycleStartContext];
1527
+ 'kubb:lifecycle:end': [];
1528
+ 'kubb:generation:start': [ctx: KubbGenerationStartContext];
1529
+ 'kubb:generation:end': [ctx: KubbGenerationEndContext];
1530
+ 'kubb:generation:summary': [ctx: KubbGenerationSummaryContext];
1531
+ 'kubb:setup:start': [];
1532
+ 'kubb:setup:end': [];
1533
+ 'kubb:format:start': [];
1534
+ 'kubb:format:end': [];
1535
+ 'kubb:lint:start': [];
1536
+ 'kubb:lint:end': [];
1537
+ 'kubb:hooks:start': [];
1538
+ 'kubb:hooks:end': [];
1539
+ 'kubb:hook:start': [ctx: KubbHookStartContext];
1540
+ 'kubb:hook:line': [ctx: KubbHookLineContext];
1541
+ 'kubb:hook:end': [ctx: KubbHookEndContext];
1542
+ 'kubb:info': [ctx: KubbInfoContext];
1543
+ 'kubb:error': [ctx: KubbErrorContext];
1544
+ 'kubb:success': [ctx: KubbSuccessContext];
1545
+ 'kubb:warn': [ctx: KubbWarnContext];
1546
+ 'kubb:diagnostic': [ctx: KubbDiagnosticContext];
1547
+ 'kubb:files:processing:start': [ctx: KubbFilesProcessingStartContext];
1548
+ 'kubb:files:processing:update': [ctx: KubbFilesProcessingUpdateContext];
1549
+ 'kubb:files:processing:end': [ctx: KubbFilesProcessingEndContext];
1550
+ 'kubb:plugin:start': [ctx: KubbPluginStartContext];
1551
+ 'kubb:plugin:end': [ctx: KubbPluginEndContext];
1552
+ 'kubb:plugin:setup': [ctx: KubbPluginSetupContext];
1553
+ 'kubb:build:start': [ctx: KubbBuildStartContext];
1554
+ 'kubb:plugins:end': [ctx: KubbPluginsEndContext];
1555
+ 'kubb:build:end': [ctx: KubbBuildEndContext];
1556
+ 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext];
1557
+ 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext];
1558
+ 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext];
1559
+ }
1560
+ }
1561
+ }
1562
+ /**
1563
+ * Lifecycle hooks emitted during Kubb code generation.
1564
+ * Attach listeners before calling `setup()` or `build()` to observe and react to build progress.
1565
+ *
1566
+ * A package can add its own hook names to this type by augmenting
1567
+ * {@link Kubb.KubbHooksRegistry} instead of exporting a second, separate hook type. Studio's
1568
+ * connection and RPC hooks intentionally use its separate `StudioHooks` registry.
1569
+ *
1570
+ * @example
1571
+ * ```ts
1572
+ * kubb.hooks.hook('kubb:lifecycle:start', () => {
1573
+ * console.log('Starting Kubb generation')
1574
+ * })
1575
+ *
1576
+ * kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => {
1577
+ * console.log(`${plugin.name} completed in ${duration}ms`)
1578
+ * })
1579
+ * ```
1580
+ */
1581
+ type KubbHooks = Kubb.KubbHooksRegistry;
1582
+ /** The file access every file-carrying hook context shares: a lazy snapshot of the files so far, and a way to add more. */
1583
+ type FilesContext = {
1584
+ /** Snapshot of all files accumulated so far, including those added by plugins that already ran. */
1585
+ readonly files: ReadonlyArray<FileNode>;
1586
+ /** Adds or merges one or more files into the file manager. */
1587
+ upsertFile: (...files: Array<FileNode>) => void;
1588
+ };
1589
+ type KubbBuildStartContext = FilesContext & {
1537
1590
  /**
1538
- * Filter by HTTP method: `'GET'`, `'POST'`, `'PUT'`, `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`.
1591
+ * Resolved configuration for this build.
1539
1592
  */
1540
- type: 'method';
1593
+ config: Config;
1541
1594
  /**
1542
- * HTTP method to match, as one of the `HttpMethod` values (`'GET'`, `'POST'`, `'PUT'`,
1543
- * `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`) or a regex.
1595
+ * Adapter that parsed the input into the universal AST.
1544
1596
  */
1545
- pattern: HttpMethod | RegExp;
1597
+ adapter: Adapter;
1598
+ /**
1599
+ * Metadata about the parsed document (title, version, base URL, circular schema names, enum names).
1600
+ * To observe individual schemas and operations use the `kubb:generate:schema` / `kubb:generate:operation` hooks.
1601
+ */
1602
+ meta: InputMeta | undefined;
1603
+ /**
1604
+ * Looks up a registered plugin by name, typed by the plugin registry.
1605
+ */
1606
+ getPlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
1546
1607
  };
1547
- type BySchemaName = {
1608
+ type KubbPluginsEndContext = FilesContext & {
1548
1609
  /**
1549
- * Filter by schema component name (TypeScript or JSON schema). Matches schemas in `#/components/schemas`.
1610
+ * Resolved configuration for this build.
1550
1611
  */
1551
- type: 'schemaName';
1612
+ config: Config;
1613
+ };
1614
+ type KubbBuildEndContext = {
1552
1615
  /**
1553
- * Schema name to match (case-sensitive). Can be a literal string or regex pattern.
1616
+ * All files generated during this build.
1554
1617
  */
1555
- pattern: string | RegExp;
1618
+ files: Array<FileNode>;
1619
+ /**
1620
+ * Resolved configuration for this build.
1621
+ */
1622
+ config: Config;
1623
+ /**
1624
+ * Absolute path to the output directory.
1625
+ */
1626
+ outputDir: string;
1556
1627
  };
1557
- type ByContentType = {
1628
+ type KubbLifecycleStartContext = {
1558
1629
  /**
1559
- * Filter by response or request content type: `'application/json'`, `'application/xml'`, etc.
1630
+ * Current Kubb version string.
1560
1631
  */
1561
- type: 'contentType';
1632
+ version: string;
1633
+ };
1634
+ type KubbGenerationStartContext = {
1562
1635
  /**
1563
- * Content type to match (case-sensitive). Can be a literal string or regex pattern.
1636
+ * Resolved configuration for this generation run.
1564
1637
  */
1565
- pattern: string | RegExp;
1638
+ config: Config;
1566
1639
  };
1567
- /**
1568
- * Pattern filter for include, exclude, and override rules. Matches operations or schemas
1569
- * by tag, operationId, path, method, content type, or schema name.
1570
- */
1571
- type Filter = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
1572
- /**
1573
- * Filter that skips matching operations or schemas during generation, for example
1574
- * deprecated endpoints or internal-only schemas.
1575
- *
1576
- * @example
1577
- * ```ts
1578
- * exclude: [
1579
- * { type: 'tag', pattern: 'internal' },
1580
- * { type: 'path', pattern: /^\/admin/ },
1581
- * { type: 'operationId', pattern: /^deprecated_/ },
1582
- * ]
1583
- * ```
1584
- */
1585
- type Exclude$1 = Filter;
1586
- /**
1587
- * Filter that restricts generation to operations or schemas matching at least
1588
- * one entry. Useful for partial builds (one tag, one API version).
1589
- *
1590
- * @example
1591
- * ```ts
1592
- * include: [
1593
- * { type: 'tag', pattern: 'public' },
1594
- * { type: 'path', pattern: /^\/api\/v1/ },
1595
- * ]
1596
- * ```
1597
- */
1598
- type Include = Filter;
1599
- /**
1600
- * Filter paired with a partial options object. When the filter matches, the
1601
- * options are merged on top of the plugin defaults for that operation only.
1602
- * Useful for "this one tag goes to a different folder" rules.
1603
- *
1604
- * Entries are evaluated top to bottom. The first matching entry wins.
1605
- *
1606
- * @example
1607
- * ```ts
1608
- * override: [
1609
- * {
1610
- * type: 'tag',
1611
- * pattern: 'admin',
1612
- * options: { output: { path: './src/gen/admin' } },
1613
- * },
1614
- * {
1615
- * type: 'operationId',
1616
- * pattern: 'listPets',
1617
- * options: { enumType: 'literal' },
1618
- * },
1619
- * ]
1620
- * ```
1621
- */
1622
- type Override<TOptions> = Filter & {
1623
- options: Omit<Partial<TOptions>, 'override'>;
1624
- };
1625
- type PluginFactoryOptions<
1626
- /**
1627
- * Unique plugin name.
1628
- */
1629
- TName extends string = string,
1630
- /**
1631
- * User-facing plugin options.
1632
- */
1633
- TOptions extends object = object,
1634
- /**
1635
- * Plugin options after defaults are applied.
1636
- */
1637
- TResolvedOptions extends object = TOptions,
1638
- /**
1639
- * Resolver that encapsulates naming and path-resolution helpers.
1640
- * Define with `createResolver` and export alongside the plugin.
1641
- */
1642
- TResolver extends Resolver = Resolver> = {
1643
- name: TName;
1644
- options: TOptions;
1645
- resolvedOptions: TResolvedOptions;
1646
- resolver: TResolver;
1647
- };
1648
- /**
1649
- * Type parameter for the object form of `definePlugin`. Same shape as `PluginFactoryOptions`.
1650
- */
1651
- type PluginType<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TResolver extends Resolver = Resolver> = PluginFactoryOptions<TName, TOptions, TResolvedOptions, TResolver>;
1652
- /**
1653
- * Context passed to a plugin's `kubb:plugin:setup` handler, where it registers generators and
1654
- * sets its resolver, transformer, and options.
1655
- */
1656
- type KubbPluginSetupContext<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
1640
+ type KubbGenerationEndContext = {
1657
1641
  /**
1658
- * Register one or more generators dynamically. Generators fire during the AST walk
1659
- * (schema/operation/operations) just like generators declared statically on `createPlugin`.
1642
+ * Resolved configuration for this generation run.
1643
+ */
1644
+ config: Config;
1645
+ /**
1646
+ * Read-only view of the files written during this build.
1647
+ * Reads go directly to `config.storage`, nothing extra is held in memory.
1660
1648
  *
1661
- * Pass generators as separate arguments. Spread an existing list to register it in one call.
1649
+ * @example Read a generated file
1650
+ * `const code = await storage.readItem('/src/gen/pet.ts')`
1662
1651
  *
1663
- * @example
1652
+ * @example Walk every generated file
1664
1653
  * ```ts
1665
- * ctx.addGenerator(myGenerator)
1666
- * ctx.addGenerator(schemaGenerator, operationGenerator)
1667
- * ctx.addGenerator(...selectedGenerators)
1654
+ * for (const path of await storage.readKeys()) {
1655
+ * const code = await storage.readItem(path)
1656
+ * }
1668
1657
  * ```
1669
1658
  */
1670
- addGenerator<TElement = unknown>(...generators: Array<Generator<TFactory, TElement>>): void;
1659
+ storage: Storage;
1671
1660
  /**
1672
- * Set or override the resolver for this plugin.
1673
- * The resolver controls file naming and path resolution. Overrides merge over the built-in
1674
- * defaults, so a partial `core` or a single namespace method replaces only what it names.
1661
+ * Diagnostics collected during the build: error/warning/info problems plus a
1662
+ * `performance` diagnostic per plugin. The end-of-run summary derives its failure counts
1663
+ * and per-plugin timings from these. Set by the CLI runner, omitted by other callers.
1675
1664
  */
1676
- setResolver(resolver: ResolverPatch<TFactory['resolver']> | TFactory['resolver']): void;
1665
+ diagnostics?: Array<Diagnostic>;
1677
1666
  /**
1678
- * Add a macro that rewrites AST nodes before they reach generators. Macros run in the order they
1679
- * are added, after any macros from earlier `addMacro` calls.
1667
+ * `'success'` when all plugins completed without errors, `'failed'` otherwise.
1680
1668
  */
1681
- addMacro(macro: Macro): void;
1669
+ status?: 'success' | 'failed';
1682
1670
  /**
1683
- * Replace this plugin's macros with `macros`.
1671
+ * High-resolution start time from `process.hrtime()`, used to compute the elapsed time.
1684
1672
  */
1685
- setMacros(macros: ReadonlyArray<Macro>): void;
1673
+ hrStart?: [number, number];
1686
1674
  /**
1687
- * Set resolved options merged into the normalized plugin's `options`.
1688
- * Call this in `kubb:plugin:setup` to provide options generators need.
1675
+ * Total number of files created during this run.
1689
1676
  */
1690
- setOptions(options: TFactory['resolvedOptions']): void;
1677
+ filesCreated?: number;
1678
+ };
1679
+ /** A human-readable message with optional detail, as carried by `kubb:info`, `kubb:success`, and `kubb:warn`. */
1680
+ type KubbMessageContext = {
1691
1681
  /**
1692
- * Inject a raw file into the build output, bypassing the generation pipeline.
1693
- *
1694
- * Pass `copy` with an absolute path to emit a real source file (a shipped template) into the
1695
- * generated folder, instead of building its content from `sources`.
1682
+ * Human-readable message.
1696
1683
  */
1697
- injectFile(userFileNode: UserFileNode): void;
1698
- /** Returns a plugin this one needs, or fails the run with `KUBB_PLUGIN_NOT_FOUND` when the config lacks it. */
1699
- requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>;
1684
+ message: string;
1700
1685
  /**
1701
- * The resolved build configuration at setup time.
1686
+ * Optional supplementary detail.
1687
+ */
1688
+ info?: string;
1689
+ };
1690
+ type KubbInfoContext = KubbMessageContext;
1691
+ type KubbSuccessContext = KubbMessageContext;
1692
+ type KubbWarnContext = KubbMessageContext;
1693
+ type KubbErrorContext = {
1694
+ /**
1695
+ * The caught error.
1696
+ */
1697
+ error: Error;
1698
+ /**
1699
+ * Optional structured metadata for additional context.
1700
+ */
1701
+ meta?: Record<string, unknown>;
1702
+ };
1703
+ type KubbDiagnosticContext = {
1704
+ /**
1705
+ * The structured diagnostic to render: a build problem or a version-update notice.
1706
+ */
1707
+ diagnostic: ProblemDiagnostic | UpdateDiagnostic;
1708
+ };
1709
+ type KubbGenerationSummaryContext = {
1710
+ duration: number;
1711
+ fileCount: number;
1712
+ failedPlugins: number;
1713
+ status: 'success' | 'failed';
1714
+ };
1715
+ type KubbFilesProcessingStartContext = {
1716
+ /**
1717
+ * Files about to be serialized and written.
1718
+ */
1719
+ files: Array<FileNode>;
1720
+ };
1721
+ type KubbFileProcessingUpdate = {
1722
+ /**
1723
+ * Number of files processed so far in this batch.
1724
+ */
1725
+ processed: number;
1726
+ /**
1727
+ * Total number of files in this batch.
1728
+ */
1729
+ total: number;
1730
+ /**
1731
+ * Completion percentage, `0` to `100`.
1732
+ */
1733
+ percentage: number;
1734
+ /**
1735
+ * The file that was just processed.
1736
+ */
1737
+ file: FileNode;
1738
+ /**
1739
+ * Resolved configuration for this build.
1702
1740
  */
1703
1741
  config: Config;
1742
+ };
1743
+ type KubbFilesProcessingUpdateContext = {
1704
1744
  /**
1705
- * The plugin's user-provided options.
1745
+ * All files processed in this flush chunk.
1706
1746
  */
1707
- options: TFactory['options'];
1747
+ files: Array<KubbFileProcessingUpdate>;
1708
1748
  };
1709
- /**
1710
- * A plugin object produced by `definePlugin`. Its lifecycle handlers live under a single
1711
- * `hooks` property rather than flat methods.
1712
- */
1713
- type Plugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = ExtensionNamed & {
1749
+ type KubbFilesProcessingEndContext = {
1714
1750
  /**
1715
- * Plugins this one builds on. They run first when the config has them. An array only orders
1716
- * plugins. A record also fails the run when a required entry is missing or out of range.
1751
+ * All files that were serialized in this batch.
1717
1752
  */
1718
- dependencies?: Array<PluginName> | ExtensionDependencies<TFactory['options']>;
1753
+ files: Array<FileNode>;
1754
+ };
1755
+ type KubbHookStartContext = {
1719
1756
  /**
1720
- * Controls the execution order of this plugin relative to others.
1721
- *
1722
- * - `'pre'` runs before all normal plugins.
1723
- * - `'post'` runs after all normal plugins.
1724
- * - `undefined` (default) runs in declaration order among normal plugins.
1725
- *
1726
- * Dependency constraints always take precedence over `enforce`.
1757
+ * Optional identifier for correlating start/end hooks.
1727
1758
  */
1728
- enforce?: Enforce;
1759
+ id?: string;
1729
1760
  /**
1730
- * The options passed by the user when calling the plugin factory.
1761
+ * The shell command that is about to run.
1731
1762
  */
1732
- options?: TFactory['options'];
1763
+ command: string;
1733
1764
  /**
1734
- * Lifecycle hook handlers for this plugin.
1735
- * Any hook from the global `KubbHooks` map can be subscribed to here.
1765
+ * Optional label for the command, shown in the CLI output when set.
1736
1766
  */
1737
- hooks: { [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void>; } & {
1738
- 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
1739
- };
1767
+ name?: string;
1740
1768
  /**
1741
- * Runs before `kubb:plugin:setup`. Takes the user's options and returns the resolved options.
1769
+ * Parsed argument list, when available.
1742
1770
  */
1743
- setup?(options: TFactory['options'], kubb: KubbPluginSetupContext<TFactory>): TFactory['resolvedOptions'] | Promise<TFactory['resolvedOptions']>;
1771
+ args?: ReadonlyArray<string>;
1744
1772
  };
1745
1773
  /**
1746
- * The object passed to `definePlugin`.
1774
+ * Emitted for each line streamed from a hook's stdout while it runs.
1775
+ * A logger correlates the line to its active UI element via `id`.
1747
1776
  */
1748
- type PluginDefinition<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = Pick<Plugin<TFactory>, 'dependencies' | 'enforce' | 'setup'> & {
1749
- meta: ExtensionMeta<TFactory['name']>;
1750
- hooks?: Plugin<TFactory>['hooks'];
1777
+ type KubbHookLineContext = {
1778
+ /**
1779
+ * Identifier matching the corresponding `kubb:hook:start` hook.
1780
+ */
1781
+ id: string;
1782
+ /**
1783
+ * A single streamed stdout line, without its trailing newline.
1784
+ */
1785
+ line: string;
1751
1786
  };
1787
+ /** Emitted when a hook subprocess ends: its `kubb:hook:start` context plus the outcome. */
1788
+ type KubbHookEndContext = KubbHookStartContext & HookResult;
1752
1789
  /**
1753
- * The function `definePlugin` returns. Call it with user options to get a `Plugin`.
1790
+ * CLI options derived from command-line flags.
1754
1791
  */
1755
- type PluginFactory<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = ExtensionFactory<'plugin', TFactory['options'], Plugin<TFactory>, TFactory['name']>;
1792
+ type CLIOptions = {
1793
+ /**
1794
+ * Path to the Kubb config file.
1795
+ */
1796
+ config?: string;
1797
+ /**
1798
+ * OpenAPI input path or URL passed as the positional argument to `kubb generate`.
1799
+ * Overrides `config.input` when set.
1800
+ */
1801
+ input?: string;
1802
+ /**
1803
+ * Re-run generation whenever input files change.
1804
+ */
1805
+ watch?: boolean;
1806
+ /**
1807
+ * Controls how much output the CLI prints.
1808
+ *
1809
+ * @default 'info'
1810
+ */
1811
+ logLevel?: 'silent' | 'info' | 'verbose';
1812
+ /**
1813
+ * Reporters selected on the CLI via `--reporter`, overriding `config.reporters`.
1814
+ */
1815
+ reporters?: Array<ReporterName>;
1816
+ };
1756
1817
  /**
1757
- * Normalized plugin after setup, with runtime fields populated. Internal only. Plugins use the
1758
- * public `Plugin` type.
1759
- *
1760
- * @internal
1761
- */
1762
- type NormalizedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & {
1763
- name: string;
1764
- meta: ExtensionMeta;
1765
- dependencies?: Array<PluginName> | ExtensionDependencyRecord;
1766
- options: TOptions['resolvedOptions'] & {
1767
- output: Output;
1768
- include?: Array<Include>;
1769
- exclude: Array<Exclude$1>;
1770
- override: Array<Override<TOptions['resolvedOptions']>>;
1771
- };
1772
- resolver: TOptions['resolver'];
1773
- macros?: Array<Macro>;
1774
- generators?: Array<Generator>;
1775
- };
1776
- type KubbPluginStartContext = {
1777
- plugin: NormalizedPlugin;
1778
- };
1779
- type KubbPluginEndContext = FilesContext & {
1780
- plugin: NormalizedPlugin;
1781
- duration: number;
1782
- success: boolean;
1783
- error?: Error;
1784
- config: Config;
1785
- };
1786
- /**
1787
- * Defines a plugin from one object and returns a factory that takes the user's options.
1788
- * Name plugins `plugin-<feature>`.
1789
- *
1790
- * @example
1791
- * ```ts
1792
- * export const pluginZod = definePlugin<PluginZod>({
1793
- * meta: { name: 'plugin-zod', compatibility: { kubb: '>=5.7.0' } },
1794
- * dependencies: { 'plugin-ts': { optional: true } },
1795
- * setup(options, kubb) {
1796
- * kubb.addGenerator(zodGenerator)
1797
- * return { ...options, inferred: options.inferred ?? false }
1798
- * },
1799
- * })
1800
- * ```
1801
- */
1802
- declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(definition: PluginDefinition<TFactory>): PluginFactory<TFactory>;
1803
- /**
1804
- * Wraps a factory function that returns a `Plugin`. Without `meta`, the plugin gets `{ name }`.
1805
- *
1806
- * @deprecated Pass a definition object with `meta` and `setup` instead. The factory form is removed in the next major.
1818
+ * All accepted forms of a Kubb configuration.
1819
+ * Accepts `Config`/`Config[]`/promise or a factory (optionally receiving `TCliOptions`).
1807
1820
  */
1808
- declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(factory: (options: TFactory['options']) => Plugin<TFactory>): ((options?: TFactory['options']) => Plugin<TFactory>) & {
1809
- kind: 'plugin';
1810
- };
1811
- //#endregion
1812
- //#region src/defineParser.d.ts
1821
+ type PossibleConfig<TCliOptions = undefined> = PossiblePromise<Config | Array<Config>> | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Array<Config>>);
1813
1822
  /**
1814
- * Converts a resolved {@link FileNode} into the final source string that gets
1815
- * written to disk. Kubb ships with TypeScript and TSX parsers. Add your own
1816
- * for new file types (JSON, Markdown, ...).
1823
+ * Full output produced by a successful or failed build.
1817
1824
  */
1818
- type Parser<TMeta extends object = object, TNode = unknown> = ExtensionNamed & {
1825
+ type BuildOutput = {
1819
1826
  /**
1820
- * File extensions this parser handles. The driver registers the parser for each
1821
- * extension in this list. A parser with `undefined` here is not registered, so
1822
- * files of an unclaimed extension fall back to joining their sources verbatim.
1823
- *
1824
- * @example
1825
- * `['.ts', '.js']`
1827
+ * Structured diagnostics collected during the build: error/warning/info problems
1828
+ * (each with a code, severity, and where known a JSON-pointer location) plus a
1829
+ * `performance` diagnostic per plugin. Includes a top-level diagnostic when the build
1830
+ * threw before completing. Use {@link Diagnostics.hasError} to test for failure.
1826
1831
  */
1827
- extNames: Array<FileNode['extname']> | undefined;
1832
+ diagnostics: Array<Diagnostic>;
1828
1833
  /**
1829
- * Serialize the file's AST into source code.
1834
+ * All files generated during this build.
1830
1835
  */
1831
- parse(file: FileNode<TMeta>): string;
1836
+ files: Array<FileNode>;
1832
1837
  /**
1833
- * Turn the content of a `copy` file into a file node that `parse` prints. Omit to copy the file verbatim.
1838
+ * The plugin driver that orchestrated this build.
1834
1839
  */
1835
- copy?(file: FileNode<TMeta>, source: string): UserFileNode<TMeta>;
1840
+ driver: KubbDriver;
1836
1841
  /**
1837
- * Render compiler AST nodes for this parser's language into source text.
1838
- * Plugins call this to format the nodes they assemble before handing them
1839
- * back to the parser as `FileNode.sources`.
1842
+ * The configured `Storage` backend, for reading back a generated file's final content.
1843
+ * Use `files` to list what this build produced.
1844
+ *
1845
+ * @example Read a generated file
1846
+ * `const code = await buildOutput.storage.readItem('/src/gen/pet.ts')`
1840
1847
  */
1841
- print(...nodes: Array<TNode>): string;
1842
- };
1843
- /**
1844
- * The object passed to `defineParser`. `setup` receives the user's options and returns the parser methods.
1845
- */
1846
- type ParserDefinition<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = {
1847
- meta: ExtensionMeta;
1848
- setup(options: TOptions): Omit<Parser<TMeta, TNode>, 'name' | 'meta'>;
1849
- };
1850
- /**
1851
- * The function `defineParser` returns. Call it with user options to get a `Parser`.
1852
- */
1853
- type ParserFactory<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = ExtensionFactory<'parser', TOptions, Parser<TMeta, TNode>>;
1854
- /**
1855
- * Defines a parser from one object and returns a factory that takes the user's options.
1856
- * Register the result in the `parsers` array on `defineConfig`.
1857
- */
1858
- declare function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(definition: ParserDefinition<TOptions, TMeta, TNode>): ParserFactory<TOptions, TMeta, TNode>;
1859
- /**
1860
- * Wraps a factory function that returns a `Parser`. Without `meta`, the parser gets `{ name }`.
1861
- *
1862
- * @deprecated Pass a definition object with `meta` and `setup` instead. The factory form is removed in the next major.
1863
- */
1864
- declare function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(factory: (options: TOptions) => Parser<TMeta, TNode>): ((options?: TOptions) => Parser<TMeta, TNode>) & {
1865
- kind: 'parser';
1848
+ storage: Storage;
1866
1849
  };
1867
1850
  //#endregion
1868
- //#region src/outputManifest.d.ts
1851
+ //#region src/nodeCache.d.ts
1869
1852
  /**
1870
- * Remembers what the output passes did to each generated file, so the next run can tell "the
1871
- * formatter already turned this exact source into what is stored" apart from a real change.
1872
- * Without it the storage compares Kubb's bytes against the formatter's, never matches, and
1873
- * rewrites the whole output tree on every build.
1853
+ * Per-node memo shared by every plugin that generates from the same schema or operation node in
1854
+ * one generate pass. The driver creates one `NodeCache` per node during the walk and hands the
1855
+ * same instance to each plugin's generator context, so work derived purely from the node (its
1856
+ * resolved name, imports, parameters) is computed by the first plugin that needs it and reused by
1857
+ * the rest instead of being recomputed per plugin.
1858
+ *
1859
+ * Keys are namespaced by convention (`'plugin-ts:imports'`) so two plugins caching different
1860
+ * derivations of the same node never collide.
1861
+ *
1862
+ * @example Fill on first read, reuse afterwards
1863
+ * ```ts
1864
+ * const imports = ctx.cache.ensureItem('plugin-ts:imports', () => ctx.resolver.imports({ node, root, output }))
1865
+ * ```
1874
1866
  */
1875
- type OutputManifest = {
1867
+ type NodeCache = {
1876
1868
  /**
1877
- * `true` when `source` is known to come out of the output passes as exactly the content stored,
1878
- * meaning the write can be skipped.
1869
+ * Returns the value stored under `key`, or `undefined` when nothing is stored yet.
1879
1870
  */
1880
- isUpToDate(options: {
1881
- key: string;
1882
- source: string;
1883
- disk: string;
1884
- }): boolean;
1871
+ readItem<TValue>(key: string): TValue | undefined;
1885
1872
  /**
1886
- * Records the source Kubb wrote for `key`, marking it as the only kind of file the output passes
1887
- * can have changed and so the only kind `commit` has to re-read.
1873
+ * Stores `value` under `key`, overwriting any previous value, and returns it.
1888
1874
  */
1889
- track(options: {
1890
- key: string;
1891
- source: string;
1892
- }): void;
1875
+ writeItem<TValue>(key: string, value: TValue): TValue;
1893
1876
  /**
1894
- * Re-reads the files written this run and persists their source/output pairs on top of what is
1895
- * stored. Nothing is pruned: a run generating a different set of files, or writing to a different
1896
- * storage in the same root, must not evict what another run recorded.
1877
+ * Returns the value stored under `key`, computing and storing it with `factory` on the first
1878
+ * call. Later calls with the same key return the stored value without running `factory` again.
1897
1879
  */
1898
- commit(): Promise<void>;
1880
+ ensureItem<TValue>(key: string, factory: () => TValue): TValue;
1899
1881
  };
1900
1882
  //#endregion
1901
- //#region src/FileManager.d.ts
1883
+ //#region src/defineGenerator.d.ts
1902
1884
  /**
1903
- * Hooks fired around a `FileManager#write` batch: `start` before it, `update` per file, `end` after.
1885
+ * Context passed to a generator's `schema`, `operation`, and `operations` methods.
1886
+ *
1887
+ * The driver sets `adapter` on the context before it runs a generator, so methods can read it
1888
+ * without a null check. `ctx.options` carries the per-node options after exclude/include/override
1889
+ * filtering for `schema` and `operation`, or the plugin-level options for `operations`.
1904
1890
  */
1905
- type FileManagerHooks = {
1906
- start: [files: Array<FileNode>];
1907
- update: [params: {
1908
- file: FileNode;
1909
- source?: string;
1910
- processed: number;
1911
- total: number;
1912
- percentage: number;
1913
- }];
1914
- end: [files: Array<FileNode>];
1915
- };
1916
- type ParseOptions = {
1917
- parsers?: Map<FileNode['extname'], Parser>;
1918
- };
1919
- type WriteOptions = ParseOptions & {
1920
- storage: Storage;
1921
- signal?: AbortSignal;
1891
+ type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1922
1892
  /**
1923
- * Consulted before each write so a file the output passes already normalized is recognized as
1924
- * unchanged. Omitted when no formatter, linter, or `postGenerate` step is configured.
1893
+ * Stops cooperative generation work at the next safe checkpoint.
1925
1894
  */
1926
- manifest?: OutputManifest;
1927
- };
1928
- /**
1929
- * In-memory file store for generated files, and the writer that turns them into source
1930
- * strings on `storage`. Files sharing a `path` are merged (sources/imports/exports
1931
- * concatenated). The `files` getter is sorted by path length (barrel `index.ts` last
1932
- * within a bucket).
1933
- *
1934
- * @example
1935
- * ```ts
1936
- * const manager = new FileManager()
1937
- * manager.upsert(myFile)
1938
- * manager.files // sorted view
1939
- * await manager.write(manager.files, { storage: fsStorage() })
1940
- * ```
1941
- */
1942
- declare class FileManager {
1943
- #private;
1944
- readonly hooks: Hookable<FileManagerHooks>;
1945
- add(...files: Array<FileNode>): Array<FileNode>;
1946
- upsert(...files: Array<FileNode>): Array<FileNode>;
1947
- /** Stores a generator result: a file array is upserted as is, an element renders through `renderer` first, falsy is a no-op. */
1948
- dispatch<TElement = unknown>({ result, renderer }: {
1949
- result: TElement | Array<FileNode> | undefined | null;
1950
- renderer?: RendererFactory<TElement> | null;
1951
- }): Promise<void>;
1895
+ signal?: AbortSignal;
1952
1896
  /**
1953
- * Releases all stored files and clears every `hooks` listener. Called by the core after
1954
- * `kubb:build:end`.
1897
+ * The resolved Kubb config for this build, including `root`, `input`, `output`, and the
1898
+ * full plugin list.
1955
1899
  */
1956
- dispose(): void;
1900
+ config: Config;
1957
1901
  /**
1958
- * All stored files in stable sort order (shortest path first, barrel files
1959
- * last within a length bucket). Returns a cached view, do not mutate.
1902
+ * Absolute path to the current plugin's output directory.
1960
1903
  */
1961
- get files(): Array<FileNode>;
1904
+ root: string;
1962
1905
  /**
1963
- * Converts a file's AST sources (or its `copy` source) into the final on-disk string.
1906
+ * The driver running this build. Most generators never need it. Prefer the scoped helpers
1907
+ * on this context (`getPlugin`, `getResolver`, `upsertFile`) over reaching into the driver.
1964
1908
  */
1965
- parse(file: FileNode, { parsers }?: ParseOptions): Promise<string>;
1909
+ driver: KubbDriver;
1966
1910
  /**
1967
- * Parses and writes every file through a bounded pool of workers. A small spec runs all its files
1968
- * at once; a spec with thousands of files keeps at most {@link FILE_CONCURRENCY} parsed sources in
1969
- * memory rather than holding every source, while still overlapping each file's write with the
1970
- * next file's parse. Each `update` carries the file's input position, so a consumer can present
1971
- * the files in generation order even though they finish in whatever order they parse.
1972
- *
1973
- * A file the storage already holds is skipped, so a rebuild that generates identical output
1974
- * writes nothing and leaves every mtime where it was.
1911
+ * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
1975
1912
  */
1976
- write(files: Array<FileNode>, { storage, parsers, manifest, signal }: WriteOptions): Promise<void>;
1977
- }
1978
- //#endregion
1979
- //#region src/KubbDriver.d.ts
1980
- type Options = {
1981
- hooks: Hookable<KubbHooks>;
1982
- signal?: AbortSignal;
1913
+ getPlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
1983
1914
  /**
1984
- * Passed to `fileManager.write` so files the output passes already normalized are left alone.
1915
+ * Get a plugin by name, throws an error if not found.
1985
1916
  */
1986
- manifest?: OutputManifest;
1917
+ requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>;
1987
1918
  /**
1988
- * The output directory `output.clean` empties. Emptied right before the files are written, so a
1989
- * run that fails earlier leaves the previous output in place.
1990
- */
1991
- cleanPath?: string;
1992
- };
1993
- type RequirePluginContext = {
1994
- /**
1995
- * Name of the plugin that declared the dependency, included in the error so users can
1996
- * trace which plugin needs the missing one.
1997
- */
1998
- requiredBy?: string;
1999
- };
2000
- declare class KubbDriver {
2001
- #private;
2002
- readonly config: Config;
2003
- readonly options: Options;
2004
- /**
2005
- * The `InputNode` produced by the adapter. Set after adapter setup.
2006
- */
2007
- inputNode: InputNode | null;
2008
- adapter: Adapter | null;
2009
- /**
2010
- * Central file store for all generated files.
2011
- * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
2012
- * add files. This property gives direct read/write access when needed.
2013
- */
2014
- readonly fileManager: FileManager;
2015
- readonly plugins: Map<string, NormalizedPlugin>;
2016
- constructor(config: Config, options: Options);
2017
- /**
2018
- * Normalizes and checks every configured plugin, orders them, and registers their lifecycle handlers.
2019
- * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
2020
- * `'post'`. When the config has an adapter, the adapter source is resolved from the input
2021
- * so `run` can parse it later.
2022
- */
2023
- setup(): Promise<void>;
2024
- get hooks(): Hookable<Kubb.KubbHooksRegistry>;
2025
- /**
2026
- * Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
2027
- * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
2028
- * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
2029
- * plugins can configure generators, resolvers, macros, and options before `buildStart`.
2030
- */
2031
- setupHooks(): Promise<void>;
2032
- /** `true` once `addGenerator()` in `kubb:plugin:setup` registered a generator for the plugin. */
2033
- hasHookGenerators(pluginName: string): boolean;
2034
- /**
2035
- * Runs the full plugin pipeline. Returns the diagnostics collected so far even
2036
- * when an outer hook throws, since the orchestrator preserves partial state by capturing
2037
- * the failure as a {@link Diagnostic} instead of propagating. Each plugin also
2038
- * contributes a `timing` diagnostic for the run summary.
2039
- */
2040
- run(): Promise<{
2041
- diagnostics: Array<Diagnostic>;
2042
- }>;
2043
- /** Stores whatever a generator method or `kubb:generate:*` hook returned, see {@link FileManager.dispatch}. */
2044
- dispatch<TElement = unknown>(params: {
2045
- result: TElement | Array<FileNode> | undefined | null;
2046
- renderer?: RendererFactory<TElement> | null;
2047
- }): Promise<void>;
2048
- /**
2049
- * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
2050
- * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
2051
- *
2052
- * @internal
2053
- */
2054
- dispose(): void;
2055
- [Symbol.dispose](): void;
2056
- /** Reads `plugin.resolver`, falling back to a fresh default for a name that is not a registered plugin. */
2057
- getResolver<TName extends PluginName>(pluginName: TName): ResolvePluginOptions<TName>['resolver'];
2058
- getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): Omit<GeneratorContext<TOptions>, 'options' | 'cache'>;
2059
- getPlugin<TName extends PluginName>(pluginName: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
2060
- /**
2061
- * Like `getPlugin` but throws a descriptive error when the plugin is not found.
2062
- */
2063
- requirePlugin<TName extends PluginName>(pluginName: TName, context?: RequirePluginContext): Plugin<ResolvePluginOptions<TName>>;
2064
- }
2065
- //#endregion
2066
- //#region src/nodeCache.d.ts
2067
- /**
2068
- * Per-node memo shared by every plugin that generates from the same schema or operation node in
2069
- * one generate pass. The driver creates one `NodeCache` per node during the walk and hands the
2070
- * same instance to each plugin's generator context, so work derived purely from the node (its
2071
- * resolved name, imports, parameters) is computed by the first plugin that needs it and reused by
2072
- * the rest instead of being recomputed per plugin.
2073
- *
2074
- * Keys are namespaced by convention (`'plugin-ts:imports'`) so two plugins caching different
2075
- * derivations of the same node never collide.
2076
- *
2077
- * @example Fill on first read, reuse afterwards
2078
- * ```ts
2079
- * const imports = ctx.cache.ensureItem('plugin-ts:imports', () => ctx.resolver.imports({ node, root, output }))
2080
- * ```
2081
- */
2082
- type NodeCache = {
2083
- /**
2084
- * Returns the value stored under `key`, or `undefined` when nothing is stored yet.
2085
- */
2086
- readItem<TValue>(key: string): TValue | undefined;
2087
- /**
2088
- * Stores `value` under `key`, overwriting any previous value, and returns it.
2089
- */
2090
- writeItem<TValue>(key: string, value: TValue): TValue;
2091
- /**
2092
- * Returns the value stored under `key`, computing and storing it with `factory` on the first
2093
- * call. Later calls with the same key return the stored value without running `factory` again.
2094
- */
2095
- ensureItem<TValue>(key: string, factory: () => TValue): TValue;
2096
- };
2097
- //#endregion
2098
- //#region src/defineGenerator.d.ts
2099
- /**
2100
- * Context passed to a generator's `schema`, `operation`, and `operations` methods.
2101
- *
2102
- * The driver sets `adapter` on the context before it runs a generator, so methods can read it
2103
- * without a null check. `ctx.options` carries the per-node options after exclude/include/override
2104
- * filtering for `schema` and `operation`, or the plugin-level options for `operations`.
2105
- */
2106
- type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
2107
- /**
2108
- * Stops cooperative generation work at the next safe checkpoint.
2109
- */
2110
- signal?: AbortSignal;
2111
- /**
2112
- * The resolved Kubb config for this build, including `root`, `input`, `output`, and the
2113
- * full plugin list.
2114
- */
2115
- config: Config;
2116
- /**
2117
- * Absolute path to the current plugin's output directory.
2118
- */
2119
- root: string;
2120
- /**
2121
- * The driver running this build. Most generators never need it. Prefer the scoped helpers
2122
- * on this context (`getPlugin`, `getResolver`, `upsertFile`) over reaching into the driver.
2123
- */
2124
- driver: KubbDriver;
2125
- /**
2126
- * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
2127
- */
2128
- getPlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
2129
- /**
2130
- * Get a plugin by name, throws an error if not found.
2131
- */
2132
- requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>;
2133
- /**
2134
- * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.
1919
+ * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.
2135
1920
  */
2136
1921
  getResolver<TName extends PluginName>(name: TName): ResolvePluginOptions<TName>['resolver'];
2137
1922
  /**
@@ -2321,713 +2106,975 @@ type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TEl
2321
2106
  */
2322
2107
  declare function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(generator: Generator<TOptions, TElement>): Generator<TOptions, TElement>;
2323
2108
  //#endregion
2324
- //#region src/output/runHook.d.ts
2109
+ //#region src/Resolver.d.ts
2325
2110
  /**
2326
- * Outcome of one hook subprocess, also carried by the `kubb:hook:end` hook it emits.
2111
+ * Context for resolving filtered options for a given operation or schema node.
2112
+ *
2113
+ * @internal
2327
2114
  */
2328
- type HookResult = {
2329
- success: true;
2330
- error: null;
2331
- } | {
2332
- success: false;
2333
- error: Error;
2334
- stdout?: string;
2335
- stderr?: string;
2115
+ type ResolveOptionsContext<TOptions> = {
2116
+ options: TOptions;
2117
+ exclude?: Array<Filter>;
2118
+ include?: Array<Filter>;
2119
+ override?: Array<Override<TOptions>>;
2336
2120
  };
2337
- type RunHookOptions = {
2338
- hooks: Hookable<KubbHooks>;
2339
- /** Executable to run, resolved on `PATH` and in every `node_modules/.bin` above `cwd`. */
2340
- command: string;
2341
- args?: ReadonlyArray<string>;
2342
- /** Label shown instead of the command line, for example a `postGenerate` step name. */
2343
- name?: string;
2344
- /** Working directory for the command. Defaults to the current process directory. */
2345
- cwd?: string;
2346
- signal?: AbortSignal;
2121
+ /**
2122
+ * The built-in resolution machinery exposed on every resolver as `resolver.default`.
2123
+ * Plugins delegate to it via `this.default.*` and set their own conventions through
2124
+ * the top-level `name` and `file` entries.
2125
+ */
2126
+ type ResolverDefault = {
2127
+ /**
2128
+ * Built-in camelCase casing for a generated identifier.
2129
+ */
2130
+ name(name: string): string;
2131
+ options<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null;
2132
+ path(options: ResolvePathOptions): string;
2133
+ file(options: ResolveFileOptions): FileNode;
2134
+ banner(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
2135
+ footer(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
2347
2136
  };
2348
2137
  /**
2349
- * Spawns a command and returns its outcome, announcing it through `kubb:hook:start`,
2350
- * `kubb:hook:line` (one per stdout or stderr line, only while a listener is attached) and
2351
- * `kubb:hook:end`. A non-zero exit, a spawn failure, an abort or a throwing line listener returns
2352
- * `success: false` instead of throwing. The failure travels on the result and `kubb:hook:end`
2353
- * only, and the caller emits `kubb:success` or a diagnostic, so nothing is reported twice.
2138
+ * The name request for `resolver.default.path`: a `baseName` plus the optional `tag`/`path` that
2139
+ * grouping keys off.
2354
2140
  */
2355
- declare function runHook({ hooks, command, args, name, cwd, signal }: RunHookOptions): Promise<HookResult>;
2356
- //#endregion
2357
- //#region src/types.d.ts
2141
+ type ResolverPathParams = Omit<ResolverFileParams, 'name' | 'extname'> & {
2142
+ baseName: FileNode['baseName'];
2143
+ };
2358
2144
  /**
2359
- * Source to generate from. Kubb detects what it was given:
2360
- *
2361
- * - A string that is a local file path (absolute or relative to the config file) or a URL is
2362
- * read and parsed by the adapter (e.g. an OpenAPI YAML or JSON spec).
2363
- * - A string that is inline OpenAPI content (JSON or YAML) is parsed directly.
2364
- * - A parsed object is used as-is, without touching the filesystem.
2145
+ * Options for `resolver.default.path`: the name request (`baseName`, `tag`, `path`) plus where the
2146
+ * output goes (`root`, `output`, `group`).
2365
2147
  *
2366
2148
  * @example
2367
2149
  * ```ts
2368
- * './petstore.yaml' // local path
2369
- * 'https://example.com/openapi.json' // URL
2370
- * '{ "openapi": "3.1.0", "info": {...} }' // inline JSON
2371
- * { openapi: '3.1.0', info: { ... } } // parsed object
2150
+ * resolver.default.path({ baseName: 'petTypes.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })
2151
+ * // → '/src/types/pets/petTypes.ts'
2372
2152
  * ```
2373
2153
  */
2374
- type Input = string | Record<string, unknown>;
2375
- /**
2376
- * A post-generate step: a shell command string, or an object that pairs the command with a `name`
2377
- * shown in the CLI output. Steps run in sequence after the generated files are formatted and linted.
2378
- */
2379
- type PostGenerateCommand = string | {
2380
- name?: string;
2381
- command: string;
2154
+ type ResolvePathOptions = ResolverPathParams & {
2155
+ /**
2156
+ * Absolute project root that the output path is resolved against.
2157
+ */
2158
+ root: string;
2159
+ /**
2160
+ * Active output config; `output.path` is the base directory.
2161
+ */
2162
+ output: Output;
2163
+ /**
2164
+ * Optional grouping strategy applied to `tag` (tag grouping) or `path` (path grouping).
2165
+ */
2166
+ group?: Group;
2382
2167
  };
2383
2168
  /**
2384
- * Resolved build configuration for a Kubb run: what to generate from (adapter, input), where to
2385
- * write it (output), how (plugins), and the runtime pieces (parsers, storage). See
2386
- * `UserConfig` for the relaxed form with defaults applied.
2387
- *
2388
- * @private
2169
+ * The file request for `resolver.file` and `resolver.default.file`: the `name` and `extname` plus
2170
+ * the optional `tag`/`path` that grouping keys off.
2389
2171
  */
2390
- type Config<TInput = Input> = {
2172
+ type ResolverFileParams = {
2173
+ name: string;
2174
+ extname: FileNode['extname'];
2391
2175
  /**
2392
- * Display name for this configuration in CLI output and logs.
2393
- * Useful when running multiple builds with `defineConfig` arrays.
2394
- *
2395
- * @example
2396
- * ```ts
2397
- * name: 'api-client'
2398
- * ```
2176
+ * Tag value used when `group.type === 'tag'`.
2399
2177
  */
2400
- name?: string;
2178
+ tag?: string;
2401
2179
  /**
2402
- * Project root directory, absolute or relative to the config file. Already
2403
- * resolved on the `Config` instance (see `UserConfig` for the optional
2404
- * form that defaults to `process.cwd()`).
2180
+ * Path value used when `group.type === 'path'`.
2405
2181
  */
2182
+ path?: string;
2183
+ };
2184
+ /**
2185
+ * Options for `resolver.file` and `resolver.default.file`: the file request (`name`, `extname`,
2186
+ * `tag`, `path`) plus where the output goes (`root`, `output`, `group`).
2187
+ *
2188
+ * @example
2189
+ * ```ts
2190
+ * resolver.default.file({ name: 'listPets', extname: '.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })
2191
+ * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }
2192
+ * ```
2193
+ */
2194
+ type ResolveFileOptions = ResolverFileParams & {
2406
2195
  root: string;
2196
+ output: Output;
2197
+ group?: Group;
2198
+ };
2199
+ /**
2200
+ * Options for `resolver.imports`: the schema tree to scan (`node`) and where the generated
2201
+ * files live (`root`, `output`, `group`). Pass `name` to override how a referenced schema
2202
+ * name becomes the imported identifier; it defaults to the resolver's top-level `name`.
2203
+ *
2204
+ * @example
2205
+ * ```ts
2206
+ * resolver.imports({ node, root, output, group })
2207
+ * // → [{ kind: 'Import', name: ['pet'], path: '/src/types/pet.ts' }]
2208
+ * ```
2209
+ */
2210
+ type ResolveImportsOptions = {
2407
2211
  /**
2408
- * Parsers that convert generated files into strings. Each parser handles a
2409
- * set of file extensions, and a fallback parser handles anything else.
2410
- *
2411
- * Already resolved on the `Config` instance (see `UserConfig` for the
2412
- * optional form that defaults to `[parserTs(), parserTsx(), parserMd()]`).
2413
- *
2414
- * @example
2415
- * ```ts
2416
- * import { defineConfig } from 'kubb'
2417
- * import { parserTs, parserTsx } from '@kubb/parser-ts'
2212
+ * Schema tree scanned for `$ref` occurrences. Each ref contributes one import entry.
2213
+ */
2214
+ node: SchemaNode;
2215
+ root: string;
2216
+ output: Output;
2217
+ group?: Group;
2218
+ /**
2219
+ * Extension of the generated files the imports point at.
2418
2220
  *
2419
- * export default defineConfig({
2420
- * parsers: [parserTs(), parserTsx()],
2421
- * })
2422
- * ```
2221
+ * @default '.ts'
2423
2222
  */
2424
- parsers: Array<Parser>;
2223
+ extname?: FileNode['extname'];
2425
2224
  /**
2426
- * Adapter that parses input files into the universal AST representation.
2427
- * Use `@kubb/adapter-oas` for OpenAPI/Swagger or `@kubb/adapter-asyncapi` for other formats.
2225
+ * Overrides how a referenced schema name becomes the imported identifier, for example to
2226
+ * point enum refs at a suffixed type name. Defaults to the resolver's top-level `name`.
2227
+ */
2228
+ name?: (schemaName: string) => string;
2229
+ };
2230
+ /**
2231
+ * The `file` field of a resolver: decides what a generated file is called and, optionally, where
2232
+ * it lives. This is how a resolver renames or relocates its files, replacing the older per-call
2233
+ * `resolveName` hook.
2234
+ *
2235
+ * @example Suffix every generated file
2236
+ * ```ts
2237
+ * file: {
2238
+ * baseName({ name, extname }) {
2239
+ * return `${name}Faker${extname}`
2240
+ * },
2241
+ * }
2242
+ * ```
2243
+ *
2244
+ * @example Own the full path
2245
+ * ```ts
2246
+ * file: {
2247
+ * path({ baseName, output }) {
2248
+ * return `${output.path}/mocks/${baseName}`
2249
+ * },
2250
+ * }
2251
+ * ```
2252
+ */
2253
+ type ResolverFile = {
2254
+ /**
2255
+ * Builds the file's complete base name, extension included, from the identifier and the target
2256
+ * `extname`. Defaults to `toFilePath(name)` with `extname` appended. Reaches sibling resolver
2257
+ * helpers through `this`.
2258
+ */
2259
+ baseName?(params: Pick<ResolverFileParams, 'name' | 'extname'>): FileNode['baseName'];
2260
+ /**
2261
+ * Returns the file's complete path, resolved against the project `root`. Bypasses `output.path`
2262
+ * and `group`, so the resolver owns the layout. The returned path may not escape `root`. Reaches
2263
+ * sibling resolver helpers through `this`.
2264
+ */
2265
+ path?(params: ResolverFilePathParams): string;
2266
+ };
2267
+ /**
2268
+ * The argument to a resolver's `file.path`: the resolved `baseName` (what `file.baseName` produced,
2269
+ * with the extension already appended) and the active `output`. `tag`, `path`, and `group` are
2270
+ * omitted because `file.path` owns the whole path and bypasses grouping, and `root` because the
2271
+ * returned path is resolved against it.
2272
+ */
2273
+ type ResolverFilePathParams = {
2274
+ baseName: FileNode['baseName'];
2275
+ output: Output;
2276
+ };
2277
+ /**
2278
+ * Per-file context describing the file a banner/footer is being resolved for, so a
2279
+ * `banner`/`footer` function can branch on the file kind (e.g. skip a `'use server'`
2280
+ * directive on re-export files).
2281
+ */
2282
+ type ResolveBannerFile = {
2283
+ /**
2284
+ * Full output path of the file being generated.
2285
+ */
2286
+ path: string;
2287
+ /**
2288
+ * File name only, e.g. `'stocks.ts'`.
2289
+ */
2290
+ baseName: string;
2291
+ /**
2292
+ * `true` for `index.ts` re-export barrels.
2293
+ */
2294
+ isBarrel?: boolean;
2295
+ /**
2296
+ * `true` for group `[dir]/[dir].ts` aggregation files.
2297
+ */
2298
+ isAggregation?: boolean;
2299
+ };
2300
+ /**
2301
+ * Document metadata extended with per-file context, passed to a `banner`/`footer` function.
2302
+ *
2303
+ * @example Skip a directive on re-export files
2304
+ * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
2305
+ */
2306
+ type BannerMeta = InputMeta & {
2307
+ /**
2308
+ * Full output path of the file being generated.
2309
+ */
2310
+ filePath: string;
2311
+ /**
2312
+ * File name only, e.g. `'stocks.ts'`.
2313
+ */
2314
+ baseName: string;
2315
+ /**
2316
+ * `true` for `index.ts` re-export barrels.
2317
+ */
2318
+ isBarrel: boolean;
2319
+ /**
2320
+ * `true` for group `[dir]/[dir].ts` aggregation files.
2321
+ */
2322
+ isAggregation: boolean;
2323
+ };
2324
+ /**
2325
+ * Context passed to `resolver.default.banner` and `resolver.default.footer`.
2326
+ * `output` is optional since not every plugin configures a banner/footer, and `config`
2327
+ * carries the global Kubb config used to derive the default Kubb banner.
2328
+ */
2329
+ type ResolveBannerContext = {
2330
+ output?: Pick<Output, 'banner' | 'footer'>;
2331
+ config: Config;
2332
+ file?: ResolveBannerFile;
2333
+ };
2334
+ /**
2335
+ * Raw resolver fields passed to `createResolver` or patched through `Resolver.merge`.
2336
+ * `default` is the built-in machinery and is not user-settable.
2337
+ */
2338
+ type ResolverBuildOptions = {
2339
+ pluginName: string;
2340
+ name?: (name: string) => string;
2341
+ file?: ResolverFile;
2342
+ };
2343
+ /**
2344
+ * Partial resolver fields accepted by `Resolver.merge` and `setResolver`. Parameterize with a
2345
+ * concrete resolver type (e.g. `ResolverPatch<ResolverTs>`) to type-check overrides and bind
2346
+ * `this` to the full resolver. Namespaces are partial, so a patch may override a single method
2347
+ * (`query.name`) and the rest keep the plugin defaults. Overriding a whole resolver is not the
2348
+ * job of this patch, that is what a custom plugin is for.
2349
+ */
2350
+ type ResolverPatch<T extends Resolver = Resolver> = { [K in keyof Omit<T, keyof Resolver>]?: T[K] extends ((...args: Array<never>) => unknown) ? T[K] : Partial<T[K]>; } & {
2351
+ imports?: T['imports'];
2352
+ name?: T['name'];
2353
+ file?: ResolverFile;
2354
+ } & ThisType<T>;
2355
+ /**
2356
+ * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
2357
+ * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
2358
+ * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
2359
+ * reachable and a `file` override is never dropped.
2360
+ */
2361
+ declare const resolverOptions: unique symbol;
2362
+ /**
2363
+ * Base constraint for all plugin resolver objects.
2364
+ *
2365
+ * The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
2366
+ * and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
2367
+ * top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
2368
+ *
2369
+ * @example Top-level helper
2370
+ * ```ts
2371
+ * type MyResolver = Resolver & {
2372
+ * typeName(name: string): string
2373
+ * }
2374
+ * ```
2375
+ *
2376
+ * @example Grouped namespace
2377
+ * ```ts
2378
+ * type MyResolver = Resolver & {
2379
+ * query: {
2380
+ * name(node: OperationNode): string
2381
+ * keyName(node: OperationNode): string
2382
+ * }
2383
+ * }
2384
+ * ```
2385
+ */
2386
+ declare class Resolver {
2387
+ #private;
2388
+ readonly pluginName: string;
2389
+ /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
2390
+ readonly default: ResolverDefault;
2391
+ constructor(options: ResolverBuildOptions);
2392
+ /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
2393
+ get [resolverOptions](): ResolverBuildOptions;
2394
+ name(name: string): string;
2395
+ file(options: ResolveFileOptions): FileNode;
2396
+ /**
2397
+ * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
2398
+ * order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
2399
+ * schemas (`targetName`) import the emitted name. Names and paths go through the top-level
2400
+ * `name` and `file`, so import entries follow the plugin's conventions, and a per-call
2401
+ * `name` override wins over both.
2428
2402
  *
2429
- * When omitted, Kubb runs in plugin-only mode: `kubb:plugin:setup` fires and files
2430
- * injected via `injectFile` are written, but no AST walk occurs and generator hooks
2431
- * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.
2403
+ * The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a
2404
+ * schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver
2405
+ * reads the same ref set instead of re-scanning it per plugin.
2406
+ */
2407
+ imports(options: ResolveImportsOptions): Array<ImportNode>;
2408
+ /**
2409
+ * Folds each `override` over `base`, left to right, and returns a new resolver with helpers
2410
+ * re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding
2411
+ * `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying
2412
+ * `setResolver` partial overrides, and to compose shared resolver fragments without spreading each
2413
+ * namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,
2414
+ * so a `file` override survives even when `base` and `override` come from different `@kubb/core`
2415
+ * copies.
2432
2416
  *
2433
- * @example
2417
+ * @example Fold several partial overrides onto a resolver
2434
2418
  * ```ts
2435
- * import { adapterOas } from '@kubb/adapter-oas'
2436
- * export default defineConfig({
2437
- * adapter: adapterOas(),
2438
- * input: './petstore.yaml',
2439
- * })
2419
+ * const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })
2440
2420
  * ```
2441
2421
  */
2442
- adapter?: Adapter;
2422
+ static merge<T extends Resolver>(base: T, ...overrides: Array<ResolverPatch<T> | Resolver>): T;
2423
+ }
2424
+ //#endregion
2425
+ //#region src/definePlugin.d.ts
2426
+ /** Reads key `K` from a registry interface, or `{}` when no package has augmented it. @internal */
2427
+ type ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {};
2428
+ /**
2429
+ * A plugin name as accepted by `getPlugin`/`requirePlugin`/`getResolver`. Registered names from
2430
+ * `Kubb.PluginRegistry` autocomplete, and any other string is still allowed.
2431
+ */
2432
+ type PluginName = LiteralUnion<keyof Kubb.PluginRegistry>;
2433
+ /**
2434
+ * Resolves a plugin name to its `PluginFactoryOptions`. A name registered in `Kubb.PluginRegistry`
2435
+ * maps to its exact factory options, any other string falls back to the generic options.
2436
+ */
2437
+ type ResolvePluginOptions<TName> = TName extends keyof Kubb.PluginRegistry ? Kubb.PluginRegistry[TName] : PluginFactoryOptions;
2438
+ /**
2439
+ * How a plugin consolidates its generated code into files.
2440
+ * - `'file'` writes everything into a single file.
2441
+ * - `'directory'` writes one file per operation or schema under `path`.
2442
+ */
2443
+ type OutputMode = 'directory' | 'file';
2444
+ /**
2445
+ * Output configuration shared by every plugin. Each plugin extends this with
2446
+ * its own keys via the `Kubb.PluginOptionsRegistry.output` interface merge.
2447
+ */
2448
+ type Output = {
2443
2449
  /**
2444
- * Source to generate code from: a local file path, a URL, inline OpenAPI content
2445
- * (JSON or YAML string), or a parsed spec object. Kubb detects which one it was given.
2446
- * Required when an adapter is configured. Omit it when running in plugin-only mode.
2450
+ * Directory where the plugin writes its generated code, resolved against the global
2451
+ * `output.path` set on `defineConfig`. With `mode: 'file'`, this is the full output file
2452
+ * path and must include the extension (e.g. `'types.ts'`, `'models.py'`).
2447
2453
  */
2448
- input?: TInput;
2449
- output: {
2450
- /**
2451
- * Output directory for generated files, absolute or relative to `root`. Plugins can nest
2452
- * subdirectories under it by grouping strategy (tag, path).
2453
- *
2454
- * @example
2455
- * ```ts
2456
- * output: {
2457
- * path: './src/gen', // generates ./src/gen/api.ts, ./src/gen/types.ts, etc.
2458
- * }
2459
- * ```
2460
- */
2461
- path: string;
2462
- /**
2463
- * Remove every file in the output directory before the build, so stale output isn't mixed
2464
- * with new files. Leave `false` to preserve manual edits in the output directory.
2465
- *
2466
- * clean only removes generated code. When `path` resolves to the project root or an ancestor
2467
- * of it, the build throws instead of wiping `kubb.config` and your source files.
2468
- *
2469
- * @example
2470
- * ```ts
2471
- * clean: true // wipes ./src/gen/* before generating
2472
- * ```
2473
- */
2474
- clean?: boolean;
2475
- /**
2476
- * Format the generated files after generation. `'auto'` runs the first formatter it finds
2477
- * (oxfmt, biome, or prettier), a named tool forces that one, and `false` skips formatting.
2478
- *
2479
- * @example
2480
- * ```ts
2481
- * format: 'auto' // auto-detect oxfmt, biome, or prettier
2482
- * format: 'prettier' // force prettier
2483
- * format: false // skip formatting
2484
- * ```
2485
- */
2486
- format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false;
2487
- /**
2488
- * Lint the generated files after generation. `'auto'` runs the first linter it finds
2489
- * (oxlint, biome, or eslint), a named tool forces that one, and `false` skips linting.
2490
- *
2491
- * @example
2492
- * ```ts
2493
- * lint: 'auto' // auto-detect oxlint, biome, or eslint
2494
- * lint: 'eslint' // force eslint
2495
- * lint: false // skip linting
2496
- * ```
2497
- */
2498
- lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false;
2499
- /**
2500
- * Shell commands to run after the generated files are formatted and linted, for post-processing
2501
- * such as a type check or a custom script. Steps run in sequence from the `root` directory. Pass
2502
- * a plain command string, or `{ name, command }` to label the step in the CLI output.
2503
- *
2504
- * @example
2505
- * ```ts
2506
- * postGenerate: ['npm run typecheck']
2507
- * postGenerate: [{ name: 'types', command: 'npm run typecheck' }, 'biome check --write ./src/gen']
2508
- * ```
2509
- */
2510
- postGenerate?: Array<PostGenerateCommand>;
2511
- /**
2512
- * Banner prepended to every generated file. `'simple'` is the basic Kubb notice, `'full'` adds
2513
- * source, title, and OpenAPI spec version, and `false` omits it.
2514
- *
2515
- * @default 'simple'
2516
- * @example
2517
- * ```ts
2518
- * defaultBanner: 'simple' // "Generated by Kubb (https://kubb.dev/). Do not edit manually."
2519
- * defaultBanner: 'full' // adds source, title, and OpenAPI spec version
2520
- * defaultBanner: false // no banner
2521
- * ```
2522
- */
2523
- defaultBanner?: 'simple' | 'full' | false;
2524
- } & ExtractRegistryKey<Kubb.ConfigOptionsRegistry, 'output'>;
2454
+ path: string;
2525
2455
  /**
2526
- * Where generated files are persisted. Defaults to `fsStorage()` (disk). Pass `memoryStorage()`
2527
- * to keep files in RAM, or implement `Storage` for a custom backend such as cloud or a database.
2528
- *
2529
- * @default fsStorage()
2530
- * @example
2531
- * ```ts
2532
- * import { memoryStorage } from '@kubb/core'
2456
+ * How generated code is consolidated into files.
2457
+ * - `'file'` writes everything into a single file. The `path` must include the file extension.
2458
+ * - `'directory'` writes one file per operation or schema under `path`.
2533
2459
  *
2534
- * // Keep generated files in memory (useful for testing, CI pipelines)
2535
- * storage: memoryStorage()
2460
+ * Defaults to `'file'` when `path` carries an extension and `'directory'` when it does not.
2461
+ */
2462
+ mode?: OutputMode;
2463
+ /**
2464
+ * Text prepended to every generated file. Useful for license headers,
2465
+ * lint disables, or `@ts-nocheck` directives.
2536
2466
  *
2537
- * // Use custom S3 storage
2538
- * storage: myS3Storage()
2539
- * ```
2467
+ * A string is applied to every file (including barrel and aggregation re-export files).
2468
+ * Pass a function to compute the banner from the file's `BannerMeta` document metadata
2469
+ * plus per-file context (`isBarrel`, `isAggregation`, `filePath`, `baseName`), so you can
2470
+ * skip the banner on specific files.
2540
2471
  *
2541
- * @see {@link Storage} interface for implementing custom backends.
2472
+ * @example Add a directive to source files but not re-export files
2473
+ * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
2542
2474
  */
2543
- storage: Storage;
2475
+ banner?: string | ((meta: BannerMeta) => string);
2476
+ /**
2477
+ * Text appended at the end of every generated file. Mirror of `banner`.
2478
+ * Pass a function to compute the footer from the file's `BannerMeta`.
2479
+ */
2480
+ footer?: string | ((meta: BannerMeta) => string);
2481
+ } & ExtractRegistryKey<Kubb.PluginOptionsRegistry, 'output'>;
2482
+ /**
2483
+ * Groups generated files into subdirectories based on an OpenAPI tag or path
2484
+ * segment.
2485
+ */
2486
+ type Group = {
2487
+ /**
2488
+ * Property used to assign each operation to a group.
2489
+ * - `'tag'` uses the first tag (`operation.getTags().at(0)?.name`).
2490
+ * - `'path'` uses the first segment of the operation's URL.
2491
+ */
2492
+ type: 'tag' | 'path';
2493
+ /**
2494
+ * Returns the subdirectory name from the group key. Defaults to the camelCased tag for
2495
+ * `tag` groups, or the first path segment as written in the spec for `path` groups.
2496
+ */
2497
+ name?: (context: {
2498
+ group: string;
2499
+ }) => string;
2500
+ };
2501
+ /**
2502
+ * Couples `output.mode` with the plugin's `group` option at the type level.
2503
+ * - An explicit `mode: 'file'` forbids `group` (a single file has nothing to group).
2504
+ * - Omitting `mode`, or setting it to `'directory'`, allows an optional `group`.
2505
+ *
2506
+ * `mode` is normally inferred from `output.path` (an extension means `'file'`, anything
2507
+ * else `'directory'`), so `group` rarely needs `mode` spelled out alongside it. Set
2508
+ * `mode: 'directory'` explicitly only to override that inference, such as a directory
2509
+ * name that carries a dot (`path: 'clients.v2'`).
2510
+ *
2511
+ * Intersect into a plugin's `Options` type instead of declaring `output` and
2512
+ * `group` directly, since `mode` lives inside `output` while `group` is its sibling.
2513
+ * The generic keeps a plugin's extended `Output` shape intact.
2514
+ *
2515
+ * @example
2516
+ * ```ts
2517
+ * export type Options = OutputOptions & {
2518
+ * exclude?: Array<Exclude>
2519
+ * }
2520
+ * ```
2521
+ */
2522
+ type OutputOptions<TOutput extends Output = Output> = {
2523
+ output?: TOutput & {
2524
+ mode?: 'directory';
2525
+ };
2526
+ group?: Group;
2527
+ } | {
2528
+ output?: TOutput & {
2529
+ mode: 'file';
2530
+ };
2531
+ group?: never;
2532
+ };
2533
+ /** Throws `KUBB_INVALID_PLUGIN_OPTIONS`, listing the allowed values, when `value` is not one of `allowed`. */
2534
+ declare function assertPluginOption({ plugin, option, value, allowed }: {
2535
+ plugin: string;
2536
+ option: string;
2537
+ value: unknown;
2538
+ allowed: ReadonlyArray<unknown>;
2539
+ }): void;
2540
+ type ByTag = {
2541
+ /**
2542
+ * Filter by OpenAPI `tags` field. Matches one or more tags assigned to operations.
2543
+ */
2544
+ type: 'tag';
2545
+ /**
2546
+ * Tag name to match (case-sensitive). Can be a literal string or regex pattern.
2547
+ */
2548
+ pattern: string | RegExp;
2549
+ };
2550
+ type ByOperationId = {
2551
+ /**
2552
+ * Filter by OpenAPI `operationId` field. Each operation (GET, POST, etc.) has a unique identifier.
2553
+ */
2554
+ type: 'operationId';
2555
+ /**
2556
+ * Operation ID to match (case-sensitive). Can be a literal string or regex pattern.
2557
+ */
2558
+ pattern: string | RegExp;
2559
+ };
2560
+ type ByPath = {
2544
2561
  /**
2545
- * Plugins that run during the build to generate code and transform the AST. Each one processes
2546
- * the adapter's AST and can emit files for a different target (TypeScript, Zod, Faker). A plugin
2547
- * that depends on another throws when that plugin isn't registered.
2548
- *
2549
- * @example
2550
- * ```ts
2551
- * import { pluginTs } from '@kubb/plugin-ts'
2552
- * import { pluginZod } from '@kubb/plugin-zod'
2553
- *
2554
- * plugins: [
2555
- * pluginTs({ output: { path: './src/gen' } }),
2556
- * pluginZod({ output: { path: './src/gen' } }),
2557
- * ]
2558
- * ```
2562
+ * Filter by OpenAPI `path` (URL endpoint). Useful to group or filter by service segments like `/pets`, `/users`, etc.
2559
2563
  */
2560
- plugins: Array<Plugin>;
2564
+ type: 'path';
2561
2565
  /**
2562
- * The reporters available to the run, registered as instances. The host
2563
- * (the CLI via `--reporter`) selects which ones to trigger by `name` with {@link selectReporters}.
2564
- * `defineConfig` from the `kubb` package registers the built-in `cli`, `json`, `file`, and
2565
- * `html` reporters by default.
2566
- *
2567
- * - `cli` writes the end-of-run summary to the terminal.
2568
- * - `json` writes a machine-readable report to stdout, for CI.
2569
- * - `file` writes a debug log to `.kubb/<name>-<timestamp>.log`.
2570
- * - `html` writes a static HTML report; opt-in via `--reporter html`.
2571
- *
2572
- * @example
2573
- * ```ts
2574
- * import { cliReporter, jsonReporter } from '@kubb/core'
2575
- *
2576
- * reporters: [cliReporter, jsonReporter, myReporter]
2577
- * ```
2566
+ * URL path to match (case-sensitive). Can be a literal string or regex pattern. Matches against the full path.
2578
2567
  */
2579
- reporters: Array<Reporter>;
2568
+ pattern: string | RegExp;
2580
2569
  };
2581
- /**
2582
- * Partial `Config` for user-facing entry points with sensible defaults.
2583
- *
2584
- * `UserConfig` is what you pass to `defineConfig()`. It has optional `root`, `plugins`, `parsers`, and `adapter`
2585
- * fields (which fall back to sensible defaults). All other Config options are available, including `output`, `input`,
2586
- * `storage`, and `hooks`.
2587
- *
2588
- * @example
2589
- * ```ts
2590
- * export default defineConfig({
2591
- * input: './petstore.yaml',
2592
- * output: { path: './src/gen' },
2593
- * plugins: [pluginTs(), pluginZod()],
2594
- * })
2595
- * ```
2596
- */
2597
- type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter' | 'storage' | 'reporters'> & {
2570
+ type ByMethod = {
2598
2571
  /**
2599
- * Project root directory, absolute or relative to the config file location.
2600
- * @default process.cwd()
2572
+ * Filter by HTTP method: `'GET'`, `'POST'`, `'PUT'`, `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`.
2601
2573
  */
2602
- root?: string;
2574
+ type: 'method';
2603
2575
  /**
2604
- * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).
2605
- * @default [parserTs(), parserTsx(), parserMd()] // applied by `defineConfig` from the `kubb` package
2576
+ * HTTP method to match, as one of the `HttpMethod` values (`'GET'`, `'POST'`, `'PUT'`,
2577
+ * `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`) or a regex.
2606
2578
  */
2607
- parsers?: Array<Parser>;
2579
+ pattern: HttpMethod | RegExp;
2580
+ };
2581
+ type BySchemaName = {
2608
2582
  /**
2609
- * Adapter that parses your API specification into Kubb's universal AST.
2610
- * When omitted, Kubb runs in plugin-only mode.
2583
+ * Filter by schema component name (TypeScript or JSON schema). Matches schemas in `#/components/schemas`.
2611
2584
  */
2612
- adapter?: Adapter;
2585
+ type: 'schemaName';
2613
2586
  /**
2614
- * Plugins that execute during the build to generate code and transform the AST.
2615
- * @default []
2587
+ * Schema name to match (case-sensitive). Can be a literal string or regex pattern.
2616
2588
  */
2617
- plugins?: Array<Plugin>;
2589
+ pattern: string | RegExp;
2590
+ };
2591
+ type ByContentType = {
2618
2592
  /**
2619
- * Storage backend that controls where and how generated files are persisted.
2620
- * @default fsStorage()
2593
+ * Filter by response or request content type: `'application/json'`, `'application/xml'`, etc.
2621
2594
  */
2622
- storage?: Storage;
2595
+ type: 'contentType';
2623
2596
  /**
2624
- * Reporters available to the run. `defineConfig` registers the built-in `cli`, `json`, `file`,
2625
- * and `html` reporters when omitted.
2626
- * @default [cliReporter, jsonReporter, fileReporter, htmlReporter] // applied by `defineConfig` from the `kubb` package
2597
+ * Content type to match (case-sensitive). Can be a literal string or regex pattern.
2627
2598
  */
2628
- reporters?: Array<Reporter>;
2599
+ pattern: string | RegExp;
2629
2600
  };
2630
- declare global {
2631
- namespace Kubb {
2632
- /**
2633
- * Registry that maps plugin names to their `PluginFactoryOptions`.
2634
- * Augment this interface in each plugin's `types.ts` to enable automatic
2635
- * typing for `getPlugin` and `requirePlugin`.
2636
- *
2637
- * @example
2638
- * ```ts
2639
- * // packages/plugin-ts/src/types.ts
2640
- * declare global {
2641
- * namespace Kubb {
2642
- * interface PluginRegistry {
2643
- * 'plugin-ts': PluginTs
2644
- * }
2645
- * }
2646
- * }
2647
- * ```
2648
- */
2649
- interface PluginRegistry {}
2650
- /**
2651
- * Extension point for root `Config['output']` options.
2652
- * Augment the `output` key in plugin packages to add extra fields
2653
- * to the global output configuration without touching core types.
2654
- *
2655
- * @example
2656
- * ```ts
2657
- * // packages/plugin-barrel/src/plugin.ts
2658
- * declare global {
2659
- * namespace Kubb {
2660
- * interface ConfigOptionsRegistry {
2661
- * output: {
2662
- * barrel?: import('./types.ts').BarrelConfig | false
2663
- * }
2664
- * }
2665
- * }
2666
- * }
2667
- * ```
2668
- */
2669
- interface ConfigOptionsRegistry {}
2670
- /**
2671
- * Extension point for per-plugin `Output` options.
2672
- * Augment the `output` key in plugin packages to add extra fields
2673
- * to the per-plugin output configuration without touching core types.
2674
- *
2675
- * @example
2676
- * ```ts
2677
- * // packages/plugin-barrel/src/plugin.ts
2678
- * declare global {
2679
- * namespace Kubb {
2680
- * interface PluginOptionsRegistry {
2681
- * output: {
2682
- * barrel?: import('./types.ts').PluginBarrelConfig | false
2683
- * }
2684
- * }
2685
- * }
2686
- * }
2687
- * ```
2688
- */
2689
- interface PluginOptionsRegistry {}
2690
- /**
2691
- * Registry of hook names to their listener argument tuples.
2692
- * Augment this interface to add hook events without touching core types.
2693
- *
2694
- * @example
2695
- * ```ts
2696
- * // packages/my-plugin/src/hooks.ts
2697
- * declare global {
2698
- * namespace Kubb {
2699
- * interface KubbHooksRegistry {
2700
- * 'my-plugin:ready': [ctx: { count: number }]
2701
- * }
2702
- * }
2703
- * }
2704
- * ```
2705
- */
2706
- interface KubbHooksRegistry {
2707
- 'kubb:lifecycle:start': [ctx: KubbLifecycleStartContext];
2708
- 'kubb:lifecycle:end': [];
2709
- 'kubb:generation:start': [ctx: KubbGenerationStartContext];
2710
- 'kubb:generation:end': [ctx: KubbGenerationEndContext];
2711
- 'kubb:generation:summary': [ctx: KubbGenerationSummaryContext];
2712
- 'kubb:setup:start': [];
2713
- 'kubb:setup:end': [];
2714
- 'kubb:format:start': [];
2715
- 'kubb:format:end': [];
2716
- 'kubb:lint:start': [];
2717
- 'kubb:lint:end': [];
2718
- 'kubb:hooks:start': [];
2719
- 'kubb:hooks:end': [];
2720
- 'kubb:hook:start': [ctx: KubbHookStartContext];
2721
- 'kubb:hook:line': [ctx: KubbHookLineContext];
2722
- 'kubb:hook:end': [ctx: KubbHookEndContext];
2723
- 'kubb:info': [ctx: KubbInfoContext];
2724
- 'kubb:error': [ctx: KubbErrorContext];
2725
- 'kubb:success': [ctx: KubbSuccessContext];
2726
- 'kubb:warn': [ctx: KubbWarnContext];
2727
- 'kubb:diagnostic': [ctx: KubbDiagnosticContext];
2728
- 'kubb:files:processing:start': [ctx: KubbFilesProcessingStartContext];
2729
- 'kubb:files:processing:update': [ctx: KubbFilesProcessingUpdateContext];
2730
- 'kubb:files:processing:end': [ctx: KubbFilesProcessingEndContext];
2731
- 'kubb:plugin:start': [ctx: KubbPluginStartContext];
2732
- 'kubb:plugin:end': [ctx: KubbPluginEndContext];
2733
- 'kubb:plugin:setup': [ctx: KubbPluginSetupContext];
2734
- 'kubb:build:start': [ctx: KubbBuildStartContext];
2735
- 'kubb:plugins:end': [ctx: KubbPluginsEndContext];
2736
- 'kubb:build:end': [ctx: KubbBuildEndContext];
2737
- 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext];
2738
- 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext];
2739
- 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext];
2740
- }
2741
- }
2742
- }
2743
2601
  /**
2744
- * Lifecycle hooks emitted during Kubb code generation.
2745
- * Attach listeners before calling `setup()` or `build()` to observe and react to build progress.
2602
+ * Pattern filter for include, exclude, and override rules. Matches operations or schemas
2603
+ * by tag, operationId, path, method, content type, or schema name.
2604
+ */
2605
+ type Filter = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
2606
+ /**
2607
+ * Filter that skips matching operations or schemas during generation, for example
2608
+ * deprecated endpoints or internal-only schemas.
2746
2609
  *
2747
- * A package can add its own hook names to this type by augmenting
2748
- * {@link Kubb.KubbHooksRegistry} instead of exporting a second, separate hook type. Studio's
2749
- * connection and RPC hooks intentionally use its separate `StudioHooks` registry.
2610
+ * @example
2611
+ * ```ts
2612
+ * exclude: [
2613
+ * { type: 'tag', pattern: 'internal' },
2614
+ * { type: 'path', pattern: /^\/admin/ },
2615
+ * { type: 'operationId', pattern: /^deprecated_/ },
2616
+ * ]
2617
+ * ```
2618
+ */
2619
+ type Exclude$1 = Filter;
2620
+ /**
2621
+ * Filter that restricts generation to operations or schemas matching at least
2622
+ * one entry. Useful for partial builds (one tag, one API version).
2750
2623
  *
2751
2624
  * @example
2752
2625
  * ```ts
2753
- * kubb.hooks.hook('kubb:lifecycle:start', () => {
2754
- * console.log('Starting Kubb generation')
2755
- * })
2626
+ * include: [
2627
+ * { type: 'tag', pattern: 'public' },
2628
+ * { type: 'path', pattern: /^\/api\/v1/ },
2629
+ * ]
2630
+ * ```
2631
+ */
2632
+ type Include = Filter;
2633
+ /**
2634
+ * Filter paired with a partial options object. When the filter matches, the
2635
+ * options are merged on top of the plugin defaults for that operation only.
2636
+ * Useful for "this one tag goes to a different folder" rules.
2756
2637
  *
2757
- * kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => {
2758
- * console.log(`${plugin.name} completed in ${duration}ms`)
2759
- * })
2638
+ * Entries are evaluated top to bottom. The first matching entry wins.
2639
+ *
2640
+ * @example
2641
+ * ```ts
2642
+ * override: [
2643
+ * {
2644
+ * type: 'tag',
2645
+ * pattern: 'admin',
2646
+ * options: { output: { path: './src/gen/admin' } },
2647
+ * },
2648
+ * {
2649
+ * type: 'operationId',
2650
+ * pattern: 'listPets',
2651
+ * options: { enumType: 'literal' },
2652
+ * },
2653
+ * ]
2760
2654
  * ```
2761
2655
  */
2762
- type KubbHooks = Kubb.KubbHooksRegistry;
2763
- /** The file access every file-carrying hook context shares: a lazy snapshot of the files so far, and a way to add more. */
2764
- type FilesContext = {
2765
- /** Snapshot of all files accumulated so far, including those added by plugins that already ran. */
2766
- readonly files: ReadonlyArray<FileNode>;
2767
- /** Adds or merges one or more files into the file manager. */
2768
- upsertFile: (...files: Array<FileNode>) => void;
2656
+ type Override<TOptions> = Filter & {
2657
+ options: Omit<Partial<TOptions>, 'override'>;
2769
2658
  };
2770
- type KubbBuildStartContext = FilesContext & {
2659
+ type PluginFactoryOptions<
2660
+ /**
2661
+ * Unique plugin name.
2662
+ */
2663
+ TName extends string = string,
2664
+ /**
2665
+ * User-facing plugin options.
2666
+ */
2667
+ TOptions extends object = object,
2668
+ /**
2669
+ * Plugin options after defaults are applied.
2670
+ */
2671
+ TResolvedOptions extends object = TOptions,
2672
+ /**
2673
+ * Resolver that encapsulates naming and path-resolution helpers.
2674
+ * Define with `createResolver` and export alongside the plugin.
2675
+ */
2676
+ TResolver extends Resolver = Resolver> = {
2677
+ name: TName;
2678
+ options: TOptions;
2679
+ resolvedOptions: TResolvedOptions;
2680
+ resolver: TResolver;
2681
+ };
2682
+ /**
2683
+ * Type parameter for the object form of `definePlugin`. Same shape as `PluginFactoryOptions`.
2684
+ */
2685
+ type PluginType<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TResolver extends Resolver = Resolver> = PluginFactoryOptions<TName, TOptions, TResolvedOptions, TResolver>;
2686
+ /**
2687
+ * Context passed to a plugin's `kubb:plugin:setup` handler, where it registers generators and
2688
+ * sets its resolver, transformer, and options.
2689
+ */
2690
+ type KubbPluginSetupContext<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
2771
2691
  /**
2772
- * Resolved configuration for this build.
2692
+ * Register one or more generators dynamically. Generators fire during the AST walk
2693
+ * (schema/operation/operations) just like generators declared statically on `createPlugin`.
2694
+ *
2695
+ * Pass generators as separate arguments. Spread an existing list to register it in one call.
2696
+ *
2697
+ * @example
2698
+ * ```ts
2699
+ * ctx.addGenerator(myGenerator)
2700
+ * ctx.addGenerator(schemaGenerator, operationGenerator)
2701
+ * ctx.addGenerator(...selectedGenerators)
2702
+ * ```
2773
2703
  */
2774
- config: Config;
2704
+ addGenerator<TElement = unknown>(...generators: Array<Generator<TFactory, TElement>>): void;
2775
2705
  /**
2776
- * Adapter that parsed the input into the universal AST.
2706
+ * Set or override the resolver for this plugin.
2707
+ * The resolver controls file naming and path resolution. Overrides merge over the built-in
2708
+ * defaults, so a partial `core` or a single namespace method replaces only what it names.
2777
2709
  */
2778
- adapter: Adapter;
2710
+ setResolver(resolver: ResolverPatch<TFactory['resolver']> | TFactory['resolver']): void;
2779
2711
  /**
2780
- * Metadata about the parsed document (title, version, base URL, circular schema names, enum names).
2781
- * To observe individual schemas and operations use the `kubb:generate:schema` / `kubb:generate:operation` hooks.
2712
+ * Add a macro that rewrites AST nodes before they reach generators. Macros run in the order they
2713
+ * are added, after any macros from earlier `addMacro` calls.
2782
2714
  */
2783
- meta: InputMeta | undefined;
2715
+ addMacro(macro: Macro): void;
2784
2716
  /**
2785
- * Looks up a registered plugin by name, typed by the plugin registry.
2717
+ * Replace this plugin's macros with `macros`.
2786
2718
  */
2787
- getPlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
2788
- };
2789
- type KubbPluginsEndContext = FilesContext & {
2719
+ setMacros(macros: ReadonlyArray<Macro>): void;
2790
2720
  /**
2791
- * Resolved configuration for this build.
2721
+ * Set resolved options merged into the normalized plugin's `options`.
2722
+ * Call this in `kubb:plugin:setup` to provide options generators need.
2792
2723
  */
2793
- config: Config;
2794
- };
2795
- type KubbBuildEndContext = {
2724
+ setOptions(options: TFactory['resolvedOptions']): void;
2796
2725
  /**
2797
- * All files generated during this build.
2726
+ * Inject a raw file into the build output, bypassing the generation pipeline.
2727
+ *
2728
+ * Pass `copy` with an absolute path to emit a real source file (a shipped template) into the
2729
+ * generated folder, instead of building its content from `sources`.
2798
2730
  */
2799
- files: Array<FileNode>;
2731
+ injectFile(userFileNode: UserFileNode): void;
2732
+ /** Returns a plugin this one needs, or fails the run with `KUBB_PLUGIN_NOT_FOUND` when the config lacks it. */
2733
+ requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>;
2800
2734
  /**
2801
- * Resolved configuration for this build.
2735
+ * The resolved build configuration at setup time.
2802
2736
  */
2803
2737
  config: Config;
2804
2738
  /**
2805
- * Absolute path to the output directory.
2806
- */
2807
- outputDir: string;
2808
- };
2809
- type KubbLifecycleStartContext = {
2810
- /**
2811
- * Current Kubb version string.
2812
- */
2813
- version: string;
2814
- };
2815
- type KubbGenerationStartContext = {
2816
- /**
2817
- * Resolved configuration for this generation run.
2739
+ * The plugin's user-provided options.
2818
2740
  */
2819
- config: Config;
2741
+ options: TFactory['options'];
2820
2742
  };
2821
- type KubbGenerationEndContext = {
2743
+ /**
2744
+ * A plugin object produced by `definePlugin`. Its lifecycle handlers live under a single
2745
+ * `hooks` property rather than flat methods.
2746
+ */
2747
+ type Plugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = ExtensionNamed & {
2822
2748
  /**
2823
- * Resolved configuration for this generation run.
2749
+ * Plugins this one builds on. They run first when the config has them. An array only orders
2750
+ * plugins. A record also fails the run when a required entry is missing or out of range.
2824
2751
  */
2825
- config: Config;
2752
+ dependencies?: Array<PluginName> | ExtensionDependencies<TFactory['options']>;
2826
2753
  /**
2827
- * Read-only view of the files written during this build.
2828
- * Reads go directly to `config.storage`, nothing extra is held in memory.
2754
+ * Controls the execution order of this plugin relative to others.
2829
2755
  *
2830
- * @example Read a generated file
2831
- * `const code = await storage.readItem('/src/gen/pet.ts')`
2756
+ * - `'pre'` runs before all normal plugins.
2757
+ * - `'post'` runs after all normal plugins.
2758
+ * - `undefined` (default) runs in declaration order among normal plugins.
2832
2759
  *
2833
- * @example Walk every generated file
2834
- * ```ts
2835
- * for (const path of await storage.readKeys()) {
2836
- * const code = await storage.readItem(path)
2837
- * }
2838
- * ```
2839
- */
2840
- storage: Storage;
2841
- /**
2842
- * Diagnostics collected during the build: error/warning/info problems plus a
2843
- * `performance` diagnostic per plugin. The end-of-run summary derives its failure counts
2844
- * and per-plugin timings from these. Set by the CLI runner, omitted by other callers.
2760
+ * Dependency constraints always take precedence over `enforce`.
2845
2761
  */
2846
- diagnostics?: Array<Diagnostic>;
2762
+ enforce?: Enforce;
2847
2763
  /**
2848
- * `'success'` when all plugins completed without errors, `'failed'` otherwise.
2764
+ * The options passed by the user when calling the plugin factory.
2849
2765
  */
2850
- status?: 'success' | 'failed';
2766
+ options?: TFactory['options'];
2851
2767
  /**
2852
- * High-resolution start time from `process.hrtime()`, used to compute the elapsed time.
2768
+ * Lifecycle hook handlers for this plugin.
2769
+ * Any hook from the global `KubbHooks` map can be subscribed to here.
2853
2770
  */
2854
- hrStart?: [number, number];
2771
+ hooks: { [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void>; } & {
2772
+ 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
2773
+ };
2855
2774
  /**
2856
- * Total number of files created during this run.
2775
+ * Runs before `kubb:plugin:setup`. Takes the user's options and returns the resolved options.
2857
2776
  */
2858
- filesCreated?: number;
2777
+ setup?(options: TFactory['options'], kubb: KubbPluginSetupContext<TFactory>): TFactory['resolvedOptions'] | Promise<TFactory['resolvedOptions']>;
2859
2778
  };
2860
- /** A human-readable message with optional detail, as carried by `kubb:info`, `kubb:success`, and `kubb:warn`. */
2861
- type KubbMessageContext = {
2862
- /**
2863
- * Human-readable message.
2864
- */
2865
- message: string;
2866
- /**
2867
- * Optional supplementary detail.
2868
- */
2869
- info?: string;
2779
+ /**
2780
+ * The object passed to `definePlugin`.
2781
+ */
2782
+ type PluginDefinition<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = Pick<Plugin<TFactory>, 'dependencies' | 'enforce' | 'setup'> & {
2783
+ meta: ExtensionMeta<TFactory['name']>;
2784
+ hooks?: Plugin<TFactory>['hooks'];
2870
2785
  };
2871
- type KubbInfoContext = KubbMessageContext;
2872
- type KubbSuccessContext = KubbMessageContext;
2873
- type KubbWarnContext = KubbMessageContext;
2874
- type KubbErrorContext = {
2875
- /**
2876
- * The caught error.
2877
- */
2878
- error: Error;
2879
- /**
2880
- * Optional structured metadata for additional context.
2881
- */
2882
- meta?: Record<string, unknown>;
2786
+ /**
2787
+ * The function `definePlugin` returns. Call it with user options to get a `Plugin`.
2788
+ */
2789
+ type PluginFactory<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = ExtensionFactory<'plugin', TFactory['options'], Plugin<TFactory>, TFactory['name']>;
2790
+ /**
2791
+ * Normalized plugin after setup, with runtime fields populated. Internal only. Plugins use the
2792
+ * public `Plugin` type.
2793
+ *
2794
+ * @internal
2795
+ */
2796
+ type NormalizedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & {
2797
+ name: string;
2798
+ meta: ExtensionMeta;
2799
+ dependencies?: Array<PluginName> | ExtensionDependencyRecord;
2800
+ options: TOptions['resolvedOptions'] & {
2801
+ output: Output;
2802
+ include?: Array<Include>;
2803
+ exclude: Array<Exclude$1>;
2804
+ override: Array<Override<TOptions['resolvedOptions']>>;
2805
+ };
2806
+ resolver: TOptions['resolver'];
2807
+ macros?: Array<Macro>;
2808
+ generators?: Array<Generator>;
2883
2809
  };
2884
- type KubbDiagnosticContext = {
2885
- /**
2886
- * The structured diagnostic to render: a build problem or a version-update notice.
2887
- */
2888
- diagnostic: ProblemDiagnostic | UpdateDiagnostic;
2810
+ type KubbPluginStartContext = {
2811
+ plugin: NormalizedPlugin;
2889
2812
  };
2890
- type KubbGenerationSummaryContext = {
2813
+ type KubbPluginEndContext = FilesContext & {
2814
+ plugin: NormalizedPlugin;
2891
2815
  duration: number;
2892
- fileCount: number;
2893
- failedPlugins: number;
2894
- status: 'success' | 'failed';
2895
- };
2896
- type KubbFilesProcessingStartContext = {
2897
- /**
2898
- * Files about to be serialized and written.
2899
- */
2900
- files: Array<FileNode>;
2901
- };
2902
- type KubbFileProcessingUpdate = {
2903
- /**
2904
- * Number of files processed so far in this batch.
2905
- */
2906
- processed: number;
2907
- /**
2908
- * Total number of files in this batch.
2909
- */
2910
- total: number;
2911
- /**
2912
- * Completion percentage, `0` to `100`.
2913
- */
2914
- percentage: number;
2915
- /**
2916
- * The file that was just processed.
2917
- */
2918
- file: FileNode;
2919
- /**
2920
- * Resolved configuration for this build.
2921
- */
2816
+ success: boolean;
2817
+ error?: Error;
2922
2818
  config: Config;
2923
2819
  };
2924
- type KubbFilesProcessingUpdateContext = {
2925
- /**
2926
- * All files processed in this flush chunk.
2927
- */
2928
- files: Array<KubbFileProcessingUpdate>;
2820
+ /**
2821
+ * Defines a plugin from one object and returns a factory that takes the user's options.
2822
+ * Name plugins `plugin-<feature>`.
2823
+ *
2824
+ * @example
2825
+ * ```ts
2826
+ * export const pluginZod = definePlugin<PluginZod>({
2827
+ * meta: { name: 'plugin-zod', compatibility: { kubb: '>=5.7.0' } },
2828
+ * dependencies: { 'plugin-ts': { optional: true } },
2829
+ * setup(options, kubb) {
2830
+ * kubb.addGenerator(zodGenerator)
2831
+ * return { ...options, inferred: options.inferred ?? false }
2832
+ * },
2833
+ * })
2834
+ * ```
2835
+ */
2836
+ declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(definition: PluginDefinition<TFactory>): PluginFactory<TFactory>;
2837
+ /**
2838
+ * Wraps a factory function that returns a `Plugin`. Without `meta`, the plugin gets `{ name }`.
2839
+ *
2840
+ * @deprecated Pass a definition object with `meta` and `setup` instead. The factory form is removed in the next major.
2841
+ */
2842
+ declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(factory: (options: TFactory['options']) => Plugin<TFactory>): ((options?: TFactory['options']) => Plugin<TFactory>) & {
2843
+ kind: 'plugin';
2929
2844
  };
2930
- type KubbFilesProcessingEndContext = {
2845
+ //#endregion
2846
+ //#region src/defineExtension.d.ts
2847
+ /**
2848
+ * What an extension extends: a plugin generates code, an adapter reads the input, a parser prints files.
2849
+ */
2850
+ type ExtensionKind = 'plugin' | 'adapter' | 'parser';
2851
+ /**
2852
+ * Identity and registry data for an extension. Kubb reads `name` and `compatibility` at runtime.
2853
+ * Studio, the kubb.dev registry, and the docs read the rest.
2854
+ */
2855
+ type ExtensionMeta<TName extends string = string> = {
2931
2856
  /**
2932
- * All files that were serialized in this batch.
2857
+ * Unique name, such as `'plugin-ts'`. Becomes the plugin's `name`.
2933
2858
  */
2934
- files: Array<FileNode>;
2935
- };
2936
- type KubbHookStartContext = {
2859
+ name: TName;
2937
2860
  /**
2938
- * Optional identifier for correlating start/end hooks.
2861
+ * Package version. Dependents check their `version` range against it.
2939
2862
  */
2940
- id?: string;
2863
+ version?: string;
2864
+ displayName?: string;
2941
2865
  /**
2942
- * The shell command that is about to run.
2866
+ * One-sentence summary of what the extension generates or does.
2943
2867
  */
2944
- command: string;
2868
+ description?: string;
2869
+ category?: string;
2870
+ icon?: {
2871
+ light: string;
2872
+ dark?: string;
2873
+ };
2874
+ /** HTTPS image or video URLs. */
2875
+ media?: Array<string>;
2876
+ tags?: Array<string>;
2945
2877
  /**
2946
- * Optional label for the command, shown in the CLI output when set.
2878
+ * Semver ranges the extension supports. A mismatch fails the run with `KUBB_INCOMPATIBLE_EXTENSION`.
2947
2879
  */
2880
+ compatibility?: {
2881
+ kubb?: string;
2882
+ node?: string;
2883
+ };
2884
+ docs?: string;
2885
+ };
2886
+ /**
2887
+ * An extension's identity: `meta`, a `name`, or both. `name` is deprecated in favor of `meta.name`.
2888
+ */
2889
+ type ExtensionNamed = {
2948
2890
  name?: string;
2949
- /**
2950
- * Parsed argument list, when available.
2951
- */
2952
- args?: ReadonlyArray<string>;
2891
+ meta?: ExtensionMeta;
2953
2892
  };
2954
2893
  /**
2955
- * Emitted for each line streamed from a hook's stdout while it runs.
2956
- * A logger correlates the line to its active UI element via `id`.
2894
+ * Returns `meta`, or `{ name }` for an extension that only sets the deprecated `name`. Throws `KUBB_INVALID_PLUGIN_OPTIONS` when it has neither.
2957
2895
  */
2958
- type KubbHookLineContext = {
2896
+ declare function resolveMeta({ name, meta }: ExtensionNamed): ExtensionMeta;
2897
+ /**
2898
+ * Sets how Kubb checks one entry in a `dependencies` record.
2899
+ */
2900
+ type ExtensionDependency = {
2959
2901
  /**
2960
- * Identifier matching the corresponding `kubb:hook:start` hook.
2902
+ * Semver range the dependency's `meta.version` must satisfy. Skipped when the dependency has no `meta.version`.
2961
2903
  */
2962
- id: string;
2904
+ version?: string;
2963
2905
  /**
2964
- * A single streamed stdout line, without its trailing newline.
2906
+ * When `true`, Kubb skips the entry if the plugin is missing, but still checks `version` on an installed one.
2907
+ * Otherwise a missing plugin fails the run with `KUBB_MISSING_DEPENDENCY`.
2965
2908
  */
2966
- line: string;
2909
+ optional?: boolean;
2967
2910
  };
2968
- /** Emitted when a hook subprocess ends: its `kubb:hook:start` context plus the outcome. */
2969
- type KubbHookEndContext = KubbHookStartContext & HookResult;
2970
2911
  /**
2971
- * CLI options derived from command-line flags.
2912
+ * Plugins an extension builds on, keyed by name, or a function that picks them from the user's options.
2972
2913
  */
2973
- type CLIOptions = {
2914
+ type ExtensionDependencies<TOptions = object> = ExtensionDependencyRecord | {
2915
+ resolve(options: TOptions, kubb: {
2916
+ config: Config;
2917
+ }): ExtensionDependencyRecord;
2918
+ }['resolve'];
2919
+ /**
2920
+ * Maps each dependency's plugin name to how Kubb checks it.
2921
+ */
2922
+ type ExtensionDependencyRecord = Partial<Record<PluginName, ExtensionDependency>>;
2923
+ /**
2924
+ * Throws `KUBB_INCOMPATIBLE_EXTENSION` when the running Kubb or Node.js version is outside `meta.compatibility`.
2925
+ */
2926
+ declare function checkCompatibility(meta: ExtensionMeta): void;
2927
+ /**
2928
+ * The function an extension definition returns. Call it with user options to get the extension.
2929
+ */
2930
+ type ExtensionFactory<TKind extends ExtensionKind, TOptions, TExtension, TName extends string = string> = {
2931
+ (options?: TOptions): TExtension;
2932
+ kind: TKind;
2933
+ meta: ExtensionMeta<TName>;
2934
+ };
2935
+ //#endregion
2936
+ //#region src/createAdapter.d.ts
2937
+ /**
2938
+ * Source data handed to an adapter's `parse` function. Mirrors the config
2939
+ * input shape with paths resolved to absolute.
2940
+ *
2941
+ * - `{ type: 'path' }`: single file on disk.
2942
+ * - `{ type: 'data' }`: raw string or parsed object provided inline.
2943
+ */
2944
+ type AdapterSource = {
2945
+ type: 'path';
2946
+ path: string;
2947
+ } | {
2948
+ type: 'data';
2949
+ data: string | unknown;
2950
+ };
2951
+ /**
2952
+ * Generic parameters used by `createAdapter` and the resulting `Adapter` type.
2953
+ *
2954
+ * - `TName`: unique adapter identifier (`'oas'`, `'asyncapi'`, ...).
2955
+ * - `TOptions`: user-facing options accepted by the adapter factory.
2956
+ * - `TResolvedOptions`: options after defaults are applied.
2957
+ * - `TDocument`: type of the parsed source document.
2958
+ */
2959
+ type AdapterFactoryOptions<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TDocument = unknown> = {
2960
+ name: TName;
2961
+ options: TOptions;
2962
+ resolvedOptions: TResolvedOptions;
2963
+ document: TDocument;
2964
+ };
2965
+ /**
2966
+ * Converts input files or inline data into Kubb's universal AST `InputNode`.
2967
+ *
2968
+ * Adapters live between the spec format and the plugins. The built-in
2969
+ * `@kubb/adapter-oas` handles OpenAPI 2.0, 3.0, and 3.1. A custom adapter can
2970
+ * support GraphQL, gRPC, or another schema language.
2971
+ *
2972
+ * @example
2973
+ * ```ts
2974
+ * import { defineConfig } from 'kubb'
2975
+ * import { adapterOas } from '@kubb/adapter-oas'
2976
+ * import { pluginTs } from '@kubb/plugin-ts'
2977
+ *
2978
+ * export default defineConfig({
2979
+ * input: './petStore.yaml',
2980
+ * output: { path: './src/gen' },
2981
+ * adapter: adapterOas(),
2982
+ * plugins: [pluginTs()],
2983
+ * })
2984
+ * ```
2985
+ */
2986
+ type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
2974
2987
  /**
2975
- * Path to the Kubb config file.
2988
+ * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).
2976
2989
  */
2977
- config?: string;
2990
+ name: TOptions['name'];
2991
+ meta?: ExtensionMeta<TOptions['name']>;
2978
2992
  /**
2979
- * OpenAPI input path or URL passed as the positional argument to `kubb generate`.
2980
- * Overrides `config.input` when set.
2993
+ * Resolved adapter options after defaults have been applied.
2981
2994
  */
2982
- input?: string;
2995
+ options: TOptions['resolvedOptions'];
2983
2996
  /**
2984
- * Re-run generation whenever input files change.
2997
+ * Parsed source document after the first `parse()` call. `null` before parsing.
2985
2998
  */
2986
- watch?: boolean;
2999
+ document: TOptions['document'] | null;
2987
3000
  /**
2988
- * Controls how much output the CLI prints.
3001
+ * Parse the source into a universal `InputNode`.
2989
3002
  *
2990
- * @default 'info'
3003
+ * An adapter that renames schemas (e.g. collision handling) must stamp `targetName` on
3004
+ * every ref node pointing at a renamed schema, so `resolveRefName` and `resolver.imports`
3005
+ * resolve a `$ref` to the file that is actually generated. Refs that keep their pointer's
3006
+ * last segment need no stamp.
2991
3007
  */
2992
- logLevel?: 'silent' | 'info' | 'verbose';
3008
+ parse: (source: AdapterSource, options?: {
3009
+ signal?: AbortSignal;
3010
+ }) => PossiblePromise<InputNode>;
2993
3011
  /**
2994
- * Reporters selected on the CLI via `--reporter`, overriding `config.reporters`.
3012
+ * Validate the document at the given path or URL.
2995
3013
  */
2996
- reporters?: Array<ReporterName>;
3014
+ validate: (input: string, options?: {
3015
+ throwOnError?: boolean;
3016
+ }) => Promise<void>;
2997
3017
  };
3018
+ type AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>;
2998
3019
  /**
2999
- * All accepted forms of a Kubb configuration.
3000
- * Accepts `Config`/`Config[]`/promise or a factory (optionally receiving `TCliOptions`).
3001
- */
3002
- type PossibleConfig<TCliOptions = undefined> = PossiblePromise<Config | Array<Config>> | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Array<Config>>);
3003
- /**
3004
- * Full output produced by a successful or failed build.
3020
+ * The object passed to `createAdapter`.
3005
3021
  */
3006
- type BuildOutput = {
3007
- /**
3008
- * Structured diagnostics collected during the build: error/warning/info problems
3009
- * (each with a code, severity, and where known a JSON-pointer location) plus a
3010
- * `performance` diagnostic per plugin. Includes a top-level diagnostic when the build
3011
- * threw before completing. Use {@link Diagnostics.hasError} to test for failure.
3012
- */
3013
- diagnostics: Array<Diagnostic>;
3014
- /**
3015
- * All files generated during this build.
3016
- */
3017
- files: Array<FileNode>;
3022
+ type AdapterDefinition<T extends AdapterFactoryOptions = AdapterFactoryOptions> = {
3023
+ meta: ExtensionMeta<T['name']>;
3018
3024
  /**
3019
- * The plugin driver that orchestrated this build.
3025
+ * Takes the user's options and returns the resolved options, which `build` receives and the adapter exposes as `options`.
3026
+ * Without `setup`, the user's options are the resolved options.
3020
3027
  */
3021
- driver: KubbDriver;
3028
+ setup?(options: T['options']): T['resolvedOptions'];
3022
3029
  /**
3023
- * The configured `Storage` backend, for reading back a generated file's final content.
3024
- * Use `files` to list what this build produced.
3025
- *
3026
- * @example Read a generated file
3027
- * `const code = await buildOutput.storage.readItem('/src/gen/pet.ts')`
3030
+ * Returns the adapter's document and methods for the resolved options.
3028
3031
  */
3029
- storage: Storage;
3032
+ build(options: T['resolvedOptions']): Omit<Adapter<T>, 'name' | 'meta' | 'options'>;
3033
+ };
3034
+ /**
3035
+ * The function `createAdapter` returns. Call it with user options to get an `Adapter`.
3036
+ */
3037
+ type AdapterFactory<T extends AdapterFactoryOptions = AdapterFactoryOptions> = ExtensionFactory<'adapter', T['options'], Adapter<T>, T['name']>;
3038
+ /**
3039
+ * Defines a custom adapter that translates a spec format into Kubb's universal
3040
+ * AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
3041
+ * handles OpenAPI/Swagger documents.
3042
+ *
3043
+ * Adapters must return an `InputNode` from `parse`. That node is what every
3044
+ * plugin in the build consumes.
3045
+ *
3046
+ * @example
3047
+ * ```ts
3048
+ * import { createAdapter, type AdapterFactoryOptions } from '@kubb/core'
3049
+ * import { ast } from '@kubb/ast'
3050
+ *
3051
+ * type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }, { validate: boolean }>
3052
+ *
3053
+ * export const myAdapter = createAdapter<MyAdapter>({
3054
+ * meta: { name: 'my-adapter', compatibility: { kubb: '>=5.7.0' } },
3055
+ * setup: (options) => ({ validate: options.validate ?? true }),
3056
+ * build: (options) => ({
3057
+ * document: null,
3058
+ * async parse(_source) {
3059
+ * // Convert the source (path or inline data) into an InputNode.
3060
+ * return ast.factory.createInput()
3061
+ * },
3062
+ * async validate() {
3063
+ * // Throw here when `options.validate` is set and the spec is invalid.
3064
+ * },
3065
+ * }),
3066
+ * })
3067
+ * ```
3068
+ */
3069
+ declare function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(definition: AdapterDefinition<T>): AdapterFactory<T>;
3070
+ /**
3071
+ * Wraps a factory function that returns an `Adapter`.
3072
+ *
3073
+ * @deprecated Pass a definition object with `meta` and `build` instead. The factory form is removed in the next major.
3074
+ */
3075
+ declare function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): ((options?: T['options']) => Adapter<T>) & {
3076
+ kind: 'adapter';
3030
3077
  };
3031
3078
  //#endregion
3032
- export { OutputOptions as $, SerializedDiagnostic as $t, HookResult as A, resolveMeta as At, ParserDefinition as B, ReporterPluginFiles as Bt, KubbMessageContext as C, ResolverPathParams as Ct, PossibleConfig as D, ExtensionFactory as Dt, KubbWarnContext as E, ExtensionDependencyRecord as Et, defineGenerator as F, createStorage as Ft, Group as G, DiagnosticDoc as Gt, defineParser as H, createReporter as Ht, NodeCache as I, GenerationResult as It, KubbPluginSetupContext as J, DiagnosticSeverity as Jt, Include as K, DiagnosticKind as Kt, KubbDriver as L, Reporter as Lt, runHook as M, RendererFactory as Mt, Generator as N, createRenderer as Nt, PostGenerateCommand as O, ExtensionKind as Ot, GeneratorContext as P, Storage as Pt, OutputMode as Q, ProblemDiagnostic as Qt, FileManagerHooks as R, ReporterContext as Rt, KubbLifecycleStartContext as S, ResolverPatch as St, KubbSuccessContext as T, ExtensionDependency as Tt, Exclude$1 as U, logLevel as Ut, ParserFactory as V, UserReporter as Vt, Filter as W, Diagnostic as Wt, NormalizedPlugin as X, PerformanceDiagnostic as Xt, KubbPluginStartContext as Y, Diagnostics as Yt, Output as Z, ProblemCode as Zt, KubbHookEndContext as _, Resolver as _t, Input as a, createAdapter as an, PluginName as at, KubbHooks as b, ResolverFileParams as bt, KubbDiagnosticContext as c, assertPluginOption as ct, KubbFilesProcessingEndContext as d, ResolveBannerContext as dt, UpdateDiagnostic as en, Override as et, KubbFilesProcessingStartContext as f, ResolveBannerFile as ft, KubbGenerationSummaryContext as g, ResolvePathOptions as gt, KubbGenerationStartContext as h, ResolveOptionsContext as ht, FilesContext as i, AdapterSource as in, PluginFactoryOptions as it, RunHookOptions as j, Renderer as jt, UserConfig as k, ExtensionMeta as kt, KubbErrorContext as l, definePlugin as lt, KubbGenerationEndContext as m, ResolveImportsOptions as mt, CLIOptions as n, Adapter as nn, PluginDefinition as nt, KubbBuildEndContext as o, PluginType as ot, KubbFilesProcessingUpdateContext as p, ResolveFileOptions as pt, KubbPluginEndContext as q, DiagnosticLocation as qt, Config as r, AdapterFactoryOptions as rn, PluginFactory as rt, KubbBuildStartContext as s, ResolvePluginOptions as st, BuildOutput as t, Hookable as tn, Plugin as tt, KubbFileProcessingUpdate as u, BannerMeta as ut, KubbHookLineContext as v, ResolverDefault as vt, KubbPluginsEndContext as w, ExtensionDependencies as wt, KubbInfoContext as x, ResolverFilePathParams as xt, KubbHookStartContext as y, ResolverFile as yt, Parser as z, ReporterName as zt };
3033
- //# sourceMappingURL=types-Cd91JYuu.d.ts.map
3079
+ export { NodeCache as $, Diagnostics as $t, PluginFactoryOptions as A, RunHookOptions as At, ResolveImportsOptions as B, GenerationResult as Bt, Output as C, KubbPluginsEndContext as Ct, Plugin as D, PostGenerateCommand as Dt, Override as E, PossibleConfig as Et, definePlugin as F, ParserDefinition as Ft, ResolverFile as G, UserReporter as Gt, ResolvePathOptions as H, ReporterContext as Ht, BannerMeta as I, ParserFactory as It, ResolverPatch as J, Diagnostic as Jt, ResolverFileParams as K, createReporter as Kt, ResolveBannerContext as L, defineParser as Lt, PluginType as M, KubbDriver as Mt, ResolvePluginOptions as N, FileManagerHooks as Nt, PluginDefinition as O, UserConfig as Ot, assertPluginOption as P, Parser as Pt, defineGenerator as Q, DiagnosticSeverity as Qt, ResolveBannerFile as R, Storage as Rt, NormalizedPlugin as S, KubbMessageContext as St, OutputOptions as T, KubbWarnContext as Tt, Resolver as U, ReporterName as Ut, ResolveOptionsContext as V, Reporter as Vt, ResolverDefault as W, ReporterPluginFiles as Wt, Generator as X, DiagnosticKind as Xt, ResolverPathParams as Y, DiagnosticDoc as Yt, GeneratorContext as Z, DiagnosticLocation as Zt, Group as _, KubbHookLineContext as _t, AdapterSource as a, Hookable as an, KubbBuildEndContext as at, KubbPluginSetupContext as b, KubbInfoContext as bt, ExtensionDependency as c, createRenderer as cn, KubbErrorContext as ct, ExtensionKind as d, KubbFilesProcessingStartContext as dt, PerformanceDiagnostic as en, BuildOutput as et, ExtensionMeta as f, KubbFilesProcessingUpdateContext as ft, Filter as g, KubbHookEndContext as gt, Exclude$1 as h, KubbGenerationSummaryContext as ht, AdapterFactoryOptions as i, UpdateDiagnostic as in, Input as it, PluginName as j, runHook as jt, PluginFactory as k, HookResult as kt, ExtensionDependencyRecord as l, KubbFileProcessingUpdate as lt, resolveMeta as m, KubbGenerationStartContext as mt, AdapterDefinition as n, ProblemDiagnostic as nn, Config as nt, createAdapter as o, Renderer as on, KubbBuildStartContext as ot, checkCompatibility as p, KubbGenerationEndContext as pt, ResolverFilePathParams as q, logLevel as qt, AdapterFactory as r, SerializedDiagnostic as rn, FilesContext as rt, ExtensionDependencies as s, RendererFactory as sn, KubbDiagnosticContext as st, Adapter as t, ProblemCode as tn, CLIOptions as tt, ExtensionFactory as u, KubbFilesProcessingEndContext as ut, Include as v, KubbHookStartContext as vt, OutputMode as w, KubbSuccessContext as wt, KubbPluginStartContext as x, KubbLifecycleStartContext as xt, KubbPluginEndContext as y, KubbHooks as yt, ResolveFileOptions as z, createStorage as zt };
3080
+ //# sourceMappingURL=createAdapter-BO_AxI05.d.ts.map