@kubb/core 5.10.3 → 5.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,6 +1,3158 @@
1
- import { $ as NodeCache, $t as ReporterPluginFiles, A as PluginFactory, At as KubbInfoContext, B as ResolveImportsOptions, Bt as RunHookOptions, C as NormalizedPlugin, Ct as KubbGenerationEndContext, D as Override, Dt as KubbHookLineContext, E as OutputOptions, Et as KubbHookEndContext, F as definePlugin, Ft as KubbWarnContext, G as ResolverFile, Gt as RendererFactory, H as ResolvePathOptions, Ht as KubbDriver, I as BannerMeta, It as PossibleConfig, J as ResolverPatch, Jt as createStorage, K as ResolverFileParams, Kt as createRenderer, L as ResolveBannerContext, Lt as PostGenerateCommand, M as PluginType, Mt as KubbMessageContext, N as ResolvePluginOptions, Nt as KubbPluginsEndContext, O as Plugin, Ot as KubbHookStartContext, P as assertPluginOption, Pt as KubbSuccessContext, Q as defineGenerator, Qt as ReporterName, R as ResolveBannerFile, Rt as UserConfig, S as KubbPluginStartContext, St as KubbFilesProcessingUpdateContext, T as OutputMode, Tt as KubbGenerationSummaryContext, U as Resolver, Ut as Hookable, V as ResolveOptionsContext, Vt as runHook, W as ResolverDefault, Wt as Renderer, X as Generator, Xt as Reporter, Y as ResolverPathParams, Yt as GenerationResult, Z as GeneratorContext, Zt as ReporterContext, _ as Filter, _t as KubbDiagnosticContext, a as AdapterSource, an as Parser, at as Diagnostics, b as KubbPluginEndContext, bt as KubbFilesProcessingEndContext, c as ExtensionDependency, cn as defineParser, ct as ProblemDiagnostic, d as ExtensionKind, dt as CLIOptions, en as UserReporter, et as Diagnostic, f as ExtensionMeta, ft as Config, g as Exclude, gt as KubbBuildStartContext, h as resolveMeta, ht as KubbBuildEndContext, i as AdapterFactoryOptions, in as SerializedDiagnostic, it as DiagnosticSeverity, j as PluginName, jt as KubbLifecycleStartContext, k as PluginDefinition, kt as KubbHooks, l as ExtensionDependencyRecord, lt as UpdateDiagnostic, m as defineExtension, mt as Input, n as AdapterDefinition, nn as logLevel, nt as DiagnosticKind, o as createAdapter, on as ParserDefinition, ot as PerformanceDiagnostic, p as checkCompatibility, pt as FilesContext, q as ResolverFilePathParams, qt as Storage, r as AdapterFactory, rn as DiagnosticFormatOptions, rt as DiagnosticLocation, s as ExtensionDependencies, sn as ParserFactory, st as ProblemCode, t as Adapter, tn as createReporter, tt as DiagnosticDoc, u as ExtensionFactory, ut as BuildOutput, v as Group, vt as KubbErrorContext, w as Output, wt as KubbGenerationStartContext, x as KubbPluginSetupContext, xt as KubbFilesProcessingStartContext, y as Include, yt as KubbFileProcessingUpdate, z as ResolveFileOptions, zt as HookResult } from "./createAdapter-B5kKMsWV.cjs";
2
- import { FileNode, Macro, UserFileNode } from "@kubb/ast";
1
+ import { Enforce, FileNode, HttpMethod, ImportNode, InputMeta, InputNode, Macro, Node, OperationNode, SchemaNode, UserFileNode } from "@kubb/ast";
3
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
+ //#region ../../internals/utils/src/promise.d.ts
4
+ /** A value that may already be resolved or still pending.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * function load(id: string): PossiblePromise<string> {
9
+ * return cache.get(id) ?? fetchRemote(id)
10
+ * }
11
+ * ```
12
+ */
13
+ type PossiblePromise<T> = Promise<T> | T;
14
+ //#endregion
15
+ //#region ../../internals/utils/src/types.d.ts
16
+ /** A union of known literals that still accepts any other value of `Base`, without collapsing
17
+ * the literals away. Editors keep autocompleting the known members while arbitrary strings stay
18
+ * assignable.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * type PluginName = LiteralUnion<'plugin-ts' | 'plugin-zod'>
23
+ * const a: PluginName = 'plugin-ts' // autocompletes
24
+ * const b: PluginName = 'anything' // still allowed
25
+ * ```
26
+ */
27
+ type LiteralUnion<T extends Base, Base = string> = T | (Base & {});
28
+ //#endregion
29
+ //#region src/defineParser.d.ts
30
+ /**
31
+ * Converts a resolved {@link FileNode} into the final source string that gets
32
+ * written to disk. Kubb ships with TypeScript and TSX parsers. Add your own
33
+ * for new file types (JSON, Markdown, ...).
34
+ */
35
+ type Parser<TMeta extends object = object, TNode = unknown, TOptions extends object = object> = ExtensionNamed & {
36
+ /**
37
+ * The options passed to the parser factory.
38
+ */
39
+ options?: TOptions;
40
+ /**
41
+ * File extensions this parser handles. The driver registers the parser for each
42
+ * extension in this list. A parser with `undefined` here is not registered, so
43
+ * files of an unclaimed extension fall back to joining their sources verbatim.
44
+ *
45
+ * @example
46
+ * `['.ts', '.js']`
47
+ */
48
+ extNames: Array<FileNode['extname']> | undefined;
49
+ /**
50
+ * Serialize the file's AST into source code.
51
+ */
52
+ parse(file: FileNode<TMeta>): string;
53
+ /**
54
+ * Turn the content of a `copy` file into a file node that `parse` prints. Omit to copy the file verbatim.
55
+ */
56
+ copy?(file: FileNode<TMeta>, source: string): UserFileNode<TMeta>;
57
+ /**
58
+ * Render compiler AST nodes for this parser's language into source text.
59
+ * Plugins call this to format the nodes they assemble before handing them
60
+ * back to the parser as `FileNode.sources`.
61
+ */
62
+ print(...nodes: Array<TNode>): string;
63
+ };
64
+ /**
65
+ * Takes the user's options and returns the parser methods.
66
+ */
67
+ type ParserBuild<TOptions extends object, TMeta extends object, TNode> = (options: TOptions) => Omit<Parser<TMeta, TNode>, 'name' | 'meta' | 'options'>;
68
+ /**
69
+ * The object passed to `defineExtension` with `kind: 'parser'`. `build` receives the user's options and returns the parser methods.
70
+ */
71
+ type ParserDefinition<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = {
72
+ meta: ExtensionMeta;
73
+ build: ParserBuild<TOptions, TMeta, TNode>;
74
+ };
75
+ /**
76
+ * The function `defineExtension` returns for a parser. Call it with user options to get a `Parser`.
77
+ */
78
+ type ParserFactory<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = ExtensionFactory<'parser', TOptions, Parser<TMeta, TNode, TOptions>>;
79
+ /**
80
+ * Defines a parser from one object and returns a factory that takes the user's options.
81
+ * Register the result in the `parsers` array on `defineConfig`.
82
+ *
83
+ * @deprecated Use `defineExtension` with `kind: 'parser'` instead.
84
+ */
85
+ export declare function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(definition: ParserDefinition<TOptions, TMeta, TNode>): ParserFactory<TOptions, TMeta, TNode>;
86
+ //#endregion
87
+ //#region src/diagnosticCatalog.d.ts
88
+ /**
89
+ * Every diagnostic code with its docs entry: a short title, what triggers it, and how to resolve
90
+ * it. The source of truth for {@link diagnosticCode}, and the kubb.dev `/reference/diagnostics`
91
+ * sections mirror it.
92
+ */
93
+ declare const diagnosticCatalog: {
94
+ readonly unknown: {
95
+ readonly code: "KUBB_UNKNOWN";
96
+ readonly title: "Unknown error";
97
+ readonly cause: "An error was thrown without a stable Kubb code, so it is reported as-is.";
98
+ readonly fix: "Read the underlying message and stack. If it comes from a plugin or adapter, check its configuration; otherwise report it as a possible Kubb bug.";
99
+ };
100
+ readonly inputNotFound: {
101
+ readonly code: "KUBB_INPUT_NOT_FOUND";
102
+ readonly title: "Input not found";
103
+ readonly cause: "The file set as `input` (or passed as `kubb generate PATH`) could not be read. A URL reports `KUBB_INPUT_REQUEST_FAILED` or `KUBB_INPUT_UNREACHABLE` instead.";
104
+ readonly fix: "Check that the path exists and is readable, then set it as `input` or pass it on the CLI.";
105
+ };
106
+ readonly inputRequestFailed: {
107
+ readonly code: "KUBB_INPUT_REQUEST_FAILED";
108
+ readonly title: "Input request failed";
109
+ readonly cause: "A URL set as `input` (or reached through a `$ref`) answered with a 4xx or 5xx status instead of the document.";
110
+ readonly fix: "Open the URL to see what the server returns. A 401 or 403 needs credentials Kubb does not send, so download the document and point `input` at the local file. A 404 means the path is wrong, and a 5xx means the server itself failed.";
111
+ };
112
+ readonly inputUnreachable: {
113
+ readonly code: "KUBB_INPUT_UNREACHABLE";
114
+ readonly title: "Input unreachable";
115
+ readonly cause: "A URL set as `input` (or reached through a `$ref`) never answered, so the request failed before a status came back. A refused connection, an unknown host, an expired certificate, and a timeout all land here.";
116
+ readonly fix: "Check that the host is running and reachable from this machine. For a local server, start it and confirm the port matches the one in `input`.";
117
+ };
118
+ readonly inputRequired: {
119
+ readonly code: "KUBB_INPUT_REQUIRED";
120
+ readonly title: "Input required";
121
+ readonly cause: "An adapter is configured but no `input` was provided.";
122
+ readonly fix: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.";
123
+ };
124
+ readonly legacyInput: {
125
+ readonly code: "KUBB_LEGACY_INPUT";
126
+ readonly title: "Legacy input shape";
127
+ readonly cause: "`input` is a `{ path }` or `{ data }` wrapper, which v4 used to point at a document and v5 reads as the document itself.";
128
+ readonly fix: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`.";
129
+ };
130
+ readonly invalidDocument: {
131
+ readonly code: "KUBB_INVALID_DOCUMENT";
132
+ readonly title: "Invalid document";
133
+ readonly cause: "The `input` cannot be read as an OpenAPI or Swagger document: its JSON or YAML has a syntax error, it declares no `openapi` or `swagger` version field, or its version cannot be upgraded to OpenAPI 3.1.";
134
+ readonly fix: "Fix the syntax at the reported line, and check that `input` points at the spec and not an HTML page. Point `input` at a Swagger 2.0, OpenAPI 3.0, or OpenAPI 3.1 document, and check that a passed object is the spec itself rather than a wrapper around it.";
135
+ };
136
+ readonly invalidSpec: {
137
+ readonly code: "KUBB_INVALID_SPEC";
138
+ readonly title: "Invalid spec";
139
+ readonly cause: "The document does not pass OpenAPI schema validation. Kubb still generates from it, but the output can be incomplete or wrong.";
140
+ readonly fix: "Fix the reported problem in the spec. Run `kubb validate` to list every error, or set `validate: false` on the adapter to skip the check.";
141
+ };
142
+ readonly refNotFound: {
143
+ readonly code: "KUBB_REF_NOT_FOUND";
144
+ readonly title: "Reference not found";
145
+ readonly cause: "A `$ref` could not be resolved in the source document.";
146
+ readonly fix: "Add the missing definition (for example under `components.schemas`) or fix the `$ref`. Run `kubb validate` to check the spec.";
147
+ };
148
+ readonly invalidServerVariable: {
149
+ readonly code: "KUBB_INVALID_SERVER_VARIABLE";
150
+ readonly title: "Invalid server variable";
151
+ readonly cause: "A server variable value is not allowed by its `enum`.";
152
+ readonly fix: "Use one of the values listed in the server variable `enum`, or update the spec.";
153
+ };
154
+ readonly pluginNotFound: {
155
+ readonly code: "KUBB_PLUGIN_NOT_FOUND";
156
+ readonly title: "Plugin not found";
157
+ readonly cause: "A plugin that another plugin depends on is missing from the config.";
158
+ readonly fix: "Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it.";
159
+ };
160
+ readonly incompatibleExtension: {
161
+ readonly code: "KUBB_INCOMPATIBLE_EXTENSION";
162
+ readonly title: "Incompatible extension";
163
+ readonly cause: "A plugin sets `meta.compatibility.kubb` or `meta.compatibility.node` to a range the running Kubb or Node.js version does not satisfy.";
164
+ readonly fix: "Upgrade Kubb or Node.js to a version in the range, or install a version of the plugin that supports your current Kubb and Node.js.";
165
+ };
166
+ readonly missingDependency: {
167
+ readonly code: "KUBB_MISSING_DEPENDENCY";
168
+ readonly title: "Missing dependency";
169
+ readonly cause: "A plugin lists another plugin in its `dependencies` record without `optional: true`, and the config does not include it.";
170
+ readonly fix: "Add the missing plugin to the `plugins` array in kubb.config.ts.";
171
+ };
172
+ readonly incompatibleDependency: {
173
+ readonly code: "KUBB_INCOMPATIBLE_DEPENDENCY";
174
+ readonly title: "Incompatible dependency";
175
+ readonly cause: "A plugin's `dependencies` record sets a `version` range, and the configured plugin's `meta.version` falls outside it.";
176
+ readonly fix: "Install a version of the dependency inside the range, or a version of the dependent plugin that supports the installed dependency.";
177
+ };
178
+ readonly pluginFailed: {
179
+ readonly code: "KUBB_PLUGIN_FAILED";
180
+ readonly title: "Plugin failed";
181
+ readonly cause: "A plugin threw while generating, or reported an error through `ctx.error`.";
182
+ readonly fix: "Check the plugin options and the node at `at:`. If it is a bug, report it with the stack at `report:`.";
183
+ };
184
+ readonly adapterFailed: {
185
+ readonly code: "KUBB_ADAPTER_FAILED";
186
+ readonly title: "Adapter failed";
187
+ readonly cause: "The adapter threw an unexpected error while parsing the input.";
188
+ readonly fix: "Check the input and the adapter options. If it is a bug, report it with the stack at `report:`.";
189
+ };
190
+ readonly parserFailed: {
191
+ readonly code: "KUBB_PARSER_FAILED";
192
+ readonly title: "Parser failed";
193
+ readonly cause: "A parser threw an unexpected error while printing a generated file.";
194
+ readonly fix: "Check the parser options. If it is a bug, report it with the stack at `report:`.";
195
+ };
196
+ readonly pluginWarning: {
197
+ readonly code: "KUBB_PLUGIN_WARNING";
198
+ readonly title: "Plugin warning";
199
+ readonly cause: "A plugin reported a non-fatal warning through `ctx.warn`.";
200
+ readonly fix: "Review the message. It does not fail the build; adjust the plugin options or input if the warning is unwanted.";
201
+ };
202
+ readonly pluginInfo: {
203
+ readonly code: "KUBB_PLUGIN_INFO";
204
+ readonly title: "Plugin info";
205
+ readonly cause: "A plugin reported an informational message through `ctx.info`.";
206
+ readonly fix: "Informational only. No action is required.";
207
+ };
208
+ readonly noContext: {
209
+ readonly code: "KUBB_NO_CONTEXT";
210
+ readonly title: "No plugin context";
211
+ readonly cause: "A `kubb/kit` composable such as `useKubb()` or `addGenerator()` ran outside the `setup` and `kubb:plugin:setup` of a plugin, so there is no plugin to apply it to.";
212
+ readonly fix: "Call the composable inside `setup` or `kubb:plugin:setup`, including in code that setup awaits.";
213
+ };
214
+ readonly unsupportedFormat: {
215
+ readonly code: "KUBB_UNSUPPORTED_FORMAT";
216
+ readonly title: "Unsupported format";
217
+ readonly cause: "A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.";
218
+ readonly fix: "Use a format Kubb supports, or handle the custom format with a parser or plugin.";
219
+ };
220
+ readonly deprecated: {
221
+ readonly code: "KUBB_DEPRECATED";
222
+ readonly title: "Deprecated";
223
+ readonly cause: "A referenced schema or operation is marked `deprecated`.";
224
+ readonly fix: "Migrate off the deprecated definition if the warning is unwanted.";
225
+ };
226
+ readonly adapterRequired: {
227
+ readonly code: "KUBB_ADAPTER_REQUIRED";
228
+ readonly title: "Adapter required";
229
+ readonly cause: "An action needs an adapter but none is configured.";
230
+ readonly fix: "Set `adapter` in kubb.config.ts, for example `adapterOas()`.";
231
+ };
232
+ readonly pathTraversal: {
233
+ readonly code: "KUBB_PATH_TRAVERSAL";
234
+ readonly title: "Path traversal";
235
+ readonly cause: "A resolved output path escaped the output directory, which can stem from a path traversal in the spec or a misconfigured `group.name`.";
236
+ readonly fix: "Keep generated paths within the output directory. Review the `group.name` function and the names coming from the spec.";
237
+ };
238
+ readonly cleanRoot: {
239
+ readonly code: "KUBB_CLEAN_ROOT";
240
+ readonly title: "Clean targets the project root";
241
+ readonly cause: "`output.clean` is enabled and `output.path` resolves to the project root or a parent of it, so cleaning would delete `kubb.config` and every source file.";
242
+ readonly fix: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code, or disable `output.clean`.";
243
+ };
244
+ readonly invalidPluginOptions: {
245
+ readonly code: "KUBB_INVALID_PLUGIN_OPTIONS";
246
+ readonly title: "Invalid plugin options";
247
+ readonly cause: "A plugin was configured with options that cannot be honored, for example `output.mode: 'file'` paired with a `group` option.";
248
+ readonly fix: "Fix the plugin options. A single-file output has nothing to group, so remove the `group` option or use `output.mode: 'directory'`.";
249
+ };
250
+ readonly postGenerateFailed: {
251
+ readonly code: "KUBB_POST_GENERATE_FAILED";
252
+ readonly title: "Post-generate command failed";
253
+ readonly cause: "A post-generate command (`output.postGenerate`) exited with a non-zero status.";
254
+ readonly fix: "Check the command is installed and correct, and run it manually to see the error.";
255
+ };
256
+ readonly formatFailed: {
257
+ readonly code: "KUBB_FORMAT_FAILED";
258
+ readonly title: "Format failed";
259
+ readonly cause: "The formatter pass over the generated files failed.";
260
+ readonly fix: "Check the formatter (oxfmt, biome, or prettier) is installed and its config is valid, then run it manually on the output.";
261
+ };
262
+ readonly lintFailed: {
263
+ readonly code: "KUBB_LINT_FAILED";
264
+ readonly title: "Lint failed";
265
+ readonly cause: "The linter pass over the generated files failed.";
266
+ readonly fix: "Check the linter (oxlint, biome, or eslint) is installed and its config is valid, then run it manually on the output.";
267
+ };
268
+ readonly barrelDuplicateExport: {
269
+ readonly code: "KUBB_BARREL_DUPLICATE_EXPORT";
270
+ readonly title: "Duplicate barrel export";
271
+ readonly cause: "Two generated modules export the same name, so the barrel cannot re-export both.";
272
+ readonly fix: "Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names.";
273
+ };
274
+ readonly internalError: {
275
+ readonly code: "KUBB_INTERNAL_ERROR";
276
+ readonly title: "Internal error";
277
+ readonly cause: "Kubb hit a state it does not expect. This is a bug in Kubb, not in your config.";
278
+ readonly fix: "Rerun with `--reporter json` or `--verbose` to get the stack. Then report it at https://github.com/kubb-labs/kubb/issues with the spec and config that trigger it.";
279
+ };
280
+ readonly performance: {
281
+ readonly code: "KUBB_PERFORMANCE";
282
+ readonly title: "Performance";
283
+ readonly cause: "Not a failure. Records a plugin’s elapsed time, summed into the run total.";
284
+ readonly fix: "No action. This is an informational metric.";
285
+ };
286
+ readonly updateAvailable: {
287
+ readonly code: "KUBB_UPDATE_AVAILABLE";
288
+ readonly title: "Update available";
289
+ readonly cause: "A newer Kubb version is published on npm than the one running.";
290
+ readonly fix: "Update the `@kubb/*` packages, for example `npm install -g @kubb/cli`, to get the latest fixes.";
291
+ };
292
+ };
293
+ /**
294
+ * Stable codes Kubb attaches to a `Diagnostic`, derived from {@link diagnosticCatalog}. Reference
295
+ * these instead of inlining the string at a throw site.
296
+ */
297
+ declare const diagnosticCode: { readonly [K in keyof typeof diagnosticCatalog]: (typeof diagnosticCatalog)[K]["code"]; };
298
+ /**
299
+ * Union of the stable {@link diagnosticCode} values.
300
+ */
301
+ type DiagnosticCode = (typeof diagnosticCode)[keyof typeof diagnosticCode];
302
+ //#endregion
303
+ //#region src/formatDiagnostic.d.ts
304
+ /**
305
+ * How {@link format} renders a diagnostic.
306
+ */
307
+ type DiagnosticFormatOptions = {
308
+ /**
309
+ * Who reads the output.
310
+ * - `'agent'` spells out every detail on labeled rows
311
+ * - `'human'` keeps it short and links to the docs
312
+ * @default 'agent'
313
+ */
314
+ audience?: 'agent' | 'human';
315
+ /**
316
+ * Show the root cause's full stack.
317
+ */
318
+ verbose?: boolean;
319
+ /**
320
+ * Columns the `human` headline fills, so the code lines up at the right edge.
321
+ * @default 0
322
+ */
323
+ width?: number;
324
+ };
325
+ /**
326
+ * A {@link Diagnostic} reduced to its JSON-safe fields plus a `docsUrl`, for
327
+ * machine-readable output (the `--reporter json` report, the MCP tools). Replaces the
328
+ * non-serializable `cause` with its message chain and drops the `kind`/`duration` bookkeeping.
329
+ */
330
+ type SerializedDiagnostic = {
331
+ code: DiagnosticCode;
332
+ severity: DiagnosticSeverity;
333
+ message: string;
334
+ /**
335
+ * Catalog title.
336
+ */
337
+ title?: string;
338
+ /**
339
+ * Catalog cause.
340
+ */
341
+ cause?: string;
342
+ location?: DiagnosticLocation;
343
+ /**
344
+ * The diagnostic's `help`, or the catalog fix.
345
+ */
346
+ help?: string;
347
+ plugin?: string;
348
+ issues?: string;
349
+ /**
350
+ * Messages of the underlying errors, outermost first.
351
+ */
352
+ causes?: Array<string>;
353
+ /**
354
+ * Root cause's stack, for `KUBB_UNKNOWN`, `KUBB_INTERNAL_ERROR`, and `*_FAILED` codes.
355
+ */
356
+ stack?: string;
357
+ /**
358
+ * The kubb.dev docs link for the code, omitted for the unknown fallback.
359
+ */
360
+ docsUrl?: string;
361
+ };
362
+ /**
363
+ * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
364
+ * consumers, with the catalog `title`, `cause`, and fix, and the `cause` error as `causes` and
365
+ * `stack`. Absent optional fields are omitted.
366
+ */
367
+ declare function serialize(diagnostic: Diagnostic): SerializedDiagnostic;
368
+ /**
369
+ * Renders a {@link Diagnostic} as lines: a headline, then indented detail rows. `agent` (the default)
370
+ * prints uncolored labeled rows (`at:`, `why:`, `fix:`, `caused by:`, `stack:` for a crash,
371
+ * `docs:`, `report:`). `human` prints an icon, the bold message, and the code aligned to `width`,
372
+ * with `at`, `fix`, the first cause, and `Learn more` for an error, and one row for a warning.
373
+ * `verbose` adds the full stack.
374
+ */
375
+ declare function format(diagnostic: Diagnostic, { audience, verbose, width }?: DiagnosticFormatOptions): Array<string>;
376
+ //#endregion
377
+ //#region src/createReporter.d.ts
378
+ /**
379
+ * Numeric log-level thresholds used internally to compare verbosity.
380
+ *
381
+ * Higher numbers are more verbose.
382
+ */
383
+ export declare const logLevel: {
384
+ readonly silent: number;
385
+ readonly error: 0;
386
+ readonly warn: 1;
387
+ readonly info: 3;
388
+ readonly verbose: 4;
389
+ };
390
+ /**
391
+ * A built-in reporter that renders a run's output, independent of the live logger view.
392
+ *
393
+ * - `cli` renders the per-config summary to the terminal (the default).
394
+ * - `json` writes a machine-readable report to stdout, for CI.
395
+ * - `file` writes a config's diagnostics to `.kubb/kubb-<name>-<timestamp>.log`.
396
+ * - `html` writes a browsable report directory to `.kubb/kubb-<name>-<timestamp>/`.
397
+ */
398
+ type ReporterName = 'cli' | 'json' | 'file' | 'html';
399
+ /**
400
+ * Files attributed to the plugin that first added them.
401
+ */
402
+ type ReporterPluginFiles = Array<{
403
+ /** Plugin name. */
404
+ plugin: string;
405
+ /** Generated file paths. */
406
+ files: Array<string>;
407
+ }>;
408
+ /**
409
+ * One config's outcome within a run, as handed to a {@link Reporter}.
410
+ */
411
+ type GenerationResult = {
412
+ config: Config;
413
+ /**
414
+ * Diagnostics collected while generating this config.
415
+ */
416
+ diagnostics: Array<Diagnostic>;
417
+ /**
418
+ * Number of files written for this config.
419
+ */
420
+ filesCreated: number;
421
+ status: 'success' | 'failed';
422
+ /**
423
+ * `process.hrtime()` snapshot taken when this config started generating.
424
+ */
425
+ hrStart: [number, number];
426
+ /**
427
+ * Files attributed to the plugin that first added them, when requested by a reporter.
428
+ */
429
+ pluginFiles?: ReporterPluginFiles;
430
+ };
431
+ /**
432
+ * Render settings passed alongside the {@link GenerationResult}. These are not part of the run
433
+ * data, such as the output verbosity.
434
+ */
435
+ type ReporterContext = {
436
+ /**
437
+ * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`
438
+ * (`silent`, `error`, `warn`, `info`, `verbose`).
439
+ */
440
+ logLevel: (typeof logLevel)[keyof typeof logLevel];
441
+ };
442
+ /**
443
+ * Host-facing reporter, as installed onto a run. Unlike a Logger (the live TUI view), a reporter
444
+ * never sees the hook emitter. `report` runs once per config. `drain`, when present, runs once
445
+ * after the last config.
446
+ */
447
+ type Reporter = {
448
+ /**
449
+ * Display name, matching a {@link ReporterName} for the built-ins.
450
+ */
451
+ name: LiteralUnion<ReporterName>;
452
+ /**
453
+ * Called once per config with that config's result and the render context.
454
+ */
455
+ report: (result: GenerationResult, context: ReporterContext) => void | Promise<void>;
456
+ /**
457
+ * Optional finalizer called once after the run's last config. The host wires it to
458
+ * `kubb:lifecycle:end`. {@link createReporter} closes it over the values that `report` returned.
459
+ */
460
+ drain: (context: ReporterContext) => void | Promise<void>;
461
+ /**
462
+ * Whether the host should collect files from `kubb:plugin:end` hooks.
463
+ */
464
+ needsPluginFiles?: boolean;
465
+ };
466
+ /**
467
+ * Reporter definition passed to {@link createReporter}. `report` returns the value to collect for
468
+ * this config (e.g. a built report), and the optional `drain` receives the collected reports to
469
+ * emit as one document. `T` is inferred from `report`'s return type.
470
+ */
471
+ type UserReporter<T = void> = {
472
+ name: LiteralUnion<ReporterName>;
473
+ /**
474
+ * Whether the host should collect files from `kubb:plugin:end` hooks.
475
+ */
476
+ needsPluginFiles?: boolean;
477
+ report: (result: GenerationResult, context: ReporterContext) => T | Promise<T>;
478
+ drain?: (context: ReporterContext, reports: Array<T>) => void | Promise<void>;
479
+ };
480
+ /**
481
+ * Defines a reporter. The returned reporter buffers each value `report` returns in order and, when
482
+ * the definition has a `drain`, hands the array to `drain` once and then clears it. Wiring the
483
+ * reporter onto the run's hooks is the host's job, so the reporter only ever deals with a
484
+ * {@link GenerationResult}.
485
+ *
486
+ * @example
487
+ * ```ts
488
+ * import { createReporter, Diagnostics } from '@kubb/core'
489
+ *
490
+ * export const jsonReporter = createReporter({
491
+ * name: 'json',
492
+ * report(result) {
493
+ * return { status: Diagnostics.hasError(result.diagnostics) ? 'failed' : 'success', diagnostics: result.diagnostics }
494
+ * },
495
+ * drain(context, reports) {
496
+ * process.stdout.write(`${JSON.stringify(reports, null, 2)}\n`)
497
+ * },
498
+ * })
499
+ * ```
500
+ */
501
+ export declare function createReporter<T = void>(reporter: UserReporter<T>): Reporter;
502
+ //#endregion
503
+ //#region src/createStorage.d.ts
504
+ /**
505
+ * Backend that persists generated files. Kubb ships with `fsStorage` (writes
506
+ * to disk) and `memoryStorage` (keeps everything in RAM). Implement this
507
+ * interface to write somewhere else, such as S3 or a database.
508
+ *
509
+ * Method names follow Node's filesystem vocabulary, so `readItem` reads like
510
+ * `readFile` and `writeItem` like `writeFile`.
511
+ */
512
+ type Storage = {
513
+ /**
514
+ * Identifier used in logs and diagnostics (`'fs'`, `'memory'`, `'s3'`).
515
+ */
516
+ readonly name: string;
517
+ /**
518
+ * Reads the stored string. Returns `null` when the key is missing.
519
+ */
520
+ readItem(key: string): Promise<string | null>;
521
+ /**
522
+ * Stores `value` under `key`, creating any required structure (directories,
523
+ * buckets, ...).
524
+ *
525
+ * Pass `stored` when the caller already read the previous value to avoid
526
+ * reading it again in storage implementations that support the optimization.
527
+ */
528
+ writeItem(key: string, value: string, options?: {
529
+ stored?: string | null;
530
+ }): Promise<void>;
531
+ /**
532
+ * Deletes the entry for `key`. No-op when the key does not exist.
533
+ */
534
+ removeItem(key: string): Promise<void>;
535
+ /**
536
+ * Returns every key. Pass `base` to filter to keys starting with that prefix.
537
+ */
538
+ readKeys(base?: string): Promise<Array<string>>;
539
+ /**
540
+ * Removes stored entries. Pass `base` to scope the wipe to a key prefix.
541
+ *
542
+ * Omitting `base` is implementation-defined: in-memory stores wipe every
543
+ * entry, while filesystem-backed stores treat a missing `base` as a no-op so
544
+ * a bare `empty()` can never delete outside a known output directory.
545
+ */
546
+ empty(base?: string): Promise<void>;
547
+ };
548
+ /**
549
+ * Defines a custom storage backend. The builder receives user options and
550
+ * returns a `Storage` implementation. Kubb ships with filesystem and in-memory
551
+ * storages. A custom backend writes generated files elsewhere, such as cloud
552
+ * storage or a database.
553
+ *
554
+ * @example In-memory storage (the built-in implementation)
555
+ * ```ts
556
+ * import { createStorage } from '@kubb/core'
557
+ *
558
+ * export const memoryStorage = createStorage(() => {
559
+ * const store = new Map<string, string>()
560
+ *
561
+ * return {
562
+ * name: 'memory',
563
+ * async readItem(key) {
564
+ * return store.get(key) ?? null
565
+ * },
566
+ * async writeItem(key, value) {
567
+ * store.set(key, value)
568
+ * },
569
+ * async removeItem(key) {
570
+ * store.delete(key)
571
+ * },
572
+ * async readKeys(base) {
573
+ * const keys = [...store.keys()]
574
+ * return base ? keys.filter((k) => k.startsWith(base)) : keys
575
+ * },
576
+ * async empty(base) {
577
+ * if (!base) store.clear()
578
+ * },
579
+ * }
580
+ * })
581
+ * ```
582
+ */
583
+ export declare const createStorage: <TOptions = Record<string, never>>(build: (options: TOptions) => Storage) => (options?: TOptions) => Storage;
584
+ //#endregion
585
+ //#region src/createRenderer.d.ts
586
+ /**
587
+ * Minimal interface any Kubb renderer must satisfy.
588
+ *
589
+ * `TElement` is the type the renderer accepts, for example `KubbReactElement`
590
+ * for `@kubb/renderer-jsx` or a custom type for your own renderer. Defaults to
591
+ * `unknown` so generators that don't care about the element type work without
592
+ * specifying it.
593
+ */
594
+ type Renderer<TElement = unknown> = {
595
+ /**
596
+ * Renders `element` and populates {@link files} with the resulting {@link FileNode} objects.
597
+ * Called once per render cycle. Must resolve before {@link files} is read.
598
+ */
599
+ render(element: TElement): Promise<void>;
600
+ /**
601
+ * Accumulated {@link FileNode} results produced by the last {@link render} call.
602
+ */
603
+ readonly files: Array<FileNode>;
604
+ /**
605
+ * Disposer hook so renderers participate in `using` blocks: `using r = rendererFactory()`
606
+ * runs cleanup on every exit path, including thrown errors.
607
+ */
608
+ [Symbol.dispose](): void;
609
+ };
610
+ /**
611
+ * A factory function that produces a fresh {@link Renderer} per render cycle.
612
+ *
613
+ * Generators use this to declare which renderer handles their output.
614
+ */
615
+ type RendererFactory<TElement = unknown> = () => Renderer<TElement>;
616
+ /**
617
+ * Defines a renderer factory. Renderers turn the generator's return value
618
+ * (JSX, a template string, a tree of any shape) into `FileNode`s that get
619
+ * written to disk.
620
+ *
621
+ * A renderer can target output formats beyond JSX, for instance a Handlebars
622
+ * renderer or one that writes binary files. Plugins and generators pick the
623
+ * renderer to use via the `renderer` field on `defineGenerator`.
624
+ *
625
+ * @example A minimal renderer that wraps a custom runtime
626
+ * ```ts
627
+ * import { createRenderer } from '@kubb/core'
628
+ *
629
+ * export const myRenderer = createRenderer(() => {
630
+ * const runtime = new MyRuntime()
631
+ * return {
632
+ * async render(element) {
633
+ * await runtime.render(element)
634
+ * },
635
+ * get files() {
636
+ * return runtime.files
637
+ * },
638
+ * [Symbol.dispose]() {
639
+ * runtime.dispose()
640
+ * },
641
+ * }
642
+ * })
643
+ * ```
644
+ */
645
+ export declare function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement>;
646
+ //#endregion
647
+ //#region src/outputManifest.d.ts
648
+ /**
649
+ * Remembers what the output passes did to each generated file, so the next run can tell "the
650
+ * formatter already turned this exact source into what is stored" apart from a real change.
651
+ * Without it the storage compares Kubb's bytes against the formatter's, never matches, and
652
+ * rewrites the whole output tree on every build.
653
+ */
654
+ type OutputManifest = {
655
+ /**
656
+ * `true` when `source` is known to come out of the output passes as exactly the content stored,
657
+ * meaning the write can be skipped.
658
+ */
659
+ isUpToDate(options: {
660
+ key: string;
661
+ source: string;
662
+ disk: string;
663
+ }): boolean;
664
+ /**
665
+ * Records the source Kubb wrote for `key`, marking it as the only kind of file the output passes
666
+ * can have changed and so the only kind `commit` has to re-read.
667
+ */
668
+ track(options: {
669
+ key: string;
670
+ source: string;
671
+ }): void;
672
+ /**
673
+ * Re-reads the files written this run and persists their source/output pairs on top of what is
674
+ * stored. Nothing is pruned: a run generating a different set of files, or writing to a different
675
+ * storage in the same root, must not evict what another run recorded.
676
+ */
677
+ commit(): Promise<void>;
678
+ };
679
+ //#endregion
680
+ //#region src/Hookable.d.ts
681
+ /**
682
+ * A function that can be registered as a hook listener, synchronous or async. Any return value is
683
+ * allowed and ignored, so handlers that return a result for their own callers still register.
684
+ */
685
+ type AsyncListener<TArgs extends Array<unknown>> = (...args: TArgs) => unknown;
686
+ /**
687
+ * Typed hook emitter that awaits all async listeners before resolving.
688
+ *
689
+ * @example
690
+ * ```ts
691
+ * const hooks = new Hookable<{ build: [name: string] }>()
692
+ * hooks.hook('build', async (name) => { console.log(name) })
693
+ * await hooks.callHook('build', 'petstore') // all listeners awaited
694
+ * ```
695
+ */
696
+ export declare class Hookable<THooks extends { [K in keyof THooks]: Array<unknown>; }> {
697
+ #private;
698
+ /**
699
+ * Calls `hookName` and awaits all registered listeners sequentially.
700
+ * Throws if any listener rejects, wrapping the cause in an error that names the hook.
701
+ *
702
+ * @example
703
+ * ```ts
704
+ * await hooks.callHook('build', 'petstore')
705
+ * ```
706
+ */
707
+ callHook<THookName extends keyof THooks & string>(hookName: THookName, ...hookArgs: THooks[THookName]): Promise<void> | void;
708
+ /**
709
+ * Registers a persistent listener for `hookName` and returns a function that removes it.
710
+ *
711
+ * @example
712
+ * ```ts
713
+ * const unhook = hooks.hook('build', async (name) => { console.log(name) })
714
+ * unhook() // removes it
715
+ * ```
716
+ */
717
+ hook<THookName extends keyof THooks & string>(hookName: THookName, handler: AsyncListener<THooks[THookName]>): () => void;
718
+ /**
719
+ * Registers every handler in `configHooks` at once and returns a function that removes them
720
+ * all. Undefined entries are skipped, so a partial hook object registers only its present keys.
721
+ *
722
+ * @example
723
+ * ```ts
724
+ * const unhook = hooks.addHooks({ build: onBuild, done: onDone })
725
+ * unhook() // removes both
726
+ * ```
727
+ */
728
+ addHooks(configHooks: Partial<{ [K in keyof THooks & string]: AsyncListener<THooks[K]>; }>): () => void;
729
+ /**
730
+ * Removes a previously registered listener.
731
+ *
732
+ * @example
733
+ * ```ts
734
+ * hooks.removeHook('build', handler)
735
+ * ```
736
+ */
737
+ removeHook<THookName extends keyof THooks & string>(hookName: THookName, handler: AsyncListener<THooks[THookName]>): void;
738
+ /**
739
+ * Returns the number of listeners registered for `hookName`.
740
+ *
741
+ * @example
742
+ * ```ts
743
+ * hooks.hook('build', handler)
744
+ * hooks.listenerCount('build') // 1
745
+ * ```
746
+ */
747
+ listenerCount<THookName extends keyof THooks & string>(hookName: THookName): number;
748
+ /**
749
+ * No-op kept for callers written against the `EventEmitter`-backed version. Listeners are unbounded.
750
+ *
751
+ * @deprecated There is no listener ceiling anymore.
752
+ */
753
+ setMaxListeners(_max: number): void;
754
+ /**
755
+ * Removes all listeners from every hook channel.
756
+ *
757
+ * @example
758
+ * ```ts
759
+ * hooks.removeAllHooks()
760
+ * ```
761
+ */
762
+ removeAllHooks(): void;
763
+ }
764
+ //#endregion
765
+ //#region src/FileManager.d.ts
766
+ type ParseOptions = {
767
+ parsers?: Map<FileNode['extname'], Parser>;
768
+ };
769
+ type WriteOptions = ParseOptions & {
770
+ storage: Storage;
771
+ signal?: AbortSignal;
772
+ /**
773
+ * Consulted before each write so a file the output passes already normalized is recognized as
774
+ * unchanged. Omitted when no formatter, linter, or `postGenerate` step is configured.
775
+ */
776
+ manifest?: OutputManifest;
777
+ /**
778
+ * Receives `kubb:files:processing:start`, `:update` (one batch, in input order) and `:end` for the write. `config` fills the update rows.
779
+ */
780
+ hooks?: Hookable<KubbHooks>;
781
+ config?: Config;
782
+ };
783
+ /**
784
+ * In-memory file store for generated files, and the writer that turns them into source
785
+ * strings on `storage`. Files sharing a `path` are merged (sources/imports/exports
786
+ * concatenated). The `files` getter is sorted by path length (barrel `index.ts` last
787
+ * within a bucket).
788
+ *
789
+ * @example
790
+ * ```ts
791
+ * const manager = new FileManager()
792
+ * manager.upsert(myFile)
793
+ * manager.files // sorted view
794
+ * await manager.write(manager.files, { storage: fsStorage() })
795
+ * ```
796
+ */
797
+ declare class FileManager {
798
+ #private;
799
+ add(...files: Array<FileNode>): Array<FileNode>;
800
+ upsert(...files: Array<FileNode>): Array<FileNode>;
801
+ /** Stores a generator result: a file array is upserted as is, an element renders through `renderer` first, falsy is a no-op. */
802
+ dispatch<TElement = unknown>({ result, renderer }: {
803
+ result: TElement | Array<FileNode> | undefined | null;
804
+ renderer?: RendererFactory<TElement> | null;
805
+ }): Promise<void>;
806
+ /**
807
+ * Releases all stored files. Called by the core after `kubb:build:end`.
808
+ */
809
+ dispose(): void;
810
+ /**
811
+ * All stored files in stable sort order (shortest path first, barrel files
812
+ * last within a length bucket). Returns a cached view, do not mutate.
813
+ */
814
+ get files(): Array<FileNode>;
815
+ /**
816
+ * Converts a file's AST sources (or its `copy` source) into the final on-disk string.
817
+ */
818
+ parse(file: FileNode, { parsers }?: ParseOptions): Promise<string>;
819
+ /**
820
+ * Parses and writes every file through a bounded pool of workers. A small spec runs all its files
821
+ * at once; a spec with thousands of files keeps at most {@link FILE_CONCURRENCY} parsed sources in
822
+ * memory rather than holding every source, while still overlapping each file's write with the
823
+ * next file's parse. Files finish in whatever order they parse, so the update rows are sorted back
824
+ * into input order before `kubb:files:processing:update` fires once with the whole batch.
825
+ *
826
+ * A file the storage already holds is skipped, so a rebuild that generates identical output
827
+ * writes nothing and leaves every mtime where it was.
828
+ */
829
+ write(files: Array<FileNode>, { storage, parsers, manifest, signal, hooks, config }: WriteOptions): Promise<void>;
830
+ }
831
+ //#endregion
832
+ //#region src/KubbDriver.d.ts
833
+ type Options = {
834
+ hooks: Hookable<KubbHooks>;
835
+ signal?: AbortSignal;
836
+ /**
837
+ * Passed to `fileManager.write` so files the output passes already normalized are left alone.
838
+ */
839
+ manifest?: OutputManifest;
840
+ /**
841
+ * The output directory `output.clean` empties. Emptied right before the files are written, so a
842
+ * run that fails earlier leaves the previous output in place.
843
+ */
844
+ cleanPath?: string;
845
+ };
846
+ type RequirePluginContext = {
847
+ /**
848
+ * Name of the plugin that declared the dependency, included in the error so users can
849
+ * trace which plugin needs the missing one.
850
+ */
851
+ requiredBy?: string;
852
+ };
853
+ export declare class KubbDriver {
854
+ #private;
855
+ readonly config: Config;
856
+ readonly options: Options;
857
+ /**
858
+ * The `InputNode` produced by the adapter. Set after adapter setup.
859
+ */
860
+ inputNode: InputNode | null;
861
+ adapter: Adapter | null;
862
+ /**
863
+ * Central file store for all generated files.
864
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
865
+ * add files. This property gives direct read/write access when needed.
866
+ */
867
+ readonly fileManager: FileManager;
868
+ readonly plugins: Map<string, NormalizedPlugin>;
869
+ constructor(config: Config, options: Options);
870
+ /**
871
+ * Checks the adapter's and parsers' `meta.compatibility`, then normalizes and checks every configured plugin, orders them, and registers their lifecycle handlers.
872
+ * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
873
+ * `'post'`. When the config has an adapter, the adapter source is resolved from the input
874
+ * so `run` can parse it later.
875
+ */
876
+ setup(): Promise<void>;
877
+ get hooks(): Hookable<Kubb.KubbHooksRegistry>;
878
+ /**
879
+ * Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
880
+ * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
881
+ * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
882
+ * plugins can configure generators, resolvers, macros, and options before `buildStart`.
883
+ */
884
+ setupHooks(): Promise<void>;
885
+ /**
886
+ * Runs the full plugin pipeline. Returns the diagnostics collected so far even
887
+ * when an outer hook throws, since the orchestrator preserves partial state by capturing
888
+ * the failure as a {@link Diagnostic} instead of propagating. Each plugin also
889
+ * contributes a `timing` diagnostic for the run summary.
890
+ */
891
+ run(): Promise<{
892
+ diagnostics: Array<Diagnostic>;
893
+ }>;
894
+ /**
895
+ * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
896
+ * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
897
+ *
898
+ * @internal
899
+ */
900
+ dispose(): void;
901
+ [Symbol.dispose](): void;
902
+ /** Reads `plugin.resolver`, falling back to a fresh default for a name that is not a registered plugin. */
903
+ getResolver<TName extends PluginName>(pluginName: TName): ResolvePluginOptions<TName>['resolver'];
904
+ getContext<TOptions extends PluginType>(plugin: NormalizedPlugin<TOptions>): Omit<GeneratorContext<TOptions>, 'options' | 'cache'>;
905
+ getPlugin<TName extends PluginName>(pluginName: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
906
+ /**
907
+ * Like `getPlugin` but throws a descriptive error when the plugin is not found.
908
+ */
909
+ requirePlugin<TName extends PluginName>(pluginName: TName, context?: RequirePluginContext): Plugin<ResolvePluginOptions<TName>>;
910
+ }
911
+ //#endregion
912
+ //#region src/output/runHook.d.ts
913
+ /**
914
+ * Outcome of one hook subprocess, also carried by the `kubb:hook:end` hook it emits.
915
+ */
916
+ type HookResult = {
917
+ success: true;
918
+ error: null;
919
+ } | {
920
+ success: false;
921
+ error: Error;
922
+ stdout?: string;
923
+ stderr?: string;
924
+ };
925
+ type RunHookOptions = {
926
+ hooks: Hookable<KubbHooks>;
927
+ /** Executable to run, resolved on `PATH` and in every `node_modules/.bin` above `cwd`. */
928
+ command: string;
929
+ args?: ReadonlyArray<string>;
930
+ /** Label shown instead of the command line, for example a `postGenerate` step name. */
931
+ name?: string;
932
+ /** Working directory for the command. Defaults to the current process directory. */
933
+ cwd?: string;
934
+ signal?: AbortSignal;
935
+ };
936
+ /**
937
+ * Spawns a command and returns its outcome, announcing it through `kubb:hook:start`,
938
+ * `kubb:hook:line` (one per stdout or stderr line, only while a listener is attached) and
939
+ * `kubb:hook:end`. A non-zero exit, a spawn failure, an abort or a throwing line listener returns
940
+ * `success: false` instead of throwing. The failure travels on the result and `kubb:hook:end`
941
+ * only, and the caller emits `kubb:success` or a diagnostic, so nothing is reported twice.
942
+ */
943
+ export declare function runHook({ hooks, command, args, name, cwd, signal }: RunHookOptions): Promise<HookResult>;
944
+ //#endregion
945
+ //#region src/types.d.ts
946
+ /**
947
+ * Source to generate from. Kubb detects what it was given:
948
+ *
949
+ * - A string that is a local file path (absolute or relative to the config file) or a URL is
950
+ * read and parsed by the adapter (e.g. an OpenAPI YAML or JSON spec).
951
+ * - A string that is inline OpenAPI content (JSON or YAML) is parsed directly.
952
+ * - A parsed object is used as-is, without touching the filesystem.
953
+ *
954
+ * @example
955
+ * ```ts
956
+ * './petstore.yaml' // local path
957
+ * 'https://example.com/openapi.json' // URL
958
+ * '{ "openapi": "3.1.0", "info": {...} }' // inline JSON
959
+ * { openapi: '3.1.0', info: { ... } } // parsed object
960
+ * ```
961
+ */
962
+ export type Input = string | Record<string, unknown>;
963
+ /**
964
+ * A post-generate step: a shell command string, or an object that pairs the command with a `name`
965
+ * shown in the CLI output. Steps run in sequence after the generated files are formatted and linted.
966
+ */
967
+ export type PostGenerateCommand = string | {
968
+ name?: string;
969
+ command: string;
970
+ };
971
+ /**
972
+ * Resolved build configuration for a Kubb run: what to generate from (adapter, input), where to
973
+ * write it (output), how (plugins), and the runtime pieces (parsers, storage). See
974
+ * `UserConfig` for the relaxed form with defaults applied.
975
+ *
976
+ * @private
977
+ */
978
+ export type Config<TInput = Input> = {
979
+ /**
980
+ * Display name for this configuration in CLI output and logs.
981
+ * Useful when running multiple builds with `defineConfig` arrays.
982
+ *
983
+ * @example
984
+ * ```ts
985
+ * name: 'api-client'
986
+ * ```
987
+ */
988
+ name?: string;
989
+ /**
990
+ * Project root directory, absolute or relative to the config file. Already
991
+ * resolved on the `Config` instance (see `UserConfig` for the optional
992
+ * form that defaults to `process.cwd()`).
993
+ */
994
+ root: string;
995
+ /**
996
+ * Parsers that convert generated files into strings. Each parser handles a
997
+ * set of file extensions, and a fallback parser handles anything else.
998
+ *
999
+ * Already resolved on the `Config` instance (see `UserConfig` for the
1000
+ * optional form that defaults to `[parserTs(), parserTsx(), parserMd()]`).
1001
+ *
1002
+ * @example
1003
+ * ```ts
1004
+ * import { defineConfig } from 'kubb'
1005
+ * import { parserTs, parserTsx } from '@kubb/parser-ts'
1006
+ *
1007
+ * export default defineConfig({
1008
+ * parsers: [parserTs(), parserTsx()],
1009
+ * })
1010
+ * ```
1011
+ */
1012
+ parsers: Array<Parser>;
1013
+ /**
1014
+ * Adapter that parses input files into the universal AST representation.
1015
+ * Use `@kubb/adapter-oas` for OpenAPI/Swagger or `@kubb/adapter-asyncapi` for other formats.
1016
+ *
1017
+ * When omitted, Kubb runs in plugin-only mode: `kubb:plugin:setup` fires and files
1018
+ * injected via `injectFile` are written, but no AST walk occurs and generator hooks
1019
+ * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.
1020
+ *
1021
+ * @example
1022
+ * ```ts
1023
+ * import { adapterOas } from '@kubb/adapter-oas'
1024
+ * export default defineConfig({
1025
+ * adapter: adapterOas(),
1026
+ * input: './petstore.yaml',
1027
+ * })
1028
+ * ```
1029
+ */
1030
+ adapter?: Adapter;
1031
+ /**
1032
+ * Source to generate code from: a local file path, a URL, inline OpenAPI content
1033
+ * (JSON or YAML string), or a parsed spec object. Kubb detects which one it was given.
1034
+ * Required when an adapter is configured. Omit it when running in plugin-only mode.
1035
+ */
1036
+ input?: TInput;
1037
+ output: {
1038
+ /**
1039
+ * Output directory for generated files, absolute or relative to `root`. Plugins can nest
1040
+ * subdirectories under it by grouping strategy (tag, path).
1041
+ *
1042
+ * @example
1043
+ * ```ts
1044
+ * output: {
1045
+ * path: './src/gen', // generates ./src/gen/api.ts, ./src/gen/types.ts, etc.
1046
+ * }
1047
+ * ```
1048
+ */
1049
+ path: string;
1050
+ /**
1051
+ * Remove every file in the output directory before the build, so stale output isn't mixed
1052
+ * with new files. Leave `false` to preserve manual edits in the output directory.
1053
+ *
1054
+ * clean only removes generated code. When `path` resolves to the project root or an ancestor
1055
+ * of it, the build throws instead of wiping `kubb.config` and your source files.
1056
+ *
1057
+ * @example
1058
+ * ```ts
1059
+ * clean: true // wipes ./src/gen/* before generating
1060
+ * ```
1061
+ */
1062
+ clean?: boolean;
1063
+ /**
1064
+ * Format the generated files after generation. `'auto'` runs the first formatter it finds
1065
+ * (oxfmt, biome, or prettier), a named tool forces that one, and `false` skips formatting.
1066
+ *
1067
+ * @example
1068
+ * ```ts
1069
+ * format: 'auto' // auto-detect oxfmt, biome, or prettier
1070
+ * format: 'prettier' // force prettier
1071
+ * format: false // skip formatting
1072
+ * ```
1073
+ */
1074
+ format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false;
1075
+ /**
1076
+ * Lint the generated files after generation. `'auto'` runs the first linter it finds
1077
+ * (oxlint, biome, or eslint), a named tool forces that one, and `false` skips linting.
1078
+ *
1079
+ * @example
1080
+ * ```ts
1081
+ * lint: 'auto' // auto-detect oxlint, biome, or eslint
1082
+ * lint: 'eslint' // force eslint
1083
+ * lint: false // skip linting
1084
+ * ```
1085
+ */
1086
+ lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false;
1087
+ /**
1088
+ * Shell commands to run after the generated files are formatted and linted, for post-processing
1089
+ * such as a type check or a custom script. Steps run in sequence from the `root` directory. Pass
1090
+ * a plain command string, or `{ name, command }` to label the step in the CLI output.
1091
+ *
1092
+ * @example
1093
+ * ```ts
1094
+ * postGenerate: ['npm run typecheck']
1095
+ * postGenerate: [{ name: 'types', command: 'npm run typecheck' }, 'biome check --write ./src/gen']
1096
+ * ```
1097
+ */
1098
+ postGenerate?: Array<PostGenerateCommand>;
1099
+ /**
1100
+ * Banner prepended to every generated file. `'simple'` is the basic Kubb notice, `'full'` adds
1101
+ * source, title, and OpenAPI spec version, and `false` omits it.
1102
+ *
1103
+ * @default 'simple'
1104
+ * @example
1105
+ * ```ts
1106
+ * defaultBanner: 'simple' // "Generated by Kubb (https://kubb.dev/). Do not edit manually."
1107
+ * defaultBanner: 'full' // adds source, title, and OpenAPI spec version
1108
+ * defaultBanner: false // no banner
1109
+ * ```
1110
+ */
1111
+ defaultBanner?: 'simple' | 'full' | false;
1112
+ } & ExtractRegistryKey<Kubb.ConfigOptionsRegistry, 'output'>;
1113
+ /**
1114
+ * Where generated files are persisted. Defaults to `fsStorage()` (disk). Pass `memoryStorage()`
1115
+ * to keep files in RAM, or implement `Storage` for a custom backend such as cloud or a database.
1116
+ *
1117
+ * @default fsStorage()
1118
+ * @example
1119
+ * ```ts
1120
+ * import { memoryStorage } from '@kubb/core'
1121
+ *
1122
+ * // Keep generated files in memory (useful for testing, CI pipelines)
1123
+ * storage: memoryStorage()
1124
+ *
1125
+ * // Use custom S3 storage
1126
+ * storage: myS3Storage()
1127
+ * ```
1128
+ *
1129
+ * @see {@link Storage} interface for implementing custom backends.
1130
+ */
1131
+ storage: Storage;
1132
+ /**
1133
+ * Plugins that run during the build to generate code and transform the AST. Each one processes
1134
+ * the adapter's AST and can emit files for a different target (TypeScript, Zod, Faker). A plugin
1135
+ * that depends on another throws when that plugin isn't registered.
1136
+ *
1137
+ * @example
1138
+ * ```ts
1139
+ * import { pluginTs } from '@kubb/plugin-ts'
1140
+ * import { pluginZod } from '@kubb/plugin-zod'
1141
+ *
1142
+ * plugins: [
1143
+ * pluginTs({ output: { path: './src/gen' } }),
1144
+ * pluginZod({ output: { path: './src/gen' } }),
1145
+ * ]
1146
+ * ```
1147
+ */
1148
+ plugins: Array<Plugin>;
1149
+ /**
1150
+ * The reporters available to the run, registered as instances. The host
1151
+ * (the CLI via `--reporter`) selects which ones to trigger by `name` with {@link selectReporters}.
1152
+ * `defineConfig` from the `kubb` package registers the built-in `cli`, `json`, `file`, and
1153
+ * `html` reporters by default.
1154
+ *
1155
+ * - `cli` writes the end-of-run summary to the terminal.
1156
+ * - `json` writes a machine-readable report to stdout, for CI.
1157
+ * - `file` writes a debug log to `.kubb/<name>-<timestamp>.log`.
1158
+ * - `html` writes a static HTML report; opt-in via `--reporter html`.
1159
+ *
1160
+ * @example
1161
+ * ```ts
1162
+ * import { cliReporter, jsonReporter } from '@kubb/core'
1163
+ *
1164
+ * reporters: [cliReporter, jsonReporter, myReporter]
1165
+ * ```
1166
+ */
1167
+ reporters: Array<Reporter>;
1168
+ };
1169
+ /**
1170
+ * Partial `Config` for user-facing entry points with sensible defaults.
1171
+ *
1172
+ * `UserConfig` is what you pass to `defineConfig()`. It has optional `root`, `plugins`, `parsers`, and `adapter`
1173
+ * fields (which fall back to sensible defaults). All other Config options are available, including `output`, `input`,
1174
+ * `storage`, and `hooks`.
1175
+ *
1176
+ * @example
1177
+ * ```ts
1178
+ * export default defineConfig({
1179
+ * input: './petstore.yaml',
1180
+ * output: { path: './src/gen' },
1181
+ * plugins: [pluginTs(), pluginZod()],
1182
+ * })
1183
+ * ```
1184
+ */
1185
+ export type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter' | 'storage' | 'reporters'> & {
1186
+ /**
1187
+ * Project root directory, absolute or relative to the config file location.
1188
+ * @default process.cwd()
1189
+ */
1190
+ root?: string;
1191
+ /**
1192
+ * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).
1193
+ * @default [parserTs(), parserTsx(), parserMd()] // applied by `defineConfig` from the `kubb` package
1194
+ */
1195
+ parsers?: Array<Parser>;
1196
+ /**
1197
+ * Adapter that parses your API specification into Kubb's universal AST.
1198
+ * When omitted, Kubb runs in plugin-only mode.
1199
+ */
1200
+ adapter?: Adapter;
1201
+ /**
1202
+ * Plugins that execute during the build to generate code and transform the AST.
1203
+ * @default []
1204
+ */
1205
+ plugins?: Array<Plugin>;
1206
+ /**
1207
+ * Storage backend that controls where and how generated files are persisted.
1208
+ * @default fsStorage()
1209
+ */
1210
+ storage?: Storage;
1211
+ /**
1212
+ * Reporters available to the run. `defineConfig` registers the built-in `cli`, `json`, `file`,
1213
+ * and `html` reporters when omitted.
1214
+ * @default [cliReporter, jsonReporter, fileReporter, htmlReporter] // applied by `defineConfig` from the `kubb` package
1215
+ */
1216
+ reporters?: Array<Reporter>;
1217
+ };
1218
+ declare global {
1219
+ namespace Kubb {
1220
+ /**
1221
+ * Registry that maps plugin names to their `PluginType`.
1222
+ * Augment this interface in each plugin's `types.ts` to enable automatic
1223
+ * typing for `getPlugin` and `requirePlugin`.
1224
+ *
1225
+ * @example
1226
+ * ```ts
1227
+ * // packages/plugin-ts/src/types.ts
1228
+ * declare global {
1229
+ * namespace Kubb {
1230
+ * interface PluginRegistry {
1231
+ * 'plugin-ts': PluginTs
1232
+ * }
1233
+ * }
1234
+ * }
1235
+ * ```
1236
+ */
1237
+ interface PluginRegistry {}
1238
+ /**
1239
+ * Extension point for root `Config['output']` options.
1240
+ * Augment the `output` key in plugin packages to add extra fields
1241
+ * to the global output configuration without touching core types.
1242
+ *
1243
+ * @example
1244
+ * ```ts
1245
+ * // packages/plugin-barrel/src/plugin.ts
1246
+ * declare global {
1247
+ * namespace Kubb {
1248
+ * interface ConfigOptionsRegistry {
1249
+ * output: {
1250
+ * barrel?: import('./types.ts').BarrelConfig | false
1251
+ * }
1252
+ * }
1253
+ * }
1254
+ * }
1255
+ * ```
1256
+ */
1257
+ interface ConfigOptionsRegistry {}
1258
+ /**
1259
+ * Extension point for per-plugin `Output` options.
1260
+ * Augment the `output` key in plugin packages to add extra fields
1261
+ * to the per-plugin output configuration without touching core types.
1262
+ *
1263
+ * @example
1264
+ * ```ts
1265
+ * // packages/plugin-barrel/src/plugin.ts
1266
+ * declare global {
1267
+ * namespace Kubb {
1268
+ * interface PluginOptionsRegistry {
1269
+ * output: {
1270
+ * barrel?: import('./types.ts').PluginBarrelConfig | false
1271
+ * }
1272
+ * }
1273
+ * }
1274
+ * }
1275
+ * ```
1276
+ */
1277
+ interface PluginOptionsRegistry {}
1278
+ /**
1279
+ * Registry of hook names to their listener argument tuples.
1280
+ * Augment this interface to add hook events without touching core types.
1281
+ *
1282
+ * @example
1283
+ * ```ts
1284
+ * // packages/my-plugin/src/hooks.ts
1285
+ * declare global {
1286
+ * namespace Kubb {
1287
+ * interface KubbHooksRegistry {
1288
+ * 'my-plugin:ready': [ctx: { count: number }]
1289
+ * }
1290
+ * }
1291
+ * }
1292
+ * ```
1293
+ */
1294
+ interface KubbHooksRegistry {
1295
+ 'kubb:lifecycle:start': [ctx: KubbLifecycleStartContext];
1296
+ 'kubb:lifecycle:end': [];
1297
+ 'kubb:generation:start': [ctx: KubbGenerationStartContext];
1298
+ 'kubb:generation:end': [ctx: KubbGenerationEndContext];
1299
+ 'kubb:generation:summary': [ctx: KubbGenerationSummaryContext];
1300
+ 'kubb:setup:start': [];
1301
+ 'kubb:setup:end': [];
1302
+ 'kubb:format:start': [];
1303
+ 'kubb:format:end': [];
1304
+ 'kubb:lint:start': [];
1305
+ 'kubb:lint:end': [];
1306
+ 'kubb:hooks:start': [];
1307
+ 'kubb:hooks:end': [];
1308
+ 'kubb:hook:start': [ctx: KubbHookStartContext];
1309
+ 'kubb:hook:line': [ctx: KubbHookLineContext];
1310
+ 'kubb:hook:end': [ctx: KubbHookEndContext];
1311
+ 'kubb:info': [ctx: KubbInfoContext];
1312
+ 'kubb:error': [ctx: KubbErrorContext];
1313
+ 'kubb:success': [ctx: KubbSuccessContext];
1314
+ 'kubb:warn': [ctx: KubbWarnContext];
1315
+ 'kubb:diagnostic': [ctx: KubbDiagnosticContext];
1316
+ 'kubb:files:processing:start': [ctx: KubbFilesProcessingStartContext];
1317
+ 'kubb:files:processing:update': [ctx: KubbFilesProcessingUpdateContext];
1318
+ 'kubb:files:processing:end': [ctx: KubbFilesProcessingEndContext];
1319
+ 'kubb:plugin:start': [ctx: KubbPluginStartContext];
1320
+ 'kubb:plugin:end': [ctx: KubbPluginEndContext];
1321
+ 'kubb:plugin:setup': [ctx: KubbPluginSetupContext];
1322
+ 'kubb:build:start': [ctx: KubbBuildStartContext];
1323
+ 'kubb:plugins:end': [ctx: KubbPluginsEndContext];
1324
+ 'kubb:build:end': [ctx: KubbBuildEndContext];
1325
+ 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext];
1326
+ 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext];
1327
+ 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext];
1328
+ }
1329
+ }
1330
+ }
1331
+ /**
1332
+ * Lifecycle hooks emitted during Kubb code generation.
1333
+ * Attach listeners before calling `setup()` or `build()` to observe and react to build progress.
1334
+ *
1335
+ * A package can add its own hook names to this type by augmenting
1336
+ * {@link Kubb.KubbHooksRegistry} instead of exporting a second, separate hook type. Studio's
1337
+ * connection and RPC hooks intentionally use its separate `StudioHooks` registry.
1338
+ *
1339
+ * @example
1340
+ * ```ts
1341
+ * kubb.hooks.hook('kubb:lifecycle:start', () => {
1342
+ * console.log('Starting Kubb generation')
1343
+ * })
1344
+ *
1345
+ * kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => {
1346
+ * console.log(`${plugin.name} completed in ${duration}ms`)
1347
+ * })
1348
+ * ```
1349
+ */
1350
+ export type KubbHooks = Kubb.KubbHooksRegistry;
1351
+ /** The file access every file-carrying hook context shares: a lazy snapshot of the files so far, and a way to add more. */
1352
+ export type FilesContext = {
1353
+ /** Snapshot of all files accumulated so far, including those added by plugins that already ran. */
1354
+ readonly files: ReadonlyArray<FileNode>;
1355
+ /** Adds or merges one or more files into the file manager. */
1356
+ upsertFile: (...files: Array<FileNode>) => void;
1357
+ };
1358
+ export type KubbBuildStartContext = FilesContext & {
1359
+ /**
1360
+ * Resolved configuration for this build.
1361
+ */
1362
+ config: Config;
1363
+ /**
1364
+ * Adapter that parsed the input into the universal AST.
1365
+ */
1366
+ adapter: Adapter;
1367
+ /**
1368
+ * Metadata about the parsed document (title, version, base URL, circular schema names, enum names).
1369
+ * To observe individual schemas and operations use the `kubb:generate:schema` / `kubb:generate:operation` hooks.
1370
+ */
1371
+ meta: InputMeta | undefined;
1372
+ /**
1373
+ * Looks up a registered plugin by name, typed by the plugin registry.
1374
+ */
1375
+ getPlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
1376
+ };
1377
+ export type KubbPluginsEndContext = FilesContext & {
1378
+ /**
1379
+ * Resolved configuration for this build.
1380
+ */
1381
+ config: Config;
1382
+ };
1383
+ export type KubbBuildEndContext = {
1384
+ /**
1385
+ * All files generated during this build.
1386
+ */
1387
+ files: Array<FileNode>;
1388
+ /**
1389
+ * Resolved configuration for this build.
1390
+ */
1391
+ config: Config;
1392
+ /**
1393
+ * Absolute path to the output directory.
1394
+ */
1395
+ outputDir: string;
1396
+ };
1397
+ export type KubbLifecycleStartContext = {
1398
+ /**
1399
+ * Current Kubb version string.
1400
+ */
1401
+ version: string;
1402
+ };
1403
+ export type KubbGenerationStartContext = {
1404
+ /**
1405
+ * Resolved configuration for this generation run.
1406
+ */
1407
+ config: Config;
1408
+ };
1409
+ export type KubbGenerationEndContext = {
1410
+ /**
1411
+ * Resolved configuration for this generation run.
1412
+ */
1413
+ config: Config;
1414
+ /**
1415
+ * Read-only view of the files written during this build.
1416
+ * Reads go directly to `config.storage`, nothing extra is held in memory.
1417
+ *
1418
+ * @example Read a generated file
1419
+ * `const code = await storage.readItem('/src/gen/pet.ts')`
1420
+ *
1421
+ * @example Walk every generated file
1422
+ * ```ts
1423
+ * for (const path of await storage.readKeys()) {
1424
+ * const code = await storage.readItem(path)
1425
+ * }
1426
+ * ```
1427
+ */
1428
+ storage: Storage;
1429
+ /**
1430
+ * Diagnostics collected during the build: error/warning/info problems plus a
1431
+ * `performance` diagnostic per plugin. The end-of-run summary derives its failure counts
1432
+ * and per-plugin timings from these. Set by the CLI runner, omitted by other callers.
1433
+ */
1434
+ diagnostics?: Array<Diagnostic>;
1435
+ /**
1436
+ * `'success'` when all plugins completed without errors, `'failed'` otherwise.
1437
+ */
1438
+ status?: 'success' | 'failed';
1439
+ /**
1440
+ * High-resolution start time from `process.hrtime()`, used to compute the elapsed time.
1441
+ */
1442
+ hrStart?: [number, number];
1443
+ /**
1444
+ * Total number of files created during this run.
1445
+ */
1446
+ filesCreated?: number;
1447
+ };
1448
+ /** A human-readable message with optional detail, as carried by `kubb:info`, `kubb:success`, and `kubb:warn`. */
1449
+ export type KubbMessageContext = {
1450
+ /**
1451
+ * Human-readable message.
1452
+ */
1453
+ message: string;
1454
+ /**
1455
+ * Optional supplementary detail.
1456
+ */
1457
+ info?: string;
1458
+ };
1459
+ export type KubbInfoContext = KubbMessageContext;
1460
+ export type KubbSuccessContext = KubbMessageContext;
1461
+ export type KubbWarnContext = KubbMessageContext;
1462
+ export type KubbErrorContext = {
1463
+ /**
1464
+ * The caught error.
1465
+ */
1466
+ error: Error;
1467
+ /**
1468
+ * Optional structured metadata for additional context.
1469
+ */
1470
+ meta?: Record<string, unknown>;
1471
+ };
1472
+ export type KubbDiagnosticContext = {
1473
+ /**
1474
+ * The structured diagnostic to render: a build problem or a version-update notice.
1475
+ */
1476
+ diagnostic: ProblemDiagnostic | UpdateDiagnostic;
1477
+ };
1478
+ export type KubbGenerationSummaryContext = {
1479
+ duration: number;
1480
+ fileCount: number;
1481
+ failedPlugins: number;
1482
+ status: 'success' | 'failed';
1483
+ };
1484
+ export type KubbFilesProcessingStartContext = {
1485
+ /**
1486
+ * Files about to be serialized and written.
1487
+ */
1488
+ files: Array<FileNode>;
1489
+ };
1490
+ export type KubbFileProcessingUpdate = {
1491
+ /**
1492
+ * Number of files processed so far in this batch.
1493
+ */
1494
+ processed: number;
1495
+ /**
1496
+ * Total number of files in this batch.
1497
+ */
1498
+ total: number;
1499
+ /**
1500
+ * Completion percentage, `0` to `100`.
1501
+ */
1502
+ percentage: number;
1503
+ /**
1504
+ * The file that was just processed.
1505
+ */
1506
+ file: FileNode;
1507
+ /**
1508
+ * Resolved configuration for this build.
1509
+ */
1510
+ config: Config;
1511
+ };
1512
+ export type KubbFilesProcessingUpdateContext = {
1513
+ /**
1514
+ * All files processed in this flush chunk.
1515
+ */
1516
+ files: Array<KubbFileProcessingUpdate>;
1517
+ };
1518
+ export type KubbFilesProcessingEndContext = {
1519
+ /**
1520
+ * All files that were serialized in this batch.
1521
+ */
1522
+ files: Array<FileNode>;
1523
+ };
1524
+ export type KubbHookStartContext = {
1525
+ /**
1526
+ * Optional identifier for correlating start/end hooks.
1527
+ */
1528
+ id?: string;
1529
+ /**
1530
+ * The shell command that is about to run.
1531
+ */
1532
+ command: string;
1533
+ /**
1534
+ * Optional label for the command, shown in the CLI output when set.
1535
+ */
1536
+ name?: string;
1537
+ /**
1538
+ * Parsed argument list, when available.
1539
+ */
1540
+ args?: ReadonlyArray<string>;
1541
+ };
1542
+ /**
1543
+ * Emitted for each line streamed from a hook's stdout while it runs.
1544
+ * A logger correlates the line to its active UI element via `id`.
1545
+ */
1546
+ export type KubbHookLineContext = {
1547
+ /**
1548
+ * Identifier matching the corresponding `kubb:hook:start` hook.
1549
+ */
1550
+ id: string;
1551
+ /**
1552
+ * A single streamed stdout line, without its trailing newline.
1553
+ */
1554
+ line: string;
1555
+ };
1556
+ /** Emitted when a hook subprocess ends: its `kubb:hook:start` context plus the outcome. */
1557
+ export type KubbHookEndContext = KubbHookStartContext & HookResult;
1558
+ /**
1559
+ * CLI options derived from command-line flags.
1560
+ */
1561
+ export type CLIOptions = {
1562
+ /**
1563
+ * Path to the Kubb config file.
1564
+ */
1565
+ config?: string;
1566
+ /**
1567
+ * OpenAPI input path or URL passed as the positional argument to `kubb generate`.
1568
+ * Overrides `config.input` when set.
1569
+ */
1570
+ input?: string;
1571
+ /**
1572
+ * Re-run generation whenever input files change.
1573
+ */
1574
+ watch?: boolean;
1575
+ /**
1576
+ * Controls how much output the CLI prints.
1577
+ *
1578
+ * @default 'info'
1579
+ */
1580
+ logLevel?: 'silent' | 'info' | 'verbose';
1581
+ /**
1582
+ * Reporters selected on the CLI via `--reporter`, overriding `config.reporters`.
1583
+ */
1584
+ reporters?: Array<ReporterName>;
1585
+ };
1586
+ /**
1587
+ * All accepted forms of a Kubb configuration.
1588
+ * Accepts `Config`/`Config[]`/promise or a factory (optionally receiving `TCliOptions`).
1589
+ */
1590
+ export type PossibleConfig<TCliOptions = undefined> = PossiblePromise<Config | Array<Config>> | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Array<Config>>);
1591
+ /**
1592
+ * Full output produced by a successful or failed build.
1593
+ */
1594
+ export type BuildOutput = {
1595
+ /**
1596
+ * Structured diagnostics collected during the build: error/warning/info problems
1597
+ * (each with a code, severity, and where known a JSON-pointer location) plus a
1598
+ * `performance` diagnostic per plugin. Includes a top-level diagnostic when the build
1599
+ * threw before completing. Use {@link Diagnostics.hasError} to test for failure.
1600
+ */
1601
+ diagnostics: Array<Diagnostic>;
1602
+ /**
1603
+ * All files generated during this build.
1604
+ */
1605
+ files: Array<FileNode>;
1606
+ /**
1607
+ * The plugin driver that orchestrated this build.
1608
+ */
1609
+ driver: KubbDriver;
1610
+ /**
1611
+ * The configured `Storage` backend, for reading back a generated file's final content.
1612
+ * Use `files` to list what this build produced.
1613
+ *
1614
+ * @example Read a generated file
1615
+ * `const code = await buildOutput.storage.readItem('/src/gen/pet.ts')`
1616
+ */
1617
+ storage: Storage;
1618
+ };
1619
+ //#endregion
1620
+ //#region src/Diagnostics.d.ts
1621
+ /**
1622
+ * How serious a diagnostic is. `error` fails the build, `warning` and `info`
1623
+ * are reported but do not.
1624
+ */
1625
+ type DiagnosticSeverity = 'error' | 'warning' | 'info';
1626
+ /**
1627
+ * A human-readable explanation of a diagnostic code: a short title, what triggers it, and how
1628
+ * to resolve it. This is the source of truth the kubb.dev `/reference/diagnostics#<slug>` sections mirror, so
1629
+ * every code stays documented in one place. Adding a code without documenting it fails the build.
1630
+ */
1631
+ type DiagnosticDoc = {
1632
+ /**
1633
+ * Short title shown as the docs heading.
1634
+ */
1635
+ title: string;
1636
+ /**
1637
+ * What triggers the diagnostic.
1638
+ */
1639
+ cause: string;
1640
+ /**
1641
+ * The action that resolves it.
1642
+ */
1643
+ fix: string;
1644
+ };
1645
+ /**
1646
+ * Points a diagnostic back into the source document. Inputs are parsed into an
1647
+ * object model with no line/column, so locations carry a JSON pointer the adapter
1648
+ * builds (the OAS adapter emits `#/components/schemas/Pet`). A `config` diagnostic
1649
+ * points at the Kubb config itself and so has no pointer.
1650
+ */
1651
+ type DiagnosticLocation = {
1652
+ kind: 'schema';
1653
+ /**
1654
+ * RFC 6901 JSON pointer into the source document.
1655
+ */
1656
+ pointer: string;
1657
+ /**
1658
+ * The original reference when the diagnostic stems from an unresolved one.
1659
+ */
1660
+ ref?: string;
1661
+ } | {
1662
+ kind: 'operation' | 'document';
1663
+ /**
1664
+ * RFC 6901 JSON pointer into the source document.
1665
+ */
1666
+ pointer: string;
1667
+ } | {
1668
+ kind: 'config';
1669
+ };
1670
+ /**
1671
+ * What a diagnostic carries.
1672
+ * - `problem` is a build issue shown to the user, and the only kind rendered as a problem.
1673
+ * - `performance` records a plugin's elapsed time.
1674
+ * - `update` is a version notice.
1675
+ */
1676
+ type DiagnosticKind = 'problem' | 'performance' | 'update';
1677
+ /**
1678
+ * Codes that describe a build problem: every {@link DiagnosticCode} except the
1679
+ * `performance` and `updateAvailable` codes, which ride on their own variants.
1680
+ */
1681
+ type ProblemCode = Exclude<DiagnosticCode, typeof diagnosticCode.performance | typeof diagnosticCode.updateAvailable>;
1682
+ /**
1683
+ * A build problem collected during a run, gathered into the result instead of
1684
+ * aborting on the first failure.
1685
+ */
1686
+ type ProblemDiagnostic = {
1687
+ /**
1688
+ * @default 'problem'
1689
+ */
1690
+ kind?: 'problem';
1691
+ /**
1692
+ * Stable identifier for the problem, from the {@link diagnosticCode} catalog.
1693
+ */
1694
+ code: ProblemCode;
1695
+ severity: DiagnosticSeverity;
1696
+ message: string;
1697
+ location?: DiagnosticLocation;
1698
+ /**
1699
+ * A suggested fix, phrased as an action the user can take.
1700
+ */
1701
+ help?: string;
1702
+ /**
1703
+ * Name of the plugin or subsystem that produced the diagnostic.
1704
+ */
1705
+ plugin?: string;
1706
+ /** Issue tracker URL of the extension that crashed, from its `meta.issues`. */
1707
+ issues?: string;
1708
+ /**
1709
+ * The underlying error, when the diagnostic wraps a thrown one.
1710
+ */
1711
+ cause?: Error;
1712
+ };
1713
+ /**
1714
+ * A per-plugin performance record, built with {@link Diagnostics.performance}. The `performance`
1715
+ * kind keeps it out of the problem list. It feeds the per-plugin timing bars, and reporters sum
1716
+ * these into the run total.
1717
+ */
1718
+ type PerformanceDiagnostic = {
1719
+ kind: 'performance';
1720
+ code: typeof diagnosticCode.performance;
1721
+ severity: 'info';
1722
+ message: string;
1723
+ /**
1724
+ * The plugin this measurement belongs to.
1725
+ */
1726
+ plugin: string;
1727
+ /**
1728
+ * Elapsed milliseconds.
1729
+ */
1730
+ duration: number;
1731
+ };
1732
+ /**
1733
+ * A notice that a newer Kubb version is available on npm, built with {@link Diagnostics.update}.
1734
+ * It renders like any info diagnostic.
1735
+ */
1736
+ type UpdateDiagnostic = {
1737
+ kind: 'update';
1738
+ code: typeof diagnosticCode.updateAvailable;
1739
+ severity: 'info';
1740
+ message: string;
1741
+ /**
1742
+ * The running Kubb version.
1743
+ */
1744
+ currentVersion: string;
1745
+ /**
1746
+ * The newest version published on npm.
1747
+ */
1748
+ latestVersion: string;
1749
+ };
1750
+ /**
1751
+ * A structured record collected during a build, discriminated on `kind`: a
1752
+ * {@link ProblemDiagnostic} for an issue, a {@link PerformanceDiagnostic} for a per-plugin
1753
+ * timing, or an {@link UpdateDiagnostic} for a version notice.
1754
+ */
1755
+ type Diagnostic = ProblemDiagnostic | PerformanceDiagnostic | UpdateDiagnostic;
1756
+ /**
1757
+ * Static helpers for working with {@link Diagnostic}s, plus the run-scoped sink
1758
+ * that lets deep code report a diagnostic without threading a callback.
1759
+ *
1760
+ * The sink lives in a single `AsyncLocalStorage` in the `@kubb/core` bundle.
1761
+ * `Diagnostics.scope` activates it for a run, so anything inside that run (the
1762
+ * adapter parse, a generator) reports through `Diagnostics.report` and lands
1763
+ * in the same run.
1764
+ */
1765
+ export declare class Diagnostics {
1766
+ #private;
1767
+ /**
1768
+ * The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).
1769
+ */
1770
+ static code: {
1771
+ readonly unknown: "KUBB_UNKNOWN";
1772
+ readonly inputNotFound: "KUBB_INPUT_NOT_FOUND";
1773
+ readonly inputRequestFailed: "KUBB_INPUT_REQUEST_FAILED";
1774
+ readonly inputUnreachable: "KUBB_INPUT_UNREACHABLE";
1775
+ readonly inputRequired: "KUBB_INPUT_REQUIRED";
1776
+ readonly legacyInput: "KUBB_LEGACY_INPUT";
1777
+ readonly invalidDocument: "KUBB_INVALID_DOCUMENT";
1778
+ readonly invalidSpec: "KUBB_INVALID_SPEC";
1779
+ readonly refNotFound: "KUBB_REF_NOT_FOUND";
1780
+ readonly invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE";
1781
+ readonly pluginNotFound: "KUBB_PLUGIN_NOT_FOUND";
1782
+ readonly incompatibleExtension: "KUBB_INCOMPATIBLE_EXTENSION";
1783
+ readonly missingDependency: "KUBB_MISSING_DEPENDENCY";
1784
+ readonly incompatibleDependency: "KUBB_INCOMPATIBLE_DEPENDENCY";
1785
+ readonly pluginFailed: "KUBB_PLUGIN_FAILED";
1786
+ readonly adapterFailed: "KUBB_ADAPTER_FAILED";
1787
+ readonly parserFailed: "KUBB_PARSER_FAILED";
1788
+ readonly pluginWarning: "KUBB_PLUGIN_WARNING";
1789
+ readonly pluginInfo: "KUBB_PLUGIN_INFO";
1790
+ readonly noContext: "KUBB_NO_CONTEXT";
1791
+ readonly unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT";
1792
+ readonly deprecated: "KUBB_DEPRECATED";
1793
+ readonly adapterRequired: "KUBB_ADAPTER_REQUIRED";
1794
+ readonly pathTraversal: "KUBB_PATH_TRAVERSAL";
1795
+ readonly cleanRoot: "KUBB_CLEAN_ROOT";
1796
+ readonly invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS";
1797
+ readonly postGenerateFailed: "KUBB_POST_GENERATE_FAILED";
1798
+ readonly formatFailed: "KUBB_FORMAT_FAILED";
1799
+ readonly lintFailed: "KUBB_LINT_FAILED";
1800
+ readonly barrelDuplicateExport: "KUBB_BARREL_DUPLICATE_EXPORT";
1801
+ readonly internalError: "KUBB_INTERNAL_ERROR";
1802
+ readonly performance: "KUBB_PERFORMANCE";
1803
+ readonly updateAvailable: "KUBB_UPDATE_AVAILABLE";
1804
+ };
1805
+ /**
1806
+ * Type guard for a build {@link ProblemDiagnostic}.
1807
+ */
1808
+ static isProblem: (diagnostic: Diagnostic) => diagnostic is ProblemDiagnostic;
1809
+ /**
1810
+ * Type guard for a version-update {@link UpdateDiagnostic}.
1811
+ */
1812
+ static isUpdate: (diagnostic: Diagnostic) => diagnostic is UpdateDiagnostic;
1813
+ /**
1814
+ * Type guard for a per-plugin {@link PerformanceDiagnostic}.
1815
+ */
1816
+ static isPerformance: (diagnostic: Diagnostic) => diagnostic is PerformanceDiagnostic;
1817
+ /**
1818
+ * An `Error` that carries a {@link Diagnostic}, so structured problems can flow
1819
+ * through the existing throw/catch paths while keeping their code and location.
1820
+ *
1821
+ * @example
1822
+ * ```ts
1823
+ * throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })
1824
+ * ```
1825
+ */
1826
+ static Error: {
1827
+ new (diagnostic: ProblemDiagnostic): {
1828
+ diagnostic: ProblemDiagnostic;
1829
+ name: string;
1830
+ message: string;
1831
+ stack?: string;
1832
+ cause?: unknown;
1833
+ };
1834
+ isError(error: unknown): error is Error;
1835
+ isError(value: unknown): value is Error;
1836
+ captureStackTrace(targetObject: object, constructorOpt?: Function): void;
1837
+ captureStackTrace(targetObject: object, constructorOpt?: Function): void;
1838
+ prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
1839
+ stackTraceLimit: number;
1840
+ };
1841
+ /**
1842
+ * Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated
1843
+ * `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`
1844
+ * that carries a `code`.
1845
+ */
1846
+ static isError(error: unknown): error is InstanceType<typeof Diagnostics.Error>;
1847
+ /**
1848
+ * Runs `fn` with `sink` as the active diagnostic sink for the whole async
1849
+ * subtree, so {@link Diagnostics.report} reaches it from anywhere inside.
1850
+ */
1851
+ static scope<T>(sink: (diagnostic: Diagnostic) => void, fn: () => T): T;
1852
+ /**
1853
+ * Collects a diagnostic into the active build via the run-scoped sink, without throwing.
1854
+ * Returns `true` when a run consumed it, `false` when called outside a {@link Diagnostics.scope}
1855
+ * (so callers can fall back to throwing). Use a `warning`/`info` severity for non-fatal issues.
1856
+ * For rendering a diagnostic live on the hook bus, use {@link Diagnostics.emit} instead.
1857
+ */
1858
+ static report(diagnostic: Diagnostic): boolean;
1859
+ /**
1860
+ * Emits a diagnostic, or any thrown value, on the run's hooks so the loggers render it live.
1861
+ * A coded problem or an update goes to `kubb:diagnostic`. An uncoded one goes to `kubb:error`
1862
+ * whole, so every wrapper's message, its help, and the stack survive. To collect a diagnostic into
1863
+ * the build result from deep in a run, use {@link Diagnostics.report} instead.
1864
+ */
1865
+ static emit(hooks: Hookable<KubbHooks>, value: ProblemDiagnostic | UpdateDiagnostic | unknown): Promise<void>;
1866
+ /**
1867
+ * Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}
1868
+ * keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.
1869
+ */
1870
+ static from(error: unknown): ProblemDiagnostic;
1871
+ /**
1872
+ * Coerces an error thrown by a plugin, adapter, or parser into a diagnostic attributed to it.
1873
+ * A structured {@link Diagnostics.Error} keeps its code. Any other error is a crash: it gets the
1874
+ * kind's `*_FAILED` code and the extension's `meta.issues` link, so the user reports it to the
1875
+ * extension's maintainers instead of to Kubb.
1876
+ */
1877
+ static fromExtension(error: unknown, { kind, extension }: {
1878
+ kind: ExtensionKind;
1879
+ extension: ExtensionNamed;
1880
+ }): ProblemDiagnostic;
1881
+ /**
1882
+ * Builds a per-plugin performance record. Reporters sum these into the run total.
1883
+ */
1884
+ static performance({ plugin, duration }: {
1885
+ plugin: string;
1886
+ duration: number;
1887
+ }): PerformanceDiagnostic;
1888
+ /**
1889
+ * Builds the version-update notice shown when a newer Kubb is published on npm.
1890
+ */
1891
+ static update({ currentVersion, latestVersion }: {
1892
+ currentVersion: string;
1893
+ latestVersion: string;
1894
+ }): UpdateDiagnostic;
1895
+ /**
1896
+ * True when any diagnostic is an error, the severity that fails a build. Non-error
1897
+ * diagnostics are ignored.
1898
+ */
1899
+ static hasError(diagnostics: ReadonlyArray<Diagnostic>): boolean;
1900
+ /**
1901
+ * Names of the plugins that failed, deduped, derived from the error diagnostics
1902
+ * that carry a `plugin`.
1903
+ */
1904
+ static failedPlugins(diagnostics: ReadonlyArray<Diagnostic>): Array<string>;
1905
+ /**
1906
+ * Counts `problem` diagnostics by severity for the run summary. `performance` and
1907
+ * `update` diagnostics are ignored.
1908
+ */
1909
+ static count(diagnostics: ReadonlyArray<Diagnostic>): {
1910
+ errors: number;
1911
+ warnings: number;
1912
+ infos: number;
1913
+ };
1914
+ /**
1915
+ * Drops duplicate `problem` diagnostics that share a code, location pointer, and
1916
+ * plugin, so the same issue reported across several passes is shown once. Non-problem
1917
+ * diagnostics are always kept.
1918
+ */
1919
+ static dedupe(diagnostics: ReadonlyArray<Diagnostic>): Array<Diagnostic>;
1920
+ /**
1921
+ * Builds the kubb.dev docs URL for a diagnostic code, e.g.
1922
+ * `KUBB_REF_NOT_FOUND` → `https://kubb.dev/docs/5.x/reference/diagnostics#kubb-ref-not-found`.
1923
+ */
1924
+ static docsUrl(code: string): string;
1925
+ /**
1926
+ * The catalog entry for a code: its title, cause, and fix. Mirrors the kubb.dev
1927
+ * `/reference/diagnostics#<slug>` section.
1928
+ */
1929
+ static explain(code: DiagnosticCode): DiagnosticDoc;
1930
+ /**
1931
+ * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
1932
+ * consumers, with the catalog `title`, `cause`, and fix, and the `cause` error as `causes` and
1933
+ * `stack`. Absent optional fields are omitted.
1934
+ */
1935
+ static serialize: typeof serialize;
1936
+ /**
1937
+ * Renders a diagnostic as lines for an `agent` (the default) or a `human`. See {@link format}.
1938
+ */
1939
+ static format: typeof format;
1940
+ }
1941
+ //#endregion
1942
+ //#region src/nodeCache.d.ts
1943
+ /**
1944
+ * Per-node memo shared by every plugin that generates from the same schema or operation node in
1945
+ * one generate pass. The driver creates one `NodeCache` per node during the walk and hands the
1946
+ * same instance to each plugin's generator context, so work derived purely from the node (its
1947
+ * resolved name, imports, parameters) is computed by the first plugin that needs it and reused by
1948
+ * the rest instead of being recomputed per plugin.
1949
+ *
1950
+ * Keys are namespaced by convention (`'plugin-ts:imports'`) so two plugins caching different
1951
+ * derivations of the same node never collide.
1952
+ *
1953
+ * @example Fill on first read, reuse afterwards
1954
+ * ```ts
1955
+ * const imports = ctx.cache.ensureItem('plugin-ts:imports', () => ctx.resolver.imports({ node, root, output }))
1956
+ * ```
1957
+ */
1958
+ type NodeCache = {
1959
+ /**
1960
+ * Returns the value stored under `key`, or `undefined` when nothing is stored yet.
1961
+ */
1962
+ readItem<TValue>(key: string): TValue | undefined;
1963
+ /**
1964
+ * Stores `value` under `key`, overwriting any previous value, and returns it.
1965
+ */
1966
+ writeItem<TValue>(key: string, value: TValue): TValue;
1967
+ /**
1968
+ * Returns the value stored under `key`, computing and storing it with `factory` on the first
1969
+ * call. Later calls with the same key return the stored value without running `factory` again.
1970
+ */
1971
+ ensureItem<TValue>(key: string, factory: () => TValue): TValue;
1972
+ };
1973
+ //#endregion
1974
+ //#region src/defineGenerator.d.ts
1975
+ /**
1976
+ * Context passed to a generator's `schema`, `operation`, and `operations` methods.
1977
+ *
1978
+ * The driver sets `adapter` on the context before it runs a generator, so methods can read it
1979
+ * without a null check. `ctx.options` carries the per-node options after exclude/include/override
1980
+ * filtering for `schema` and `operation`, or the plugin-level options for `operations`.
1981
+ */
1982
+ type GeneratorContext<TOptions extends PluginType = PluginType> = {
1983
+ /**
1984
+ * Stops cooperative generation work at the next safe checkpoint.
1985
+ */
1986
+ signal?: AbortSignal;
1987
+ /**
1988
+ * The resolved Kubb config for this build, including `root`, `input`, `output`, and the
1989
+ * full plugin list.
1990
+ */
1991
+ config: Config;
1992
+ /**
1993
+ * Absolute path to the current plugin's output directory.
1994
+ */
1995
+ root: string;
1996
+ /**
1997
+ * The driver running this build. Most generators never need it. Prefer the scoped helpers
1998
+ * on this context (`getPlugin`, `getResolver`, `upsertFile`) over reaching into the driver.
1999
+ */
2000
+ driver: KubbDriver;
2001
+ /**
2002
+ * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
2003
+ */
2004
+ getPlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined;
2005
+ /**
2006
+ * Get a plugin by name, throws an error if not found.
2007
+ */
2008
+ requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>;
2009
+ /**
2010
+ * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.
2011
+ */
2012
+ getResolver<TName extends PluginName>(name: TName): ResolvePluginOptions<TName>['resolver'];
2013
+ /**
2014
+ * Add files only if they don't exist.
2015
+ */
2016
+ addFile: (...file: Array<FileNode>) => Promise<void>;
2017
+ /**
2018
+ * Merge sources into the same output file.
2019
+ */
2020
+ upsertFile: (...file: Array<FileNode>) => Promise<void>;
2021
+ /**
2022
+ * The build's hook bus. Emit or listen to any `KubbHooks` hook, for example to react to
2023
+ * `kubb:build:end` from inside a generator.
2024
+ */
2025
+ hooks: Hookable<KubbHooks>;
2026
+ /**
2027
+ * The current plugin instance.
2028
+ */
2029
+ plugin: Plugin<TOptions> & {
2030
+ name: string;
2031
+ meta: ExtensionMeta;
2032
+ };
2033
+ /**
2034
+ * The current plugin's resolver. It decides what every generated symbol and file path is
2035
+ * called. Kubb picks a `setResolver` registration first, then the plugin's static
2036
+ * `resolver`, then the built-in default.
2037
+ *
2038
+ * @example Resolve a name
2039
+ * `ctx.resolver.name('pet') // 'pet'`
2040
+ *
2041
+ * @example Resolve an output file
2042
+ * `ctx.resolver.file({ name: 'pet', extname: '.ts', root, output })`
2043
+ */
2044
+ resolver: TOptions['resolver'];
2045
+ /**
2046
+ * Report a warning. Collected as a `warning` diagnostic attributed to the current
2047
+ * plugin. It surfaces in the run summary but does not fail the build. Pass `options` to set
2048
+ * the `code`, the `help` text, or the source `location`.
2049
+ *
2050
+ * @example
2051
+ * `ctx.warn('Enum has no values', { help: 'Add values to the enum.', location: { kind: 'schema', pointer: '#/components/schemas/Status' } })`
2052
+ */
2053
+ warn: (message: string, options?: Partial<Pick<ProblemDiagnostic, 'code' | 'help' | 'location'>>) => void;
2054
+ /**
2055
+ * Report an error. Collected as an `error` diagnostic attributed to the current
2056
+ * plugin, which fails the build. A `Diagnostics.Error` keeps its own code, help, and location.
2057
+ * Pass `options` to set them for a plain message or error.
2058
+ */
2059
+ error: (error: string | Error, options?: Partial<Pick<ProblemDiagnostic, 'code' | 'help' | 'location'>>) => void;
2060
+ /**
2061
+ * Report an informational message. Collected as an `info` diagnostic attributed to
2062
+ * the current plugin. Pass `options` to set the `code`, the `help` text, or the source `location`.
2063
+ */
2064
+ info: (message: string, options?: Partial<Pick<ProblemDiagnostic, 'code' | 'help' | 'location'>>) => void;
2065
+ /**
2066
+ * The configured adapter instance.
2067
+ */
2068
+ adapter: Adapter;
2069
+ /**
2070
+ * Document metadata from the adapter: title, version, base URL, and pre-computed
2071
+ * schema index fields (`circularNames`, `enumNames`).
2072
+ */
2073
+ meta: InputMeta;
2074
+ /**
2075
+ * Resolved options after exclude/include/override filtering.
2076
+ */
2077
+ options: TOptions['resolvedOptions'];
2078
+ /**
2079
+ * Cache scoped to the node being generated, shared by every plugin that generates from that
2080
+ * same node in the current pass. Use it to compute node-derived work (resolved names, imports,
2081
+ * parameters) once and let the other plugins reuse it. For the `operations` batch call, where
2082
+ * there is no single node, the cache is a fresh scratch scope for that call.
2083
+ */
2084
+ cache: NodeCache;
2085
+ };
2086
+ /**
2087
+ * Declares a named generator unit that walks the AST and emits files.
2088
+ *
2089
+ * `schema` runs for each schema node and `operation` for each operation node. `operations` runs
2090
+ * once after every operation node is walked. JSX-based generators require a `renderer` factory.
2091
+ * Return `Array<FileNode>` directly, or call `ctx.upsertFile()` manually and return `null` to
2092
+ * bypass rendering.
2093
+ *
2094
+ * @note Generators are consumed by plugins and registered via `ctx.addGenerator()` in `kubb:plugin:setup`.
2095
+ *
2096
+ * @example
2097
+ * ```ts
2098
+ * import { defineGenerator } from '@kubb/core'
2099
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
2100
+ *
2101
+ * export const typeGenerator = defineGenerator({
2102
+ * name: 'typescript',
2103
+ * renderer: jsxRenderer,
2104
+ * schema(node, ctx) {
2105
+ * const { adapter, resolver, root, options } = ctx
2106
+ * return <File ...><Type node={node} resolver={resolver} /></File>
2107
+ * },
2108
+ * })
2109
+ * ```
2110
+ */
2111
+ type Generator<TOptions extends PluginType = PluginType, TElement = unknown> = {
2112
+ /**
2113
+ * Used in diagnostic messages and debug output.
2114
+ */
2115
+ name: string;
2116
+ /**
2117
+ * Optional renderer factory that produces a {@link Renderer} for each render cycle.
2118
+ *
2119
+ * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this
2120
+ * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).
2121
+ *
2122
+ * Generators that only return `Array<FileNode>` or `void` do not need to set this.
2123
+ *
2124
+ * Leave it unset or set `renderer: null` to opt out of rendering.
2125
+ *
2126
+ * @example
2127
+ * ```ts
2128
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
2129
+ * export const myGenerator = defineGenerator<PluginTs>({
2130
+ * renderer: jsxRenderer,
2131
+ * schema(node, ctx) { return <File ...>...</File> },
2132
+ * })
2133
+ * ```
2134
+ */
2135
+ renderer?: RendererFactory<TElement> | null;
2136
+ /**
2137
+ * Predicate checked before `schema` or `operation` runs for a node, mirroring `Macro['match']`
2138
+ * in `@kubb/ast`. Returning `false` skips the call for that node entirely, with no context work
2139
+ * beyond what the driver already builds per node and no render call, instead of the generator
2140
+ * itself being invoked and returning early. Omit it to run for every node, the default when
2141
+ * unset.
2142
+ *
2143
+ * Does not gate `operations`, which already runs once per plugin on the full batch rather than
2144
+ * per node.
2145
+ *
2146
+ * @example Only match GET operations
2147
+ * ```ts
2148
+ * match(node, ctx) {
2149
+ * return ast.isHttpOperationNode(node) && node.method.toLowerCase() === 'get'
2150
+ * }
2151
+ * ```
2152
+ */
2153
+ match?: (node: SchemaNode | OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<boolean>;
2154
+ /**
2155
+ * Called for each schema node in the AST walk.
2156
+ * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
2157
+ * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
2158
+ */
2159
+ schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>;
2160
+ /**
2161
+ * Called for each operation node in the AST walk.
2162
+ * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
2163
+ * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
2164
+ */
2165
+ operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>;
2166
+ /**
2167
+ * Called once after all operations have been walked.
2168
+ * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
2169
+ * plus `ctx.options` with the plugin-level options for the batch call.
2170
+ */
2171
+ operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>;
2172
+ };
2173
+ /**
2174
+ * Defines a generator: a unit of work that runs during the plugin's AST walk
2175
+ * and produces files. Plugins register generators via `ctx.addGenerator()`
2176
+ * inside `kubb:plugin:setup`.
2177
+ *
2178
+ * The returned object is the input as-is, but with `this` types preserved so
2179
+ * `schema`/`operation`/`operations` methods are correctly typed against the
2180
+ * plugin's `PluginType`. Renderer elements and `FileNode[]` returns
2181
+ * are both handled by the runtime, so pick whichever style fits.
2182
+ *
2183
+ * @example JSX-based schema generator
2184
+ * ```tsx
2185
+ * import { defineGenerator } from '@kubb/core'
2186
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
2187
+ *
2188
+ * export const typeGenerator = defineGenerator({
2189
+ * name: 'typescript',
2190
+ * renderer: jsxRenderer,
2191
+ * schema(node, ctx) {
2192
+ * return (
2193
+ * <File path={`${ctx.root}/${node.name}.ts`}>
2194
+ * <Type node={node} resolver={ctx.resolver} />
2195
+ * </File>
2196
+ * )
2197
+ * },
2198
+ * })
2199
+ * ```
2200
+ */
2201
+ export declare function defineGenerator<TOptions extends PluginType = PluginType, TElement = unknown>(generator: Generator<TOptions, TElement>): Generator<TOptions, TElement>;
2202
+ //#endregion
2203
+ //#region src/Resolver.d.ts
2204
+ /**
2205
+ * Context for resolving filtered options for a given operation or schema node.
2206
+ *
2207
+ * @internal
2208
+ */
2209
+ type ResolveOptionsContext<TOptions> = {
2210
+ options: TOptions;
2211
+ exclude?: Array<Filter>;
2212
+ include?: Array<Filter>;
2213
+ override?: Array<Override<TOptions>>;
2214
+ };
2215
+ /**
2216
+ * The built-in resolution machinery exposed on every resolver as `resolver.default`.
2217
+ * Plugins delegate to it via `this.default.*` and set their own conventions through
2218
+ * the top-level `name` and `file` entries.
2219
+ */
2220
+ type ResolverDefault = {
2221
+ /**
2222
+ * Built-in camelCase casing for a generated identifier.
2223
+ */
2224
+ name(name: string): string;
2225
+ options<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null;
2226
+ path(options: ResolvePathOptions): string;
2227
+ file(options: ResolveFileOptions): FileNode;
2228
+ banner(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
2229
+ footer(meta: InputMeta | undefined, context: ResolveBannerContext): string | null;
2230
+ };
2231
+ /**
2232
+ * The name request for `resolver.default.path`: a `baseName` plus the optional `tag`/`path` that
2233
+ * grouping keys off.
2234
+ */
2235
+ type ResolverPathParams = Omit<ResolverFileParams, 'name' | 'extname'> & {
2236
+ baseName: FileNode['baseName'];
2237
+ };
2238
+ /**
2239
+ * Options for `resolver.default.path`: the name request (`baseName`, `tag`, `path`) plus where the
2240
+ * output goes (`root`, `output`, `group`).
2241
+ *
2242
+ * @example
2243
+ * ```ts
2244
+ * resolver.default.path({ baseName: 'petTypes.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })
2245
+ * // → '/src/types/pets/petTypes.ts'
2246
+ * ```
2247
+ */
2248
+ type ResolvePathOptions = ResolverPathParams & {
2249
+ /**
2250
+ * Absolute project root that the output path is resolved against.
2251
+ */
2252
+ root: string;
2253
+ /**
2254
+ * Active output config; `output.path` is the base directory.
2255
+ */
2256
+ output: Output;
2257
+ /**
2258
+ * Optional grouping strategy applied to `tag` (tag grouping) or `path` (path grouping).
2259
+ */
2260
+ group?: Group;
2261
+ };
2262
+ /**
2263
+ * The file request for `resolver.file` and `resolver.default.file`: the `name` and `extname` plus
2264
+ * the optional `tag`/`path` that grouping keys off.
2265
+ */
2266
+ type ResolverFileParams = {
2267
+ name: string;
2268
+ extname: FileNode['extname'];
2269
+ /**
2270
+ * Tag value used when `group.type === 'tag'`.
2271
+ */
2272
+ tag?: string;
2273
+ /**
2274
+ * Path value used when `group.type === 'path'`.
2275
+ */
2276
+ path?: string;
2277
+ };
2278
+ /**
2279
+ * Options for `resolver.file` and `resolver.default.file`: the file request (`name`, `extname`,
2280
+ * `tag`, `path`) plus where the output goes (`root`, `output`, `group`).
2281
+ *
2282
+ * @example
2283
+ * ```ts
2284
+ * resolver.default.file({ name: 'listPets', extname: '.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })
2285
+ * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }
2286
+ * ```
2287
+ */
2288
+ type ResolveFileOptions = ResolverFileParams & {
2289
+ root: string;
2290
+ output: Output;
2291
+ group?: Group;
2292
+ };
2293
+ /**
2294
+ * Options for `resolver.imports`: the schema tree to scan (`node`) and where the generated
2295
+ * files live (`root`, `output`, `group`). Pass `name` to override how a referenced schema
2296
+ * name becomes the imported identifier; it defaults to the resolver's top-level `name`.
2297
+ *
2298
+ * @example
2299
+ * ```ts
2300
+ * resolver.imports({ node, root, output, group })
2301
+ * // → [{ kind: 'Import', name: ['pet'], path: '/src/types/pet.ts' }]
2302
+ * ```
2303
+ */
2304
+ type ResolveImportsOptions = {
2305
+ /**
2306
+ * Schema tree scanned for `$ref` occurrences. Each ref contributes one import entry.
2307
+ */
2308
+ node: SchemaNode;
2309
+ root: string;
2310
+ output: Output;
2311
+ group?: Group;
2312
+ /**
2313
+ * Extension of the generated files the imports point at.
2314
+ *
2315
+ * @default '.ts'
2316
+ */
2317
+ extname?: FileNode['extname'];
2318
+ /**
2319
+ * Overrides how a referenced schema name becomes the imported identifier, for example to
2320
+ * point enum refs at a suffixed type name. Defaults to the resolver's top-level `name`.
2321
+ */
2322
+ name?: (schemaName: string) => string;
2323
+ };
2324
+ /**
2325
+ * The `file` field of a resolver: decides what a generated file is called and, optionally, where
2326
+ * it lives. This is how a resolver renames or relocates its files, replacing the older per-call
2327
+ * `resolveName` hook.
2328
+ *
2329
+ * @example Suffix every generated file
2330
+ * ```ts
2331
+ * file: {
2332
+ * baseName({ name, extname }) {
2333
+ * return `${name}Faker${extname}`
2334
+ * },
2335
+ * }
2336
+ * ```
2337
+ *
2338
+ * @example Own the full path
2339
+ * ```ts
2340
+ * file: {
2341
+ * path({ baseName, output }) {
2342
+ * return `${output.path}/mocks/${baseName}`
2343
+ * },
2344
+ * }
2345
+ * ```
2346
+ */
2347
+ type ResolverFile = {
2348
+ /**
2349
+ * Builds the file's complete base name, extension included, from the identifier and the target
2350
+ * `extname`. Defaults to `toFilePath(name)` with `extname` appended. Reaches sibling resolver
2351
+ * helpers through `this`.
2352
+ */
2353
+ baseName?(params: Pick<ResolverFileParams, 'name' | 'extname'>): FileNode['baseName'];
2354
+ /**
2355
+ * Returns the file's complete path, resolved against the project `root`. Bypasses `output.path`
2356
+ * and `group`, so the resolver owns the layout. The returned path may not escape `root`. Reaches
2357
+ * sibling resolver helpers through `this`.
2358
+ */
2359
+ path?(params: ResolverFilePathParams): string;
2360
+ };
2361
+ /**
2362
+ * The argument to a resolver's `file.path`: the resolved `baseName` (what `file.baseName` produced,
2363
+ * with the extension already appended) and the active `output`. `tag`, `path`, and `group` are
2364
+ * omitted because `file.path` owns the whole path and bypasses grouping, and `root` because the
2365
+ * returned path is resolved against it.
2366
+ */
2367
+ type ResolverFilePathParams = {
2368
+ baseName: FileNode['baseName'];
2369
+ output: Output;
2370
+ };
2371
+ /**
2372
+ * Per-file context describing the file a banner/footer is being resolved for, so a
2373
+ * `banner`/`footer` function can branch on the file kind (e.g. skip a `'use server'`
2374
+ * directive on re-export files).
2375
+ */
2376
+ type ResolveBannerFile = {
2377
+ /**
2378
+ * Full output path of the file being generated.
2379
+ */
2380
+ path: string;
2381
+ /**
2382
+ * File name only, e.g. `'stocks.ts'`.
2383
+ */
2384
+ baseName: string;
2385
+ /**
2386
+ * `true` for `index.ts` re-export barrels.
2387
+ */
2388
+ isBarrel?: boolean;
2389
+ /**
2390
+ * `true` for group `[dir]/[dir].ts` aggregation files.
2391
+ */
2392
+ isAggregation?: boolean;
2393
+ };
2394
+ /**
2395
+ * Document metadata extended with per-file context, passed to a `banner`/`footer` function.
2396
+ *
2397
+ * @example Skip a directive on re-export files
2398
+ * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
2399
+ */
2400
+ type BannerMeta = InputMeta & {
2401
+ /**
2402
+ * Full output path of the file being generated.
2403
+ */
2404
+ filePath: string;
2405
+ /**
2406
+ * File name only, e.g. `'stocks.ts'`.
2407
+ */
2408
+ baseName: string;
2409
+ /**
2410
+ * `true` for `index.ts` re-export barrels.
2411
+ */
2412
+ isBarrel: boolean;
2413
+ /**
2414
+ * `true` for group `[dir]/[dir].ts` aggregation files.
2415
+ */
2416
+ isAggregation: boolean;
2417
+ };
2418
+ /**
2419
+ * Context passed to `resolver.default.banner` and `resolver.default.footer`.
2420
+ * `output` is optional since not every plugin configures a banner/footer, and `config`
2421
+ * carries the global Kubb config used to derive the default Kubb banner.
2422
+ */
2423
+ type ResolveBannerContext = {
2424
+ output?: Pick<Output, 'banner' | 'footer'>;
2425
+ config: Config;
2426
+ file?: ResolveBannerFile;
2427
+ };
2428
+ /**
2429
+ * Raw resolver fields passed to `createResolver` or patched through `Resolver.merge`.
2430
+ * `default` is the built-in machinery and is not user-settable.
2431
+ */
2432
+ type ResolverBuildOptions = {
2433
+ pluginName: string;
2434
+ name?: (name: string) => string;
2435
+ file?: ResolverFile;
2436
+ };
2437
+ /**
2438
+ * Partial resolver fields accepted by `Resolver.merge` and `setResolver`. Parameterize with a
2439
+ * concrete resolver type (e.g. `ResolverPatch<ResolverTs>`) to type-check overrides and bind
2440
+ * `this` to the full resolver. Namespaces are partial, so a patch may override a single method
2441
+ * (`query.name`) and the rest keep the plugin defaults. Overriding a whole resolver is not the
2442
+ * job of this patch, that is what a custom plugin is for.
2443
+ */
2444
+ 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]>; } & {
2445
+ imports?: T['imports'];
2446
+ name?: T['name'];
2447
+ file?: ResolverFile;
2448
+ } & ThisType<T>;
2449
+ /**
2450
+ * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
2451
+ * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
2452
+ * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
2453
+ * reachable and a `file` override is never dropped.
2454
+ */
2455
+ declare const resolverOptions: unique symbol;
2456
+ /**
2457
+ * Base constraint for all plugin resolver objects.
2458
+ *
2459
+ * The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
2460
+ * and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
2461
+ * top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
2462
+ *
2463
+ * @example Top-level helper
2464
+ * ```ts
2465
+ * type MyResolver = Resolver & {
2466
+ * typeName(name: string): string
2467
+ * }
2468
+ * ```
2469
+ *
2470
+ * @example Grouped namespace
2471
+ * ```ts
2472
+ * type MyResolver = Resolver & {
2473
+ * query: {
2474
+ * name(node: OperationNode): string
2475
+ * keyName(node: OperationNode): string
2476
+ * }
2477
+ * }
2478
+ * ```
2479
+ */
2480
+ export declare class Resolver {
2481
+ #private;
2482
+ readonly pluginName: string;
2483
+ /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
2484
+ readonly default: ResolverDefault;
2485
+ constructor(options: ResolverBuildOptions);
2486
+ /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
2487
+ get [resolverOptions](): ResolverBuildOptions;
2488
+ name(name: string): string;
2489
+ file(options: ResolveFileOptions): FileNode;
2490
+ /**
2491
+ * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
2492
+ * order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
2493
+ * schemas (`targetName`) import the emitted name. Names and paths go through the top-level
2494
+ * `name` and `file`, so import entries follow the plugin's conventions, and a per-call
2495
+ * `name` override wins over both.
2496
+ *
2497
+ * The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a
2498
+ * schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver
2499
+ * reads the same ref set instead of re-scanning it per plugin.
2500
+ */
2501
+ imports(options: ResolveImportsOptions): Array<ImportNode>;
2502
+ /**
2503
+ * Folds each `override` over `base`, left to right, and returns a new resolver with helpers
2504
+ * re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding
2505
+ * `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying
2506
+ * `setResolver` partial overrides, and to compose shared resolver fragments without spreading each
2507
+ * namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,
2508
+ * so a `file` override survives even when `base` and `override` come from different `@kubb/core`
2509
+ * copies.
2510
+ *
2511
+ * @example Fold several partial overrides onto a resolver
2512
+ * ```ts
2513
+ * const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })
2514
+ * ```
2515
+ */
2516
+ static merge<T extends Resolver>(base: T, ...overrides: Array<ResolverPatch<T> | Resolver>): T;
2517
+ }
2518
+ //#endregion
2519
+ //#region src/definePlugin.d.ts
2520
+ /** Reads key `K` from a registry interface, or `{}` when no package has augmented it. @internal */
2521
+ type ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {};
2522
+ /**
2523
+ * A plugin name as accepted by `getPlugin`/`requirePlugin`/`getResolver`. Registered names from
2524
+ * `Kubb.PluginRegistry` autocomplete, and any other string is still allowed.
2525
+ */
2526
+ type PluginName = LiteralUnion<keyof Kubb.PluginRegistry>;
2527
+ /**
2528
+ * Resolves a plugin name to its `PluginType`. A name registered in `Kubb.PluginRegistry`
2529
+ * maps to its exact factory options, any other string falls back to the generic options.
2530
+ */
2531
+ type ResolvePluginOptions<TName> = TName extends keyof Kubb.PluginRegistry ? Kubb.PluginRegistry[TName] : PluginType;
2532
+ /**
2533
+ * How a plugin consolidates its generated code into files.
2534
+ * - `'file'` writes everything into a single file.
2535
+ * - `'directory'` writes one file per operation or schema under `path`.
2536
+ */
2537
+ type OutputMode = 'directory' | 'file';
2538
+ /**
2539
+ * Output configuration shared by every plugin. Each plugin extends this with
2540
+ * its own keys via the `Kubb.PluginOptionsRegistry.output` interface merge.
2541
+ */
2542
+ type Output = {
2543
+ /**
2544
+ * Directory where the plugin writes its generated code, resolved against the global
2545
+ * `output.path` set on `defineConfig`. With `mode: 'file'`, this is the full output file
2546
+ * path and must include the extension (e.g. `'types.ts'`, `'models.py'`).
2547
+ */
2548
+ path: string;
2549
+ /**
2550
+ * How generated code is consolidated into files.
2551
+ * - `'file'` writes everything into a single file. The `path` must include the file extension.
2552
+ * - `'directory'` writes one file per operation or schema under `path`.
2553
+ *
2554
+ * Defaults to `'file'` when `path` carries an extension and `'directory'` when it does not.
2555
+ */
2556
+ mode?: OutputMode;
2557
+ /**
2558
+ * Text prepended to every generated file. Useful for license headers,
2559
+ * lint disables, or `@ts-nocheck` directives.
2560
+ *
2561
+ * A string is applied to every file (including barrel and aggregation re-export files).
2562
+ * Pass a function to compute the banner from the file's `BannerMeta` document metadata
2563
+ * plus per-file context (`isBarrel`, `isAggregation`, `filePath`, `baseName`), so you can
2564
+ * skip the banner on specific files.
2565
+ *
2566
+ * @example Add a directive to source files but not re-export files
2567
+ * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : "'use server'"`
2568
+ */
2569
+ banner?: string | ((meta: BannerMeta) => string);
2570
+ /**
2571
+ * Text appended at the end of every generated file. Mirror of `banner`.
2572
+ * Pass a function to compute the footer from the file's `BannerMeta`.
2573
+ */
2574
+ footer?: string | ((meta: BannerMeta) => string);
2575
+ } & ExtractRegistryKey<Kubb.PluginOptionsRegistry, 'output'>;
2576
+ /**
2577
+ * Groups generated files into subdirectories based on an OpenAPI tag or path
2578
+ * segment.
2579
+ */
2580
+ type Group = {
2581
+ /**
2582
+ * Property used to assign each operation to a group.
2583
+ * - `'tag'` uses the first tag (`operation.getTags().at(0)?.name`).
2584
+ * - `'path'` uses the first segment of the operation's URL.
2585
+ */
2586
+ type: 'tag' | 'path';
2587
+ /**
2588
+ * Returns the subdirectory name from the group key. Defaults to the camelCased tag for
2589
+ * `tag` groups, or the first path segment as written in the spec for `path` groups.
2590
+ */
2591
+ name?: (context: {
2592
+ group: string;
2593
+ }) => string;
2594
+ };
2595
+ /**
2596
+ * Couples `output.mode` with the plugin's `group` option at the type level.
2597
+ * - An explicit `mode: 'file'` forbids `group` (a single file has nothing to group).
2598
+ * - Omitting `mode`, or setting it to `'directory'`, allows an optional `group`.
2599
+ *
2600
+ * `mode` is normally inferred from `output.path` (an extension means `'file'`, anything
2601
+ * else `'directory'`), so `group` rarely needs `mode` spelled out alongside it. Set
2602
+ * `mode: 'directory'` explicitly only to override that inference, such as a directory
2603
+ * name that carries a dot (`path: 'clients.v2'`).
2604
+ *
2605
+ * Intersect into a plugin's `Options` type instead of declaring `output` and
2606
+ * `group` directly, since `mode` lives inside `output` while `group` is its sibling.
2607
+ * The generic keeps a plugin's extended `Output` shape intact.
2608
+ *
2609
+ * @example
2610
+ * ```ts
2611
+ * export type Options = OutputOptions & {
2612
+ * exclude?: Array<Exclude>
2613
+ * }
2614
+ * ```
2615
+ */
2616
+ type OutputOptions<TOutput extends Output = Output> = {
2617
+ output?: TOutput & {
2618
+ mode?: 'directory';
2619
+ };
2620
+ group?: Group;
2621
+ } | {
2622
+ output?: TOutput & {
2623
+ mode: 'file';
2624
+ };
2625
+ group?: never;
2626
+ };
2627
+ /** Throws `KUBB_INVALID_PLUGIN_OPTIONS`, listing the allowed values, when `value` is not one of `allowed`. */
2628
+ export declare function assertPluginOption({ plugin, option, value, allowed }: {
2629
+ plugin: string;
2630
+ option: string;
2631
+ value: unknown;
2632
+ allowed: ReadonlyArray<unknown>;
2633
+ }): void;
2634
+ type ByTag = {
2635
+ /**
2636
+ * Filter by OpenAPI `tags` field. Matches one or more tags assigned to operations.
2637
+ */
2638
+ type: 'tag';
2639
+ /**
2640
+ * Tag name to match (case-sensitive). Can be a literal string or regex pattern.
2641
+ */
2642
+ pattern: string | RegExp;
2643
+ };
2644
+ type ByOperationId = {
2645
+ /**
2646
+ * Filter by OpenAPI `operationId` field. Each operation (GET, POST, etc.) has a unique identifier.
2647
+ */
2648
+ type: 'operationId';
2649
+ /**
2650
+ * Operation ID to match (case-sensitive). Can be a literal string or regex pattern.
2651
+ */
2652
+ pattern: string | RegExp;
2653
+ };
2654
+ type ByPath = {
2655
+ /**
2656
+ * Filter by OpenAPI `path` (URL endpoint). Useful to group or filter by service segments like `/pets`, `/users`, etc.
2657
+ */
2658
+ type: 'path';
2659
+ /**
2660
+ * URL path to match (case-sensitive). Can be a literal string or regex pattern. Matches against the full path.
2661
+ */
2662
+ pattern: string | RegExp;
2663
+ };
2664
+ type ByMethod = {
2665
+ /**
2666
+ * Filter by HTTP method: `'GET'`, `'POST'`, `'PUT'`, `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`, `'QUERY'`.
2667
+ */
2668
+ type: 'method';
2669
+ /**
2670
+ * HTTP method to match, as one of the `HttpMethod` values (`'GET'`, `'POST'`, `'PUT'`,
2671
+ * `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`, `'QUERY'`) or a regex.
2672
+ */
2673
+ pattern: HttpMethod | RegExp;
2674
+ };
2675
+ type BySchemaName = {
2676
+ /**
2677
+ * Filter by schema component name (TypeScript or JSON schema). Matches schemas in `#/components/schemas`.
2678
+ */
2679
+ type: 'schemaName';
2680
+ /**
2681
+ * Schema name to match (case-sensitive). Can be a literal string or regex pattern.
2682
+ */
2683
+ pattern: string | RegExp;
2684
+ };
2685
+ type ByContentType = {
2686
+ /**
2687
+ * Filter by response or request content type: `'application/json'`, `'application/xml'`, etc.
2688
+ */
2689
+ type: 'contentType';
2690
+ /**
2691
+ * Content type to match (case-sensitive). Can be a literal string or regex pattern.
2692
+ */
2693
+ pattern: string | RegExp;
2694
+ };
2695
+ type ByExtension = {
2696
+ /** Filter operations by a vendor extension (`x-*` key) on the source operation. Does not apply to schemas. */
2697
+ type: 'extension';
2698
+ /** Extension key, including the `x-` prefix. */
2699
+ key: `x-${string}`;
2700
+ /** Value the extension must strictly equal. When omitted, the key being present is enough. */
2701
+ value?: unknown;
2702
+ };
2703
+ /**
2704
+ * Pattern filter for include, exclude, and override rules. Matches operations or schemas
2705
+ * by tag, operationId, path, method, content type, schema name, or vendor extension.
2706
+ */
2707
+ type Filter = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName | ByExtension;
2708
+ /**
2709
+ * Filter that skips matching operations or schemas during generation, for example
2710
+ * deprecated endpoints or internal-only schemas.
2711
+ *
2712
+ * @example
2713
+ * ```ts
2714
+ * exclude: [
2715
+ * { type: 'tag', pattern: 'internal' },
2716
+ * { type: 'path', pattern: /^\/admin/ },
2717
+ * { type: 'operationId', pattern: /^deprecated_/ },
2718
+ * { type: 'extension', key: 'x-internal', value: true },
2719
+ * ]
2720
+ * ```
2721
+ */
2722
+ type Exclude$1 = Filter;
2723
+ /**
2724
+ * Filter that restricts generation to operations or schemas matching at least
2725
+ * one entry. Useful for partial builds (one tag, one API version).
2726
+ *
2727
+ * @example
2728
+ * ```ts
2729
+ * include: [
2730
+ * { type: 'tag', pattern: 'public' },
2731
+ * { type: 'path', pattern: /^\/api\/v1/ },
2732
+ * ]
2733
+ * ```
2734
+ */
2735
+ type Include = Filter;
2736
+ /**
2737
+ * Filter paired with a partial options object. When the filter matches, the
2738
+ * options are merged on top of the plugin defaults for that operation only.
2739
+ * Useful for "this one tag goes to a different folder" rules.
2740
+ *
2741
+ * Entries are evaluated top to bottom. The first matching entry wins.
2742
+ *
2743
+ * @example
2744
+ * ```ts
2745
+ * override: [
2746
+ * {
2747
+ * type: 'tag',
2748
+ * pattern: 'admin',
2749
+ * options: { output: { path: './src/gen/admin' } },
2750
+ * },
2751
+ * {
2752
+ * type: 'operationId',
2753
+ * pattern: 'listPets',
2754
+ * options: { enumType: 'literal' },
2755
+ * },
2756
+ * ]
2757
+ * ```
2758
+ */
2759
+ type Override<TOptions> = Filter & {
2760
+ options: Omit<Partial<TOptions>, 'override'>;
2761
+ };
2762
+ type PluginType<
2763
+ /**
2764
+ * Unique plugin name.
2765
+ */
2766
+ TName extends string = string,
2767
+ /**
2768
+ * User-facing plugin options.
2769
+ */
2770
+ TOptions extends object = object,
2771
+ /**
2772
+ * Plugin options after defaults are applied.
2773
+ */
2774
+ TResolvedOptions extends object = TOptions,
2775
+ /**
2776
+ * Resolver that encapsulates naming and path-resolution helpers.
2777
+ * Define with `createResolver` and export alongside the plugin.
2778
+ */
2779
+ TResolver extends Resolver = Resolver> = {
2780
+ name: TName;
2781
+ options: TOptions;
2782
+ resolvedOptions: TResolvedOptions;
2783
+ resolver: TResolver;
2784
+ };
2785
+ /**
2786
+ * Context passed to a plugin's `kubb:plugin:setup` handler, where it registers generators and
2787
+ * sets its resolver, transformer, and options.
2788
+ */
2789
+ type KubbPluginSetupContext<TFactory extends PluginType = PluginType> = {
2790
+ /**
2791
+ * Register one or more generators dynamically. Generators fire during the AST walk
2792
+ * (schema/operation/operations) just like generators declared statically on `createPlugin`.
2793
+ *
2794
+ * Pass generators as separate arguments. Spread an existing list to register it in one call.
2795
+ *
2796
+ * @example
2797
+ * ```ts
2798
+ * ctx.addGenerator(myGenerator)
2799
+ * ctx.addGenerator(schemaGenerator, operationGenerator)
2800
+ * ctx.addGenerator(...selectedGenerators)
2801
+ * ```
2802
+ */
2803
+ addGenerator<TElement = unknown>(...generators: Array<Generator<TFactory, TElement>>): void;
2804
+ /**
2805
+ * Set or override the resolver for this plugin.
2806
+ * The resolver controls file naming and path resolution. Overrides merge over the built-in
2807
+ * defaults, so a partial `core` or a single namespace method replaces only what it names.
2808
+ */
2809
+ setResolver(resolver: ResolverPatch<TFactory['resolver']> | TFactory['resolver']): void;
2810
+ /**
2811
+ * Add a macro that rewrites AST nodes before they reach generators. Macros run in the order they
2812
+ * are added, after any macros from earlier `addMacro` calls.
2813
+ */
2814
+ addMacro(macro: Macro): void;
2815
+ /**
2816
+ * Replace this plugin's macros with `macros`.
2817
+ */
2818
+ setMacros(macros: ReadonlyArray<Macro>): void;
2819
+ /**
2820
+ * Set resolved options merged into the normalized plugin's `options`.
2821
+ * Call this in `kubb:plugin:setup` to provide options generators need.
2822
+ */
2823
+ setOptions(options: TFactory['resolvedOptions']): void;
2824
+ /**
2825
+ * Inject a raw file into the build output, bypassing the generation pipeline.
2826
+ *
2827
+ * Pass `copy` with an absolute path to emit a real source file (a shipped template) into the
2828
+ * generated folder, instead of building its content from `sources`.
2829
+ */
2830
+ injectFile(userFileNode: UserFileNode): void;
2831
+ /** Returns a plugin this one needs, or fails the run with `KUBB_PLUGIN_NOT_FOUND` when the config lacks it. */
2832
+ requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>;
2833
+ /**
2834
+ * The resolved build configuration at setup time.
2835
+ */
2836
+ config: Config;
2837
+ /**
2838
+ * The plugin's user-provided options.
2839
+ */
2840
+ options: TFactory['options'];
2841
+ };
2842
+ /**
2843
+ * A plugin object produced by `defineExtension`. Its lifecycle handlers live under a single
2844
+ * `hooks` property rather than flat methods.
2845
+ */
2846
+ type Plugin<TFactory extends PluginType = PluginType> = ExtensionNamed & {
2847
+ /**
2848
+ * Plugins this one builds on. They run first when the config has them. An array only orders
2849
+ * plugins. A record also fails the run when a required entry is missing or out of range.
2850
+ */
2851
+ dependencies?: Array<PluginName> | ExtensionDependencies<TFactory['options']>;
2852
+ /**
2853
+ * Controls the execution order of this plugin relative to others.
2854
+ *
2855
+ * - `'pre'` runs before all normal plugins.
2856
+ * - `'post'` runs after all normal plugins.
2857
+ * - `undefined` (default) runs in declaration order among normal plugins.
2858
+ *
2859
+ * Dependency constraints always take precedence over `enforce`.
2860
+ */
2861
+ enforce?: Enforce;
2862
+ /**
2863
+ * The options passed by the user when calling the plugin factory.
2864
+ */
2865
+ options?: TFactory['options'];
2866
+ /**
2867
+ * Lifecycle hook handlers for this plugin.
2868
+ * Any hook from the global `KubbHooks` map can be subscribed to here.
2869
+ */
2870
+ hooks: { [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void>; } & {
2871
+ 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
2872
+ };
2873
+ /**
2874
+ * Runs before `kubb:plugin:setup`. Takes the user's options and returns the resolved options.
2875
+ */
2876
+ setup?(options: TFactory['options'], kubb: KubbPluginSetupContext<TFactory>): TFactory['resolvedOptions'] | Promise<TFactory['resolvedOptions']>;
2877
+ };
2878
+ /**
2879
+ * The object passed to `defineExtension` with `kind: 'plugin'`.
2880
+ */
2881
+ type PluginDefinition<TFactory extends PluginType = PluginType> = Pick<Plugin<TFactory>, 'dependencies' | 'enforce' | 'setup'> & {
2882
+ meta: ExtensionMeta<TFactory['name']>;
2883
+ hooks?: Plugin<TFactory>['hooks'];
2884
+ };
2885
+ /**
2886
+ * The function `defineExtension` returns for a plugin. Call it with user options to get a `Plugin`.
2887
+ */
2888
+ type PluginFactory<TFactory extends PluginType = PluginType> = ExtensionFactory<'plugin', TFactory['options'], Plugin<TFactory>, TFactory['name']>;
2889
+ /**
2890
+ * Normalized plugin after setup, with runtime fields populated. Internal only. Plugins use the
2891
+ * public `Plugin` type.
2892
+ *
2893
+ * @internal
2894
+ */
2895
+ type NormalizedPlugin<TOptions extends PluginType = PluginType> = Plugin<TOptions> & {
2896
+ name: string;
2897
+ meta: ExtensionMeta;
2898
+ dependencies?: Array<PluginName> | ExtensionDependencyRecord;
2899
+ options: TOptions['resolvedOptions'] & {
2900
+ output: Output;
2901
+ include?: Array<Include>;
2902
+ exclude: Array<Exclude$1>;
2903
+ override: Array<Override<TOptions['resolvedOptions']>>;
2904
+ };
2905
+ resolver: TOptions['resolver'];
2906
+ macros?: Array<Macro>;
2907
+ generators?: Array<Generator>;
2908
+ };
2909
+ type KubbPluginStartContext = {
2910
+ plugin: NormalizedPlugin;
2911
+ };
2912
+ type KubbPluginEndContext = FilesContext & {
2913
+ plugin: NormalizedPlugin;
2914
+ duration: number;
2915
+ success: boolean;
2916
+ error?: Error;
2917
+ config: Config;
2918
+ };
2919
+ /**
2920
+ * Defines a plugin from one object and returns a factory that takes the user's options.
2921
+ *
2922
+ * @deprecated Use `defineExtension` with `kind: 'plugin'` instead.
2923
+ */
2924
+ export declare function definePlugin<TFactory extends PluginType = PluginType>(definition: PluginDefinition<TFactory>): PluginFactory<TFactory>;
2925
+ //#endregion
2926
+ //#region src/defineExtension.d.ts
2927
+ /**
2928
+ * What an extension extends: a plugin generates code, an adapter reads the input, a parser prints files.
2929
+ */
2930
+ type ExtensionKind = 'plugin' | 'adapter' | 'parser';
2931
+ /**
2932
+ * Identity and registry data for an extension. Kubb reads `name` and `compatibility` at runtime.
2933
+ * Studio, the kubb.dev registry, and the docs read the rest.
2934
+ */
2935
+ type ExtensionMeta<TName extends string = string> = {
2936
+ /**
2937
+ * Unique name, such as `'plugin-ts'`. Becomes the plugin's `name`.
2938
+ */
2939
+ name: TName;
2940
+ /**
2941
+ * Package version. Dependents check their `version` range against it.
2942
+ */
2943
+ version?: string;
2944
+ displayName?: string;
2945
+ /**
2946
+ * One-sentence summary of what the extension generates or does.
2947
+ */
2948
+ description?: string;
2949
+ category?: string;
2950
+ icon?: {
2951
+ light: string;
2952
+ dark?: string;
2953
+ };
2954
+ /** HTTPS image or video URLs. */
2955
+ media?: Array<string>;
2956
+ tags?: Array<string>;
2957
+ /**
2958
+ * Semver ranges the extension supports. A mismatch fails the run with `KUBB_INCOMPATIBLE_EXTENSION`.
2959
+ */
2960
+ compatibility?: {
2961
+ kubb?: string;
2962
+ node?: string;
2963
+ };
2964
+ docs?: string;
2965
+ /** Issue tracker URL. Kubb prints it when the extension crashes, so users report the bug to its maintainers. */
2966
+ issues?: string;
2967
+ };
2968
+ /**
2969
+ * An extension's identity: `meta`, a `name`, or both. `name` is deprecated in favor of `meta.name`.
2970
+ */
2971
+ type ExtensionNamed = {
2972
+ name?: string;
2973
+ meta?: ExtensionMeta;
2974
+ };
2975
+ /**
2976
+ * Returns `meta`, or `{ name }` for an extension that only sets the deprecated `name`. Throws `KUBB_INVALID_PLUGIN_OPTIONS` when it has neither.
2977
+ */
2978
+ export declare function resolveMeta(extension: ExtensionNamed): ExtensionMeta;
2979
+ /**
2980
+ * Sets how Kubb checks one entry in a `dependencies` record.
2981
+ */
2982
+ type ExtensionDependency = {
2983
+ /**
2984
+ * Semver range the dependency's `meta.version` must satisfy. Skipped when the dependency has no `meta.version`.
2985
+ */
2986
+ version?: string;
2987
+ /**
2988
+ * When `true`, Kubb skips the entry if the plugin is missing, but still checks `version` on an installed one.
2989
+ * Otherwise a missing plugin fails the run with `KUBB_MISSING_DEPENDENCY`.
2990
+ */
2991
+ optional?: boolean;
2992
+ };
2993
+ /**
2994
+ * Plugins an extension builds on, keyed by name, or a function that picks them from the user's options.
2995
+ */
2996
+ type ExtensionDependencies<TOptions = object> = ExtensionDependencyRecord | {
2997
+ resolve(options: TOptions, kubb: {
2998
+ config: Config;
2999
+ }): ExtensionDependencyRecord;
3000
+ }['resolve'];
3001
+ /**
3002
+ * Maps each dependency's plugin name to how Kubb checks it.
3003
+ */
3004
+ type ExtensionDependencyRecord = Partial<Record<PluginName, ExtensionDependency>>;
3005
+ /**
3006
+ * Throws `KUBB_INCOMPATIBLE_EXTENSION` when the running Kubb or Node.js version is outside `meta.compatibility`.
3007
+ */
3008
+ export declare function checkCompatibility(meta: ExtensionMeta): void;
3009
+ /**
3010
+ * The function an extension definition returns. Call it with user options to get the extension.
3011
+ */
3012
+ type ExtensionFactory<TKind extends ExtensionKind, TOptions, TExtension, TName extends string = string> = {
3013
+ (options?: TOptions): TExtension;
3014
+ kind: TKind;
3015
+ meta: ExtensionMeta<TName>;
3016
+ };
3017
+ /**
3018
+ * Defines a parser and returns a factory that takes the user's options. `build` returns the parser methods.
3019
+ */
3020
+ export declare function defineExtension<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(definition: {
3021
+ kind: 'parser';
3022
+ meta: ExtensionMeta;
3023
+ build: ParserBuild<TOptions, TMeta, TNode>;
3024
+ }): ParserFactory<TOptions, TMeta, TNode>;
3025
+ /**
3026
+ * Defines an adapter and returns a factory that takes the user's options. `parse` must return an `InputNode`.
3027
+ */
3028
+ export declare function defineExtension<T extends AdapterFactoryOptions = AdapterFactoryOptions>(definition: {
3029
+ kind: 'adapter';
3030
+ } & AdapterDefinition<T>): AdapterFactory<T>;
3031
+ /**
3032
+ * Defines a plugin and returns a factory that takes the user's options. Name plugins `plugin-<feature>`.
3033
+ *
3034
+ * @example
3035
+ * ```ts
3036
+ * defineExtension<PluginZod>({ kind: 'plugin', meta: { name: 'plugin-zod' }, setup: (options) => options })
3037
+ * ```
3038
+ */
3039
+ export declare function defineExtension<TFactory extends PluginType = PluginType>(definition: {
3040
+ kind: 'plugin';
3041
+ } & PluginDefinition<TFactory>): PluginFactory<TFactory>;
3042
+ //#endregion
3043
+ //#region src/createAdapter.d.ts
3044
+ /**
3045
+ * Source data handed to an adapter's `parse` function. Mirrors the config
3046
+ * input shape with paths resolved to absolute.
3047
+ *
3048
+ * - `{ type: 'path' }`: single file on disk.
3049
+ * - `{ type: 'data' }`: raw string or parsed object provided inline.
3050
+ */
3051
+ type AdapterSource = {
3052
+ type: 'path';
3053
+ path: string;
3054
+ } | {
3055
+ type: 'data';
3056
+ data: string | unknown;
3057
+ };
3058
+ /**
3059
+ * Generic parameters used by `defineExtension` with `kind: 'adapter'` and the resulting `Adapter` type.
3060
+ *
3061
+ * - `TName`: unique adapter identifier (`'oas'`, `'asyncapi'`, ...).
3062
+ * - `TOptions`: user-facing options accepted by the adapter factory.
3063
+ * - `TResolvedOptions`: options after defaults are applied.
3064
+ * - `TDocument`: type of the parsed source document.
3065
+ */
3066
+ type AdapterFactoryOptions<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TDocument = unknown> = {
3067
+ name: TName;
3068
+ options: TOptions;
3069
+ resolvedOptions: TResolvedOptions;
3070
+ document: TDocument;
3071
+ };
3072
+ /**
3073
+ * Converts input files or inline data into Kubb's universal AST `InputNode`.
3074
+ *
3075
+ * Adapters live between the spec format and the plugins. The built-in
3076
+ * `@kubb/adapter-oas` handles OpenAPI 2.0, 3.0, and 3.1. A custom adapter can
3077
+ * support GraphQL, gRPC, or another schema language.
3078
+ *
3079
+ * @example
3080
+ * ```ts
3081
+ * import { defineConfig } from 'kubb'
3082
+ * import { adapterOas } from '@kubb/adapter-oas'
3083
+ * import { pluginTs } from '@kubb/plugin-ts'
3084
+ *
3085
+ * export default defineConfig({
3086
+ * input: './petStore.yaml',
3087
+ * output: { path: './src/gen' },
3088
+ * adapter: adapterOas(),
3089
+ * plugins: [pluginTs()],
3090
+ * })
3091
+ * ```
3092
+ */
3093
+ type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
3094
+ /**
3095
+ * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).
3096
+ */
3097
+ name: TOptions['name'];
3098
+ meta?: ExtensionMeta<TOptions['name']>;
3099
+ /**
3100
+ * Resolved adapter options after defaults have been applied.
3101
+ */
3102
+ options: TOptions['resolvedOptions'];
3103
+ /**
3104
+ * Parsed source document after the first `parse()` call. `null` before parsing.
3105
+ */
3106
+ document: TOptions['document'] | null;
3107
+ /**
3108
+ * Parse the source into a universal `InputNode`.
3109
+ *
3110
+ * An adapter that renames schemas (e.g. collision handling) must stamp `targetName` on
3111
+ * every ref node pointing at a renamed schema, so `resolveRefName` and `resolver.imports`
3112
+ * resolve a `$ref` to the file that is actually generated. Refs that keep their pointer's
3113
+ * last segment need no stamp.
3114
+ */
3115
+ parse: (source: AdapterSource, options?: {
3116
+ signal?: AbortSignal;
3117
+ }) => PossiblePromise<InputNode>;
3118
+ /**
3119
+ * Validate the document at the given path or URL.
3120
+ */
3121
+ validate: (input: string, options?: {
3122
+ throwOnError?: boolean;
3123
+ }) => Promise<void>;
3124
+ };
3125
+ /**
3126
+ * The object passed to `defineExtension` with `kind: 'adapter'`.
3127
+ */
3128
+ type AdapterDefinition<T extends AdapterFactoryOptions = AdapterFactoryOptions> = {
3129
+ meta: ExtensionMeta<T['name']>;
3130
+ /**
3131
+ * Takes the user's options and returns the resolved options, which `build` receives and the adapter exposes as `options`.
3132
+ * Without `setup`, the user's options are the resolved options.
3133
+ */
3134
+ setup?(options: T['options']): T['resolvedOptions'];
3135
+ /**
3136
+ * Returns the adapter's document and methods for the resolved options.
3137
+ */
3138
+ build(options: T['resolvedOptions']): Omit<Adapter<T>, 'name' | 'meta' | 'options'>;
3139
+ };
3140
+ /**
3141
+ * The function `defineExtension` returns for an adapter. Call it with user options to get an `Adapter`.
3142
+ */
3143
+ type AdapterFactory<T extends AdapterFactoryOptions = AdapterFactoryOptions> = ExtensionFactory<'adapter', T['options'], Adapter<T>, T['name']>;
3144
+ /**
3145
+ * Defines a custom adapter that translates a spec format into Kubb's universal
3146
+ * AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
3147
+ * handles OpenAPI/Swagger documents.
3148
+ *
3149
+ * Adapters must return an `InputNode` from `parse`. That node is what every
3150
+ * plugin in the build consumes.
3151
+ *
3152
+ * @deprecated Use `defineExtension` with `kind: 'adapter'` instead.
3153
+ */
3154
+ export declare function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(definition: AdapterDefinition<T>): AdapterFactory<T>;
3155
+ //#endregion
4
3156
  //#region src/composables.d.ts
