@kubb/core 5.0.0-beta.2 → 5.0.0-beta.20

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 (42) hide show
  1. package/README.md +8 -38
  2. package/dist/{PluginDriver-BXibeQk-.cjs → KubbDriver-BXSnJ3qM.cjs} +719 -164
  3. package/dist/KubbDriver-BXSnJ3qM.cjs.map +1 -0
  4. package/dist/{PluginDriver-DV3p2Hky.js → KubbDriver-Cxii_rBp.js} +693 -162
  5. package/dist/KubbDriver-Cxii_rBp.js.map +1 -0
  6. package/dist/{types-CC09VtBt.d.ts → createKubb-Dcmtjqds.d.ts} +1395 -1238
  7. package/dist/index.cjs +556 -785
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.ts +2 -185
  10. package/dist/index.js +551 -783
  11. package/dist/index.js.map +1 -1
  12. package/dist/mocks.cjs +30 -21
  13. package/dist/mocks.cjs.map +1 -1
  14. package/dist/mocks.d.ts +5 -5
  15. package/dist/mocks.js +29 -20
  16. package/dist/mocks.js.map +1 -1
  17. package/package.json +6 -18
  18. package/src/FileManager.ts +12 -0
  19. package/src/FileProcessor.ts +37 -38
  20. package/src/{PluginDriver.ts → KubbDriver.ts} +249 -86
  21. package/src/constants.ts +11 -6
  22. package/src/createAdapter.ts +84 -1
  23. package/src/createKubb.ts +1336 -297
  24. package/src/createRenderer.ts +23 -22
  25. package/src/defineGenerator.ts +96 -7
  26. package/src/defineLogger.ts +42 -3
  27. package/src/defineMiddleware.ts +1 -1
  28. package/src/defineParser.ts +1 -1
  29. package/src/definePlugin.ts +304 -8
  30. package/src/defineResolver.ts +268 -147
  31. package/src/devtools.ts +8 -1
  32. package/src/index.ts +2 -2
  33. package/src/mocks.ts +11 -14
  34. package/src/storages/fsStorage.ts +13 -37
  35. package/src/types.ts +38 -1292
  36. package/dist/PluginDriver-BXibeQk-.cjs.map +0 -1
  37. package/dist/PluginDriver-DV3p2Hky.js.map +0 -1
  38. package/src/Kubb.ts +0 -300
  39. package/src/renderNode.ts +0 -35
  40. package/src/utils/diagnostics.ts +0 -18
  41. package/src/utils/isInputPath.ts +0 -10
  42. package/src/utils/packageJSON.ts +0 -99
@@ -1,5 +1,5 @@
1
1
  import { t as __name } from "./chunk--u3MIqq1.js";
2
- import { FileNode, HttpMethod, ImportNode, InputNode, Node, OperationNode, SchemaNode, UserFileNode, Visitor } from "@kubb/ast";
2
+ import { FileNode, HttpMethod, ImportNode, InputMeta, InputNode, InputStreamNode, Node, OperationNode, SchemaNode, UserFileNode, Visitor } from "@kubb/ast";
3
3
 
4
4
  //#region ../../internals/utils/src/asyncEventEmitter.d.ts
5
5
  /**
@@ -33,7 +33,7 @@ declare class AsyncEventEmitter<TEvents extends { [K in keyof TEvents]: unknown[
33
33
  * await emitter.emit('build', 'petstore')
34
34
  * ```
35
35
  */
36
- emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArgs: TEvents[TEventName]): Promise<void>;
36
+ emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArgs: TEvents[TEventName]): Promise<void> | void;
37
37
  /**
38
38
  * Registers a persistent listener for `eventName`.
39
39
  *
@@ -98,7 +98,7 @@ type PossiblePromise<T> = Promise<T> | T;
98
98
  /**
99
99
  * Base URL for the Kubb Studio web app.
100
100
  */
101
- declare const DEFAULT_STUDIO_URL: "https://studio.kubb.dev";
101
+ declare const DEFAULT_STUDIO_URL: "https://kubb.studio";
102
102
  /**
103
103
  * Numeric log-level thresholds used internally to compare verbosity.
104
104
  *
@@ -113,39 +113,165 @@ declare const logLevel: {
113
113
  readonly debug: 5;
114
114
  };
115
115
  //#endregion
116
+ //#region src/createAdapter.d.ts
117
+ /**
118
+ * Source data passed to an adapter's `parse` function.
119
+ * Mirrors the config input shape with paths resolved to absolute.
120
+ */
121
+ type AdapterSource = {
122
+ type: 'path';
123
+ path: string;
124
+ } | {
125
+ type: 'data';
126
+ data: string | unknown;
127
+ } | {
128
+ type: 'paths';
129
+ paths: Array<string>;
130
+ };
131
+ /**
132
+ * Generic type parameters for an adapter definition.
133
+ *
134
+ * - `TName` — unique identifier (e.g. `'oas'`, `'asyncapi'`)
135
+ * - `TOptions` — user-facing options passed to the adapter factory
136
+ * - `TResolvedOptions` — options after defaults applied
137
+ * - `TDocument` — type of the parsed source document
138
+ */
139
+ type AdapterFactoryOptions<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TDocument = unknown> = {
140
+ name: TName;
141
+ options: TOptions;
142
+ resolvedOptions: TResolvedOptions;
143
+ document: TDocument;
144
+ };
145
+ /**
146
+ * Adapter that converts input files or data into an `InputNode`.
147
+ *
148
+ * Adapters parse different schema formats (OpenAPI, AsyncAPI, Drizzle, etc.) into Kubb's
149
+ * universal intermediate representation that all plugins consume.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * import { adapterOas } from '@kubb/adapter-oas'
154
+ *
155
+ * export default defineConfig({
156
+ * adapter: adapterOas(),
157
+ * input: { path: './openapi.yaml' },
158
+ * plugins: [pluginTs(), pluginZod()],
159
+ * })
160
+ * ```
161
+ */
162
+ type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
163
+ /**
164
+ * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).
165
+ */
166
+ name: TOptions['name'];
167
+ /**
168
+ * Resolved adapter options after defaults have been applied.
169
+ */
170
+ options: TOptions['resolvedOptions'];
171
+ /**
172
+ * Parsed source document after the first `parse()` call. `null` before parsing.
173
+ */
174
+ document: TOptions['document'] | null;
175
+ /**
176
+ * Parse the source into a universal `InputNode`.
177
+ */
178
+ parse: (source: AdapterSource) => PossiblePromise<InputNode>;
179
+ /**
180
+ * Extract `ImportNode` entries for a schema tree.
181
+ * Returns an empty array before the first `parse()` call.
182
+ *
183
+ * The `resolve` callback receives the collision-corrected schema name and must
184
+ * return `{ name, path }` for the import, or `undefined` to skip it.
185
+ */
186
+ getImports: (node: SchemaNode, resolve: (schemaName: string) => {
187
+ name: string;
188
+ path: string;
189
+ }) => Array<ImportNode>;
190
+ /**
191
+ * Validate the document at the given path or URL.
192
+ */
193
+ validate: (input: string, options?: {
194
+ throwOnError?: boolean;
195
+ }) => Promise<void>;
196
+ /**
197
+ * Memory-efficient streaming variant of `parse()`.
198
+ *
199
+ * Returns an `InputStreamNode` whose `schemas` and `operations` are `AsyncIterable`.
200
+ * Each `for await` loop creates a fresh parse pass over the cached in-memory document —
201
+ * no pre-built arrays are held in memory.
202
+ */
203
+ stream?: (source: AdapterSource) => Promise<InputStreamNode>;
204
+ };
205
+ type AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>;
206
+ /**
207
+ * Factory for implementing custom adapters that translate non-OpenAPI specs into Kubb's AST.
208
+ *
209
+ * Use this to support GraphQL schemas, gRPC definitions, AsyncAPI, or custom domain-specific languages.
210
+ * Built-in adapters include `@kubb/adapter-oas` for OpenAPI and Swagger documents.
211
+ *
212
+ * @note Adapters must parse their input format to Kubb's `InputNode` structure.
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * export const myAdapter = createAdapter<MyAdapter>((options) => {
217
+ * return {
218
+ * name: 'my-adapter',
219
+ * options,
220
+ * async parse(source) {
221
+ * // Transform source format to InputNode
222
+ * return { ... }
223
+ * },
224
+ * }
225
+ * })
226
+ *
227
+ * // Instantiate:
228
+ * const adapter = myAdapter({ validate: true })
229
+ * ```
230
+ */
231
+ declare function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T>;
232
+ //#endregion
116
233
  //#region src/createRenderer.d.ts
117
234
  /**
118
235
  * Minimal interface any Kubb renderer must satisfy.
119
236
  *
120
- * The generic `TElement` is the type of the element the renderer accepts
121
- * e.g. `KubbReactElement` for `@kubb/renderer-jsx`, or a custom type for
122
- * your own renderer. Defaults to `unknown` so that generators which do not
123
- * care about the element type continue to work without specifying it.
124
- *
125
- * This allows core to drive rendering without a hard dependency on
126
- * `@kubb/renderer-jsx` or any specific renderer implementation.
237
+ * `TElement` is the type the renderer accepts, for example `KubbReactElement`
238
+ * for `@kubb/renderer-jsx` or a custom type for your own renderer. Defaults to
239
+ * `unknown` so generators that don't care about the element type work without
240
+ * specifying it.
127
241
  */
128
242
  type Renderer<TElement = unknown> = {
243
+ /**
244
+ * Renders `element` and populates {@link files} with the resulting {@link FileNode} objects.
245
+ * Called once per render cycle; must resolve before {@link files} is read.
246
+ */
129
247
  render(element: TElement): Promise<void>;
248
+ /**
249
+ * Tears down the renderer and releases any held resources.
250
+ * Pass an `Error` to signal a failure, a number for an exit code, or omit for a clean shutdown.
251
+ */
130
252
  unmount(error?: Error | number | null): void;
253
+ /**
254
+ * Accumulated {@link FileNode} results produced by the last {@link render} call.
255
+ * Not populated when {@link stream} is implemented.
256
+ */
131
257
  readonly files: Array<FileNode>;
258
+ /**
259
+ * When present, core calls this instead of {@link render} and {@link files},
260
+ * forwarding each file to `FileManager` as soon as it is ready.
261
+ */
262
+ stream?(element: TElement): Iterable<FileNode>;
132
263
  };
133
264
  /**
134
- * A factory function that produces a fresh {@link Renderer} per render.
265
+ * A factory function that produces a fresh {@link Renderer} per render cycle.
135
266
  *
136
267
  * Generators use this to declare which renderer handles their output.
137
268
  */
138
269
  type RendererFactory<TElement = unknown> = () => Renderer<TElement>;
139
270
  /**
140
- * Creates a renderer factory for use in generator definitions.
141
- *
142
- * Wrap your renderer factory function with this helper to register it as the
143
- * renderer for a generator. Core will call this factory once per render cycle
144
- * to obtain a fresh renderer instance.
271
+ * Wraps a renderer factory for use in generator definitions.
145
272
  *
146
273
  * @example
147
274
  * ```ts
148
- * // packages/renderer-jsx/src/index.ts
149
275
  * export const jsxRenderer = createRenderer(() => {
150
276
  * const runtime = new Runtime()
151
277
  * return {
@@ -154,14 +280,6 @@ type RendererFactory<TElement = unknown> = () => Renderer<TElement>;
154
280
  * unmount(error) { runtime.unmount(error) },
155
281
  * }
156
282
  * })
157
- *
158
- * // packages/plugin-zod/src/generators/zodGenerator.tsx
159
- * import { jsxRenderer } from '@kubb/renderer-jsx'
160
- * export const zodGenerator = defineGenerator<PluginZod>({
161
- * name: 'zod',
162
- * renderer: jsxRenderer,
163
- * schema(node, options) { return <File ...>...</File> },
164
- * })
165
283
  * ```
166
284
  */
167
285
  declare function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement>;
