@kubb/core 5.0.0-beta.4 → 5.0.0-beta.41

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