@kubb/core 5.0.0-alpha.3 → 5.0.0-alpha.30

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 (54) hide show
  1. package/dist/PluginDriver-D110FoJ-.d.ts +1632 -0
  2. package/dist/hooks.cjs +12 -27
  3. package/dist/hooks.cjs.map +1 -1
  4. package/dist/hooks.d.ts +11 -36
  5. package/dist/hooks.js +13 -27
  6. package/dist/hooks.js.map +1 -1
  7. package/dist/index.cjs +1410 -823
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.ts +597 -95
  10. package/dist/index.js +1391 -818
  11. package/dist/index.js.map +1 -1
  12. package/package.json +7 -7
  13. package/src/Kubb.ts +40 -58
  14. package/src/{PluginManager.ts → PluginDriver.ts} +165 -177
  15. package/src/build.ts +167 -44
  16. package/src/config.ts +9 -8
  17. package/src/constants.ts +40 -7
  18. package/src/createAdapter.ts +25 -0
  19. package/src/createPlugin.ts +30 -0
  20. package/src/createStorage.ts +58 -0
  21. package/src/defineGenerator.ts +126 -0
  22. package/src/defineLogger.ts +13 -3
  23. package/src/definePresets.ts +16 -0
  24. package/src/defineResolver.ts +457 -0
  25. package/src/hooks/index.ts +1 -6
  26. package/src/hooks/useDriver.ts +11 -0
  27. package/src/hooks/useMode.ts +5 -5
  28. package/src/hooks/usePlugin.ts +3 -3
  29. package/src/index.ts +18 -7
  30. package/src/renderNode.tsx +25 -0
  31. package/src/storages/fsStorage.ts +2 -2
  32. package/src/storages/memoryStorage.ts +2 -2
  33. package/src/types.ts +589 -52
  34. package/src/utils/FunctionParams.ts +2 -2
  35. package/src/utils/TreeNode.ts +45 -7
  36. package/src/utils/diagnostics.ts +4 -1
  37. package/src/utils/executeStrategies.ts +29 -10
  38. package/src/utils/formatters.ts +10 -21
  39. package/src/utils/getBarrelFiles.ts +83 -10
  40. package/src/utils/getConfigs.ts +8 -22
  41. package/src/utils/getPreset.ts +78 -0
  42. package/src/utils/linters.ts +23 -3
  43. package/src/utils/packageJSON.ts +76 -0
  44. package/dist/types-CiPWLv-5.d.ts +0 -1001
  45. package/src/BarrelManager.ts +0 -74
  46. package/src/PackageManager.ts +0 -180
  47. package/src/PromiseManager.ts +0 -40
  48. package/src/defineAdapter.ts +0 -22
  49. package/src/definePlugin.ts +0 -12
  50. package/src/defineStorage.ts +0 -56
  51. package/src/errors.ts +0 -1
  52. package/src/hooks/useKubb.ts +0 -22
  53. package/src/hooks/usePluginManager.ts +0 -11
  54. package/src/utils/getPlugins.ts +0 -23