@@ -235,698 +353,1043 @@ type Storage = {
235
353
  */
236
354
  declare function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage;
237
355
  //#endregion
238
- //#region src/defineGenerator.d.ts
356
+ //#region src/devtools.d.ts
357
+ type DevtoolsOptions = {
358
+ /**
359
+ * Open the AST inspector in Kubb Studio (`/ast`). Defaults to the main Studio page.
360
+ * @default false
361
+ */
362
+ ast?: boolean;
363
+ };
364
+ //#endregion
365
+ //#region src/defineParser.d.ts
366
+ type PrintOptions = {
367
+ extname?: FileNode['extname'];
368
+ };
369
+ type Parser<TMeta extends object = any> = {
370
+ name: string;
371
+ /**
372
+ * File extensions this parser handles.
373
+ * Use `undefined` to create a catch-all fallback parser.
374
+ *
375
+ * @example Handled extensions
376
+ * `['.ts', '.js']`
377
+ */
378
+ extNames: Array<FileNode['extname']> | undefined;
379
+ /**
380
+ * Convert a resolved file to a string.
381
+ */
382
+ parse(file: FileNode<TMeta>, options?: PrintOptions): string;
383
+ };
239
384
  /**
240
- * Declares a named generator unit that walks the AST and emits files.
241
- *
242
- * Each method (`schema`, `operation`, `operations`) is called for the matching node type.
243
- * Each method returns `TElement | Array<FileNode> | void`. JSX-based generators require a `renderer` factory.
244
- * Return `Array<FileNode>` directly or call `ctx.upsertFile()` manually and return `void` to bypass rendering.
385
+ * Defines a parser with type safety. Creates parsers that transform generated files to strings based on their extension.
245
386
  *
246
- * @note Generators are consumed by plugins and registered via `ctx.addGenerator()` in `kubb:plugin:setup`.
387
+ * @note Call the returned factory with optional options to instantiate the parser.
247
388
  *
248
389
  * @example
249
390
  * ```ts
250
- * import { defineGenerator } from '@kubb/core'
251
- * import { jsxRenderer } from '@kubb/renderer-jsx'
391
+ * import { defineParser } from '@kubb/core'
252
392
  *
253
- * export const typeGenerator = defineGenerator({
254
- * name: 'typescript',
255
- * renderer: jsxRenderer,
256
- * schema(node, ctx) {
257
- * const { adapter, resolver, root, options } = ctx
258
- * return <File ...><Type node={node} resolver={resolver} /></File>
393
+ * export const jsonParser = defineParser({
394
+ * name: 'json',
395
+ * extNames: ['.json'],
396
+ * parse(file) {
397
+ * const { extractStringsFromNodes } = await import('@kubb/ast')
398
+ * return file.sources.map((s) => extractStringsFromNodes(s.nodes ?? [])).join('\n')
259
399
  * },
260
400
  * })
261
401
  * ```
262
402
  */
263
- type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {
403
+ declare function defineParser<TMeta extends object = any>(parser: Parser<TMeta>): Parser<TMeta>;
404
+ //#endregion
405
+ //#region src/FileProcessor.d.ts
406
+ type ParseOptions = {
407
+ parsers?: Map<FileNode['extname'], Parser>;
408
+ extension?: Record<FileNode['extname'], FileNode['extname'] | ''>;
409
+ };
410
+ type FileProcessorEvents = {
411
+ start: [files: Array<FileNode>];
412
+ update: [params: {
413
+ file: FileNode;
414
+ source?: string;
415
+ processed: number;
416
+ total: number;
417
+ percentage: number;
418
+ }];
419
+ end: [files: Array<FileNode>];
420
+ };
421
+ type ParsedFile = {
422
+ file: FileNode;
423
+ source: string;
424
+ processed: number;
425
+ total: number;
426
+ percentage: number;
427
+ };
428
+ /**
429
+ * Converts a single file to a string using the registered parsers.
430
+ * Falls back to joining source values when no matching parser is found.
431
+ *
432
+ * @internal
433
+ */
434
+ declare class FileProcessor {
435
+ readonly events: AsyncEventEmitter<FileProcessorEvents>;
436
+ parse(file: FileNode, {
437
+ parsers,
438
+ extension
439
+ }?: ParseOptions): string;
440
+ stream(files: ReadonlyArray<FileNode>, options?: ParseOptions): Generator<ParsedFile>;
441
+ run(files: Array<FileNode>, options?: ParseOptions): Promise<Array<FileNode>>;
442
+ }
443
+ //#endregion
444
+ //#region src/defineLogger.d.ts
445
+ type LoggerOptions = {
264
446
  /**
265
- * Used in diagnostic messages and debug output.
447
+ * Log level for output verbosity.
448
+ * @default 3
266
449
  */
450
+ logLevel: (typeof logLevel)[keyof typeof logLevel];
451
+ };
452
+ /**
453
+ * Shared context passed to plugins, parsers, and other internals.
454
+ */
455
+ type LoggerContext = AsyncEventEmitter<KubbHooks>;
456
+ type Logger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = {
267
457
  name: string;
268
- /**
269
- * Optional renderer factory that produces a {@link Renderer} for each render cycle.
270
- *
271
- * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this
272
- * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).
273
- *
274
- * Generators that only return `Array<FileNode>` or `void` do not need to set this.
275
- *
276
- * Set `renderer: null` to explicitly opt out of rendering even when the parent plugin
277
- * declares a `renderer` (overrides the plugin-level fallback).
278
- *
279
- * @example
280
- * ```ts
281
- * import { jsxRenderer } from '@kubb/renderer-jsx'
282
- * export const myGenerator = defineGenerator<PluginTs>({
283
- * renderer: jsxRenderer,
284
- * schema(node, ctx) { return <File ...>...</File> },
285
- * })
286
- * ```
287
- */
288
- renderer?: RendererFactory<TElement> | null;
289
- /**
290
- * Called for each schema node in the AST walk.
291
- * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
292
- * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
293
- */
294
- schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
295
- /**
296
- * Called for each operation node in the AST walk.
297
- * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
298
- * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
299
- */
300
- operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
301
- /**
302
- * Called once after all operations have been walked.
303
- * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,
304
- * plus `ctx.options` with the plugin-level options for the batch call.
305
- */
306
- operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
458
+ install: (context: LoggerContext, options?: TOptions) => TInstallReturn | Promise<TInstallReturn>;
307
459
  };
460
+ type UserLogger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = Logger<TOptions, TInstallReturn>;
308
461
  /**
309
- * Defines a generator. Returns the object as-is with correct `this` typings.
310
- * `applyHookResult` handles renderer elements and `File[]` uniformly using
311
- * the generator's declared `renderer` factory.
462
+ * Wraps a logger definition into a typed {@link Logger}.
463
+ *
464
+ * The optional second type parameter `TInstallReturn` allows loggers to return
465
+ * a value from `install` — for example, a sink factory that the caller can
466
+ * forward to hook execution.
467
+ *
468
+ * @example Basic logger
469
+ * ```ts
470
+ * export const myLogger = defineLogger({
471
+ * name: 'my-logger',
472
+ * install(context, options) {
473
+ * context.on('kubb:info', (message) => console.log('ℹ', message))
474
+ * context.on('kubb:error', (error) => console.error('✗', error.message))
475
+ * },
476
+ * })
477
+ * ```
478
+ *
479
+ * @example Logger that returns a hook sink factory
480
+ * ```ts
481
+ * export const myLogger = defineLogger<LoggerOptions, HookSinkFactory>({
482
+ * name: 'my-logger',
483
+ * install(context, options) {
484
+ * // … register event handlers …
485
+ * return (commandWithArgs) => ({ onStdout: console.log })
486
+ * },
487
+ * })
488
+ * ```
312
489
  */
313
- declare function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(generator: Generator<TOptions, TElement>): Generator<TOptions, TElement>;
490
+ declare function defineLogger<Options extends LoggerOptions = LoggerOptions, TInstallReturn = void>(logger: UserLogger<Options, TInstallReturn>): Logger<Options, TInstallReturn>;
314
491
  //#endregion
315
- //#region src/definePlugin.d.ts
492
+ //#region src/defineMiddleware.d.ts
316
493
  /**
317
- * A plugin object produced by `definePlugin`.
318
- * Instead of flat lifecycle methods, it groups all handlers under a `hooks:` property
319
- * (matching Astro's integration naming convention).
320
- *
321
- * @template TFactory - The plugin's `PluginFactoryOptions` type.
494
+ * A middleware instance produced by calling a factory created with `defineMiddleware`.
495
+ * It declares event handlers under a `hooks` object which are registered on the
496
+ * shared emitter after all plugin hooks, so middleware handlers for any event
497
+ * always fire last.
322
498
  */
323
- type Plugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
499
+ type Middleware = {
324
500
  /**
325
- * Unique name for the plugin, following the same naming convention as `createPlugin`.
501
+ * Unique identifier for this middleware.
326
502
  */
327
503
  name: string;
328
504
  /**
329
- * Plugins that must be registered before this plugin executes.
330
- * An error is thrown at startup when any listed dependency is missing.
505
+ * Lifecycle event handlers for this middleware.
506
+ * Any event from the global `KubbHooks` map can be subscribed to here.
507
+ * Handlers are registered after all plugin handlers, so they always fire last.
331
508
  */
332
- dependencies?: Array<string>;
333
- /**
334
- * Controls the execution order of this plugin relative to others.
335
- *
336
- * - `'pre'` — runs before all normal plugins.
337
- * - `'post'` — runs after all normal plugins.
338
- * - `undefined` (default) — runs in declaration order among normal plugins.
339
- *
340
- * Dependency constraints always take precedence over `enforce`.
341
- */
342
- enforce?: 'pre' | 'post';
343
- /**
344
- * The options passed by the user when calling the plugin factory.
345
- */
346
- options?: TFactory['options'];
347
- /**
348
- * Lifecycle event handlers for this plugin.
349
- * Any event from the global `KubbHooks` map can be subscribed to here.
350
- */
351
- hooks: { [K in Exclude<keyof KubbHooks, 'kubb:plugin:setup'>]?: (...args: KubbHooks[K]) => void | Promise<void> } & {
352
- 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
353
- };
509
+ hooks: { [K in keyof KubbHooks]?: (...args: KubbHooks[K]) => void | Promise<void> };
354
510
  };
355
511
  /**
356
- * Wraps a factory function and returns a typed `Plugin` with lifecycle handlers grouped under `hooks`.
512
+ * Creates a middleware factory using the hook-style `hooks` API.
357
513
  *
358
- * Handlers live in a single `hooks` object (inspired by Astro integrations).
359
- * All lifecycle events from `KubbHooks` are available for subscription.
514
+ * Middleware handlers fire after all plugin handlers for any given event, making them ideal for post-processing, logging, and auditing.
515
+ * Per-build state (such as accumulators) belongs inside the factory closure so each `createKubb` invocation gets its own isolated instance.
360
516
  *
361
- * @note For real plugins, use a `PluginFactoryOptions` type parameter to get type-safe context in `kubb:plugin:setup`.
362
- * Plugin names should follow the convention `plugin-<feature>` (e.g., `plugin-react-query`, `plugin-zod`).
517
+ * @note The factory can accept typed options. See examples for using options and per-build state patterns.
363
518
  *
364
519
  * @example
365
520
  * ```ts
366
- * import { definePlugin } from '@kubb/core'
521
+ * import { defineMiddleware } from '@kubb/core'
367
522
  *
368
- * export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({
369
- * name: 'plugin-ts',
523
+ * // Stateless middleware
524
+ * export const logMiddleware = defineMiddleware(() => ({
525
+ * name: 'log-middleware',
370
526
  * hooks: {
371
- * 'kubb:plugin:setup'(ctx) {
372
- * ctx.setResolver(resolverTs)
527
+ * 'kubb:build:end'({ files }) {
528
+ * console.log(`Build complete with ${files.length} files`)
373
529
  * },
374
530
  * },
375
531
  * }))
532
+ *
533
+ * // Middleware with options and per-build state
534
+ * export const prefixMiddleware = defineMiddleware((options: { prefix: string } = { prefix: '' }) => {
535
+ * const seen = new Set<string>()
536
+ * return {
537
+ * name: 'prefix-middleware',
538
+ * hooks: {
539
+ * 'kubb:plugin:end'({ plugin }) {
540
+ * seen.add(`${options.prefix}${plugin.name}`)
541
+ * },
542
+ * },
543
+ * }
544
+ * })
376
545
  * ```
377
546
  */
378
- declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(factory: (options: TFactory['options']) => Plugin<TFactory>): (options?: TFactory['options']) => Plugin<TFactory>;
547
+ declare function defineMiddleware<TOptions extends object = object>(factory: (options: TOptions) => Middleware): (options?: TOptions) => Middleware;
379
548
  //#endregion
380
- //#region src/FileManager.d.ts
549
+ //#region src/defineResolver.d.ts
381
550
  /**
382
- * In-memory file store for generated files.
551
+ * Type/string pattern filter for include/exclude/override matching.
552
+ */
553
+ type PatternFilter = {
554
+ type: string;
555
+ pattern: string | RegExp;
556
+ };
557
+ /**
558
+ * Pattern filter with partial option overrides applied when the pattern matches.
559
+ */
560
+ type PatternOverride<TOptions> = PatternFilter & {
561
+ options: Omit<Partial<TOptions>, 'override'>;
562
+ };
563
+ /**
564
+ * Context for resolving filtered options for a given operation or schema node.
383
565
  *
384
- * Files with the same `path` are merged — sources, imports, and exports are concatenated.
385
- * The `files` getter returns all stored files sorted by path length (shortest first).
566
+ * @internal
567
+ */
568
+ type ResolveOptionsContext<TOptions> = {
569
+ options: TOptions;
570
+ exclude?: Array<PatternFilter>;
571
+ include?: Array<PatternFilter>;
572
+ override?: Array<PatternOverride<TOptions>>;
573
+ };
574
+ /**
575
+ * Base constraint for all plugin resolver objects.
576
+ *
577
+ * `default`, `resolveOptions`, `resolvePath`, `resolveFile`, `resolveBanner`, and `resolveFooter`
578
+ * are injected automatically by `defineResolver` — extend this type to add custom resolution methods.
386
579
  *
387
580
  * @example
388
581
  * ```ts
389
- * import { FileManager } from '@kubb/core'
582
+ * type MyResolver = Resolver & {
583
+ * resolveName(node: SchemaNode): string
584
+ * resolveTypedName(node: SchemaNode): string
585
+ * }
586
+ * ```
587
+ */
588
+ type Resolver = {
589
+ name: string;
590
+ pluginName: string;
591
+ default(name: string, type?: 'file' | 'function' | 'type' | 'const'): string;
592
+ resolveOptions<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null;
593
+ resolvePath(params: ResolverPathParams, context: ResolverContext): string;
594
+ resolveFile(params: ResolverFileParams, context: ResolverContext): FileNode;
595
+ resolveBanner(meta: InputMeta | undefined, context: ResolveBannerContext): string | undefined;
596
+ resolveFooter(meta: InputMeta | undefined, context: ResolveBannerContext): string | undefined;
597
+ };
598
+ /**
599
+ * File-specific parameters for `Resolver.resolvePath`.
390
600
  *
391
- * const manager = new FileManager()
392
- * manager.upsert(myFile)
393
- * console.log(manager.files) // all stored files
601
+ * Pass alongside a `ResolverContext` to identify which file to resolve.
602
+ * Provide `tag` for tag-based grouping or `path` for path-based grouping.
603
+ *
604
+ * @example
605
+ * ```ts
606
+ * resolver.resolvePath(
607
+ * { baseName: 'petTypes.ts', tag: 'pets' },
608
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
609
+ * )
610
+ * // → '/src/types/petsController/petTypes.ts'
394
611
  * ```
395
612
  */
396
- declare class FileManager {
397
- #private;
613
+ type ResolverPathParams = {
614
+ baseName: FileNode['baseName'];
615
+ pathMode?: 'single' | 'split';
398
616
  /**
399
- * Adds one or more files. Incoming files with the same path are merged
400
- * (sources/imports/exports concatenated), but existing cache entries are
401
- * replaced — use {@link upsert} when you want to merge into the cache too.
617
+ * Tag value used when `group.type === 'tag'`.
402
618
  */
403
- add(...files: Array<FileNode>): Array<FileNode>;
619
+ tag?: string;
404
620
  /**
405
- * Adds or merges one or more files.
406
- * If a file with the same path already exists in the cache, its
407
- * sources/imports/exports are merged into the incoming file.
621
+ * Path value used when `group.type === 'path'`.
408
622
  */
409
- upsert(...files: Array<FileNode>): Array<FileNode>;
410
- getByPath(path: string): FileNode | null;
411
- deleteByPath(path: string): void;
412
- clear(): void;
623
+ path?: string;
624
+ };
625
+ /**
626
+ * Shared context passed as the second argument to `Resolver.resolvePath` and `Resolver.resolveFile`.
627
+ *
628
+ * Describes where on disk output is rooted, which output config is active, and the optional
629
+ * grouping strategy that controls subdirectory layout.
630
+ *
631
+ * @example
632
+ * ```ts
633
+ * const context: ResolverContext = {
634
+ * root: config.root,
635
+ * output,
636
+ * group,
637
+ * }
638
+ * ```
639
+ */
640
+ type ResolverContext = {
641
+ root: string;
642
+ output: Output;
643
+ group?: Group;
413
644
  /**
414
- * All stored files, sorted by path length (shorter paths first).
645
+ * Plugin name used to populate `meta.pluginName` on the resolved file.
415
646
  */
416
- get files(): Array<FileNode>;
417
- }
418
- //#endregion
419
- //#region src/PluginDriver.d.ts
420
- type Options = {
421
- hooks: AsyncEventEmitter<KubbHooks>;
647
+ pluginName?: string;
422
648
  };
423
- declare class PluginDriver {
424
- #private;
425
- readonly config: Config;
426
- readonly options: Options;
649
+ /**
650
+ * File-specific parameters for `Resolver.resolveFile`.
651
+ *
652
+ * Pass alongside a `ResolverContext` to fully describe the file to resolve.
653
+ * `tag` and `path` are used only when a matching `group` is present in the context.
654
+ *
655
+ * @example
656
+ * ```ts
657
+ * resolver.resolveFile(
658
+ * { name: 'listPets', extname: '.ts', tag: 'pets' },
659
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
660
+ * )
661
+ * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }
662
+ * ```
663
+ */
664
+ type ResolverFileParams = {
665
+ name: string;
666
+ extname: FileNode['extname'];
427
667
  /**
428
- * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
429
- *
430
- * @example
431
- * ```ts
432
- * PluginDriver.getMode('src/gen/types.ts') // 'single'
433
- * PluginDriver.getMode('src/gen/types') // 'split'
434
- * ```
668
+ * Tag value used when `group.type === 'tag'`.
435
669
  */
436
- static getMode(fileOrFolder: string | undefined | null): 'single' | 'split';
670
+ tag?: string;
437
671
  /**
438
- * The universal `@kubb/ast` `InputNode` produced by the adapter, set by
439
- * the build pipeline after the adapter's `parse()` resolves.
672
+ * Path value used when `group.type === 'path'`.
440
673
  */
441
- inputNode: InputNode | undefined;
442
- adapter: Adapter | undefined;
674
+ path?: string;
675
+ };
676
+ /**
677
+ * Context passed to `Resolver.resolveBanner` and `Resolver.resolveFooter`.
678
+ *
679
+ * `output` is optional — not every plugin configures a banner/footer.
680
+ * `config` carries the global Kubb config, used to derive the default Kubb banner.
681
+ *
682
+ * @example
683
+ * ```ts
684
+ * resolver.resolveBanner(meta, { output: { banner: '// generated' }, config })
685
+ * // → '// generated'
686
+ * ```
687
+ */
688
+ type ResolveBannerContext = {
689
+ output?: Pick<Output, 'banner' | 'footer'>;
690
+ config: Config;
691
+ };
692
+ /**
693
+ * Builder type for the plugin-specific resolver fields.
694
+ *
695
+ * `default`, `resolveOptions`, `resolvePath`, `resolveFile`, `resolveBanner`, and `resolveFooter`
696
+ * are optional — built-in fallbacks are injected when omitted.
697
+ *
698
+ * Methods in the returned object can call sibling resolver methods via `this`.
699
+ */
700
+ 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'>> & {
701
+ name: string;
702
+ pluginName: T['name'];
703
+ } & ThisType<T['resolver']>;
704
+ /**
705
+ * Defines a resolver for a plugin, injecting built-in defaults for name casing,
706
+ * include/exclude/override filtering, path resolution, and file construction.
707
+ *
708
+ * All four defaults can be overridden by providing them in the builder function:
709
+ * - `default` — name casing strategy (camelCase / PascalCase)
710
+ * - `resolveOptions` — include/exclude/override filtering
711
+ * - `resolvePath` — output path computation
712
+ * - `resolveFile` — full `FileNode` construction
713
+ *
714
+ * Methods in the returned object can call sibling resolver methods via `this`.
715
+ *
716
+ * @example Basic resolver with naming helpers
717
+ * ```ts
718
+ * export const resolver = defineResolver<PluginTs>(() => ({
719
+ * name: 'default',
720
+ * resolveName(node) {
721
+ * return this.default(node.name, 'function')
722
+ * },
723
+ * resolveTypedName(node) {
724
+ * return this.default(node.name, 'type')
725
+ * },
726
+ * }))
727
+ * ```
728
+ *
729
+ * @example Override resolvePath for a custom output structure
730
+ * ```ts
731
+ * export const resolver = defineResolver<PluginTs>(() => ({
732
+ * name: 'custom',
733
+ * resolvePath({ baseName }, { root, output }) {
734
+ * return path.resolve(root, output.path, 'generated', baseName)
735
+ * },
736
+ * }))
737
+ * ```
738
+ *
739
+ * @example Use this.default inside a helper
740
+ * ```ts
741
+ * export const resolver = defineResolver<PluginTs>(() => ({
742
+ * name: 'default',
743
+ * resolveParamName(node, param) {
744
+ * return this.default(`${node.operationId} ${param.in} ${param.name}`, 'type')
745
+ * },
746
+ * }))
747
+ * ```
748
+ */
749
+ declare function defineResolver<T extends PluginFactoryOptions>(build: ResolverBuilder<T>): T['resolver'];
750
+ //#endregion
751
+ //#region src/definePlugin.d.ts
752
+ /**
753
+ * Safely extracts a type from a registry, returning `{}` if the key doesn't exist.
754
+ * Enables optional interface augmentation for `Kubb.ConfigOptionsRegistry` and `Kubb.PluginOptionsRegistry`
755
+ * without requiring changes to core.
756
+ *
757
+ * @internal
758
+ */
759
+ type ExtractRegistryKey$1<T, K extends PropertyKey> = K extends keyof T ? T[K] : {};
760
+ /**
761
+ * Output configuration for generated files.
762
+ */
763
+ type Output<_TOptions = unknown> = {
443
764
  /**
444
- * Central file store for all generated files.
445
- * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
446
- * add files; this property gives direct read/write access when needed.
765
+ * Output folder or file path for generated code.
447
766
  */
448
- readonly fileManager: FileManager;
449
- readonly plugins: Map<string, NormalizedPlugin>;
450
- constructor(config: Config, options: Options);
451
- get hooks(): AsyncEventEmitter<KubbHooks>;
767
+ path: string;
452
768
  /**
453
- * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
454
- *
455
- * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
456
- * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
457
- * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
458
- *
459
- * All other hooks are iterated and registered directly as pass-through listeners.
460
- * Any event key present in the global `KubbHooks` interface can be subscribed to.
461
- *
462
- * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
463
- * the plugin lifecycle without modifying plugin behavior.
464
- *
465
- * @internal
769
+ * Text or function prepended to every generated file.
770
+ * When a function, receives the document metadata and returns a string.
466
771
  */
467
- registerPluginHooks(hookPlugin: Plugin, normalizedPlugin: NormalizedPlugin): void;
772
+ banner?: string | ((meta?: InputMeta) => string);
468
773
  /**
469
- * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
470
- * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
471
- *
472
- * Call this once from `safeBuild` before the plugin execution loop begins.
774
+ * Text or function appended to every generated file.
775
+ * When a function, receives the document metadata and returns a string.
473
776
  */
474
- emitSetupHooks(): Promise<void>;
777
+ footer?: string | ((meta?: InputMeta) => string);
475
778
  /**
476
- * Registers a generator for the given plugin on the shared event emitter.
477
- *
478
- * The generator's `schema`, `operation`, and `operations` methods are registered as
479
- * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
480
- * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
481
- * so that generators from different plugins do not cross-fire.
482
- *
483
- * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
484
- * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
485
- * declares a renderer.
486
- *
487
- * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
779
+ * Whether to override existing external files if they already exist.
780
+ * @default false
488
781
  */
489
- registerGenerator(pluginName: string, gen: Generator): void;
782
+ override?: boolean;
783
+ } & ExtractRegistryKey$1<Kubb.PluginOptionsRegistry, 'output'>;
784
+ type Group = {
490
785
  /**
491
- * Returns `true` when at least one generator was registered for the given plugin
492
- * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
493
- *
494
- * Used by the build loop to decide whether to walk the AST and emit generator events
495
- * for a plugin that has no static `plugin.generators`.
786
+ * How to group files into subdirectories.
787
+ * - `'tag'` group by OpenAPI tags
788
+ * - `'path'` — group by OpenAPI paths
496
789
  */
497
- hasRegisteredGenerators(pluginName: string): boolean;
790
+ type: 'tag' | 'path';
498
791
  /**
499
- * Unregisters all plugin lifecycle listeners from the shared event emitter.
500
- * Called at the end of a build to prevent listener leaks across repeated builds.
501
- *
502
- * @internal
792
+ * Function that returns the subdirectory name for a group value.
793
+ * Defaults to `${camelCase(group)}Controller` for tags, first path segment for paths.
503
794
  */
504
- dispose(): void;
795
+ name?: (context: {
796
+ group: string;
797
+ }) => string;
798
+ };
799
+ type ByTag = {
505
800
  /**
506
- * Merges `partial` with the plugin's default resolver and stores the result.
507
- * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
508
- * get the up-to-date resolver without going through `getResolver()`.
801
+ * Filter by OpenAPI `tags` field. Matches one or more tags assigned to operations.
509
802
  */
510
- setPluginResolver(pluginName: string, partial: Partial<Resolver>): void;
803
+ type: 'tag';
511
804
  /**
512
- * Returns the resolver for the given plugin.
513
- *
514
- * Resolution order: dynamic resolver set via `setPluginResolver` → static resolver on the
515
- * plugin → lazily created default resolver (identity name, no path transforms).
805
+ * Tag name to match (case-sensitive). Can be a literal string or regex pattern.
516
806
  */
517
- getResolver<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Kubb.PluginRegistry[TName]['resolver'];
518
- getResolver<TResolver extends Resolver = Resolver>(pluginName: string): TResolver;
519
- getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): GeneratorContext<TOptions> & Record<string, unknown>;
520
- getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
521
- getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined;
807
+ pattern: string | RegExp;
808
+ };
809
+ type ByOperationId = {
522
810
  /**
523
- * Like `getPlugin` but throws a descriptive error when the plugin is not found.
811
+ * Filter by OpenAPI `operationId` field. Each operation (GET, POST, etc.) has a unique identifier.
524
812
  */
525
- requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]>;
526
- requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>;
527
- }
528
- //#endregion
529
- //#region src/createKubb.d.ts
530
- /**
531
- * Full output produced by a successful or failed build.
532
- */
533
- type BuildOutput = {
813
+ type: 'operationId';
534
814
  /**
535
- * Plugins that threw during installation, paired with the caught error.
815
+ * Operation ID to match (case-sensitive). Can be a literal string or regex pattern.
536
816
  */
537
- failedPlugins: Set<{
538
- plugin: Plugin;
539
- error: Error;
540
- }>;
541
- files: Array<FileNode>;
542
- driver: PluginDriver;
817
+ pattern: string | RegExp;
818
+ };
819
+ type ByPath = {
543
820
  /**
544
- * Elapsed time in milliseconds for each plugin, keyed by plugin name.
821
+ * Filter by OpenAPI `path` (URL endpoint). Useful to group or filter by service segments like `/pets`, `/users`, etc.
545
822
  */
546
- pluginTimings: Map<string, number>;
547
- error?: Error;
823
+ type: 'path';
548
824
  /**
549
- * Raw generated source, keyed by absolute file path.
825
+ * URL path to match (case-sensitive). Can be a literal string or regex pattern. Matches against the full path.
550
826
  */
551
- sources: Map<string, string>;
552
- };
553
- type CreateKubbOptions = {
554
- hooks?: AsyncEventEmitter<KubbHooks>;
827
+ pattern: string | RegExp;
555
828
  };
556
- /**
557
- * Creates a Kubb instance bound to a single config entry.
558
- *
559
- * Accepts a user-facing config shape and resolves it to a full {@link Config} during
560
- * `setup()`. The instance then holds shared state (`hooks`, `sources`, `driver`, `config`)
561
- * across the `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before
562
- * calling `setup()` or `build()`.
563
- *
564
- * @example
565
- * ```ts
566
- * const kubb = createKubb(userConfig)
567
- *
568
- * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {
569
- * console.log(`${plugin.name} completed in ${duration}ms`)
570
- * })
571
- *
572
- * const { files, failedPlugins } = await kubb.safeBuild()
573
- * ```
574
- */
575
- declare function createKubb(userConfig: UserConfig, options?: CreateKubbOptions): Kubb$1;
576
- //#endregion
577
- //#region src/Kubb.d.ts
578
- /**
579
- * Kubb code generation instance returned by {@link createKubb}.
580
- *
581
- * Use this when orchestrating multiple builds, inspecting plugin timings, or integrating Kubb into a larger toolchain.
582
- * For a single one-off build, chain directly: `await createKubb(config).build()`.
583
- */
584
- type Kubb$1 = {
585
- /**
586
- * Shared event emitter for lifecycle and status events. Attach listeners before calling `setup()` or `build()`.
587
- */
588
- readonly hooks: AsyncEventEmitter<KubbHooks>;
829
+ type ByMethod = {
589
830
  /**
590
- * Generated source code keyed by absolute file path. Available after `build()` or `safeBuild()` completes.
831
+ * Filter by HTTP method: `'get'`, `'post'`, `'put'`, `'delete'`, `'patch'`, `'head'`, `'options'`.
591
832
  */
592
- readonly sources: Map<string, string>;
833
+ type: 'method';
593
834
  /**
594
- * Plugin driver managing all plugins. Available after `setup()` completes.
835
+ * HTTP method to match (case-insensitive when using string, or regex for dynamic matching).
595
836
  */
596
- readonly driver: PluginDriver | undefined;
837
+ pattern: HttpMethod | RegExp;
838
+ };
839
+ type BySchemaName = {
597
840
  /**
598
- * Resolved configuration with defaults applied. Available after `setup()` completes.
841
+ * Filter by schema component name (TypeScript or JSON schema). Matches schemas in `#/components/schemas`.
599
842
  */
600
- readonly config: Config | undefined;
843
+ type: 'schemaName';
601
844
  /**
602
- * Resolves config and initializes the driver. `build()` calls this automatically.
845
+ * Schema name to match (case-sensitive). Can be a literal string or regex pattern.
603
846
  */
604
- setup(): Promise<void>;
847
+ pattern: string | RegExp;
848
+ };
849
+ type ByContentType = {
605
850
  /**
606
- * Runs the full pipeline and throws on any plugin error. Automatically calls `setup()` if needed.
851
+ * Filter by response or request content type: `'application/json'`, `'application/xml'`, etc.
607
852
  */
608
- build(): Promise<BuildOutput>;
853
+ type: 'contentType';
609
854
  /**
610
- * Runs the full pipeline and captures errors in `BuildOutput` instead of throwing. Automatically calls `setup()` if needed.
855
+ * Content type to match (case-sensitive). Can be a literal string or regex pattern.
611
856
  */
612
- safeBuild(): Promise<BuildOutput>;
857
+ pattern: string | RegExp;
613
858
  };
614
859
  /**
615
- * Lifecycle events emitted during Kubb code generation.
616
- * Use these for logging, progress tracking, and custom integrations.
860
+ * A pattern filter that prevents matching nodes from being generated.
861
+ *
862
+ * Use to skip code generation for specific operations or schemas. For example, exclude deprecated endpoints
863
+ * or internal-only schemas. Can filter by tag, operationId, path, HTTP method, content type, or schema name.
617
864
  *
618
865
  * @example
619
- * ```typescript
620
- * import type { AsyncEventEmitter } from '@internals/utils'
621
- * import type { KubbHooks } from '@kubb/core'
866
+ * ```ts
867
+ * exclude: [
868
+ * { type: 'tag', pattern: 'internal' }, // skip "internal" tag
869
+ * { type: 'path', pattern: /^\/admin/ }, // skip all /admin endpoints
870
+ * { type: 'operationId', pattern: 'deprecated_*' } // skip operationIds matching pattern
871
+ * ]
872
+ * ```
873
+ */
874
+ type Exclude = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
875
+ /**
876
+ * A pattern filter that restricts generation to only matching nodes.
622
877
  *
623
- * const hooks: AsyncEventEmitter<KubbHooks> = new AsyncEventEmitter()
878
+ * Use to generate code for a subset of operations or schemas. For example, only generate for a specific service
879
+ * tag or only for "production" endpoints. Can filter by tag, operationId, path, HTTP method, content type, or schema name.
624
880
  *
625
- * hooks.on('kubb:lifecycle:start', () => {
626
- * console.log('Starting Kubb generation')
627
- * })
881
+ * @example
882
+ * ```ts
883
+ * include: [
884
+ * { type: 'tag', pattern: 'public' }, // generate only "public" tag
885
+ * { type: 'path', pattern: /^\/api\/v1/ }, // generate only v1 endpoints
886
+ * ]
887
+ * ```
888
+ */
889
+ type Include = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
890
+ /**
891
+ * A pattern filter paired with partial option overrides applied when the pattern matches.
628
892
  *
629
- * hooks.on('kubb:plugin:end', ({ plugin, duration }) => {
630
- * console.log(`Plugin ${plugin.name} completed in ${duration}ms`)
631
- * })
893
+ * Use to customize generation for specific operations or schemas. For example, apply different output paths
894
+ * for different tags, or use custom resolver functions per operation. Can filter by tag, operationId, path,
895
+ * HTTP method, schema name, or content type.
896
+ *
897
+ * @example
898
+ * ```ts
899
+ * override: [
900
+ * {
901
+ * type: 'tag',
902
+ * pattern: 'admin',
903
+ * options: { output: { path: './src/gen/admin' } } // admin APIs go to separate folder
904
+ * },
905
+ * {
906
+ * type: 'operationId',
907
+ * pattern: 'listPets',
908
+ * options: { exclude: true } // skip this specific operation
909
+ * }
910
+ * ]
632
911
  * ```
633
912
  */
634
- interface KubbHooks {
913
+ type Override<TOptions> = (ByTag | ByOperationId | ByPath | ByMethod | BySchemaName | ByContentType) & {
914
+ options: Partial<TOptions>;
915
+ };
916
+ type PluginFactoryOptions<
917
+ /**
918
+ * Unique plugin name.
919
+ */
920
+ TName extends string = string,
921
+ /**
922
+ * User-facing plugin options.
923
+ */
924
+ TOptions extends object = object,
925
+ /**
926
+ * Plugin options after defaults are applied.
927
+ */
928
+ TResolvedOptions extends object = TOptions,
929
+ /**
930
+ * Resolver that encapsulates naming and path-resolution helpers.
931
+ * Define with `defineResolver` and export alongside the plugin.
932
+ */
933
+ TResolver extends Resolver = Resolver> = {
934
+ name: TName;
935
+ options: TOptions;
936
+ resolvedOptions: TResolvedOptions;
937
+ resolver: TResolver;
938
+ };
939
+ /**
940
+ * Context for hook-style plugin `kubb:plugin:setup` handler.
941
+ * Provides methods to register generators, configure resolvers, transformers, and renderers.
942
+ */
943
+ type KubbPluginSetupContext<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
635
944
  /**
636
- * Fires at the start of the Kubb lifecycle, before code generation begins.
945
+ * Register a generator dynamically. Generators fire during the AST walk (schema/operation/operations)
946
+ * just like generators declared statically on `createPlugin`.
637
947
  */
638
- 'kubb:lifecycle:start': [ctx: KubbLifecycleStartContext];
948
+ addGenerator<TElement = unknown>(generator: Generator$1<TFactory, TElement>): void;
639
949
  /**
640
- * Fires at the end of the Kubb lifecycle, after all code generation completes.
950
+ * Set or override the resolver for this plugin.
951
+ * The resolver controls file naming and path resolution.
641
952
  */
642
- 'kubb:lifecycle:end': [];
953
+ setResolver(resolver: Partial<TFactory['resolver']>): void;
643
954
  /**
644
- * Fires when configuration loading starts.
955
+ * Set the AST transformer to pre-process nodes before they reach generators.
645
956
  */
646
- 'kubb:config:start': [];
957
+ setTransformer(visitor: Visitor): void;
647
958
  /**
648
- * Fires when configuration loading completes.
959
+ * Set the renderer factory to process JSX elements from generators.
649
960
  */
650
- 'kubb:config:end': [ctx: KubbConfigEndContext];
961
+ setRenderer(renderer: RendererFactory): void;
651
962
  /**
652
- * Fires when code generation starts.
963
+ * Set resolved options merged into the normalized plugin's `options`.
964
+ * Call this in `kubb:plugin:setup` to provide options generators need.
653
965
  */
654
- 'kubb:generation:start': [ctx: KubbGenerationStartContext];
966
+ setOptions(options: TFactory['resolvedOptions']): void;
655
967
  /**
656
- * Fires when code generation completes.
968
+ * Inject a raw file into the build output, bypassing the generation pipeline.
657
969
  */
658
- 'kubb:generation:end': [ctx: KubbGenerationEndContext];
970
+ injectFile(userFileNode: UserFileNode): void;
659
971
  /**
660
- * Fires with a generation summary including summary lines, title, and success status.
972
+ * Merge a partial config update into the current build configuration.
661
973
  */
662
- 'kubb:generation:summary': [ctx: KubbGenerationSummaryContext];
974
+ updateConfig(config: Partial<Config>): void;
663
975
  /**
664
- * Fires when code formatting starts (e.g., Biome or Prettier).
976
+ * The resolved build configuration at setup time.
665
977
  */
666
- 'kubb:format:start': [];
978
+ config: Config;
667
979
  /**
668
- * Fires when code formatting completes.
980
+ * The plugin's user-provided options.
669
981
  */
670
- 'kubb:format:end': [];
982
+ options: TFactory['options'];
983
+ };
984
+ /**
985
+ * A plugin object produced by `definePlugin`.
986
+ * Instead of flat lifecycle methods, it groups all handlers under a `hooks:` property
987
+ * (matching Astro's integration naming convention).
988
+ *
989
+ * @template TFactory - The plugin's `PluginFactoryOptions` type.
990
+ */
991
+ type Plugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
671
992
  /**
672
- * Fires when linting starts.
993
+ * Unique name for the plugin, following the same naming convention as `createPlugin`.
673
994
  */
674
- 'kubb:lint:start': [];
995
+ name: string;
675
996
  /**
676
- * Fires when linting completes.
997
+ * Plugins that must be registered before this plugin executes.
998
+ * An error is thrown at startup when any listed dependency is missing.
677
999
  */
678
- 'kubb:lint:end': [];
1000
+ dependencies?: Array<string>;
679
1001
  /**
680
- * Fires when plugin hooks execution starts.
1002
+ * Controls the execution order of this plugin relative to others.
1003
+ *
1004
+ * - `'pre'` — runs before all normal plugins.
1005
+ * - `'post'` — runs after all normal plugins.
1006
+ * - `undefined` (default) — runs in declaration order among normal plugins.
1007
+ *
1008
+ * Dependency constraints always take precedence over `enforce`.
681
1009
  */
682
- 'kubb:hooks:start': [];
1010
+ enforce?: 'pre' | 'post';
683
1011
  /**
684
- * Fires when plugin hooks execution completes.
1012
+ * The options passed by the user when calling the plugin factory.
685
1013
  */
686
- 'kubb:hooks:end': [];
1014
+ options?: TFactory['options'];
687
1015
  /**
688
- * Fires when a single hook executes (e.g., format or lint). The callback is invoked when the command finishes.
1016
+ * Lifecycle event handlers for this plugin.
1017
+ * Any event from the global `KubbHooks` map can be subscribed to here.
689
1018
  */
690
- 'kubb:hook:start': [ctx: KubbHookStartContext];
1019
+ hooks: { [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void> } & {
1020
+ 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>;
1021
+ };
1022
+ };
1023
+ /**
1024
+ * Normalized plugin after setup, with runtime fields populated.
1025
+ * For internal use only — plugins use the public `Plugin` type externally.
1026
+ *
1027
+ * @internal
1028
+ */
1029
+ type NormalizedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & {
1030
+ options: TOptions['resolvedOptions'] & {
1031
+ output: Output;
1032
+ include?: Array<Include>;
1033
+ exclude: Array<Exclude>;
1034
+ override: Array<Override<TOptions['resolvedOptions']>>;
1035
+ };
1036
+ resolver: TOptions['resolver'];
1037
+ transformer?: Visitor;
1038
+ renderer?: RendererFactory;
1039
+ generators?: Array<Generator$1>;
1040
+ apply?: (config: Config) => boolean;
1041
+ version?: string;
1042
+ };
1043
+ type KubbPluginStartContext = {
1044
+ plugin: NormalizedPlugin;
1045
+ };
1046
+ type KubbPluginEndContext = {
1047
+ plugin: NormalizedPlugin;
1048
+ duration: number;
1049
+ success: boolean;
1050
+ error?: Error;
1051
+ config: Config;
691
1052
  /**
692
- * Fires when a single hook execution completes.
1053
+ * Returns all files currently in the file manager (lazy snapshot).
1054
+ * Includes files added by plugins that have already run.
693
1055
  */
694
- 'kubb:hook:end': [ctx: KubbHookEndContext];
1056
+ readonly files: ReadonlyArray<FileNode>;
695
1057
  /**
696
- * Fires when a new Kubb version is available.
1058
+ * Upsert one or more files into the file manager.
697
1059
  */
698
- 'kubb:version:new': [ctx: KubbVersionNewContext];
1060
+ upsertFile: (...files: Array<FileNode>) => void;
1061
+ };
1062
+ /**
1063
+ * Wraps a factory function and returns a typed `Plugin` with lifecycle handlers grouped under `hooks`.
1064
+ *
1065
+ * Handlers live in a single `hooks` object (inspired by Astro integrations).
1066
+ * All lifecycle events from `KubbHooks` are available for subscription.
1067
+ *
1068
+ * @note For real plugins, use a `PluginFactoryOptions` type parameter to get type-safe context in `kubb:plugin:setup`.
1069
+ * Plugin names should follow the convention `plugin-<feature>` (e.g., `plugin-react-query`, `plugin-zod`).
1070
+ *
1071
+ * @example
1072
+ * ```ts
1073
+ * import { definePlugin } from '@kubb/core'
1074
+ *
1075
+ * export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({
1076
+ * name: 'plugin-ts',
1077
+ * hooks: {
1078
+ * 'kubb:plugin:setup'(ctx) {
1079
+ * ctx.setResolver(resolverTs)
1080
+ * },
1081
+ * },
1082
+ * }))
1083
+ * ```
1084
+ */
1085
+ declare function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(factory: (options: TFactory['options']) => Plugin<TFactory>): (options?: TFactory['options']) => Plugin<TFactory>;
1086
+ //#endregion
1087
+ //#region src/FileManager.d.ts
1088
+ /**
1089
+ * In-memory file store for generated files.
1090
+ *
1091
+ * Files with the same `path` are merged — sources, imports, and exports are concatenated.
1092
+ * The `files` getter returns all stored files sorted by path length (shortest first).
1093
+ *
1094
+ * @example
1095
+ * ```ts
1096
+ * import { FileManager } from '@kubb/core'
1097
+ *
1098
+ * const manager = new FileManager()
1099
+ * manager.upsert(myFile)
1100
+ * console.log(manager.files) // all stored files
1101
+ * ```
1102
+ */
1103
+ declare class FileManager {
1104
+ #private;
699
1105
  /**
700
- * Informational message event.
1106
+ * Adds one or more files. Incoming files with the same path are merged
1107
+ * (sources/imports/exports concatenated), but existing cache entries are
1108
+ * replaced — use {@link upsert} when you want to merge into the cache too.
701
1109
  */
702
- 'kubb:info': [ctx: KubbInfoContext];
1110
+ add(...files: Array<FileNode>): Array<FileNode>;
703
1111
  /**
704
- * Error event, fired when an error occurs during generation.
1112
+ * Adds or merges one or more files.
1113
+ * If a file with the same path already exists in the cache, its
1114
+ * sources/imports/exports are merged into the incoming file.
705
1115
  */
706
- 'kubb:error': [ctx: KubbErrorContext];
1116
+ upsert(...files: Array<FileNode>): Array<FileNode>;
1117
+ getByPath(path: string): FileNode | null;
1118
+ deleteByPath(path: string): void;
1119
+ clear(): void;
707
1120
  /**
708
- * Success message event.
1121
+ * Releases all stored files. Called by the core after `kubb:build:end` to
1122
+ * free the per-plugin FileNode caches for the rest of the process lifetime.
709
1123
  */
710
- 'kubb:success': [ctx: KubbSuccessContext];
1124
+ dispose(): void;
1125
+ [Symbol.dispose](): void;
711
1126
  /**
712
- * Warning message event.
1127
+ * All stored files, sorted by path length (shorter paths first).
713
1128
  */
714
- 'kubb:warn': [ctx: KubbWarnContext];
1129
+ get files(): Array<FileNode>;
1130
+ }
1131
+ //#endregion
1132
+ //#region src/KubbDriver.d.ts
1133
+ type Options = {
1134
+ hooks: AsyncEventEmitter<KubbHooks>;
1135
+ };
1136
+ declare class KubbDriver {
1137
+ #private;
1138
+ readonly config: Config;
1139
+ readonly options: Options;
715
1140
  /**
716
- * Debug event for detailed logging with timestamp and optional filename.
1141
+ * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
1142
+ *
1143
+ * @example
1144
+ * ```ts
1145
+ * KubbDriver.getMode('src/gen/types.ts') // 'single'
1146
+ * KubbDriver.getMode('src/gen/types') // 'split'
1147
+ * ```
717
1148
  */
718
- 'kubb:debug': [ctx: KubbDebugContext];
1149
+ static getMode(fileOrFolder: string | undefined | null): 'single' | 'split';
719
1150
  /**
720
- * Fires when file processing starts with the list of files to process.
1151
+ * The streaming `InputStreamNode` produced by the adapter.
1152
+ * Always set after adapter setup — parse-only adapters are wrapped automatically.
721
1153
  */
722
- 'kubb:files:processing:start': [ctx: KubbFilesProcessingStartContext];
1154
+ inputNode: InputStreamNode | undefined;
1155
+ adapter: Adapter | undefined;
723
1156
  /**
724
- * Fires for each file with progress updates: processed count, total, percentage, and file details.
1157
+ * Central file store for all generated files.
1158
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
1159
+ * add files; this property gives direct read/write access when needed.
725
1160
  */
726
- 'kubb:file:processing:update': [ctx: KubbFileProcessingUpdateContext];
1161
+ readonly fileManager: FileManager;
1162
+ readonly plugins: Map<string, NormalizedPlugin>;
1163
+ constructor(config: Config, options: Options);
1164
+ setup(): Promise<void>;
1165
+ get hooks(): AsyncEventEmitter<KubbHooks>;
727
1166
  /**
728
- * Fires when file processing completes with the list of processed files.
1167
+ * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
1168
+ * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
1169
+ *
1170
+ * Call this once from `safeBuild` before the plugin execution loop begins.
729
1171
  */
730
- 'kubb:files:processing:end': [ctx: KubbFilesProcessingEndContext];
1172
+ emitSetupHooks(): Promise<void>;
731
1173
  /**
732
- * Fires when a plugin starts execution.
1174
+ * Registers a generator for the given plugin on the shared event emitter.
1175
+ *
1176
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
1177
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
1178
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
1179
+ * so that generators from different plugins do not cross-fire.
1180
+ *
1181
+ * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
1182
+ * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
1183
+ * declares a renderer.
1184
+ *
1185
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
733
1186
  */
734
- 'kubb:plugin:start': [ctx: KubbPluginStartContext];
1187
+ registerGenerator(pluginName: string, gen: Generator$1): void;
735
1188
  /**
736
- * Fires when a plugin completes execution. Duration measured in milliseconds.
1189
+ * Returns `true` when at least one generator was registered for the given plugin
1190
+ * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
1191
+ *
1192
+ * Used by the build loop to decide whether to walk the AST and emit generator events
1193
+ * for a plugin that has no static `plugin.generators`.
737
1194
  */
738
- 'kubb:plugin:end': [ctx: KubbPluginEndContext];
1195
+ hasEventGenerators(pluginName: string): boolean;
739
1196
  /**
740
- * Fires once before plugins execute allowing plugins to register generators, configure resolvers/transformers/renderers, or inject files.
1197
+ * Unregisters all plugin lifecycle listeners from the shared event emitter.
1198
+ * Called at the end of a build to prevent listener leaks across repeated builds.
1199
+ *
1200
+ * @internal
741
1201
  */
742
- 'kubb:plugin:setup': [ctx: KubbPluginSetupContext];
1202
+ dispose(): void;
1203
+ [Symbol.dispose](): void;
743
1204
  /**
744
- * Fires before the plugin execution loop begins. The adapter has already parsed the source and `inputNode` is available.
1205
+ * Merges `partial` with the plugin's default resolver and stores the result.
1206
+ * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
1207
+ * get the up-to-date resolver without going through `getResolver()`.
745
1208
  */
746
- 'kubb:build:start': [ctx: KubbBuildStartContext];
1209
+ setPluginResolver(pluginName: string, partial: Partial<Resolver>): void;
747
1210
  /**
748
- * Fires after all plugins run and per-plugin barrels generate, but before files write to disk.
749
- * Use this to inject final files that must persist in the same write pass as plugin output.
1211
+ * Returns the resolver for the given plugin.
1212
+ *
1213
+ * Resolution order: dynamic resolver set via `setPluginResolver` → static resolver on the
1214
+ * plugin → lazily created default resolver (identity name, no path transforms).
750
1215
  */
751
- 'kubb:plugins:end': [ctx: KubbPluginsEndContext];
1216
+ getResolver<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Kubb.PluginRegistry[TName]['resolver'];
1217
+ getResolver<TResolver extends Resolver = Resolver>(pluginName: string): TResolver;
1218
+ getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): GeneratorContext<TOptions> & Record<string, unknown>;
1219
+ getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
1220
+ getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined;
752
1221
  /**
753
- * Fires after all files write to disk.
1222
+ * Like `getPlugin` but throws a descriptive error when the plugin is not found.
754
1223
  */
755
- 'kubb:build:end': [ctx: KubbBuildEndContext];
1224
+ requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]>;
1225
+ requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>;
1226
+ }
1227
+ //#endregion
1228
+ //#region src/defineGenerator.d.ts
1229
+ /**
1230
+ * Context object passed to generator `schema`, `operation`, and `operations` methods.
1231
+ *
1232
+ * The adapter is always defined (guaranteed by `runPluginAstHooks`) so no runtime checks
1233
+ * are needed. `ctx.options` carries resolved per-node options after exclude/include/override
1234
+ * filtering for individual schema/operation calls, or plugin-level options for operations.
1235
+ */
1236
+ type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1237
+ config: Config;
756
1238
  /**
757
- * Fires for each schema node during AST traversal. Generator listeners respond to this.
1239
+ * Absolute path to the current plugin's output directory.
758
1240
  */
