@kubb/core 5.0.0-beta.7 → 5.0.0-beta.71

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