@kubb/core 5.15.1 → 5.15.3

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