759
- 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext];
1241
+ root: string;
760
1242
  /**
761
- * Fires for each operation node during AST traversal. Generator listeners respond to this.
1243
+ * Determine output mode based on the output config.
1244
+ * Returns `'single'` when `output.path` is a file, `'split'` for a directory.
762
1245
  */
763
- 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext];
1246
+ getMode: (output: {
1247
+ path: string;
1248
+ }) => 'single' | 'split';
1249
+ driver: KubbDriver;
764
1250
  /**
765
- * Fires once after all operations traverse with the full collected array. Batch generator listeners respond to this.
1251
+ * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
766
1252
  */
767
- 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext];
768
- }
769
- declare global {
770
- namespace Kubb {
771
- /**
772
- * Registry that maps plugin names to their `PluginFactoryOptions`.
773
- * Augment this interface in each plugin's `types.ts` to enable automatic
774
- * typing for `getPlugin` and `requirePlugin`.
775
- *
776
- * @example
777
- * ```ts
778
- * // packages/plugin-ts/src/types.ts
779
- * declare global {
780
- * namespace Kubb {
781
- * interface PluginRegistry {
782
- * 'plugin-ts': PluginTs
783
- * }
784
- * }
785
- * }
786
- * ```
787
- */
788
- interface PluginRegistry {}
789
- /**
790
- * Extension point for root `Config['output']` options.
791
- * Augment the `output` key in middleware or plugin packages to add extra fields
792
- * to the global output configuration without touching core types.
793
- *
794
- * @example
795
- * ```ts
796
- * // packages/middleware-barrel/src/types.ts
797
- * declare global {
798
- * namespace Kubb {
799
- * interface ConfigOptionsRegistry {
800
- * output: {
801
- * barrel?: import('./types.ts').BarrelConfig | false
802
- * }
803
- * }
804
- * }
805
- * }
806
- * ```
807
- */
808
- interface ConfigOptionsRegistry {}
809
- /**
810
- * Extension point for per-plugin `Output` options.
811
- * Augment the `output` key in middleware or plugin packages to add extra fields
812
- * to the per-plugin output configuration without touching core types.
813
- *
814
- * @example
815
- * ```ts
816
- * // packages/middleware-barrel/src/types.ts
817
- * declare global {
818
- * namespace Kubb {
819
- * interface PluginOptionsRegistry {
820
- * output: {
821
- * barrel?: import('./types.ts').PluginBarrelConfig | false
822
- * }
823
- * }
824
- * }
825
- * }
826
- * ```
827
- */
828
- interface PluginOptionsRegistry {}
829
- }
830
- }
831
- //#endregion
832
- //#region src/defineMiddleware.d.ts
833
- /**
834
- * A middleware instance produced by calling a factory created with `defineMiddleware`.
835
- * It declares event handlers under a `hooks` object which are registered on the
836
- * shared emitter after all plugin hooks, so middleware handlers for any event
837
- * always fire last.
838
- */
839
- type Middleware = {
1253
+ getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
1254
+ getPlugin(name: string): Plugin | undefined;
840
1255
  /**
841
- * Unique identifier for this middleware.
1256
+ * Get a plugin by name, throws an error if not found.
842
1257
  */
843
- name: string;
1258
+ requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>;
1259
+ requirePlugin(name: string): Plugin;
844
1260
  /**
845
- * Lifecycle event handlers for this middleware.
846
- * Any event from the global `KubbHooks` map can be subscribed to here.
847
- * Handlers are registered after all plugin handlers, so they always fire last.
1261
+ * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.
848
1262
  */
849
- hooks: { [K in keyof KubbHooks]?: (...args: KubbHooks[K]) => void | Promise<void> };
1263
+ getResolver<TName extends keyof Kubb.PluginRegistry>(name: TName): Kubb.PluginRegistry[TName]['resolver'];
1264
+ getResolver(name: string): Resolver;
1265
+ /**
1266
+ * Add files only if they don't exist.
1267
+ */
1268
+ addFile: (...file: Array<FileNode>) => Promise<void>;
1269
+ /**
1270
+ * Merge sources into the same output file.
1271
+ */
1272
+ upsertFile: (...file: Array<FileNode>) => Promise<void>;
1273
+ hooks: AsyncEventEmitter<KubbHooks>;
1274
+ /**
1275
+ * The current plugin instance.
1276
+ */
1277
+ plugin: Plugin<TOptions>;
1278
+ /**
1279
+ * The current plugin's resolver.
1280
+ */
1281
+ resolver: TOptions['resolver'];
1282
+ /**
1283
+ * The current plugin's transformer.
1284
+ */
1285
+ transformer: Visitor | undefined;
1286
+ /**
1287
+ * Emit a warning.
1288
+ */
1289
+ warn: (message: string) => void;
1290
+ /**
1291
+ * Emit an error.
1292
+ */
1293
+ error: (error: string | Error) => void;
1294
+ /**
1295
+ * Emit an info message.
1296
+ */
1297
+ info: (message: string) => void;
1298
+ /**
1299
+ * Open the current input node in Kubb Studio.
1300
+ */
1301
+ openInStudio: (options?: DevtoolsOptions) => Promise<void>;
1302
+ /**
1303
+ * The configured adapter instance.
1304
+ */
1305
+ adapter: Adapter;
1306
+ /**
1307
+ * Document metadata from the adapter — title, version, base URL, and pre-computed
1308
+ * schema index fields (`circularNames`, `enumNames`).
1309
+ */
1310
+ meta: InputMeta;
1311
+ /**
1312
+ * Resolved options after exclude/include/override filtering.
1313
+ */
1314
+ options: TOptions['resolvedOptions'];
850
1315
  };