5
3157
  /**
6
3158
  * Holds the setup context of the plugin whose `setup` or `kubb:plugin:setup` is running. `KubbDriver` sets it for each plugin.
@@ -139,7 +3291,7 @@ type GenerateResult = {
139
3291
  * const { files, diagnostics } = await kubb.safeBuild()
140
3292
  * ```
141
3293
  */
142
- declare class Kubb {
3294
+ declare class Kubb$1 {
143
3295
  #private;
144
3296
  readonly hooks: Hookable<KubbHooks>;
145
3297
  readonly config: Config;
@@ -197,7 +3349,7 @@ declare class Kubb {
197
3349
  * await kubb.build()
198
3350
  * ```
199
3351
  */
200
- export declare function createKubb(userConfig: UserConfig, options?: CreateKubbOptions): Kubb;
3352
+ export declare function createKubb(userConfig: UserConfig, options?: CreateKubbOptions): Kubb$1;
201
3353
  //#endregion
202
3354
  //#region src/reporters/summary.d.ts
203
3355
  /**
@@ -616,5 +3768,5 @@ export declare function readInstalledPackages({ root, packages, resolveFrom }: {
616
3768
  resolveFrom?: Array<string>;
617
3769
  }): Promise<Array<InstalledPackage>>;
618
3770
  //#endregion
619
- export { type Adapter, type AdapterDefinition, type AdapterFactory, type AdapterFactoryOptions, type AdapterSource, type BannerMeta, BuildOutput, CLIOptions, Config, type CreateKubbOptions, type Diagnostic, type DiagnosticDoc, type DiagnosticFormatOptions, type DiagnosticKind, type DiagnosticLocation, type DiagnosticSeverity, Diagnostics, type Exclude, type ExtensionDependencies, type ExtensionDependency, type ExtensionDependencyRecord, type ExtensionFactory, type ExtensionKind, type ExtensionManifest, type ExtensionManifestOption, type ExtensionMeta, FilesContext, type Filter, type GenerateOptions, type GenerateResult, type GenerationResult, type Generator, type GeneratorContext, type Group, type HookResult, Hookable, type Include, Input, type InputKind, type InstalledPackage, type JSONValue, type Kubb, KubbBuildEndContext, KubbBuildStartContext, KubbDiagnosticContext, KubbDriver, KubbErrorContext, KubbFileProcessingUpdate, KubbFilesProcessingEndContext, KubbFilesProcessingStartContext, KubbFilesProcessingUpdateContext, KubbGenerationEndContext, KubbGenerationStartContext, KubbGenerationSummaryContext, KubbHookEndContext, KubbHookLineContext, KubbHookStartContext, KubbHooks, KubbInfoContext, KubbLifecycleStartContext, KubbMessageContext, type KubbPluginEndContext, type KubbPluginSetupContext, type KubbPluginStartContext, KubbPluginsEndContext, KubbSuccessContext, KubbWarnContext, type NodeCache, type NormalizedPlugin, type Output, type OutputMode, type OutputOptions, type Override, type Parser, type ParserDefinition, type ParserFactory, type PerformanceDiagnostic, type Plugin, type PluginDefinition, type PluginFactory, type PluginName, type PluginType, PossibleConfig, PostGenerateCommand, type ProblemCode, type ProblemDiagnostic, type RegistryArtifact, type RegistryDetail, type RegistryEntry, type RegistryGuide, type RegistryIndex, type Renderer, type RendererFactory, type Reporter, type ReporterContext, type ReporterName, type ReporterPluginFiles, type ResolveBannerContext, type ResolveBannerFile, type ResolveFileOptions, type ResolveImportsOptions, type ResolveOptionsContext, type ResolvePathOptions, type ResolvePluginOptions, Resolver, type ResolverDefault, type ResolverFile, type ResolverFileParams, type ResolverFilePathParams, type ResolverPatch, type ResolverPathParams, type RunHookOptions, type RunOutputPassesOptions, type SerializedDiagnostic, type Storage, type SummaryRenderer, type UpdateDiagnostic, UserConfig, type UserReporter, assertPluginOption, checkCompatibility, createAdapter, createRenderer, createReporter, createStorage, defineExtension, defineGenerator, defineParser, definePlugin, logLevel, resolveMeta, runHook };
3771
+ export type { Adapter, AdapterDefinition, AdapterFactory, AdapterFactoryOptions, AdapterSource, BannerMeta, CreateKubbOptions, Diagnostic, DiagnosticDoc, DiagnosticFormatOptions, DiagnosticKind, DiagnosticLocation, DiagnosticSeverity, Exclude$1 as Exclude, ExtensionDependencies, ExtensionDependency, ExtensionDependencyRecord, ExtensionFactory, ExtensionKind, ExtensionManifest, ExtensionManifestOption, ExtensionMeta, Filter, GenerateOptions, GenerateResult, GenerationResult, Generator, GeneratorContext, Group, HookResult, Include, InputKind, InstalledPackage, JSONValue, Kubb$1 as Kubb, KubbPluginEndContext, KubbPluginSetupContext, KubbPluginStartContext, NodeCache, NormalizedPlugin, Output, OutputMode, OutputOptions, Override, Parser, ParserDefinition, ParserFactory, PerformanceDiagnostic, Plugin, PluginDefinition, PluginFactory, PluginName, PluginType, ProblemCode, ProblemDiagnostic, RegistryArtifact, RegistryDetail, RegistryEntry, RegistryGuide, RegistryIndex, Renderer, RendererFactory, Reporter, ReporterContext, ReporterName, ReporterPluginFiles, ResolveBannerContext, ResolveBannerFile, ResolveFileOptions, ResolveImportsOptions, ResolveOptionsContext, ResolvePathOptions, ResolvePluginOptions, ResolverDefault, ResolverFile, ResolverFileParams, ResolverFilePathParams, ResolverPatch, ResolverPathParams, RunHookOptions, RunOutputPassesOptions, SerializedDiagnostic, Storage, SummaryRenderer, UpdateDiagnostic, UserReporter };
620
3772
  //# sourceMappingURL=index.d.cts.map