@kubb/core 5.0.0-beta.9 → 5.0.0-beta.93
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.
- package/LICENSE +17 -10
- package/README.md +20 -123
- package/dist/index.cjs +2217 -1132
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +135 -178
- package/dist/index.js +2209 -1125
- package/dist/index.js.map +1 -1
- package/dist/mocks.cjs +77 -24
- package/dist/mocks.cjs.map +1 -1
- package/dist/mocks.d.ts +37 -11
- package/dist/mocks.js +79 -28
- package/dist/mocks.js.map +1 -1
- package/dist/types-BLFyAJLZ.d.ts +2785 -0
- package/dist/usingCtx-BriKju-v.js +577 -0
- package/dist/usingCtx-BriKju-v.js.map +1 -0
- package/dist/usingCtx-eyNeehd2.cjs +679 -0
- package/dist/usingCtx-eyNeehd2.cjs.map +1 -0
- package/package.json +7 -28
- package/dist/PluginDriver-Cu1Kj9S-.cjs +0 -1075
- package/dist/PluginDriver-Cu1Kj9S-.cjs.map +0 -1
- package/dist/PluginDriver-D8Z0Htid.js +0 -978
- package/dist/PluginDriver-D8Z0Htid.js.map +0 -1
- package/dist/createKubb-ALdb8lmq.d.ts +0 -2082
- package/src/FileManager.ts +0 -115
- package/src/FileProcessor.ts +0 -86
- package/src/PluginDriver.ts +0 -457
- package/src/constants.ts +0 -35
- package/src/createAdapter.ts +0 -108
- package/src/createKubb.ts +0 -1268
- package/src/createRenderer.ts +0 -57
- package/src/createStorage.ts +0 -70
- package/src/defineGenerator.ts +0 -175
- package/src/defineLogger.ts +0 -58
- package/src/defineMiddleware.ts +0 -62
- package/src/defineParser.ts +0 -44
- package/src/definePlugin.ts +0 -379
- package/src/defineResolver.ts +0 -654
- package/src/devtools.ts +0 -66
- package/src/index.ts +0 -20
- package/src/mocks.ts +0 -177
- package/src/storages/fsStorage.ts +0 -90
- package/src/storages/memoryStorage.ts +0 -55
- package/src/types.ts +0 -41
- /package/dist/{chunk--u3MIqq1.js → rolldown-runtime-C0LytTxp.js} +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#emitter","NodeEventEmitter","#options","camelCase","#transformParam","#eachParam","#head","#tail","#size","#limit","DEFAULT_EXTENSION","DEFAULT_BANNER","DEFAULT_STUDIO_URL","PluginDriver","applyHookResult"],"sources":["../../../internals/utils/src/errors.ts","../../../internals/utils/src/asyncEventEmitter.ts","../../../internals/utils/src/time.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/urlPath.ts","../src/createAdapter.ts","../package.json","../../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js","../../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js","../src/FileProcessor.ts","../src/createStorage.ts","../src/storages/fsStorage.ts","../src/createKubb.ts","../src/createRenderer.ts","../src/defineGenerator.ts","../src/defineLogger.ts","../src/defineMiddleware.ts","../src/defineParser.ts","../src/storages/memoryStorage.ts"],"sourcesContent":["/**\n * Thrown when one or more errors occur during a Kubb build.\n * Carries the full list of underlying errors on `errors`.\n *\n * @example\n * ```ts\n * throw new BuildError('Build failed', { errors: [err1, err2] })\n * ```\n */\nexport class BuildError extends Error {\n errors: Array<Error>\n\n constructor(message: string, options: { cause?: Error; errors: Array<Error> }) {\n super(message, { cause: options.cause })\n this.name = 'BuildError'\n this.errors = options.errors\n }\n}\n\n/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new BuildError('Build failed', { cause: toError(err), errors: [] })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Extracts the `.cause` of an `Error` as an `Error`, or `undefined` when absent or not an `Error`.\n *\n * @example\n * ```ts\n * const cause = toCause(buildError) // Error | undefined\n * ```\n */\nexport function toCause(error: Error): Error | undefined {\n return error.cause instanceof Error ? error.cause : undefined\n}\n","import { EventEmitter as NodeEventEmitter } from 'node:events'\nimport { toError } from './errors.ts'\n\n/**\n * A function that can be registered as an event listener, synchronous or async.\n */\ntype AsyncListener<TArgs extends unknown[]> = (...args: TArgs) => void | Promise<void>\n\n/**\n * Typed `EventEmitter` that awaits all async listeners before resolving.\n * Wraps Node's `EventEmitter` with full TypeScript event-map inference.\n *\n * @example\n * ```ts\n * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()\n * emitter.on('build', async (name) => { console.log(name) })\n * await emitter.emit('build', 'petstore') // all listeners awaited\n * ```\n */\nexport class AsyncEventEmitter<TEvents extends { [K in keyof TEvents]: unknown[] }> {\n /**\n * Maximum number of listeners per event before Node emits a memory-leak warning.\n * @default 10\n */\n constructor(maxListener = 10) {\n this.#emitter.setMaxListeners(maxListener)\n }\n\n #emitter = new NodeEventEmitter()\n\n /**\n * Emits `eventName` and awaits all registered listeners sequentially.\n * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.\n *\n * @example\n * ```ts\n * await emitter.emit('build', 'petstore')\n * ```\n */\n async emit<TEventName extends keyof TEvents & string>(eventName: TEventName, ...eventArgs: TEvents[TEventName]): Promise<void> {\n const listeners = this.#emitter.listeners(eventName) as Array<AsyncListener<TEvents[TEventName]>>\n\n if (listeners.length === 0) {\n return\n }\n\n for (const listener of listeners) {\n try {\n await listener(...eventArgs)\n } catch (err) {\n let serializedArgs: string\n try {\n serializedArgs = JSON.stringify(eventArgs)\n } catch {\n serializedArgs = String(eventArgs)\n }\n throw new Error(`Error in async listener for \"${eventName}\" with eventArgs ${serializedArgs}`, { cause: toError(err) })\n }\n }\n }\n\n /**\n * Registers a persistent listener for `eventName`.\n *\n * @example\n * ```ts\n * emitter.on('build', async (name) => { console.log(name) })\n * ```\n */\n on<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n this.#emitter.on(eventName, handler as AsyncListener<unknown[]>)\n }\n\n /**\n * Registers a one-shot listener that removes itself after the first invocation.\n *\n * @example\n * ```ts\n * emitter.onOnce('build', async (name) => { console.log(name) })\n * ```\n */\n onOnce<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n const wrapper: AsyncListener<TEvents[TEventName]> = (...args) => {\n this.off(eventName, wrapper)\n return handler(...args)\n }\n this.on(eventName, wrapper)\n }\n\n /**\n * Removes a previously registered listener.\n *\n * @example\n * ```ts\n * emitter.off('build', handler)\n * ```\n */\n off<TEventName extends keyof TEvents & string>(eventName: TEventName, handler: AsyncListener<TEvents[TEventName]>): void {\n this.#emitter.off(eventName, handler as AsyncListener<unknown[]>)\n }\n\n /**\n * Returns the number of listeners registered for `eventName`.\n *\n * @example\n * ```ts\n * emitter.on('build', handler)\n * emitter.listenerCount('build') // 1\n * ```\n */\n listenerCount<TEventName extends keyof TEvents & string>(eventName: TEventName): number {\n return this.#emitter.listenerCount(eventName)\n }\n\n /**\n * Removes all listeners from every event channel.\n *\n * @example\n * ```ts\n * emitter.removeAll()\n * ```\n */\n removeAll(): void {\n this.#emitter.removeAllListeners()\n }\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n\n/**\n * Formats the elapsed time since `hrStart` as a human-readable string.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * formatHrtime(start) // '1.50s'\n * ```\n */\nexport function formatHrtime(hrStart: [number, number]): string {\n return formatMs(getElapsedMs(hrStart))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, join, posix, resolve } from 'node:path'\n\n/**\n * Walks up the directory tree from `cwd` (defaults to `process.cwd()`) and\n * returns the absolute path of the nearest `package.json`, or `null` when none\n * is found before reaching the filesystem root.\n *\n * @example\n * ```ts\n * const pkgPath = findPackageJSON('/home/user/project/src') // '/home/user/project/package.json'\n * ```\n */\nexport function findPackageJSON(cwd?: string): string | null {\n let dir = cwd ? resolve(cwd) : process.cwd()\n while (true) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) return pkgPath\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\n/**\n * Converts all backslashes to forward slashes.\n * Extended-length Windows paths (`\\\\?\\...`) are left unchanged.\n */\nfunction toSlash(p: string): string {\n if (p.startsWith('\\\\\\\\?\\\\')) return p\n return p.replaceAll('\\\\', '/')\n}\n\n/**\n * Returns the relative path from `rootDir` to `filePath`, always using forward slashes\n * and prefixed with `./` when not already traversing upward.\n *\n * @example\n * ```ts\n * getRelativePath('/src/components', '/src/components/Button.tsx') // './Button.tsx'\n * getRelativePath('/src/components', '/src/utils/helpers.ts') // '../utils/helpers.ts'\n * ```\n */\nexport function getRelativePath(rootDir?: string | null, filePath?: string | null): string {\n if (!rootDir || !filePath) {\n throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ''} ${filePath || ''}`)\n }\n\n const relativePath = posix.relative(toSlash(rootDir), toSlash(filePath))\n\n return relativePath.startsWith('../') ? relativePath : `./${relativePath}`\n}\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (typeof Bun !== 'undefined') {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\n/**\n * Synchronous counterpart of `read`.\n *\n * @example\n * ```ts\n * const source = readSync('./src/Pet.ts')\n * ```\n */\nexport function readSync(path: string): string {\n return readFileSync(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Writes `data` to `path`, trimming leading/trailing whitespace before saving.\n * Skips the write when the trimmed content is empty or identical to what is already on disk.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns trimmed content\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const resolved = resolve(path)\n\n if (typeof Bun !== 'undefined') {\n const file = Bun.file(resolved)\n const oldContent = (await file.exists()) ? await file.text() : null\n if (oldContent === trimmed) return null\n await Bun.write(resolved, trimmed)\n return trimmed\n }\n\n try {\n const oldContent = await readFile(resolved, { encoding: 'utf-8' })\n if (oldContent === trimmed) return null\n } catch {\n /* file doesn't exist yet */\n }\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, trimmed, { encoding: 'utf-8' })\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== trimmed) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return trimmed\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n","/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n if (!name || reservedWords.has(name as 'valueOf')) {\n return false\n }\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\nexport type URLObject = {\n /**\n * The resolved URL string (Express-style or template literal, depending on context).\n */\n url: string\n /**\n * Extracted path parameters as a key-value map, or `undefined` when the path has none.\n */\n params?: Record<string, string>\n}\n\ntype ObjectOptions = {\n /**\n * Controls whether the `url` is rendered as an Express path or a template literal.\n * @default 'path'\n */\n type?: 'path' | 'template'\n /**\n * Optional transform applied to each extracted parameter name.\n */\n replacer?: (pathParam: string) => string\n /**\n * When `true`, the result is serialized to a string expression instead of a plain object.\n */\n stringify?: boolean\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\ntype PathCasing = 'camelcase'\n\ntype Options = {\n /**\n * Casing strategy applied to path parameter names.\n * @default undefined (original identifier preserved)\n */\n casing?: PathCasing\n}\n\n/**\n * Parses and transforms an OpenAPI/Swagger path string into various URL formats.\n *\n * @example\n * const p = new URLPath('/pet/{petId}')\n * p.URL // '/pet/:petId'\n * p.template // '`/pet/${petId}`'\n */\nexport class URLPath {\n /**\n * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.\n */\n path: string\n\n #options: Options\n\n constructor(path: string, options: Options = {}) {\n this.path = path\n this.#options = options\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').URL // '/pet/:petId'\n * ```\n */\n get URL(): string {\n return this.toURLPath()\n }\n\n /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).\n *\n * @example\n * ```ts\n * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true\n * new URLPath('/pet/{petId}').isURL // false\n * ```\n */\n get isURL(): boolean {\n try {\n return !!new URL(this.path).href\n } catch {\n return false\n }\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n *\n * @example\n * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'\n * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'\n */\n get template(): string {\n return this.toTemplateString()\n }\n\n /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').object\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n * ```\n */\n get object(): URLObject | string {\n return this.toObject()\n }\n\n /** Returns a map of path parameter names, or `undefined` when the path has no parameters.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').params // { petId: 'petId' }\n * new URLPath('/pet').params // undefined\n * ```\n */\n get params(): Record<string, string> | undefined {\n return this.getParams()\n }\n\n #transformParam(raw: string): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return this.#options.casing === 'camelcase' ? camelCase(param) : param\n }\n\n /**\n * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.\n */\n #eachParam(fn: (raw: string, param: string) => void): void {\n for (const match of this.path.matchAll(/\\{([^}]+)\\}/g)) {\n const raw = match[1]!\n fn(raw, this.#transformParam(raw))\n }\n }\n\n toObject({ type = 'path', replacer, stringify }: ObjectOptions = {}): URLObject | string {\n const object = {\n url: type === 'path' ? this.toURLPath() : this.toTemplateString({ replacer }),\n params: this.getParams(),\n }\n\n if (stringify) {\n if (type === 'template') {\n return JSON.stringify(object).replaceAll(\"'\", '').replaceAll(`\"`, '')\n }\n\n if (object.params) {\n return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll(\"'\", '').replaceAll(`\"`, '')} }`\n }\n\n return `{ url: '${object.url}' }`\n }\n\n return object\n }\n\n /**\n * Converts the OpenAPI path to a TypeScript template literal string.\n * An optional `replacer` can transform each extracted parameter name before interpolation.\n *\n * @example\n * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'\n */\n toTemplateString({\n prefix = '',\n replacer,\n }: {\n prefix?: string\n replacer?: (pathParam: string) => string\n } = {}): string {\n const parts = this.path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = this.#transformParam(part)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix}${result}\\``\n }\n\n /**\n * Extracts all `{param}` segments from the path and returns them as a key-value map.\n * An optional `replacer` transforms each parameter name in both key and value positions.\n * Returns `undefined` when no path parameters are found.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}/tag/{tagId}').getParams()\n * // { petId: 'petId', tagId: 'tagId' }\n * ```\n */\n getParams(replacer?: (pathParam: string) => string): Record<string, string> | undefined {\n const params: Record<string, string> = {}\n\n this.#eachParam((_raw, param) => {\n const key = replacer ? replacer(param) : param\n params[key] = key\n })\n\n return Object.keys(params).length > 0 ? params : undefined\n }\n\n /** Converts the OpenAPI path to Express-style colon syntax.\n *\n * @example\n * ```ts\n * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'\n * ```\n */\n toURLPath(): string {\n return this.path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n}\n","import type { PossiblePromise } from '@internals/utils'\nimport type { ImportNode, InputNode, SchemaNode } from '@kubb/ast'\n\n/**\n * Source data passed to an adapter's `parse` function.\n * Mirrors the config input shape with paths resolved to absolute.\n */\nexport type AdapterSource = { type: 'path'; path: string } | { type: 'data'; data: string | unknown } | { type: 'paths'; paths: Array<string> }\n\n/**\n * Generic type parameters for an adapter definition.\n *\n * - `TName` — unique identifier (e.g. `'oas'`, `'asyncapi'`)\n * - `TOptions` — user-facing options passed to the adapter factory\n * - `TResolvedOptions` — options after defaults applied\n * - `TDocument` — type of the parsed source document\n */\nexport type AdapterFactoryOptions<\n TName extends string = string,\n TOptions extends object = object,\n TResolvedOptions extends object = TOptions,\n TDocument = unknown,\n> = {\n name: TName\n options: TOptions\n resolvedOptions: TResolvedOptions\n document: TDocument\n}\n\n/**\n * Adapter that converts input files or data into an `InputNode`.\n *\n * Adapters parse different schema formats (OpenAPI, AsyncAPI, Drizzle, etc.) into Kubb's\n * universal intermediate representation that all plugins consume.\n *\n * @example\n * ```ts\n * import { adapterOas } from '@kubb/adapter-oas'\n *\n * export default defineConfig({\n * adapter: adapterOas(),\n * input: { path: './openapi.yaml' },\n * plugins: [pluginTs(), pluginZod()],\n * })\n * ```\n */\nexport type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {\n /**\n * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).\n */\n name: TOptions['name']\n /**\n * Resolved adapter options after defaults have been applied.\n */\n options: TOptions['resolvedOptions']\n /**\n * Parsed source document after the first `parse()` call. `null` before parsing.\n */\n document: TOptions['document'] | null\n inputNode: InputNode | null\n /**\n * Parse the source into a universal `InputNode`.\n */\n parse: (source: AdapterSource) => PossiblePromise<InputNode>\n /**\n * Extract `ImportNode` entries for a schema tree.\n * Returns an empty array before the first `parse()` call.\n *\n * The `resolve` callback receives the collision-corrected schema name and must\n * return `{ name, path }` for the import, or `undefined` to skip it.\n */\n getImports: (node: SchemaNode, resolve: (schemaName: string) => { name: string; path: string }) => Array<ImportNode>\n /**\n * Validate the document at the given path or URL.\n */\n validate: (input: string, options?: { throwOnError?: boolean }) => Promise<void>\n}\n\ntype AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>\n\n/**\n * Factory for implementing custom adapters that translate non-OpenAPI specs into Kubb's AST.\n *\n * Use this to support GraphQL schemas, gRPC definitions, AsyncAPI, or custom domain-specific languages.\n * Built-in adapters include `@kubb/adapter-oas` for OpenAPI and Swagger documents.\n *\n * @note Adapters must parse their input format to Kubb's `InputNode` structure.\n *\n * @example\n * ```ts\n * export const myAdapter = createAdapter<MyAdapter>((options) => {\n * return {\n * name: 'my-adapter',\n * options,\n * async parse(source) {\n * // Transform source format to InputNode\n * return { ... }\n * },\n * }\n * })\n *\n * // Instantiate:\n * const adapter = myAdapter({ validate: true })\n * ```\n */\nexport function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T> {\n return (options) => build(options ?? ({} as T['options']))\n}\n","","/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\n\t\t// Clean up tail reference when queue becomes empty\n\t\tif (!this.#head) {\n\t\t\tthis.#tail = undefined;\n\t\t}\n\n\t\treturn current.value;\n\t}\n\n\tpeek() {\n\t\tif (!this.#head) {\n\t\t\treturn;\n\t\t}\n\n\t\treturn this.#head.value;\n\n\t\t// TODO: Node.js 18.\n\t\t// return this.#head?.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n\n\t* drain() {\n\t\twhile (this.#head) {\n\t\t\tyield this.dequeue();\n\t\t}\n\t}\n}\n","import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tlet rejectOnClear = false;\n\n\tif (typeof concurrency === 'object') {\n\t\t({concurrency, rejectOnClear = false} = concurrency);\n\t}\n\n\tvalidateConcurrency(concurrency);\n\n\tif (typeof rejectOnClear !== 'boolean') {\n\t\tthrow new TypeError('Expected `rejectOnClear` to be a boolean');\n\t}\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst resumeNext = () => {\n\t\t// Process the next queued function if we're under the concurrency limit\n\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\tactiveCount++;\n\t\t\tqueue.dequeue().run();\n\t\t}\n\t};\n\n\tconst next = () => {\n\t\tactiveCount--;\n\t\tresumeNext();\n\t};\n\n\tconst run = async (function_, resolve, arguments_) => {\n\t\t// Execute the function and capture the result promise\n\t\tconst result = (async () => function_(...arguments_))();\n\n\t\t// Resolve immediately with the promise (don't wait for completion)\n\t\tresolve(result);\n\n\t\t// Wait for the function to complete (success or failure)\n\t\t// We catch errors here to prevent unhandled rejections,\n\t\t// but the original promise rejection is preserved for the caller\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\t// Decrement active count and process next queued function\n\t\tnext();\n\t};\n\n\tconst enqueue = (function_, resolve, reject, arguments_) => {\n\t\tconst queueItem = {reject};\n\n\t\t// Queue the internal resolve function instead of the run function\n\t\t// to preserve the asynchronous execution context.\n\t\tnew Promise(internalResolve => { // eslint-disable-line promise/param-names\n\t\t\tqueueItem.run = internalResolve;\n\t\t\tqueue.enqueue(queueItem);\n\t\t}).then(run.bind(undefined, function_, resolve, arguments_)); // eslint-disable-line promise/prefer-await-to-then\n\n\t\t// Start processing immediately if we haven't reached the concurrency limit\n\t\tif (activeCount < concurrency) {\n\t\t\tresumeNext();\n\t\t}\n\t};\n\n\tconst generator = (function_, ...arguments_) => new Promise((resolve, reject) => {\n\t\tenqueue(function_, resolve, reject, arguments_);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue() {\n\t\t\t\tif (!rejectOnClear) {\n\t\t\t\t\tqueue.clear();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst abortError = AbortSignal.abort().reason;\n\n\t\t\t\twhile (queue.size > 0) {\n\t\t\t\t\tqueue.dequeue().reject(abortError);\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tconcurrency: {\n\t\t\tget: () => concurrency,\n\n\t\t\tset(newConcurrency) {\n\t\t\t\tvalidateConcurrency(newConcurrency);\n\t\t\t\tconcurrency = newConcurrency;\n\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\t// eslint-disable-next-line no-unmodified-loop-condition\n\t\t\t\t\twhile (activeCount < concurrency && queue.size > 0) {\n\t\t\t\t\t\tresumeNext();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t\tmap: {\n\t\t\tasync value(iterable, function_) {\n\t\t\t\tconst promises = Array.from(iterable, (value, index) => this(function_, value, index));\n\t\t\t\treturn Promise.all(promises);\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n\nexport function limitFunction(function_, options) {\n\tconst limit = pLimit(options);\n\n\treturn (...arguments_) => limit(() => function_(...arguments_));\n}\n\nfunction validateConcurrency(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n}\n","import type { CodeNode, FileNode } from '@kubb/ast'\nimport { extractStringsFromNodes } from '@kubb/ast'\nimport pLimit from 'p-limit'\nimport { PARALLEL_CONCURRENCY_LIMIT } from './constants.ts'\nimport type { Parser } from './defineParser.ts'\n\ntype ParseOptions = {\n parsers?: Map<FileNode['extname'], Parser>\n extension?: Record<FileNode['extname'], FileNode['extname'] | ''>\n}\n\ntype RunOptions = ParseOptions & {\n /**\n * @default 'sequential'\n */\n mode?: 'sequential' | 'parallel'\n onStart?: (files: Array<FileNode>) => Promise<void> | void\n onEnd?: (files: Array<FileNode>) => Promise<void> | void\n onUpdate?: (params: { file: FileNode; source?: string; processed: number; total: number; percentage: number }) => Promise<void> | void\n}\n\nfunction joinSources(file: FileNode): string {\n return file.sources\n .map((item) => extractStringsFromNodes(item.nodes as Array<CodeNode>))\n .filter(Boolean)\n .join('\\n\\n')\n}\n\n/**\n * Converts a single file to a string using the registered parsers.\n * Falls back to joining source values when no matching parser is found.\n *\n * @internal\n */\nexport class FileProcessor {\n readonly #limit = pLimit(PARALLEL_CONCURRENCY_LIMIT)\n\n async parse(file: FileNode, { parsers, extension }: ParseOptions = {}): Promise<string> {\n const parseExtName = extension?.[file.extname] || undefined\n\n if (!parsers || !file.extname) {\n return joinSources(file)\n }\n\n const parser = parsers.get(file.extname)\n\n if (!parser) {\n return joinSources(file)\n }\n\n return parser.parse(file, { extname: parseExtName })\n }\n\n async run(files: Array<FileNode>, { parsers, mode = 'sequential', extension, onStart, onEnd, onUpdate }: RunOptions = {}): Promise<Array<FileNode>> {\n await onStart?.(files)\n\n const total = files.length\n let processed = 0\n\n const processOne = async (file: FileNode) => {\n const source = await this.parse(file, { extension, parsers })\n const currentProcessed = ++processed\n const percentage = (currentProcessed / total) * 100\n\n await onUpdate?.({\n file,\n source,\n processed: currentProcessed,\n percentage,\n total,\n })\n }\n\n if (mode === 'sequential') {\n for (const file of files) {\n await processOne(file)\n }\n } else {\n await Promise.all(files.map((file) => this.#limit(() => processOne(file))))\n }\n\n await onEnd?.(files)\n\n return files\n }\n}\n","export type Storage = {\n /**\n * Identifier used for logging and debugging (e.g. `'fs'`, `'s3'`).\n */\n readonly name: string\n /**\n * Returns `true` when an entry for `key` exists in storage.\n */\n hasItem(key: string): Promise<boolean>\n /**\n * Returns the stored string value, or `null` when `key` does not exist.\n */\n getItem(key: string): Promise<string | null>\n /**\n * Persists `value` under `key`, creating any required structure.\n */\n setItem(key: string, value: string): Promise<void>\n /**\n * Removes the entry for `key`. No-ops when the key does not exist.\n */\n removeItem(key: string): Promise<void>\n /**\n * Returns all keys, optionally filtered to those starting with `base`.\n */\n getKeys(base?: string): Promise<Array<string>>\n /**\n * Removes all entries, optionally scoped to those starting with `base`.\n */\n clear(base?: string): Promise<void>\n /**\n * Optional teardown hook called after the build completes.\n */\n dispose?(): Promise<void>\n}\n\n/**\n * Factory for implementing custom storage backends that control where generated files are written.\n *\n * Takes a builder function `(options: TOptions) => Storage` and returns a factory `(options?: TOptions) => Storage`.\n * Kubb provides filesystem and in-memory implementations out of the box.\n *\n * @note Call the returned factory with optional options to instantiate the storage adapter.\n *\n * @example\n * ```ts\n * import { createStorage } from '@kubb/core'\n *\n * export const memoryStorage = createStorage(() => {\n * const store = new Map<string, string>()\n * return {\n * name: 'memory',\n * async hasItem(key) { return store.has(key) },\n * async getItem(key) { return store.get(key) ?? null },\n * async setItem(key, value) { store.set(key, value) },\n * async removeItem(key) { store.delete(key) },\n * async getKeys(base) {\n * const keys = [...store.keys()]\n * return base ? keys.filter((k) => k.startsWith(base)) : keys\n * },\n * async clear(base) { if (!base) store.clear() },\n * }\n * })\n *\n * // Instantiate:\n * const storage = memoryStorage()\n * ```\n */\nexport function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage {\n return (options) => build(options ?? ({} as TOptions))\n}\n","import type { Dirent } from 'node:fs'\nimport { access, readdir, readFile, rm } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport { clean, write } from '@internals/utils'\nimport { createStorage } from '../createStorage.ts'\n\n\n/**\n * Built-in filesystem storage driver.\n *\n * This is the default storage when no `storage` option is configured in the root config.\n * Keys are resolved against `process.cwd()`, so root-relative paths such as\n * `src/gen/api/getPets.ts` are written to the correct location without extra configuration.\n *\n * Internally uses the `write` utility from `@internals/utils`, which:\n * - trims leading/trailing whitespace before writing\n * - skips the write when file content is already identical (deduplication)\n * - creates missing parent directories automatically\n * - supports Bun's native file API when running under Bun\n *\n * @example\n * ```ts\n * import { fsStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * storage: fsStorage(),\n * })\n * ```\n */\nexport const fsStorage = createStorage(() => ({\n name: 'fs',\n async hasItem(key: string) {\n try {\n await access(resolve(key))\n return true\n } catch (_error) {\n return false\n }\n },\n async getItem(key: string) {\n try {\n return await readFile(resolve(key), 'utf8')\n } catch (_error) {\n return null\n }\n },\n async setItem(key: string, value: string) {\n await write(resolve(key), value, { sanity: false })\n },\n async removeItem(key: string) {\n await rm(resolve(key), { force: true })\n },\n async getKeys(base?: string) {\n const keys: Array<string> = []\n const resolvedBase = resolve(base ?? process.cwd())\n\n async function walk(dir: string, prefix: string): Promise<void> {\n let entries: Array<Dirent>\n try {\n entries = (await readdir(dir, {\n withFileTypes: true,\n })) as Array<Dirent>\n } catch (_error) {\n return\n }\n for (const entry of entries) {\n const rel = prefix ? `${prefix}/${entry.name}` : entry.name\n if (entry.isDirectory()) {\n await walk(join(dir, entry.name), rel)\n } else {\n keys.push(rel)\n }\n }\n }\n\n await walk(resolvedBase, '')\n\n return keys\n },\n async clear(base?: string) {\n if (!base) {\n return\n }\n\n await clean(resolve(base))\n },\n}))\n","import { resolve } from 'node:path'\nimport { version as nodeVersion } from 'node:process'\nimport type { PossiblePromise } from '@internals/utils'\nimport { AsyncEventEmitter, BuildError, exists, formatMs, getElapsedMs, URLPath } from '@internals/utils'\nimport type { FileNode, InputNode, OperationNode, SchemaNode } from '@kubb/ast'\nimport { collectUsedSchemaNames, transform, walk } from '@kubb/ast'\nimport { version as KubbVersion } from '../package.json'\nimport { DEFAULT_BANNER, DEFAULT_EXTENSION, DEFAULT_STUDIO_URL } from './constants.ts'\nimport type { Adapter, AdapterSource } from './createAdapter.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { Storage } from './createStorage.ts'\nimport type { GeneratorContext, Generator } from './defineGenerator.ts'\nimport type { Middleware } from './defineMiddleware.ts'\nimport type { Parser } from './defineParser.ts'\nimport type { KubbPluginEndContext, KubbPluginSetupContext, KubbPluginStartContext, NormalizedPlugin, Plugin } from './definePlugin.ts'\nimport { FileProcessor } from './FileProcessor.ts'\nimport { applyHookResult, PluginDriver } from './PluginDriver.ts'\nimport { fsStorage } from './storages/fsStorage.ts'\n\n/**\n * Safely extracts a type from a registry, returning `{}` if the key doesn't exist.\n * Enables optional interface augmentation for `Kubb.ConfigOptionsRegistry` and `Kubb.PluginOptionsRegistry`\n * without requiring changes to core.\n *\n * @internal\n */\ntype ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {}\n\n/**\n * Reference to an input file to generate code from.\n *\n * Specify an absolute path or a path relative to the config file location.\n * The adapter will parse this file (e.g., OpenAPI YAML or JSON) into the universal AST.\n */\nexport type InputPath = {\n /**\n * Path to your Swagger/OpenAPI file, absolute or relative to the config file location.\n *\n * @example\n * ```ts\n * { path: './petstore.yaml' }\n * { path: '/absolute/path/to/openapi.json' }\n * ```\n */\n path: string\n}\n\n/**\n * Inline input data to generate code from.\n *\n * Useful when you want to pass the specification directly instead of from a file.\n * Can be a string (YAML/JSON) or a parsed object.\n */\nexport type InputData = {\n /**\n * Swagger/OpenAPI data as a string (YAML/JSON) or a parsed object.\n *\n * @example\n * ```ts\n * { data: fs.readFileSync('./openapi.yaml', 'utf8') }\n * { data: { openapi: '3.1.0', info: { ... } } }\n * ```\n */\n data: string | unknown\n}\n\ntype Input = InputPath | InputData\n\n/**\n * Build configuration for Kubb code generation.\n *\n * The Config is the main entry point for customizing how Kubb generates code. It specifies:\n * - What to generate from (adapter + input)\n * - Where to output generated code (output)\n * - How to generate (plugins + middleware)\n * - Runtime details (parsers, storage, renderer)\n *\n * See `UserConfig` for a relaxed version with sensible defaults.\n *\n * @private\n */\nexport type Config<TInput = Input> = {\n /**\n * Display name for this configuration in CLI output and logs.\n * Useful when running multiple builds with `defineConfig` arrays.\n *\n * @example\n * ```ts\n * name: 'api-client'\n * ```\n */\n name?: string\n /**\n * Project root directory, absolute or relative to the config file.\n * @default process.cwd()\n */\n root: string\n /**\n * Parsers that convert generated files to strings.\n * Each parser handles specific extensions (e.g. `.ts`, `.tsx`).\n * A fallback parser is appended for unhandled extensions.\n * When omitted, defaults to `parserTs` from `@kubb/parser-ts`.\n *\n * @default [parserTs] from `@kubb/parser-ts`\n * @example\n * ```ts\n * import { parserTs, tsxParser } from '@kubb/parser-ts'\n * export default defineConfig({\n * parsers: [parserTs, tsxParser],\n * })\n * ```\n */\n parsers: Array<Parser>\n /**\n * Adapter that parses input files into the universal `InputNode` representation.\n * Use `@kubb/adapter-oas` for OpenAPI/Swagger or `@kubb/adapter-asyncapi` for other formats.\n *\n * When omitted, Kubb runs in plugin-only mode: `kubb:plugin:setup` fires and files\n * injected via `injectFile` are written, but no AST walk occurs and generator hooks\n * (`kubb:generate:schema`, `kubb:generate:operation`) are never emitted.\n *\n * @example\n * ```ts\n * import { adapterOas } from '@kubb/adapter-oas'\n * export default defineConfig({\n * adapter: adapterOas(),\n * input: { path: './petstore.yaml' },\n * })\n * ```\n */\n adapter?: Adapter\n /**\n * Source file or data to generate code from.\n * Use `input.path` for a file path or `input.data` for inline data.\n * Required when an adapter is configured; omit when running in plugin-only mode.\n */\n input?: TInput\n output: {\n /**\n * Output directory for generated files, absolute or relative to `root`.\n *\n * All generated files will be written under this directory. Subdirectories can be created\n * by plugins based on grouping strategy (by tag, path, etc.).\n *\n * @example\n * ```ts\n * output: {\n * path: './src/gen', // generates ./src/gen/api.ts, ./src/gen/types.ts, etc.\n * }\n * ```\n */\n path: string\n /**\n * Remove all files from the output directory before starting the build.\n *\n * Useful to ensure old generated files aren't mixed with new ones.\n * Set to `true` for fresh builds, `false` to preserve manual edits in output dir.\n *\n * @default false\n * @example\n * ```ts\n * clean: true // wipes ./src/gen/* before generating\n * ```\n */\n clean?: boolean\n /**\n * Auto-format generated files after code generation completes.\n *\n * Applies a code formatter to all generated files. Use `'auto'` to detect which formatter\n * is available on your system. Pass `false` to skip formatting (useful for CI or specific workflows).\n *\n * @default false\n * @example\n * ```ts\n * format: 'auto' // auto-detect prettier, biome, or oxfmt\n * format: 'prettier' // force prettier\n * format: false // skip formatting\n * ```\n */\n format?: 'auto' | 'prettier' | 'biome' | 'oxfmt' | false\n /**\n * Auto-lint generated files after code generation completes.\n *\n * Analyzes all generated files for style/correctness issues. Use `'auto'` to detect which linter\n * is available on your system. Pass `false` to skip linting.\n *\n * @default false\n * @example\n * ```ts\n * lint: 'auto' // auto-detect oxlint, biome, or eslint\n * lint: 'eslint' // force eslint\n * lint: false // skip linting\n * ```\n */\n lint?: 'auto' | 'eslint' | 'biome' | 'oxlint' | false\n /**\n * Map file extensions to different output extensions.\n *\n * Useful when you want generated `.ts` imports to reference `.js` files or vice versa (e.g., for ESM dual packages).\n * Keys are the original extension, values are the output extension. Use empty string `''` to omit extension.\n *\n * @default { '.ts': '.ts' }\n * @example\n * ```ts\n * extension: { '.ts': '.js' } // generates import './api.js' instead of './api.ts'\n * extension: { '.ts': '', '.tsx': '.jsx' }\n * ```\n */\n extension?: Record<FileNode['extname'], FileNode['extname'] | ''>\n /**\n * Banner text prepended to every generated file.\n *\n * Useful for auto-generation notices or license headers. Choose a preset or write custom text.\n * Use `'simple'` for a basic Kubb banner, `'full'` for detailed metadata, or `false` to omit.\n *\n * @default 'simple'\n * @example\n * ```ts\n * defaultBanner: 'simple' // \"This file was autogenerated by Kubb\"\n * defaultBanner: 'full' // adds source, title, description, API version\n * defaultBanner: false // no banner\n * ```\n */\n defaultBanner?: 'simple' | 'full' | false\n /**\n * When `true`, overwrites existing files. When `false`, skips generated files that already exist.\n *\n * Individual plugins can override this setting. This is useful for preventing accidental data loss\n * when re-generating while you have local edits in the output folder.\n *\n * @default false\n * @example\n * ```ts\n * override: true // regenerate everything, even existing files\n * override: false // skip files that already exist\n * ```\n */\n override?: boolean\n } & ExtractRegistryKey<Kubb.ConfigOptionsRegistry, 'output'>\n /**\n * Storage backend that controls where and how generated files are persisted.\n *\n * Defaults to `fsStorage()` which writes to the file system. Pass `memoryStorage()` to keep files in RAM,\n * or implement a custom `Storage` interface to write to cloud storage, databases, or other backends.\n *\n * @default fsStorage()\n * @example\n * ```ts\n * import { memoryStorage } from '@kubb/core'\n *\n * // Keep generated files in memory (useful for testing, CI pipelines)\n * storage: memoryStorage()\n *\n * // Use custom S3 storage\n * storage: myS3Storage()\n * ```\n *\n * @see {@link Storage} interface for implementing custom backends.\n */\n storage: Storage\n /**\n * Plugins that execute during the build to generate code and transform the AST.\n *\n * Each plugin processes the AST produced by the adapter and can emit files for different\n * programming languages or formats (TypeScript, Zod schemas, Faker data, etc.).\n * Dependencies are enforced — an error is thrown if a plugin requires another plugin that isn't registered.\n *\n * Plugins can declare their own options via `PluginFactoryOptions`. See plugin documentation for details.\n *\n * @example\n * ```ts\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginZod } from '@kubb/plugin-zod'\n *\n * plugins: [\n * pluginTs({ output: { path: './src/gen' } }),\n * pluginZod({ output: { path: './src/gen' } }),\n * ]\n * ```\n */\n plugins: Array<Plugin>\n /**\n * Middleware instances that observe build events and post-process generated code.\n *\n * Middleware fires AFTER all plugins for each event. Perfect for tasks like:\n * - Auditing what was generated\n * - Adding barrel/index files\n * - Validating output\n * - Running custom transformations\n *\n * @example\n * ```ts\n * import { middlewareBarrel } from '@kubb/middleware-barrel'\n *\n * middleware: [middlewareBarrel()]\n * ```\n *\n * @see {@link defineMiddleware} to create custom middleware.\n */\n middleware?: Array<Middleware>\n /**\n * Renderer that converts generated AST nodes to code strings.\n *\n * By default, Kubb uses the JSX renderer (`rendererJsx`). Pass a custom renderer to support\n * different output formats (template engines, code generation DSLs, etc.).\n *\n * @default rendererJsx() // from @kubb/renderer-jsx\n * @example\n * ```ts\n * import { rendererJsx } from '@kubb/renderer-jsx'\n * renderer: rendererJsx()\n * ```\n *\n * @see {@link Renderer} to implement a custom renderer.\n */\n renderer?: RendererFactory\n /**\n * Kubb Studio cloud integration settings.\n *\n * Kubb Studio (https://kubb.studio) is a web-based IDE for managing API specs and generated code.\n * Set to `true` to enable with default settings, or pass an object to customize the Studio URL.\n *\n * @default false // disabled by default\n * @example\n * ```ts\n * devtools: true // use default Kubb Studio\n * devtools: { studioUrl: 'https://my-studio.dev' } // custom Studio instance\n * ```\n */\n devtools?:\n | true\n | {\n /**\n * Override the Kubb Studio base URL.\n * @default 'https://kubb.studio'\n */\n studioUrl?: typeof DEFAULT_STUDIO_URL | (string & {})\n }\n /**\n * Lifecycle hooks that execute during or after the build process.\n *\n * Hooks allow you to run external tools (prettier, eslint, custom scripts) based on build events.\n * Currently supports the `done` hook which fires after all plugins and middleware complete.\n *\n * @example\n * ```ts\n * hooks: {\n * done: 'prettier --write \"./src/gen\"', // auto-format generated files\n * // or multiple commands:\n * done: ['prettier --write \"./src/gen\"', 'eslint --fix \"./src/gen\"']\n * }\n * ```\n */\n hooks?: {\n /**\n * Command(s) to run after all plugins and middleware complete generation.\n *\n * Useful for post-processing: formatting, linting, copying files, or custom validation.\n * Pass a single command string or array of command strings to run sequentially.\n * Commands are executed relative to the `root` directory.\n *\n * @example\n * ```ts\n * done: 'prettier --write \"./src/gen\"'\n * done: ['prettier --write \"./src/gen\"', 'eslint --fix \"./src/gen\"']\n * ```\n */\n done?: string | Array<string>\n }\n}\n\n/**\n * Partial `Config` for user-facing entry points with sensible defaults.\n *\n * `UserConfig` is what you pass to `defineConfig()`. It has optional `root`, `plugins`, `parsers`, and `adapter`\n * fields (which fall back to sensible defaults). All other Config options are available, including `output`, `input`,\n * `storage`, `middleware`, `renderer`, `devtools`, and `hooks`.\n *\n * @example\n * ```ts\n * export default defineConfig({\n * input: { path: './petstore.yaml' },\n * output: { path: './src/gen' },\n * plugins: [pluginTs(), pluginZod()],\n * })\n * ```\n */\nexport type UserConfig<TInput = Input> = Omit<Config<TInput>, 'root' | 'plugins' | 'parsers' | 'adapter'| 'storage'> & {\n /**\n * Project root directory, absolute or relative to the config file location.\n * @default process.cwd()\n */\n root?: string\n /**\n * Custom parsers that convert generated AST nodes to strings (TypeScript, JSON, markdown, etc.).\n * @default [parserTs] // from `@kubb/parser-ts`\n */\n parsers?: Array<Parser>\n /**\n * Adapter that parses your API specification into Kubb's universal AST.\n * When omitted, Kubb runs in plugin-only mode.\n */\n adapter?: Adapter\n /**\n * Plugins that execute during the build to generate code and transform the AST.\n * @default []\n */\n plugins?: Array<Plugin>\n /**\n * Storage backend that controls where and how generated files are persisted.\n * @default fsStorage()\n */\n storage?: Storage\n}\n\ndeclare global {\n namespace Kubb {\n /**\n * Registry that maps plugin names to their `PluginFactoryOptions`.\n * Augment this interface in each plugin's `types.ts` to enable automatic\n * typing for `getPlugin` and `requirePlugin`.\n *\n * @example\n * ```ts\n * // packages/plugin-ts/src/types.ts\n * declare global {\n * namespace Kubb {\n * interface PluginRegistry {\n * 'plugin-ts': PluginTs\n * }\n * }\n * }\n * ```\n */\n interface PluginRegistry {}\n\n /**\n * Extension point for root `Config['output']` options.\n * Augment the `output` key in middleware or plugin packages to add extra fields\n * to the global output configuration without touching core types.\n *\n * @example\n * ```ts\n * // packages/middleware-barrel/src/types.ts\n * declare global {\n * namespace Kubb {\n * interface ConfigOptionsRegistry {\n * output: {\n * barrel?: import('./types.ts').BarrelConfig | false\n * }\n * }\n * }\n * }\n * ```\n */\n interface ConfigOptionsRegistry {}\n\n /**\n * Extension point for per-plugin `Output` options.\n * Augment the `output` key in middleware or plugin packages to add extra fields\n * to the per-plugin output configuration without touching core types.\n *\n * @example\n * ```ts\n * // packages/middleware-barrel/src/types.ts\n * declare global {\n * namespace Kubb {\n * interface PluginOptionsRegistry {\n * output: {\n * barrel?: import('./types.ts').PluginBarrelConfig | false\n * }\n * }\n * }\n * }\n * ```\n */\n interface PluginOptionsRegistry {}\n }\n}\n\n/**\n * Lifecycle events emitted during Kubb code generation.\n * Use these for logging, progress tracking, and custom integrations.\n *\n * @example\n * ```typescript\n * import type { AsyncEventEmitter } from '@internals/utils'\n * import type { KubbHooks } from '@kubb/core'\n *\n * const hooks: AsyncEventEmitter<KubbHooks> = new AsyncEventEmitter()\n *\n * hooks.on('kubb:lifecycle:start', () => {\n * console.log('Starting Kubb generation')\n * })\n *\n * hooks.on('kubb:plugin:end', ({ plugin, duration }) => {\n * console.log(`Plugin ${plugin.name} completed in ${duration}ms`)\n * })\n * ```\n */\nexport interface KubbHooks {\n 'kubb:lifecycle:start': [ctx: KubbLifecycleStartContext]\n 'kubb:lifecycle:end': []\n 'kubb:config:start': []\n 'kubb:config:end': [ctx: KubbConfigEndContext]\n 'kubb:generation:start': [ctx: KubbGenerationStartContext]\n 'kubb:generation:end': [ctx: KubbGenerationEndContext]\n 'kubb:generation:summary': [ctx: KubbGenerationSummaryContext]\n 'kubb:format:start': []\n 'kubb:format:end': []\n 'kubb:lint:start': []\n 'kubb:lint:end': []\n 'kubb:hooks:start': []\n 'kubb:hooks:end': []\n 'kubb:hook:start': [ctx: KubbHookStartContext]\n 'kubb:hook:end': [ctx: KubbHookEndContext]\n 'kubb:version:new': [ctx: KubbVersionNewContext]\n 'kubb:info': [ctx: KubbInfoContext]\n 'kubb:error': [ctx: KubbErrorContext]\n 'kubb:success': [ctx: KubbSuccessContext]\n 'kubb:warn': [ctx: KubbWarnContext]\n 'kubb:debug': [ctx: KubbDebugContext]\n 'kubb:files:processing:start': [ctx: KubbFilesProcessingStartContext]\n 'kubb:file:processing:update': [ctx: KubbFileProcessingUpdateContext]\n 'kubb:files:processing:end': [ctx: KubbFilesProcessingEndContext]\n 'kubb:plugin:start': [ctx: KubbPluginStartContext]\n 'kubb:plugin:end': [ctx: KubbPluginEndContext]\n 'kubb:plugin:setup': [ctx: KubbPluginSetupContext]\n 'kubb:build:start': [ctx: KubbBuildStartContext]\n 'kubb:plugins:end': [ctx: KubbPluginsEndContext]\n 'kubb:build:end': [ctx: KubbBuildEndContext]\n 'kubb:generate:schema': [node: SchemaNode, ctx: GeneratorContext]\n 'kubb:generate:operation': [node: OperationNode, ctx: GeneratorContext]\n 'kubb:generate:operations': [nodes: Array<OperationNode>, ctx: GeneratorContext]\n}\n\nexport type KubbBuildStartContext = {\n config: Config\n adapter: Adapter\n inputNode: InputNode\n getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined\n getPlugin(name: string): Plugin | undefined\n readonly files: ReadonlyArray<FileNode>\n upsertFile: (...files: Array<FileNode>) => void\n}\n\nexport type KubbPluginsEndContext = {\n config: Config\n readonly files: ReadonlyArray<FileNode>\n upsertFile: (...files: Array<FileNode>) => void\n}\n\nexport type KubbBuildEndContext = {\n files: Array<FileNode>\n config: Config\n outputDir: string\n}\n\nexport type KubbLifecycleStartContext = {\n version: string\n}\n\nexport type KubbConfigEndContext = {\n configs: Array<Config>\n}\n\nexport type KubbGenerationStartContext = {\n config: Config\n}\n\nexport type KubbGenerationEndContext = {\n config: Config\n files: Array<FileNode>\n sources: Map<string, string>\n}\n\nexport type KubbGenerationSummaryContext = {\n config: Config\n failedPlugins: Set<{ plugin: Plugin; error: Error }>\n status: 'success' | 'failed'\n hrStart: [number, number]\n filesCreated: number\n pluginTimings?: Map<Plugin['name'], number>\n}\n\nexport type KubbVersionNewContext = {\n currentVersion: string\n latestVersion: string\n}\n\nexport type KubbInfoContext = {\n message: string\n info?: string\n}\n\nexport type KubbErrorContext = {\n error: Error\n meta?: Record<string, unknown>\n}\n\nexport type KubbSuccessContext = {\n message: string\n info?: string\n}\n\nexport type KubbWarnContext = {\n message: string\n info?: string\n}\n\nexport type KubbDebugContext = {\n date: Date\n logs: Array<string>\n fileName?: string\n}\n\nexport type KubbFilesProcessingStartContext = {\n files: Array<FileNode>\n}\n\nexport type KubbFileProcessingUpdateContext = {\n processed: number\n total: number\n percentage: number\n source?: string\n file: FileNode\n config: Config\n}\n\nexport type KubbFilesProcessingEndContext = {\n files: Array<FileNode>\n}\n\nexport type KubbHookStartContext = {\n id?: string\n command: string\n args?: readonly string[]\n}\n\nexport type KubbHookEndContext = {\n id?: string\n command: string\n args?: readonly string[]\n success: boolean\n error: Error | null\n}\n\n/**\n * CLI options derived from command-line flags.\n */\nexport type CLIOptions = {\n config?: string\n watch?: boolean\n /** @default 'silent' */\n logLevel?: 'silent' | 'info' | 'debug'\n}\n\n/**\n * All accepted forms of a Kubb configuration.\n * Accepts `Config`/`Config[]`/promise or a factory (optionally receiving `TCliOptions`).\n */\nexport type PossibleConfig<TCliOptions = undefined> =\n | PossiblePromise<Config | Config[]>\n | ((...args: [TCliOptions] extends [undefined] ? [] : [TCliOptions]) => PossiblePromise<Config | Config[]>)\n\ntype SetupOptions = {\n hooks?: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Full output produced by a successful or failed build.\n */\nexport type BuildOutput = {\n /**\n * Plugins that threw during installation, paired with the caught error.\n */\n failedPlugins: Set<{ plugin: Plugin; error: Error }>\n files: Array<FileNode>\n driver: PluginDriver\n /**\n * Elapsed time in milliseconds for each plugin, keyed by plugin name.\n */\n pluginTimings: Map<string, number>\n error?: Error\n /**\n * Raw generated source, keyed by absolute file path.\n */\n sources: Map<string, string>\n}\n\n/**\n * Kubb code generation instance returned by {@link createKubb}.\n *\n * Use this when orchestrating multiple builds, inspecting plugin timings, or integrating Kubb into a larger toolchain.\n * For a single one-off build, chain directly: `await createKubb(config).build()`.\n */\nexport type Kubb = {\n /**\n * Shared event emitter for lifecycle and status events. Attach listeners before calling `setup()` or `build()`.\n */\n readonly hooks: AsyncEventEmitter<KubbHooks>\n /**\n * Generated source code keyed by absolute file path. Available after `build()` or `safeBuild()` completes.\n */\n readonly sources: Map<string, string>\n /**\n * Plugin driver managing all plugins. Available after `setup()` completes.\n */\n readonly driver: PluginDriver | undefined\n /**\n * Resolved configuration with defaults applied. Available after `setup()` completes.\n */\n readonly config: Config | undefined\n /**\n * Resolves config and initializes the driver. `build()` calls this automatically.\n */\n setup(): Promise<void>\n /**\n * Runs the full pipeline and throws on any plugin error. Automatically calls `setup()` if needed.\n */\n build(): Promise<BuildOutput>\n /**\n * Runs the full pipeline and captures errors in `BuildOutput` instead of throwing. Automatically calls `setup()` if needed.\n */\n safeBuild(): Promise<BuildOutput>\n}\n\ntype SetupResult = {\n hooks: AsyncEventEmitter<KubbHooks>\n driver: PluginDriver\n sources: Map<string, string>\n config: Config\n}\n\nasync function setup(userConfig: UserConfig, options: SetupOptions = {}): Promise<SetupResult> {\n const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()\n const config: Config = {\n ...userConfig,\n root: userConfig.root || process.cwd(),\n parsers: userConfig.parsers ?? [],\n adapter: userConfig.adapter,\n output: {\n format: false,\n lint: false,\n extension: DEFAULT_EXTENSION,\n defaultBanner: DEFAULT_BANNER,\n ...userConfig.output,\n },\n storage: userConfig.storage ?? fsStorage(),\n devtools: userConfig.devtools\n ? {\n studioUrl: DEFAULT_STUDIO_URL,\n ...(typeof userConfig.devtools === 'boolean' ? {} : userConfig.devtools),\n }\n : undefined,\n plugins: (userConfig.plugins ?? []) as unknown as Config['plugins'],\n }\n const driver = new PluginDriver(config, {\n hooks,\n })\n const sources: Map<string, string> = new Map<string, string>()\n const diagnosticInfo = getDiagnosticInfo()\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [\n 'Configuration:',\n ` • Name: ${userConfig.name || 'unnamed'}`,\n ` • Root: ${userConfig.root || process.cwd()}`,\n ` • Output: ${userConfig.output?.path || 'not specified'}`,\n ` • Plugins: ${userConfig.plugins?.length || 0}`,\n 'Output Settings:',\n ` • Storage: ${config.storage.name}`,\n ` • Formatter: ${userConfig.output?.format || 'none'}`,\n ` • Linter: ${userConfig.output?.lint || 'none'}`,\n 'Environment:',\n Object.entries(diagnosticInfo)\n .map(([key, value]) => ` • ${key}: ${value}`)\n .join('\\n'),\n ],\n })\n\n try {\n if (isInputPath(userConfig) && !new URLPath(userConfig.input.path).isURL) {\n await exists(userConfig.input.path)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ Input file validated: ${userConfig.input.path}`],\n })\n }\n } catch (caughtError) {\n if (isInputPath(userConfig)) {\n const error = caughtError as Error\n\n throw new Error(\n `Cannot read file/URL defined in \\`input.path\\` or set with \\`kubb generate PATH\\` in the CLI of your Kubb config ${userConfig.input.path}`,\n {\n cause: error,\n },\n )\n }\n }\n\n\n\n if (config.output.clean) {\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: ['Cleaning output directories', ` • Output: ${config.output.path}`],\n })\n await config.storage.clear(resolve(config.root, config.output.path))\n }\n\n // Register middleware hooks after all plugin hooks are registered.\n // Because AsyncEventEmitter calls listeners in registration order,\n // middleware hooks for any event fire after all plugin hooks for that event.\n function registerMiddlewareHook<K extends keyof KubbHooks & string>(event: K, middlewareHooks: Middleware['hooks']) {\n const handler = middlewareHooks[event]\n if (handler) {\n hooks.on(event, handler)\n }\n }\n\n for (const middleware of config.middleware ?? []) {\n for (const event of Object.keys(middleware.hooks) as Array<keyof KubbHooks & string>) {\n registerMiddlewareHook(event, middleware.hooks)\n }\n }\n\n if (config.adapter) {\n const source = inputToAdapterSource(config)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`Running adapter: ${config.adapter.name}`],\n })\n\n driver.adapter = config.adapter\n driver.inputNode = await config.adapter.parse(source)\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [\n `✓ Adapter '${config.adapter.name}' resolved InputNode`,\n ` • Schemas: ${driver.inputNode.schemas.length}`,\n ` • Operations: ${driver.inputNode.operations.length}`,\n ],\n })\n }\n\n return {\n config,\n hooks,\n driver,\n sources,\n }\n}\n\n/**\n * Walks the AST and dispatches nodes to a plugin's direct AST hooks\n * (`schema`, `operation`, `operations`).\n *\n * When `include` contains only operation-scoped filters (`tag`, `operationId`, `path`,\n * `method`, `contentType`) and no `schemaName` filter, the function pre-computes the set\n * of top-level schema names transitively reachable from the included operations and skips\n * schemas that fall outside that set. This ensures that component schemas referenced\n * exclusively by excluded operations are not generated.\n */\nasync function runPluginAstHooks(plugin: NormalizedPlugin, context: GeneratorContext): Promise<void> {\n const { adapter, inputNode, resolver, driver } = context\n const { exclude, include, override } = plugin.options\n\n if (!adapter || !inputNode) {\n throw new Error(`[${plugin.name}] No adapter found. Add an OAS adapter (e.g. adapterOas()) before this plugin in your Kubb config.`)\n }\n\n function resolveRenderer(gen: Generator): RendererFactory | undefined {\n return gen.renderer === null ? undefined : (gen.renderer ?? plugin.renderer ?? context.config.renderer)\n }\n\n const generators = plugin.generators ?? []\n const collectedOperations: Array<OperationNode> = []\n\n const generatorContext = {\n ...context,\n resolver: driver.getResolver(plugin.name),\n }\n\n // When `include` has operation-based filters (tag, operationId, path, method, contentType)\n // but no schema-level filters (schemaName), pre-compute the set of top-level schema names\n // that are transitively referenced by the included operations. Schemas outside that set are\n // skipped so that types belonging exclusively to excluded operations are not generated.\n const operationFilterTypes = new Set(['tag', 'operationId', 'path', 'method', 'contentType'])\n const hasOperationBasedIncludes = include?.some(({ type }) => operationFilterTypes.has(type)) ?? false\n const hasSchemaNameIncludes = include?.some(({ type }) => type === 'schemaName') ?? false\n\n let allowedSchemaNames: Set<string> | undefined\n if (hasOperationBasedIncludes && !hasSchemaNameIncludes) {\n const includedOps = inputNode.operations.filter((op) => resolver.resolveOptions(op, { options: plugin.options, exclude, include, override }) !== null)\n allowedSchemaNames = collectUsedSchemaNames(includedOps, inputNode.schemas)\n }\n\n await walk(inputNode, {\n depth: 'shallow',\n async schema(node) {\n const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node\n\n // Skip named top-level schemas that are not reachable from any included operation.\n if (allowedSchemaNames !== undefined && transformedNode.name && !allowedSchemaNames.has(transformedNode.name)) {\n return\n }\n\n const options = resolver.resolveOptions(transformedNode, {\n options: plugin.options,\n exclude,\n include,\n override,\n })\n if (options === null) return\n\n const ctx = { ...generatorContext, options }\n\n for (const gen of generators) {\n if (!gen.schema) continue\n const result = await gen.schema(transformedNode, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:schema', transformedNode, ctx)\n },\n async operation(node) {\n const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node\n const options = resolver.resolveOptions(transformedNode, {\n options: plugin.options,\n exclude,\n include,\n override,\n })\n if (options !== null) {\n collectedOperations.push(transformedNode)\n\n const ctx = { ...generatorContext, options }\n\n for (const gen of generators) {\n if (!gen.operation) continue\n const result = await gen.operation(transformedNode, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:operation', transformedNode, ctx)\n }\n },\n })\n\n if (collectedOperations.length > 0) {\n const ctx = { ...generatorContext, options: plugin.options }\n\n for (const gen of generators) {\n if (!gen.operations) continue\n const result = await gen.operations(collectedOperations, ctx)\n await applyHookResult(result, driver, resolveRenderer(gen))\n }\n\n await driver.hooks.emit('kubb:generate:operations', collectedOperations, ctx)\n }\n}\n\nasync function safeBuild(setupResult: SetupResult): Promise<BuildOutput> {\n const { driver, hooks, sources } = setupResult\n\n const failedPlugins = new Set<{ plugin: Plugin; error: Error }>()\n const pluginTimings = new Map<string, number>()\n const config = driver.config\n\n try {\n await driver.emitSetupHooks()\n\n if (driver.adapter && driver.inputNode) {\n await hooks.emit('kubb:build:start', {\n config,\n adapter: driver.adapter,\n inputNode: driver.inputNode,\n getPlugin: driver.getPlugin.bind(driver),\n get files() {\n return driver.fileManager.files\n },\n upsertFile: (...files) => driver.fileManager.upsert(...files),\n })\n }\n\n for (const plugin of driver.plugins.values()) {\n const context = driver.getContext(plugin)\n const hrStart = process.hrtime()\n\n try {\n const timestamp = new Date()\n\n await hooks.emit('kubb:plugin:start', { plugin })\n await hooks.emit('kubb:debug', {\n date: timestamp,\n logs: ['Starting plugin...', ` • Plugin Name: ${plugin.name}`],\n })\n\n if (plugin.generators?.length || driver.hasRegisteredGenerators(plugin.name)) {\n await runPluginAstHooks(plugin, context)\n }\n\n const duration = getElapsedMs(hrStart)\n pluginTimings.set(plugin.name, duration)\n\n await hooks.emit('kubb:plugin:end', {\n plugin,\n duration,\n success: true,\n config,\n get files() {\n return driver.fileManager.files\n },\n upsertFile: (...files) => driver.fileManager.upsert(...files),\n })\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ Plugin started successfully (${formatMs(duration)})`],\n })\n } catch (caughtError) {\n const error = caughtError as Error\n const errorTimestamp = new Date()\n const duration = getElapsedMs(hrStart)\n\n await hooks.emit('kubb:plugin:end', {\n plugin,\n duration,\n success: false,\n error,\n config,\n get files() {\n return driver.fileManager.files\n },\n upsertFile: (...files) => driver.fileManager.upsert(...files),\n })\n\n await hooks.emit('kubb:debug', {\n date: errorTimestamp,\n logs: [\n '✗ Plugin start failed',\n ` • Plugin Name: ${plugin.name}`,\n ` • Error: ${error.constructor.name} - ${error.message}`,\n ' • Stack Trace:',\n error.stack || 'No stack trace available',\n ],\n })\n\n failedPlugins.add({ plugin, error })\n }\n }\n\n await hooks.emit('kubb:plugins:end', {\n config,\n get files() {\n return driver.fileManager.files\n },\n upsertFile: (...files) => driver.fileManager.upsert(...files),\n })\n\n const files = driver.fileManager.files\n\n const parsersMap = new Map<FileNode['extname'], Parser>()\n for (const parser of config.parsers) {\n if (parser.extNames) {\n for (const extname of parser.extNames) {\n parsersMap.set(extname, parser)\n }\n }\n }\n\n const fileProcessor = new FileProcessor()\n\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`Writing ${files.length} files...`],\n })\n\n await fileProcessor.run(files, {\n parsers: parsersMap,\n mode: 'parallel',\n extension: config.output.extension,\n onStart: async (processingFiles) => {\n await hooks.emit('kubb:files:processing:start', { files: processingFiles })\n },\n onUpdate: async ({ file, source, processed, total, percentage }) => {\n await hooks.emit('kubb:file:processing:update', {\n file,\n source,\n processed,\n total,\n percentage,\n config,\n })\n if (source) {\n await config.storage.setItem(file.path, source)\n\n sources.set(file.path, source)\n }\n },\n onEnd: async (processedFiles) => {\n await hooks.emit('kubb:files:processing:end', { files: processedFiles })\n await hooks.emit('kubb:debug', {\n date: new Date(),\n logs: [`✓ File write process completed for ${processedFiles.length} files`],\n })\n },\n })\n\n await hooks.emit('kubb:build:end', {\n files,\n config,\n outputDir: resolve(config.root, config.output.path),\n })\n\n return {\n failedPlugins,\n files,\n driver,\n pluginTimings,\n sources,\n }\n } catch (error) {\n return {\n failedPlugins,\n files: [],\n driver,\n pluginTimings,\n error: error as Error,\n sources,\n }\n } finally {\n driver.dispose()\n }\n}\n\nasync function build(setupResult: SetupResult): Promise<BuildOutput> {\n const { files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(setupResult)\n\n if (error) {\n throw error\n }\n\n if (failedPlugins.size > 0) {\n const errors = [...failedPlugins].map(({ error }) => error)\n\n throw new BuildError(`Build Error with ${failedPlugins.size} failed plugins`, { errors })\n }\n\n return {\n failedPlugins,\n files,\n driver,\n pluginTimings,\n error: undefined,\n sources,\n }\n}\n\n/**\n * Returns a snapshot of the current runtime environment.\n *\n * Useful for attaching context to debug logs and error reports so that\n * issues can be reproduced without manual information gathering.\n */\nexport function getDiagnosticInfo() {\n return {\n nodeVersion,\n KubbVersion,\n platform: process.platform,\n arch: process.arch,\n cwd: process.cwd(),\n } as const\n}\n\n/**\n * Type guard to check if a given config has an `input.path`.\n */\nexport function isInputPath(config: UserConfig | undefined): config is UserConfig<InputPath> & { input: InputPath }\nexport function isInputPath(config: Config | undefined): config is Config<InputPath> & { input: InputPath }\nexport function isInputPath(config: Config | UserConfig | undefined): config is (Config<InputPath> | UserConfig<InputPath>) & { input: InputPath } {\n return typeof config?.input === 'object' && config.input !== null && 'path' in config.input\n}\n\nfunction inputToAdapterSource(config: Config): AdapterSource {\n const input = config.input\n if (!input) {\n throw new Error('[kubb] input is required when using an adapter. Provide input.path or input.data in your config.')\n }\n\n if ('data' in input) {\n return { type: 'data', data: input.data }\n }\n\n if (new URLPath(input.path).isURL) {\n return { type: 'path', path: input.path }\n }\n\n const resolved = resolve(config.root, input.path)\n\n return { type: 'path', path: resolved }\n}\n\ntype CreateKubbOptions = {\n hooks?: AsyncEventEmitter<KubbHooks>\n}\n\n/**\n * Creates a Kubb instance bound to a single config entry.\n *\n * Accepts a user-facing config shape and resolves it to a full {@link Config} during\n * `setup()`. The instance then holds shared state (`hooks`, `sources`, `driver`, `config`)\n * across the `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before\n * calling `setup()` or `build()`.\n *\n * @example\n * ```ts\n * const kubb = createKubb(userConfig)\n *\n * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {\n * console.log(`${plugin.name} completed in ${duration}ms`)\n * })\n *\n * const { files, failedPlugins } = await kubb.safeBuild()\n * ```\n */\nexport function createKubb(userConfig: UserConfig, options: CreateKubbOptions = {}): Kubb {\n const hooks = options.hooks ?? new AsyncEventEmitter<KubbHooks>()\n let setupResult: SetupResult | undefined\n\n const instance: Kubb = {\n get hooks() {\n return hooks\n },\n get sources() {\n return setupResult?.sources ?? new Map()\n },\n get driver() {\n return setupResult?.driver\n },\n get config() {\n return setupResult?.config\n },\n async setup() {\n setupResult = await setup(userConfig, { hooks })\n },\n async build() {\n if (!setupResult) {\n await instance.setup()\n }\n return build(setupResult!)\n },\n async safeBuild() {\n if (!setupResult) {\n await instance.setup()\n }\n return safeBuild(setupResult!)\n },\n }\n\n return instance\n}\n","import type { FileNode } from '@kubb/ast'\n\n/**\n * Minimal interface any Kubb renderer must satisfy.\n *\n * The generic `TElement` is the type of the element the renderer accepts —\n * e.g. `KubbReactElement` for `@kubb/renderer-jsx`, or a custom type for\n * your own renderer. Defaults to `unknown` so that generators which do not\n * care about the element type continue to work without specifying it.\n *\n * This allows core to drive rendering without a hard dependency on\n * `@kubb/renderer-jsx` or any specific renderer implementation.\n */\nexport type Renderer<TElement = unknown> = {\n render(element: TElement): Promise<void>\n unmount(error?: Error | number | null): void\n readonly files: Array<FileNode>\n}\n\n/**\n * A factory function that produces a fresh {@link Renderer} per render.\n *\n * Generators use this to declare which renderer handles their output.\n */\nexport type RendererFactory<TElement = unknown> = () => Renderer<TElement>\n\n/**\n * Creates a renderer factory for use in generator definitions.\n *\n * Wrap your renderer factory function with this helper to register it as the\n * renderer for a generator. Core will call this factory once per render cycle\n * to obtain a fresh renderer instance.\n *\n * @example\n * ```ts\n * // packages/renderer-jsx/src/index.ts\n * export const jsxRenderer = createRenderer(() => {\n * const runtime = new Runtime()\n * return {\n * async render(element) { await runtime.render(element) },\n * get files() { return runtime.nodes },\n * unmount(error) { runtime.unmount(error) },\n * }\n * })\n *\n * // packages/plugin-zod/src/generators/zodGenerator.tsx\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n * export const zodGenerator = defineGenerator<PluginZod>({\n * name: 'zod',\n * renderer: jsxRenderer,\n * schema(node, options) { return <File ...>...</File> },\n * })\n * ```\n */\nexport function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement> {\n return factory\n}\n","import type { AsyncEventEmitter, PossiblePromise } from '@internals/utils'\nimport type { FileNode, InputNode, OperationNode, SchemaNode, Visitor } from '@kubb/ast'\nimport type { Adapter } from './createAdapter.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { KubbHooks } from './types.ts'\nimport type { PluginDriver } from './PluginDriver.ts'\nimport type { Plugin, PluginFactoryOptions } from './definePlugin.ts'\nimport type { Resolver } from './defineResolver.ts'\nimport type { Config, DevtoolsOptions } from './types.ts'\n\n/**\n * Context object passed to generator `schema`, `operation`, and `operations` methods.\n *\n * The adapter is always defined (guaranteed by `runPluginAstHooks`) so no runtime checks\n * are needed. `ctx.options` carries resolved per-node options after exclude/include/override\n * filtering for individual schema/operation calls, or plugin-level options for operations.\n */\nexport type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {\n config: Config\n /**\n * Absolute path to the current plugin's output directory.\n */\n root: string\n /**\n * Determine output mode based on the output config.\n * Returns `'single'` when `output.path` is a file, `'split'` for a directory.\n */\n getMode: (output: { path: string }) => 'single' | 'split'\n driver: PluginDriver\n /**\n * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.\n */\n getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined\n getPlugin(name: string): Plugin | undefined\n /**\n * Get a plugin by name, throws an error if not found.\n */\n requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>\n requirePlugin(name: string): Plugin\n /**\n * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.\n */\n getResolver<TName extends keyof Kubb.PluginRegistry>(name: TName): Kubb.PluginRegistry[TName]['resolver']\n getResolver(name: string): Resolver\n /**\n * Add files only if they don't exist.\n */\n addFile: (...file: Array<FileNode>) => Promise<void>\n /**\n * Merge sources into the same output file.\n */\n upsertFile: (...file: Array<FileNode>) => Promise<void>\n hooks: AsyncEventEmitter<KubbHooks>\n /**\n * The current plugin instance.\n */\n plugin: Plugin<TOptions>\n /**\n * The current plugin's resolver.\n */\n resolver: TOptions['resolver']\n /**\n * The current plugin's transformer.\n */\n transformer: Visitor | undefined\n /**\n * Emit a warning.\n */\n warn: (message: string) => void\n /**\n * Emit an error.\n */\n error: (error: string | Error) => void\n /**\n * Emit an info message.\n */\n info: (message: string) => void\n /**\n * Open the current input node in Kubb Studio.\n */\n openInStudio: (options?: DevtoolsOptions) => Promise<void>\n /**\n * The configured adapter instance.\n */\n adapter: Adapter\n /**\n * The universal `InputNode` produced by the adapter.\n */\n inputNode: InputNode\n /**\n * Resolved options after exclude/include/override filtering.\n */\n options: TOptions['resolvedOptions']\n}\n\n/**\n * Declares a named generator unit that walks the AST and emits files.\n *\n * Each method (`schema`, `operation`, `operations`) is called for the matching node type.\n * Each method returns `TElement | Array<FileNode> | void`. JSX-based generators require a `renderer` factory.\n * Return `Array<FileNode>` directly or call `ctx.upsertFile()` manually and return `void` to bypass rendering.\n *\n * @note Generators are consumed by plugins and registered via `ctx.addGenerator()` in `kubb:plugin:setup`.\n *\n * @example\n * ```ts\n * import { defineGenerator } from '@kubb/core'\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n *\n * export const typeGenerator = defineGenerator({\n * name: 'typescript',\n * renderer: jsxRenderer,\n * schema(node, ctx) {\n * const { adapter, resolver, root, options } = ctx\n * return <File ...><Type node={node} resolver={resolver} /></File>\n * },\n * })\n * ```\n */\nexport type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {\n /**\n * Used in diagnostic messages and debug output.\n */\n name: string\n /**\n * Optional renderer factory that produces a {@link Renderer} for each render cycle.\n *\n * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this\n * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).\n *\n * Generators that only return `Array<FileNode>` or `void` do not need to set this.\n *\n * Set `renderer: null` to explicitly opt out of rendering even when the parent plugin\n * declares a `renderer` (overrides the plugin-level fallback).\n *\n * @example\n * ```ts\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n * export const myGenerator = defineGenerator<PluginTs>({\n * renderer: jsxRenderer,\n * schema(node, ctx) { return <File ...>...</File> },\n * })\n * ```\n */\n renderer?: RendererFactory<TElement> | null\n /**\n * Called for each schema node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n /**\n * Called for each operation node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n /**\n * Called once after all operations have been walked.\n * `ctx` carries the plugin context with `adapter` and `inputNode` guaranteed present,\n * plus `ctx.options` with the plugin-level options for the batch call.\n */\n operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | void>\n}\n\n/**\n * Defines a generator. Returns the object as-is with correct `this` typings.\n * `applyHookResult` handles renderer elements and `File[]` uniformly using\n * the generator's declared `renderer` factory.\n */\nexport function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(\n generator: Generator<TOptions, TElement>,\n): Generator<TOptions, TElement> {\n return generator\n}\n","import type { AsyncEventEmitter } from '@internals/utils'\nimport type { logLevel } from './constants.ts'\nimport type { KubbHooks } from './types.ts'\n\nexport type LoggerOptions = {\n /**\n * Log level for output verbosity.\n * @default 3\n */\n logLevel: (typeof logLevel)[keyof typeof logLevel]\n}\n\n/**\n * Shared context passed to plugins, parsers, and other internals.\n */\nexport type LoggerContext = AsyncEventEmitter<KubbHooks>\n\nexport type Logger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = {\n name: string\n install: (context: LoggerContext, options?: TOptions) => TInstallReturn | Promise<TInstallReturn>\n}\n\nexport type UserLogger<TOptions extends LoggerOptions = LoggerOptions, TInstallReturn = void> = Logger<TOptions, TInstallReturn>\n\n/**\n * Wraps a logger definition into a typed {@link Logger}.\n *\n * The optional second type parameter `TInstallReturn` allows loggers to return\n * a value from `install` — for example, a sink factory that the caller can\n * forward to hook execution.\n *\n * @example Basic logger\n * ```ts\n * export const myLogger = defineLogger({\n * name: 'my-logger',\n * install(context, options) {\n * context.on('kubb:info', (message) => console.log('ℹ', message))\n * context.on('kubb:error', (error) => console.error('✗', error.message))\n * },\n * })\n * ```\n *\n * @example Logger that returns a hook sink factory\n * ```ts\n * export const myLogger = defineLogger<LoggerOptions, HookSinkFactory>({\n * name: 'my-logger',\n * install(context, options) {\n * // … register event handlers …\n * return (commandWithArgs) => ({ onStdout: console.log })\n * },\n * })\n * ```\n */\nexport function defineLogger<Options extends LoggerOptions = LoggerOptions, TInstallReturn = void>(\n logger: UserLogger<Options, TInstallReturn>,\n): Logger<Options, TInstallReturn> {\n return logger\n}\n","import type { KubbHooks } from './types.ts'\n\n/**\n * A middleware instance produced by calling a factory created with `defineMiddleware`.\n * It declares event handlers under a `hooks` object which are registered on the\n * shared emitter after all plugin hooks, so middleware handlers for any event\n * always fire last.\n */\nexport type Middleware = {\n /**\n * Unique identifier for this middleware.\n */\n name: string\n /**\n * Lifecycle event handlers for this middleware.\n * Any event from the global `KubbHooks` map can be subscribed to here.\n * Handlers are registered after all plugin handlers, so they always fire last.\n */\n hooks: {\n [K in keyof KubbHooks]?: (...args: KubbHooks[K]) => void | Promise<void>\n }\n}\n\n/**\n * Creates a middleware factory using the hook-style `hooks` API.\n *\n * Middleware handlers fire after all plugin handlers for any given event, making them ideal for post-processing, logging, and auditing.\n * Per-build state (such as accumulators) belongs inside the factory closure so each `createKubb` invocation gets its own isolated instance.\n *\n * @note The factory can accept typed options. See examples for using options and per-build state patterns.\n *\n * @example\n * ```ts\n * import { defineMiddleware } from '@kubb/core'\n *\n * // Stateless middleware\n * export const logMiddleware = defineMiddleware(() => ({\n * name: 'log-middleware',\n * hooks: {\n * 'kubb:build:end'({ files }) {\n * console.log(`Build complete with ${files.length} files`)\n * },\n * },\n * }))\n *\n * // Middleware with options and per-build state\n * export const prefixMiddleware = defineMiddleware((options: { prefix: string } = { prefix: '' }) => {\n * const seen = new Set<string>()\n * return {\n * name: 'prefix-middleware',\n * hooks: {\n * 'kubb:plugin:end'({ plugin }) {\n * seen.add(`${options.prefix}${plugin.name}`)\n * },\n * },\n * }\n * })\n * ```\n */\nexport function defineMiddleware<TOptions extends object = object>(factory: (options: TOptions) => Middleware): (options?: TOptions) => Middleware {\n return (options) => factory(options ?? ({} as TOptions))\n}\n","import type { FileNode } from '@kubb/ast'\n\ntype PrintOptions = {\n extname?: FileNode['extname']\n}\n\nexport type Parser<TMeta extends object = any> = {\n name: string\n /**\n * File extensions this parser handles.\n * Use `undefined` to create a catch-all fallback parser.\n *\n * @example Handled extensions\n * `['.ts', '.js']`\n */\n extNames: Array<FileNode['extname']> | undefined\n /**\n * Convert a resolved file to a string.\n */\n parse(file: FileNode<TMeta>, options?: PrintOptions): Promise<string> | string\n}\n\n/**\n * Defines a parser with type safety. Creates parsers that transform generated files to strings based on their extension.\n *\n * @note Call the returned factory with optional options to instantiate the parser.\n *\n * @example\n * ```ts\n * import { defineParser } from '@kubb/core'\n *\n * export const jsonParser = defineParser({\n * name: 'json',\n * extNames: ['.json'],\n * parse(file) {\n * const { extractStringsFromNodes } = await import('@kubb/ast')\n * return file.sources.map((s) => extractStringsFromNodes(s.nodes ?? [])).join('\\n')\n * },\n * })\n * ```\n */\nexport function defineParser<TMeta extends object = any>(parser: Parser<TMeta>): Parser<TMeta> {\n return parser\n}\n","import { createStorage } from '../createStorage.ts'\n\n/**\n * In-memory storage driver. Useful for testing and dry-run scenarios where\n * generated output should be captured without touching the filesystem.\n *\n * All data lives in a `Map` scoped to the storage instance and is discarded\n * when the instance is garbage-collected.\n *\n * @example\n * ```ts\n * import { memoryStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: { path: './petStore.yaml' },\n * output: { path: './src/gen' },\n * storage: memoryStorage(),\n * })\n * ```\n */\nexport const memoryStorage = createStorage(() => {\n const store = new Map<string, string>()\n\n return {\n name: 'memory',\n async hasItem(key: string) {\n return store.has(key)\n },\n async getItem(key: string) {\n return store.get(key) ?? null\n },\n async setItem(key: string, value: string) {\n store.set(key, value)\n },\n async removeItem(key: string) {\n store.delete(key)\n },\n async getKeys(base?: string) {\n const keys = [...store.keys()]\n return base ? keys.filter((k) => k.startsWith(base)) : keys\n },\n async clear(base?: string) {\n if (!base) {\n store.clear()\n return\n }\n for (const key of store.keys()) {\n if (key.startsWith(base)) {\n store.delete(key)\n }\n }\n },\n }\n})\n"],"x_google_ignoreList":[8,9],"mappings":";;;;;;;;;;;;;;;;;;AASA,IAAa,aAAb,cAAgC,MAAM;CACpC;CAEA,YAAY,SAAiB,SAAkD;EAC7E,MAAM,SAAS,EAAE,OAAO,QAAQ,OAAO,CAAC;EACxC,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;;;;;;;;;;;;;;AAe1B,SAAgB,QAAQ,OAAuB;CAC7C,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC;;;;;;;;;;;;;;;ACZlE,IAAa,oBAAb,MAAoF;;;;;CAKlF,YAAY,cAAc,IAAI;EAC5B,KAAKA,SAAS,gBAAgB,YAAY;;CAG5C,WAAW,IAAIC,YAAAA,cAAkB;;;;;;;;;;CAWjC,MAAM,KAAgD,WAAuB,GAAG,WAA+C;EAC7H,MAAM,YAAY,KAAKD,SAAS,UAAU,UAAU;EAEpD,IAAI,UAAU,WAAW,GACvB;EAGF,KAAK,MAAM,YAAY,WACrB,IAAI;GACF,MAAM,SAAS,GAAG,UAAU;WACrB,KAAK;GACZ,IAAI;GACJ,IAAI;IACF,iBAAiB,KAAK,UAAU,UAAU;WACpC;IACN,iBAAi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zB,IAAI,CAAC,MAAM;IACT,MAAM,OAAO;IACb;;GAEF,KAAK,MAAM,OAAO,MAAM,MAAM,EAC5B,IAAI,IAAI,WAAW,KAAK,EACtB,MAAM,OAAO,IAAI;;EAIxB;EACD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["#reporterStorage","AsyncLocalStorage","getErrorMessage","toFilePath","#patternCache","#optionsCache","#options","#baseName","#filePath","#apply","camelCase","#resolveOptions","#resolvePath","#resolveFile","#resolveBanner","#resolveFooter","#testPattern","#matchesOperation","#matchesSchema","#computeOptions","operationDef","schemaDef","#resolveGroupDir","path","#resolveOverridePath","ast","#buildBannerMeta","#resolveUserText","#buildDefaultBanner","#macros","#composed","#memo","#invalidate","#visitorFor","FileManager","#hookGeneratorPlugins","#resolvers","#defaultResolvers","#unhooks","#transforms","#sortPlugins","#registerPlugin","#adapterSource","#parseInput","ast","#filesPayload","toError","#emitPluginEnd","#runGenerators","#getDefaultResolver","write","toPosixPath","clean","Hookable","#storage","#driver","BuildError","logLevel","logLevelMap","process","write"],"sources":["../src/createAdapter.ts","../src/applyConfigDefaults.ts","../../../internals/utils/src/time.ts","../../../internals/utils/src/colors.ts","../../../internals/utils/src/promise.ts","../package.json","../src/constants.ts","../src/Diagnostics.ts","../src/definePlugin.ts","../src/input.ts","../src/Resolver.ts","../src/createResolver.ts","../src/Transform.ts","../src/KubbDriver.ts","../src/createStorage.ts","../src/storages/fsStorage.ts","../src/createKubb.ts","../src/createReporter.ts","../src/reporters/report.ts","../src/reporters/cliReporter.ts","../src/reporters/fileReporter.ts","../src/reporters/jsonReporter.ts","../src/createRenderer.ts","../src/defineGenerator.ts","../src/defineParser.ts","../src/storages/memoryStorage.ts"],"sourcesContent":["import type { PossiblePromise } from '@internals/utils'\nimport type { ImportNode, InputNode, SchemaNode } from '@kubb/ast'\n\n/**\n * Source data handed to an adapter's `parse` function. Mirrors the config\n * input shape with paths resolved to absolute.\n *\n * - `{ type: 'path' }`: single file on disk.\n * - `{ type: 'data' }`: raw string or parsed object provided inline.\n */\nexport type AdapterSource = { type: 'path'; path: string } | { type: 'data'; data: string | unknown }\n\n/**\n * Generic parameters used by `createAdapter` and the resulting `Adapter` type.\n *\n * - `TName`: unique adapter identifier (`'oas'`, `'asyncapi'`, ...).\n * - `TOptions`: user-facing options accepted by the adapter factory.\n * - `TResolvedOptions`: options after defaults are applied.\n * - `TDocument`: type of the parsed source document.\n */\nexport type AdapterFactoryOptions<\n TName extends string = string,\n TOptions extends object = object,\n TResolvedOptions extends object = TOptions,\n TDocument = unknown,\n> = {\n name: TName\n options: TOptions\n resolvedOptions: TResolvedOptions\n document: TDocument\n}\n\n/**\n * Converts input files or inline data into Kubb's universal AST `InputNode`.\n *\n * Adapters live between the spec format and the plugins. The built-in\n * `@kubb/adapter-oas` handles OpenAPI 2.0, 3.0, and 3.1. A custom adapter can\n * support GraphQL, gRPC, or another schema language.\n *\n * @example\n * ```ts\n * import { defineConfig } from 'kubb'\n * import { adapterOas } from '@kubb/adapter-oas'\n * import { pluginTs } from '@kubb/plugin-ts'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * adapter: adapterOas(),\n * plugins: [pluginTs()],\n * })\n * ```\n */\nexport type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {\n /**\n * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).\n */\n name: TOptions['name']\n /**\n * Resolved adapter options after defaults have been applied.\n */\n options: TOptions['resolvedOptions']\n /**\n * Parsed source document after the first `parse()` call. `null` before parsing.\n */\n document: TOptions['document'] | null\n /**\n * Parse the source into a universal `InputNode`.\n */\n parse: (source: AdapterSource) => PossiblePromise<InputNode>\n /**\n * Extract `ImportNode` entries for a schema tree.\n * Returns an empty array before the first `parse()` call.\n *\n * The `resolve` callback receives the collision-corrected schema name and must\n * return `{ name, path }` for the import, or `undefined` to skip it.\n */\n getImports: (node: SchemaNode, resolve: (schemaName: string) => { name: string; path: string }) => Array<ImportNode>\n /**\n * Validate the document at the given path or URL.\n */\n validate: (input: string, options?: { throwOnError?: boolean }) => Promise<void>\n}\n\ntype AdapterBuilder<T extends AdapterFactoryOptions> = (options: T['options']) => Adapter<T>\n\n/**\n * Defines a custom adapter that translates a spec format into Kubb's universal\n * AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`\n * handles OpenAPI/Swagger documents.\n *\n * Adapters must return an `InputNode` from `parse`. That node is what every\n * plugin in the build consumes.\n *\n * @example\n * ```ts\n * import { createAdapter, type AdapterFactoryOptions } from '@kubb/core'\n * import { ast } from '@kubb/ast'\n *\n * type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }>\n *\n * export const myAdapter = createAdapter<MyAdapter>((options) => ({\n * name: 'my-adapter',\n * options,\n * document: null,\n * async parse(_source) {\n * // Convert the source (path or inline data) into an InputNode.\n * return ast.factory.createInput()\n * },\n * getImports: () => [],\n * async validate() {\n * // Throw here when the spec is invalid.\n * },\n * }))\n * ```\n */\nexport function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(build: AdapterBuilder<T>): (options?: T['options']) => Adapter<T> {\n return (options) => build(options ?? ({} as T['options']))\n}\n","import type { Adapter, Config, Plugin } from './types.ts'\n\ntype ApplyConfigDefaultsOptions<TOutput> = {\n defaultAdapter: Adapter\n barrelPlugin: Plugin\n barrelPluginName: string\n /** Output fields to fill in when the user's config leaves them unset. */\n defaultOutput: Partial<TOutput>\n}\n\n/**\n * Fills in the config defaults shared by `defineConfig` and the unplugin factory: the fallback\n * adapter, `defaultOutput`'s fields, and appending the barrel plugin when it's not already\n * registered. Both entry points construct their own adapter, barrel plugin, and output defaults\n * (`barrel` is a `@kubb/plugin-barrel` extension field core doesn't know about) and pass them in,\n * so `@kubb/core` doesn't need to depend on `@kubb/adapter-oas` or `@kubb/plugin-barrel`.\n */\nexport function applyConfigDefaults<TOutput extends Config['output'] = Config['output']>(\n config: { adapter?: Adapter; output: TOutput; plugins?: Array<Plugin> },\n { defaultAdapter, barrelPlugin, barrelPluginName, defaultOutput }: ApplyConfigDefaultsOptions<TOutput>,\n): { adapter: Adapter; output: TOutput; plugins: Array<Plugin> } {\n const alreadyHasBarrel = config.plugins?.some((plugin) => plugin.name === barrelPluginName)\n const plugins = alreadyHasBarrel ? (config.plugins ?? []) : [...(config.plugins ?? []), barrelPlugin]\n\n return {\n adapter: config.adapter ?? defaultAdapter,\n plugins,\n output: { ...defaultOutput, ...config.output },\n }\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n","import { hash } from 'node:crypto'\nimport { styleText } from 'node:util'\nimport { formatMs } from './time.ts'\n\n/**\n * Parsed RGB channels from a CSS hex color string.\n */\ntype RGB = { r: number; g: number; b: number }\n\n/**\n * Parses a CSS hex color string (`#RGB`) into its RGB channels.\n * Falls back to `255` for any channel that cannot be parsed.\n */\nfunction parseHex(color: string): RGB {\n const int = Number.parseInt(color.replace('#', ''), 16)\n return Number.isNaN(int) ? { r: 255, g: 255, b: 255 } : { r: (int >> 16) & 0xff, g: (int >> 8) & 0xff, b: int & 0xff }\n}\n\n/**\n * Returns a function that wraps a string in a 24-bit ANSI true-color escape sequence\n * for the given hex color.\n */\nfunction hex(color: string): (text: string) => string {\n const { r, g, b } = parseHex(color)\n return (text: string) => `\\x1b[38;2;${r};${g};${b}m${text}\\x1b[0m`\n}\n\nfunction gradient(colorStops: Array<string>, text: string): string {\n const chars = text.split('')\n return chars\n .map((char, i) => {\n const t = chars.length <= 1 ? 0 : i / (chars.length - 1)\n const seg = Math.min(Math.floor(t * (colorStops.length - 1)), colorStops.length - 2)\n const lt = t * (colorStops.length - 1) - seg\n const from = parseHex(colorStops[seg]!)\n const to = parseHex(colorStops[seg + 1]!)\n const r = Math.round(from.r + (to.r - from.r) * lt)\n const g = Math.round(from.g + (to.g - from.g) * lt)\n const b = Math.round(from.b + (to.b - from.b) * lt)\n return `\\x1b[38;2;${r};${g};${b}m${char}\\x1b[0m`\n })\n .join('')\n}\n\n/**\n * ANSI color functions for each part of the Kubb mascot illustration.\n */\nconst palette = {\n /**\n * Top cap of the skittle.\n */\n lid: hex('#F55A17'),\n /**\n * Upper wood body.\n */\n woodTop: hex('#F5A217'),\n /**\n * Middle wood body.\n */\n woodMid: hex('#F58517'),\n /**\n * Base wood body.\n */\n woodBase: hex('#B45309'),\n /**\n * Eye whites.\n */\n eye: hex('#FFFFFF'),\n /**\n * Highlight accent.\n */\n highlight: hex('#adadc6'),\n /**\n * Cheek blush.\n */\n blush: hex('#FDA4AF'),\n}\n\n/**\n * Generates the Kubb mascot welcome banner as an ANSI-colored string.\n *\n * @example\n * ```ts\n * console.log(getIntro({ title: 'kubb.config.ts', description: 'generating…', version: '5.0.0', areEyesOpen: true }))\n * ```\n */\nexport function getIntro({\n title,\n description,\n version,\n areEyesOpen,\n}: {\n /**\n * Name of the active configuration or tool being started.\n */\n title: string\n /**\n * Short subtitle shown next to the arrow prompt.\n */\n description: string\n /**\n * Kubb version string rendered in the gradient header.\n */\n version: string\n /**\n * When `false` the eyes are shown as closed dashes instead of open blocks.\n */\n areEyesOpen: boolean\n}): string {\n const kubbVersion = gradient(['#F58517', '#F5A217', '#F55A17'], `KUBB v${version}`)\n\n const eyeTop = areEyesOpen ? palette.eye('█▀█') : palette.eye('───')\n const eyeBottom = areEyesOpen ? palette.eye('▀▀▀') : palette.eye('───')\n\n return `\n ${palette.lid('▄▄▄▄▄▄▄▄▄▄▄▄▄')}\n ${palette.woodTop('█ ')}${palette.highlight('▄▄')}${palette.woodTop(' ')}${palette.highlight('▄▄')}${palette.woodTop(' █')} ${kubbVersion}\n ${palette.woodMid('█ ')}${eyeTop}${palette.woodMid(' ')}${eyeTop}${palette.woodMid(' █')} ${styleText('gray', title)}\n ${palette.woodMid('█ ')}${eyeBottom}${palette.woodMid(' ')}${palette.blush('◡')}${palette.woodMid(' ')}${eyeBottom}${palette.woodMid(' █')} ${styleText('yellow', '➜')} ${styleText('white', description)}\n ${palette.woodBase('▀▀▀▀▀▀▀▀▀▀▀▀▀')}\n`\n}\n\n/**\n * ANSI color names used by {@link randomCliColor} for deterministic terminal coloring.\n */\nconst randomColors = ['black', 'red', 'green', 'yellow', 'blue', 'white', 'magenta', 'cyan', 'gray'] as const\n\n/**\n * Wraps `text` in a deterministic ANSI color derived from the text's SHA-256 hash.\n *\n * @example\n * ```ts\n * randomCliColor('petstore') // '\\x1b[33m' + 'petstore' + '\\x1b[39m' (always the same color for 'petstore')\n * ```\n */\nexport function randomCliColor(text?: string): string {\n if (!text) return ''\n const index = hash('sha256', text, 'buffer').readUInt32BE(0) % randomColors.length\n const color = randomColors[index] ?? 'white'\n\n return styleText(color, text)\n}\n\n/**\n * Formats a millisecond duration with a threshold-based ANSI color.\n * `≤ 500 ms` → green · `≤ 1 000 ms` → yellow · `> 1 000 ms` → red.\n *\n * @example\n * ```ts\n * formatMsWithColor(200) // '\\x1b[32m200ms\\x1b[39m'\n * formatMsWithColor(800) // '\\x1b[33m800ms\\x1b[39m'\n * formatMsWithColor(1500) // '\\x1b[31m1.50s\\x1b[39m'\n * ```\n */\nexport function formatMsWithColor(ms: number): string {\n const formatted = formatMs(ms)\n if (ms <= 500) return styleText('green', formatted)\n if (ms <= 1000) return styleText('yellow', formatted)\n\n return styleText('red', formatted)\n}\n","import { toError } from './errors.ts'\n\n/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\ntype SerialRunnerOptions = {\n /**\n * The async work to serialize.\n */\n run(): Promise<void>\n /**\n * Receives errors thrown by `run`, so a failure never rejects the returned trigger.\n */\n onError(error: Error): void\n}\n\n/**\n * Wraps `run` so invocations never overlap: a trigger that lands while a run is in flight\n * marks it dirty and runs once more after it finishes, no matter how many triggers arrived.\n * Useful for event-driven reruns (a file watcher, a queue drain) where bursts should\n * coalesce into a single trailing run.\n *\n * @example\n * ```ts\n * const rebuild = createSerialRunner({\n * run: () => build(),\n * onError: (error) => log.error(error.message),\n * })\n * watcher.on('change', () => void rebuild())\n * ```\n */\nexport function createSerialRunner({ run, onError }: SerialRunnerOptions): () => Promise<void> {\n let running = false\n let dirty = false\n\n return async (): Promise<void> => {\n if (running) {\n dirty = true\n return\n }\n running = true\n do {\n dirty = false\n try {\n await run()\n } catch (error) {\n onError(toError(error))\n }\n } while (dirty)\n running = false\n }\n}\n","","/**\n * Maximum number of █ characters in a plugin timing bar.\n */\nexport const SUMMARY_MAX_BAR_LENGTH = 10 as const\n\n/**\n * Divides elapsed milliseconds into bar-length units (1 block per 100 ms).\n */\nexport const SUMMARY_TIME_SCALE_DIVISOR = 100 as const\n\n/**\n * Upper bound of hook listeners a single plugin can add to one hook (its schema, operation,\n * and operations generators, plus lifecycle hooks). Used to size the hooks emitter's\n * max-listener ceiling so a multi-generator plugin set does not trip Node's leak warning.\n */\nexport const HOOK_LISTENERS_PER_PLUGIN = 4\n\n/**\n * Plugin `include` filter types that select operations directly. When one of these is set\n * without a `schemaName` include, the generate phase pre-scans operations to compute the set\n * of schemas they reach, so unreachable schemas can be pruned for that plugin.\n */\nexport const OPERATION_FILTER_TYPES: ReadonlySet<string> = new Set(['tag', 'operationId', 'path', 'method', 'contentType'])\n\n/**\n * Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode\n * and stays stable so it can be referenced in tooling and (later) docs. Reference\n * these instead of inlining the string at a throw site.\n */\nexport const diagnosticCode = {\n /**\n * Fallback for an unstructured error with no specific code.\n */\n unknown: 'KUBB_UNKNOWN',\n /**\n * The file or URL set as `input` could not be read.\n */\n inputNotFound: 'KUBB_INPUT_NOT_FOUND',\n /**\n * An adapter was configured without an `input`.\n */\n inputRequired: 'KUBB_INPUT_REQUIRED',\n /**\n * A `$ref` (or equivalent reference) could not be resolved in the source document.\n */\n refNotFound: 'KUBB_REF_NOT_FOUND',\n /**\n * A server variable value is not allowed by its `enum`.\n */\n invalidServerVariable: 'KUBB_INVALID_SERVER_VARIABLE',\n /**\n * A required plugin is missing from the config.\n */\n pluginNotFound: 'KUBB_PLUGIN_NOT_FOUND',\n /**\n * A plugin threw while generating.\n */\n pluginFailed: 'KUBB_PLUGIN_FAILED',\n /**\n * A plugin reported a non-fatal warning through `ctx.warn`.\n */\n pluginWarning: 'KUBB_PLUGIN_WARNING',\n /**\n * A plugin reported an informational message through `ctx.info`.\n */\n pluginInfo: 'KUBB_PLUGIN_INFO',\n /**\n * A schema uses a `format` Kubb does not map to a specific type. Reserved for\n * adapters to emit as a `warning`.\n */\n unsupportedFormat: 'KUBB_UNSUPPORTED_FORMAT',\n /**\n * A referenced schema or operation is marked `deprecated`. Reserved for adapters\n * to emit as an `info`.\n */\n deprecated: 'KUBB_DEPRECATED',\n /**\n * An adapter is required but the config has none. The build cannot read the input\n * without one.\n */\n adapterRequired: 'KUBB_ADAPTER_REQUIRED',\n /**\n * A resolved output path escapes the output directory, which can stem from a path\n * traversal in the spec or a misconfigured `group.name`.\n */\n pathTraversal: 'KUBB_PATH_TRAVERSAL',\n /**\n * A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.\n */\n invalidPluginOptions: 'KUBB_INVALID_PLUGIN_OPTIONS',\n /**\n * A post-generate command (`output.postGenerate`) exited with a failure.\n */\n postGenerateFailed: 'KUBB_POST_GENERATE_FAILED',\n /**\n * The formatter pass over the generated files failed.\n */\n formatFailed: 'KUBB_FORMAT_FAILED',\n /**\n * The linter pass over the generated files failed.\n */\n lintFailed: 'KUBB_LINT_FAILED',\n /**\n * Not a failure. Carries a plugin's elapsed time, summed into the run total.\n */\n performance: 'KUBB_PERFORMANCE',\n /**\n * Not a failure. A newer Kubb version is available on npm.\n */\n updateAvailable: 'KUBB_UPDATE_AVAILABLE',\n} as const\n\n/**\n * Union of the stable {@link diagnosticCode} values.\n */\nexport type DiagnosticCode = (typeof diagnosticCode)[keyof typeof diagnosticCode]\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { styleText } from 'node:util'\nimport { getErrorMessage } from '@internals/utils'\nimport { version } from '../package.json'\nimport { type DiagnosticCode, diagnosticCode } from './constants.ts'\nimport type { KubbHooks } from './types.ts'\nimport type { Hookable } from './Hookable.ts'\n\n/**\n * Docs major version, derived from the package version so the link tracks the published major.\n */\nconst docsMajor = version.split('.')[0] ?? '5'\n\n/**\n * How serious a diagnostic is. `error` fails the build, `warning` and `info`\n * are reported but do not.\n */\nexport type DiagnosticSeverity = 'error' | 'warning' | 'info'\n\n/**\n * A human-readable explanation of a diagnostic code: a short title, what triggers it, and how\n * to resolve it. This is the source of truth the kubb.dev `/diagnostics/<slug>` pages mirror, so\n * every code stays documented in one place. Adding a code without documenting it fails the build.\n */\nexport type DiagnosticDoc = {\n /**\n * Short title shown as the docs heading.\n */\n title: string\n /**\n * What triggers the diagnostic.\n */\n cause: string\n /**\n * The action that resolves it.\n */\n fix: string\n}\n\n/**\n * Points a diagnostic back into the source document. Inputs are parsed into an\n * object model with no line/column, so locations carry a JSON pointer the adapter\n * builds (the OAS adapter emits `#/components/schemas/Pet`). A `config` diagnostic\n * points at the Kubb config itself and so has no pointer.\n */\nexport type DiagnosticLocation =\n | {\n kind: 'schema'\n /**\n * RFC 6901 JSON pointer into the source document.\n */\n pointer: string\n /**\n * The original reference when the diagnostic stems from an unresolved one.\n */\n ref?: string\n }\n | {\n kind: 'operation' | 'document'\n /**\n * RFC 6901 JSON pointer into the source document.\n */\n pointer: string\n }\n | {\n kind: 'config'\n }\n\n/**\n * What a diagnostic carries.\n * - `problem` is a build issue shown to the user, and the only kind rendered as a problem.\n * - `performance` records a plugin's elapsed time.\n * - `update` is a version notice.\n */\nexport type DiagnosticKind = 'problem' | 'performance' | 'update'\n\n/**\n * Codes that describe a build problem: every {@link DiagnosticCode} except the\n * `performance` and `updateAvailable` codes, which ride on their own variants.\n */\nexport type ProblemCode = Exclude<DiagnosticCode, typeof diagnosticCode.performance | typeof diagnosticCode.updateAvailable>\n\n/**\n * A build problem collected during a run, gathered into the result instead of\n * aborting on the first failure.\n */\nexport type ProblemDiagnostic = {\n /**\n * @default 'problem'\n */\n kind?: 'problem'\n /**\n * Stable identifier for the problem, from the {@link diagnosticCode} catalog.\n */\n code: ProblemCode\n severity: DiagnosticSeverity\n message: string\n location?: DiagnosticLocation\n /**\n * A suggested fix, phrased as an action the user can take.\n */\n help?: string\n /**\n * Name of the plugin or subsystem that produced the diagnostic.\n */\n plugin?: string\n /**\n * The underlying error, when the diagnostic wraps a thrown one.\n */\n cause?: Error\n}\n\n/**\n * A per-plugin performance record, built with {@link Diagnostics.performance}. The `performance`\n * kind keeps it out of the problem list. It feeds the per-plugin timing bars, and reporters sum\n * these into the run total.\n */\nexport type PerformanceDiagnostic = {\n kind: 'performance'\n code: typeof diagnosticCode.performance\n severity: 'info'\n message: string\n /**\n * The plugin this measurement belongs to.\n */\n plugin: string\n /**\n * Elapsed milliseconds.\n */\n duration: number\n}\n\n/**\n * A notice that a newer Kubb version is available on npm, built with {@link Diagnostics.update}.\n * It renders like any info diagnostic.\n */\nexport type UpdateDiagnostic = {\n kind: 'update'\n code: typeof diagnosticCode.updateAvailable\n severity: 'info'\n message: string\n /**\n * The running Kubb version.\n */\n currentVersion: string\n /**\n * The newest version published on npm.\n */\n latestVersion: string\n}\n\n/**\n * A structured record collected during a build, discriminated on `kind`: a\n * {@link ProblemDiagnostic} for an issue, a {@link PerformanceDiagnostic} for a per-plugin\n * timing, or an {@link UpdateDiagnostic} for a version notice.\n */\nexport type Diagnostic = ProblemDiagnostic | PerformanceDiagnostic | UpdateDiagnostic\n\n/**\n * Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic\n * with no `kind` is treated as a `problem`.\n */\nfunction isKind<T extends Diagnostic>(kind: DiagnosticKind) {\n return (diagnostic: Diagnostic): diagnostic is T => (diagnostic.kind ?? 'problem') === kind\n}\n\n/**\n * Returns `true` when the diagnostic is a build {@link ProblemDiagnostic}.\n *\n * @example\n * ```ts\n * if (isProblem(diagnostic)) {\n * console.log(diagnostic.location)\n * }\n * ```\n */\nconst isProblem = isKind<ProblemDiagnostic>('problem')\n\n/**\n * Returns `true` when the diagnostic is a per-plugin {@link PerformanceDiagnostic}.\n *\n * @example\n * ```ts\n * const timings = diagnostics.filter(isPerformance)\n * ```\n */\nconst isPerformance = isKind<PerformanceDiagnostic>('performance')\n\n/**\n * Returns `true` when the diagnostic is a version-update {@link UpdateDiagnostic}.\n *\n * @example\n * ```ts\n * if (isUpdate(diagnostic)) {\n * console.log(diagnostic.latestVersion)\n * }\n * ```\n */\nconst isUpdate = isKind<UpdateDiagnostic>('update')\n\n/**\n * Accent color per severity. The color tints the `[CODE]` tag (red error, yellow warning,\n * blue info).\n */\nconst severityStyle: Record<DiagnosticSeverity, 'red' | 'yellow' | 'blue'> = {\n error: 'red',\n warning: 'yellow',\n info: 'blue',\n}\n\n/**\n * A {@link Diagnostic} reduced to its JSON-safe fields plus a `docsUrl`, for\n * machine-readable output (the `--reporter json` report, the MCP tools). Drops the\n * non-serializable `cause` and the `kind`/`duration` bookkeeping.\n */\nexport type SerializedDiagnostic = {\n code: DiagnosticCode\n severity: DiagnosticSeverity\n message: string\n location?: DiagnosticLocation\n help?: string\n plugin?: string\n /**\n * The kubb.dev docs link for the code, omitted for the unknown fallback.\n */\n docsUrl?: string\n}\n\n/**\n * Explanation for every {@link diagnosticCode}. Use {@link Diagnostics.explain} to look one up\n * and `Diagnostics.docsUrl` for the matching kubb.dev page.\n */\nconst diagnosticCatalog: Record<DiagnosticCode, DiagnosticDoc> = {\n [diagnosticCode.unknown]: {\n title: 'Unknown error',\n cause: 'An error was thrown without a stable Kubb code, so it is reported as-is.',\n fix: 'Read the underlying message and stack. If it comes from a plugin or adapter, check its configuration; otherwise report it as a possible Kubb bug.',\n },\n [diagnosticCode.inputNotFound]: {\n title: 'Input not found',\n cause: 'The file or URL set as `input` (or passed as `kubb generate PATH`) could not be read.',\n fix: 'Check that the path or URL exists and is readable, then set it as `input` or pass it on the CLI.',\n },\n [diagnosticCode.inputRequired]: {\n title: 'Input required',\n cause: 'An adapter is configured but no `input` was provided.',\n fix: 'Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.',\n },\n [diagnosticCode.refNotFound]: {\n title: 'Reference not found',\n cause: 'A `$ref` could not be resolved in the source document.',\n fix: 'Add the missing definition (for example under `components.schemas`) or fix the `$ref`. Run `kubb validate` to check the spec.',\n },\n [diagnosticCode.invalidServerVariable]: {\n title: 'Invalid server variable',\n cause: 'A server variable value is not allowed by its `enum`.',\n fix: 'Use one of the values listed in the server variable `enum`, or update the spec.',\n },\n [diagnosticCode.pluginNotFound]: {\n title: 'Plugin not found',\n cause: 'A plugin that another plugin depends on is missing from the config.',\n fix: 'Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it.',\n },\n [diagnosticCode.pluginFailed]: {\n title: 'Plugin failed',\n cause: 'A plugin threw while generating, or reported an error through `ctx.error`.',\n fix: 'Read the underlying error and check the plugin options and the schema or operation it failed on.',\n },\n [diagnosticCode.pluginWarning]: {\n title: 'Plugin warning',\n cause: 'A plugin reported a non-fatal warning through `ctx.warn`.',\n fix: 'Review the message. It does not fail the build; adjust the plugin options or input if the warning is unwanted.',\n },\n [diagnosticCode.pluginInfo]: {\n title: 'Plugin info',\n cause: 'A plugin reported an informational message through `ctx.info`.',\n fix: 'Informational only. No action is required.',\n },\n [diagnosticCode.unsupportedFormat]: {\n title: 'Unsupported format',\n cause: 'A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.',\n fix: 'Use a format Kubb supports, or handle the custom format with a parser or plugin.',\n },\n [diagnosticCode.deprecated]: {\n title: 'Deprecated',\n cause: 'A referenced schema or operation is marked `deprecated`.',\n fix: 'Migrate off the deprecated definition if the warning is unwanted.',\n },\n [diagnosticCode.adapterRequired]: {\n title: 'Adapter required',\n cause: 'An action needs an adapter but none is configured.',\n fix: 'Set `adapter` in kubb.config.ts, for example `adapterOas()`.',\n },\n [diagnosticCode.pathTraversal]: {\n title: 'Path traversal',\n cause: 'A resolved output path escaped the output directory, which can stem from a path traversal in the spec or a misconfigured `group.name`.',\n fix: 'Keep generated paths within the output directory. Review the `group.name` function and the names coming from the spec.',\n },\n [diagnosticCode.invalidPluginOptions]: {\n title: 'Invalid plugin options',\n cause: \"A plugin was configured with options that cannot be honored, for example `output.mode: 'file'` paired with a `group` option.\",\n fix: \"Fix the plugin options. A single-file output has nothing to group, so remove the `group` option or use `output.mode: 'directory'`.\",\n },\n [diagnosticCode.postGenerateFailed]: {\n title: 'Post-generate command failed',\n cause: 'A post-generate command (`output.postGenerate`) exited with a non-zero status.',\n fix: 'Check the command is installed and correct, and run it manually to see the error.',\n },\n [diagnosticCode.formatFailed]: {\n title: 'Format failed',\n cause: 'The formatter pass over the generated files failed.',\n fix: 'Check the formatter (oxfmt, biome, or prettier) is installed and its config is valid, then run it manually on the output.',\n },\n [diagnosticCode.lintFailed]: {\n title: 'Lint failed',\n cause: 'The linter pass over the generated files failed.',\n fix: 'Check the linter (oxlint, biome, or eslint) is installed and its config is valid, then run it manually on the output.',\n },\n [diagnosticCode.performance]: {\n title: 'Performance',\n cause: 'Not a failure. Records a plugin’s elapsed time, summed into the run total.',\n fix: 'No action. This is an informational metric.',\n },\n [diagnosticCode.updateAvailable]: {\n title: 'Update available',\n cause: 'A newer Kubb version is published on npm than the one running.',\n fix: 'Update the `@kubb/*` packages, for example `npm install -g @kubb/cli`, to get the latest fixes.',\n },\n}\n\n/**\n * Static helpers for working with {@link Diagnostic}s, plus the run-scoped sink\n * that lets deep code report a diagnostic without threading a callback.\n *\n * The sink lives in a single `AsyncLocalStorage` in the `@kubb/core` bundle.\n * `Diagnostics.scope` activates it for a run, so anything inside that run (the\n * adapter parse, a generator) reports through `Diagnostics.report` and lands\n * in the same run.\n */\nexport class Diagnostics {\n static #reporterStorage = new AsyncLocalStorage<(diagnostic: Diagnostic) => void>()\n\n /**\n * The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).\n */\n static code = diagnosticCode\n\n /**\n * Type guard for a build {@link ProblemDiagnostic}.\n */\n static isProblem = isProblem\n\n /**\n * Type guard for a version-update {@link UpdateDiagnostic}.\n */\n static isUpdate = isUpdate\n\n /**\n * Type guard for a per-plugin {@link PerformanceDiagnostic}.\n */\n static isPerformance = isPerformance\n\n /**\n * An `Error` that carries a {@link Diagnostic}, so structured problems can flow\n * through the existing throw/catch paths while keeping their code and location.\n *\n * @example\n * ```ts\n * throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })\n * ```\n */\n static Error = class DiagnosticError extends Error {\n diagnostic: ProblemDiagnostic\n\n constructor(diagnostic: ProblemDiagnostic) {\n super(diagnostic.message, { cause: diagnostic.cause })\n this.name = 'DiagnosticError'\n this.diagnostic = diagnostic\n }\n }\n\n /**\n * Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated\n * `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`\n * that carries a `code`.\n */\n static isError(error: unknown): error is InstanceType<typeof Diagnostics.Error> {\n if (error instanceof Diagnostics.Error) {\n return true\n }\n return (\n error instanceof Error &&\n error.name === 'DiagnosticError' &&\n 'diagnostic' in error &&\n typeof (error as { diagnostic?: unknown }).diagnostic === 'object' &&\n (error as { diagnostic?: Diagnostic }).diagnostic !== null &&\n typeof (error as { diagnostic?: { code?: unknown } }).diagnostic?.code === 'string'\n )\n }\n\n /**\n * Runs `fn` with `sink` as the active diagnostic sink for the whole async\n * subtree, so {@link Diagnostics.report} reaches it from anywhere inside.\n */\n static scope<T>(sink: (diagnostic: Diagnostic) => void, fn: () => T): T {\n return Diagnostics.#reporterStorage.run(sink, fn)\n }\n\n /**\n * Collects a diagnostic into the active build via the run-scoped sink, without throwing.\n * Returns `true` when a run consumed it, `false` when called outside a {@link Diagnostics.scope}\n * (so callers can fall back to throwing). Use a `warning`/`info` severity for non-fatal issues.\n * For rendering a diagnostic live on the hook bus, use {@link Diagnostics.emit} instead.\n */\n static report(diagnostic: Diagnostic): boolean {\n const sink = Diagnostics.#reporterStorage.getStore()\n if (!sink) {\n return false\n }\n sink(diagnostic)\n return true\n }\n\n /**\n * Emits a diagnostic on the run's `kubb:diagnostic` hook so the loggers render it live.\n * Use it instead of calling `hooks.callHook('kubb:diagnostic', ...)` directly. To collect a\n * diagnostic into the build result from deep in a run, use {@link Diagnostics.report} instead.\n */\n static async emit(hooks: Hookable<KubbHooks>, diagnostic: ProblemDiagnostic | UpdateDiagnostic): Promise<void> {\n await hooks.callHook('kubb:diagnostic', { diagnostic })\n }\n\n /**\n * Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}\n * keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.\n */\n static from(error: unknown): ProblemDiagnostic {\n // The hook emitter and BuildError wrap the original, so walk the cause chain to\n // recover a Diagnostics.Error thrown deeper down. `root` tracks the deepest error so\n // the unknown diagnostic reports the original message and stack, not the wrapper's.\n const seen = new Set<unknown>()\n let current: unknown = error\n let root: Error | undefined\n while (current instanceof Error && !seen.has(current)) {\n // Match structurally, not just by `instanceof`: a `Diagnostics.Error` thrown from a\n // duplicated `@kubb/core` copy (bundled into an adapter or plugin) is a different\n // class, but still carries the same `diagnostic`, so its code must survive.\n if (Diagnostics.isError(current)) {\n return current.diagnostic\n }\n seen.add(current)\n root = current\n current = current.cause\n }\n\n return {\n code: diagnosticCode.unknown,\n severity: 'error',\n message: root ? root.message : getErrorMessage(error),\n cause: root,\n }\n }\n\n /**\n * Builds a per-plugin performance record. Reporters sum these into the run total.\n */\n static performance({ plugin, duration }: { plugin: string; duration: number }): PerformanceDiagnostic {\n return {\n kind: 'performance',\n code: diagnosticCode.performance,\n severity: 'info',\n message: `${plugin} generated in ${Math.round(duration)}ms`,\n plugin,\n duration,\n }\n }\n\n /**\n * Builds the version-update notice shown when a newer Kubb is published on npm.\n */\n static update({ currentVersion, latestVersion }: { currentVersion: string; latestVersion: string }): UpdateDiagnostic {\n return {\n kind: 'update',\n code: diagnosticCode.updateAvailable,\n severity: 'info',\n message: `Update available: v${currentVersion} → v${latestVersion}. Run \\`npm install -g @kubb/cli\\` to update.`,\n currentVersion,\n latestVersion,\n }\n }\n\n /**\n * True when any diagnostic is an error, the severity that fails a build. Non-error\n * diagnostics are ignored.\n */\n static hasError(diagnostics: ReadonlyArray<Diagnostic>): boolean {\n return diagnostics.some((diagnostic) => diagnostic.severity === 'error')\n }\n\n /**\n * Names of the plugins that failed, deduped, derived from the error diagnostics\n * that carry a `plugin`.\n */\n static failedPlugins(diagnostics: ReadonlyArray<Diagnostic>): Array<string> {\n const names = new Set<string>()\n for (const diagnostic of diagnostics) {\n if (diagnostic.severity === 'error' && diagnostic.plugin) {\n names.add(diagnostic.plugin)\n }\n }\n return [...names]\n }\n\n /**\n * Counts `problem` diagnostics by severity for the run summary. `performance` and\n * `update` diagnostics are ignored.\n */\n static count(diagnostics: ReadonlyArray<Diagnostic>): { errors: number; warnings: number; infos: number } {\n let errors = 0\n let warnings = 0\n let infos = 0\n for (const diagnostic of diagnostics) {\n if (!isProblem(diagnostic)) {\n continue\n }\n if (diagnostic.severity === 'error') {\n errors += 1\n } else if (diagnostic.severity === 'warning') {\n warnings += 1\n } else {\n infos += 1\n }\n }\n return { errors, warnings, infos }\n }\n\n /**\n * Drops duplicate `problem` diagnostics that share a code, location pointer, and\n * plugin, so the same issue reported across several passes is shown once. Non-problem\n * diagnostics are always kept.\n */\n static dedupe(diagnostics: ReadonlyArray<Diagnostic>): Array<Diagnostic> {\n const seen = new Set<string>()\n const result: Array<Diagnostic> = []\n for (const diagnostic of diagnostics) {\n if (!isProblem(diagnostic)) {\n result.push(diagnostic)\n continue\n }\n const pointer = diagnostic.location && 'pointer' in diagnostic.location ? diagnostic.location.pointer : ''\n const key = `${diagnostic.code} ${pointer} ${diagnostic.plugin ?? ''}`\n if (seen.has(key)) {\n continue\n }\n seen.add(key)\n result.push(diagnostic)\n }\n return result\n }\n\n /**\n * Builds the kubb.dev docs URL for a diagnostic code, e.g.\n * `KUBB_REF_NOT_FOUND` → `https://kubb.dev/docs/5.x/reference/diagnostics/kubb-ref-not-found`.\n */\n static docsUrl(code: string): string {\n const slug = code.toLowerCase().replaceAll('_', '-')\n return `https://kubb.dev/docs/${docsMajor}.x/reference/diagnostics/${slug}`\n }\n\n /**\n * The catalog entry for a code: its title, cause, and fix. Mirrors the kubb.dev\n * `/diagnostics/<slug>` page.\n */\n static explain(code: DiagnosticCode): DiagnosticDoc {\n return diagnosticCatalog[code]\n }\n\n /**\n * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable\n * consumers. The `cause`, `kind`, and `duration` are dropped, and absent optional\n * fields are omitted rather than set to `undefined`.\n */\n static serialize(diagnostic: Diagnostic): SerializedDiagnostic {\n const problem = isProblem(diagnostic) ? diagnostic : undefined\n return {\n code: diagnostic.code,\n severity: diagnostic.severity,\n message: diagnostic.message,\n ...(problem?.location ? { location: problem.location } : {}),\n ...(problem?.help ? { help: problem.help } : {}),\n ...(problem?.plugin ? { plugin: problem.plugin } : {}),\n ...(diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }),\n }\n }\n\n /**\n * Renders a {@link Diagnostic} for terminal output as its parts: the `headline`\n * (`[CODE] plugin: message`, with the code in the severity color) and the indented `details`\n * rows (`at:` pointer, `fix:` help, `see:` docs link).\n *\n * Hosts compose these to fit their gutter: a clack logger passes `[headline, ...details]` as the\n * message with no gutter symbol, while plain text outputs use {@link Diagnostics.formatLines}.\n */\n static format(diagnostic: Diagnostic): { headline: string; details: Array<string> } {\n const { code, severity, message } = diagnostic\n const color = severityStyle[severity]\n const problem = isProblem(diagnostic) ? diagnostic : undefined\n\n const tag = styleText(color, styleText('bold', `[${code}]`))\n const headline = problem?.plugin ? `${tag} ${problem.plugin}: ${message}` : `${tag}: ${message}`\n\n const details: Array<string> = []\n if (problem?.location && 'pointer' in problem.location) {\n details.push(` ${styleText('dim', 'at:')} ${styleText('cyan', problem.location.pointer)}`)\n }\n if (problem?.help) {\n details.push(` ${styleText('cyan', 'fix:')} ${problem.help}`)\n }\n if (code !== diagnosticCode.unknown) {\n details.push(` ${styleText('dim', 'see:')} ${styleText('cyan', Diagnostics.docsUrl(code))}`)\n }\n\n return { headline, details }\n }\n\n /**\n * The self-contained block form of {@link Diagnostics.format}: the `headline` followed by the\n * indented detail rows. Used where there is no gutter (plain and file output).\n */\n static formatLines(diagnostic: Diagnostic): Array<string> {\n const { headline, details } = Diagnostics.format(diagnostic)\n return [headline, ...details]\n }\n}\n","import type { Enforce, FileNode, HttpMethod, Macro, UserFileNode } from '@kubb/ast'\nimport { diagnosticCode } from './constants.ts'\nimport type { Generator } from './defineGenerator.ts'\nimport type { BannerMeta, Resolver, ResolverPatch } from './Resolver.ts'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { Config, KubbHooks } from './types.ts'\n\ntype ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {}\n\n/**\n * How a plugin consolidates its generated code into files.\n * - `'directory'` writes one file per operation or schema under `path`.\n * - `'file'` writes everything into a single file.\n */\nexport type OutputMode = 'directory' | 'file'\n\n/**\n * Output configuration shared by every plugin. Each plugin extends this with\n * its own keys via the `Kubb.PluginOptionsRegistry.output` interface merge.\n */\nexport type Output = {\n /**\n * Directory where the plugin writes its generated code, resolved against the global\n * `output.path` set on `defineConfig`. With `mode: 'file'`, this is the full output file\n * path and must include the extension (e.g. `'types.ts'`, `'models.py'`).\n */\n path: string\n /**\n * How generated code is consolidated into files.\n * - `'directory'` writes one file per operation or schema under `path`.\n * - `'file'` writes everything into a single file. The `path` must include the file extension.\n *\n * @default 'directory'\n */\n mode?: OutputMode\n /**\n * Text prepended to every generated file. Useful for license headers,\n * lint disables, or `@ts-nocheck` directives.\n *\n * A string is applied to every file (including barrel and aggregation re-export files).\n * Pass a function to compute the banner from the file's `BannerMeta` document metadata\n * plus per-file context (`isBarrel`, `isAggregation`, `filePath`, `baseName`), so you can\n * skip the banner on specific files.\n *\n * @example Add a directive to source files but not re-export files\n * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : \"'use server'\"`\n */\n banner?: string | ((meta: BannerMeta) => string)\n /**\n * Text appended at the end of every generated file. Mirror of `banner`.\n * Pass a function to compute the footer from the file's `BannerMeta`.\n */\n footer?: string | ((meta: BannerMeta) => string)\n} & ExtractRegistryKey<Kubb.PluginOptionsRegistry, 'output'>\n\n/**\n * Groups generated files into subdirectories based on an OpenAPI tag or path\n * segment.\n */\nexport type Group = {\n /**\n * Property used to assign each operation to a group.\n * - `'tag'` uses the first tag (`operation.getTags().at(0)?.name`).\n * - `'path'` uses the first segment of the operation's URL.\n */\n type: 'tag' | 'path'\n /**\n * Returns the subdirectory name from the group key. Defaults to the camelCased tag for\n * `tag` groups, or the camelCased first path segment for `path` groups.\n */\n name?: (context: { group: string }) => string\n}\n\n/**\n * Couples `output.mode` with the plugin's `group` option at the type level.\n * - `mode: 'file'` forbids `group` (a single file has nothing to group).\n * - `mode: 'directory'` (or no mode) allows an optional `group` to organize\n * files into per-group subdirectories.\n *\n * Intersect into a plugin's `Options` type instead of declaring `output` and\n * `group` directly, since `mode` lives inside `output` while `group` is its sibling.\n * The generic keeps a plugin's extended `Output` shape intact.\n *\n * @example\n * ```ts\n * export type Options = OutputOptions & {\n * exclude?: Array<Exclude>\n * }\n * ```\n */\nexport type OutputOptions<TOutput extends Output = Output> =\n | {\n output?: TOutput & { mode?: 'directory' }\n group?: Group\n }\n | {\n output: TOutput & { mode: 'file' }\n group?: never\n }\n\n/**\n * Merges the `output.mode` default into the output config and validates the combination.\n * Throws `KUBB_INVALID_PLUGIN_OPTIONS` when `mode: 'file'` is paired with a `group` option,\n * since a single-file output has nothing to group.\n */\nexport function normalizeOutput({ output, group, pluginName }: { output: Output; group?: Group | null; pluginName: string }): Output {\n const mode = output.mode ?? 'directory'\n\n if (mode === 'file' && group) {\n throw new Diagnostics.Error({\n code: diagnosticCode.invalidPluginOptions,\n severity: 'error',\n message: `Plugin \"${pluginName}\" sets \\`output.mode: 'file'\\` but also configures a \\`group\\` option.`,\n help: \"A single-file output has nothing to group. Remove the `group` option, or use `output.mode: 'directory'` to organize files into subdirectories.\",\n location: { kind: 'config' },\n plugin: pluginName,\n })\n }\n\n return { ...output, mode }\n}\n\ntype ByTag = {\n /**\n * Filter by OpenAPI `tags` field. Matches one or more tags assigned to operations.\n */\n type: 'tag'\n /**\n * Tag name to match (case-sensitive). Can be a literal string or regex pattern.\n */\n pattern: string | RegExp\n}\n\ntype ByOperationId = {\n /**\n * Filter by OpenAPI `operationId` field. Each operation (GET, POST, etc.) has a unique identifier.\n */\n type: 'operationId'\n /**\n * Operation ID to match (case-sensitive). Can be a literal string or regex pattern.\n */\n pattern: string | RegExp\n}\n\ntype ByPath = {\n /**\n * Filter by OpenAPI `path` (URL endpoint). Useful to group or filter by service segments like `/pets`, `/users`, etc.\n */\n type: 'path'\n /**\n * URL path to match (case-sensitive). Can be a literal string or regex pattern. Matches against the full path.\n */\n pattern: string | RegExp\n}\n\ntype ByMethod = {\n /**\n * Filter by HTTP method: `'GET'`, `'POST'`, `'PUT'`, `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`.\n */\n type: 'method'\n /**\n * HTTP method to match, as one of the `HttpMethod` values (`'GET'`, `'POST'`, `'PUT'`,\n * `'PATCH'`, `'DELETE'`, `'HEAD'`, `'OPTIONS'`, `'TRACE'`) or a regex.\n */\n pattern: HttpMethod | RegExp\n}\n\ntype BySchemaName = {\n /**\n * Filter by schema component name (TypeScript or JSON schema). Matches schemas in `#/components/schemas`.\n */\n type: 'schemaName'\n /**\n * Schema name to match (case-sensitive). Can be a literal string or regex pattern.\n */\n pattern: string | RegExp\n}\n\ntype ByContentType = {\n /**\n * Filter by response or request content type: `'application/json'`, `'application/xml'`, etc.\n */\n type: 'contentType'\n /**\n * Content type to match (case-sensitive). Can be a literal string or regex pattern.\n */\n pattern: string | RegExp\n}\n\n/**\n * Pattern filter for include, exclude, and override rules. Matches operations or schemas\n * by tag, operationId, path, method, content type, or schema name.\n */\nexport type Filter = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName\n\n/**\n * Filter that skips matching operations or schemas during generation, for example\n * deprecated endpoints or internal-only schemas.\n *\n * @example\n * ```ts\n * exclude: [\n * { type: 'tag', pattern: 'internal' },\n * { type: 'path', pattern: /^\\/admin/ },\n * { type: 'operationId', pattern: /^deprecated_/ },\n * ]\n * ```\n */\nexport type Exclude = Filter\n\n/**\n * Filter that restricts generation to operations or schemas matching at least\n * one entry. Useful for partial builds (one tag, one API version).\n *\n * @example\n * ```ts\n * include: [\n * { type: 'tag', pattern: 'public' },\n * { type: 'path', pattern: /^\\/api\\/v1/ },\n * ]\n * ```\n */\nexport type Include = Filter\n\n/**\n * Filter paired with a partial options object. When the filter matches, the\n * options are merged on top of the plugin defaults for that operation only.\n * Useful for \"this one tag goes to a different folder\" rules.\n *\n * Entries are evaluated top to bottom. The first matching entry wins.\n *\n * @example\n * ```ts\n * override: [\n * {\n * type: 'tag',\n * pattern: 'admin',\n * options: { output: { path: './src/gen/admin' } },\n * },\n * {\n * type: 'operationId',\n * pattern: 'listPets',\n * options: { enumType: 'literal' },\n * },\n * ]\n * ```\n */\nexport type Override<TOptions> = Filter & {\n options: Omit<Partial<TOptions>, 'override'>\n}\n\nexport type PluginFactoryOptions<\n /**\n * Unique plugin name.\n */\n TName extends string = string,\n /**\n * User-facing plugin options.\n */\n TOptions extends object = object,\n /**\n * Plugin options after defaults are applied.\n */\n TResolvedOptions extends object = TOptions,\n /**\n * Resolver that encapsulates naming and path-resolution helpers.\n * Define with `createResolver` and export alongside the plugin.\n */\n TResolver extends Resolver = Resolver,\n> = {\n name: TName\n options: TOptions\n resolvedOptions: TResolvedOptions\n resolver: TResolver\n}\n\n/**\n * Context passed to a plugin's `kubb:plugin:setup` handler, where it registers generators and\n * sets its resolver, transformer, and options.\n */\nexport type KubbPluginSetupContext<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {\n /**\n * Register one or more generators dynamically. Generators fire during the AST walk\n * (schema/operation/operations) just like generators declared statically on `createPlugin`.\n *\n * Pass generators as separate arguments. Spread an existing list to register it in one call.\n *\n * @example\n * ```ts\n * ctx.addGenerator(myGenerator)\n * ctx.addGenerator(schemaGenerator, operationGenerator)\n * ctx.addGenerator(...selectedGenerators)\n * ```\n */\n addGenerator<TElement = unknown>(...generators: Array<Generator<TFactory, TElement>>): void\n /**\n * Set or override the resolver for this plugin.\n * The resolver controls file naming and path resolution. Overrides merge over the built-in\n * defaults, so a partial `core` or a single namespace method replaces only what it names.\n */\n setResolver(resolver: ResolverPatch<TFactory['resolver']> | TFactory['resolver']): void\n /**\n * Add a macro that rewrites AST nodes before they reach generators. Macros run in the order they\n * are added, after any macros from earlier `addMacro` calls.\n */\n addMacro(macro: Macro): void\n /**\n * Replace this plugin's macros with `macros`.\n */\n setMacros(macros: ReadonlyArray<Macro>): void\n /**\n * Set resolved options merged into the normalized plugin's `options`.\n * Call this in `kubb:plugin:setup` to provide options generators need.\n */\n setOptions(options: TFactory['resolvedOptions']): void\n /**\n * Inject a raw file into the build output, bypassing the generation pipeline.\n *\n * Pass `copy` with an absolute path to emit a real source file (a shipped template) into the\n * generated folder verbatim, instead of building its content from `sources`.\n */\n injectFile(userFileNode: UserFileNode): void\n /**\n * The resolved build configuration at setup time.\n */\n config: Config\n /**\n * The plugin's user-provided options.\n */\n options: TFactory['options']\n}\n\n/**\n * A plugin object produced by `definePlugin`. Its lifecycle handlers live under a single\n * `hooks` property rather than flat methods.\n */\nexport type Plugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions> = {\n /**\n * Unique name for the plugin, following the same naming convention as `createPlugin`.\n */\n name: string\n /**\n * Plugins that must be registered before this plugin executes.\n * An error is thrown at startup when any listed dependency is missing.\n */\n dependencies?: Array<string>\n /**\n * Controls the execution order of this plugin relative to others.\n *\n * - `'pre'` runs before all normal plugins.\n * - `'post'` runs after all normal plugins.\n * - `undefined` (default) runs in declaration order among normal plugins.\n *\n * Dependency constraints always take precedence over `enforce`.\n */\n enforce?: Enforce\n /**\n * The options passed by the user when calling the plugin factory.\n */\n options?: TFactory['options']\n /**\n * Lifecycle hook handlers for this plugin.\n * Any hook from the global `KubbHooks` map can be subscribed to here.\n */\n hooks: {\n [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void>\n } & {\n 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>\n }\n}\n\n/**\n * Normalized plugin after setup, with runtime fields populated. Internal only. Plugins use the\n * public `Plugin` type.\n *\n * @internal\n */\nexport type NormalizedPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = Plugin<TOptions> & {\n options: TOptions['resolvedOptions'] & {\n output: Output\n include?: Array<Include>\n exclude: Array<Exclude>\n override: Array<Override<TOptions['resolvedOptions']>>\n }\n resolver: TOptions['resolver']\n macros?: Array<Macro>\n generators?: Array<Generator>\n}\n\nexport type KubbPluginStartContext = {\n plugin: NormalizedPlugin\n}\n\nexport type KubbPluginEndContext = {\n plugin: NormalizedPlugin\n duration: number\n success: boolean\n error?: Error\n config: Config\n /**\n * Returns all files currently in the file manager (lazy snapshot).\n * Includes files added by plugins that have already run.\n */\n readonly files: ReadonlyArray<FileNode>\n /**\n * Upsert one or more files into the file manager.\n */\n upsertFile: (...files: Array<FileNode>) => void\n}\n\n/**\n * Wraps a plugin factory and returns a function that accepts user options and\n * yields a typed `Plugin`. Lifecycle handlers go inside a single `hooks` object.\n *\n * Pass a `PluginFactoryOptions` type parameter to get a typed `ctx` inside\n * `kubb:plugin:setup`. Plugin names should follow the `plugin-<feature>`\n * convention (`plugin-react-query`, `plugin-zod`, ...).\n *\n * @example\n * ```ts\n * import { definePlugin } from '@kubb/core'\n *\n * export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({\n * name: 'plugin-ts',\n * hooks: {\n * 'kubb:plugin:setup'(ctx) {\n * ctx.setResolver(resolverTs)\n * },\n * },\n * }))\n * ```\n */\nexport function definePlugin<TFactory extends PluginFactoryOptions = PluginFactoryOptions>(\n factory: (options: TFactory['options']) => Plugin<TFactory>,\n): (options?: TFactory['options']) => Plugin<TFactory> {\n return (options) => factory(options ?? ({} as TFactory['options']))\n}\n","import { resolve } from 'node:path'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { AdapterSource, Config, Input } from './types.ts'\n\n/**\n * What an `input` value points at, once Kubb has looked at it.\n *\n * - `file` is a local file path, absolute or relative to the config file.\n * - `url` is a remote document to fetch.\n * - `inline` is OpenAPI content held in the string itself (JSON or YAML).\n * - `object` is an already-parsed spec.\n */\nexport type InputKind = 'file' | 'url' | 'inline' | 'object'\n\n/**\n * Classifies an `input` value so callers branch on it once instead of repeating the checks.\n *\n * A non-string is a parsed spec (`object`). A string is `inline` when it holds OpenAPI content,\n * meaning it starts with `{` or `[`, spans multiple lines, or opens with a YAML `openapi:` or\n * `swagger:` key. Otherwise a string is a `url` when it parses as one, or a `file` path.\n */\nexport function getInputKind(input: NonNullable<Input>): InputKind {\n if (typeof input !== 'string') return 'object'\n\n const trimmed = input.trimStart()\n const isInline = trimmed.startsWith('{') || trimmed.startsWith('[') || input.includes('\\n') || /^(openapi|swagger)\\s*:/i.test(trimmed)\n if (isInline) return 'inline'\n\n if (URL.canParse(input)) return 'url'\n\n return 'file'\n}\n\n/**\n * Normalizes `config.input` into an `AdapterSource` the adapter can parse.\n *\n * A parsed object and inline content become `{ type: 'data' }`; a URL is kept verbatim and a\n * local path is resolved against `config.root`, both as `{ type: 'path' }`.\n */\nexport function inputToAdapterSource(config: Config): AdapterSource {\n const input = config.input\n\n if (!input) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputRequired,\n severity: 'error',\n message: 'An adapter is configured without an input.',\n help: 'Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.',\n location: { kind: 'config' },\n })\n }\n\n if (typeof input !== 'string') {\n return { type: 'data', data: input }\n }\n\n const kind = getInputKind(input)\n if (kind === 'inline') return { type: 'data', data: input }\n if (kind === 'url') return { type: 'path', path: input }\n\n return { type: 'path', path: resolve(config.root, input) }\n}\n","import path from 'node:path'\nimport { camelCase, toFilePath } from '@internals/utils'\nimport { ast, operationDef, schemaDef, type FileNode, type InputMeta, type Node, type OperationNode, type SchemaNode } from '@kubb/ast'\nimport { Diagnostics } from './Diagnostics.ts'\nimport { getInputKind } from './input.ts'\nimport type { Filter, Override } from './definePlugin.ts'\nimport type { Config, Group, Output } from './types.ts'\n\n/**\n * Context for resolving filtered options for a given operation or schema node.\n *\n * @internal\n */\nexport type ResolveOptionsContext<TOptions> = {\n options: TOptions\n exclude?: Array<Filter>\n include?: Array<Filter>\n override?: Array<Override<TOptions>>\n}\n\n/**\n * The built-in resolution machinery exposed on every resolver as `resolver.default`.\n * Plugins delegate to it via `this.default.*` and set their own conventions through\n * the top-level `name` and `file` entries.\n */\nexport type ResolverDefault = {\n /**\n * Built-in camelCase casing for a generated identifier.\n */\n name(name: string): string\n options<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null\n path(options: ResolvePathOptions): string\n file(options: ResolveFileOptions): FileNode\n banner(meta: InputMeta | undefined, context: ResolveBannerContext): string | null\n footer(meta: InputMeta | undefined, context: ResolveBannerContext): string | null\n}\n\n/**\n * The name request for `resolver.default.path`: a `baseName` plus the optional `tag`/`path` that\n * grouping keys off.\n */\nexport type ResolverPathParams = {\n baseName: FileNode['baseName']\n /**\n * Tag value used when `group.type === 'tag'`.\n */\n tag?: string\n /**\n * Path value used when `group.type === 'path'`.\n */\n path?: string\n}\n\n/**\n * Options for `resolver.default.path`: the name request (`baseName`, `tag`, `path`) plus where the\n * output goes (`root`, `output`, `group`).\n *\n * @example\n * ```ts\n * resolver.default.path({ baseName: 'petTypes.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })\n * // → '/src/types/pets/petTypes.ts'\n * ```\n */\nexport type ResolvePathOptions = ResolverPathParams & {\n /**\n * Absolute project root that the output path is resolved against.\n */\n root: string\n /**\n * Active output config; `output.path` is the base directory.\n */\n output: Output\n /**\n * Optional grouping strategy applied to `tag` (tag grouping) or `path` (path grouping).\n */\n group?: Group\n}\n\n/**\n * The file request for `resolver.file` and `resolver.default.file`: the `name` and `extname` plus\n * the optional `tag`/`path` that grouping keys off.\n */\nexport type ResolverFileParams = {\n name: string\n extname: FileNode['extname']\n /**\n * Tag value used when `group.type === 'tag'`.\n */\n tag?: string\n /**\n * Path value used when `group.type === 'path'`.\n */\n path?: string\n}\n\n/**\n * Options for `resolver.file` and `resolver.default.file`: the file request (`name`, `extname`,\n * `tag`, `path`) plus where the output goes (`root`, `output`, `group`).\n *\n * @example\n * ```ts\n * resolver.default.file({ name: 'listPets', extname: '.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })\n * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }\n * ```\n */\nexport type ResolveFileOptions = ResolverFileParams & {\n root: string\n output: Output\n group?: Group\n}\n\n/**\n * The `file` field of a resolver: decides what a generated file is called and, optionally, where\n * it lives. This is how a resolver renames or relocates its files, replacing the older per-call\n * `resolveName` hook.\n *\n * @example Suffix every generated file\n * ```ts\n * file: {\n * baseName({ name, extname }) {\n * return `${name}Faker${extname}`\n * },\n * }\n * ```\n *\n * @example Own the full path\n * ```ts\n * file: {\n * path({ baseName, output }) {\n * return `${output.path}/mocks/${baseName}`\n * },\n * }\n * ```\n */\nexport type ResolverFile = {\n /**\n * Builds the file's complete base name, extension included, from the identifier and the target\n * `extname`. Defaults to `toFilePath(name)` with `extname` appended. Reaches sibling resolver\n * helpers through `this`.\n */\n baseName?(params: Pick<ResolverFileParams, 'name' | 'extname'>): FileNode['baseName']\n /**\n * Returns the file's complete path, resolved against the project `root`. Bypasses `output.path`\n * and `group`, so the resolver owns the layout. The returned path may not escape `root`. Reaches\n * sibling resolver helpers through `this`.\n */\n path?(params: ResolverFilePathParams): string\n}\n\n/**\n * The argument to a resolver's `file.path`: the resolved `baseName` (what `file.baseName` produced,\n * with the extension already appended) and the active `output`. `tag`, `path`, and `group` are\n * omitted because `file.path` owns the whole path and bypasses grouping, and `root` because the\n * returned path is resolved against it.\n */\nexport type ResolverFilePathParams = {\n baseName: FileNode['baseName']\n output: Output\n}\n\n/**\n * Per-file context describing the file a banner/footer is being resolved for, so a\n * `banner`/`footer` function can branch on the file kind (e.g. skip a `'use server'`\n * directive on re-export files).\n */\nexport type ResolveBannerFile = {\n /**\n * Full output path of the file being generated.\n */\n path: string\n /**\n * File name only, e.g. `'stocks.ts'`.\n */\n baseName: string\n /**\n * `true` for `index.ts` re-export barrels.\n */\n isBarrel?: boolean\n /**\n * `true` for group `[dir]/[dir].ts` aggregation files.\n */\n isAggregation?: boolean\n}\n\n/**\n * Document metadata extended with per-file context, passed to a `banner`/`footer` function.\n *\n * @example Skip a directive on re-export files\n * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : \"'use server'\"`\n */\nexport type BannerMeta = InputMeta & {\n /**\n * Full output path of the file being generated.\n */\n filePath: string\n /**\n * File name only, e.g. `'stocks.ts'`.\n */\n baseName: string\n /**\n * `true` for `index.ts` re-export barrels.\n */\n isBarrel: boolean\n /**\n * `true` for group `[dir]/[dir].ts` aggregation files.\n */\n isAggregation: boolean\n}\n\n/**\n * Context passed to `resolver.default.banner` and `resolver.default.footer`.\n * `output` is optional since not every plugin configures a banner/footer, and `config`\n * carries the global Kubb config used to derive the default Kubb banner.\n */\nexport type ResolveBannerContext = {\n output?: Pick<Output, 'banner' | 'footer'>\n config: Config\n file?: ResolveBannerFile\n}\n\n/**\n * Raw resolver fields passed to `createResolver` or patched through `Resolver.merge`.\n * `default` is the built-in machinery and is not user-settable.\n */\nexport type ResolverBuildOptions = {\n pluginName: string\n name?: (name: string) => string\n file?: ResolverFile\n [key: string]: unknown\n}\n\n/**\n * Partial resolver fields accepted by `Resolver.merge` and `setResolver`. Parameterize with a\n * concrete resolver type (e.g. `ResolverPatch<ResolverTs>`) to type-check overrides and bind\n * `this` to the full resolver. Namespaces are partial, so a patch may override a single method\n * (`query.name`) and the rest keep the plugin defaults. Overriding a whole resolver is not the\n * job of this patch, that is what a custom plugin is for.\n */\nexport type ResolverPatch<T extends Resolver = Resolver> = {\n [K in keyof Omit<T, keyof Resolver>]?: T[K] extends (...args: Array<never>) => unknown ? T[K] : Partial<T[K]>\n} & {\n name?: T['name']\n file?: ResolverFile\n} & ThisType<T>\n\nfunction isNamespace(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of\n * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own\n * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay\n * reachable and a `file` override is never dropped.\n */\nconst resolverOptions: unique symbol = Symbol.for('@kubb/core/resolver/options')\n\n/**\n * Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.\n */\nfunction toBaseName({ name, extname }: Pick<ResolverFileParams, 'name' | 'extname'>): FileNode['baseName'] {\n return `${toFilePath(name)}${extname}` as FileNode['baseName']\n}\n\n/**\n * Base constraint for all plugin resolver objects.\n *\n * The built-in machinery lives under `default`. Generators call the top-level `name` and\n * `file`, and a plugin overrides them to set its conventions. Extend with top-level helpers\n * (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).\n *\n * @example Top-level helper\n * ```ts\n * type MyResolver = Resolver & {\n * typeName(name: string): string\n * }\n * ```\n *\n * @example Grouped namespace\n * ```ts\n * type MyResolver = Resolver & {\n * query: {\n * name(node: OperationNode): string\n * keyName(node: OperationNode): string\n * }\n * }\n * ```\n */\nexport class Resolver {\n // String patterns are compiled lazily and cached, so the same filter is reused for every node.\n static #patternCache = new Map<string, RegExp>()\n static #optionsCache = new WeakMap<object, WeakMap<Node, { value: unknown }>>()\n\n readonly pluginName: string\n #options: ResolverBuildOptions\n // Base-name builder from `options.file.baseName`, bound to the resolver so it can reach `this`.\n // Defaults to `toBaseName` when a resolver sets no `file.baseName`.\n #baseName: (params: Pick<ResolverFileParams, 'name' | 'extname'>) => FileNode['baseName']\n // Full-path override from `options.file.path`, bound to the resolver. Absent by default, in which\n // case the built-in `output.path`/`group` layout is used.\n #filePath: ((params: ResolverFilePathParams) => string) | undefined\n\n constructor(options: ResolverBuildOptions) {\n this.pluginName = options.pluginName\n this.#options = options\n this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName\n this.#filePath = options.file?.path ? options.file.path.bind(this) : undefined\n this.#apply(options)\n }\n\n /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */\n get [resolverOptions](): ResolverBuildOptions {\n return this.#options\n }\n\n /**\n * The built-in resolution machinery. Always reaches the untouched defaults, even when a\n * plugin overrides the top-level `name` or `file`.\n */\n get default(): ResolverDefault {\n return {\n name: camelCase,\n options: this.#resolveOptions.bind(this),\n path: this.#resolvePath.bind(this),\n file: this.#resolveFile.bind(this),\n banner: this.#resolveBanner.bind(this),\n footer: this.#resolveFooter.bind(this),\n }\n }\n\n name(name: string): string {\n return this.default.name(name)\n }\n\n file(options: ResolveFileOptions): FileNode {\n return this.#resolveFile(options)\n }\n\n /**\n * Merges `override` over `base` and returns a new resolver with helpers re-bound. Top-level\n * keys replace, and a namespace (or `file`) merges per method, so overriding `query.name`\n * keeps the base `query.keyName`. Used when applying `setResolver` partial overrides. Reads a\n * resolver's options through the shared brand rather than `instanceof`, so a `file` override\n * survives even when `base` and `override` come from different `@kubb/core` copies.\n */\n static merge<T extends Resolver>(base: T, override: ResolverPatch<T> | Resolver): T {\n const patch = resolverOptions in override ? override[resolverOptions] : override\n const merged: Record<string, unknown> = { ...base[resolverOptions] }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue\n const current = merged[key]\n merged[key] = isNamespace(value) && isNamespace(current) ? { ...current, ...value } : value\n }\n return new Resolver(merged as ResolverBuildOptions) as T\n }\n\n /**\n * Binds each entry of `options` onto the resolver, so `this.name`, `this.default`, and\n * `this.file` resolve there for top-level helpers and namespace methods alike. `default`\n * is skipped so it can't be shadowed.\n */\n #apply(options: ResolverBuildOptions): void {\n const root = this as Resolver & Record<string, unknown>\n const bind = (value: unknown) => (typeof value === 'function' ? value.bind(root) : value)\n\n for (const [key, value] of Object.entries(options)) {\n // `file` drives file naming through `#baseName`, not a top-level method, so it must not be\n // assigned here (it would shadow the `file` method with a plain `{ name }` object).\n if (key === 'pluginName' || key === 'default' || key === 'file' || value === undefined) continue\n root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value)\n }\n }\n\n static #testPattern(value: string, pattern: string | RegExp): boolean {\n if (typeof pattern === 'string') {\n let regex = Resolver.#patternCache.get(pattern)\n regex ??= new RegExp(pattern)\n Resolver.#patternCache.set(pattern, regex)\n return regex.test(value)\n }\n // Use .match() for user-supplied RegExp to preserve semantics regardless of `g`/`y` flags.\n return value.match(pattern) !== null\n }\n\n static #matchesOperation(node: OperationNode, { type, pattern }: Filter): boolean {\n if (type === 'tag') return node.tags.some((tag) => Resolver.#testPattern(tag, pattern))\n if (type === 'operationId') return Resolver.#testPattern(node.operationId, pattern)\n if (type === 'path') return node.path !== undefined && Resolver.#testPattern(node.path, pattern)\n if (type === 'method') return node.method !== undefined && Resolver.#testPattern(node.method.toLowerCase(), pattern)\n if (type === 'contentType') return node.requestBody?.content?.some((c) => Resolver.#testPattern(c.contentType, pattern)) ?? false\n return false\n }\n\n /**\n * Returns `null` when the filter type doesn't apply to schemas, so include rules built\n * from operation filters (e.g. `tag`) don't exclude every schema.\n */\n static #matchesSchema(node: SchemaNode, { type, pattern }: Filter): boolean | null {\n if (type === 'schemaName') return node.name ? Resolver.#testPattern(node.name, pattern) : false\n return null\n }\n\n static #computeOptions<TOptions>(node: Node, { options, exclude = [], include, override = [] }: ResolveOptionsContext<TOptions>): TOptions | null {\n if (operationDef.is(node)) {\n if (exclude.some((filter) => Resolver.#matchesOperation(node, filter))) return null\n if (include && !include.some((filter) => Resolver.#matchesOperation(node, filter))) return null\n\n return { ...options, ...override.find((filter) => Resolver.#matchesOperation(node, filter))?.options }\n }\n\n if (schemaDef.is(node)) {\n if (exclude.some((filter) => Resolver.#matchesSchema(node, filter) === true)) return null\n if (include) {\n const applicable = include.map((filter) => Resolver.#matchesSchema(node, filter)).filter((result) => result !== null)\n if (applicable.length > 0 && !applicable.includes(true)) return null\n }\n\n return { ...options, ...override.find((filter) => Resolver.#matchesSchema(node, filter) === true)?.options }\n }\n\n return options\n }\n\n /**\n * Applies include/exclude filters and merges matching override options, caching the result\n * per `(options, node)` pair. Returns `null` when the node is filtered out.\n */\n #resolveOptions<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null {\n // A re-instantiated plugin can hand back a non-object `options`, which WeakMap rejects\n // as a key. Compute directly in that case instead of throwing.\n const { options } = context\n if (typeof options !== 'object' || options === null) {\n return Resolver.#computeOptions(node, context)\n }\n\n let byOptions = Resolver.#optionsCache.get(options)\n if (!byOptions) {\n byOptions = new WeakMap()\n Resolver.#optionsCache.set(options, byOptions)\n }\n\n const cached = byOptions.get(node)\n if (cached) return cached.value as TOptions | null\n\n const result = Resolver.#computeOptions(node, context)\n byOptions.set(node, { value: result })\n return result\n }\n\n /**\n * A custom `group.name` wins; otherwise `tag` groups use the camelCased tag and `path`\n * groups use the first non-traversal segment (`''` when none remain, placing the file in\n * the output root, kept safe by the caller's boundary check).\n */\n static #resolveGroupDir(group: Group, groupValue: string): string {\n if (group.name) return group.name({ group: groupValue })\n if (group.type === 'tag') return camelCase(groupValue)\n const segment = groupValue.split('/').filter((part) => part !== '' && part !== '.' && part !== '..')[0]\n return segment ? camelCase(segment) : ''\n }\n\n /**\n * `mode: 'file'` resolves directly to `output.path`. `mode: 'directory'` (default) resolves\n * to `output.path/{baseName}`, or into a subdirectory when `group` and a `tag`/`path` value\n * are provided.\n */\n #resolvePath({ baseName, tag, path: groupPath, root, output, group }: ResolvePathOptions): string {\n if (output.mode === 'file') {\n return path.resolve(root, output.path)\n }\n\n const outputDir = path.resolve(root, output.path)\n const result =\n group && (groupPath || tag)\n ? path.resolve(outputDir, Resolver.#resolveGroupDir(group, group.type === 'path' ? groupPath! : tag!), baseName)\n : path.resolve(outputDir, baseName)\n\n // Reject paths escaping the output directory: a malicious OpenAPI spec or a misconfigured\n // group.name function could otherwise write anywhere. `result === outputDir` stays allowed\n // for the edge case where baseName resolves to the output directory itself.\n const outputDirWithSep = outputDir.endsWith(path.sep) ? outputDir : `${outputDir}${path.sep}`\n if (result !== outputDir && !result.startsWith(outputDirWithSep)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message: `Resolved path \"${result}\" is outside the output directory \"${outputDir}\".`,\n help: 'This can stem from a path traversal in the OpenAPI specification or a misconfigured `group.name` function. Keep generated paths within the output directory.',\n location: { kind: 'config' },\n })\n }\n\n return result\n }\n\n /**\n * Resolves a resolver-supplied full path (`file.path`) against `root`, bypassing `output.path`\n * and `group`. The path may not escape `root`, which keeps a `file.path` that interpolates\n * spec-derived values from writing outside the project.\n */\n #resolveOverridePath(filePath: string, root: string): string {\n const resolved = path.resolve(root, filePath)\n const rootWithSep = root.endsWith(path.sep) ? root : `${root}${path.sep}`\n if (resolved !== root && !resolved.startsWith(rootWithSep)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message: `Resolved path \"${resolved}\" is outside the project root \"${root}\".`,\n help: 'A resolver `file.path` must return a path inside the project root.',\n location: { kind: 'config' },\n })\n }\n\n return resolved\n }\n\n /**\n * Builds a `FileNode`. When `#filePath` (the resolver's `file.path`) is set it owns the whole\n * path; otherwise the base name (from `#baseName`, the resolver's `file.baseName` or the\n * built-in `toBaseName`) is placed by the `output.path`/`group` layout. The resolved file starts\n * with empty `sources`, `imports`, and `exports`, which consumers populate separately.\n */\n #resolveFile(options: ResolveFileOptions): FileNode {\n const { name, extname, tag, path: groupPath, root, output, group } = options\n const baseName = this.#baseName({ name, extname })\n const filePath = this.#filePath\n ? this.#resolveOverridePath(this.#filePath({ baseName, output }), root)\n : this.#resolvePath({ baseName, tag, path: groupPath, root, output, group })\n\n return ast.factory.createFile({\n path: filePath,\n baseName: path.basename(filePath) as `${string}.${string}`,\n meta: {\n pluginName: this.pluginName,\n },\n sources: [],\n imports: [],\n exports: [],\n })\n }\n\n /**\n * Missing fields default to empty/`false` so the `BannerMeta` shape stays stable even when\n * a caller (e.g. the barrel plugin) has no document metadata.\n */\n static #buildBannerMeta(meta: InputMeta | undefined, file: ResolveBannerFile | undefined): BannerMeta {\n return {\n title: meta?.title,\n description: meta?.description,\n version: meta?.version,\n baseURL: meta?.baseURL,\n circularNames: meta?.circularNames ?? [],\n enumNames: meta?.enumNames ?? [],\n filePath: file?.path ?? '',\n baseName: file?.baseName ?? '',\n isBarrel: file?.isBarrel ?? false,\n isAggregation: file?.isAggregation ?? false,\n }\n }\n\n /**\n * Resolves a user-configured banner/footer value. `undefined` means not configured.\n */\n static #resolveUserText(\n value: string | ((meta: BannerMeta) => string) | undefined,\n meta: InputMeta | undefined,\n file: ResolveBannerFile | undefined,\n ): string | undefined {\n if (typeof value === 'function') return value(Resolver.#buildBannerMeta(meta, file))\n if (typeof value === 'string') return value\n return undefined\n }\n\n static #buildDefaultBanner({ title, version, config }: { title?: string; version?: string; config: Config }): string {\n const lines = ['/**', '* Generated by Kubb (https://kubb.dev/).', '* Do not edit manually.']\n\n if (config.output.defaultBanner !== 'simple') {\n const input = config.input\n let source = ''\n if (typeof input === 'string') {\n source = getInputKind(input) === 'inline' ? 'text content' : path.basename(input)\n } else if (input) {\n source = 'text content'\n }\n\n if (source) lines.push(`* Source: ${source}`)\n if (title) lines.push(`* Title: ${title}`)\n if (version) lines.push(`* OpenAPI spec version: ${version}`)\n }\n\n return `${lines.join('\\n')}\\n*/\\n`\n }\n\n /**\n * A user-supplied `output.banner` overrides the default Kubb notice. When\n * `config.output.defaultBanner` is `false` and no user banner is set, returns `null`.\n */\n #resolveBanner(meta: InputMeta | undefined, { output, config, file }: ResolveBannerContext): string | null {\n const userBanner = Resolver.#resolveUserText(output?.banner, meta, file)\n if (userBanner !== undefined) return userBanner\n\n if (config.output.defaultBanner === false) return null\n\n return Resolver.#buildDefaultBanner({ title: meta?.title, version: meta?.version, config })\n }\n\n #resolveFooter(meta: InputMeta | undefined, { output, file }: ResolveBannerContext): string | null {\n return Resolver.#resolveUserText(output?.footer, meta, file) ?? null\n }\n}\n","import type { PluginFactoryOptions } from './definePlugin.ts'\nimport { Resolver, type ResolverBuildOptions, type ResolverFile } from './Resolver.ts'\n\n/**\n * The plugin-specific resolver fields handed to `createResolver`. `name` and `file` fall\n * back to the built-ins when omitted. Every method reaches sibling helpers through `this`,\n * which `ThisType` types as the full resolver.\n */\ntype ResolverOptions<T extends PluginFactoryOptions> = Omit<T['resolver'], keyof Resolver> & {\n pluginName: T['name']\n name?: T['resolver']['name']\n file?: ResolverFile\n} & ThisType<T['resolver']>\n\n/**\n * Defines a plugin resolver, the object that decides what every generated symbol and file\n * path is called. Override the top-level `name` and `file` to set the plugin's conventions,\n * and add your own naming helpers, top-level (`typeName`, …) or grouped in namespaces\n * (`query`, `schema`, …). Every method reaches sibling helpers and the built-in machinery\n * through `this.name`, `this.file`, and `this.default`.\n *\n * @example Custom identifier casing\n * ```ts\n * export const resolverTs = createResolver<PluginTs>({\n * pluginName: 'plugin-ts',\n * name(name) {\n * return ensureValidVarName(pascalCase(name))\n * },\n * })\n * ```\n *\n * @example Rename generated files with `file.baseName`\n * ```ts\n * export const resolverFaker = createResolver<PluginFaker>({\n * pluginName: 'plugin-faker',\n * name(name) {\n * return camelCase(name, { prefix: 'create' })\n * },\n * file: {\n * baseName({ name, extname }) {\n * return `${camelCase(name, { prefix: 'create' })}${extname}`\n * },\n * },\n * })\n * ```\n *\n * @example Own the full path with `file.path`\n * ```ts\n * export const resolverFaker = createResolver<PluginFaker>({\n * pluginName: 'plugin-faker',\n * file: {\n * path({ baseName, output }) {\n * return `${output.path}/mocks/${baseName}`\n * },\n * },\n * })\n * ```\n */\nexport function createResolver<T extends PluginFactoryOptions>(options: ResolverOptions<T>): T['resolver'] {\n return new Resolver(options as unknown as ResolverBuildOptions) as T['resolver']\n}\n","import type { Macro, OperationNode, SchemaNode, Visitor } from '@kubb/ast'\nimport { composeMacros, transform } from '@kubb/ast'\n\n/**\n * Holds an ordered list of macros per plugin, keyed by plugin name. Each plugin's macros run in\n * isolation on the original adapter node and are composed into a single `Visitor` that the\n * `@kubb/ast` `transform` primitive applies. `applyTo` is a per-plugin lookup, not a cross-plugin\n * chain, so plugin A's macros never see plugin B's output. When a plugin has no macros, `applyTo`\n * returns the original node reference, and `transform` does the same when the composed visitor\n * leaves the tree untouched, so callers can detect a no-op by identity.\n *\n * Registration order matches the order setup hooks fire, which the driver has already sorted by\n * `enforce` and dependency edges. The registry preserves that order. Macro `enforce` only reorders\n * within a single plugin's list.\n */\nexport class Transform {\n readonly #macros = new Map<string, Array<Macro>>()\n // Composed visitor per plugin, rebuilt lazily after the macro list changes.\n readonly #composed = new Map<string, Visitor>()\n // Memoized results per plugin. Repeated `applyTo` calls return the same node identity, so\n // downstream WeakMap caches keyed by node (the resolver's resolveOptions memo) hit when the\n // driver resolves a node a second time, and a stateful macro runs once per node.\n readonly #memo = new Map<string, WeakMap<SchemaNode | OperationNode, SchemaNode | OperationNode>>()\n\n /**\n * Appends `macro` to the plugin's list, after any macros already registered.\n */\n add(pluginName: string, macro: Macro): void {\n const list = this.#macros.get(pluginName)\n if (list) list.push(macro)\n else this.#macros.set(pluginName, [macro])\n this.#invalidate(pluginName)\n }\n\n /**\n * Replaces the plugin's macro list with `macros`.\n */\n set(pluginName: string, macros: ReadonlyArray<Macro>): void {\n this.#macros.set(pluginName, [...macros])\n this.#invalidate(pluginName)\n }\n\n /**\n * Runs the plugin's macros on `node`. Returns the original node reference when the plugin has no\n * macros, so callers can compare by identity to detect a no-op.\n */\n applyTo<TNode extends SchemaNode | OperationNode>(pluginName: string, node: TNode): TNode {\n const visitor = this.#visitorFor(pluginName)\n if (!visitor) return node\n\n let memo = this.#memo.get(pluginName)\n if (!memo) {\n memo = new WeakMap()\n this.#memo.set(pluginName, memo)\n }\n\n const cached = memo.get(node)\n if (cached) return cached as TNode\n\n const result = transform(node, visitor) as TNode\n memo.set(node, result)\n return result\n }\n\n /**\n * Clears every registration. Called from the driver's `dispose()` so macros do not leak across\n * builds.\n */\n dispose(): void {\n this.#macros.clear()\n this.#composed.clear()\n this.#memo.clear()\n }\n\n #invalidate(pluginName: string): void {\n this.#composed.delete(pluginName)\n this.#memo.delete(pluginName)\n }\n\n #visitorFor(pluginName: string): Visitor | undefined {\n const macros = this.#macros.get(pluginName)\n if (!macros || macros.length === 0) return undefined\n\n let composed = this.#composed.get(pluginName)\n if (!composed) {\n composed = composeMacros(macros)\n this.#composed.set(pluginName, composed)\n }\n return composed\n }\n}\n","import { resolve } from 'node:path'\nimport { getElapsedMs, memoize, toError } from '@internals/utils'\nimport { ast, collectUsedSchemaNames, type Enforce, type FileNode, type InputMeta, type InputNode, type OperationNode, type SchemaNode } from '@kubb/ast'\nimport { OPERATION_FILTER_TYPES } from './constants.ts'\nimport { type Diagnostic, Diagnostics, type ProblemDiagnostic } from './Diagnostics.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { Generator } from './defineGenerator.ts'\nimport type { Parser } from './defineParser.ts'\nimport type { Plugin } from './definePlugin.ts'\nimport { normalizeOutput } from './definePlugin.ts'\nimport { createResolver } from './createResolver.ts'\nimport { Resolver, type ResolverPatch } from './Resolver.ts'\nimport { FileManager } from './FileManager.ts'\nimport { Transform } from './Transform.ts'\nimport { inputToAdapterSource } from './input.ts'\n\nimport type { Adapter, AdapterSource, Config, GeneratorContext, Group, KubbHooks, NormalizedPlugin, PluginFactoryOptions } from './types.ts'\nimport type { Hookable } from './Hookable.ts'\n\ntype Options = {\n hooks: Hookable<KubbHooks>\n}\n\ntype RequirePluginContext = {\n /**\n * Name of the plugin that declared the dependency, included in the error so users can\n * trace which plugin needs the missing one.\n */\n requiredBy?: string\n}\n\nconst ENFORCE_ORDER = { pre: -1, post: 1 } satisfies Record<Enforce, number>\n\nconst enforceWeight = (plugin: NormalizedPlugin): number => (plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0)\n\nexport class KubbDriver {\n readonly config: Config\n readonly options: Options\n\n /**\n * The `InputNode` produced by the adapter. Set after adapter setup.\n */\n inputNode: InputNode | null = null\n adapter: Adapter | null = null\n /**\n * Raw adapter source so `adapter.parse()` can run lazily.\n * Intentionally outlives the build, cleared by `dispose()`.\n */\n #adapterSource: AdapterSource | null = null\n\n /**\n * Central file store for all generated files.\n * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to\n * add files. This property gives direct read/write access when needed.\n */\n readonly fileManager = new FileManager()\n readonly plugins = new Map<string, NormalizedPlugin>()\n\n /**\n * Tracks which plugins have generators registered via `addGenerator()` (hook-based path).\n * Used by the build loop to decide whether to emit generator hooks for a given plugin.\n */\n readonly #hookGeneratorPlugins = new Set<string>()\n readonly #resolvers = new Map<string, Resolver>()\n readonly #defaultResolvers = new Map<string, Resolver>()\n\n /**\n * Removers for every listener the driver added (plugin, generator) so `dispose()` can detach\n * them in one pass. External `hooks.hook(...)` listeners are not tracked.\n */\n readonly #unhooks: Array<() => void> = []\n\n /**\n * Transform registry. Plugins populate it during `kubb:plugin:setup` via `addMacro`/`setMacros`,\n * and `#runGenerators` reads it once per `(plugin, node)` pair through `applyTo`.\n */\n readonly #transforms = new Transform()\n\n constructor(config: Config, options: Options) {\n this.config = config\n this.options = options\n this.adapter = config.adapter ?? null\n }\n\n /**\n * Normalizes every configured plugin, orders them, and registers their lifecycle handlers.\n * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before\n * `'post'`. When the config has an adapter, the adapter source is resolved from the input\n * so `run` can parse it later.\n */\n async setup() {\n const normalized = this.#sortPlugins(\n this.config.plugins.map((rawPlugin) => {\n return {\n name: rawPlugin.name,\n dependencies: rawPlugin.dependencies,\n enforce: rawPlugin.enforce,\n hooks: rawPlugin.hooks,\n options: rawPlugin.options ?? { output: { path: '.', mode: 'directory' }, exclude: [], override: [] },\n } as NormalizedPlugin\n }),\n )\n\n for (const plugin of normalized) {\n this.#registerPlugin(plugin)\n this.plugins.set(plugin.name, plugin)\n }\n\n if (this.config.adapter) {\n this.#adapterSource = inputToAdapterSource(this.config)\n }\n }\n\n /**\n * Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with\n * `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks.\n * A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive\n * at the comparator level, so a chain where A depends on B and B depends on C could come out\n * wrong when A and C are never compared directly. Dependencies on plugins missing from the\n * config are ignored here and surface later through `requirePlugin`.\n */\n #sortPlugins(plugins: Array<NormalizedPlugin>): Array<NormalizedPlugin> {\n const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b))\n const names = new Set(queue.map((plugin) => plugin.name))\n const blockedBy = new Map(queue.map((plugin) => [plugin.name, new Set(plugin.dependencies?.filter((name) => names.has(name) && name !== plugin.name))]))\n\n // One plugin leaves `queue` per pass, so iterating once per plugin drains it. Each pass takes\n // the lowest-index plugin with no remaining blockers, preserving enforce and declaration order.\n const sorted: Array<NormalizedPlugin> = []\n for (const _ of plugins) {\n const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0)\n if (index === -1) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(' → ')}.`,\n help: 'Remove one of the `dependencies` entries so the plugins can be ordered.',\n location: { kind: 'config' },\n })\n }\n\n const [plugin] = queue.splice(index, 1)\n if (!plugin) break\n\n sorted.push(plugin)\n for (const blockers of blockedBy.values()) blockers.delete(plugin.name)\n }\n\n return sorted\n }\n\n get hooks() {\n return this.options.hooks\n }\n\n /**\n * Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from\n * `run` do not re-parse.\n */\n async #parseInput(): Promise<void> {\n if (this.inputNode || !this.adapter || !this.#adapterSource) return\n\n this.inputNode = await this.adapter.parse(this.#adapterSource)\n }\n\n /**\n * Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that\n * external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for\n * `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a\n * plugin-scoped context.\n *\n * @internal\n */\n #registerPlugin(plugin: NormalizedPlugin): void {\n const { hooks } = plugin\n\n if (!hooks) return\n\n const { 'kubb:plugin:setup': _setup, ...configHooks } = hooks\n\n this.#unhooks.push(this.hooks.addHooks(configHooks))\n }\n\n /**\n * Runs each plugin's `kubb:plugin:setup` handler, in plugin order, with a context scoped to that\n * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its\n * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so\n * plugins can configure generators, resolvers, macros, and options before `buildStart`.\n */\n async setupHooks(): Promise<void> {\n for (const plugin of this.plugins.values()) {\n const setup = plugin.hooks?.['kubb:plugin:setup']\n if (!setup) continue\n\n await setup({\n config: this.config,\n options: plugin.options ?? {},\n addGenerator: (...generators) => {\n for (const generator of generators) {\n this.registerGenerator(plugin.name, generator)\n }\n },\n setResolver: (resolver) => {\n this.setPluginResolver(plugin.name, resolver)\n },\n addMacro: (macro) => {\n this.#transforms.add(plugin.name, macro)\n },\n setMacros: (macros) => {\n this.#transforms.set(plugin.name, macros)\n },\n setOptions: (opts) => {\n plugin.options = { ...plugin.options, ...opts }\n if (plugin.options.output) {\n const group = 'group' in plugin.options ? (plugin.options.group as Group | null | undefined) : undefined\n plugin.options.output = normalizeOutput({ output: plugin.options.output, group, pluginName: plugin.name })\n }\n },\n injectFile: (userFileNode) => {\n this.fileManager.add(ast.factory.createFile(userFileNode))\n },\n })\n }\n }\n\n /**\n * Registers a generator for the given plugin on the shared hook emitter.\n *\n * The generator's `schema`, `operation`, and `operations` methods are registered as\n * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`\n * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check\n * so that generators from different plugins do not cross-fire.\n *\n * The renderer comes from `generator.renderer`. Set `generator.renderer = null` (or leave it\n * unset) to opt out of rendering.\n *\n * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.\n */\n registerGenerator(pluginName: string, generator: Generator): void {\n // Scope each generator method to its owning plugin and route its result through `dispatch`.\n // Returns `undefined` for an absent method so `addHooks` skips that hook.\n const wrap = <TNode>(method: ((node: TNode, ctx: GeneratorContext) => unknown) | undefined) => {\n if (!method) return undefined\n\n return async (node: TNode, ctx: GeneratorContext): Promise<void> => {\n if (ctx.plugin.name !== pluginName) return\n const result = await method(node, ctx)\n\n await this.dispatch({ result, renderer: generator.renderer })\n }\n }\n\n this.#unhooks.push(\n this.hooks.addHooks({\n 'kubb:generate:schema': wrap(generator.schema),\n 'kubb:generate:operation': wrap(generator.operation),\n 'kubb:generate:operations': wrap(generator.operations),\n }),\n )\n\n this.#hookGeneratorPlugins.add(pluginName)\n }\n\n /**\n * Returns `true` when at least one generator was registered for the given plugin\n * via `addGenerator()` in `kubb:plugin:setup`.\n *\n * Used by the build loop to decide whether to walk the AST and emit generator hooks\n * for a plugin.\n */\n hasHookGenerators(pluginName: string): boolean {\n return this.#hookGeneratorPlugins.has(pluginName)\n }\n\n /**\n * Runs the full plugin pipeline. Returns the diagnostics collected so far even\n * when an outer hook throws, since the orchestrator preserves partial state by capturing\n * the failure as a {@link Diagnostic} instead of propagating. Each plugin also\n * contributes a `timing` diagnostic for the run summary.\n */\n async run(): Promise<{ diagnostics: Array<Diagnostic> }> {\n const { hooks, config, fileManager } = this\n const diagnostics: Array<Diagnostic> = []\n const parsersMap = new Map<FileNode['extname'], Parser>()\n\n for (const parser of config.parsers) {\n if (parser.extNames) {\n for (const ext of parser.extNames) parsersMap.set(ext, parser)\n }\n }\n\n // Bridge the write batch's lifecycle to the user-facing kubb hooks so existing listeners\n // on kubb:files:processing:* keep firing. Tracked locally (not via #hook) since\n // these must come off at the end of this run, not just at driver disposal.\n const onWriteStart = async (files: Array<FileNode>) => {\n await hooks.callHook('kubb:files:processing:start', { files })\n }\n const updateBuffer: Array<{ file: FileNode; source?: string; processed: number; total: number; percentage: number }> = []\n const onWriteUpdate = (item: (typeof updateBuffer)[number]) => {\n updateBuffer.push(item)\n }\n const onWriteEnd = async (files: Array<FileNode>) => {\n await hooks.callHook('kubb:files:processing:update', {\n files: updateBuffer.map((item) => ({ ...item, config })),\n })\n updateBuffer.length = 0\n await hooks.callHook('kubb:files:processing:end', { files })\n }\n const unhookWrites = fileManager.hooks.addHooks({ start: onWriteStart, update: onWriteUpdate, end: onWriteEnd })\n\n // Make `diagnostics` the active sink so deep code (adapter parse, generators) can\n // report into this run via `Diagnostics.report`.\n return Diagnostics.scope(\n (diagnostic) => diagnostics.push(diagnostic),\n async () => {\n try {\n const outputRoot = resolve(config.root, config.output.path)\n\n // Parse the adapter source into `this.inputNode`.\n await this.#parseInput()\n // Emit `kubb:plugin:setup` so plugins can register macros via `addMacro`/`setMacros`.\n // Each call writes into `this.#transforms`, which `#runGenerators` later reads through\n // `transforms.applyTo`.\n await this.setupHooks()\n\n if (this.adapter && this.inputNode) {\n await hooks.callHook(\n 'kubb:build:start',\n Object.assign({ config, adapter: this.adapter, meta: this.inputNode.meta, getPlugin: this.getPlugin.bind(this) }, this.#filesPayload()),\n )\n }\n\n const generatorPlugins: Array<{ plugin: NormalizedPlugin; context: Omit<GeneratorContext, 'options'>; hrStart: ReturnType<typeof process.hrtime> }> =\n []\n\n for (const plugin of this.plugins.values()) {\n const context = this.getContext(plugin)\n const hrStart = process.hrtime()\n\n try {\n await hooks.callHook('kubb:plugin:start', { plugin })\n } catch (caughtError) {\n const error = toError(caughtError)\n const duration = getElapsedMs(hrStart)\n\n await this.#emitPluginEnd({ plugin, duration, success: false, error })\n\n diagnostics.push({ ...Diagnostics.from(error), plugin: plugin.name }, Diagnostics.performance({ plugin: plugin.name, duration }))\n\n continue\n }\n\n if (this.hasHookGenerators(plugin.name)) {\n generatorPlugins.push({ plugin, context, hrStart })\n\n continue\n }\n\n const duration = getElapsedMs(hrStart)\n diagnostics.push(Diagnostics.performance({ plugin: plugin.name, duration }))\n\n await this.#emitPluginEnd({ plugin, duration, success: true })\n }\n\n // Run every node through the transform registry and into each plugin's generators.\n diagnostics.push(...(await this.#runGenerators(generatorPlugins)))\n\n await hooks.callHook('kubb:plugins:end', Object.assign({ config }, this.#filesPayload()))\n\n // Write every generated file once, after post-processing (barrel etc.) has had its\n // chance to add more. Writing mid-generation measured no faster in practice, so a\n // single pass keeps the pipeline simpler.\n await fileManager.write(fileManager.files, { storage: config.storage, parsers: parsersMap })\n\n await hooks.callHook('kubb:build:end', { files: this.fileManager.files, config, outputDir: outputRoot })\n\n return { diagnostics: Diagnostics.dedupe(diagnostics) }\n } catch (caughtError) {\n diagnostics.push(Diagnostics.from(caughtError))\n return { diagnostics: Diagnostics.dedupe(diagnostics) }\n } finally {\n unhookWrites()\n }\n },\n )\n }\n\n // Returns a fresh object with a lazy `files` getter and a bound `upsertFile`.\n // Caller must use `Object.assign(extra, this.#filesPayload())`, not object spread.\n // Spread would eagerly invoke the getter and freeze a stale snapshot into the payload.\n #filesPayload(): { readonly files: Array<FileNode>; upsertFile: (...files: Array<FileNode>) => Array<FileNode> } {\n const driver = this\n\n return {\n get files() {\n return driver.fileManager.files\n },\n upsertFile: (...files: Array<FileNode>) => driver.fileManager.upsert(...files),\n }\n }\n\n #emitPluginEnd({ plugin, duration, success, error }: { plugin: NormalizedPlugin; duration: number; success: boolean; error?: Error }): Promise<void> | void {\n return this.hooks.callHook(\n 'kubb:plugin:end',\n Object.assign({ plugin, duration, success, ...(error ? { error } : {}), config: this.config }, this.#filesPayload()),\n )\n }\n\n /**\n * Runs schemas and operations through every plugin's generators. Each node is run\n * through the plugin's macros (from `this.#transforms`) before the generator sees it,\n * so plugins stay isolated and the hot path stays per-node. Schemas run before operations\n * so file output stays deterministic across runs.\n * A failing plugin contributes an error diagnostic so the rest of the build continues.\n * Every plugin also contributes a `timing` diagnostic.\n *\n * Plugins are processed one at a time, in full, so `kubb:plugin:end` fires as each one\n * completes rather than all at once at the end. That ordering drives the CLI's\n * `Plugins N/M` counter.\n *\n * When `this.inputNode` is `null`, every entry still gets a `kubb:plugin:end` so\n * post-plugin listeners (the barrel writer and friends) complete.\n */\n async #runGenerators(\n entries: Array<{ plugin: NormalizedPlugin; context: Omit<GeneratorContext, 'options'>; hrStart: ReturnType<typeof process.hrtime> }>,\n ): Promise<Array<Diagnostic>> {\n const diagnostics: Array<Diagnostic> = []\n\n if (entries.length === 0) return diagnostics\n\n if (!this.inputNode) {\n for (const { plugin, hrStart } of entries) {\n const duration = getElapsedMs(hrStart)\n diagnostics.push(Diagnostics.performance({ plugin: plugin.name, duration }))\n await this.#emitPluginEnd({ plugin, duration, success: true })\n }\n return diagnostics\n }\n\n const transforms = this.#transforms\n const { schemas, operations } = this.inputNode\n\n const emitsSchemaHook = this.hooks.listenerCount('kubb:generate:schema') > 0\n const emitsOperationHook = this.hooks.listenerCount('kubb:generate:operation') > 0\n const emitsOperationsHook = this.hooks.listenerCount('kubb:generate:operations') > 0\n\n // Pre-scan: plugins with operation-based includes (but no schemaName include) need\n // the reachable schema set, keyed by plugin name. This requires the full schema graph\n // in memory at once, since transitive reachability can't be derived from a single node.\n const allowedSchemaNamesByPlugin = new Map<string, Set<string>>()\n for (const { plugin } of entries) {\n const { exclude, include, override } = plugin.options\n const needsPruning =\n (include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === 'schemaName') ?? false)\n if (!needsPruning) continue\n\n const resolver = this.getResolver(plugin.name)\n const includedOps = operations.filter(\n (operation) => resolver.default.options(operation, { options: plugin.options, exclude, include, override }) !== null,\n )\n allowedSchemaNamesByPlugin.set(plugin.name, collectUsedSchemaNames(includedOps, schemas))\n }\n\n for (const { plugin, context, hrStart } of entries) {\n const generatorContext = { ...context, resolver: this.getResolver(plugin.name) }\n const { exclude, include, override } = plugin.options\n const optionsAreStatic = !exclude?.length && !include?.length && !override?.length\n const allowedSchemaNames = allowedSchemaNamesByPlugin.get(plugin.name) ?? null\n\n let error: Error | null = null\n\n // Applies the plugin's macros, then resolves options (skipping the resolver when\n // optionsAreStatic). Returns null when include/exclude/override rules out the node.\n // The per-node dispatch and the collected-operations tail both go through this so\n // they agree on what the plugin sees.\n const resolveForPlugin = <TNode extends SchemaNode | OperationNode>(\n node: TNode,\n ): { transformedNode: TNode; options: NormalizedPlugin['options'] } | null => {\n const transformedNode = transforms.applyTo(plugin.name, node)\n if (optionsAreStatic) return { transformedNode, options: plugin.options }\n\n const options = generatorContext.resolver.default.options<NormalizedPlugin['options']>(transformedNode, {\n options: plugin.options,\n exclude,\n include,\n override,\n })\n if (options === null) return null\n\n return { transformedNode, options }\n }\n\n // Schemas before operations, in adapter order, so file output stays deterministic. A\n // caught error stops this plugin but not the others, so its remaining nodes are\n // skipped rather than retried.\n if (emitsSchemaHook) {\n for (const node of schemas) {\n if (error) break\n try {\n const resolved = resolveForPlugin(node)\n if (!resolved) continue\n\n const { transformedNode, options } = resolved\n if (allowedSchemaNames !== null && transformedNode.name && !allowedSchemaNames.has(transformedNode.name)) continue\n\n await this.hooks.callHook('kubb:generate:schema', transformedNode, { ...generatorContext, options })\n } catch (caughtError) {\n error = toError(caughtError)\n }\n }\n }\n\n if (emitsOperationHook) {\n for (const node of operations) {\n if (error) break\n try {\n const resolved = resolveForPlugin(node)\n if (!resolved) continue\n\n await this.hooks.callHook('kubb:generate:operation', resolved.transformedNode, { ...generatorContext, options: resolved.options })\n } catch (caughtError) {\n error = toError(caughtError)\n }\n }\n }\n\n if (!error && emitsOperationsHook) {\n try {\n const ctx = { ...generatorContext, options: plugin.options }\n // Match what the per-node dispatch emitted on kubb:generate:operation: each operation\n // transformed and filtered by this plugin's excludes/includes/overrides.\n const pluginOperations = operations.reduce<Array<OperationNode>>((acc, node) => {\n const resolved = resolveForPlugin(node)\n if (resolved) acc.push(resolved.transformedNode)\n return acc\n }, [])\n await this.hooks.callHook('kubb:generate:operations', pluginOperations, ctx)\n } catch (caughtError) {\n error = toError(caughtError)\n }\n }\n\n const duration = getElapsedMs(hrStart)\n await this.#emitPluginEnd({ plugin, duration, success: !error, error: error ?? undefined })\n\n if (error) {\n diagnostics.push({ ...Diagnostics.from(error), plugin: plugin.name })\n }\n diagnostics.push(Diagnostics.performance({ plugin: plugin.name, duration }))\n }\n\n return diagnostics\n }\n\n /**\n * Stores whatever a generator method or `kubb:generate:*` hook returned.\n *\n * - An `Array<FileNode>` goes straight into `fileManager` via `upsert`.\n * - A renderer element runs through `renderer` (the renderer factory, e.g. JSX) and the\n * produced files go to `fileManager.upsert`.\n * - A falsy result is treated as a no-op. The generator wrote files itself via\n * `ctx.upsertFile`.\n *\n * Pass `renderer` when the result may be a renderer element. Generators that only return\n * `Array<FileNode>` do not need one.\n */\n async dispatch<TElement = unknown>({\n result,\n renderer,\n }: {\n result: TElement | Array<FileNode> | undefined | null\n renderer?: RendererFactory<TElement> | null\n }): Promise<void> {\n if (!result) return\n\n if (Array.isArray(result)) {\n this.fileManager.upsert(...(result as Array<FileNode>))\n return\n }\n\n if (!renderer) {\n return\n }\n\n using instance = renderer()\n await instance.render(result)\n\n this.fileManager.upsert(...instance.files)\n }\n\n /**\n * Removes every listener the driver added. Listeners attached directly to `hooks` from outside\n * the driver survive. Called at the end of a build to prevent leaks across repeated builds.\n *\n * @internal\n */\n dispose(): void {\n for (const unhook of this.#unhooks) unhook()\n this.#unhooks.length = 0\n this.#hookGeneratorPlugins.clear()\n this.#transforms.dispose()\n // Release resolver closures. The driver is rebuilt for each build() call\n // so there is no value in retaining these maps after disposal.\n this.#resolvers.clear()\n this.#defaultResolvers.clear()\n // Release the FileNode cache and parsed adapter graph so memory is reclaimed\n // between builds. The returned `BuildOutput.files` array still references any\n // FileNodes the caller needs to inspect.\n this.fileManager.dispose()\n this.inputNode = null\n this.#adapterSource = null\n }\n\n [Symbol.dispose](): void {\n this.dispose()\n }\n\n #getDefaultResolver = memoize(this.#defaultResolvers, (pluginName: string): Resolver => createResolver<PluginFactoryOptions>({ pluginName }))\n\n /**\n * Merges `partial` with the plugin's default resolver and stores the result.\n * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`\n * get the up-to-date resolver without going through `getResolver()`.\n */\n setPluginResolver(pluginName: string, partial: ResolverPatch | Resolver): void {\n const defaultResolver = this.#getDefaultResolver(pluginName)\n const merged = Resolver.merge(defaultResolver, partial)\n this.#resolvers.set(pluginName, merged)\n const plugin = this.plugins.get(pluginName)\n if (plugin) {\n plugin.resolver = merged\n }\n }\n\n /**\n * Returns the resolver for the given plugin.\n *\n * Resolution order: resolver set via `setPluginResolver` → lazily created default\n * resolver (identity name, no path transforms).\n */\n getResolver<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Kubb.PluginRegistry[TName]['resolver']\n getResolver<TResolver extends Resolver = Resolver>(pluginName: string): TResolver\n getResolver(pluginName: string): Resolver {\n return this.#resolvers.get(pluginName) ?? this.#getDefaultResolver(pluginName)\n }\n\n getContext<TOptions extends PluginFactoryOptions>(plugin: NormalizedPlugin<TOptions>): Omit<GeneratorContext<TOptions>, 'options'> {\n const driver = this\n\n // Collect into the active build only. The host renders each collected diagnostic once after the\n // build (the CLI via `Diagnostics.emit`, the agent via its post-build loop), so emitting a live\n // `kubb:error`/`kubb:warn`/`kubb:info` here would render it twice.\n const report = (diagnostic: Omit<ProblemDiagnostic, 'plugin'>): void => {\n Diagnostics.report({ ...diagnostic, plugin: plugin.name })\n }\n\n return {\n config: driver.config,\n get root(): string {\n return resolve(driver.config.root, driver.config.output.path)\n },\n hooks: driver.hooks,\n plugin,\n getPlugin: driver.getPlugin.bind(driver),\n // Close over the owning plugin so a missing dependency error names who required it.\n requirePlugin: ((name: string) => driver.requirePlugin(name, { requiredBy: plugin.name })) as GeneratorContext<TOptions>['requirePlugin'],\n getResolver: driver.getResolver.bind(driver),\n driver,\n addFile: async (...files: Array<FileNode>) => {\n driver.fileManager.add(...files)\n },\n upsertFile: async (...files: Array<FileNode>) => {\n driver.fileManager.upsert(...files)\n },\n get meta(): InputMeta {\n return driver.inputNode?.meta ?? { circularNames: [], enumNames: [] }\n },\n get adapter(): Adapter {\n // Generators only read `adapter` during AST hooks, which run after the\n // adapter is set, so it is guaranteed defined at read time.\n return driver.adapter!\n },\n get resolver() {\n return driver.getResolver(plugin.name)\n },\n warn(message: string) {\n report({ code: Diagnostics.code.pluginWarning, severity: 'warning', message })\n },\n error(error: string | Error) {\n const cause = typeof error === 'string' ? undefined : error\n report({ code: Diagnostics.code.pluginFailed, severity: 'error', message: typeof error === 'string' ? error : error.message, cause })\n },\n info(message: string) {\n report({ code: Diagnostics.code.pluginInfo, severity: 'info', message })\n },\n }\n }\n\n getPlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined\n getPlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string): Plugin<TOptions> | undefined\n getPlugin(pluginName: string): Plugin | undefined {\n return this.plugins.get(pluginName)\n }\n\n /**\n * Like `getPlugin` but throws a descriptive error when the plugin is not found.\n */\n requirePlugin<TName extends keyof Kubb.PluginRegistry>(pluginName: TName, context?: RequirePluginContext): Plugin<Kubb.PluginRegistry[TName]>\n requirePlugin<TOptions extends PluginFactoryOptions = PluginFactoryOptions>(pluginName: string, context?: RequirePluginContext): Plugin<TOptions>\n requirePlugin(pluginName: string, context?: RequirePluginContext): Plugin {\n const plugin = this.getPlugin(pluginName)\n if (plugin) return plugin\n\n const requiredBy = context?.requiredBy\n const by = requiredBy ? ` by \"${requiredBy}\"` : ''\n const help = requiredBy ? ` (required by \"${requiredBy}\")` : ''\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.pluginNotFound,\n severity: 'error',\n message: `Plugin \"${pluginName}\" is required${by} but not found. Make sure it is included in your Kubb config.`,\n help: `Add \"${pluginName}\" to the \\`plugins\\` array in kubb.config.ts${help}, or remove the dependency on it.`,\n location: { kind: 'config' },\n })\n }\n}\n","/**\n * Backend that persists generated files. Kubb ships with `fsStorage` (writes\n * to disk) and `memoryStorage` (keeps everything in RAM). Implement this\n * interface to write somewhere else, such as S3 or a database.\n */\nexport type Storage = {\n /**\n * Identifier used in logs and diagnostics (`'fs'`, `'memory'`, `'s3'`).\n */\n readonly name: string\n /**\n * Returns `true` when an entry for `key` exists.\n */\n hasItem(key: string): Promise<boolean>\n /**\n * Reads the stored string. Returns `null` when the key is missing.\n */\n getItem(key: string): Promise<string | null>\n /**\n * Stores `value` under `key`, creating any required structure (directories,\n * buckets, ...).\n */\n setItem(key: string, value: string): Promise<void>\n /**\n * Deletes the entry for `key`. No-op when the key does not exist.\n */\n removeItem(key: string): Promise<void>\n /**\n * Returns every key. Pass `base` to filter to keys starting with that prefix.\n */\n getKeys(base?: string): Promise<Array<string>>\n /**\n * Removes every entry. Pass `base` to scope the wipe to a key prefix.\n */\n clear(base?: string): Promise<void>\n}\n\n/**\n * Defines a custom storage backend. The builder receives user options and\n * returns a `Storage` implementation. Kubb ships with filesystem and in-memory\n * storages. A custom backend writes generated files elsewhere, such as cloud\n * storage or a database.\n *\n * @example In-memory storage (the built-in implementation)\n * ```ts\n * import { createStorage } from '@kubb/core'\n *\n * export const memoryStorage = createStorage(() => {\n * const store = new Map<string, string>()\n *\n * return {\n * name: 'memory',\n * async hasItem(key) {\n * return store.has(key)\n * },\n * async getItem(key) {\n * return store.get(key) ?? null\n * },\n * async setItem(key, value) {\n * store.set(key, value)\n * },\n * async removeItem(key) {\n * store.delete(key)\n * },\n * async getKeys(base) {\n * const keys = [...store.keys()]\n * return base ? keys.filter((k) => k.startsWith(base)) : keys\n * },\n * async clear(base) {\n * if (!base) store.clear()\n * },\n * }\n * })\n * ```\n */\nexport function createStorage<TOptions = Record<string, never>>(build: (options: TOptions) => Storage): (options?: TOptions) => Storage {\n return (options) => build(options ?? ({} as TOptions))\n}\n","import { access, glob, readFile, rm } from 'node:fs/promises'\nimport { join, relative, resolve } from 'node:path'\nimport { clean, toPosixPath, write } from '@internals/utils'\nimport { createStorage } from '../createStorage.ts'\n\n// Caps concurrent writes so a build with thousands of files doesn't open that many file\n// descriptors at once.\nconst WRITE_CONCURRENCY = 50\n\nfunction createLimiter(concurrency: number) {\n let active = 0\n const queue: Array<() => void> = []\n\n function next(): void {\n if (active >= concurrency) return\n const run = queue.shift()\n if (!run) return\n active++\n run()\n }\n\n return function limit<TResult>(task: () => Promise<TResult>): Promise<TResult> {\n return new Promise((resolve, reject) => {\n queue.push(() => {\n task()\n .then(resolve, reject)\n .finally(() => {\n active--\n next()\n })\n })\n next()\n })\n }\n}\n\n/**\n * Built-in filesystem storage driver.\n *\n * This is the default storage when no `storage` option is configured in the root config.\n * Keys are resolved against `process.cwd()`, so root-relative paths such as\n * `src/gen/api/getPets.ts` are written to the correct location without extra configuration.\n *\n * Writes are deduplicated and directory-safe:\n * - leading and trailing whitespace is trimmed before writing\n * - the write is skipped when the file content is already identical\n * - missing parent directories are created automatically\n * - Bun's native file API is used when running under Bun\n * - concurrent `setItem` calls are capped at {@link WRITE_CONCURRENCY} in flight, so a caller\n * can fire every file's write without pacing itself\n *\n * @example\n * ```ts\n * import { fsStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * storage: fsStorage(),\n * })\n * ```\n */\nexport const fsStorage = createStorage(() => {\n const limit = createLimiter(WRITE_CONCURRENCY)\n\n return {\n name: 'fs',\n async hasItem(key: string) {\n try {\n await access(resolve(key))\n return true\n } catch (_error) {\n return false\n }\n },\n async getItem(key: string) {\n try {\n return await readFile(resolve(key), 'utf8')\n } catch (_error) {\n return null\n }\n },\n async setItem(key: string, value: string) {\n await limit(() => write(resolve(key), value, { sanity: false }))\n },\n async removeItem(key: string) {\n await rm(resolve(key), { force: true })\n },\n async getKeys(base?: string) {\n const resolvedBase = resolve(base ?? process.cwd())\n const keys: Array<string> = []\n\n try {\n for await (const entry of glob('**/*', { cwd: resolvedBase, withFileTypes: true })) {\n if (entry.isFile()) {\n keys.push(toPosixPath(relative(resolvedBase, join(entry.parentPath, entry.name))))\n }\n }\n } catch (_error) {\n // base directory does not exist yet\n }\n\n return keys\n },\n async clear(base?: string) {\n if (!base) {\n return\n }\n\n await clean(resolve(base))\n },\n }\n})\n","import { resolve } from 'node:path'\nimport { BuildError } from '@internals/utils'\nimport { HOOK_LISTENERS_PER_PLUGIN } from './constants.ts'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { Storage } from './createStorage.ts'\nimport { KubbDriver } from './KubbDriver.ts'\nimport { fsStorage } from './storages/fsStorage.ts'\nimport type { BuildOutput, Config, KubbHooks, UserConfig } from './types.ts'\nimport { Hookable } from './Hookable.ts'\n\nfunction resolveConfig(userConfig: UserConfig): Config {\n return {\n ...userConfig,\n root: userConfig.root || process.cwd(),\n parsers: userConfig.parsers ?? [],\n output: {\n format: false,\n lint: false,\n defaultBanner: 'simple',\n ...userConfig.output,\n },\n storage: userConfig.storage ?? fsStorage(),\n reporters: userConfig.reporters ?? [],\n plugins: userConfig.plugins ?? [],\n }\n}\n\nexport type CreateKubbOptions = {\n hooks?: Hookable<KubbHooks>\n}\n\n/**\n * Kubb code-generation instance bound to a single config entry. Resolves the user\n * config in the constructor, so `config` is available right away, and shares `hooks`,\n * `storage`, and `driver` across the `setup → build` lifecycle.\n *\n * `createKubb` takes a plain config object (the shape `defineConfig` produces),\n * not a fluent builder.\n *\n * Attach hook listeners to `.hooks` before calling `setup()` or `build()`.\n *\n * @example\n * ```ts\n * const kubb = createKubb(userConfig)\n * kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => console.log(plugin.name, duration))\n * const { files, diagnostics } = await kubb.safeBuild()\n * ```\n */\nexport class Kubb {\n readonly hooks: Hookable<KubbHooks>\n readonly config: Config\n #driver: KubbDriver | null = null\n #storage: Storage | null = null\n\n constructor(userConfig: UserConfig, options: CreateKubbOptions = {}) {\n this.config = resolveConfig(userConfig)\n this.hooks = options.hooks ?? new Hookable<KubbHooks>()\n }\n\n get storage(): Storage {\n if (!this.#storage) throw new Error('[kubb] setup() must be called before accessing storage')\n return this.#storage\n }\n\n get driver(): KubbDriver {\n if (!this.#driver) throw new Error('[kubb] setup() must be called before accessing driver')\n return this.#driver\n }\n\n /**\n * Initializes the driver and storage. `build()` calls this automatically.\n */\n async setup(): Promise<void> {\n const config = this.config\n const driver = new KubbDriver(config, { hooks: this.hooks })\n\n // Each generator a plugin registers adds a listener to the shared hooks emitter, so size the\n // ceiling to the plugin count. Without this, a multi-generator plugin set trips Node's\n // EventEmitter leak warning at the default 10.\n this.hooks.setMaxListeners(Math.max(10, config.plugins.length * HOOK_LISTENERS_PER_PLUGIN))\n\n if (config.output.clean) {\n await config.storage.clear(resolve(config.root, config.output.path))\n }\n\n await driver.setup()\n\n this.#driver = driver\n this.#storage = config.storage\n }\n\n /**\n * Runs the full pipeline and throws on any plugin error.\n * Automatically calls `setup()` if needed.\n */\n async build(): Promise<BuildOutput> {\n const out = await this.safeBuild()\n if (Diagnostics.hasError(out.diagnostics)) {\n const errors = out.diagnostics\n .filter(Diagnostics.isProblem)\n .filter((diagnostic) => diagnostic.severity === 'error')\n .map((diagnostic) => diagnostic.cause ?? new Diagnostics.Error(diagnostic))\n throw new BuildError(`Build failed with ${errors.length} ${errors.length === 1 ? 'error' : 'errors'}`, { errors })\n }\n return out\n }\n\n /**\n * Runs the full pipeline and captures errors in `BuildOutput` instead of throwing.\n * Automatically calls `setup()` if needed. This is the canonical call: it never throws on\n * plugin errors, so callers stay in control of how failures surface.\n */\n async safeBuild(): Promise<BuildOutput> {\n if (!this.#driver) await this.setup()\n using self = this\n const driver = self.driver\n const storage = self.storage\n const { diagnostics } = await driver.run()\n\n return { diagnostics, files: driver.fileManager.files, driver, storage }\n }\n\n dispose(): void {\n this.#driver?.dispose()\n }\n\n [Symbol.dispose](): void {\n this.dispose()\n }\n}\n\n/**\n * Constructs a {@link Kubb} build orchestrator from a user config. Equivalent\n * to `new Kubb(userConfig, options)` and the canonical public entry point.\n *\n * @example\n * ```ts\n * import { createKubb } from '@kubb/core'\n * import { adapterOas } from '@kubb/adapter-oas'\n * import { pluginTs } from '@kubb/plugin-ts'\n *\n * const kubb = createKubb({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * adapter: adapterOas(),\n * plugins: [pluginTs()],\n * })\n *\n * await kubb.build()\n * ```\n */\nexport function createKubb(userConfig: UserConfig, options: CreateKubbOptions = {}): Kubb {\n return new Kubb(userConfig, options)\n}\n","import type { Config } from './types.ts'\nimport type { Diagnostic } from './Diagnostics.ts'\n\n/**\n * Numeric log-level thresholds used internally to compare verbosity.\n *\n * Higher numbers are more verbose.\n */\nexport const logLevel = {\n silent: Number.NEGATIVE_INFINITY,\n error: 0,\n warn: 1,\n info: 3,\n verbose: 4,\n} as const\n\n/**\n * A built-in reporter that renders a run's output, independent of the live logger view.\n *\n * - `cli` renders the per-config summary to the terminal (the default).\n * - `json` writes a machine-readable report to stdout, for CI.\n * - `file` writes a config's diagnostics to `.kubb/kubb-<name>-<timestamp>.log`.\n */\nexport type ReporterName = 'cli' | 'json' | 'file'\n\n/**\n * One config's outcome within a run, as handed to a {@link Reporter}.\n */\nexport type GenerationResult = {\n config: Config\n /**\n * Diagnostics collected while generating this config.\n */\n diagnostics: Array<Diagnostic>\n /**\n * Number of files written for this config.\n */\n filesCreated: number\n status: 'success' | 'failed'\n /**\n * `process.hrtime()` snapshot taken when this config started generating.\n */\n hrStart: [number, number]\n}\n\n/**\n * Render settings passed alongside the {@link GenerationResult}. These are not part of the run\n * data, such as the output verbosity.\n */\nexport type ReporterContext = {\n /**\n * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`\n * (`silent`, `error`, `warn`, `info`, `verbose`).\n */\n logLevel: (typeof logLevel)[keyof typeof logLevel]\n}\n\n/**\n * Host-facing reporter, as installed onto a run. Unlike a Logger (the live TUI view), a reporter\n * never sees the hook emitter. `report` runs once per config. `drain`, when present, runs once\n * after the last config.\n */\nexport type Reporter = {\n /**\n * Display name, matching a {@link ReporterName} for the built-ins.\n */\n name: string\n /**\n * Called once per config with that config's result and the render context.\n */\n report: (result: GenerationResult, context: ReporterContext) => void | Promise<void>\n /**\n * Optional finalizer called once after the run's last config. The host wires it to\n * `kubb:lifecycle:end`. {@link createReporter} closes it over the values that `report` returned.\n */\n drain: (context: ReporterContext) => void | Promise<void>\n [Symbol.dispose](): void\n}\n\n/**\n * Reporter definition passed to {@link createReporter}. `report` returns the value to collect for\n * this config (e.g. a built report), and the optional `drain` receives the collected reports to\n * emit as one document. `T` is inferred from `report`'s return type.\n */\nexport type UserReporter<T = void> = {\n name: string\n report: (result: GenerationResult, context: ReporterContext) => T | Promise<T>\n drain?: (context: ReporterContext, reports: Array<T>) => void | Promise<void>\n}\n\n/**\n * Defines a reporter. When the definition has a `drain`, the returned reporter buffers each value\n * `report` returns and hands the array to `drain` once, then clears it. Without a `drain`, nothing\n * is buffered. Wiring the reporter onto the run's hooks is the host's job, so the reporter only\n * ever deals with a {@link GenerationResult}.\n *\n * @example\n * ```ts\n * import { createReporter, Diagnostics } from '@kubb/core'\n *\n * export const jsonReporter = createReporter({\n * name: 'json',\n * report(result) {\n * return { status: Diagnostics.hasError(result.diagnostics) ? 'failed' : 'success', diagnostics: result.diagnostics }\n * },\n * drain(context, reports) {\n * process.stdout.write(`${JSON.stringify(reports, null, 2)}\\n`)\n * },\n * })\n * ```\n */\nexport function createReporter<T = void>(reporter: UserReporter<T>): Reporter {\n const reports = new Set<T>()\n\n return {\n name: reporter.name,\n async report(result, context) {\n const report = await reporter.report(result, context)\n reports.add(report)\n },\n async drain(context) {\n await reporter.drain?.(context, Array.from(reports))\n reports.clear()\n },\n [Symbol.dispose]() {\n reports.clear()\n },\n }\n}\n","import { resolve } from 'node:path'\nimport { getElapsedMs } from '@internals/utils'\nimport type { GenerationResult } from '../createReporter.ts'\nimport { Diagnostics, type SerializedDiagnostic } from '../Diagnostics.ts'\n\n/**\n * One plugin's elapsed time, derived from a `performance` diagnostic.\n */\ntype ReportTiming = {\n plugin: string\n durationMs: number\n}\n\n/**\n * The normalized result of generating one config, shared by every reporter. Each reporter renders\n * the same {@link Report} in its own format (the `cli` summary, the `json` document, the `file`\n * log), so they always agree on the numbers. Build it with {@link buildReport}.\n */\nexport type Report = {\n /**\n * The config name, or an empty string when it is unnamed.\n */\n name: string\n status: 'success' | 'failed'\n plugins: {\n passed: number\n /**\n * Names of the plugins that failed.\n */\n failed: Array<string>\n total: number\n }\n counts: {\n errors: number\n warnings: number\n infos: number\n }\n filesCreated: number\n /**\n * Wall-clock time spent generating this config, in milliseconds.\n */\n durationMs: number\n /**\n * Absolute output directory the files were written to.\n */\n output: string\n /**\n * Per-plugin durations, slowest first.\n */\n timings: Array<ReportTiming>\n /**\n * The build problems, serialized to their JSON-safe fields plus a `docsUrl`.\n */\n diagnostics: Array<SerializedDiagnostic>\n}\n\n/**\n * Builds the normalized {@link Report} for one config from its {@link GenerationResult}. Splits the\n * diagnostics into problems and per-plugin timings (slowest first) and derives the plugin and issue\n * counts, so every reporter renders the same data.\n */\nexport function buildReport(result: GenerationResult): Report {\n const { config, diagnostics, filesCreated, status, hrStart } = result\n\n const failed = Diagnostics.failedPlugins(diagnostics)\n const total = config.plugins?.length ?? 0\n const counts = Diagnostics.count(diagnostics)\n const problems = diagnostics.filter(Diagnostics.isProblem)\n const timings = diagnostics\n .filter(Diagnostics.isPerformance)\n .sort((a, b) => b.duration - a.duration)\n .map((diagnostic) => ({ plugin: diagnostic.plugin, durationMs: diagnostic.duration }))\n\n return {\n name: config.name ?? '',\n status,\n plugins: { passed: total - failed.length, failed, total },\n counts,\n filesCreated,\n durationMs: getElapsedMs(hrStart),\n output: resolve(config.root, config.output.path),\n timings,\n diagnostics: problems.map((diagnostic) => Diagnostics.serialize(diagnostic)),\n }\n}\n","import { styleText } from 'node:util'\nimport { formatMs, randomCliColor } from '@internals/utils'\nimport { SUMMARY_MAX_BAR_LENGTH, SUMMARY_TIME_SCALE_DIVISOR } from '../constants.ts'\nimport { createReporter, logLevel as logLevelMap } from '../createReporter.ts'\nimport { buildReport, type Report } from './report.ts'\n\n/**\n * Builds the vitest/jest-style summary for one {@link Report}: right-aligned dim labels with\n * `N passed (total)` counts, and a per-plugin `Timings` section when `showTimings`.\n */\nfunction buildSummaryLines(report: Report, { showTimings }: { showTimings: boolean }): Array<string> {\n const { status, plugins, counts, filesCreated, durationMs, output, timings } = report\n\n const rows: Array<[label: string, value: string]> = []\n\n rows.push([\n 'Plugins',\n status === 'success'\n ? `${styleText('green', `${plugins.passed} passed`)} (${plugins.total})`\n : `${styleText('green', `${plugins.passed} passed`)} | ${styleText('red', `${plugins.failed.length} failed`)} (${plugins.total})`,\n ])\n\n if (status === 'failed' && plugins.failed.length > 0) {\n rows.push(['Failed', plugins.failed.map((name) => randomCliColor(name)).join(', ')])\n }\n\n if (counts.errors > 0 || counts.warnings > 0) {\n const issues = [\n counts.errors > 0 ? styleText('red', `${counts.errors} ${counts.errors === 1 ? 'error' : 'errors'}`) : undefined,\n counts.warnings > 0 ? styleText('yellow', `${counts.warnings} ${counts.warnings === 1 ? 'warning' : 'warnings'}`) : undefined,\n ]\n .filter(Boolean)\n .join(' | ')\n rows.push(['Issues', issues])\n }\n\n rows.push(['Files', `${styleText('green', String(filesCreated))} generated`])\n rows.push(['Duration', styleText('green', formatMs(durationMs))])\n rows.push(['Output', output])\n\n const labelWidth = Math.max(...rows.map(([label]) => label.length), timings.length > 0 ? 'Timings'.length : 0)\n const lines = rows.map(([label, value]) => `${styleText('dim', label.padStart(labelWidth))} ${value}`)\n\n if (showTimings && timings.length > 0) {\n const nameWidth = Math.max(0, ...timings.map((timing) => timing.plugin.length))\n const indent = ' '.repeat(labelWidth + 2)\n\n lines.push(styleText('dim', 'Timings'.padStart(labelWidth)))\n for (const timing of timings) {\n const timeStr = formatMs(timing.durationMs)\n const barLength = Math.min(Math.ceil(timing.durationMs / SUMMARY_TIME_SCALE_DIVISOR), SUMMARY_MAX_BAR_LENGTH)\n const bar = styleText('dim', '█'.repeat(barLength))\n lines.push(`${indent}${styleText('dim', '•')} ${timing.plugin.padEnd(nameWidth)} ${bar} ${timeStr}`)\n }\n }\n\n return lines\n}\n\n/**\n * Renders the summary as plain `console.log` lines so it works in every CLI (no clack/TTY\n * dependency): a blank line, the config name colored by status, then the summary rows.\n */\nfunction renderSummary(lines: ReadonlyArray<string>, { title, status }: { title: string; status: 'success' | 'failed' }): void {\n console.log('')\n if (title) {\n console.log(styleText(status === 'failed' ? 'red' : 'green', title))\n }\n for (const line of lines) {\n console.log(line)\n }\n}\n\n/**\n * The default `cli` reporter. Renders the {@link Report} for each config as it finishes, independent\n * of the live logger view. Suppressed at `silent`. The `verbose` level adds the per-plugin timings.\n */\nexport const cliReporter = createReporter({\n name: 'cli',\n report(result, { logLevel }) {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const report = buildReport(result)\n const lines = buildSummaryLines(report, { showTimings: logLevel >= logLevelMap.verbose })\n renderSummary(lines, { title: report.name, status: report.status })\n },\n})\n","import { relative, resolve } from 'node:path'\nimport process from 'node:process'\nimport { stripVTControlCharacters } from 'node:util'\nimport { formatMs, write } from '@internals/utils'\nimport { createReporter } from '../createReporter.ts'\nimport { type Diagnostic, Diagnostics } from '../Diagnostics.ts'\nimport { buildReport, type Report } from './report.ts'\n\n/**\n * Builds the `## Summary` section: the same counts the cli and json reporters expose, as a list of\n * `label value` rows with the labels padded to a common width.\n */\nfunction buildSummarySection(report: Report): Array<string> {\n const { status, plugins, counts, filesCreated, durationMs, output } = report\n\n const rows: Array<[label: string, value: string]> = [\n ['Status', status],\n [\n 'Plugins',\n status === 'success' ? `${plugins.passed} passed (${plugins.total})` : `${plugins.passed} passed | ${plugins.failed.length} failed (${plugins.total})`,\n ],\n ]\n\n if (plugins.failed.length > 0) {\n rows.push(['Failed', plugins.failed.join(', ')])\n }\n\n rows.push(['Issues', `${counts.errors} errors | ${counts.warnings} warnings | ${counts.infos} infos`])\n rows.push(['Files', `${filesCreated} generated`])\n rows.push(['Duration', formatMs(durationMs)])\n rows.push(['Output', output])\n\n const labelWidth = Math.max(...rows.map(([label]) => label.length))\n const lines = rows.map(([label, value]) => ` ${label.padEnd(labelWidth)} ${value}`)\n\n return ['## Summary', '', ...lines]\n}\n\n/**\n * Builds the `## Problems` section: each problem rendered in the miette block format, blocks\n * separated by a blank line. Returns an empty array when there are no problems, so the caller\n * can drop the heading.\n */\nfunction buildProblemSection(diagnostics: ReadonlyArray<Diagnostic>): Array<string> {\n const problems = diagnostics.filter(Diagnostics.isProblem)\n if (problems.length === 0) {\n return []\n }\n\n const blocks = problems.map((diagnostic) => Diagnostics.formatLines(diagnostic).join('\\n'))\n return ['## Problems', '', blocks.join('\\n\\n')]\n}\n\n/**\n * Builds the `## Timings` section from a {@link Report}: one `plugin duration` row per record,\n * slowest first with the plugin names left-aligned and the durations right-aligned. Returns an\n * empty array when there are no timings.\n */\nfunction buildTimingSection(report: Report): Array<string> {\n const { timings } = report\n if (timings.length === 0) {\n return []\n }\n\n const nameWidth = Math.max(...timings.map((timing) => timing.plugin.length))\n const durations = timings.map((timing) => formatMs(timing.durationMs))\n const durationWidth = Math.max(...durations.map((duration) => duration.length))\n const rows = timings.map((timing, index) => ` ${timing.plugin.padEnd(nameWidth)} ${durations[index]!.padStart(durationWidth)}`)\n\n return ['## Timings', '', ...rows]\n}\n\n/**\n * The `file` reporter. Writes a config's {@link Report} to `.kubb/kubb-<name>-<timestamp>.log` as a\n * plain-text document: a `# <name> — <timestamp>` header, a `## Summary` with the same counts the\n * cli and json reporters expose, a `## Problems` section in the miette block format, and a\n * `## Timings` section. Selected with `--reporter file` (or `reporters: ['file']`).\n *\n * @note It captures the collected diagnostics once a config finishes, not the live\n * `kubb:info`/`kubb:plugin` hook stream. Color is stripped so the file stays plain text even when\n * the run is attached to a TTY.\n */\nexport const fileReporter = createReporter({\n name: 'file',\n async report(result) {\n const { diagnostics, config } = result\n if (diagnostics.length === 0) {\n return\n }\n\n const report = buildReport(result)\n const header = config.name ? `# ${config.name} — ${new Date().toISOString()}` : `# ${new Date().toISOString()}`\n const sections = [buildSummarySection(report), buildProblemSection(diagnostics), buildTimingSection(report)].filter((section) => section.length > 0)\n const content = stripVTControlCharacters([header, ...sections.map((section) => section.join('\\n'))].join('\\n\\n'))\n\n const baseName = `${['kubb', config.name, Date.now()].filter(Boolean).join('-')}.log`\n const pathName = resolve(process.cwd(), '.kubb', baseName)\n\n await write(pathName, `${content}\\n`)\n console.error(`Debug log written to ${relative(process.cwd(), pathName)}`)\n },\n})\n","import process from 'node:process'\nimport { createReporter } from '../createReporter.ts'\nimport { buildReport } from './report.ts'\n\n/**\n * The `json` reporter. `report` returns one config's {@link Report}, which {@link createReporter}\n * buffers, and `drain` writes them as a single pretty-printed JSON array on `kubb:lifecycle:end`.\n * Buffering keeps a multi-config run one valid JSON document on stdout instead of concatenated\n * objects that would break `jq .`. The terminal reporter is suppressed while `json` is active so\n * stdout stays valid JSON.\n */\nexport const jsonReporter = createReporter({\n name: 'json',\n report(result) {\n return buildReport(result)\n },\n drain(_context, reports) {\n process.stdout.write(`${JSON.stringify(reports, null, 2)}\\n`)\n },\n})\n","import type { FileNode } from '@kubb/ast'\n\n/**\n * Minimal interface any Kubb renderer must satisfy.\n *\n * `TElement` is the type the renderer accepts, for example `KubbReactElement`\n * for `@kubb/renderer-jsx` or a custom type for your own renderer. Defaults to\n * `unknown` so generators that don't care about the element type work without\n * specifying it.\n */\nexport type Renderer<TElement = unknown> = {\n /**\n * Renders `element` and populates {@link files} with the resulting {@link FileNode} objects.\n * Called once per render cycle. Must resolve before {@link files} is read.\n */\n render(element: TElement): Promise<void>\n /**\n * Accumulated {@link FileNode} results produced by the last {@link render} call.\n */\n readonly files: Array<FileNode>\n /**\n * Disposer hook so renderers participate in `using` blocks: `using r = rendererFactory()`\n * runs cleanup on every exit path, including thrown errors.\n */\n [Symbol.dispose](): void\n}\n\n/**\n * A factory function that produces a fresh {@link Renderer} per render cycle.\n *\n * Generators use this to declare which renderer handles their output.\n */\nexport type RendererFactory<TElement = unknown> = () => Renderer<TElement>\n\n/**\n * Defines a renderer factory. Renderers turn the generator's return value\n * (JSX, a template string, a tree of any shape) into `FileNode`s that get\n * written to disk.\n *\n * A renderer can target output formats beyond JSX, for instance a Handlebars\n * renderer or one that writes binary files. Plugins and generators pick the\n * renderer to use via the `renderer` field on `defineGenerator`.\n *\n * @example A minimal renderer that wraps a custom runtime\n * ```ts\n * import { createRenderer } from '@kubb/core'\n *\n * export const myRenderer = createRenderer(() => {\n * const runtime = new MyRuntime()\n * return {\n * async render(element) {\n * await runtime.render(element)\n * },\n * get files() {\n * return runtime.files\n * },\n * [Symbol.dispose]() {\n * runtime.dispose()\n * },\n * }\n * })\n * ```\n */\nexport function createRenderer<TElement = unknown>(factory: RendererFactory<TElement>): RendererFactory<TElement> {\n return factory\n}\n","import type { PossiblePromise } from '@internals/utils'\nimport type { FileNode, InputMeta, OperationNode, SchemaNode } from '@kubb/ast'\nimport type { Adapter } from './createAdapter.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { KubbHooks } from './types.ts'\nimport type { KubbDriver } from './KubbDriver.ts'\nimport type { Plugin, PluginFactoryOptions } from './definePlugin.ts'\nimport type { Resolver } from './Resolver.ts'\nimport type { Config } from './types.ts'\nimport type { Hookable } from './Hookable.ts'\n\n/**\n * Context passed to a generator's `schema`, `operation`, and `operations` methods.\n *\n * The driver sets `adapter` on the context before it runs a generator, so methods can read it\n * without a null check. `ctx.options` carries the per-node options after exclude/include/override\n * filtering for `schema` and `operation`, or the plugin-level options for `operations`.\n */\nexport type GeneratorContext<TOptions extends PluginFactoryOptions = PluginFactoryOptions> = {\n /**\n * The resolved Kubb config for this build, including `root`, `input`, `output`, and the\n * full plugin list.\n */\n config: Config\n /**\n * Absolute path to the current plugin's output directory.\n */\n root: string\n /**\n * The driver running this build. Most generators never need it. Prefer the scoped helpers\n * on this context (`getPlugin`, `getResolver`, `upsertFile`) over reaching into the driver.\n */\n driver: KubbDriver\n /**\n * Get a plugin by name, typed via `Kubb.PluginRegistry` when registered.\n */\n getPlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]> | undefined\n getPlugin(name: string): Plugin | undefined\n /**\n * Get a plugin by name, throws an error if not found.\n */\n requirePlugin<TName extends keyof Kubb.PluginRegistry>(name: TName): Plugin<Kubb.PluginRegistry[TName]>\n requirePlugin(name: string): Plugin\n /**\n * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.\n */\n getResolver<TName extends keyof Kubb.PluginRegistry>(name: TName): Kubb.PluginRegistry[TName]['resolver']\n getResolver(name: string): Resolver\n /**\n * Add files only if they don't exist.\n */\n addFile: (...file: Array<FileNode>) => Promise<void>\n /**\n * Merge sources into the same output file.\n */\n upsertFile: (...file: Array<FileNode>) => Promise<void>\n /**\n * The build's hook bus. Emit or listen to any `KubbHooks` hook, for example to react to\n * `kubb:build:end` from inside a generator.\n */\n hooks: Hookable<KubbHooks>\n /**\n * The current plugin instance.\n */\n plugin: Plugin<TOptions>\n /**\n * The current plugin's resolver. It decides what every generated symbol and file path is\n * called. Kubb picks a `setResolver` registration first, then the plugin's static\n * `resolver`, then the built-in default.\n *\n * @example Resolve a name\n * `ctx.resolver.name('pet') // 'pet'`\n *\n * @example Resolve an output file\n * `ctx.resolver.file({ name: 'pet', extname: '.ts', root, output })`\n */\n resolver: TOptions['resolver']\n /**\n * Report a warning. Collected as a `warning` diagnostic attributed to the current\n * plugin. It surfaces in the run summary but does not fail the build. For a structured\n * diagnostic with a code and source location, use `Diagnostics.report` or throw a\n * `Diagnostics.Error` directly.\n */\n warn: (message: string) => void\n /**\n * Report an error. Collected as an `error` diagnostic attributed to the current\n * plugin, which fails the build.\n */\n error: (error: string | Error) => void\n /**\n * Report an informational message. Collected as an `info` diagnostic attributed to\n * the current plugin.\n */\n info: (message: string) => void\n /**\n * The configured adapter instance.\n */\n adapter: Adapter\n /**\n * Document metadata from the adapter: title, version, base URL, and pre-computed\n * schema index fields (`circularNames`, `enumNames`).\n */\n meta: InputMeta\n /**\n * Resolved options after exclude/include/override filtering.\n */\n options: TOptions['resolvedOptions']\n}\n\n/**\n * Declares a named generator unit that walks the AST and emits files.\n *\n * `schema` runs for each schema node and `operation` for each operation node. `operations` runs\n * once after every operation node is walked. JSX-based generators require a `renderer` factory.\n * Return `Array<FileNode>` directly, or call `ctx.upsertFile()` manually and return `null` to\n * bypass rendering.\n *\n * @note Generators are consumed by plugins and registered via `ctx.addGenerator()` in `kubb:plugin:setup`.\n *\n * @example\n * ```ts\n * import { defineGenerator } from '@kubb/core'\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n *\n * export const typeGenerator = defineGenerator({\n * name: 'typescript',\n * renderer: jsxRenderer,\n * schema(node, ctx) {\n * const { adapter, resolver, root, options } = ctx\n * return <File ...><Type node={node} resolver={resolver} /></File>\n * },\n * })\n * ```\n */\nexport type Generator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown> = {\n /**\n * Used in diagnostic messages and debug output.\n */\n name: string\n /**\n * Optional renderer factory that produces a {@link Renderer} for each render cycle.\n *\n * Generators that return renderer elements (e.g. JSX via `@kubb/renderer-jsx`) must set this\n * to the matching renderer factory (e.g. `jsxRenderer` from `@kubb/renderer-jsx`).\n *\n * Generators that only return `Array<FileNode>` or `void` do not need to set this.\n *\n * Leave it unset or set `renderer: null` to opt out of rendering.\n *\n * @example\n * ```ts\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n * export const myGenerator = defineGenerator<PluginTs>({\n * renderer: jsxRenderer,\n * schema(node, ctx) { return <File ...>...</File> },\n * })\n * ```\n */\n renderer?: RendererFactory<TElement> | null\n /**\n * Called for each schema node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n schema?: (node: SchemaNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>\n /**\n * Called for each operation node in the AST walk.\n * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),\n * plus `ctx.options` with the per-node resolved options (after exclude/include/override).\n */\n operation?: (node: OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>\n /**\n * Called once after all operations have been walked.\n * `ctx` carries the plugin context with `adapter` and `meta` (document metadata),\n * plus `ctx.options` with the plugin-level options for the batch call.\n */\n operations?: (nodes: Array<OperationNode>, ctx: GeneratorContext<TOptions>) => PossiblePromise<TElement | Array<FileNode> | undefined | null>\n}\n\n/**\n * Defines a generator: a unit of work that runs during the plugin's AST walk\n * and produces files. Plugins register generators via `ctx.addGenerator()`\n * inside `kubb:plugin:setup`.\n *\n * The returned object is the input as-is, but with `this` types preserved so\n * `schema`/`operation`/`operations` methods are correctly typed against the\n * plugin's `PluginFactoryOptions`. Renderer elements and `FileNode[]` returns\n * are both handled by the runtime, so pick whichever style fits.\n *\n * @example JSX-based schema generator\n * ```tsx\n * import { defineGenerator } from '@kubb/core'\n * import { jsxRenderer } from '@kubb/renderer-jsx'\n *\n * export const typeGenerator = defineGenerator({\n * name: 'typescript',\n * renderer: jsxRenderer,\n * schema(node, ctx) {\n * return (\n * <File path={`${ctx.root}/${node.name}.ts`}>\n * <Type node={node} resolver={ctx.resolver} />\n * </File>\n * )\n * },\n * })\n * ```\n */\nexport function defineGenerator<TOptions extends PluginFactoryOptions = PluginFactoryOptions, TElement = unknown>(\n generator: Generator<TOptions, TElement>,\n): Generator<TOptions, TElement> {\n return generator\n}\n","import type { FileNode } from '@kubb/ast'\n\n/**\n * Converts a resolved {@link FileNode} into the final source string that gets\n * written to disk. Kubb ships with TypeScript and TSX parsers. Add your own\n * for new file types (JSON, Markdown, ...).\n */\nexport type Parser<TMeta extends object = object, TNode = unknown> = {\n /**\n * Display name used in diagnostics and the parser registry.\n */\n name: string\n /**\n * File extensions this parser handles. The driver registers the parser for each\n * extension in this list. A parser with `undefined` here is not registered, so\n * files of an unclaimed extension fall back to joining their sources verbatim.\n *\n * @example\n * `['.ts', '.js']`\n */\n extNames: Array<FileNode['extname']> | undefined\n /**\n * Serialize the file's AST into source code.\n */\n parse(file: FileNode<TMeta>): string\n /**\n * Render compiler AST nodes for this parser's language into source text.\n * Plugins call this to format the nodes they assemble before handing them\n * back to the parser as `FileNode.sources`.\n */\n print(...nodes: Array<TNode>): string\n}\n\n/**\n * Wraps a parser factory and returns a function that accepts user options and\n * yields a typed {@link Parser}. Mirrors {@link definePlugin}: the factory\n * receives the caller's options, and calling the returned function without\n * options passes an empty object.\n *\n * Register the result in the `parsers` array on `defineConfig`, calling it to\n * apply options (`parserTs({ extension: { '.ts': '.js' } })`).\n *\n * @example\n * ```ts\n * import { defineParser } from '@kubb/core'\n * import { extractStringsFromNodes } from '@kubb/ast'\n *\n * export const parserJson = defineParser((options: { pretty?: boolean } = {}) => ({\n * name: 'json',\n * extNames: ['.json'],\n * parse(file) {\n * const source = file.sources.map((source) => extractStringsFromNodes(source.nodes ?? [])).join('\\n')\n * return options.pretty ? JSON.stringify(JSON.parse(source), null, 2) : source\n * },\n * print(...nodes) {\n * return nodes.map(String).join('\\n')\n * },\n * }))\n * ```\n */\nexport function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(\n factory: (options: TOptions) => Parser<TMeta, TNode>,\n): (options?: TOptions) => Parser<TMeta, TNode> {\n return (options) => factory(options ?? ({} as TOptions))\n}\n","import { createStorage } from '../createStorage.ts'\n\n/**\n * In-memory storage driver. Useful for testing and dry-run scenarios where\n * generated output should be captured without touching the filesystem.\n *\n * All data lives in a `Map` scoped to the storage instance and is discarded\n * when the instance is garbage-collected.\n *\n * @example\n * ```ts\n * import { memoryStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * storage: memoryStorage(),\n * })\n * ```\n */\nexport const memoryStorage = createStorage(() => {\n const store = new Map<string, string>()\n\n return {\n name: 'memory',\n async hasItem(key: string) {\n return store.has(key)\n },\n async getItem(key: string) {\n return store.get(key) ?? null\n },\n async setItem(key: string, value: string) {\n store.set(key, value)\n },\n async removeItem(key: string) {\n store.delete(key)\n },\n async getKeys(base?: string) {\n const keys = [...store.keys()]\n return base ? keys.filter((k) => k.startsWith(base)) : keys\n },\n async clear(base?: string) {\n if (!base) {\n store.clear()\n return\n }\n for (const key of store.keys()) {\n if (key.startsWith(base)) {\n store.delete(key)\n }\n }\n },\n }\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoHA,SAAgB,cAAuE,OAAkE;CACvJ,QAAQ,YAAY,MAAM,WAAY,CAAC,CAAkB;AAC3D;;;;;;;;;;ACrGA,SAAgB,oBACd,QACA,EAAE,gBAAgB,cAAc,kBAAkB,iBACa;CAE/D,MAAM,UADmB,OAAO,SAAS,MAAM,WAAW,OAAO,SAAS,gBAAgB,IACtD,OAAO,WAA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