851
1316
  /**
852
- * Creates a middleware factory using the hook-style `hooks` API.
1317
+ * Declares a named generator unit that walks the AST and emits files.
853
1318
  *
854
- * Middleware handlers fire after all plugin handlers for any given event, making them ideal for post-processing, logging, and auditing.
855
- * Per-build state (such as accumulators) belongs inside the factory closure so each `createKubb` invocation gets its own isolated instance.
1319
+ * Each method (`schema`, `operation`, `operations`) is called for the matching node type.
1320
+ * Each method returns `TElement | Array<FileNode> | void`. JSX-based generators require a `renderer` factory.
1321
+ * Return `Array<FileNode>` directly or call `ctx.upsertFile()` manually and return `void` to bypass rendering.
856
1322
  *
857
- * @note The factory can accept typed options. See examples for using options and per-build state patterns.
1323
+ * @note Generators are consumed by plugins and registered via `ctx.addGenerator()` in `kubb:plugin:setup`.
858
1324
  *
859
1325
  * @example
860
1326
  * ```ts
861
- * import { defineMiddleware } from '@kubb/core'
1327
+ * import { defineGenerator } from '@kubb/core'
1328
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
862
1329
  *
863
- * // Stateless middleware
864
- * export const logMiddleware = defineMiddleware(() => ({
865
- * name: 'log-middleware',
866
- * hooks: {
867
- * 'kubb:build:end'({ files }) {
868
- * console.log(`Build complete with ${files.length} files`)
869
- * },
1330
+ * export const typeGenerator = defineGenerator({
1331
+ * name: 'typescript',
1332
+ * renderer: jsxRenderer,
1333
+ * schema(node, ctx) {
1334
+ * const { adapter, resolver, root, options } = ctx
1335
+ * return <File ...><Type node={node} resolver={resolver} /></File>
870
1336
  * },
871
- * }))
872
- *
873
- * // Middleware with options and per-build state
874
- * export const prefixMiddleware = defineMiddleware((options: { prefix: string } = { prefix: '' }) => {
875
- * const seen = new Set<string>()
876
- * return {
877
- * name: 'prefix-middleware',
878
- * hooks: {
879
- * 'kubb:plugin:end'({ plugin }) {
880
- * seen.add(`${options.prefix}${plugin.name}`)
881
- * },
882
- * },
883
- * }
884
1337
  * })
885
1338
  * ```
886
1339
  */
