@kubb/core 5.0.0-beta.82 → 5.0.0-beta.85

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["camelCase","diagnosticCode","#reporterStorage","AsyncLocalStorage","getErrorMessage","diagnosticCode","toFilePath","pascalCase","camelCase","operationDef","schemaDef","path","ast","#macros","#composed","#memo","#invalidate","#visitorFor","FileManager","#eventGeneratorPlugins","#resolvers","#defaultResolvers","#listeners","#transforms","#normalizePlugin","#registerPlugin","#adapterSource","#parseInput","ast","#trackListener","FileProcessor","#filesPayload","#emitPluginEnd","#runGenerators","OPERATION_FILTER_TYPES","#getDefaultResolver","createStorage","write","runtime","toPosixPath","clean","createStorage","AsyncEventEmitter","#storage","#driver","BuildError","logLevel","logLevelMap","process","write"],"sources":["../../../internals/utils/src/time.ts","../../../internals/utils/src/colors.ts","../../../internals/utils/src/promise.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/url.ts","../src/createAdapter.ts","../package.json","../src/diagnostics.ts","../src/definePlugin.ts","../src/defineResolver.ts","../src/Transform.ts","../src/KubbDriver.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"],"sourcesContent":["/**\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","/** 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\n/**\n * Container that switches between an eager `Array<T>` and a lazy `AsyncIterable<T>`.\n *\n * `Array<T>` by default. With `Stream` set to `true` it becomes `AsyncIterable<T>`, so large\n * collections can be produced lazily without holding every item in memory. Pairs with\n * {@link arrayToAsyncIterable}, which lifts a plain array into the streaming form.\n *\n * @example\n * ```ts\n * type Eager = Streamable<number> // Array<number>\n * type Lazy = Streamable<number, true> // AsyncIterable<number>\n * ```\n */\nexport type Streamable<T, Stream extends boolean = false> = Stream extends true ? AsyncIterable<T> : Array<T>\n\n/**\n * Wraps a plain array in a reusable `AsyncIterable`.\n * Each `[Symbol.asyncIterator]()` call returns a fresh generator so the\n * iterable can be consumed multiple times (e.g. once per plugin pre-scan).\n *\n * @example\n * ```ts\n * const stream = arrayToAsyncIterable([1, 2, 3])\n * for await (const n of stream) console.log(n) // 1, 2, 3\n * ```\n */\nexport function arrayToAsyncIterable<T>(arr: ReadonlyArray<T>): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]() {\n return (async function* () {\n yield* arr\n })()\n },\n }\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 isIdentifier(name)\n}\n\n/**\n * Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.\n *\n * Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys\n * even though they are not valid variable names, so use this (not {@link isValidVarName}) when\n * deciding whether an object key needs quoting.\n *\n * @example\n * ```ts\n * isIdentifier('name') // true\n * isIdentifier('x-total')// false\n * ```\n */\nexport function isIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n}\n","import { camelCase } from './casing.ts'\nimport { isValidVarName } from './reserved.ts'\n\ntype 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 `null` when the path has none.\n */\n params: Record<string, string> | null\n}\n\n/**\n * Supported identifier casing strategies for path parameters.\n */\ntype PathCasing = 'camelcase'\n\ntype TemplateOptions = {\n /**\n * Literal text prepended inside the template literal, e.g. a base URL.\n */\n prefix?: string | null\n /**\n * Transform applied to each extracted parameter name before interpolation.\n */\n replacer?: (pathParam: string) => string\n /**\n * Casing strategy applied to path parameter names.\n */\n casing?: PathCasing\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 * 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 * Casing strategy applied to path parameter names.\n */\n casing?: PathCasing\n}\n\nfunction transformParam(raw: string, casing?: PathCasing): string {\n const param = isValidVarName(raw) ? raw : camelCase(raw)\n return casing === 'camelcase' ? camelCase(param) : param\n}\n\nfunction toParamsObject(\n path: string,\n { replacer, casing }: { replacer?: (pathParam: string) => string; casing?: PathCasing } = {},\n): Record<string, string> | null {\n const params: Record<string, string> = {}\n\n for (const match of path.matchAll(/\\{([^}]+)\\}/g)) {\n const param = transformParam(match[1]!, casing)\n const key = replacer ? replacer(param) : param\n params[key] = key\n }\n\n return Object.keys(params).length > 0 ? params : null\n}\n\n/**\n * Helpers for OpenAPI/Swagger paths, plus a thin wrapper over the native `URL`.\n */\nexport class Url {\n /**\n * Converts an OpenAPI/Swagger path to Express-style colon syntax.\n *\n * @example\n * Url.toPath('/pet/{petId}') // '/pet/:petId'\n */\n static toPath(path: string): string {\n return path.replace(/\\{([^}]+)\\}/g, ':$1')\n }\n\n /**\n * Converts an OpenAPI/Swagger path to a TypeScript template literal string.\n * `prefix` is prepended inside the literal, `replacer` transforms each parameter name,\n * and `casing` controls parameter identifier casing.\n *\n * @example\n * Url.toTemplateString('/pet/{petId}') // '`/pet/${petId}`'\n *\n * @example\n * Url.toTemplateString('/pet/{petId}', { prefix: 'https://api' }) // '`https://api/pet/${petId}`'\n */\n static toTemplateString(path: string, { prefix, replacer, casing }: TemplateOptions = {}): string {\n const parts = path.split(/\\{([^}]+)\\}/)\n const result = parts\n .map((part, i) => {\n if (i % 2 === 0) return part\n const param = transformParam(part, casing)\n return `\\${${replacer ? replacer(param) : param}}`\n })\n .join('')\n\n return `\\`${prefix ?? ''}${result}\\``\n }\n\n /**\n * Returns the path and its extracted params as a structured `URLObject`, or as a stringified\n * expression when `stringify` is set.\n *\n * @example\n * Url.toObject('/pet/{petId}')\n * // { url: '/pet/:petId', params: { petId: 'petId' } }\n */\n static toObject(path: string, { type = 'path', replacer, stringify, casing }: ObjectOptions = {}): URLObject | string {\n const object: URLObject = {\n url: type === 'path' ? Url.toPath(path) : Url.toTemplateString(path, { replacer, casing }),\n params: toParamsObject(path, { replacer, casing }),\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","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: { path: './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 * Memory-efficient streaming variant of `parse()`.\n *\n * Returns an `InputNode<true>` whose `schemas` and `operations` are `AsyncIterable`.\n * Each `for await` loop creates a fresh parse pass over the cached in-memory document.\n * No pre-built arrays are held in memory.\n */\n stream?: (source: AdapterSource) => Promise<InputNode<true>>\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 { AsyncLocalStorage } from 'node:async_hooks'\nimport { styleText } from 'node:util'\nimport type { AsyncEventEmitter } from '@internals/utils'\nimport { getErrorMessage } from '@internals/utils'\nimport { version } from '../package.json'\nimport { type DiagnosticCode, diagnosticCode } from './constants.ts'\nimport type { KubbHooks } from './types.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 * Maps each {@link DiagnosticCode} to the variant it selects, for {@link narrow}.\n * Every {@link ProblemCode} selects a {@link ProblemDiagnostic}, and the two bookkeeping codes\n * select their own variant.\n */\nexport type DiagnosticByCode = Record<ProblemCode, ProblemDiagnostic> &\n Record<typeof diagnosticCode.performance, PerformanceDiagnostic> &\n Record<typeof diagnosticCode.updateAvailable, UpdateDiagnostic>\n\n/**\n * Narrows a {@link Diagnostic} to the variant for `code`, or `null` when it does not match.\n *\n * @example\n * ```ts\n * const update = narrow(diagnostic, diagnosticCode.updateAvailable)\n * if (update) {\n * console.log(update.latestVersion)\n * }\n * ```\n */\nfunction narrow<C extends DiagnosticCode>(diagnostic: Diagnostic, code: C): DiagnosticByCode[C] | null {\n return diagnostic.code === code ? (diagnostic as DiagnosticByCode[C]) : null\n}\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, { color: 'red' | 'yellow' | 'blue' }> = {\n error: { color: 'red' },\n warning: { color: 'yellow' },\n info: { color: '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 in `input.path` (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 in `input.path` 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.path` (a file or URL) or `input.data` (an inline spec) 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.hookFailed]: {\n title: 'Hook failed',\n cause: 'A post-generate shell hook (`hooks.done`) 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 lazily consumed stream, a generator) reports through\n * `Diagnostics.report` and lands 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 * Narrows a {@link Diagnostic} to the variant for `code`, or `null` when it does not match.\n */\n static narrow = narrow\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` event so the loggers render it live.\n * Use it instead of calling `hooks.emit('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: AsyncEventEmitter<KubbHooks>, diagnostic: ProblemDiagnostic | UpdateDiagnostic): Promise<void> {\n await hooks.emit('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 event 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 } from './defineResolver.ts'\nimport { Diagnostics } from './diagnostics.ts'\nimport type { Config, KubbHooks } from './types.ts'\n\n/**\n * Reads a type from a registry, falling back to `{}` when the key is absent. Lets\n * `Kubb.ConfigOptionsRegistry` and `Kubb.PluginOptionsRegistry` be augmented without\n * touching core.\n *\n * @internal\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<_TOptions = unknown> = {\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 * 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 = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName\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 = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName\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> = (ByTag | ByOperationId | ByPath | ByMethod | BySchemaName | ByContentType) & {\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 `defineResolver` 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.\n */\n setResolver(resolver: Partial<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 * Merge a partial config update into the current build configuration.\n */\n updateConfig(config: Partial<Config>): 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 event handlers for this plugin.\n * Any event 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 apply?: (config: Config) => boolean\n version?: string\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 path from 'node:path'\nimport { camelCase, pascalCase, 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 type { PluginFactoryOptions } from './definePlugin.ts'\nimport type { Config, Group, Output } from './types.ts'\n\n/**\n * Type/string pattern filter for include/exclude/override matching.\n */\ntype PatternFilter = {\n type: string\n pattern: string | RegExp\n}\n\n/**\n * Pattern filter with partial option overrides applied when the pattern matches.\n */\ntype PatternOverride<TOptions> = PatternFilter & {\n options: Omit<Partial<TOptions>, 'override'>\n}\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<PatternFilter>\n include?: Array<PatternFilter>\n override?: Array<PatternOverride<TOptions>>\n}\n\n/**\n * Base constraint for all plugin resolver objects.\n *\n * `default`, `resolveOptions`, `resolvePath`, `resolveFile`, `resolveBanner`, and `resolveFooter`\n * are injected automatically by `defineResolver`. Extend this type to add custom resolution methods.\n *\n * @example\n * ```ts\n * type MyResolver = Resolver & {\n * resolveName(node: SchemaNode): string\n * resolveTypedName(node: SchemaNode): string\n * }\n * ```\n */\nexport type Resolver = {\n name: string\n pluginName: string\n default(name: string, type?: 'file' | 'function' | 'type' | 'const'): string\n resolveOptions<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null\n resolvePath(params: ResolverPathParams, context: ResolverContext): string\n resolveFile(params: ResolverFileParams, context: ResolverContext): FileNode\n resolveBanner(meta: InputMeta | undefined, context: ResolveBannerContext): string | null\n resolveFooter(meta: InputMeta | undefined, context: ResolveBannerContext): string | null\n}\n\n/**\n * File-specific parameters for `Resolver.resolvePath`.\n *\n * Pass alongside a `ResolverContext` to identify which file to resolve.\n * Provide `tag` for tag-based grouping or `path` for path-based grouping.\n *\n * @example\n * ```ts\n * resolver.resolvePath(\n * { baseName: 'petTypes.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → '/src/types/pets/petTypes.ts'\n * ```\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 * Shared context passed as the second argument to `Resolver.resolvePath` and `Resolver.resolveFile`.\n *\n * Describes where on disk output is rooted, which output config is active, and the optional\n * grouping strategy that controls subdirectory layout.\n *\n * @example\n * ```ts\n * const context: ResolverContext = {\n * root: config.root,\n * output,\n * group,\n * }\n * ```\n */\nexport type ResolverContext = {\n root: string\n output: Output\n group?: Group\n /**\n * Plugin name used to populate `meta.pluginName` on the resolved file.\n */\n pluginName?: string\n}\n\n/**\n * File-specific parameters for `Resolver.resolveFile`.\n *\n * Pass alongside a `ResolverContext` to fully describe the file to resolve.\n * `tag` and `path` are used only when a matching `group` is present in the context.\n *\n * @example\n * ```ts\n * resolver.resolveFile(\n * { name: 'listPets', extname: '.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }\n * ```\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 * Per-file context describing the file a banner/footer is being resolved for.\n *\n * Supplied by the generator (or the barrel plugin) at resolve-time and merged\n * into `BannerMeta` so a `banner`/`footer` function can branch on the file kind,\n * e.g. omit a `'use server'` 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 * Carries everything in {@link InputMeta} plus the file the banner is rendered into, so a\n * single function can decide per file (e.g. skip a directive on barrel/aggregation files).\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.resolveBanner` and `Resolver.resolveFooter`.\n *\n * `output` is optional, since not every plugin configures a banner/footer.\n * `config` carries the global Kubb config, used to derive the default Kubb banner.\n * `file` carries per-file context forwarded to a `banner`/`footer` function.\n *\n * @example\n * ```ts\n * resolver.resolveBanner(meta, { output: { banner: '// generated' }, config })\n * // → '// generated'\n * ```\n */\nexport type ResolveBannerContext = {\n output?: Pick<Output, 'banner' | 'footer'>\n config: Config\n file?: ResolveBannerFile\n}\n\n/**\n * Merges document `meta` with per-file `file` context into the `BannerMeta` passed to a\n * `banner`/`footer` function. Missing fields default to empty/`false` so the object shape\n * is stable even when a caller (e.g. the barrel plugin) has no document metadata.\n */\nfunction buildBannerMeta({ meta, file }: { 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 * Builder type for the plugin-specific resolver fields.\n *\n * `default`, `resolveOptions`, `resolvePath`, `resolveFile`, `resolveBanner`, and `resolveFooter`\n * are optional, with built-in fallbacks injected when omitted.\n *\n * Methods in the returned object can call sibling resolver methods via `this`.\n */\ntype ResolverBuilder<T extends PluginFactoryOptions> = () => Omit<\n T['resolver'],\n 'default' | 'resolveOptions' | 'resolvePath' | 'resolveFile' | 'resolveBanner' | 'resolveFooter' | 'name' | 'pluginName'\n> &\n Partial<Pick<T['resolver'], 'default' | 'resolveOptions' | 'resolvePath' | 'resolveFile' | 'resolveBanner' | 'resolveFooter'>> & {\n name: string\n pluginName: T['name']\n } & ThisType<T['resolver']>\n\n// String patterns are compiled lazily and cached, so the same filter is reused for every node.\nconst stringPatternCache = new Map<string, RegExp>()\n\nfunction testPattern(value: string, pattern: string | RegExp): boolean {\n if (typeof pattern === 'string') {\n let regex = stringPatternCache.get(pattern)\n if (!regex) {\n regex = new RegExp(pattern)\n stringPatternCache.set(pattern, regex)\n }\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/**\n * Checks if an operation matches a pattern for a given filter type (`tag`, `operationId`, `path`, `method`).\n */\nfunction matchesOperationPattern(node: OperationNode, type: string, pattern: string | RegExp): boolean {\n if (type === 'tag') return node.tags.some((tag) => testPattern(tag, pattern))\n if (type === 'operationId') return testPattern(node.operationId, pattern)\n if (type === 'path') return node.path !== undefined && testPattern(node.path, pattern)\n if (type === 'method') return node.method !== undefined && testPattern(node.method.toLowerCase(), pattern)\n if (type === 'contentType') return node.requestBody?.content?.some((c) => testPattern(c.contentType, pattern)) ?? false\n return false\n}\n\n/**\n * Checks if a schema matches a pattern for a given filter type (`schemaName`).\n *\n * Returns `null` when the filter type doesn't apply to schemas.\n */\nfunction matchesSchemaPattern(node: SchemaNode, type: string, pattern: string | RegExp): boolean | null {\n if (type === 'schemaName') return node.name ? testPattern(node.name, pattern) : false\n return null\n}\n\n/**\n * Default name resolver used by `defineResolver`.\n *\n * - `camelCase` for `file`, with dotted names split into `/`-joined nested paths.\n * - `PascalCase` for `type`.\n * - `camelCase` for `function` and everything else.\n */\nfunction defaultResolver(name: string, type?: 'file' | 'function' | 'type' | 'const'): string {\n if (type === 'file') return toFilePath(name)\n if (type === 'type') return pascalCase(name)\n return camelCase(name)\n}\n\n/**\n * Default option resolver. Applies include/exclude filters and merges matching override options.\n *\n * Returns `null` when the node is filtered out by an `exclude` rule or not matched by any `include` rule.\n *\n * @example Include/exclude filtering\n * ```ts\n * const options = defaultResolveOptions(operationNode, {\n * options: { output: 'types' },\n * exclude: [{ type: 'tag', pattern: 'internal' }],\n * })\n * // → null when node has tag 'internal'\n * ```\n *\n * @example Override merging\n * ```ts\n * const options = defaultResolveOptions(operationNode, {\n * options: { enumType: 'asConst' },\n * override: [{ type: 'operationId', pattern: 'listPets', options: { enumType: 'enum' } }],\n * })\n * // → { enumType: 'enum' } when operationId matches\n * ```\n */\nconst resolveOptionsCache = new WeakMap<object, WeakMap<Node, { value: unknown }>>()\n\nfunction computeOptions<TOptions>(\n node: Node,\n options: TOptions,\n exclude: Array<PatternFilter>,\n include: Array<PatternFilter> | undefined,\n override: Array<PatternOverride<TOptions>>,\n): TOptions | null {\n if (operationDef.is(node)) {\n if (exclude.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null\n if (include && !include.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null\n\n const overrideOptions = override.find(({ type, pattern }) => matchesOperationPattern(node, type, pattern))?.options\n\n return { ...options, ...overrideOptions }\n }\n\n if (schemaDef.is(node)) {\n if (exclude.some(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)) return null\n if (include) {\n const results = include.map(({ type, pattern }) => matchesSchemaPattern(node, type, pattern))\n const applicable = results.filter((result) => result !== null)\n\n if (applicable.length > 0 && !applicable.includes(true)) return null\n }\n const overrideOptions = override.find(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)?.options\n\n return { ...options, ...overrideOptions }\n }\n\n return options\n}\n\nfunction defaultResolveOptions<TOptions>(node: Node, { options, exclude = [], include, override = [] }: ResolveOptionsContext<TOptions>): TOptions | null {\n // A plugin's `options` is normally an object, but a re-instantiated plugin (e.g. a\n // Studio/agent merge) can hand back something falsy-but-not-nullish. `WeakMap` only\n // accepts object keys, so cache only when `options` actually qualifies; otherwise fall\n // back to computing directly instead of throwing \"Invalid value used as weak map key\".\n if (typeof options !== 'object' || options === null) {\n return computeOptions(node, options, exclude, include, override)\n }\n\n let byOptions = resolveOptionsCache.get(options)\n if (!byOptions) {\n byOptions = new WeakMap()\n resolveOptionsCache.set(options, byOptions)\n }\n const cached = byOptions.get(node)\n if (cached !== undefined) return cached.value as TOptions | null\n\n const result = computeOptions(node, options, exclude, include, override)\n\n byOptions.set(node, { value: result })\n\n return result\n}\n\n/**\n * Default path resolver used by `defineResolver`.\n *\n * - `mode: 'file'` resolves directly to `output.path` (the full file path, extension included).\n * - `mode: 'directory'` (default) resolves to `output.path/{baseName}`, or into a\n * subdirectory when `group` and a `tag`/`path` value are provided.\n *\n * A custom `group.name` function overrides the default subdirectory naming.\n * For `tag` groups the default is the camelCased tag.\n * For `path` groups the default is the first path segment after `/`.\n *\n * @example Flat output\n * ```ts\n * defaultResolvePath({ baseName: 'petTypes.ts' }, { root: '/src', output: { path: 'types' } })\n * // → '/src/types/petTypes.ts'\n * ```\n *\n * @example Tag-based grouping\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → '/src/types/pets/petTypes.ts'\n * ```\n *\n * @example Path-based grouping\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts', path: '/pets/list' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'path' } },\n * )\n * // → '/src/types/pets/petTypes.ts'\n * ```\n *\n * @example Single file (`mode: 'file'`)\n * ```ts\n * defaultResolvePath(\n * { baseName: 'petTypes.ts' },\n * { root: '/src', output: { path: 'types.ts', mode: 'file' } },\n * )\n * // → '/src/types.ts'\n * ```\n */\nexport function defaultResolvePath({ baseName, tag, path: groupPath }: ResolverPathParams, { root, output, group }: ResolverContext): string {\n const mode = output.mode ?? 'directory'\n\n if (mode === 'file') {\n return path.resolve(root, output.path)\n }\n\n const result: string = (() => {\n if (group && (groupPath || tag)) {\n const groupValue = group.type === 'path' ? groupPath! : tag!\n const defaultName =\n group.type === 'tag'\n ? ({ group: groupName }: { group: string }) => camelCase(groupName)\n : ({ group: groupName }: { group: string }) => {\n // Strip traversal components (empty, '.', '..') before taking the first meaningful segment.\n // When every segment is a traversal component (e.g. '../../') we fall back to '' so the\n // file is placed directly in the output root, and the boundary check below ensures safety.\n const segment = groupName.split('/').filter((part) => part !== '' && part !== '.' && part !== '..')[0]\n return segment ? camelCase(segment) : ''\n }\n const resolveName = group.name ?? defaultName\n const groupName = resolveName({ group: groupValue })\n\n return path.resolve(root, output.path, groupName, baseName)\n }\n return path.resolve(root, output.path, baseName)\n })()\n\n // Ensure the resolved path stays within the configured output directory.\n // This prevents path traversal from malicious OpenAPI specs or custom group.name functions.\n // `result === outputDir` is intentionally permitted: it matches edge cases where baseName\n // resolves to the output directory itself.\n const outputDir = path.resolve(root, output.path)\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 * Default file resolver used by `defineResolver`.\n *\n * Resolves a `FileNode` by combining name resolution (`resolver.default`) with\n * path resolution (`resolver.resolvePath`). The resolved file always has empty\n * `sources`, `imports`, and `exports` arrays, which consumers populate separately.\n *\n * In `mode: 'file'` the name is omitted and the file sits directly at the output path.\n *\n * @example Resolve a schema file\n * ```ts\n * const file = defaultResolveFile.call(\n * resolver,\n * { name: 'pet', extname: '.ts' },\n * { root: '/src', output: { path: 'types' } },\n * )\n * // → { baseName: 'pet.ts', path: '/src/types/pet.ts', sources: [], ... }\n * ```\n *\n * @example Resolve an operation file with tag grouping\n * ```ts\n * const file = defaultResolveFile.call(\n * resolver,\n * { name: 'listPets', extname: '.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }\n * ```\n */\nexport function defaultResolveFile(this: Resolver, { name, extname, tag, path: groupPath }: ResolverFileParams, context: ResolverContext): FileNode {\n const mode = context.output.mode ?? 'directory'\n const resolvedName = mode === 'file' ? '' : this.default(name, 'file')\n const baseName = `${resolvedName}${extname}` as FileNode['baseName']\n const filePath = this.resolvePath({ baseName, tag, path: groupPath }, context)\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 * Generates the default \"Generated by Kubb\" banner from config and optional node metadata.\n */\nfunction buildDefaultBanner({ title, description, version, config }: { title?: string; description?: string; version?: string; config: Config }): string {\n try {\n const source = (() => {\n if (Array.isArray(config.input)) {\n const first = config.input[0]\n if (first && 'path' in first) return path.basename(first.path)\n return ''\n }\n if (config.input && 'path' in config.input) return path.basename(config.input.path)\n if (config.input && 'data' in config.input) return 'text content'\n return ''\n })()\n\n let banner = '/**\\n* Generated by Kubb (https://kubb.dev/).\\n* Do not edit manually.\\n'\n\n if (config.output.defaultBanner === 'simple') {\n banner += '*/\\n'\n return banner\n }\n\n if (source) {\n banner += `* Source: ${source}\\n`\n }\n\n if (title) {\n banner += `* Title: ${title}\\n`\n }\n\n if (description) {\n const formattedDescription = description.replace(/\\n/gm, '\\n* ')\n banner += `* Description: ${formattedDescription}\\n`\n }\n\n if (version) {\n banner += `* OpenAPI spec version: ${version}\\n`\n }\n\n banner += '*/\\n'\n return banner\n } catch (_error) {\n return '/**\\n* Generated by Kubb (https://kubb.dev/).\\n* Do not edit manually.\\n*/'\n }\n}\n\n/**\n * Default banner resolver. Returns the banner string for a generated file.\n *\n * A user-supplied `output.banner` overrides the default Kubb \"Generated by Kubb\" notice.\n * When no `output.banner` is set, the Kubb notice is used (including `title` and `version`\n * from the document metadata when `meta` is provided).\n *\n * - When `output.banner` is a function, calls it with the file's `BannerMeta` and returns the result.\n * - When `output.banner` is a string, returns it directly.\n * - When `config.output.defaultBanner` is `false`, returns `undefined`.\n * - Otherwise returns the Kubb \"Generated by Kubb\" notice.\n *\n * @example String banner overrides default\n * ```ts\n * defaultResolveBanner(undefined, { output: { banner: '// my banner' }, config })\n * // → '// my banner'\n * ```\n *\n * @example Function banner with metadata\n * ```ts\n * defaultResolveBanner(meta, { output: { banner: (m) => `// v${m.version}` }, config })\n * // → '// v3.0.0'\n * ```\n *\n * @example Function banner skips re-export files\n * ```ts\n * defaultResolveBanner(meta, { output: { banner: (m) => (m.isBarrel ? '' : \"'use server'\") }, config, file: { path, baseName, isBarrel: true } })\n * // → ''\n * ```\n *\n * @example No user banner, Kubb notice with OAS metadata\n * ```ts\n * defaultResolveBanner(meta, { config })\n * // → '/** Generated by Kubb ... Title: Pet Store ... *\\/'\n * ```\n *\n * @example Disabled default banner\n * ```ts\n * defaultResolveBanner(undefined, { config: { output: { defaultBanner: false }, ...config } })\n * // → null\n * ```\n */\nexport function defaultResolveBanner(meta: InputMeta | undefined, { output, config, file }: ResolveBannerContext): string | null {\n if (typeof output?.banner === 'function') {\n return output.banner(buildBannerMeta({ meta, file }))\n }\n\n if (typeof output?.banner === 'string') {\n return output.banner\n }\n\n if (config.output.defaultBanner === false) {\n return null\n }\n\n return buildDefaultBanner({\n title: meta?.title,\n version: meta?.version,\n config,\n })\n}\n\n/**\n * Default footer resolver. Returns the footer string for a generated file.\n *\n * - When `output.footer` is a function, calls it with the file's `BannerMeta` and returns the result.\n * - When `output.footer` is a string, returns it directly.\n * - Otherwise returns `undefined`.\n *\n * @example String footer\n * ```ts\n * defaultResolveFooter(undefined, { output: { footer: '// end of file' }, config })\n * // → '// end of file'\n * ```\n *\n * @example Function footer with metadata\n * ```ts\n * defaultResolveFooter(meta, { output: { footer: (m) => `// ${m.title}` }, config })\n * // → '// Pet Store'\n * ```\n */\nexport function defaultResolveFooter(meta: InputMeta | undefined, { output, file }: ResolveBannerContext): string | null {\n if (typeof output?.footer === 'function') {\n return output.footer(buildBannerMeta({ meta, file }))\n }\n if (typeof output?.footer === 'string') {\n return output.footer\n }\n return null\n}\n\n/**\n * Defines a plugin resolver. The resolver is the object that decides what\n * every generated symbol and file path is called. Built-in defaults handle\n * name casing, include/exclude/override filtering, output path computation,\n * and file construction. Supply your own to override any of them:\n *\n * - `default` sets the name casing strategy (camelCase or PascalCase).\n * - `resolveOptions` does include/exclude/override filtering.\n * - `resolvePath` computes the output path.\n * - `resolveFile` builds the full `FileNode`.\n * - `resolveBanner` and `resolveFooter` produce the top and bottom of file text.\n *\n * Methods in the returned object can call sibling resolver methods via `this`.\n * A custom rule can delegate to a default, for example `this.default(name, 'type')`.\n *\n * @example Basic resolver with naming helpers\n * ```ts\n * export const resolverTs = defineResolver<PluginTs>(() => ({\n * name: 'default',\n * resolveName(name) {\n * return this.default(name, 'function')\n * },\n * resolveTypeName(name) {\n * return this.default(name, 'type')\n * },\n * }))\n * ```\n *\n * @example Custom output path\n * ```ts\n * import path from 'node:path'\n *\n * export const resolverTs = defineResolver<PluginTs>(() => ({\n * name: 'custom',\n * resolvePath({ baseName }, { root, output }) {\n * return path.resolve(root, output.path, 'generated', baseName)\n * },\n * }))\n * ```\n */\nexport function defineResolver<T extends PluginFactoryOptions>(build: ResolverBuilder<T>): T['resolver'] {\n // `resolver` is kept so the default `resolveFile` wrapper can reference the fully assembled\n // object via `.call(resolver, ...)` at call-time, after the result is assigned below.\n let resolver: T['resolver']\n\n const result = {\n default: defaultResolver,\n resolveOptions: defaultResolveOptions,\n resolvePath: defaultResolvePath,\n resolveFile: (params: ResolverFileParams, context: ResolverContext) => defaultResolveFile.call(resolver as Resolver, params, context),\n resolveBanner: defaultResolveBanner,\n resolveFooter: defaultResolveFooter,\n ...build(),\n } as T['resolver']\n\n resolver = result\n\n return 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 * Number of plugins with at least one registered macro.\n */\n get size(): number {\n return this.#macros.size\n }\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 * Looks up the composed visitor for `pluginName`, or `undefined` when the plugin has no macros.\n */\n get(pluginName: string): Visitor | undefined {\n return this.#visitorFor(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 { arrayToAsyncIterable, type AsyncEventEmitter, getElapsedMs, isPromise, memoize } from '@internals/utils'\nimport { ast, collectUsedSchemaNames, type Enforce, type FileNode, type InputMeta, type InputNode, type OperationNode, type SchemaNode } from '@kubb/ast'\nimport { GENERATE_FLUSH_EVERY, OPERATION_FILTER_TYPES } from './constants.ts'\nimport { type Diagnostic, Diagnostics, type ProblemDiagnostic } from './diagnostics.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { Storage } from './createStorage.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 { defineResolver } from './defineResolver.ts'\nimport { FileManager } from './FileManager.ts'\nimport { FileProcessor } from './FileProcessor.ts'\nimport { Transform } from './Transform.ts'\n\nimport type {\n Adapter,\n AdapterSource,\n Config,\n GeneratorContext,\n Group,\n KubbHooks,\n KubbPluginSetupContext,\n NormalizedPlugin,\n PluginFactoryOptions,\n Resolver,\n} from './types.ts'\n\ntype Options = {\n hooks: AsyncEventEmitter<KubbHooks>\n}\n\ntype HookListener<TArgs extends Array<unknown>, TResult = void> = (...args: TArgs) => TResult | Promise<TResult>\n\ntype ListenerEntry = [event: keyof KubbHooks & string, handler: HookListener<Array<unknown>, unknown>]\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\nfunction enforceOrder(enforce: Enforce | undefined): number {\n return enforce === 'pre' ? -1 : enforce === 'post' ? 1 : 0\n}\n\nexport class KubbDriver {\n readonly config: Config\n readonly options: Options\n\n /**\n * The streaming `InputNode<true>` produced by the adapter. Set after adapter setup.\n * Parse-only adapters are wrapped automatically.\n */\n inputNode: InputNode<true> | null = null\n adapter: Adapter | null = null\n /**\n * Raw adapter source so `adapter.parse()` / `adapter.stream()` 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()` (event-based path).\n * Used by the build loop to decide whether to emit generator events for a given plugin.\n */\n readonly #eventGeneratorPlugins = new Set<string>()\n readonly #resolvers = new Map<string, Resolver>()\n readonly #defaultResolvers = new Map<string, Resolver>()\n\n /**\n * Tracks every listener the driver added (plugin, generator) so `dispose()` can remove them\n * in one pass. External `hooks.on(...)` listeners are not tracked.\n */\n readonly #listeners: Array<ListenerEntry> = []\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 * Attaches a listener to the shared emitter and tracks it so `dispose()` can remove it later.\n * Listeners attached directly via `hooks.on(...)` are not tracked and survive disposal.\n */\n #trackListener<K extends keyof KubbHooks & string>(event: K, handler: HookListener<KubbHooks[K], unknown>): void {\n this.hooks.on(event, handler as HookListener<KubbHooks[K]>)\n this.#listeners.push([event, handler as HookListener<Array<unknown>, unknown>])\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: Array<NormalizedPlugin> = this.config.plugins.map((rawPlugin) => this.#normalizePlugin(rawPlugin as Plugin))\n\n const dependenciesByName = new Map(normalized.map((plugin) => [plugin.name, new Set(plugin.dependencies ?? [])]))\n\n normalized.sort((a, b) => {\n if (dependenciesByName.get(b.name)?.has(a.name)) return -1\n if (dependenciesByName.get(a.name)?.has(b.name)) return 1\n\n return enforceOrder(a.enforce) - enforceOrder(b.enforce)\n })\n\n for (const plugin of normalized) {\n if (plugin.apply) {\n plugin.apply(this.config)\n }\n\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 get hooks() {\n return this.options.hooks\n }\n\n /**\n * Builds a `NormalizedPlugin` from a hook-style plugin, filling in default\n * options and copying `apply` when present. Registering its lifecycle handlers\n * on the `AsyncEventEmitter` is done separately by `#registerPlugin`.\n */\n #normalizePlugin(plugin: Plugin): NormalizedPlugin {\n const normalized: NormalizedPlugin = {\n name: plugin.name,\n dependencies: plugin.dependencies,\n enforce: plugin.enforce,\n hooks: plugin.hooks,\n options: plugin.options ?? { output: { path: '.', mode: 'directory' }, exclude: [], override: [] },\n } as NormalizedPlugin\n\n if ('apply' in plugin && typeof plugin.apply === 'function') {\n normalized.apply = plugin.apply as (config: Config) => boolean\n }\n\n return normalized\n }\n\n /**\n * Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from\n * `run` do not re-parse. Adapters with `stream()` are used directly.\n * Adapters with only `parse()` are wrapped via `ast.factory.createInput({ stream: true })` so the dispatch loop\n * stays stream-only.\n */\n async #parseInput(): Promise<void> {\n if (this.inputNode || !this.adapter || !this.#adapterSource) return\n\n const adapter = this.adapter\n const source = this.#adapterSource\n\n if (adapter.stream) {\n this.inputNode = await adapter.stream(source)\n return\n }\n\n const parsed = await adapter.parse(source)\n this.inputNode = ast.factory.createInput({\n stream: true,\n schemas: arrayToAsyncIterable(parsed.schemas),\n operations: arrayToAsyncIterable(parsed.operations),\n meta: parsed.meta,\n })\n }\n\n /**\n * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.\n *\n * The `kubb:plugin:setup` listener wraps the global context in a plugin-specific one so\n * `addGenerator`, `setResolver`, and `setMacros` target the right `normalizedPlugin`.\n * Every other `KubbHooks` event registers as a pass-through listener that external tooling\n * can observe via `hooks.on(...)`.\n *\n * @internal\n */\n #registerPlugin(plugin: NormalizedPlugin): void {\n const { hooks } = plugin\n\n if (!hooks) return\n\n // kubb:plugin:setup gets special treatment: the globally emitted context is wrapped with\n // plugin-specific implementations so that addGenerator / setResolver / etc. target\n // this plugin's normalizedPlugin entry rather than being no-ops.\n if (hooks['kubb:plugin:setup']) {\n const setupHandler = (globalCtx: KubbPluginSetupContext) => {\n const pluginCtx: KubbPluginSetupContext = {\n ...globalCtx,\n options: plugin.options ?? {},\n addGenerator: (...generators) => {\n for (const generator of generators.flat()) {\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 return hooks['kubb:plugin:setup']!(pluginCtx)\n }\n\n this.#trackListener('kubb:plugin:setup', setupHandler)\n }\n\n // All other hooks are registered as direct pass-through listeners on the shared emitter.\n for (const event of Object.keys(hooks) as Array<keyof KubbHooks & string>) {\n if (event === 'kubb:plugin:setup') continue\n const handler = hooks[event]\n if (!handler) continue\n\n this.#trackListener(event, handler as HookListener<KubbHooks[typeof event], unknown>)\n }\n }\n\n /**\n * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners\n * can configure generators, resolvers, macros and renderers before `buildStart` runs.\n *\n * Called once from `run` before the plugin execution loop begins.\n */\n async emitSetupHooks(): Promise<void> {\n const noop = () => {}\n\n await this.hooks.emit('kubb:plugin:setup', {\n config: this.config,\n options: {},\n addGenerator: noop,\n setResolver: noop,\n addMacro: noop,\n setMacros: noop,\n setOptions: noop,\n injectFile: noop,\n updateConfig: noop,\n })\n }\n\n /**\n * Registers a generator for the given plugin on the shared event 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 const register = <TNode>(event: keyof KubbHooks & string, method: ((node: TNode, ctx: GeneratorContext) => unknown) | undefined): void => {\n if (!method) return\n\n const handler = async (node: TNode, ctx: GeneratorContext) => {\n if (ctx.plugin.name !== pluginName) return\n const result = await method(node, ctx)\n await this.dispatch({ result, renderer: generator.renderer })\n }\n\n this.#trackListener(event, handler as HookListener<KubbHooks[typeof event], unknown>)\n }\n\n register('kubb:generate:schema', generator.schema)\n register('kubb:generate:operation', generator.operation)\n register('kubb:generate:operations', generator.operations)\n\n this.#eventGeneratorPlugins.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` (event-based path).\n *\n * Used by the build loop to decide whether to walk the AST and emit generator events\n * for a plugin that has no static `plugin.generators`.\n */\n hasEventGenerators(pluginName: string): boolean {\n return this.#eventGeneratorPlugins.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({ storage }: { storage: Storage }): Promise<{ diagnostics: Array<Diagnostic> }> {\n const { hooks, config } = 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 const processor = new FileProcessor({ parsers: parsersMap, storage, extension: config.output.extension })\n // Bridge processor lifecycle to the user-facing kubb hooks so existing listeners on\n // kubb:files:processing:* keep firing.\n processor.hooks.on('start', async (files) => {\n await hooks.emit('kubb:files:processing:start', { files })\n })\n const updateBuffer: Array<{ file: FileNode; source?: string; processed: number; total: number; percentage: number }> = []\n processor.hooks.on('update', (item) => {\n updateBuffer.push(item)\n })\n processor.hooks.on('end', async (files) => {\n await hooks.emit('kubb:files:processing:update', {\n files: updateBuffer.map((item) => ({ ...item, config })),\n })\n updateBuffer.length = 0\n await hooks.emit('kubb:files:processing:end', { files })\n })\n const onFileUpsert = (file: FileNode): void => {\n processor.enqueue(file)\n }\n this.fileManager.hooks.on('upsert', onFileUpsert)\n\n // Make `diagnostics` the active sink so deep code (adapter parse, lazily consumed\n // streams, generators) can 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 the streaming `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.emitSetupHooks()\n\n if (this.adapter && this.inputNode) {\n await hooks.emit(\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.emit('kubb:plugin:start', { plugin })\n } catch (caughtError) {\n const error = caughtError as Error\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.hasEventGenerators(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 // Stream every node through the transform registry and into each plugin's generators.\n // When there are no entries it returns early. When `inputNode` is missing it still\n // closes out each entry's `kubb:plugin:end` directly.\n diagnostics.push(...(await this.#runGenerators(generatorPlugins, () => processor.flush())))\n // Wait for the last in-flight batch and write anything still pending.\n await processor.drain()\n\n await hooks.emit('kubb:plugins:end', Object.assign({ config }, this.#filesPayload()))\n\n // Plugins-end listeners (barrel plugin etc.) may have queued more files.\n await processor.drain()\n\n await hooks.emit('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 this.fileManager.hooks.off('upsert', onFileUpsert)\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.emit(\n 'kubb:plugin:end',\n Object.assign({ plugin, duration, success, ...(error ? { error } : {}), config: this.config }, this.#filesPayload()),\n )\n }\n\n /**\n * Streams 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 * because the two passes share `flushPending` and the FileProcessor's event emitter.\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 run sequentially so `kubb:plugin:end` fires as each plugin completes, instead\n * of all at once after every plugin has marched through the parallel batches together.\n * That ordering is what drives the CLI's `Plugins N/M` counter. Without it the bar would\n * sit at the initial value until the very end of the run.\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 flushPending: () => Promise<void>,\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 type PluginState = {\n plugin: NormalizedPlugin\n generatorContext: Omit<GeneratorContext, 'options'>\n generators: Array<Generator>\n hrStart: ReturnType<typeof process.hrtime>\n failed: boolean\n error: Error | null\n optionsAreStatic: boolean\n allowedSchemaNames: Set<string> | null\n }\n\n const states: Array<PluginState> = entries.map(({ plugin, context, hrStart }) => {\n const { exclude, include, override } = plugin.options\n const hasExclude = Array.isArray(exclude) && exclude.length > 0\n const hasInclude = Array.isArray(include) && include.length > 0\n const hasOverride = Array.isArray(override) && override.length > 0\n return {\n plugin,\n generatorContext: { ...context, resolver: this.getResolver(plugin.name) },\n generators: plugin.generators ?? [],\n hrStart,\n failed: false,\n error: null,\n optionsAreStatic: !hasExclude && !hasInclude && !hasOverride,\n allowedSchemaNames: null,\n }\n })\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 // Buffer the streaming adapter's nodes once. Each plugin reads the same buffer\n // instead of re-parsing the document per pass, and the pruning pre-scan below\n // shares it too (previously it iterated its own copies).\n const schemasBuffer: Array<SchemaNode> = await Array.fromAsync(schemas)\n const operationsBuffer: Array<OperationNode> = await Array.fromAsync(operations)\n\n // Pre-scan: plugins with operation-based includes (but no schemaName include) need\n // the reachable schema set. This requires the full schema graph in memory at once,\n // since transitive reachability can't be derived from a single node.\n const pruningStates = states.filter(({ plugin }) => {\n const { include } = plugin.options\n return (include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === 'schemaName') ?? false)\n })\n\n if (pruningStates.length > 0) {\n const includedOpsByState = new Map<PluginState, Array<OperationNode>>(pruningStates.map((state) => [state, []]))\n for (const operation of operationsBuffer) {\n for (const state of pruningStates) {\n const { exclude, include, override } = state.plugin.options\n const options = state.generatorContext.resolver.resolveOptions(operation, { options: state.plugin.options, exclude, include, override })\n if (options !== null) includedOpsByState.get(state)?.push(operation)\n }\n }\n\n for (const state of pruningStates) {\n state.allowedSchemaNames = collectUsedSchemaNames(includedOpsByState.get(state) ?? [], schemasBuffer)\n includedOpsByState.delete(state)\n }\n }\n\n // Apply the plugin's macros, then resolve 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 a plugin sees.\n const resolveForPlugin = <TNode extends SchemaNode | OperationNode>(\n state: PluginState,\n node: TNode,\n ): { transformedNode: TNode; options: NormalizedPlugin['options'] } | null => {\n const { plugin, generatorContext } = state\n const transformedNode = transforms.applyTo(plugin.name, node)\n if (state.optionsAreStatic) return { transformedNode, options: plugin.options }\n\n const { exclude, include, override } = plugin.options\n const options = generatorContext.resolver.resolveOptions(transformedNode, { options: plugin.options, exclude, include, override })\n if (options === null) return null\n return { transformedNode, options }\n }\n\n // One generation pass: which generator method runs, which kubb:generate hook fires, and\n // whether the schema-only allowedSchemaNames prune applies.\n type NodeDispatch<TNode extends SchemaNode | OperationNode> = {\n method: 'schema' | 'operation'\n checkAllowedNames: boolean\n emit: ((node: TNode, ctx: GeneratorContext) => Promise<void> | void) | null\n }\n\n // Schemas and operations share this body, differing only in the dispatch descriptor.\n const dispatchNode = async <TNode extends SchemaNode | OperationNode>(state: PluginState, node: TNode, dispatch: NodeDispatch<TNode>): Promise<void> => {\n if (state.failed) return\n try {\n const resolved = resolveForPlugin(state, node)\n if (!resolved) return\n\n const { transformedNode, options } = resolved\n if (\n dispatch.checkAllowedNames &&\n state.allowedSchemaNames !== null &&\n 'name' in transformedNode &&\n transformedNode.name &&\n !state.allowedSchemaNames.has(transformedNode.name)\n ) {\n return\n }\n\n const ctx = { ...state.generatorContext, options }\n for (const gen of state.generators) {\n const run = gen[dispatch.method] as ((node: TNode, ctx: GeneratorContext) => unknown) | undefined\n if (!run) continue\n const raw = run(transformedNode, ctx)\n const result = isPromise(raw) ? await raw : raw\n const applied = this.dispatch({ result, renderer: gen.renderer })\n if (isPromise(applied)) await applied\n }\n if (dispatch.emit) await dispatch.emit(transformedNode, ctx)\n } catch (caughtError) {\n state.failed = true\n state.error = caughtError as Error\n }\n }\n\n const schemaDispatch = {\n method: 'schema',\n checkAllowedNames: true,\n emit: emitsSchemaHook ? (node: SchemaNode, ctx: GeneratorContext) => this.hooks.emit('kubb:generate:schema', node, ctx) : null,\n } as const\n const operationDispatch = {\n method: 'operation',\n checkAllowedNames: false,\n emit: emitsOperationHook ? (node: OperationNode, ctx: GeneratorContext) => this.hooks.emit('kubb:generate:operation', node, ctx) : null,\n } as const\n\n // Walk nodes in order, flushing queued writes every GENERATE_FLUSH_EVERY nodes so writes\n // reach disk while later nodes are still generating. The generators are synchronous, so\n // batching them through Promise.all never overlapped anything a sequential walk doesn't.\n const dispatchPass = async <TNode extends SchemaNode | OperationNode>(\n state: PluginState,\n nodes: ReadonlyArray<TNode>,\n dispatch: NodeDispatch<TNode>,\n ): Promise<void> => {\n let sinceFlush = 0\n for (const node of nodes) {\n await dispatchNode(state, node, dispatch)\n if (++sinceFlush >= GENERATE_FLUSH_EVERY) {\n sinceFlush = 0\n await flushPending()\n }\n }\n if (sinceFlush > 0) await flushPending()\n }\n\n for (const state of states) {\n // Only plugins with a gen.operations (or a kubb:generate:operations listener) need the\n // aggregated pass below.\n const needsOperationsAggregate = emitsOperationsHook || state.generators.some((gen) => !!gen.operations)\n\n // Run schemas before operations: the two passes share the flush and the FileProcessor's\n // event emitter, so interleaving them would race on the shared dirty list.\n await dispatchPass(state, schemasBuffer, schemaDispatch)\n await dispatchPass(state, operationsBuffer, operationDispatch)\n\n if (!state.failed && needsOperationsAggregate) {\n try {\n const { plugin, generatorContext, generators } = state\n const ctx = { ...generatorContext, options: plugin.options }\n // Match what the per-node dispatch passed to gen.operation(): each operation\n // transformed and filtered by this plugin's excludes/includes/overrides.\n const pluginOperations = operationsBuffer.reduce<Array<OperationNode>>((acc, node) => {\n const resolved = resolveForPlugin(state, node)\n if (resolved) acc.push(resolved.transformedNode)\n return acc\n }, [])\n for (const gen of generators) {\n if (!gen.operations) continue\n const result = await gen.operations(pluginOperations, ctx)\n await this.dispatch({ result, renderer: gen.renderer })\n }\n await this.hooks.emit('kubb:generate:operations', pluginOperations, ctx)\n } catch (caughtError) {\n state.failed = true\n state.error = caughtError as Error\n }\n }\n\n const duration = getElapsedMs(state.hrStart)\n await this.#emitPluginEnd({ plugin: state.plugin, duration, success: !state.failed, error: state.failed && state.error ? state.error : undefined })\n\n if (state.failed && state.error) {\n diagnostics.push({ ...Diagnostics.from(state.error), plugin: state.plugin.name })\n }\n diagnostics.push(Diagnostics.performance({ plugin: state.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 if (instance.stream) {\n for (const file of instance.stream(result)) {\n this.fileManager.upsert(file)\n }\n return\n }\n\n await instance.render(result)\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 [event, handler] of this.#listeners) {\n this.hooks.off(event, handler as HookListener<KubbHooks[typeof event]>)\n }\n this.#listeners.length = 0\n this.#eventGeneratorPlugins.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(\n this.#defaultResolvers,\n (pluginName: string): Resolver => defineResolver<PluginFactoryOptions>(() => ({ name: 'default', pluginName })),\n )\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: Partial<Resolver>): void {\n const defaultResolver = this.#getDefaultResolver(pluginName)\n const merged = { ...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: dynamic resolver set via `setPluginResolver` → static resolver on the\n * plugin → lazily created default 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.plugins.get(pluginName)?.resolver ?? 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.plugins.get(pluginName)\n if (!plugin) {\n const requiredBy = context?.requiredBy\n throw new Diagnostics.Error({\n code: Diagnostics.code.pluginNotFound,\n severity: 'error',\n message: requiredBy\n ? `Plugin \"${pluginName}\" is required by \"${requiredBy}\" but not found. Make sure it is included in your Kubb config.`\n : `Plugin \"${pluginName}\" is required but not found. Make sure it is included in your Kubb config.`,\n help: requiredBy\n ? `Add \"${pluginName}\" to the \\`plugins\\` array in kubb.config.ts (required by \"${requiredBy}\"), or remove the dependency on it.`\n : `Add \"${pluginName}\" to the \\`plugins\\` array in kubb.config.ts, or remove the dependency on it.`,\n location: { kind: 'config' },\n })\n }\n return plugin\n }\n}\n\nfunction inputToAdapterSource(config: Config): AdapterSource {\n const input = config.input\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: 'Provide `input.path` (a file or URL) or `input.data` (an inline spec) in your Kubb config.',\n location: { kind: 'config' },\n })\n }\n\n if ('data' in input) {\n return { type: 'data', data: input.data }\n }\n\n if (URL.canParse(input.path)) {\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","import { access, glob, readFile, rm } from 'node:fs/promises'\nimport { join, relative, resolve } from 'node:path'\nimport { clean, runtime, toPosixPath, write } from '@internals/utils'\nimport { createStorage } from '../createStorage.ts'\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 *\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 resolvedBase = resolve(base ?? process.cwd())\n\n if (runtime.isBun) {\n const bunGlob = new Bun.Glob('**/*')\n return Array.fromAsync(bunGlob.scan({ cwd: resolvedBase, onlyFiles: true, dot: true }))\n }\n\n const keys: Array<string> = []\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","import { resolve } from 'node:path'\nimport { AsyncEventEmitter, BuildError } from '@internals/utils'\nimport { HOOK_LISTENERS_PER_PLUGIN } from './constants.ts'\nimport { Diagnostics } from './diagnostics.ts'\nimport { createStorage, 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'\n\n/**\n * Builds a `Storage` view scoped to the file paths produced by the current build.\n * Reads delegate to the underlying `storage` so source bytes stay where they were\n * written. Writes register the key so subsequent reads and `getKeys` are scoped\n * to this build's output.\n */\nfunction createSourcesView(storage: Storage): Storage {\n const paths = new Set<string>()\n\n return createStorage(() => ({\n name: `${storage.name}:sources`,\n async hasItem(key: string) {\n return paths.has(key) && (await storage.hasItem(key))\n },\n async getItem(key: string) {\n return paths.has(key) ? storage.getItem(key) : null\n },\n async setItem(key: string, value: string) {\n paths.add(key)\n await storage.setItem(key, value)\n },\n async removeItem(key: string) {\n paths.delete(key)\n await storage.removeItem(key)\n },\n async getKeys(base?: string) {\n if (!base) return [...paths]\n const result: Array<string> = []\n for (const key of paths) {\n if (key.startsWith(base)) result.push(key)\n }\n return result\n },\n async clear() {\n paths.clear()\n await storage.clear()\n },\n }))()\n}\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 extension: { '.ts': '.ts' },\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?: AsyncEventEmitter<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 event listeners to `.hooks` before calling `setup()` or `build()`.\n *\n * @example\n * ```ts\n * const kubb = createKubb(userConfig)\n * kubb.hooks.on('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: AsyncEventEmitter<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 AsyncEventEmitter<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 const storage = createSourcesView(config.storage)\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 = 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 cleanup = this\n const driver = cleanup.driver\n const storage = cleanup.storage\n const { diagnostics } = await driver.run({ storage })\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: { path: './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 event 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}\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 events 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 drain = reporter.drain\n if (!drain) {\n return {\n name: reporter.name,\n async report(result, context) {\n await reporter.report(result, context)\n },\n }\n }\n\n const reports: Array<T> = []\n\n return {\n name: reporter.name,\n async report(result, context) {\n reports.push(await reporter.report(result, context))\n },\n async drain(context) {\n await drain(context, reports)\n reports.length = 0\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` event 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 * Not populated when {@link stream} is implemented.\n */\n readonly files: Array<FileNode>\n /**\n * When present, core calls this instead of {@link render} and {@link files},\n * forwarding each file to `FileManager` as soon as it is ready.\n */\n stream?(element: TElement): Iterable<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 { AsyncEventEmitter, 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 './defineResolver.ts'\nimport type { Config } from './types.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 event bus. Emit or listen to any `KubbHooks` event, for example to react to\n * `kubb:build:end` from inside a generator.\n */\n hooks: AsyncEventEmitter<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 type name\n * `ctx.resolver.default('pet', 'type') // 'Pet'`\n *\n * @example Resolve an output file\n * `ctx.resolver.resolveFile({ 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\ntype PrintOptions = {\n extname?: FileNode['extname']\n}\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>, options?: PrintOptions): 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 * Defines a parser with type-safe `this`. Used to register handlers for new\n * file extensions or to plug a non-TypeScript output into the build.\n *\n * @example\n * ```ts\n * import { defineParser } from '@kubb/core'\n * import { extractStringsFromNodes } from '@kubb/ast'\n *\n * export const jsonParser = defineParser({\n * name: 'json',\n * extNames: ['.json'],\n * parse(file) {\n * return file.sources\n * .map((source) => extractStringsFromNodes(source.nodes ?? []))\n * .join('\\n')\n * },\n * print(...nodes) {\n * return nodes.map(String).join('\\n')\n * },\n * })\n * ```\n */\nexport function defineParser<T extends Parser>(parser: T): T {\n return parser\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAgB,aAAa,SAAmC;CAC9D,MAAM,CAAC,SAAS,eAAe,QAAQ,OAAO,OAAO;CACrD,MAAM,KAAK,UAAU,MAAO,cAAc;CAC1C,OAAO,KAAK,MAAM,KAAK,GAAG,IAAI;AAChC;;;;;;;;;;;AAYA,SAAgB,SAAS,IAAoB;CAC3C,IAAI,MAAM,KAGR,OAAO,GAFM,KAAK,MAAM,KAAK,GAEhB,EAAE,KADA,KAAK,MAAS,IAAA,CAAM,QAAQ,CACrB,EAAE;CAG1B,IAAI,MAAM,KACR,OAAO,IAAI,KAAK,IAAA,CAAM,QAAQ,CAAC,EAAE;CAEnC,OAAO,G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AO,OAAO,CAAC,CAAC,KAAK,GAAG,EAAE;EAChF,MAAM,YAAA,GAAA,UAAA,QAAA,CAAmBC,aAAAA,QAAQ,IAAI,GAAG,SAAS,QAAQ;EAEzD,MAAMC,sBAAAA,MAAM,UAAU,GAAG,QAAQ,GAAG;EACpC,QAAQ,MAAM,yBAAA,GAAA,UAAA,SAAA,CAAiCD,aAAAA,QAAQ,IAAI,GAAG,QAAQ,GAAG;CAC3E;AACF,CAAC;;;;;;;;;;AC1FD,MAAa,eAAe,eAAe;CACzC,MAAM;CACN,OAAO,QAAQ;EACb,OAAO,YAAY,MAAM;CAC3B;CACA,MAAM,UAAU,SAAS;EACvB,aAAA,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,SAAS,MAAM,CAAC,EAAE,GAAG;CAC9D;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACkDD,SAAgB,eAAmC,SAA+D;CAChH,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuIA,SAAgB,gBACd,WAC+B;CAC/B,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;ACtJA,SAAgB,aAA+B,QAAc;CAC3D,OAAO;AACT"}
1
+ {"version":3,"file":"index.cjs","names":["#reporterStorage","AsyncLocalStorage","getErrorMessage","#patternCache","#optionsCache","#options","#apply","camelCase","#resolveOptions","#resolvePath","#resolveFile","#resolveBanner","#resolveFooter","#testPattern","#matchesOperation","#matchesSchema","#computeOptions","operationDef","schemaDef","#resolveGroupDir","path","toFilePath","ast","#buildBannerMeta","#resolveUserText","#buildDefaultBanner","#macros","#composed","#memo","#invalidate","#visitorFor","FileManager","#eventGeneratorPlugins","#resolvers","#defaultResolvers","#listeners","#transforms","#normalizePlugin","#registerPlugin","#adapterSource","#parseInput","ast","#trackListener","#filesPayload","#emitPluginEnd","#runGenerators","#getDefaultResolver","write","toPosixPath","clean","AsyncEventEmitter","#storage","#driver","BuildError","logLevel","logLevelMap","process","write"],"sources":["../src/createAdapter.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/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: { path: './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","/**\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 event (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 `input.path` file or URL 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 shell hook (`hooks.done`) exited with a failure.\n */\n hookFailed: 'KUBB_HOOK_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 { AsyncEventEmitter } from './asyncEventEmitter.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 * Maps each {@link DiagnosticCode} to the variant it selects, for {@link narrow}.\n * Every {@link ProblemCode} selects a {@link ProblemDiagnostic}, and the two bookkeeping codes\n * select their own variant.\n */\nexport type DiagnosticByCode = Record<ProblemCode, ProblemDiagnostic> &\n Record<typeof diagnosticCode.performance, PerformanceDiagnostic> &\n Record<typeof diagnosticCode.updateAvailable, UpdateDiagnostic>\n\n/**\n * Narrows a {@link Diagnostic} to the variant for `code`, or `null` when it does not match.\n *\n * @example\n * ```ts\n * const update = narrow(diagnostic, diagnosticCode.updateAvailable)\n * if (update) {\n * console.log(update.latestVersion)\n * }\n * ```\n */\nfunction narrow<C extends DiagnosticCode>(diagnostic: Diagnostic, code: C): DiagnosticByCode[C] | null {\n return diagnostic.code === code ? (diagnostic as DiagnosticByCode[C]) : null\n}\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 in `input.path` (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 in `input.path` 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.path` (a file or URL) or `input.data` (an inline spec) 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.hookFailed]: {\n title: 'Hook failed',\n cause: 'A post-generate shell hook (`hooks.done`) 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 * Narrows a {@link Diagnostic} to the variant for `code`, or `null` when it does not match.\n */\n static narrow = narrow\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` event so the loggers render it live.\n * Use it instead of calling `hooks.emit('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: AsyncEventEmitter<KubbHooks>, diagnostic: ProblemDiagnostic | UpdateDiagnostic): Promise<void> {\n await hooks.emit('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 event 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, ResolverOverride } from './createResolver.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: ResolverOverride): 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 * Merge a partial config update into the current build configuration.\n */\n updateConfig(config: Partial<Config>): 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 event handlers for this plugin.\n * Any event 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 apply?: (config: Config) => boolean\n version?: string\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 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 type { Filter, Override, PluginFactoryOptions } 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(params: ResolverPathParams, context: ResolverContext): string\n file(params: ResolverFileParams, context: ResolverContext): FileNode\n banner(meta: InputMeta | undefined, context: ResolveBannerContext): string | null\n footer(meta: InputMeta | undefined, context: ResolveBannerContext): string | null\n}\n\n/**\n * File-specific parameters for `resolver.default.path`.\n * Provide `tag` for tag-based grouping or `path` for path-based grouping.\n *\n * @example\n * ```ts\n * resolver.default.path(\n * { baseName: 'petTypes.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → '/src/types/pets/petTypes.ts'\n * ```\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 * Shared context passed as the second argument to `resolver.default.path` and\n * `resolver.default.file`: where output is rooted, which output config is active,\n * and the optional grouping strategy.\n */\nexport type ResolverContext = {\n root: string\n output: Output\n group?: Group\n}\n\n/**\n * File-specific parameters for `resolver.default.file`.\n * `tag` and `path` are used only when a matching `group` is present in the context.\n *\n * @example\n * ```ts\n * resolver.default.file(\n * { name: 'listPets', extname: '.ts', tag: 'pets' },\n * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },\n * )\n * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }\n * ```\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 * Casing applied to `name` to build the file base name. A plugin's `file` override\n * threads its own caser here to change file naming without reimplementing the builder.\n *\n * @default toFilePath\n */\n resolveName?: (name: string) => string\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 */\ntype ResolverBuildOptions = {\n pluginName: string\n name?: (name: string) => string\n file?: (params: ResolverFileParams, context: ResolverContext) => FileNode\n [key: string]: unknown\n}\n\n/**\n * Partial resolver fields accepted by `Resolver.merge` and `setResolver`.\n */\nexport type ResolverOverride = Omit<ResolverBuildOptions, 'pluginName'>\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?: T['resolver']['file']\n} & ThisType<T['resolver']>\n\nfunction isNamespace(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\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\n constructor(options: ResolverBuildOptions) {\n this.pluginName = options.pluginName\n this.#options = options\n this.#apply(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(params: ResolverFileParams, context: ResolverContext): FileNode {\n return this.default.file(params, context)\n }\n\n /**\n * Merges `override` over `base` and returns a new resolver with helpers re-bound.\n * Each key is replaced wholesale. Used when applying `setResolver` partial overrides.\n */\n static merge<T extends Resolver>(base: T, override: ResolverOverride | Resolver): T {\n const patch = override instanceof Resolver ? override.#options : override\n return createResolver({ ...base.#options, ...patch }) 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 if (key === 'pluginName' || key === 'default' || 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 }: ResolverPathParams, { root, output, group }: ResolverContext): 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 * Builds a `FileNode` by combining file-name casing (`params.resolveName`) with path\n * resolution. The resolved file starts with empty `sources`, `imports`, and `exports`,\n * which consumers populate separately.\n */\n #resolveFile({ name, extname, tag, path: groupPath, resolveName = toFilePath }: ResolverFileParams, context: ResolverContext): FileNode {\n const resolvedName = context.output.mode === 'file' ? '' : resolveName(name)\n const filePath = this.#resolvePath({ baseName: `${resolvedName}${extname}` as FileNode['baseName'], tag, path: groupPath }, context)\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 = Array.isArray(config.input) ? config.input[0] : config.input\n const source = input && 'path' in input ? path.basename(input.path) : input && 'data' in input ? 'text content' : ''\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\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 and file casing\n * ```ts\n * export const resolverTs = createResolver<PluginTs>({\n * pluginName: 'plugin-ts',\n * name(name) {\n * return ensureValidVarName(pascalCase(name))\n * },\n * file(params, context) {\n * return this.default.file({ ...params, resolveName: (name) => toFilePath(name, pascalCase) }, context)\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 } 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 { Storage } from './createStorage.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 type { ResolverOverride } from './createResolver.ts'\nimport { createResolver, Resolver } from './createResolver.ts'\nimport { FileManager } from './FileManager.ts'\nimport { Transform } from './Transform.ts'\n\nimport type {\n Adapter,\n AdapterSource,\n Config,\n GeneratorContext,\n Group,\n KubbHooks,\n KubbPluginSetupContext,\n NormalizedPlugin,\n PluginFactoryOptions,\n} from './types.ts'\nimport type { AsyncEventEmitter } from './asyncEventEmitter.ts'\n\ntype Options = {\n hooks: AsyncEventEmitter<KubbHooks>\n}\n\ntype HookListener<TArgs extends Array<unknown>, TResult = void> = (...args: TArgs) => TResult | Promise<TResult>\n\ntype ListenerEntry = [event: keyof KubbHooks & string, handler: HookListener<Array<unknown>, unknown>]\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\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 */\nfunction sortPlugins(plugins: Array<NormalizedPlugin>): Array<NormalizedPlugin> {\n const queue = [...plugins].sort((a, b) => (a.enforce ? ENFORCE_ORDER[a.enforce] : 0) - (b.enforce ? ENFORCE_ORDER[b.enforce] : 0))\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 const sorted: Array<NormalizedPlugin> = []\n while (queue.length > 0) {\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 const [plugin] = queue.splice(index, 1)\n if (!plugin) break\n sorted.push(plugin)\n for (const blockers of blockedBy.values()) {\n blockers.delete(plugin.name)\n }\n }\n return sorted\n}\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()` (event-based path).\n * Used by the build loop to decide whether to emit generator events for a given plugin.\n */\n readonly #eventGeneratorPlugins = new Set<string>()\n readonly #resolvers = new Map<string, Resolver>()\n readonly #defaultResolvers = new Map<string, Resolver>()\n\n /**\n * Tracks every listener the driver added (plugin, generator) so `dispose()` can remove them\n * in one pass. External `hooks.on(...)` listeners are not tracked.\n */\n readonly #listeners: Array<ListenerEntry> = []\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 * Attaches a listener to the shared emitter and tracks it so `dispose()` can remove it later.\n * Listeners attached directly via `hooks.on(...)` are not tracked and survive disposal.\n */\n #trackListener<K extends keyof KubbHooks & string>(event: K, handler: HookListener<KubbHooks[K], unknown>): void {\n this.hooks.on(event, handler as HookListener<KubbHooks[K]>)\n this.#listeners.push([event, handler as HookListener<Array<unknown>, unknown>])\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 = sortPlugins(this.config.plugins.map((rawPlugin) => this.#normalizePlugin(rawPlugin as Plugin)))\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 get hooks() {\n return this.options.hooks\n }\n\n /**\n * Builds a `NormalizedPlugin` from a hook-style plugin, filling in default\n * options. Registering its lifecycle handlers on the `AsyncEventEmitter` is\n * done separately by `#registerPlugin`.\n */\n #normalizePlugin(plugin: Plugin): NormalizedPlugin {\n return {\n name: plugin.name,\n dependencies: plugin.dependencies,\n enforce: plugin.enforce,\n hooks: plugin.hooks,\n options: plugin.options ?? { output: { path: '.', mode: 'directory' }, exclude: [], override: [] },\n } as NormalizedPlugin\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 hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.\n *\n * The `kubb:plugin:setup` listener wraps the global context in a plugin-specific one so\n * `addGenerator`, `setResolver`, and `setMacros` target the right `normalizedPlugin`.\n * Every other `KubbHooks` event registers as a pass-through listener that external tooling\n * can observe via `hooks.on(...)`.\n *\n * @internal\n */\n #registerPlugin(plugin: NormalizedPlugin): void {\n const { hooks } = plugin\n\n if (!hooks) return\n\n // kubb:plugin:setup gets special treatment: the globally emitted context is wrapped with\n // plugin-specific implementations so that addGenerator / setResolver / etc. target\n // this plugin's normalizedPlugin entry rather than being no-ops.\n if (hooks['kubb:plugin:setup']) {\n const setupHandler = (globalCtx: KubbPluginSetupContext) => {\n const pluginCtx: KubbPluginSetupContext = {\n ...globalCtx,\n options: plugin.options ?? {},\n addGenerator: (...generators) => {\n for (const generator of generators.flat()) {\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 return hooks['kubb:plugin:setup']!(pluginCtx)\n }\n\n this.#trackListener('kubb:plugin:setup', setupHandler)\n }\n\n // All other hooks are registered as direct pass-through listeners on the shared emitter.\n for (const event of Object.keys(hooks) as Array<keyof KubbHooks & string>) {\n if (event === 'kubb:plugin:setup') continue\n const handler = hooks[event]\n if (!handler) continue\n\n this.#trackListener(event, handler as HookListener<KubbHooks[typeof event], unknown>)\n }\n }\n\n /**\n * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners\n * can configure generators, resolvers, macros and renderers before `buildStart` runs.\n *\n * Called once from `run` before the plugin execution loop begins.\n */\n async emitSetupHooks(): Promise<void> {\n const noop = () => {}\n\n await this.hooks.emit('kubb:plugin:setup', {\n config: this.config,\n options: {},\n addGenerator: noop,\n setResolver: noop,\n addMacro: noop,\n setMacros: noop,\n setOptions: noop,\n injectFile: noop,\n updateConfig: noop,\n })\n }\n\n /**\n * Registers a generator for the given plugin on the shared event 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 const register = <TNode>(event: keyof KubbHooks & string, method: ((node: TNode, ctx: GeneratorContext) => unknown) | undefined): void => {\n if (!method) return\n\n const handler = async (node: TNode, ctx: GeneratorContext) => {\n if (ctx.plugin.name !== pluginName) return\n const result = await method(node, ctx)\n await this.dispatch({ result, renderer: generator.renderer })\n }\n\n this.#trackListener(event, handler as HookListener<KubbHooks[typeof event], unknown>)\n }\n\n register('kubb:generate:schema', generator.schema)\n register('kubb:generate:operation', generator.operation)\n register('kubb:generate:operations', generator.operations)\n\n this.#eventGeneratorPlugins.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 events\n * for a plugin.\n */\n hasEventGenerators(pluginName: string): boolean {\n return this.#eventGeneratorPlugins.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({ storage }: { storage: Storage }): 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 #trackListener) 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.emit('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.emit('kubb:files:processing:update', {\n files: updateBuffer.map((item) => ({ ...item, config })),\n })\n updateBuffer.length = 0\n await hooks.emit('kubb:files:processing:end', { files })\n }\n fileManager.hooks.on('start', onWriteStart)\n fileManager.hooks.on('update', onWriteUpdate)\n fileManager.hooks.on('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.emitSetupHooks()\n\n if (this.adapter && this.inputNode) {\n await hooks.emit(\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.emit('kubb:plugin:start', { plugin })\n } catch (caughtError) {\n const error = caughtError as Error\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.hasEventGenerators(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.emit('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, parsers: parsersMap, extension: config.output.extension })\n\n await hooks.emit('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 fileManager.hooks.off('start', onWriteStart)\n fileManager.hooks.off('update', onWriteUpdate)\n fileManager.hooks.off('end', onWriteEnd)\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.emit(\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.emit('kubb:generate:schema', transformedNode, { ...generatorContext, options })\n } catch (caughtError) {\n error = caughtError as Error\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.emit('kubb:generate:operation', resolved.transformedNode, { ...generatorContext, options: resolved.options })\n } catch (caughtError) {\n error = caughtError as Error\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.emit('kubb:generate:operations', pluginOperations, ctx)\n } catch (caughtError) {\n error = caughtError as Error\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 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 [event, handler] of this.#listeners) {\n this.hooks.off(event, handler as HookListener<KubbHooks[typeof event]>)\n }\n this.#listeners.length = 0\n this.#eventGeneratorPlugins.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: ResolverOverride): 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.plugins.get(pluginName)\n if (!plugin) {\n const requiredBy = context?.requiredBy\n throw new Diagnostics.Error({\n code: Diagnostics.code.pluginNotFound,\n severity: 'error',\n message: requiredBy\n ? `Plugin \"${pluginName}\" is required by \"${requiredBy}\" but not found. Make sure it is included in your Kubb config.`\n : `Plugin \"${pluginName}\" is required but not found. Make sure it is included in your Kubb config.`,\n help: requiredBy\n ? `Add \"${pluginName}\" to the \\`plugins\\` array in kubb.config.ts (required by \"${requiredBy}\"), or remove the dependency on it.`\n : `Add \"${pluginName}\" to the \\`plugins\\` array in kubb.config.ts, or remove the dependency on it.`,\n location: { kind: 'config' },\n })\n }\n return plugin\n }\n}\n\nfunction inputToAdapterSource(config: Config): AdapterSource {\n const input = config.input\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: 'Provide `input.path` (a file or URL) or `input.data` (an inline spec) in your Kubb config.',\n location: { kind: 'config' },\n })\n }\n\n if ('data' in input) {\n return { type: 'data', data: input.data }\n }\n\n if (URL.canParse(input.path)) {\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","/**\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 * Optional teardown hook for a backend to flush buffers, close connections,\n * or release file locks.\n */\n dispose?(): 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: { path: './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 { AsyncEventEmitter } from './asyncEventEmitter.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 extension: { '.ts': '.ts' },\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?: AsyncEventEmitter<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 event listeners to `.hooks` before calling `setup()` or `build()`.\n *\n * @example\n * ```ts\n * const kubb = createKubb(userConfig)\n * kubb.hooks.on('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: AsyncEventEmitter<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 AsyncEventEmitter<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 cleanup = this\n const driver = cleanup.driver\n const storage = cleanup.storage\n const { diagnostics } = await driver.run({ storage })\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: { path: './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 event 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 events 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` event 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 './createResolver.ts'\nimport type { Config } from './types.ts'\nimport type { AsyncEventEmitter } from './asyncEventEmitter.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 event bus. Emit or listen to any `KubbHooks` event, for example to react to\n * `kubb:build:end` from inside a generator.\n */\n hooks: AsyncEventEmitter<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\ntype PrintOptions = {\n extname?: FileNode['extname']\n}\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>, options?: PrintOptions): 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 * Defines a parser with type-safe `this`. Used to register handlers for new\n * file extensions or to plug a non-TypeScript output into the build.\n *\n * @example\n * ```ts\n * import { defineParser } from '@kubb/core'\n * import { extractStringsFromNodes } from '@kubb/ast'\n *\n * export const jsonParser = defineParser({\n * name: 'json',\n * extNames: ['.json'],\n * parse(file) {\n * return file.sources\n * .map((source) => extractStringsFromNodes(source.nodes ?? []))\n * .join('\\n')\n * },\n * print(...nodes) {\n * return nodes.map(String).join('\\n')\n * },\n * })\n * ```\n */\nexport function defineParser<T extends Parser>(parser: T): T {\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoHA,SAAgB,cAAuE,OAAkE;CACvJ,QAAQ,YAAY,MAAM,WAAY,CAAC,CAAkB;AAC3D;;;;;;;;;;;;;;AC3GA,SAAgB,aAAa,SAAmC;CAC9D,MAAM,CAAC,SAAS,eAAe,QAAQ,OAAO,OAAO;CACrD,MAAM,KAAK,UAAU,MAAO,cAAc;CAC1C,OAAO,KAAK,MAAM,KAAK,GAAG,IAAI;AAChC;;;;;;;;;;;AAYA,SAAgB,SAAS,IAAoB;CAC3C,IAAI,MAAM,KAGR,OAAO,GAFM,KAAK,MAAM,KAAK,GAEhB,EAAE,KADA,KAAK,MAAS,IAAA,CAAM,QAAQ,CACrB,EAAE;CAG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