@kubb/core 5.0.0-beta.8 → 5.0.0-beta.81

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