887
- declare function defineMiddleware<TOptions extends object = object>(factory: (options: TOptions) => Middleware): (options?: TOptions) => Middleware;
888
- //#endregion
889
- //#region src/defineParser.d.ts
890
- type PrintOptions = {
891
- extname?: FileNode['extname'];
892
- };
893
- type Parser<TMeta extends object = any> = {
1340
+ type Generator$1<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {
1341
+ /**
1342
+ * Used in diagnostic messages and debug output.
1343
+ */
894
1344
  name: string;
895
1345
  /**
896
- * File extensions this parser handles.
897
- * Use `undefined` to create a catch-all fallback parser.
1346
+ * Optional renderer factory that produces a {@link Renderer} for each render cycle.
898
1347
  *
899
- * @example Handled extensions
900
- * `['.ts', '.js']`
1348
+ * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this
1349
+ * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).
1350
+ *
1351
+ * Generators that only return `Array<FileNode>` or `void` do not need to set this.
1352
+ *
1353
+ * Set `renderer: null` to explicitly opt out of rendering even when the parent plugin
1354
+ * declares a `renderer` (overrides the plugin-level fallback).
1355
+ *
1356
+ * @example
1357
+ * ```ts
1358
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1359
+ * export const myGenerator = defineGenerator<PluginTs>({
1360
+ * renderer: jsxRenderer,
1361
+ * schema(node, ctx) { return <File ...>...</File> },
1362
+ * })
1363
+ * ```
901
1364
  */
902
- extNames: Array<FileNode['extname']> | undefined;
1365
+ renderer?: RendererFactory<TElement> | null;
903
1366
  /**
904
- * Convert a resolved file to a string.
1367
+ * Called for each schema node in the AST walk.
1368
+ * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
1369
+ * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
1370
+ */
1371
+ schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
1372
+ /**
1373
+ * Called for each operation node in the AST walk.
1374
+ * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
1375
+ * plus `ctx.options` with the per-node resolved options (after exclude/include/override).
1376
+ */
1377
+ operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
1378
+ /**
1379
+ * Called once after all operations have been walked.
1380
+ * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),
1381
+ * plus `ctx.options` with the plugin-level options for the batch call.
905
1382
  */
906
- parse(file: FileNode<TMeta>, options?: PrintOptions): Promise<string> | string;
1383
+ operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>;
907
1384
  };
908
1385
  /**
909
- * Defines a parser with type safety. Creates parsers that transform generated files to strings based on their extension.
910
- *
911
- * @note Call the returned factory with optional options to instantiate the parser.
912
- *
913
- * @example
914
- * ```ts
915
- * import { defineParser } from '@kubb/core'
916
- *
917
- * export const jsonParser = defineParser({
918
- * name: 'json',
919
- * extNames: ['.json'],
920
- * parse(file) {
921
- * const { extractStringsFromNodes } = await import('@kubb/ast')
922
- * return file.sources.map((s) => extractStringsFromNodes(s.nodes ?? [])).join('\n')
923
- * },
924
- * })
925
- * ```
1386
+ * Defines a generator. Returns the object as-is with correct `this` typings.
1387
+ * `applyHookResult` handles renderer elements and `File[]` uniformly using
1388
+ * the generator's declared `renderer` factory.
926
1389
  */
927
- declare function defineParser<TMeta extends object = any>(parser: Parser<TMeta>): Parser<TMeta>;
1390
+ declare function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(generator: Generator$1<TOptions, TElement>): Generator$1<TOptions, TElement>;
928
1391
  //#endregion
929
- //#region src/types.d.ts
1392
+ //#region src/createKubb.d.ts
930
1393
  /**
931
1394
  * Safely extracts a type from a registry, returning `{}` if the key doesn't exist.
932
1395
  * Enables optional interface augmentation for `Kubb.ConfigOptionsRegistry` and `Kubb.PluginOptionsRegistry`
@@ -973,95 +1436,13 @@ type InputData = {
973
1436
  };
974
1437
  type Input = InputPath | InputData;
975
1438
  /**
976
- * Source data passed to an adapter's `parse` function.
977
- * Mirrors the config input shape with paths resolved to absolute.
978
- */
979
- type AdapterSource = {
980
- type: 'path';
981
- path: string;
982
- } | {
983
- type: 'data';
984
- data: string | unknown;
985
- } | {
986
- type: 'paths';
987
- paths: Array<string>;
988
- };
989
- /**
990
- * Generic type parameters for an adapter definition.
1439
+ * Build configuration for Kubb code generation.
991
1440
  *
992
- * - `TName` unique identifier (e.g. `'oas'`, `'asyncapi'`)
993
- * - `TOptions` user-facing options passed to the adapter factory
994
- * - `TResolvedOptions` options after defaults applied
995
- * - `TDocument` type of the parsed source document
996
- */
997
- type AdapterFactoryOptions<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TDocument = unknown> = {
998
- name: TName;
999
- options: TOptions;
1000
- resolvedOptions: TResolvedOptions;
1001
- document: TDocument;
1002
- };
1003
- /**
1004
- * Adapter that converts input files or data into an `InputNode`.
1005
- *
1006
- * Adapters parse different schema formats (OpenAPI, AsyncAPI, Drizzle, etc.) into Kubb's
1007
- * universal intermediate representation that all plugins consume.
1008
- *
1009
- * @example
1010
- * ```ts
1011
- * import { adapterOas } from '@kubb/adapter-oas'
1012
- *
1013
- * export default defineConfig({
1014
- * adapter: adapterOas(),
1015
- * input: { path: './openapi.yaml' },
1016
- * plugins: [pluginTs(), pluginZod()],
1017
- * })
1018
- * ```
1019
- */
1020
- type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
1021
- /**
1022
- * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).
1023
- */
1024
- name: TOptions['name'];
1025
- /**
1026
- * Resolved adapter options after defaults have been applied.
1027
- */
1028
- options: TOptions['resolvedOptions'];
1029
- /**
1030
- * Parsed source document after the first `parse()` call. `null` before parsing.
1031
- */
1032
- document: TOptions['document'] | null;
1033
- inputNode: InputNode | null;
1034
- /**
1035
- * Parse the source into a universal `InputNode`.
1036
- */
1037
- parse: (source: AdapterSource) => PossiblePromise<InputNode>;
1038
- /**
1039
- * Extract `ImportNode` entries for a schema tree.
1040
- * Returns an empty array before the first `parse()` call.
1041
- *
1042
- * The `resolve` callback receives the collision-corrected schema name and must
1043
- * return `{ name, path }` for the import, or `undefined` to skip it.
1044
- */
1045
- getImports: (node: SchemaNode, resolve: (schemaName: string) => {
1046
- name: string;
1047
- path: string;
1048
- }) => Array<ImportNode>;
1049
- };
1050
- type DevtoolsOptions = {
1051
- /**
1052
- * Open the AST inspector in Kubb Studio (`/ast`). Defaults to the main Studio page.
1053
- * @default false
1054
- */
1055
- ast?: boolean;
1056
- };
1057
- /**
1058
- * Build configuration for Kubb code generation.
1059
- *
1060
- * The Config is the main entry point for customizing how Kubb generates code. It specifies:
1061
- * - What to generate from (adapter + input)
1062
- * - Where to output generated code (output)
1063
- * - How to generate (plugins + middleware)
1064
- * - Runtime details (parsers, storage, renderer)
1441
+ * The Config is the main entry point for customizing how Kubb generates code. It specifies:
1442
+ * - What to generate from (adapter + input)
1443
+ * - Where to output generated code (output)
1444
+ * - How to generate (plugins + middleware)
1445
+ * - Runtime details (parsers, storage, renderer)
1065
1446
  *
1066
1447
  * See `UserConfig` for a relaxed version with sensible defaults.
1067
1448
  *
@@ -1100,9 +1481,13 @@ type Config<TInput = Input> = {
1100
1481
  */
1101
1482
  parsers: Array<Parser>;
1102
1483
  /**
1103
- * Adapter that parses input files into the universal `InputNode` representation.
1484
+ * Adapter that parses input files into the universal AST representation.
1104
1485
  * Use `@kubb/adapter-oas` for OpenAPI/Swagger or `@kubb/adapter-asyncapi` for other formats.
1105
1486
  *
1487
+ * When omitted, Kubb runs in plugin-only mode: `kubb:plugin:setup` fires and files
1488
+ * injected via `injectFile` are written, but no AST walk occurs and generator hooks
1489
+ * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.
1490
+ *
1106
1491
  * @example
1107
1492
  * ```ts
1108
1493
  * import { adapterOas } from '@kubb/adapter-oas'
@@ -1112,12 +1497,13 @@ type Config<TInput = Input> = {
1112
1497
  * })
1113
1498
  * ```
1114
1499
  */
1115
- adapter: Adapter;
1500
+ adapter?: Adapter;
1116
1501
  /**
1117
1502
  * Source file or data to generate code from.
1118
1503
  * Use `input.path` for a file path or `input.data` for inline data.
1504
+ * Required when an adapter is configured; omit when running in plugin-only mode.
1119
1505
  */
1120
- input: TInput;
1506
+ input?: TInput;
1121
1507
  output: {
1122
1508
  /**
1123
1509
  * Output directory for generated files, absolute or relative to `root`.
@@ -1146,13 +1532,6 @@ type Config<TInput = Input> = {
1146
1532
  * ```
1147
1533
  */
1148
1534
  clean?: boolean;
1149
- /**
1150
- * Persists generated files to the file system.
1151
- *
1152
- * @default true
1153
- * @deprecated Use `storage` option to control where files are written instead.
1154
- */
1155
- write?: boolean;
1156
1535
  /**
1157
1536
  * Auto-format generated files after code generation completes.
1158
1537
  *
@@ -1226,7 +1605,7 @@ type Config<TInput = Input> = {
1226
1605
  * ```
1227
1606
  */
1228
1607
  override?: boolean;
1229
- } & ExtractRegistryKey<Kubb.ConfigOptionsRegistry, 'output'>;
1608
+ } & ExtractRegistryKey<Kubb$1.ConfigOptionsRegistry, 'output'>;
1230
1609
  /**
1231
1610
  * Storage backend that controls where and how generated files are persisted.
1232
1611
  *
@@ -1247,7 +1626,7 @@ type Config<TInput = Input> = {
1247
1626
  *
1248
1627
  * @see {@link Storage} interface for implementing custom backends.
1249
1628
  */
1250
- storage?: Storage;
1629
+ storage: Storage;
1251
1630
  /**
1252
1631
  * Plugins that execute during the build to generate code and transform the AST.
1253
1632
  *
@@ -1288,19 +1667,6 @@ type Config<TInput = Input> = {
1288
1667
  * @see {@link defineMiddleware} to create custom middleware.
1289
1668
  */
1290
1669
  middleware?: Array<Middleware>;
1291
- /**
1292
- * Default renderer factory used by all plugins and generators.
1293
- * Resolution chain: `generator.renderer` → `plugin.renderer` → `config.renderer` → `undefined` (raw FileNode[] mode).
1294
- *
1295
- * @example
1296
- * ```ts
1297
- * import { jsxRenderer } from '@kubb/renderer-jsx'
1298
- * export default defineConfig({
1299
- * renderer: jsxRenderer,
1300
- * plugins: [pluginTs(), pluginZod()],
1301
- * })
1302
- * ```
1303
- */
1304
1670
  /**
1305
1671
  * Renderer that converts generated AST nodes to code strings.
1306
1672
  *
@@ -1320,7 +1686,7 @@ type Config<TInput = Input> = {
1320
1686
  /**
1321
1687
  * Kubb Studio cloud integration settings.
1322
1688
  *
1323
- * Kubb Studio (https://studio.kubb.dev) is a web-based IDE for managing API specs and generated code.
1689
+ * Kubb Studio (https://kubb.studio) is a web-based IDE for managing API specs and generated code.
1324
1690
  * Set to `true` to enable with default settings, or pass an object to customize the Studio URL.
1325
1691
  *
1326
1692
  * @default false // disabled by default
@@ -1333,7 +1699,7 @@ type Config<TInput = Input> = {
1333
1699
  devtools?: true | {
1334
1700
  /**
1335
1701
  * Override the Kubb Studio base URL.
1336
- * @default 'https://studio.kubb.dev'
1702
+ * @default 'https://kubb.studio'
1337
1703
  */