@@ -0,0 +1,1632 @@
1
+ import { t as __name } from "./chunk--u3MIqq1.js";
2
+ import { Node, OperationNode, Printer, Printer as Printer$1, PrinterFactoryOptions, PrinterPartial, RootNode, SchemaNode, Visitor } from "@kubb/ast/types";
3
+ import { Fabric, FabricFile } from "@kubb/fabric-core/types";
4
+ import { HttpMethod } from "@kubb/oas";
5
+ import { FabricReactNode } from "@kubb/react-fabric/types";
6
+
7
+ //#region ../../internals/utils/src/asyncEventEmitter.d.ts
8
+ /**
9
+ * A function that can be registered as an event listener, synchronous or async.
10
+ */
11
+ type AsyncListener<TArgs extends unknown[]> = (...args: TArgs) => void | Promise<void>;
12
+ /**
13
+ * Typed `EventEmitter` that awaits all async listeners before resolving.
14
+ * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
19
+ * emitter.on('build', async (name) => { console.log(name) })
20
+ * await emitter.emit('build', 'petstore') // all listeners awaited
21
+ * ```
22
+ */
23
+ declare class AsyncEventEmitter<TEvents extends { [K in keyof TEvents]: unknown[] }> {
24
+ #private;
25
+ /**
26
+ * Maximum number of listeners per event before Node emits a memory-leak warning.
27
+ * @default 10
28
+ */
29
+ constructor(maxListener?: number);
30
+ /**
31
+ * Emits `eventName` and awaits all registered listeners sequentially.
32
+ * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * await emitter.emit('build', 'petstore')
37
+ * ```
38
+ */
39
+ emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArgs: TEvents[TEventName]): Promise<void>;
40
+ /**
41
+ * Registers a persistent listener for `eventName`.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * emitter.on('build', async (name) => { console.log(name) })
46
+ * ```
47
+ */
48
+ on<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void;
49
+ /**
50
+ * Registers a one-shot listener that removes itself after the first invocation.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * emitter.onOnce('build', async (name) => { console.log(name) })
55
+ * ```
56
+ */
57
+ onOnce<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void;
58
+ /**
59
+ * Removes a previously registered listener.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * emitter.off('build', handler)
64
+ * ```
65
+ */
66
+ off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void;
67
+ /**
68
+ * Removes all listeners from every event channel.
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * emitter.removeAll()
73
+ * ```
74
+ */
75
+ removeAll(): void;
76
+ }
77
+ //#endregion
78
+ //#region ../../internals/utils/src/promise.d.ts
79
+ /** A value that may already be resolved or still pending.
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * function load(id: string): PossiblePromise<string> {
84
+ * return cache.get(id) ?? fetchRemote(id)
85
+ * }
86
+ * ```
87
+ */
88
+ type PossiblePromise<T> = Promise<T> | T;
89
+ //#endregion
90
+ //#region src/constants.d.ts
91
+ /**
92
+ * Base URL for the Kubb Studio web app.
93
+ */
94
+ declare const DEFAULT_STUDIO_URL: "https://studio.kubb.dev";
95
+ /**
96
+ * Numeric log-level thresholds used internally to compare verbosity.
97
+ *
98
+ * Higher numbers are more verbose.
99
+ */
100
+ declare const logLevel: {
101
+ readonly silent: number;
102
+ readonly error: 0;
103
+ readonly warn: 1;
104
+ readonly info: 3;
105
+ readonly verbose: 4;
106
+ readonly debug: 5;
107
+ };
108
+ /**
109
+ * CLI command descriptors for each supported linter.
110
+ *
111
+ * Each entry contains the executable `command`, an `args` factory that maps an
112
+ * output path to the correct argument list, and an `errorMessage` shown when
113
+ * the linter is not found.
114
+ */
115
+ declare const linters: {
116
+ readonly eslint: {
117
+ readonly command: "eslint";
118
+ readonly args: (outputPath: string) => string[];
119
+ readonly errorMessage: "Eslint not found";
120
+ };
121
+ readonly biome: {
122
+ readonly command: "biome";
123
+ readonly args: (outputPath: string) => string[];
124
+ readonly errorMessage: "Biome not found";
125
+ };
126
+ readonly oxlint: {
127
+ readonly command: "oxlint";
128
+ readonly args: (outputPath: string) => string[];
129
+ readonly errorMessage: "Oxlint not found";
130
+ };
131
+ };
132
+ /**
133
+ * CLI command descriptors for each supported code formatter.
134
+ *
135
+ * Each entry contains the executable `command`, an `args` factory that maps an
136
+ * output path to the correct argument list, and an `errorMessage` shown when
137
+ * the formatter is not found.
138
+ */
139
+ declare const formatters: {
140
+ readonly prettier: {
141
+ readonly command: "prettier";
142
+ readonly args: (outputPath: string) => string[];
143
+ readonly errorMessage: "Prettier not found";
144
+ };
145
+ readonly biome: {
146
+ readonly command: "biome";
147
+ readonly args: (outputPath: string) => string[];
148
+ readonly errorMessage: "Biome not found";
149
+ };
150
+ readonly oxfmt: {
151
+ readonly command: "oxfmt";
152
+ readonly args: (outputPath: string) => string[];
153
+ readonly errorMessage: "Oxfmt not found";
154
+ };
155
+ };
156
+ //#endregion
157
+ //#region src/createStorage.d.ts
158
+ type Storage = {
159
+ /**
160
+ * Identifier used for logging and debugging (e.g. `'fs'`, `'s3'`).
161
+ */
162
+ readonly name: string;
163
+ /**
164
+ * Returns `true` when an entry for `key` exists in storage.
165
+ */
166
+ hasItem(key: string): Promise<boolean>;
167
+ /**
168
+ * Returns the stored string value, or `null` when `key` does not exist.
169
+ */
170
+ getItem(key: string): Promise<string | null>;
171
+ /**
172
+ * Persists `value` under `key`, creating any required structure.
173
+ */
174
+ setItem(key: string, value: string): Promise<void>;
175
+ /**
176
+ * Removes the entry for `key`. No-ops when the key does not exist.
177
+ */
178
+ removeItem(key: string): Promise<void>;
179
+ /**
180
+ * Returns all keys, optionally filtered to those starting with `base`.
181
+ */
182
+ getKeys(base?: string): Promise<Array<string>>;
183
+ /**
184
+ * Removes all entries, optionally scoped to those starting with `base`.
185
+ */
186
+ clear(base?: string): Promise<void>;
187
+ /**
188
+ * Optional teardown hook called after the build completes.
189
+ */
190
+ dispose?(): Promise<void>;
191
+ };
192
+ /**
193
+ * Creates a storage factory. Call the returned function with optional options to get the storage instance.
194
+ *
195
+ * @example
196
+ * export const memoryStorage = createStorage(() => {
197
+ * const store = new Map<string, string>()
198
+ * return {
199
+ * name: 'memory',
200
+ * async hasItem(key) { return store.has(key) },
201
+ * async getItem(key) { return store.get(key) ?? null },
202
+ * async setItem(key, value) { store.set(key, value) },
203
+ * async removeItem(key) { store.delete(key) },
204
+ * async getKeys(base) {
205
+ * const keys = [...store.keys()]
206
+ * return base ? keys.filter((k) => k.startsWith(base)) : keys
207
+ * },
208
+ * async clear(base) { if (!base) store.clear() },
209
+ * }
210
+ * })
211
+ */
212
+ declare function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage;
213
+ //#endregion
214
+ //#region src/defineGenerator.d.ts
215
+ /**
216
+ * A generator is a named object with optional `schema`, `operation`, and `operations`
217
+ * methods. Each method is called with `this = PluginContext` of the parent plugin,
218
+ * giving full access to `this.config`, `this.resolver`, `this.adapter`, `this.fabric`,
219
+ * `this.driver`, etc.
220
+ *
221
+ * Return a React element, an array of `FabricFile.File`, or `void` to handle file
222
+ * writing manually via `this.upsertFile`. Both React and core (non-React) generators
223
+ * use the same method signatures — the return type determines how output is handled.
224
+ *
225
+ * @example
226
+ * ```ts
227
+ * export const typeGenerator = defineGenerator<PluginTs>({
228
+ * name: 'typescript',
229
+ * schema(node, options) {
230
+ * const { adapter, resolver, root } = this
231
+ * return <File ...><Type node={node} resolver={resolver} /></File>
232
+ * },
233
+ * operation(node, options) {
234
+ * return <File ...><OperationType node={node} /></File>
235
+ * },
236
+ * })
237
+ * ```
238
+ */
239
+ type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
240
+ /** Used in diagnostic messages and debug output. */name: string;
241
+ /**
242
+ * Called for each schema node in the AST walk.
243
+ * `this` is the parent plugin's context with `adapter` and `rootNode` guaranteed present.
244
+ * `options` contains the per-node resolved options (after exclude/include/override).
245
+ */
246
+ schema?: (this: GeneratorContext<TOptions>, node: SchemaNode, options: TOptions['resolvedOptions']) => PossiblePromise<FabricReactNode | Array<FabricFile.File> | void>;
247
+ /**
248
+ * Called for each operation node in the AST walk.
249
+ * `this` is the parent plugin's context with `adapter` and `rootNode` guaranteed present.
250
+ */
251
+ operation?: (this: GeneratorContext<TOptions>, node: OperationNode, options: TOptions['resolvedOptions']) => PossiblePromise<FabricReactNode | Array<FabricFile.File> | void>;
252
+ /**
253
+ * Called once after all operations have been walked.
254
+ * `this` is the parent plugin's context with `adapter` and `rootNode` guaranteed present.
255
+ */
256
+ operations?: (this: GeneratorContext<TOptions>, nodes: Array<OperationNode>, options: TOptions['resolvedOptions']) => PossiblePromise<FabricReactNode | Array<FabricFile.File> | void>;
257
+ };
258
+ /**
259
+ * Defines a generator. Returns the object as-is with correct `this` typings.
260
+ * No type discrimination (`type: 'react' | 'core'`) needed — `applyHookResult`
261
+ * handles React elements and `File[]` uniformly.
262
+ */
263
+ declare function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(generator: Generator<TOptions>): Generator<TOptions>;
264
+ /**
265
+ * Merges an array of generators into a single generator.
266
+ *
267
+ * The merged generator's `schema`, `operation`, and `operations` methods run
268
+ * the corresponding method from each input generator in sequence, applying each
269
+ * result via `applyHookResult`. This eliminates the need to write the loop
270
+ * manually in each plugin.
271
+ *
272
+ * @param generators - Array of generators to merge into a single generator.
273
+ *
274
+ * @example
275
+ * ```ts
276
+ * const merged = mergeGenerators(generators)
277
+ *
278
+ * return {
279
+ * name: pluginName,
280
+ * schema: merged.schema,
281
+ * operation: merged.operation,
282
+ * operations: merged.operations,
283
+ * }
284
+ * ```
285
+ */
286
+ declare function mergeGenerators<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(generators: Array<Generator<TOptions>>): Generator<TOptions>;
287
+ //#endregion
288
+ //#region src/Kubb.d.ts
289
+ type DebugInfo = {
290
+ date: Date;
291
+ logs: Array<string>;
292
+ fileName?: string;
293
+ };
294
+ type HookProgress<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
295
+ hookName: H;
296
+ plugins: Array<Plugin>;
297
+ };
298
+ type HookExecution<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
299
+ strategy: Strategy;
300
+ hookName: H;
301
+ plugin: Plugin;
302
+ parameters?: Array<unknown>;
303
+ output?: unknown;
304
+ };
305
+ type HookResult<H extends PluginLifecycleHooks = PluginLifecycleHooks> = {
306
+ duration: number;
307
+ strategy: Strategy;
308
+ hookName: H;
309
+ plugin: Plugin;
310
+ parameters?: Array<unknown>;
311
+ output?: unknown;
312
+ };
313
+ /**
314
+ * Events emitted during the Kubb code generation lifecycle.
315
+ * These events can be listened to for logging, progress tracking, and custom integrations.
316
+ *
317
+ * @example
318
+ * ```typescript
319
+ * import type { AsyncEventEmitter } from '@internals/utils'
320
+ * import type { KubbEvents } from '@kubb/core'
321
+ *
322
+ * const events: AsyncEventEmitter<KubbEvents> = new AsyncEventEmitter()
323
+ *
324
+ * events.on('lifecycle:start', () => {
325
+ * console.log('Starting Kubb generation')
326
+ * })
327
+ *
328
+ * events.on('plugin:end', (plugin, { duration }) => {
329
+ * console.log(`Plugin ${plugin.name} completed in ${duration}ms`)
330
+ * })
331
+ * ```
332
+ */
333
+ interface KubbEvents {
334
+ /**
335
+ * Emitted at the beginning of the Kubb lifecycle, before any code generation starts.
336
+ */
337
+ 'lifecycle:start': [version: string];
338
+ /**
339
+ * Emitted at the end of the Kubb lifecycle, after all code generation is complete.
340
+ */
341
+ 'lifecycle:end': [];
342
+ /**
343
+ * Emitted when configuration loading starts.
344
+ */
345
+ 'config:start': [];
346
+ /**
347
+ * Emitted when configuration loading is complete.
348
+ */
349
+ 'config:end': [configs: Array<Config>];
350
+ /**
351
+ * Emitted when code generation phase starts.
352
+ */
353
+ 'generation:start': [config: Config];
354
+ /**
355
+ * Emitted when code generation phase completes.
356
+ */
357
+ 'generation:end': [config: Config, files: Array<FabricFile.ResolvedFile>, sources: Map<FabricFile.Path, string>];
358
+ /**
359
+ * Emitted with a summary of the generation results.
360
+ * Contains summary lines, title, and success status.
361
+ */
362
+ 'generation:summary': [config: Config, {
363
+ failedPlugins: Set<{
364
+ plugin: Plugin;
365
+ error: Error;
366
+ }>;
367
+ status: 'success' | 'failed';
368
+ hrStart: [number, number];
369
+ filesCreated: number;
370
+ pluginTimings?: Map<Plugin['name'], number>;
371
+ }];
372
+ /**
373
+ * Emitted when code formatting starts (e.g., running Biome or Prettier).
374
+ */
375
+ 'format:start': [];
376
+ /**
377
+ * Emitted when code formatting completes.
378
+ */
379
+ 'format:end': [];
380
+ /**
381
+ * Emitted when linting starts.
382
+ */
383
+ 'lint:start': [];
384
+ /**
385
+ * Emitted when linting completes.
386
+ */
387
+ 'lint:end': [];
388
+ /**
389
+ * Emitted when plugin hooks execution starts.
390
+ */
391
+ 'hooks:start': [];
392
+ /**
393
+ * Emitted when plugin hooks execution completes.
394
+ */
395
+ 'hooks:end': [];
396
+ /**
397
+ * Emitted when a single hook execution starts (e.g., format or lint).
398
+ * The callback should be invoked when the command completes.
399
+ */
400
+ 'hook:start': [{
401
+ id?: string;
402
+ command: string;
403
+ args?: readonly string[];
404
+ }];
405
+ /**
406
+ * Emitted when a single hook execution completes.
407
+ */
408
+ 'hook:end': [{
409
+ id?: string;
410
+ command: string;
411
+ args?: readonly string[];
412
+ success: boolean;
413
+ error: Error | null;
414
+ }];
415
+ /**
416
+ * Emitted when a new version of Kubb is available.
417
+ */
418
+ 'version:new': [currentVersion: string, latestVersion: string];
419
+ /**
420
+ * Informational message event.
421
+ */
422
+ info: [message: string, info?: string];
423
+ /**
424
+ * Error event. Emitted when an error occurs during code generation.
425
+ */
426
+ error: [error: Error, meta?: Record<string, unknown>];
427
+ /**
428
+ * Success message event.
429
+ */
430
+ success: [message: string, info?: string];
431
+ /**
432
+ * Warning message event.
433
+ */
434
+ warn: [message: string, info?: string];
435
+ /**
436
+ * Debug event for detailed logging.
437
+ * Contains timestamp, log messages, and optional filename.
438
+ */
439
+ debug: [info: DebugInfo];
440
+ /**
441
+ * Emitted when file processing starts.
442
+ * Contains the list of files to be processed.
443
+ */
444
+ 'files:processing:start': [files: Array<FabricFile.ResolvedFile>];
445
+ /**
446
+ * Emitted for each file being processed, providing progress updates.
447
+ * Contains processed count, total count, percentage, and file details.
448
+ */
449
+ 'file:processing:update': [{
450
+ /**
451
+ * Number of files processed so far.
452
+ */
453
+ processed: number;
454
+ /**
455
+ * Total number of files to process.
456
+ */
457
+ total: number;
458
+ /**
459
+ * Processing percentage (0–100).
460
+ */
461
+ percentage: number;
462
+ /**
463
+ * Optional source identifier.
464
+ */
465
+ source?: string;
466
+ /**
467
+ * The file being processed.
468
+ */
469
+ file: FabricFile.ResolvedFile;
470
+ /**
471
+ * Kubb configuration (not present in Fabric).
472
+ * Provides access to the current config during file processing.
473
+ */
474
+ config: Config;
475
+ }];
476
+ /**
477
+ * Emitted when file processing completes.
478
+ * Contains the list of processed files.
479
+ */
480
+ 'files:processing:end': [files: Array<FabricFile.ResolvedFile>];
481
+ /**
482
+ * Emitted when a plugin starts executing.
483
+ */
484
+ 'plugin:start': [plugin: Plugin];
485
+ /**
486
+ * Emitted when a plugin completes execution.
487
+ * Duration in ms.
488
+ */
489
+ 'plugin:end': [plugin: Plugin, result: {
490
+ duration: number;
491
+ success: boolean;
492
+ error?: Error;
493
+ }];
494
+ /**
495
+ * Emitted when plugin hook progress tracking starts.
496
+ * Contains the hook name and list of plugins to execute.
497
+ */
498
+ 'plugins:hook:progress:start': [progress: HookProgress];
499
+ /**
500
+ * Emitted when plugin hook progress tracking ends.
501
+ * Contains the hook name that completed.
502
+ */
503
+ 'plugins:hook:progress:end': [{
504
+ hookName: PluginLifecycleHooks;
505
+ }];
506
+ /**
507
+ * Emitted when a plugin hook starts processing.
508
+ * Contains strategy, hook name, plugin, parameters, and output.
509
+ */
510
+ 'plugins:hook:processing:start': [execution: HookExecution];
511
+ /**
512
+ * Emitted when a plugin hook completes processing.
513
+ * Contains duration, strategy, hook name, plugin, parameters, and output.
514
+ */
515
+ 'plugins:hook:processing:end': [result: HookResult];
516
+ }
517
+ //#endregion
518
+ //#region src/types.d.ts
519
+ declare global {
520
+ namespace Kubb {
521
+ interface PluginContext {}
522
+ /**
523
+ * Registry that maps plugin names to their `PluginFactoryOptions`.
524
+ * Augment this interface in each plugin's `types.ts` to enable automatic
525
+ * typing for `getPlugin` and `requirePlugin`.
526
+ *
527
+ * @example
528
+ * ```ts
529
+ * // packages/plugin-ts/src/types.ts
530
+ * declare global {
531
+ * namespace Kubb {
532
+ * interface PluginRegistry {
533
+ * 'plugin-ts': PluginTs
534
+ * }
535
+ * }
536
+ * }
537
+ * ```
538
+ */
539
+ interface PluginRegistry {}
540
+ }
541
+ }
542
+ /**
543
+ * Config used in `kubb.config.ts`
544
+ *
545
+ * @example
546
+ * import { defineConfig } from '@kubb/core'
547
+ * export default defineConfig({
548
+ * ...
549
+ * })
550
+ */
551
+ type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins'> & {
552
+ /**
553
+ * The project root directory, which can be either an absolute path or a path relative to the location of your `kubb.config.ts` file.
554
+ * @default process.cwd()
555
+ */
556
+ root?: string;
557
+ /**
558
+ * An array of Kubb plugins used for generation. Each plugin may have additional configurable options (defined within the plugin itself). If a plugin relies on another plugin, an error will occur if the required dependency is missing. Refer to “pre” for more details.
559
+ */
560
+ plugins?: Array<Omit<UnknownUserPlugin, 'inject'>>;
561
+ };
562
+ type InputPath = {
563
+ /**
564
+ * Specify your Swagger/OpenAPI file, either as an absolute path or a path relative to the root.
565
+ */
566
+ path: string;
567
+ };
568
+ type InputData = {
569
+ /**
570
+ * A `string` or `object` that contains your Swagger/OpenAPI data.
571
+ */
572
+ data: string | unknown;
573
+ };
574
+ type Input = InputPath | InputData | Array<InputPath>;
575
+ /**
576
+ * The raw source passed to an adapter's `parse` function.
577
+ * Mirrors the shape of `Config['input']` with paths already resolved to absolute.
578
+ */
579
+ type AdapterSource = {
580
+ type: 'path';
581
+ path: string;
582
+ } | {
583
+ type: 'data';
584
+ data: string | unknown;
585
+ } | {
586
+ type: 'paths';
587
+ paths: Array<string>;
588
+ };
589
+ /**
590
+ * Type parameters for an adapter definition.
591
+ *
592
+ * Mirrors `PluginFactoryOptions` but scoped to the adapter lifecycle:
593
+ * - `TName` — unique string identifier (e.g. `'oas'`, `'asyncapi'`)
594
+ * - `TOptions` — raw user-facing options passed to the adapter factory
595
+ * - `TResolvedOptions` — defaults applied; what the adapter stores as `options`
596
+ * - `TDocument` — type of the raw source document exposed by the adapter after `parse()`
597
+ */
598
+ type AdapterFactoryOptions<TName extends string = string, TOptions extends object = object, TResolvedOptions extends object = TOptions, TDocument = unknown> = {
599
+ name: TName;
600
+ options: TOptions;
601
+ resolvedOptions: TResolvedOptions;
602
+ document: TDocument;
603
+ };
604
+ /**
605
+ * An adapter converts a source file or data into a `@kubb/ast` `RootNode`.
606
+ *
607
+ * Adapters are the single entry-point for different schema formats
608
+ * (OpenAPI, AsyncAPI, Drizzle, …) and produce the universal `RootNode`
609
+ * that all Kubb plugins consume.
610
+ *
611
+ * @example
612
+ * ```ts
613
+ * import { oasAdapter } from '@kubb/adapter-oas'
614
+ *
615
+ * export default defineConfig({
616
+ * adapter: adapterOas(), // default — OpenAPI / Swagger
617
+ * input: { path: './openapi.yaml' },
618
+ * plugins: [pluginTs(), pluginZod()],
619
+ * })
620
+ * ```
621
+ */
622
+ type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {
623
+ /**
624
+ * Human-readable identifier, e.g. `'oas'`, `'drizzle'`, `'asyncapi'`.
625
+ */
626
+ name: TOptions['name'];
627
+ /**
628
+ * Resolved options (after defaults have been applied).
629
+ */
630
+ options: TOptions['resolvedOptions'];
631
+ /**
632
+ * The raw source document produced after the first `parse()` call.
633
+ * `undefined` before parsing; typed by the adapter's `TDocument` generic.
634
+ */
635
+ document: TOptions['document'] | null;
636
+ rootNode: RootNode | null;
637
+ /**
638
+ * Convert the raw source into a universal `RootNode`.
639
+ */
640
+ parse: (source: AdapterSource) => PossiblePromise<RootNode>;
641
+ /**
642
+ * Extracts `FabricFile.Import` entries needed by a `SchemaNode` tree.
643
+ * Populated after the first `parse()` call. Returns an empty array before that.
644
+ *
645
+ * The `resolve` callback receives the collision-corrected schema name and must
646
+ * return the `{ name, path }` pair for the import, or `undefined` to skip it.
647
+ */
648
+ getImports: (node: SchemaNode, resolve: (schemaName: string) => {
649
+ name: string;
650
+ path: string;
651
+ }) => Array<FabricFile.Import>;
652
+ };
653
+ type BarrelType = 'all' | 'named' | 'propagate';
654
+ type DevtoolsOptions = {
655
+ /**
656
+ * Open the AST inspector view (`/ast`) in Kubb Studio.
657
+ * When `false`, opens the main Studio page instead.
658
+ * @default false
659
+ */
660
+ ast?: boolean;
661
+ };
662
+ /**
663
+ * @private
664
+ */
665
+ type Config<TInput = Input> = {
666
+ /**
667
+ * The name to display in the CLI output.
668
+ */
669
+ name?: string;
670
+ /**
671
+ * The project root directory, which can be either an absolute path or a path relative to the location of your `kubb.config.ts` file.
672
+ * @default process.cwd()
673
+ */
674
+ root: string;
675
+ /**
676
+ * Adapter that converts the input file into a `@kubb/ast` `RootNode` — the universal
677
+ * intermediate representation consumed by all Kubb plugins.
678
+ *
679
+ * - Omit (or pass `undefined`) to use the built-in OpenAPI/Swagger adapter.
680
+ * - Use `@kubb/adapter-oas` for explicit OpenAPI configuration (validate, contentType, …).
681
+ * - Use `@kubb/adapter-drizzle` or `@kubb/adapter-asyncapi` for other formats.
682
+ *
683
+ * @example
684
+ * ```ts
685
+ * import { drizzleAdapter } from '@kubb/adapter-drizzle'
686
+ * export default defineConfig({
687
+ * adapter: drizzleAdapter(),
688
+ * input: { path: './src/schema.ts' },
689
+ * })
690
+ * ```
691
+ */
692
+ adapter?: Adapter;
693
+ /**
694
+ * You can use either `input.path` or `input.data`, depending on your specific needs.
695
+ */
696
+ input: TInput;
697
+ output: {
698
+ /**
699
+ * The path where all generated files receives exported.
700
+ * This can be an absolute path or a path relative to the specified root option.
701
+ */
702
+ path: string;
703
+ /**
704
+ * Clean the output directory before each build.
705
+ */
706
+ clean?: boolean;
707
+ /**
708
+ * Save files to the file system.
709
+ * @default true
710
+ * @deprecated Use `storage` to control where files are written.
711
+ */
712
+ write?: boolean;
713
+ /**
714
+ * Storage backend for generated files.
715
+ * Defaults to `fsStorage()` — the built-in filesystem driver.
716
+ * Accepts any object implementing the {@link Storage} interface.
717
+ * Keys are root-relative paths (e.g. `src/gen/api/getPets.ts`).
718
+ * @default fsStorage()
719
+ * @example
720
+ * ```ts
721
+ * import { memoryStorage } from '@kubb/core'
722
+ * storage: memoryStorage()
723
+ * ```
724
+ */
725
+ storage?: Storage;
726
+ /**
727
+ * Specifies the formatting tool to be used.
728
+ * - 'auto' automatically detects and uses biome or prettier (in that order of preference).
729
+ * - 'prettier' uses Prettier for code formatting.
730
+ * - 'biome' uses Biome for code formatting.
731
+ * - 'oxfmt' uses Oxfmt for code formatting.
732
+ * - false disables code formatting.
733
+ * @default 'prettier'
734
+ */
735
+ format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false;
736
+ /**
737
+ * Specifies the linter that should be used to analyze the code.
738
+ * - 'auto' automatically detects and uses biome, oxlint, or eslint (in that order of preference).
739
+ * - 'eslint' uses ESLint for linting.
740
+ * - 'biome' uses Biome for linting.
741
+ * - 'oxlint' uses Oxlint for linting.
742
+ * - false disables linting.
743
+ * @default 'auto'
744
+ */
745
+ lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false;
746
+ /**
747
+ * Overrides the extension for generated imports and exports. By default, each plugin adds an extension.
748
+ * @default { '.ts': '.ts'}
749
+ */
750
+ extension?: Record<FabricFile.Extname, FabricFile.Extname | ''>;
751
+ /**
752
+ * Configures how `index.ts` files are created, including disabling barrel file generation. Each plugin has its own `barrelType` option; this setting controls the root barrel file (e.g., `src/gen/index.ts`).
753
+ * @default 'named'
754
+ */
755
+ barrelType?: 'all' | 'named' | false;
756
+ /**
757
+ * Adds a default banner to the start of every generated file indicating it was generated by Kubb.
758
+ * - 'simple' adds banner with link to Kubb.
759
+ * - 'full' adds source, title, description, and OpenAPI version.
760
+ * - false disables banner generation.
761
+ * @default 'simple'
762
+ */
763
+ defaultBanner?: 'simple' | 'full' | false;
764
+ /**
765
+ * Whether to override existing external files if they already exist.
766
+ * When setting the option in the global configuration, all plugins inherit the same behavior by default.
767
+ * However, all plugins also have an `output.override` option, which can be used to override the behavior for a specific plugin.
768
+ * @default false
769
+ */
770
+ override?: boolean;
771
+ };
772
+ /**
773
+ * An array of Kubb plugins that used in the generation.
774
+ * Each plugin may include additional configurable options(defined in the plugin itself).
775
+ * If a plugin depends on another plugin, an error is returned if the required dependency is missing. See pre for more details.
776
+ */
777
+ plugins: Array<Plugin>;
778
+ /**
779
+ * Devtools configuration for Kubb Studio integration.
780
+ */
781
+ devtools?: true | {
782
+ /**
783
+ * Override the Kubb Studio base URL.
784
+ * @default 'https://studio.kubb.dev'
785
+ */
786
+ studioUrl?: typeof DEFAULT_STUDIO_URL | (string & {});
787
+ };
788
+ /**
789
+ * Hooks triggered when a specific action occurs in Kubb.
790
+ */
791
+ hooks?: {
792
+ /**
793
+ * Hook that triggers at the end of all executions.
794
+ * Useful for running Prettier or ESLint to format/lint your code.
795
+ */
796
+ done?: string | Array<string>;
797
+ };
798
+ };
799
+ /**
800
+ * A type/string-pattern filter used for `include`, `exclude`, and `override` matching.
801
+ */
802
+ type PatternFilter = {
803
+ type: string;
804
+ pattern: string | RegExp;
805
+ };
806
+ /**
807
+ * A pattern filter paired with partial option overrides to apply when the pattern matches.
808
+ */
809
+ type PatternOverride<TOptions> = PatternFilter & {
810
+ options: Omit<Partial<TOptions>, 'override'>;
811
+ };
812
+ /**
813
+ * Context passed to `resolver.resolveOptions` to apply include/exclude/override filtering
814
+ * for a given operation or schema node.
815
+ */
816
+ type ResolveOptionsContext<TOptions> = {
817
+ options: TOptions;
818
+ exclude?: Array<PatternFilter>;
819
+ include?: Array<PatternFilter>;
820
+ override?: Array<PatternOverride<TOptions>>;
821
+ };
822
+ /**
823
+ * Base constraint for all plugin resolver objects.
824
+ *
825
+ * `default`, `resolveOptions`, `resolvePath`, and `resolveFile` are injected automatically
826
+ * by `defineResolver` — plugin authors may override them but never need to implement them
827
+ * from scratch.
828
+ *
829
+ * @example
830
+ * ```ts
831
+ * type MyResolver = Resolver & {
832
+ * resolveName(node: SchemaNode): string
833
+ * resolveTypedName(node: SchemaNode): string
834
+ * }
835
+ * ```
836
+ */
837
+ type Resolver = {
838
+ name: string;
839
+ pluginName: Plugin['name'];
840
+ default(name: ResolveNameParams['name'], type?: ResolveNameParams['type']): string;
841
+ resolveOptions<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null;
842
+ resolvePath(params: ResolverPathParams, context: ResolverContext): FabricFile.Path;
843
+ resolveFile(params: ResolverFileParams, context: ResolverContext): FabricFile.File;
844
+ resolveBanner(node: RootNode | null, context: ResolveBannerContext): string | undefined;
845
+ resolveFooter(node: RootNode | null, context: ResolveBannerContext): string | undefined;
846
+ };
847
+ /**
848
+ * The user-facing subset of a `Resolver` — everything except the four methods injected by
849
+ * `defineResolver` (`default`, `resolveOptions`, `resolvePath`, and `resolveFile`).
850
+ *
851
+ * All four injected methods can still be overridden by providing them explicitly in the builder.
852
+ *
853
+ * @example
854
+ * ```ts
855
+ * export const resolver = defineResolver<PluginTs>(() => ({
856
+ * name: 'default',
857
+ * resolveName(node) { return this.default(node.name, 'function') },
858
+ * }))
859
+ * ```
860
+ */
861
+ type UserResolver = Omit<Resolver, 'default' | 'resolveOptions' | 'resolvePath' | 'resolveFile' | 'resolveBanner' | 'resolveFooter'>;
862
+ type PluginFactoryOptions<
863
+ /**
864
+ * Name to be used for the plugin.
865
+ */
866
+ TName extends string = string,
867
+ /**
868
+ * Options of the plugin.
869
+ */
870
+ TOptions extends object = object,
871
+ /**
872
+ * Options of the plugin that can be used later on, see `options` inside your plugin config.
873
+ */
874
+ TResolvedOptions extends object = TOptions,
875
+ /**
876
+ * Context that you want to expose to other plugins.
877
+ */
878
+ TContext = unknown,
879
+ /**
880
+ * When calling `resolvePath` you can specify better types.
881
+ */
882
+ TResolvePathOptions extends object = object,
883
+ /**
884
+ * Resolver object that encapsulates the naming and path-resolution helpers used by this plugin.
885
+ * Use `defineResolver` to define the resolver object and export it alongside the plugin.
886
+ */
887
+ TResolver extends Resolver = Resolver> = {
888
+ name: TName;
889
+ options: TOptions;
890
+ resolvedOptions: TResolvedOptions;
891
+ context: TContext;
892
+ resolvePathOptions: TResolvePathOptions;
893
+ resolver: TResolver;
894
+ };
895
+ type UserPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
896
+ /**
897
+ * Unique name used for the plugin
898
+ * The name of the plugin follows the format scope:foo-bar or foo-bar, adding scope: can avoid naming conflicts with other plugins.
899
+ * @example @kubb/typescript
900
+ */
901
+ name: TOptions['name'];
902
+ /**
903
+ * Options set for a specific plugin(see kubb.config.js), passthrough of options.
904
+ */
905
+ options: TOptions['resolvedOptions'] & {
906
+ output: Output;
907
+ include?: Array<Include>;
908
+ exclude: Array<Exclude>;
909
+ override: Array<Override<TOptions['resolvedOptions']>>;
910
+ };
911
+ /**
912
+ * The resolver for this plugin.
913
+ * Composed by `getPreset` from the preset resolver and the user's `resolver` partial override.
914
+ */
915
+ resolver?: TOptions['resolver'];
916
+ /**
917
+ * The composed transformer for this plugin.
918
+ * Composed by `getPreset` from the preset's transformers and the user's `transformer` visitor.
919
+ * When a visitor method returns `null`/`undefined`, the preset transformer's result is used instead.
920
+ */
921
+ transformer?: Visitor;
922
+ /**
923
+ * Specifies the preceding plugins for the current plugin. You can pass an array of preceding plugin names, and the current plugin is executed after these plugins.
924
+ * Can be used to validate dependent plugins.
925
+ */
926
+ pre?: Array<string>;
927
+ /**
928
+ * Specifies the succeeding plugins for the current plugin. You can pass an array of succeeding plugin names, and the current plugin is executed before these plugins.
929
+ */
930
+ post?: Array<string>;
931
+ /**
932
+ * When `apply` is defined, the plugin is only activated when `apply(config)` returns `true`.
933
+ * Inspired by Vite's `apply` option.
934
+ *
935
+ * @example
936
+ * ```ts
937
+ * apply: (config) => config.output.path !== 'disabled'
938
+ * ```
939
+ */
940
+ apply?: (config: Config) => boolean;
941
+ /**
942
+ * Expose shared helpers or data to all other plugins via `PluginContext`.
943
+ * The object returned is merged into the context that every plugin receives.
944
+ * Use the `declare global { namespace Kubb { interface PluginContext { … } } }` pattern
945
+ * to make the injected properties type-safe.
946
+ *
947
+ * @example
948
+ * ```ts
949
+ * inject() {
950
+ * return { getOas: () => parseSpec(this.config) }
951
+ * }
952
+ * // Other plugins can then call `this.getOas()` inside buildStart()
953
+ * ```
954
+ */
955
+ inject?: (this: PluginContext<TOptions>) => TOptions['context'];
956
+ };
957
+ type UserPluginWithLifeCycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = UserPlugin<TOptions> & PluginLifecycle<TOptions>;
958
+ type UnknownUserPlugin = UserPlugin<PluginFactoryOptions<string, object, object, unknown, object>>;
959
+ /**
960
+ * Handler for a single schema node. Used by the `schema` hook on a plugin.
961
+ */
962
+ type SchemaHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, node: SchemaNode, options: TOptions['resolvedOptions']) => PossiblePromise<FabricReactNode | Array<FabricFile.File> | void>;
963
+ /**
964
+ * Handler for a single operation node. Used by the `operation` hook on a plugin.
965
+ */
966
+ type OperationHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, node: OperationNode, options: TOptions['resolvedOptions']) => PossiblePromise<FabricReactNode | Array<FabricFile.File> | void>;
967
+ /**
968
+ * Handler for all collected operation nodes. Used by the `operations` hook on a plugin.
969
+ */
970
+ type OperationsHook<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = (this: GeneratorContext<TOptions>, nodes: Array<OperationNode>, options: TOptions['resolvedOptions']) => PossiblePromise<FabricReactNode | Array<FabricFile.File> | void>;
971
+ type Plugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
972
+ /**
973
+ * Unique name used for the plugin
974
+ * @example @kubb/typescript
975
+ */
976
+ name: TOptions['name'];
977
+ /**
978
+ * Specifies the preceding plugins for the current plugin. You can pass an array of preceding plugin names, and the current plugin is executed after these plugins.
979
+ * Can be used to validate dependent plugins.
980
+ */
981
+ pre?: Array<string>;
982
+ /**
983
+ * Specifies the succeeding plugins for the current plugin. You can pass an array of succeeding plugin names, and the current plugin is executed before these plugins.
984
+ */
985
+ post?: Array<string>;
986
+ /**
987
+ * Options set for a specific plugin(see kubb.config.js), passthrough of options.
988
+ */
989
+ options: TOptions['resolvedOptions'] & {
990
+ output: Output;
991
+ include?: Array<Include>;
992
+ exclude: Array<Exclude>;
993
+ override: Array<Override<TOptions['resolvedOptions']>>;
994
+ };
995
+ /**
996
+ * The resolver for this plugin.
997
+ * Composed by `getPreset` from the preset resolver and the user's `resolver` partial override.
998
+ */
999
+ resolver: TOptions['resolver'];
1000
+ /**
1001
+ * The composed transformer for this plugin. Accessible via `context.transformer`.
1002
+ * Composed by `getPreset` from the preset's transformers and the user's `transformer` visitor.
1003
+ * When a visitor method returns `null`/`undefined`, the preset transformer's result is used instead.
1004
+ */
1005
+ transformer?: Visitor;
1006
+ /**
1007
+ * When `apply` is defined, the plugin is only activated when `apply(config)` returns `true`.
1008
+ * Inspired by Vite's `apply` option.
1009
+ */
1010
+ apply?: (config: Config) => boolean;
1011
+ /**
1012
+ * Optional semver version string for this plugin, e.g. `"1.2.3"`.
1013
+ * Used in diagnostic messages and version-conflict detection.
1014
+ */
1015
+ version?: string;
1016
+ buildStart: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1017
+ /**
1018
+ * Called once per plugin after all files have been written to disk.
1019
+ * Use this for post-processing, copying assets, or generating summary reports.
1020
+ */
1021
+ buildEnd: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1022
+ /**
1023
+ * Called for each schema node during the AST walk.
1024
+ * Return a React element, an array of `FabricFile.File`, or `void` for manual handling.
1025
+ * Nodes matching `exclude`/`include` filters are skipped automatically.
1026
+ *
1027
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1028
+ */
1029
+ schema?: SchemaHook<TOptions>;
1030
+ /**
1031
+ * Called for each operation node during the AST walk.
1032
+ * Return a React element, an array of `FabricFile.File`, or `void` for manual handling.
1033
+ *
1034
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1035
+ */
1036
+ operation?: OperationHook<TOptions>;
1037
+ /**
1038
+ * Called once after all operations have been walked, with the full collected set.
1039
+ *
1040
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1041
+ */
1042
+ operations?: OperationsHook<TOptions>;
1043
+ /**
1044
+ * Expose shared helpers or data to all other plugins via `PluginContext`.
1045
+ * The returned object is merged into the context received by every plugin.
1046
+ */
1047
+ inject: (this: PluginContext<TOptions>) => TOptions['context'];
1048
+ };
1049
+ type PluginWithLifeCycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & PluginLifecycle<TOptions>;
1050
+ type PluginLifecycle<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1051
+ /**
1052
+ * Called once per plugin at the start of its processing phase, before schema/operation/operations hooks run.
1053
+ * Use this to set up shared state, fetch remote data, or perform any async initialization.
1054
+ * @type hookParallel
1055
+ */
1056
+ buildStart?: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1057
+ /**
1058
+ * Called once per plugin after all files have been written to disk.
1059
+ * Use this for post-processing, copying assets, or generating summary reports.
1060
+ * @type hookParallel
1061
+ */
1062
+ buildEnd?: (this: PluginContext<TOptions>) => PossiblePromise<void>;
1063
+ /**
1064
+ * Called for each schema node during the AST walk.
1065
+ * Return a React element (`<File>...</File>`), an array of `FabricFile.File` objects,
1066
+ * or `void` to handle file writing manually via `this.upsertFile`.
1067
+ * Nodes matching `exclude` / `include` filters are skipped automatically.
1068
+ *
1069
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1070
+ */
1071
+ schema?: SchemaHook<TOptions>;
1072
+ /**
1073
+ * Called for each operation node during the AST walk.
1074
+ * Return a React element (`<File>...</File>`), an array of `FabricFile.File` objects,
1075
+ * or `void` to handle file writing manually via `this.upsertFile`.
1076
+ *
1077
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1078
+ */
1079
+ operation?: OperationHook<TOptions>;
1080
+ /**
1081
+ * Called once after all operation nodes have been walked, with the full collection.
1082
+ * Useful for generating index/barrel files per group or aggregate operation handlers.
1083
+ *
1084
+ * For multiple generators, use `composeGenerators` inside the plugin factory.
1085
+ */
1086
+ operations?: OperationsHook<TOptions>;
1087
+ /**
1088
+ * Resolve to a Path based on a baseName(example: `./Pet.ts`) and directory(example: `./models`).
1089
+ * Options can als be included.
1090
+ * @type hookFirst
1091
+ * @example ('./Pet.ts', './src/gen/') => '/src/gen/Pet.ts'
1092
+ * @deprecated this will be replaced by resolvers
1093
+ */
1094
+ resolvePath?: (this: PluginContext<TOptions>, baseName: FabricFile.BaseName, mode?: FabricFile.Mode, options?: TOptions['resolvePathOptions']) => FabricFile.Path;
1095
+ /**
1096
+ * Resolve to a name based on a string.
1097
+ * Useful when converting to PascalCase or camelCase.
1098
+ * @type hookFirst
1099
+ * @example ('pet') => 'Pet'
1100
+ * @deprecated this will be replaced by resolvers
1101
+ */
1102
+ resolveName?: (this: PluginContext<TOptions>, name: ResolveNameParams['name'], type?: ResolveNameParams['type']) => string;
1103
+ };
1104
+ type PluginLifecycleHooks = keyof PluginLifecycle;
1105
+ type PluginParameter<H extends PluginLifecycleHooks> = Parameters<Required<PluginLifecycle>[H]>;
1106
+ type ResolvePathParams<TOptions = object> = {
1107
+ pluginName?: string;
1108
+ baseName: FabricFile.BaseName;
1109
+ mode?: FabricFile.Mode;
1110
+ /**
1111
+ * Options to be passed to 'resolvePath' 3th parameter
1112
+ */
1113
+ options?: TOptions;
1114
+ };
1115
+ type ResolveNameParams = {
1116
+ name: string;
1117
+ pluginName?: string;
1118
+ /**
1119
+ * Specifies the type of entity being named.
1120
+ * - 'file' customizes the name of the created file (uses camelCase).
1121
+ * - 'function' customizes the exported function names (uses camelCase).
1122
+ * - 'type' customizes TypeScript types (uses PascalCase).
1123
+ * - 'const' customizes variable names (uses camelCase).
1124
+ * @default undefined
1125
+ */
1126
+ type?: 'file' | 'function' | 'type' | 'const';
1127
+ };
1128
+ type PluginContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {
1129
+ fabric: Fabric;
1130
+ config: Config;
1131
+ /**
1132
+ * Absolute path to the output directory for the current plugin.
1133
+ * Shorthand for `path.resolve(config.root, config.output.path)`.
1134
+ */
1135
+ root: string;
1136
+ /**
1137
+ * Returns the output mode for the given output config.
1138
+ * Returns `'single'` when `output.path` has a file extension, `'split'` otherwise.
1139
+ * Shorthand for `getMode(path.resolve(this.root, output.path))`.
1140
+ */
1141
+ getMode: (output: {
1142
+ path: string;
1143
+ }) => FabricFile.Mode;
1144
+ driver: PluginDriver;
1145
+ /**
1146
+ * Get a plugin by name. Returns the plugin typed via `Kubb.PluginRegistry` when
1147
+ * the name is a registered key, otherwise returns the generic `Plugin`.
1148
+ */
1149
+ getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
1150
+ getPlugin(name: string): Plugin | undefined;
1151
+ /**
1152
+ * Like `getPlugin` but throws a descriptive error when the plugin is not found.
1153
+ * Useful for enforcing dependencies inside `buildStart()`.
1154
+ */
1155
+ requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>;
1156
+ requirePlugin(name: string): Plugin;
1157
+ /**
1158
+ * Only add when the file does not exist yet
1159
+ */
1160
+ addFile: (...file: Array<FabricFile.File>) => Promise<void>;
1161
+ /**
1162
+ * merging multiple sources into the same output file
1163
+ */
1164
+ upsertFile: (...file: Array<FabricFile.File>) => Promise<void>;
1165
+ /**
1166
+ * @deprecated use this.warn, this.error, this.info instead
1167
+ */
1168
+ events: AsyncEventEmitter<KubbEvents>;
1169
+ /**
1170
+ * Current plugin
1171
+ */
1172
+ plugin: Plugin<TOptions>;
1173
+ /**
1174
+ * Resolver for the current plugin. Shorthand for `plugin.resolver`.
1175
+ */
1176
+ resolver: TOptions['resolver'];
1177
+ /**
1178
+ * Composed transformer for the current plugin. Shorthand for `plugin.transformer`.
1179
+ * Apply with `transform(node, context.transformer)` to pre-process AST nodes before printing.
1180
+ */
1181
+ transformer: Visitor | undefined;
1182
+ /**
1183
+ * Emit a warning via the build event system.
1184
+ * Shorthand for `this.events.emit('warn', message)`.
1185
+ */
1186
+ warn: (message: string) => void;
1187
+ /**
1188
+ * Emit an error via the build event system.
1189
+ * Shorthand for `this.events.emit('error', error)`.
1190
+ */
1191
+ error: (error: string | Error) => void;
1192
+ /**
1193
+ * Emit an info message via the build event system.
1194
+ * Shorthand for `this.events.emit('info', message)`.
1195
+ */
1196
+ info: (message: string) => void;
1197
+ /**
1198
+ * Opens the Kubb Studio URL for the current `rootNode` in the default browser.
1199
+ * Falls back to printing the URL if the browser cannot be launched.
1200
+ * No-ops silently when no adapter has set a `rootNode`.
1201
+ */
1202
+ openInStudio: (options?: DevtoolsOptions) => Promise<void>;
1203
+ } & ({
1204
+ /**
1205
+ * Returns the universal `@kubb/ast` `RootNode` produced by the configured adapter.
1206
+ * Returns `undefined` when no adapter was set (legacy OAS-only usage).
1207
+ */
1208
+ rootNode: RootNode;
1209
+ /**
1210
+ * Return the adapter from `@kubb/ast`
1211
+ */
1212
+ adapter: Adapter;
1213
+ } | {
1214
+ rootNode?: never;
1215
+ adapter?: never;
1216
+ }) & Kubb.PluginContext;
1217
+ /**
1218
+ * Narrowed `PluginContext` used as the `this` type inside generator and plugin AST hook methods.
1219
+ *
1220
+ * Generators and the `schema`/`operation`/`operations` plugin hooks are only invoked from
1221
+ * `runPluginAstHooks`, which already guards against a missing adapter. This type reflects
1222
+ * that guarantee — `this.adapter` and `this.rootNode` are always defined, so no runtime
1223
+ * checks or casts are needed inside the method bodies.
1224
+ */
1225
+ type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Omit<PluginContext<TOptions>, 'adapter' | 'rootNode'> & {
1226
+ adapter: Adapter;
1227
+ rootNode: RootNode;
1228
+ };
1229
+ /**
1230
+ * Specify the export location for the files and define the behavior of the output
1231
+ */
1232
+ type Output<_TOptions = unknown> = {
1233
+ /**
1234
+ * Path to the output folder or file that will contain the generated code
1235
+ */
1236
+ path: string;
1237
+ /**
1238
+ * Define what needs to be exported, here you can also disable the export of barrel files
1239
+ * @default 'named'
1240
+ */
1241
+ barrelType?: BarrelType | false;
1242
+ /**
1243
+ * Add a banner text in the beginning of every file
1244
+ */
1245
+ banner?: string | ((node?: RootNode) => string);
1246
+ /**
1247
+ * Add a footer text in the beginning of every file
1248
+ */
1249
+ footer?: string | ((node?: RootNode) => string);
1250
+ /**
1251
+ * Whether to override existing external files if they already exist.
1252
+ * @default false
1253
+ */
1254
+ override?: boolean;
1255
+ };
1256
+ type UserGroup = {
1257
+ /**
1258
+ * Defines the type where to group the files.
1259
+ * - 'tag' groups files by OpenAPI tags.
1260
+ * - 'path' groups files by OpenAPI paths.
1261
+ * @default undefined
1262
+ */
1263
+ type: 'tag' | 'path';
1264
+ /**
1265
+ * Return the name of a group based on the group name, this is used for the file and name generation.
1266
+ */
1267
+ name?: (context: {
1268
+ group: string;
1269
+ }) => string;
1270
+ };
1271
+ type Group = {
1272
+ /**
1273
+ * Defines the type where to group the files.
1274
+ * - 'tag' groups files by OpenAPI tags.
1275
+ * - 'path' groups files by OpenAPI paths.
1276
+ * @default undefined
1277
+ */
1278
+ type: 'tag' | 'path';
1279
+ /**
1280
+ * Return the name of a group based on the group name, this is used for the file and name generation.
1281
+ */
1282
+ name: (context: {
1283
+ group: string;
1284
+ }) => string;
1285
+ };
1286
+ type LoggerOptions = {
1287
+ /**
1288
+ * @default 3
1289
+ */
1290
+ logLevel: (typeof logLevel)[keyof typeof logLevel];
1291
+ };
1292
+ /**
1293
+ * Shared context passed to all plugins, parsers, and Fabric internals.
1294
+ */
1295
+ type LoggerContext = AsyncEventEmitter<KubbEvents>;
1296
+ type Logger<TOptions extends LoggerOptions = LoggerOptions> = {
1297
+ name: string;
1298
+ install: (context: LoggerContext, options?: TOptions) => void | Promise<void>;
1299
+ };
1300
+ type UserLogger<TOptions extends LoggerOptions = LoggerOptions> = Logger<TOptions>;
1301
+ /**
1302
+ * Compatibility preset for code generation tools.
1303
+ * - `'default'` – no compatibility adjustments (default behavior).
1304
+ * - `'kubbV4'` – align generated names and structures with Kubb v4 output.
1305
+ */
1306
+ type CompatibilityPreset = 'default' | 'kubbV4';
1307
+ /**
1308
+ * A preset bundles a name, a resolver, optional AST transformers,
1309
+ * and optional generators into a single reusable configuration object.
1310
+ *
1311
+ * @template TResolver - The concrete resolver type for this preset.
1312
+ */
1313
+ type Preset<TResolver extends Resolver = Resolver> = {
1314
+ /**
1315
+ * Unique identifier for this preset.
1316
+ */
1317
+ name: string;
1318
+ /**
1319
+ * The resolver used by this preset.
1320
+ */
1321
+ resolver: TResolver;
1322
+ /**
1323
+ * Optional AST visitors / transformers applied after resolving.
1324
+ */
1325
+ transformers?: Array<Visitor>;
1326
+ /**
1327
+ * Optional generators used by this preset. Plugin implementations cast this
1328
+ * to their concrete generator type.
1329
+ */
1330
+ generators?: Array<Generator<any>>;
1331
+ /**
1332
+ * Optional printer factory used by this preset.
1333
+ * The generator calls this function at render-time to produce a configured printer instance.
1334
+ */
1335
+ printer?: (options: any) => Printer;
1336
+ };
1337
+ /**
1338
+ * A named registry of presets, keyed by preset name.
1339
+ *
1340
+ * @template TResolver - The concrete resolver type shared by all presets in this registry.
1341
+ * @template TName - The union of valid preset name keys.
1342
+ */
1343
+ type Presets<TResolver extends Resolver = Resolver> = Record<CompatibilityPreset, Preset<TResolver>>;
1344
+ type ByTag = {
1345
+ type: 'tag';
1346
+ pattern: string | RegExp;
1347
+ };
1348
+ type ByOperationId = {
1349
+ type: 'operationId';
1350
+ pattern: string | RegExp;
1351
+ };
1352
+ type ByPath = {
1353
+ type: 'path';
1354
+ pattern: string | RegExp;
1355
+ };
1356
+ type ByMethod = {
1357
+ type: 'method';
1358
+ pattern: HttpMethod | RegExp;
1359
+ };
1360
+ type BySchemaName = {
1361
+ type: 'schemaName';
1362
+ pattern: string | RegExp;
1363
+ };
1364
+ type ByContentType = {
1365
+ type: 'contentType';
1366
+ pattern: string | RegExp;
1367
+ };
1368
+ type Exclude = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
1369
+ type Include = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName;
1370
+ type Override<TOptions> = (ByTag | ByOperationId | ByPath | ByMethod | BySchemaName | ByContentType) & {
1371
+ options: Partial<TOptions>;
1372
+ };
1373
+ type ResolvePathOptions = {
1374
+ pluginName?: string;
1375
+ group?: {
1376
+ tag?: string;
1377
+ path?: string;
1378
+ };
1379
+ type?: ResolveNameParams['type'];
1380
+ };
1381
+ /**
1382
+ * File-specific parameters for `Resolver.resolvePath`.
1383
+ *
1384
+ * Pass alongside a `ResolverContext` to identify which file to resolve.
1385
+ * Provide `tag` for tag-based grouping or `path` for path-based grouping.
1386
+ *
1387
+ * @example
1388
+ * ```ts
1389
+ * resolver.resolvePath(
1390
+ * { baseName: 'petTypes.ts', tag: 'pets' },
1391
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
1392
+ * )
1393
+ * // → '/src/types/petsController/petTypes.ts'
1394
+ * ```
1395
+ */
1396
+ type ResolverPathParams = {
1397
+ baseName: FabricFile.BaseName;
1398
+ pathMode?: FabricFile.Mode;
1399
+ /**
1400
+ * Tag value used when `group.type === 'tag'`.
1401
+ */
1402
+ tag?: string;
1403
+ /**
1404
+ * Path value used when `group.type === 'path'`.
1405
+ */
1406
+ path?: string;
1407
+ };
1408
+ /**
1409
+ * Shared context passed as the second argument to `Resolver.resolvePath` and `Resolver.resolveFile`.
1410
+ *
1411
+ * Describes where on disk output is rooted, which output config is active, and the optional
1412
+ * grouping strategy that controls subdirectory layout.
1413
+ *
1414
+ * @example
1415
+ * ```ts
1416
+ * const context: ResolverContext = {
1417
+ * root: config.root,
1418
+ * output,
1419
+ * group,
1420
+ * }
1421
+ * ```
1422
+ */
1423
+ type ResolverContext = {
1424
+ root: string;
1425
+ output: Output;
1426
+ group?: Group;
1427
+ /**
1428
+ * Plugin name used to populate `meta.pluginName` on the resolved file.
1429
+ */
1430
+ pluginName?: string;
1431
+ };
1432
+ /**
1433
+ * File-specific parameters for `Resolver.resolveFile`.
1434
+ *
1435
+ * Pass alongside a `ResolverContext` to fully describe the file to resolve.
1436
+ * `tag` and `path` are used only when a matching `group` is present in the context.
1437
+ *
1438
+ * @example
1439
+ * ```ts
1440
+ * resolver.resolveFile(
1441
+ * { name: 'listPets', extname: '.ts', tag: 'pets' },
1442
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
1443
+ * )
1444
+ * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }
1445
+ * ```
1446
+ */
1447
+ type ResolverFileParams = {
1448
+ name: string;
1449
+ extname: FabricFile.Extname;
1450
+ /**
1451
+ * Tag value used when `group.type === 'tag'`.
1452
+ */
1453
+ tag?: string;
1454
+ /**
1455
+ * Path value used when `group.type === 'path'`.
1456
+ */
1457
+ path?: string;
1458
+ };
1459
+ /**
1460
+ * Context passed to `Resolver.resolveBanner` and `Resolver.resolveFooter`.
1461
+ *
1462
+ * `output` is optional — not every plugin configures a banner/footer.
1463
+ * `config` carries the global Kubb config, used to derive the default Kubb banner.
1464
+ *
1465
+ * @example
1466
+ * ```ts
1467
+ * resolver.resolveBanner(rootNode, { output: { banner: '// generated' }, config })
1468
+ * // → '// generated'
1469
+ * ```
1470
+ */
1471
+ type ResolveBannerContext = {
1472
+ output?: Pick<Output, 'banner' | 'footer'>;
1473
+ config: Config;
1474
+ };
1475
+ //#endregion
1476
+ //#region src/PluginDriver.d.ts
1477
+ type RequiredPluginLifecycle = Required<PluginLifecycle>;
1478
+ /**
1479
+ * Hook dispatch strategy used by the `PluginDriver`.
1480
+ *
1481
+ * - `hookFirst` — stops at the first non-null result.
1482
+ * - `hookForPlugin` — calls only the matching plugin.
1483
+ * - `hookParallel` — calls all plugins concurrently.
1484
+ * - `hookSeq` — calls all plugins in order, threading the result.
1485
+ */
1486
+ type Strategy = 'hookFirst' | 'hookForPlugin' | 'hookParallel' | 'hookSeq';
1487
+ type ParseResult<H extends PluginLifecycleHooks> = RequiredPluginLifecycle[H];
1488
+ type SafeParseResult<H extends PluginLifecycleHooks, Result = ReturnType<ParseResult<H>>> = {
1489
+ result: Result;
1490
+ plugin: Plugin;
1491
+ };
1492
+ type Options = {
1493
+ fabric: Fabric;
1494
+ events: AsyncEventEmitter<KubbEvents>;
1495
+ /**
1496
+ * @default Number.POSITIVE_INFINITY
1497
+ */
1498
+ concurrency?: number;
1499
+ };
1500
+ /**
1501
+ * Parameters accepted by `PluginDriver.getFile` to resolve a generated file descriptor.
1502
+ */
1503
+ type GetFileOptions<TOptions = object> = {
1504
+ name: string;
1505
+ mode?: FabricFile.Mode;
1506
+ extname: FabricFile.Extname;
1507
+ pluginName: string;
1508
+ options?: TOptions;
1509
+ };
1510
+ /**
1511
+ * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
1512
+ *
1513
+ * @example
1514
+ * ```ts
1515
+ * getMode('src/gen/types.ts') // 'single'
1516
+ * getMode('src/gen/types') // 'split'
1517
+ * ```
1518
+ */
1519
+ declare function getMode(fileOrFolder: string | undefined | null): FabricFile.Mode;
1520
+ declare class PluginDriver {
1521
+ #private;
1522
+ readonly config: Config;
1523
+ readonly options: Options;
1524
+ /**
1525
+ * The universal `@kubb/ast` `RootNode` produced by the adapter, set by
1526
+ * the build pipeline after the adapter's `parse()` resolves.
1527
+ */
1528
+ rootNode: RootNode | undefined;
1529
+ adapter: Adapter | undefined;
1530
+ readonly plugins: Map<string, Plugin>;
1531
+ constructor(config: Config, options: Options);
1532
+ get events(): AsyncEventEmitter<KubbEvents>;
1533
+ getContext<TOptions extends PluginFactoryOptions>(plugin: Plugin<TOptions>): PluginContext<TOptions> & Record<string, unknown>;
1534
+ /**
1535
+ * @deprecated use resolvers context instead
1536
+ */
1537
+ getFile<TOptions = object>({
1538
+ name,
1539
+ mode,
1540
+ extname,
1541
+ pluginName,
1542
+ options
1543
+ }: GetFileOptions<TOptions>): FabricFile.File<{
1544
+ pluginName: string;
1545
+ }>;
1546
+ /**
1547
+ * @deprecated use resolvers context instead
1548
+ */
1549
+ resolvePath: <TOptions = object>(params: ResolvePathParams<TOptions>) => FabricFile.Path;
1550
+ /**
1551
+ * @deprecated use resolvers context instead
1552
+ */
1553
+ resolveName: (params: ResolveNameParams) => string;
1554
+ /**
1555
+ * Run a specific hookName for plugin x.
1556
+ */
1557
+ hookForPlugin<H extends PluginLifecycleHooks>({
1558
+ pluginName,
1559
+ hookName,
1560
+ parameters
1561
+ }: {
1562
+ pluginName: string;
1563
+ hookName: H;
1564
+ parameters: PluginParameter<H>;
1565
+ }): Promise<Array<ReturnType<ParseResult<H>> | null>>;
1566
+ /**
1567
+ * Run a specific hookName for plugin x.
1568
+ */
1569
+ hookForPluginSync<H extends PluginLifecycleHooks>({
1570
+ pluginName,
1571
+ hookName,
1572
+ parameters
1573
+ }: {
1574
+ pluginName: string;
1575
+ hookName: H;
1576
+ parameters: PluginParameter<H>;
1577
+ }): Array<ReturnType<ParseResult<H>>> | null;
1578
+ /**
1579
+ * Returns the first non-null result.
1580
+ */
1581
+ hookFirst<H extends PluginLifecycleHooks>({
1582
+ hookName,
1583
+ parameters,
1584
+ skipped
1585
+ }: {
1586
+ hookName: H;
1587
+ parameters: PluginParameter<H>;
1588
+ skipped?: ReadonlySet<Plugin> | null;
1589
+ }): Promise<SafeParseResult<H>>;
1590
+ /**
1591
+ * Returns the first non-null result.
1592
+ */
1593
+ hookFirstSync<H extends PluginLifecycleHooks>({
1594
+ hookName,
1595
+ parameters,
1596
+ skipped
1597
+ }: {
1598
+ hookName: H;
1599
+ parameters: PluginParameter<H>;
1600
+ skipped?: ReadonlySet<Plugin> | null;
1601
+ }): SafeParseResult<H> | null;
1602
+ /**
1603
+ * Runs all plugins in parallel based on `this.plugin` order and `pre`/`post` settings.
1604
+ */
1605
+ hookParallel<H extends PluginLifecycleHooks, TOutput = void>({
1606
+ hookName,
1607
+ parameters
1608
+ }: {
1609
+ hookName: H;
1610
+ parameters?: Parameters<RequiredPluginLifecycle[H]> | undefined;
1611
+ }): Promise<Awaited<TOutput>[]>;
1612
+ /**
1613
+ * Chains plugins
1614
+ */
1615
+ hookSeq<H extends PluginLifecycleHooks>({
1616
+ hookName,
1617
+ parameters
1618
+ }: {
1619
+ hookName: H;
1620
+ parameters?: PluginParameter<H>;
1621
+ }): Promise<void>;
1622
+ getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined;
1623
+ getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined;
1624
+ /**
1625
+ * Like `getPlugin` but throws a descriptive error when the plugin is not found.
1626
+ */
1627
+ requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]>;
1628
+ requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions>;
1629
+ }
1630
+ //#endregion
1631
+ export { defineGenerator as $, Preset as A, Resolver as B, Plugin as C, PluginLifecycleHooks as D, PluginLifecycle as E, ResolveBannerContext as F, UserConfig as G, ResolverFileParams as H, ResolveNameParams as I, UserPlugin as J, UserGroup as K, ResolveOptionsContext as L, Printer$1 as M, PrinterFactoryOptions as N, PluginParameter as O, PrinterPartial as P, Generator as Q, ResolvePathOptions as R, Override as S, PluginFactoryOptions as T, ResolverPathParams as U, ResolverContext as V, SchemaHook as W, UserResolver as X, UserPluginWithLifeCycle as Y, KubbEvents as Z, LoggerContext as _, AdapterSource as a, logLevel as at, OperationsHook as b, Config as c, GeneratorContext as d, mergeGenerators as et, Group as f, Logger as g, InputPath as h, AdapterFactoryOptions as i, linters as it, Presets as j, PluginWithLifeCycle as k, DevtoolsOptions as l, InputData as m, getMode as n, createStorage as nt, BarrelType as o, PossiblePromise as ot, Include as p, UserLogger as q, Adapter as r, formatters as rt, CompatibilityPreset as s, AsyncEventEmitter as st, PluginDriver as t, Storage as tt, Exclude as u, LoggerOptions as v, PluginContext as w, Output as x, OperationHook as y, ResolvePathParams as z };
1632
+ //# sourceMappingURL=PluginDriver-D110FoJ-.d.ts.map