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