@kubb/core 5.0.0-beta.11 → 5.0.0-beta.110

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