1338
1704
  studioUrl?: typeof DEFAULT_STUDIO_URL | (string & {});
1339
1705
  };
@@ -1369,780 +1735,571 @@ type Config<TInput = Input> = {
1369
1735
  done?: string | Array<string>;
1370
1736
  };
1371
1737
  };
1372
- /**
1373
- * Type/string pattern filter for include/exclude/override matching.
1374
- */
1375
- type PatternFilter = {
1376
- type: string;
1377
- pattern: string | RegExp;
1378
- };
1379
- /**
1380
- * Pattern filter with partial option overrides applied when the pattern matches.
1381
- */
1382
- type PatternOverride<TOptions> = PatternFilter & {
1383
- options: Omit<Partial<TOptions>, 'override'>;
1384
- };
1385
- /**
1386
- * Context for resolving filtered options for a given operation or schema node.
1387
- *
1388
- * @internal
1389
- */
1390
- type ResolveOptionsContext<TOptions> = {
1391
- options: TOptions;
1392
- exclude?: Array<PatternFilter>;
1393
- include?: Array<PatternFilter>;
1394
- override?: Array<PatternOverride<TOptions>>;
1395
- };
1396
- /**
1397
- * Base constraint for all plugin resolver objects.
1398
- *
1399
- * `default`, `resolveOptions`, `resolvePath`, `resolveFile`, `resolveBanner`, and `resolveFooter`
1400
- * are injected automatically by `defineResolver` — extend this type to add custom resolution methods.
1401
- *
1402
- * @example
1403
- * ```ts
1404
- * type MyResolver = Resolver & {
1405
- * resolveName(node: SchemaNode): string
1406
- * resolveTypedName(node: SchemaNode): string
1407
- * }
1408
- * ```
1409
- */
1410
- type Resolver = {
1411
- name: string;
1412
- pluginName: Plugin['name'];
1413
- default(name: string, type?: 'file' | 'function' | 'type' | 'const'): string;
1414
- resolveOptions<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null;
1415
- resolvePath(params: ResolverPathParams, context: ResolverContext): string;
1416
- resolveFile(params: ResolverFileParams, context: ResolverContext): FileNode;
1417
- resolveBanner(node: InputNode | null, context: ResolveBannerContext): string | undefined;
1418
- resolveFooter(node: InputNode | null, context: ResolveBannerContext): string | undefined;
1419
- };
1420
- type PluginFactoryOptions<
1421
- /**
1422
- * Unique plugin name.
1423
- */
1424
- TName extends string = string,
1425
- /**
1426
- * User-facing plugin options.
1427
- */
1428
- TOptions extends object = object,
1429
- /**
1430
- * Plugin options after defaults are applied.
1431
- */
1432
- TResolvedOptions extends object = TOptions,
1433
- /**
1434
- * Resolver that encapsulates naming and path-resolution helpers.
1435
- * Define with `defineResolver` and export alongside the plugin.
1436
- */
1437
- TResolver extends Resolver = Resolver> = {
1438
- name: TName;
1439
- options: TOptions;
1440
- resolvedOptions: TResolvedOptions;
1441
- resolver: TResolver;
1442
- };
1443
- /**
1444
- * Normalized plugin after setup, with runtime fields populated.
1445
- * For internal use only — plugins use the public `Plugin` type externally.
1446
- *
1447
- * @internal
1448
- */
1449
- type NormalizedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & {
1450
- options: TOptions['resolvedOptions'] & {
1451
- output: Output;
1452
- include?: Array<Include>;
1453
- exclude: Array<Exclude$1>;
1454
- override: Array<Override<TOptions['resolvedOptions']>>;
1455
- };
1456
- resolver: TOptions['resolver'];
1457
- transformer?: Visitor;
1458
- renderer?: RendererFactory;
1459
- generators?: Array<Generator>;
1460
- apply?: (config: Config) => boolean;
1461
- version?: string;
1462
- };
1463
1738
  /**
1464
1739
  * Partial `Config` for user-facing entry points with sensible defaults.
1465
1740
  *
1466
1741
  * `UserConfig` is what you pass to `defineConfig()`. It has optional `root`, `plugins`, `parsers`, and `adapter`
1467
1742
  * fields (which fall back to sensible defaults). All other Config options are available, including `output`, `input`,
1468
1743
  * `storage`, `middleware`, `renderer`, `devtools`, and `hooks`.
1469
- *
1470
- * @example
1471
- * ```ts
1472
- * export default defineConfig({
1473
- * input: { path: './petstore.yaml' },
1474
- * output: { path: './src/gen' },
1475
- * plugins: [pluginTs(), pluginZod()],
1476
- * })
1477
- * ```
1478
- */
1479
- type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter'> & {
1480
- /**
1481
- * Project root directory, absolute or relative to the config file location.
1482
- *
1483
- * Used as the base path for `root`-relative paths (e.g., `output.path`, file paths in hooks).
1484
- *
1485
- * @default process.cwd()
1486
- * @example
1487
- * ```ts
1488
- * root: '/home/user/my-project'
1489
- * root: './my-project' // relative to config file
1490
- * ```
1491
- */
1492
- root?: string;
1493
- /**
1494
- * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).
1495
- *
1496
- * Each parser handles a specific file type. By default, Kubb uses `parserTs` from `@kubb/parser-ts` for TypeScript files.
1497
- * Pass custom parsers to support additional languages or custom formats.
1498
- *
1499
- * @default [parserTs] // from @kubb/parser-ts
1500
- * @example
1501
- * ```ts
1502
- * import { parserTs } from '@kubb/parser-ts'
1503
- * import { parserJsonSchema } from '@kubb/parser-json-schema'
1504
- *
1505
- * parsers: [parserTs(), parserJsonSchema()]
1506
- * ```
1507
- *
1508
- * @see {@link Parser} to implement a custom parser.
1509
- */
1510
- parsers?: Array<Parser>;
1511
- /**
1512
- * Adapter that parses your API specification (OpenAPI, GraphQL, AsyncAPI, etc.) into Kubb's universal AST.
1513
- *
1514
- * The adapter bridge between your input format and Kubb's internal representation. By default, uses the OAS adapter.
1515
- * Pass an alternative adapter (or multiple configs with different adapters) to support different spec formats.
1516
- *
1517
- * @default new OasAdapter() // from @kubb/adapter-oas
1518
- * @example
1519
- * ```ts
1520
- * import { Oas } from '@kubb/adapter-oas'
1521
- *
1522
- * adapter: new Oas({ apiVersion: '3.0.0' })
1523
- * ```
1524
- *
1525
- * @see {@link Adapter} to implement a custom adapter for GraphQL or other formats.
1526
- */
1527
- adapter?: Adapter;
1528
- /**
1529
- * Plugins that execute during the build to generate code and transform the AST.
1530
- *
1531
- * Each plugin processes the AST produced by the adapter and can emit files for different
1532
- * programming languages or formats (TypeScript, Zod schemas, Faker data, etc.).
1533
- *
1534
- * @default [] // no plugins (useful for setup/testing)
1535
- * @example
1536
- * ```ts
1537
- * plugins: [
1538
- * pluginTs({ output: { path: './src/gen' } }),
1539
- * pluginZod({ output: { path: './src/gen' } }),
1540
- * ]
1541
- * ```
1542
- *
1543
- * @see {@link definePlugin} to create a custom plugin.
1544
- */
1545
- plugins?: Array<Plugin>;
1546
- };
1547
- type ResolveNameParams = {
1548
- name: string;
1549
- pluginName?: string;
1550
- /**
1551
- * Entity type being named.
1552
- * - `'file'` — file name (camelCase)
1553
- * - `'function'` — exported function name (camelCase)
1554
- * - `'type'` — TypeScript type name (PascalCase)
1555
- * - `'const'` — variable name (camelCase)
1556
- */
1557
- type?: 'file' | 'function' | 'type' | 'const';
1558
- };
1559
- /**
1560
- * Context object passed to generator `schema`, `operation`, and `operations` methods.
1561
- *
1562
- * The adapter is always defined (guaranteed by `runPluginAstHooks`) so no runtime checks
1563
- * are needed. `ctx.options` carries resolved per-node options after exclude/include/override
1564
- * filtering for individual schema/operation calls, or plugin-level options for operations.
1565
- */
1566
- type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1567
- config: Config;
1568
- /**
1569
- * Absolute path to the current plugin's output directory.
1570
- */
1571
- root: string;
1572
- /**
1573
- * Determine output mode based on the output config.
1574
- * Returns `'single'` when `output.path` is a file, `'split'` for a directory.
1575
- */
1576
- getMode: (output: {
1577
- path: string;
1578
- }) => 'single' | 'split';
1579
- driver: PluginDriver;
1580
- /**
1581
- * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
1582
- */
1583
- getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
1584
- getPlugin(name: string): Plugin | undefined;
1585
- /**
1586
- * Get a plugin by name, throws an error if not found.
1587
- */
1588
- requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>;
1589
- requirePlugin(name: string): Plugin;
1590
- /**
1591
- * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.
1592
- */
1593
- getResolver<TName extends keyof Kubb.PluginRegistry>(name: TName): Kubb.PluginRegistry[TName]['resolver'];
1594
- getResolver(name: string): Resolver;
1595
- /**
1596
- * Add files only if they don't exist.
1597
- */
1598
- addFile: (...file: Array<FileNode>) => Promise<void>;
1599
- /**
1600
- * Merge sources into the same output file.
1601
- */
1602
- upsertFile: (...file: Array<FileNode>) => Promise<void>;
1603
- hooks: AsyncEventEmitter<KubbHooks>;
1604
- /**
1605
- * The current plugin instance.
1606
- */
1607
- plugin: Plugin<TOptions>;
1608
- /**
1609
- * The current plugin's resolver.
1610
- */
1611
- resolver: TOptions['resolver'];
1612
- /**
1613
- * The current plugin's transformer.
1614
- */
1615
- transformer: Visitor | undefined;
1616
- /**
1617
- * Emit a warning.
1618
- */
1619
- warn: (message: string) => void;
1620
- /**
1621
- * Emit an error.
1622
- */
1623
- error: (error: string | Error) => void;
1624
- /**
1625
- * Emit an info message.
1626
- */
1627
- info: (message: string) => void;
1628
- /**
1629
- * Open the current input node in Kubb Studio.
1630
- */
1631
- openInStudio: (options?: DevtoolsOptions) => Promise<void>;
1632
- /**
1633
- * The configured adapter instance.
1634
- */
1635
- adapter: Adapter;
1636
- /**
1637
- * The universal `InputNode` produced by the adapter.
1638
- */
1639
- inputNode: InputNode;
1640
- /**
1641
- * Resolved options after exclude/include/override filtering.
1642
- */
1643
- options: TOptions['resolvedOptions'];
1644
- };
1645
- /**
1646
- * Output configuration for generated files.
1647
- */
1648
- type Output<_TOptions = unknown> = {
1649
- /**
1650
- * Output folder or file path for generated code.
1651
- */
1652
- path: string;
1653
- /**
1654
- * Text or function prepended to every generated file.
1655
- * When a function, receives the current `InputNode` and returns a string.
1656
- */
1657
- banner?: string | ((node?: InputNode) => string);
1658
- /**
1659
- * Text or function appended to every generated file.
1660
- * When a function, receives the current `InputNode` and returns a string.
1661
- */
1662
- footer?: string | ((node?: InputNode) => string);
1663
- /**
1664
- * Whether to override existing external files if they already exist.
1665
- * @default false
1666
- */
1667
- override?: boolean;
1668
- } & ExtractRegistryKey<Kubb.PluginOptionsRegistry, 'output'>;
1669
- type Group = {
1670
- /**
1671
- * How to group files into subdirectories.
1672
- * - `'tag'` — group by OpenAPI tags
1673
- * - `'path'` — group by OpenAPI paths
1674
- */
1675
- type: 'tag' | 'path';
1676
- /**
1677
- * Function that returns the subdirectory name for a group value.
1678
- * Defaults to `${camelCase(group)}Controller` for tags, first path segment for paths.
1679
- */
1680
- name?: (context: {
1681
- group: string;
1682
- }) => string;
1683
- };
1684
- type LoggerOptions = {
1685
- /**
1686
- * Log level for output verbosity.
1687
- * @default 3
1688
- */
1689
- logLevel: (typeof logLevel)[keyof typeof logLevel];
1690
- };
1691
- /**
1692
- * Shared context passed to plugins, parsers, and other internals.
1693
- */
1694
- type LoggerContext = AsyncEventEmitter<KubbHooks>;
1695
- type Logger<TOptions extends LoggerOptions = LoggerOptions> = {
1696
- name: string;
1697
- install: (context: LoggerContext, options?: TOptions) => void | Promise<void>;
1698
- };
1699
- type UserLogger<TOptions extends LoggerOptions = LoggerOptions> = Logger<TOptions>;
1700
- /**
1701
- * Context for hook-style plugin `kubb:plugin:setup` handler.
1702
- * Provides methods to register generators, configure resolvers, transformers, and renderers.
1703
- */
1704
- type KubbPluginSetupContext<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {
1705
- /**
1706
- * Register a generator dynamically. Generators fire during the AST walk (schema/operation/operations)
1707
- * just like generators declared statically on `createPlugin`.
1708
- */
1709
- addGenerator<TElement = unknown>(generator: Generator<TFactory, TElement>): void;
1710
- /**
1711
- * Set or override the resolver for this plugin.
1712
- * The resolver controls file naming and path resolution.
1713
- */
1714
- setResolver(resolver: Partial<TFactory['resolver']>): void;
1715
- /**
1716
- * Set the AST transformer to pre-process nodes before they reach generators.
1717
- */
1718
- setTransformer(visitor: Visitor): void;
1719
- /**
1720
- * Set the renderer factory to process JSX elements from generators.
1721
- */
1722
- setRenderer(renderer: RendererFactory): void;
1744
+ *
1745
+ * @example
1746
+ * ```ts
1747
+ * export default defineConfig({
1748
+ * input: { path: './petstore.yaml' },
1749
+ * output: { path: './src/gen' },
1750
+ * plugins: [pluginTs(), pluginZod()],
1751
+ * })
1752
+ * ```
1753
+ */
1754
+ type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter' | 'storage'> & {
1723
1755
  /**
1724
- * Set resolved options merged into the normalized plugin's `options`.
1725
- * Call this in `kubb:plugin:setup` to provide options generators need.
1756
+ * Project root directory, absolute or relative to the config file location.
1757
+ * @default process.cwd()
1726
1758
  */
1727
- setOptions(options: TFactory['resolvedOptions']): void;
1759
+ root?: string;
1728
1760
  /**
1729
- * Inject a raw file into the build output, bypassing the generation pipeline.
1761
+ * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).
1762
+ * @default [parserTs] // from `@kubb/parser-ts`
1730
1763
  */
1731
- injectFile(userFileNode: UserFileNode): void;
1764
+ parsers?: Array<Parser>;
1732
1765
  /**
1733
- * Merge a partial config update into the current build configuration.
1766
+ * Adapter that parses your API specification into Kubb's universal AST.
1767
+ * When omitted, Kubb runs in plugin-only mode.
1734
1768
  */
1735
- updateConfig(config: Partial<Config>): void;
1769
+ adapter?: Adapter;
1736
1770
  /**
1737
- * The resolved build configuration at setup time.
1771
+ * Plugins that execute during the build to generate code and transform the AST.
1772
+ * @default []
1738
1773
  */
1739
- config: Config;
1774
+ plugins?: Array<Plugin>;
1740
1775
  /**
1741
- * The plugin's user-provided options.
1776
+ * Storage backend that controls where and how generated files are persisted.
1777
+ * @default fsStorage()
1742
1778
  */
1743
- options: TFactory['options'];
1779
+ storage?: Storage;
1744
1780
  };
1781
+ declare global {
1782
+ namespace Kubb {
1783
+ /**
1784
+ * Registry that maps plugin names to their `PluginFactoryOptions`.
1785
+ * Augment this interface in each plugin's `types.ts` to enable automatic
1786
+ * typing for `getPlugin` and `requirePlugin`.
1787
+ *
1788
+ * @example
1789
+ * ```ts
1790
+ * // packages/plugin-ts/src/types.ts
1791
+ * declare global {
1792
+ * namespace Kubb {
1793
+ * interface PluginRegistry {
1794
+ * 'plugin-ts': PluginTs
1795
+ * }
1796
+ * }
1797
+ * }
1798
+ * ```
1799
+ */
1800
+ interface PluginRegistry {}
1801
+ /**
1802
+ * Extension point for root `Config['output']` options.
1803
+ * Augment the `output` key in middleware or plugin packages to add extra fields
1804
+ * to the global output configuration without touching core types.
1805
+ *
1806
+ * @example
1807
+ * ```ts
1808
+ * // packages/middleware-barrel/src/types.ts
1809
+ * declare global {
1810
+ * namespace Kubb {
1811
+ * interface ConfigOptionsRegistry {
1812
+ * output: {
1813
+ * barrel?: import('./types.ts').BarrelConfig | false
1814
+ * }
1815
+ * }
1816
+ * }
1817
+ * }
1818
+ * ```
1819
+ */
1820
+ interface ConfigOptionsRegistry {}
1821
+ /**
1822
+ * Extension point for per-plugin `Output` options.
1823
+ * Augment the `output` key in middleware or plugin packages to add extra fields
1824
+ * to the per-plugin output configuration without touching core types.
1825
+ *
1826
+ * @example
1827
+ * ```ts
1828
+ * // packages/middleware-barrel/src/types.ts
1829
+ * declare global {
1830
+ * namespace Kubb {
1831
+ * interface PluginOptionsRegistry {
1832
+ * output: {
1833
+ * barrel?: import('./types.ts').PluginBarrelConfig | false
1834
+ * }
1835
+ * }
1836
+ * }
1837
+ * }
1838
+ * ```
1839
+ */
1840
+ interface PluginOptionsRegistry {}
1841
+ }
1842
+ }
1745
1843
  /**
1746
- * Context for hook-style plugin `kubb:build:start` handler.
1747
- * Fires immediately before the plugin execution loop begins.
1844
+ * Lifecycle events emitted during Kubb code generation.
1845
+ * Attach listeners before calling `setup()` or `build()` to observe and react to build progress.
1846
+ *
1847
+ * @example
1848
+ * ```ts
1849
+ * kubb.hooks.on('kubb:lifecycle:start', () => {
1850
+ * console.log('Starting Kubb generation')
1851
+ * })
1852
+ *
1853
+ * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {
1854
+ * console.log(`${plugin.name} completed in ${duration}ms`)
1855
+ * })
1856
+ * ```
1748
1857
  */
1858
+ interface KubbHooks {
1859
+ 'kubb:lifecycle:start': [ctx: KubbLifecycleStartContext];
1860
+ 'kubb:lifecycle:end': [];
1861
+ 'kubb:config:start': [];
1862
+ 'kubb:config:end': [ctx: KubbConfigEndContext];
1863
+ 'kubb:generation:start': [ctx: KubbGenerationStartContext];
1864
+ 'kubb:generation:end': [ctx: KubbGenerationEndContext];
1865
+ 'kubb:generation:summary': [ctx: KubbGenerationSummaryContext];
1866
+ 'kubb:format:start': [];
1867
+ 'kubb:format:end': [];
1868
+ 'kubb:lint:start': [];
1869
+ 'kubb:lint:end': [];
1870
+ 'kubb:hooks:start': [];
1871
+ 'kubb:hooks:end': [];
1872
+ 'kubb:hook:start': [ctx: KubbHookStartContext];
1873
+ 'kubb:hook:end': [ctx: KubbHookEndContext];
1874
+ 'kubb:version:new': [ctx: KubbVersionNewContext];
1875
+ 'kubb:info': [ctx: KubbInfoContext];
1876
+ 'kubb:error': [ctx: KubbErrorContext];
1877
+ 'kubb:success': [ctx: KubbSuccessContext];
1878
+ 'kubb:warn': [ctx: KubbWarnContext];
1879
+ 'kubb:debug': [ctx: KubbDebugContext];
1880
+ 'kubb:files:processing:start': [ctx: KubbFilesProcessingStartContext];
1881
+ 'kubb:file:processing:update': [ctx: KubbFileProcessingUpdateContext];
1882
+ 'kubb:files:processing:end': [ctx: KubbFilesProcessingEndContext];
1883
+ 'kubb:plugin:start': [ctx: KubbPluginStartContext];
1884
+ 'kubb:plugin:end': [ctx: KubbPluginEndContext];
1885
+ 'kubb:plugin:setup': [ctx: KubbPluginSetupContext];
1886
+ 'kubb:build:start': [ctx: KubbBuildStartContext];
1887
+ 'kubb:plugins:end': [ctx: KubbPluginsEndContext];
1888
+ 'kubb:build:end': [ctx: KubbBuildEndContext];
1889
+ 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext];
1890
+ 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext];
1891
+ 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext];
1892
+ }
1749
1893
  type KubbBuildStartContext = {
1894
+ /**
1895
+ * Resolved configuration for this build.
1896
+ */
1750
1897
  config: Config;
1898
+ /**
1899
+ * Adapter that parsed the input into the universal AST.
1900
+ */
1751
1901
  adapter: Adapter;
1752
- inputNode: InputNode;
1753
1902
  /**
1754
- * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.
1903
+ * Metadata about the parsed document (title, version, base URL, circular schema names, enum names).
1904
+ * To observe individual schemas and operations use the `kubb:generate:schema` / `kubb:generate:operation` hooks.
1755
1905
  */
1756
- getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
1906
+ meta: InputMeta | undefined;
1907
+ /**
1908
+ * Looks up a registered plugin by name, typed by the plugin registry.
1909
+ */
1910
+ getPlugin<TName extends keyof Kubb$1.PluginRegistry>(name: TName): Plugin<Kubb$1.PluginRegistry[TName]> | undefined;
1757
1911
  getPlugin(name: string): Plugin | undefined;
1758
1912
  /**
1759
- * Get all files currently in the file manager.
1760
- * Call this lazily (e.g. in `kubb:plugin:end`) to see files added by prior plugins.
1913
+ * Snapshot of all files accumulated so far.
1761
1914
  */
1762
1915
  readonly files: ReadonlyArray<FileNode>;
1763
1916
  /**
1764
- * Upsert one or more files into the file manager.
1765
- * Files with the same path are merged; new files are appended.
1766
- * Safe to call at any point during the plugin lifecycle, including inside `kubb:plugin:end`.
1917
+ * Adds or merges one or more files into the file manager.
1767
1918
  */
1768
1919
  upsertFile: (...files: Array<FileNode>) => void;
1769
1920
  };
1770
- /**
1771
- * Context for `kubb:plugins:end` handlers.
1772
- * Fires after plugins run and per-plugin barrels are written, before final write to disk.
1773
- * Middleware that needs final files (e.g. root barrel) use this event.
1774
- */
1775
1921
  type KubbPluginsEndContext = {
1922
+ /**
1923
+ * Resolved configuration for this build.
1924
+ */
1776
1925
  config: Config;
1777
1926
  /**
1778
- * All files currently in the file manager (lazy snapshot).
1927
+ * Snapshot of all files accumulated across all plugins.
1779
1928
  */
1780
1929
  readonly files: ReadonlyArray<FileNode>;
1781
1930
  /**
1782
- * Upsert files into the file manager.
1783
- * Files added here are included in the write pass.
1931
+ * Adds or merges one or more files into the file manager.
1784
1932
  */
1785
1933
  upsertFile: (...files: Array<FileNode>) => void;
1786
1934
  };
1787
- /**
1788
- * Context for hook-style plugin `kubb:build:end` handler.
1789
- * Fires after all files have been written to disk.
1790
- */
1791
1935
  type KubbBuildEndContext = {
1936
+ /**
1937
+ * All files generated during this build.
1938
+ */
1792
1939
  files: Array<FileNode>;
1940
+ /**
1941
+ * Resolved configuration for this build.
1942
+ */
1793
1943
  config: Config;
1944
+ /**
1945
+ * Absolute path to the output directory.
1946
+ */
1794
1947
  outputDir: string;
1795
1948
  };
1796
1949
  type KubbLifecycleStartContext = {
1950
+ /**
1951
+ * Current Kubb version string.
1952
+ */
1797
1953
  version: string;
1798
1954
  };
1799
1955
  type KubbConfigEndContext = {
1956
+ /**
1957
+ * All resolved configs after defaults are applied.
1958
+ */
1800
1959
  configs: Array<Config>;
1801
1960
  };
1802
1961
  type KubbGenerationStartContext = {
1962
+ /**
1963
+ * Resolved configuration for this generation run.
1964
+ */
1803
1965
  config: Config;
1804
1966
  };
1805
1967
  type KubbGenerationEndContext = {
1968
+ /**
1969
+ * Resolved configuration for this generation run.
1970
+ */
1806
1971
  config: Config;
1807
- files: Array<FileNode>;
1808
- sources: Map<string, string>;
1972
+ /**
1973
+ * Read-only view of the files written during this build.
1974
+ * Reads go directly to `config.storage` — nothing extra is held in memory.
1975
+ *
1976
+ * @example Read a generated file
1977
+ * `const code = await storage.getItem('/src/gen/pet.ts')`
1978
+ *
1979
+ * @example Walk every generated file
1980
+ * ```ts
1981
+ * for (const path of await storage.getKeys()) {
1982
+ * const code = await storage.getItem(path)
1983
+ * }
1984
+ * ```
1985
+ */
1986
+ storage: Storage;
1809
1987
  };
1810
1988
  type KubbGenerationSummaryContext = {
1989
+ /**
1990
+ * Resolved configuration for this generation run.
1991
+ */
1811
1992
  config: Config;
1993
+ /**
1994
+ * Plugins that threw during generation, paired with their errors.
1995
+ */
1812
1996
  failedPlugins: Set<{
1813
1997
  plugin: Plugin;
1814
1998
  error: Error;
1815
1999
  }>;
2000
+ /**
2001
+ * `'success'` when all plugins completed without errors, `'failed'` otherwise.
2002
+ */
1816
2003
  status: 'success' | 'failed';
2004
+ /**
2005
+ * High-resolution start time from `process.hrtime()`.
2006
+ */
1817
2007
  hrStart: [number, number];
2008
+ /**
2009
+ * Total number of files created during this run.
2010
+ */
1818
2011
  filesCreated: number;
2012
+ /**
2013
+ * Elapsed milliseconds per plugin, keyed by plugin name.
2014
+ */
1819
2015
  pluginTimings?: Map<Plugin['name'], number>;
1820
2016
  };
1821
2017
  type KubbVersionNewContext = {
2018
+ /**
2019
+ * The installed Kubb version.
2020
+ */
1822
2021
  currentVersion: string;
2022
+ /**
2023
+ * The newest available version on npm.
2024
+ */
1823
2025
  latestVersion: string;
1824
2026
  };
1825
2027
  type KubbInfoContext = {
2028
+ /**
2029
+ * Human-readable info message.
2030
+ */
1826
2031
  message: string;
2032
+ /**
2033
+ * Optional supplementary detail.
2034
+ */
1827
2035
  info?: string;
1828
2036
  };
1829
2037
  type KubbErrorContext = {
2038
+ /**
2039
+ * The caught error.
2040
+ */
1830
2041
  error: Error;
2042
+ /**
2043
+ * Optional structured metadata for additional context.
2044
+ */
1831
2045
  meta?: Record<string, unknown>;
1832
2046
  };
1833
2047
  type KubbSuccessContext = {
2048
+ /**
2049
+ * Human-readable success message.
2050
+ */
1834
2051
  message: string;
2052
+ /**
2053
+ * Optional supplementary detail.
2054
+ */
1835
2055
  info?: string;
1836
2056
  };
1837
2057
  type KubbWarnContext = {
2058
+ /**
2059
+ * Human-readable warning message.
2060
+ */
1838
2061
  message: string;
2062
+ /**
2063
+ * Optional supplementary detail.
2064
+ */
1839
2065
  info?: string;
1840
2066
  };
1841
2067
  type KubbDebugContext = {
2068
+ /**
2069
+ * Timestamp when the debug entry was created.
2070
+ */
1842
2071
  date: Date;
2072
+ /**
2073
+ * One or more log lines to emit.
2074
+ */
1843
2075
  logs: Array<string>;
2076
+ /**
2077
+ * Optional source file name associated with this entry.
2078
+ */
1844
2079
  fileName?: string;
1845
2080
  };
1846
2081
  type KubbFilesProcessingStartContext = {
2082
+ /**
2083
+ * Files about to be serialised and written.
2084
+ */
1847
2085
  files: Array<FileNode>;
1848
2086
  };
1849
2087
  type KubbFileProcessingUpdateContext = {
1850
2088
  /**
1851
- * Number of files processed.
2089
+ * Number of files processed so far in this batch.
1852
2090
  */
1853
2091
  processed: number;
1854
2092
  /**
1855
- * Total files to process.
2093
+ * Total number of files in this batch.
1856
2094
  */
1857
2095
  total: number;
1858
2096
  /**
1859
- * Processing percentage (0100).
2097
+ * Completion percentage (`0`–`100`).
1860
2098
  */
1861
2099
  percentage: number;
1862
2100
  /**
1863
- * Optional source identifier.
2101
+ * Serialised file content, or `undefined` when the file produced no output.
1864
2102
  */
1865
2103
  source?: string;
1866
2104
  /**
1867
- * The file being processed.
2105
+ * The file that was just processed.
1868
2106
  */
1869
2107
  file: FileNode;
1870
2108
  /**
1871
- * The current build configuration.
2109
+ * Resolved configuration for this build.
1872
2110
  */
1873
2111
  config: Config;
1874
2112
  };
1875
2113
  type KubbFilesProcessingEndContext = {
1876
- files: Array<FileNode>;
1877
- };
1878
- type KubbPluginStartContext = {
1879
- plugin: NormalizedPlugin;
1880
- };
1881
- type KubbPluginEndContext = {
1882
- plugin: NormalizedPlugin;
1883
- duration: number;
1884
- success: boolean;
1885
- error?: Error;
1886
- config: Config;
1887
- /**
1888
- * Returns all files currently in the file manager (lazy snapshot).
1889
- * Includes files added by plugins that have already run.
1890
- */
1891
- readonly files: ReadonlyArray<FileNode>;
1892
2114
  /**
1893
- * Upsert one or more files into the file manager.
2115
+ * All files that were serialised in this batch.
1894
2116
  */
1895
- upsertFile: (...files: Array<FileNode>) => void;
2117
+ files: Array<FileNode>;
1896
2118
  };
1897
2119
  type KubbHookStartContext = {
1898
- id?: string;
1899
- command: string;
1900
- args?: readonly string[];
1901
- };
1902
- type KubbHookEndContext = {
1903
- id?: string;
1904
- command: string;
1905
- args?: readonly string[];
1906
- success: boolean;
1907
- error: Error | null;
1908
- };
1909
- type ByTag = {
1910
2120
  /**
1911
- * Filter by OpenAPI `tags` field. Matches one or more tags assigned to operations.
1912
- */
1913
- type: 'tag';
1914
- /**
1915
- * Tag name to match (case-sensitive). Can be a literal string or regex pattern.
2121
+ * Optional identifier for correlating start/end events.
1916
2122
  */
1917
- pattern: string | RegExp;
1918
- };
1919
- type ByOperationId = {
2123
+ id?: string;
1920
2124
  /**
1921
- * Filter by OpenAPI `operationId` field. Each operation (GET, POST, etc.) has a unique identifier.
2125
+ * The shell command that is about to run.
1922
2126
  */
1923
- type: 'operationId';
2127
+ command: string;
1924
2128
  /**
1925
- * Operation ID to match (case-sensitive). Can be a literal string or regex pattern.
2129
+ * Parsed argument list, when available.
1926
2130
  */
1927
- pattern: string | RegExp;
2131
+ args?: readonly string[];
1928
2132
  };
1929
- type ByPath = {
2133
+ type KubbHookEndContext = {
1930
2134
  /**
1931
- * Filter by OpenAPI `path` (URL endpoint). Useful to group or filter by service segments like `/pets`, `/users`, etc.
2135
+ * Optional identifier matching the corresponding `kubb:hook:start` event.
1932
2136
  */
1933
- type: 'path';
2137
+ id?: string;
1934
2138
  /**
1935
- * URL path to match (case-sensitive). Can be a literal string or regex pattern. Matches against the full path.
2139
+ * The shell command that ran.
1936
2140
  */
1937
- pattern: string | RegExp;
1938
- };
1939
- type ByMethod = {
2141
+ command: string;
1940
2142
  /**
1941
- * Filter by HTTP method: `'get'`, `'post'`, `'put'`, `'delete'`, `'patch'`, `'head'`, `'options'`.
2143
+ * Parsed argument list, when available.
1942
2144
  */
1943
- type: 'method';
2145
+ args?: readonly string[];
1944
2146
  /**
1945
- * HTTP method to match (case-insensitive when using string, or regex for dynamic matching).
2147
+ * `true` when the command exited with code `0`.
1946
2148
  */
1947
- pattern: HttpMethod | RegExp;
1948
- };
1949
- type BySchemaName = {
2149
+ success: boolean;
1950
2150
  /**
1951
- * Filter by schema component name (TypeScript or JSON schema). Matches schemas in `#/components/schemas`.
2151
+ * Error thrown by the command, or `null` on success.
1952
2152
  */
1953
- type: 'schemaName';
2153
+ error: Error | null;
2154
+ };
2155
+ /**
2156
+ * CLI options derived from command-line flags.
2157
+ */
2158
+ type CLIOptions = {
1954
2159
  /**
1955
- * Schema name to match (case-sensitive). Can be a literal string or regex pattern.
2160
+ * Path to the Kubb config file.
1956
2161
  */
1957
- pattern: string | RegExp;
1958
- };
1959
- type ByContentType = {
2162
+ config?: string;
1960
2163
  /**
1961
- * Filter by response or request content type: `'application/json'`, `'application/xml'`, etc.
2164
+ * Re-run generation whenever input files change.
1962
2165
  */
1963
- type: 'contentType';
2166
+ watch?: boolean;
1964
2167
  /**
1965
- * Content type to match (case-sensitive). Can be a literal string or regex pattern.
2168
+ * Controls how much output the CLI prints.
2169
+ *
2170
+ * @default 'silent'
1966
2171
  */
1967
- pattern: string | RegExp;
2172
+ logLevel?: 'silent' | 'info' | 'debug';
1968
2173
  };
1969
2174
  /**
1970
- * A pattern filter that prevents matching nodes from being generated.
1971
- *
1972
- * Use to skip code generation for specific operations or schemas. For example, exclude deprecated endpoints
1973
- * or internal-only schemas. Can filter by tag, operationId, path, HTTP method, content type, or schema name.
1974
- *
1975
- * @example
1976
- * ```ts
1977
- * exclude: [
1978
- * { type: 'tag', pattern: 'internal' }, // skip "internal" tag
1979
- * { type: 'path', pattern: /^\/admin/ }, // skip all /admin endpoints
1980
- * { type: 'operationId', pattern: 'deprecated_*' } // skip operationIds matching pattern
1981
- * ]
1982
- * ```
1983
- */
1984
- type Exclude$1 = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
1985
- /**
1986
- * A pattern filter that restricts generation to only matching nodes.
1987
- *
1988
- * Use to generate code for a subset of operations or schemas. For example, only generate for a specific service
1989
- * tag or only for "production" endpoints. Can filter by tag, operationId, path, HTTP method, content type, or schema name.
1990
- *
1991
- * @example
1992
- * ```ts
1993
- * include: [
1994
- * { type: 'tag', pattern: 'public' }, // generate only "public" tag
1995
- * { type: 'path', pattern: /^\/api\/v1/ }, // generate only v1 endpoints
1996
- * ]
1997
- * ```
1998
- */
1999
- type Include = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
2000
- /**
2001
- * A pattern filter paired with partial option overrides applied when the pattern matches.
2002
- *
2003
- * Use to customize generation for specific operations or schemas. For example, apply different output paths
2004
- * for different tags, or use custom resolver functions per operation. Can filter by tag, operationId, path,
2005
- * HTTP method, schema name, or content type.
2006
- *
2007
- * @example
2008
- * ```ts
2009
- * override: [
2010
- * {
2011
- * type: 'tag',
2012
- * pattern: 'admin',
2013
- * options: { output: { path: './src/gen/admin' } } // admin APIs go to separate folder
2014
- * },
2015
- * {
2016
- * type: 'operationId',
2017
- * pattern: 'listPets',
2018
- * options: { exclude: true } // skip this specific operation
2019
- * }
2020
- * ]
2021
- * ```
2175
+ * All accepted forms of a Kubb configuration.
2176
+ * Accepts `Config`/`Config[]`/promise or a factory (optionally receiving `TCliOptions`.
2022
2177
  */
2023
- type Override<TOptions> = (ByTag | ByOperationId | ByPath | ByMethod | BySchemaName | ByContentType) & {
2024
- options: Partial<TOptions>;
2025
- };
2178
+ type PossibleConfig<TCliOptions = undefined> = PossiblePromise<Config | Config[]> | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Config[]>);
2026
2179
  /**
2027
- * File-specific parameters for `Resolver.resolvePath`.
2028
- *
2029
- * Pass alongside a `ResolverContext` to identify which file to resolve.
2030
- * Provide `tag` for tag-based grouping or `path` for path-based grouping.
2031
- *
2032
- * @example
2033
- * ```ts
2034
- * resolver.resolvePath(
2035
- * { baseName: 'petTypes.ts', tag: 'pets' },
2036
- * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
2037
- * )
2038
- * // → '/src/types/petsController/petTypes.ts'
2039
- * ```
2180
+ * Full output produced by a successful or failed build.
2040
2181
  */
2041
- type ResolverPathParams = {
2042
- baseName: FileNode['baseName'];
2043
- pathMode?: 'single' | 'split';
2182
+ type BuildOutput = {
2044
2183
  /**
2045
- * Tag value used when `group.type === 'tag'`.
2184
+ * Plugins that threw during generation, paired with their errors.
2046
2185
  */
2047
- tag?: string;
2186
+ failedPlugins: Set<{
2187
+ plugin: Plugin;
2188
+ error: Error;
2189
+ }>;
2048
2190
  /**
2049
- * Path value used when `group.type === 'path'`.
2191
+ * All files generated during this build.
2050
2192
  */
2051
- path?: string;
2052
- };
2053
- /**
2054
- * Shared context passed as the second argument to `Resolver.resolvePath` and `Resolver.resolveFile`.
2055
- *
2056
- * Describes where on disk output is rooted, which output config is active, and the optional
2057
- * grouping strategy that controls subdirectory layout.
2058
- *
2059
- * @example
2060
- * ```ts
2061
- * const context: ResolverContext = {
2062
- * root: config.root,
2063
- * output,
2064
- * group,
2065
- * }
2066
- * ```
2067
- */
2068
- type ResolverContext = {
2069
- root: string;
2070
- output: Output;
2071
- group?: Group;
2193
+ files: Array<FileNode>;
2072
2194
  /**
2073
- * Plugin name used to populate `meta.pluginName` on the resolved file.
2195
+ * The plugin driver that orchestrated this build.
2074
2196
  */
2075
- pluginName?: string;
2076
- };
2077
- /**
2078
- * File-specific parameters for `Resolver.resolveFile`.
2079
- *
2080
- * Pass alongside a `ResolverContext` to fully describe the file to resolve.
2081
- * `tag` and `path` are used only when a matching `group` is present in the context.
2082
- *
2083
- * @example
2084
- * ```ts
2085
- * resolver.resolveFile(
2086
- * { name: 'listPets', extname: '.ts', tag: 'pets' },
2087
- * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
2088
- * )
2089
- * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }
2090
- * ```
2091
- */
2092
- type ResolverFileParams = {
2093
- name: string;
2094
- extname: FileNode['extname'];
2197
+ driver: KubbDriver;
2095
2198
  /**
2096
- * Tag value used when `group.type === 'tag'`.
2199
+ * Elapsed milliseconds per plugin, keyed by plugin name.
2097
2200
  */
2098
- tag?: string;
2201
+ pluginTimings: Map<string, number>;
2099
2202
  /**
2100
- * Path value used when `group.type === 'path'`.
2203
+ * Top-level error when the build threw before completing, otherwise `undefined`.
2101
2204
  */
2102
- path?: string;
2205
+ error?: Error;
2206
+ /**
2207
+ * Read-only view of every file written during this build.
2208
+ * Reads go straight to `config.storage` — nothing extra is held in memory.
2209
+ *
2210
+ * @example Read a generated file
2211
+ * `const code = await buildOutput.storage.getItem('/src/gen/pet.ts')`
2212
+ *
2213
+ * @example List all generated file paths
2214
+ * `const paths = await buildOutput.storage.getKeys()`
2215
+ */
2216
+ storage: Storage;
2103
2217
  };
2104
2218
  /**
2105
- * Context passed to `Resolver.resolveBanner` and `Resolver.resolveFooter`.
2106
- *
2107
- * `output` is optional — not every plugin configures a banner/footer.
2108
- * `config` carries the global Kubb config, used to derive the default Kubb banner.
2219
+ * Kubb code generation instance returned by {@link createKubb}.
2109
2220
  *
2110
- * @example
2111
- * ```ts
2112
- * resolver.resolveBanner(inputNode, { output: { banner: '// generated' }, config })
2113
- * // → '// generated'
2114
- * ```
2115
- */
2116
- type ResolveBannerContext = {
2117
- output?: Pick<Output, 'banner' | 'footer'>;
2118
- config: Config;
2119
- };
2120
- /**
2121
- * CLI options derived from command-line flags.
2221
+ * Use this when orchestrating multiple builds, inspecting plugin timings, or integrating Kubb into a larger toolchain.
2222
+ * For a single one-off build, chain directly: `await createKubb(config).build()`.
2122
2223
  */
2123
- type CLIOptions = {
2224
+ type Kubb$1 = {
2124
2225
  /**
2125
- * Path to `kubb.config.js`.
2226
+ * Shared event emitter for lifecycle and status events. Attach listeners before calling `setup()` or `build()`.
2126
2227
  */
2127
- config?: string;
2228
+ readonly hooks: AsyncEventEmitter<KubbHooks>;
2229
+ /**
2230
+ * Read-only view of the files from the most recent `build()` or `safeBuild()` call.
2231
+ * Only populated after the build completes.
2232
+ *
2233
+ * Keys are scoped to the current run. Reads go straight to `config.storage`,
2234
+ * so nothing extra is held in memory.
2235
+ *
2236
+ * @example Read a generated file
2237
+ * ```ts
2238
+ * const { storage } = await kubb.safeBuild()
2239
+ * const code = await storage.getItem('/src/gen/pet.ts')
2240
+ * ```
2241
+ *
2242
+ * @example Walk every generated file
2243
+ * ```ts
2244
+ * for (const path of await kubb.storage.getKeys()) {
2245
+ * const code = await kubb.storage.getItem(path)
2246
+ * }
2247
+ * ```
2248
+ */
2249
+ readonly storage: Storage;
2128
2250
  /**
2129
- * Enable watch mode for input files.
2251
+ * Plugin driver managing all plugins. Available after `setup()` completes.
2130
2252
  */
2131
- watch?: boolean;
2253
+ readonly driver: KubbDriver;
2132
2254
  /**
2133
- * Logging verbosity for CLI usage.
2134
- * @default 'silent'
2255
+ * Resolved configuration with defaults applied. Available after `setup()` completes.
2135
2256
  */
2136
- logLevel?: 'silent' | 'info' | 'debug';
2257
+ readonly config: Config;
2258
+ /**
2259
+ * Resolves config and initializes the driver. `build()` calls this automatically.
2260
+ */
2261
+ setup(): Promise<void>;
2262
+ /**
2263
+ * Runs the full pipeline and throws on any plugin error. Automatically calls `setup()` if needed.
2264
+ */
2265
+ build(): Promise<BuildOutput>;
2266
+ /**
2267
+ * Runs the full pipeline and captures errors in `BuildOutput` instead of throwing. Automatically calls `setup()` if needed.
2268
+ */
2269
+ safeBuild(): Promise<BuildOutput>;
2137
2270
  };
2138
2271
  /**
2139
- * All accepted forms of a Kubb configuration.
2272
+ * Type guard to check if a given config has an `input.path`.
2273
+ */
2274
+ declare function isInputPath(config: UserConfig | undefined): config is UserConfig<InputPath> & {
2275
+ input: InputPath;
2276
+ };
2277
+ declare function isInputPath(config: Config | undefined): config is Config<InputPath> & {
2278
+ input: InputPath;
2279
+ };
2280
+ type CreateKubbOptions = {
2281
+ hooks?: AsyncEventEmitter<KubbHooks>;
2282
+ };
2283
+ /**
2284
+ * Creates a Kubb instance bound to a single config entry.
2140
2285
  *
2141
- * Config is always `@kubb/core` {@link Config}.
2142
- * - `PossibleConfig` accepts `Config`/`Config[]`/promise or a no-arg config factory.
2143
- * - `PossibleConfig<TCliOptions>` accepts the same config forms or a config factory receiving `TCliOptions`.
2286
+ * Accepts a user-facing config shape and resolves it to a full {@link Config} during
2287
+ * `setup()`. The instance then holds shared state (`hooks`, `storage`, `driver`, `config`)
2288
+ * across the `setup build` lifecycle. Attach event listeners to `kubb.hooks` before
2289
+ * calling `setup()` or `build()`.
2290
+ *
2291
+ * @example
2292
+ * ```ts
2293
+ * const kubb = createKubb(userConfig)
2294
+ *
2295
+ * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {
2296
+ * console.log(`${plugin.name} completed in ${duration}ms`)
2297
+ * })
2298
+ *
2299
+ * const { files, failedPlugins } = await kubb.safeBuild()
2300
+ * ```
2144
2301
  */
2145
- type PossibleConfig<TCliOptions = undefined> = PossiblePromise<Config | Config[]> | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Config[]>);
2302
+ declare function createKubb(userConfig: UserConfig, options?: CreateKubbOptions): Kubb$1;
2146
2303
  //#endregion
2147
- export { defineParser as $, KubbPluginStartContext as A, Override as B, KubbGenerationSummaryContext as C, KubbLifecycleStartContext as D, KubbInfoContext as E, Logger as F, ResolveOptionsContext as G, PossibleConfig as H, LoggerContext as I, ResolverFileParams as J, Resolver as K, LoggerOptions as L, KubbSuccessContext as M, KubbVersionNewContext as N, KubbPluginEndContext as O, KubbWarnContext as P, Parser as Q, NormalizedPlugin as R, KubbGenerationStartContext as S, KubbHookStartContext as T, ResolveBannerContext as U, PluginFactoryOptions as V, ResolveNameParams as W, UserConfig as X, ResolverPathParams as Y, UserLogger as Z, KubbErrorContext as _, logLevel as _t, Config as a, createKubb as at, KubbFilesProcessingStartContext as b, GeneratorContext as c, Plugin as ct, InputData as d, defineGenerator as dt, Middleware as et, InputPath as f, Storage as ft, KubbDebugContext as g, createRenderer as gt, KubbConfigEndContext as h, RendererFactory as ht, CLIOptions as i, BuildOutput as it, KubbPluginsEndContext as j, KubbPluginSetupContext as k, Group as l, definePlugin as lt, KubbBuildStartContext as m, Renderer as mt, AdapterFactoryOptions as n, Kubb$1 as nt, DevtoolsOptions as o, PluginDriver as ot, KubbBuildEndContext as p, createStorage as pt, ResolverContext as q, AdapterSource as r, KubbHooks as rt, Exclude$1 as s, FileManager as st, Adapter as t, defineMiddleware as tt, Include as u, Generator as ut, KubbFileProcessingUpdateContext as v, AsyncEventEmitter as vt, KubbHookEndContext as w, KubbGenerationEndContext as x, KubbFilesProcessingEndContext as y, Output as z };
2148
- //# sourceMappingURL=types-CC09VtBt.d.ts.map
2304
+ export { ResolverPathParams as $, isInputPath as A, KubbPluginSetupContext as B, KubbPluginsEndContext as C, logLevel as Ct, PossibleConfig as D, KubbWarnContext as E, FileManager as F, Plugin as G, NormalizedPlugin as H, Exclude as I, ResolveBannerContext as J, PluginFactoryOptions as K, Group as L, GeneratorContext as M, defineGenerator as N, UserConfig as O, KubbDriver as P, ResolverFileParams as Q, Include as R, KubbLifecycleStartContext as S, createAdapter as St, KubbVersionNewContext as T, Output as U, KubbPluginStartContext as V, Override as W, Resolver as X, ResolveOptionsContext as Y, ResolverContext as Z, KubbGenerationSummaryContext as _, RendererFactory as _t, InputPath as a, LoggerOptions as at, KubbHooks as b, AdapterFactoryOptions as bt, KubbBuildStartContext as c, FileProcessor as ct, KubbErrorContext as d, Parser as dt, defineResolver as et, KubbFileProcessingUpdateContext as f, defineParser as ft, KubbGenerationStartContext as g, Renderer as gt, KubbGenerationEndContext as h, createStorage as ht, InputData as i, LoggerContext as it, Generator$1 as j, createKubb as k, KubbConfigEndContext as l, FileProcessorEvents as lt, KubbFilesProcessingStartContext as m, Storage as mt, CLIOptions as n, defineMiddleware as nt, Kubb$1 as o, UserLogger as ot, KubbFilesProcessingEndContext as p, DevtoolsOptions as pt, definePlugin as q, Config as r, Logger as rt, KubbBuildEndContext as s, defineLogger as st, BuildOutput as t, Middleware as tt, KubbDebugContext as u, ParsedFile as ut, KubbHookEndContext as v, createRenderer as vt, KubbSuccessContext as w, AsyncEventEmitter as wt, KubbInfoContext as x, AdapterSource as xt, KubbHookStartContext as y, Adapter as yt, KubbPluginEndContext as z };
2305
+ //# sourceMappingURL=createKubb-Dcmtjqds.d.ts.map