@kubb/core 5.12.2 → 5.12.3

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":["process","process","readFile","resolve","writeFile","mkdir","dirname","globNode","relative","join","isAbsolute","x","styleText","stripVTControlCharacters","AsyncLocalStorage","kubbVersion","satisfies","AsyncLocalStorage","path","net","net","dns","x","mkdtemp","join","tmpdir","rm","resolve","relative","sep","isAbsolute","process","resolve","path","collectImportedRefNames","ast","extractStringsFromNodes","readFile","ast","ast","resolve","collectUsedSchemaNames","hash","resolve","rm","join","existsSync","tmpdir","hash","process","randomUUID","x","styleText","existsSync","resolve","resolve","styleText","relative","isAbsolute","styleText","logLevel","logLevelMap","resolve","process","join","homedir","tmpdir","hash","createUnstorage","fsDriver","stripVTControlCharacters","resolve","process","relative","join","resolve","fileURLToPath","join","relative","isValid","readFile","createRequire","path","require","existsSync"],"sources":["../package.json","../../../internals/utils/src/casing.ts","../../../internals/utils/src/errors.ts","../../../internals/utils/src/isCIEnvironment.ts","../../../internals/utils/src/jsonPointer.ts","../../../internals/utils/src/openInBrowser.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/promise.ts","../../../internals/utils/src/tools.ts","../../../internals/utils/src/time.ts","../src/diagnosticCatalog.ts","../src/formatDiagnostic.ts","../src/Diagnostics.ts","../src/defineExtension.ts","../src/createAdapter.ts","../src/composables.ts","../src/definePlugin.ts","../src/publicAddress.ts","../src/gitInput.ts","../src/input.ts","../src/Resolver.ts","../src/createResolver.ts","../src/FileManager.ts","../src/nodeCache.ts","../src/KubbDriver.ts","../src/outputManifest.ts","../src/createStorage.ts","../src/storages/fsStorage.ts","../src/storages/cacheStorage.ts","../src/Hookable.ts","../src/output/runHook.ts","../src/output/runOutputPasses.ts","../src/createKubb.ts","../src/createReporter.ts","../src/reporters/report.ts","../src/reporters/summary.ts","../src/reporters/cliReporter.ts","../src/storages/kubbStorage.ts","../src/reporters/fileReporter.ts","../src/reporters/jsonReporter.ts","../src/reporters/htmlReporter.ts","../src/createRenderer.ts","../src/defineGenerator.ts","../src/defineParser.ts","../src/storages/memoryStorage.ts","../src/manifest.ts","../src/installedPackages.ts"],"sourcesContent":["","type Options = {\n /**\n * Text prepended before casing is applied.\n */\n prefix?: string\n /**\n * Text appended before casing is applied.\n */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n return text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n .split(/[\\s\\-_./\\\\:]+/)\n .filter(Boolean)\n .map((word, i) => {\n if (word.length > 1 && word === word.toUpperCase()) return word\n const head = i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()\n return head + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Converts `text` to camelCase.\n *\n * @example Word boundaries\n * `camelCase('hello-world') // 'helloWorld'`\n *\n * @example With a prefix\n * `camelCase('tag', { prefix: 'create' }) // 'createTag'`\n */\nexport function camelCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n *\n * @example Word boundaries\n * `pascalCase('hello-world') // 'HelloWorld'`\n *\n * @example With a suffix\n * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`\n */\nexport function pascalCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n","/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new Error('Build failed', { cause: toError(err) })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Returns `error` followed by every error in its `cause` chain, outermost first. Stops at a\n * non-`Error` cause or a cycle.\n *\n * @example\n * ```ts\n * getErrorChain(new Error('Config failed loading', { cause: new Error('boom') })).map((error) => error.message)\n * // ['Config failed loading', 'boom']\n * ```\n */\nexport function getErrorChain(error: unknown): Array<Error> {\n const chain: Array<Error> = []\n for (let current = error; current instanceof Error && !chain.includes(current); current = current.cause) {\n chain.push(current)\n }\n return chain\n}\n","import process from 'node:process'\n\n/**\n * Returns `true` when a known CI provider has set its environment variable.\n * `CI=false` and `CI=0` count as not CI, so a user can opt out locally.\n */\nexport function isCIEnvironment(): boolean {\n const ci = process.env.CI\n return !!(\n (ci && ci !== 'false' && ci !== '0') ||\n process.env.GITHUB_ACTIONS ||\n process.env.GITLAB_CI ||\n process.env.BITBUCKET_BUILD_NUMBER ||\n process.env.JENKINS_URL ||\n process.env.CIRCLECI ||\n process.env.TRAVIS ||\n process.env.TEAMCITY_VERSION ||\n process.env.BUILDKITE ||\n process.env.TF_BUILD\n )\n}\n","/**\n * Escapes a single JSON pointer reference token per RFC 6901 (`~` → `~0`, `/` → `~1`), so a\n * name holding those characters maps to a distinct pointer.\n *\n * @example\n * ```ts\n * escapePointerToken('/pets/{id}') // '~1pets~1{id}'\n * ```\n */\nexport function escapePointerToken(token: string): string {\n return token.replaceAll('~', '~0').replaceAll('/', '~1')\n}\n","import process from 'node:process'\nimport { x } from 'tinyexec'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\n\nconst ignore = () => {}\n\n/**\n * Opens a URL or local file in the default browser, unless running in CI.\n */\nexport function openInBrowser(target: string): void {\n if (isCIEnvironment()) return\n\n if (process.platform === 'win32') {\n x('cmd', ['/c', 'start', '', target]).then(ignore, ignore)\n return\n }\n x(process.platform === 'darwin' ? 'open' : 'xdg-open', [target]).then(ignore, ignore)\n}\n","// Bun polyfills `process.versions.node`, so detection keys off the globals instead.\nconst isBun = typeof Bun !== 'undefined'\nconst isDeno = 'Deno' in globalThis\n\n/**\n * The JavaScript runtime executing the current process: its name, version and whether it is Bun.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\nexport const runtime = { isBun, ...detect() } as const\n\nfunction detect(): { name: 'bun' | 'deno' | 'node'; version: string } {\n if (isBun) return { name: 'bun', version: process.versions.bun ?? '' }\n if (isDeno) return { name: 'deno', version: (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? '' }\n return { name: 'node', version: process.versions?.node ?? '' }\n}\n","import { access, glob as globNode, mkdir, readFile, writeFile } from 'node:fs/promises'\n\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\nexport { existsSync } from 'node:fs'\nexport { mkdir, mkdtemp, rm } from 'node:fs/promises'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n await writeRaw(resolved, content)\n\n if (options.sanity) {\n const savedData = await read(resolved)\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Writes UTF-8 content verbatim, including empty files and surrounding whitespace.\n * Uses Bun.write under Bun and creates missing parent directories under either runtime.\n *\n * @example\n * await writeRaw('./cache/output.ts', ' // keep these bytes\\n\\n')\n */\nexport async function writeRaw(path: string, content: string): Promise<void> {\n const resolved = resolve(path)\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return\n }\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n}\n\n/**\n * Lists non-hidden regular files below `directory` as relative POSIX paths, excluding directories and symlinks.\n * Uses Bun.Glob under Bun because its Node glob compatibility API lacks directory-entry support.\n *\n * @example\n * for await (const path of listFiles('./src')) console.log(path)\n */\nexport async function* listFiles(directory: string): AsyncGenerator<string> {\n const cwd = resolve(directory)\n if (runtime.isBun) {\n yield* new Bun.Glob('**/*').scan({ cwd, dot: false, onlyFiles: true, followSymlinks: false })\n return\n }\n for await (const entry of globNode('**/*', { cwd, withFileTypes: true })) {\n if (entry.isFile()) yield toPosixPath(relative(cwd, join(entry.parentPath, entry.name)))\n }\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\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\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 ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { x } from 'tinyexec'\n\n/**\n * How one formatter or linter is invoked: the executable, the argv it takes for an output\n * directory, and what to report when it is not installed.\n */\nexport type ToolCommand = {\n command: string\n args: (outputPath: string) => Array<string>\n errorMessage: string\n}\n\n/**\n * CLI command descriptors for each supported code formatter.\n */\nexport const formatters = {\n prettier: {\n command: 'prettier',\n args: (outputPath: string) => ['--ignore-unknown', '--write', outputPath],\n errorMessage: 'Prettier not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['format', '--write', outputPath],\n errorMessage: 'Biome not found',\n },\n oxfmt: {\n command: 'oxfmt',\n args: (outputPath: string) => [outputPath],\n errorMessage: 'Oxfmt not found',\n },\n} as const satisfies Record<string, ToolCommand>\n\n/**\n * CLI command descriptors for each supported linter.\n */\nexport const linters = {\n eslint: {\n command: 'eslint',\n args: (outputPath: string) => [outputPath, '--fix'],\n errorMessage: 'Eslint not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['lint', '--fix', outputPath],\n errorMessage: 'Biome not found',\n },\n oxlint: {\n command: 'oxlint',\n // --no-ignore so oxlint lints the folder even when it's gitignored (generated output dirs usually are).\n args: (outputPath: string) => ['--fix', '--no-ignore', outputPath],\n errorMessage: 'Oxlint not found',\n },\n} as const satisfies Record<string, ToolCommand>\n\n/**\n * Preference order for `format: 'auto'`, most-preferred first. Spelled out rather than taken from\n * the table's key order, which is arbitrary and would silently change what `auto` picks.\n */\nexport const FORMATTER_PREFERENCE = ['oxfmt', 'biome', 'prettier'] as const\n\n/**\n * Preference order for `lint: 'auto'`, most-preferred first.\n */\nexport const LINTER_PREFERENCE = ['oxlint', 'biome', 'eslint'] as const\n\n/**\n * Whether `name` is on PATH or in a `node_modules/.bin` above `cwd` and answers `--version` with a zero exit.\n */\nasync function isToolAvailable(name: string, cwd?: string): Promise<boolean> {\n return x(name, ['--version'], { throwOnError: false, nodeOptions: { cwd, stdio: 'ignore' } }).then(\n ({ exitCode }) => exitCode === 0,\n () => false,\n )\n}\n\n/**\n * Returns the first installed executable from `candidates`, or `null` when none are found.\n *\n * Not memoized: a long-running host that probes repeatedly should cache the result itself, and a\n * `--watch` build should keep noticing a tool installed mid-session.\n */\nexport async function detectTool<TName extends string>(candidates: ReadonlyArray<TName>, cwd?: string): Promise<TName | null> {\n for (const candidate of candidates) {\n if (await isToolAvailable(candidate, cwd)) {\n return candidate\n }\n }\n\n return null\n}\n\n/**\n * Tokenizes a shell command string, respecting single and double quotes.\n *\n * @example\n * ```ts\n * tokenize('git commit -m \"initial commit\"')\n * // → ['git', 'commit', '-m', 'initial commit']\n * ```\n */\nexport function tokenize(command: string): Array<string> {\n return (command.match(/[^\\s\"']+|\"([^\"]*)\"|'([^']*)'/g) ?? []).map((token) => token.replace(/^[\"']|[\"']$/g, ''))\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n","/**\n * Every diagnostic code with its docs entry: a short title, what triggers it, and how to resolve\n * it. The source of truth for {@link diagnosticCode}, and the kubb.dev `/reference/diagnostics`\n * sections mirror it.\n */\nexport const diagnosticCatalog = {\n unknown: {\n code: 'KUBB_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 inputNotFound: {\n code: 'KUBB_INPUT_NOT_FOUND',\n title: 'Input not found',\n cause:\n 'The file set as `input` (or passed as `kubb generate PATH`) could not be read. A URL reports `KUBB_INPUT_REQUEST_FAILED` or `KUBB_INPUT_UNREACHABLE` instead.',\n fix: 'Check that the path exists and is readable, then set it as `input` or pass it on the CLI.',\n },\n inputRequestFailed: {\n code: 'KUBB_INPUT_REQUEST_FAILED',\n title: 'Input request failed',\n cause: 'A URL set as `input` (or reached through a `$ref`) answered with a 4xx or 5xx status instead of the document.',\n fix: 'Open the URL to see what the server returns. A 401 or 403 needs credentials Kubb does not send, so download the document and point `input` at the local file. A 404 means the path is wrong, and a 5xx means the server itself failed.',\n },\n inputUnreachable: {\n code: 'KUBB_INPUT_UNREACHABLE',\n title: 'Input unreachable',\n cause:\n 'A URL set as `input` (or reached through a `$ref`) never answered, so the request failed before a status came back. A refused connection, an unknown host, an expired certificate, and a timeout all land here.',\n fix: 'Check that the host is running and reachable from this machine. For a local server, start it and confirm the port matches the one in `input`.',\n },\n gitInputFailed: {\n code: 'KUBB_GIT_INPUT_FAILED',\n title: 'Git input failed',\n cause:\n 'A git `input` (`git+<repo>#<ref>:<path>`) is malformed, or `git` could not fetch it: git is not installed, the repository or ref does not exist, or the credentials were refused.',\n fix: 'Write the input as `git+<repo>#<ref>:<path>`. Run `git fetch --depth 1 <repo> <ref>` yourself to see the git error, and set up a credential helper or SSH key for a private repository.',\n },\n inputRequired: {\n code: 'KUBB_INPUT_REQUIRED',\n title: 'Input required',\n cause: 'An adapter is configured but no `input` was provided.',\n fix: 'Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.',\n },\n legacyInput: {\n code: 'KUBB_LEGACY_INPUT',\n title: 'Legacy input shape',\n cause: '`input` is a `{ path }` or `{ data }` wrapper, which v4 used to point at a document and v5 reads as the document itself.',\n fix: 'Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`.',\n },\n invalidDocument: {\n code: 'KUBB_INVALID_DOCUMENT',\n title: 'Invalid document',\n cause:\n 'The `input` cannot be read as an OpenAPI or Swagger document: its JSON or YAML has a syntax error, it declares no `openapi` or `swagger` version field, or its version cannot be upgraded to OpenAPI 3.1.',\n fix: 'Fix the syntax at the reported line, and check that `input` points at the spec and not an HTML page. Point `input` at a Swagger 2.0, OpenAPI 3.0, or OpenAPI 3.1 document, and check that a passed object is the spec itself rather than a wrapper around it.',\n },\n invalidSpec: {\n code: 'KUBB_INVALID_SPEC',\n title: 'Invalid spec',\n cause: 'The document does not pass OpenAPI schema validation. Kubb still generates from it, but the output can be incomplete or wrong.',\n fix: 'Fix the reported problem in the spec. Run `kubb validate` to list every error, or set `validate: false` on the adapter to skip the check.',\n },\n refNotFound: {\n code: 'KUBB_REF_NOT_FOUND',\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 invalidServerVariable: {\n code: 'KUBB_INVALID_SERVER_VARIABLE',\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 pluginNotFound: {\n code: 'KUBB_PLUGIN_NOT_FOUND',\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 incompatibleExtension: {\n code: 'KUBB_INCOMPATIBLE_EXTENSION',\n title: 'Incompatible extension',\n cause: 'A plugin sets `meta.compatibility.kubb` or `meta.compatibility.node` to a range the running Kubb or Node.js version does not satisfy.',\n fix: 'Upgrade Kubb or Node.js to a version in the range, or install a version of the plugin that supports your current Kubb and Node.js.',\n },\n missingDependency: {\n code: 'KUBB_MISSING_DEPENDENCY',\n title: 'Missing dependency',\n cause: 'A plugin lists another plugin in its `dependencies` record without `optional: true`, and the config does not include it.',\n fix: 'Add the missing plugin to the `plugins` array in kubb.config.ts.',\n },\n incompatibleDependency: {\n code: 'KUBB_INCOMPATIBLE_DEPENDENCY',\n title: 'Incompatible dependency',\n cause: \"A plugin's `dependencies` record sets a `version` range, and the configured plugin's `meta.version` falls outside it.\",\n fix: 'Install a version of the dependency inside the range, or a version of the dependent plugin that supports the installed dependency.',\n },\n pluginFailed: {\n code: 'KUBB_PLUGIN_FAILED',\n title: 'Plugin failed',\n cause: 'A plugin threw while generating, or reported an error through `ctx.error`.',\n fix: 'Check the plugin options and the node at `at:`. If it is a bug, report it with the stack at `report:`.',\n },\n adapterFailed: {\n code: 'KUBB_ADAPTER_FAILED',\n title: 'Adapter failed',\n cause: 'The adapter threw an unexpected error while parsing the input.',\n fix: 'Check the input and the adapter options. If it is a bug, report it with the stack at `report:`.',\n },\n parserFailed: {\n code: 'KUBB_PARSER_FAILED',\n title: 'Parser failed',\n cause: 'A parser threw an unexpected error while printing a generated file.',\n fix: 'Check the parser options. If it is a bug, report it with the stack at `report:`.',\n },\n pluginWarning: {\n code: 'KUBB_PLUGIN_WARNING',\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 pluginInfo: {\n code: 'KUBB_PLUGIN_INFO',\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 noContext: {\n code: 'KUBB_NO_CONTEXT',\n title: 'No plugin context',\n cause:\n 'A `kubb/kit` composable such as `useKubb()` or `addGenerator()` ran outside the `setup` and `kubb:plugin:setup` of a plugin, so there is no plugin to apply it to.',\n fix: 'Call the composable inside `setup` or `kubb:plugin:setup`, including in code that setup awaits.',\n },\n unsupportedFormat: {\n code: 'KUBB_UNSUPPORTED_FORMAT',\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 deprecated: {\n code: 'KUBB_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 adapterRequired: {\n code: 'KUBB_ADAPTER_REQUIRED',\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 pathTraversal: {\n code: 'KUBB_PATH_TRAVERSAL',\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 cleanRoot: {\n code: 'KUBB_CLEAN_ROOT',\n title: 'Clean targets the project root',\n cause:\n '`output.clean` is enabled and `output.path` resolves to the project root or a parent of it, so cleaning would delete `kubb.config` and every source file.',\n fix: 'Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code, or disable `output.clean`.',\n },\n invalidPluginOptions: {\n code: 'KUBB_INVALID_PLUGIN_OPTIONS',\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 postGenerateFailed: {\n code: 'KUBB_POST_GENERATE_FAILED',\n title: 'Post-generate command failed',\n cause: 'A post-generate command (`output.postGenerate`) exited with a non-zero status.',\n fix: 'Check the command is installed and correct, and run it manually to see the error.',\n },\n formatFailed: {\n code: 'KUBB_FORMAT_FAILED',\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 lintFailed: {\n code: 'KUBB_LINT_FAILED',\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 barrelDuplicateExport: {\n code: 'KUBB_BARREL_DUPLICATE_EXPORT',\n title: 'Duplicate barrel export',\n cause: 'Two generated modules export the same name, so the barrel cannot re-export both.',\n fix: 'Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names.',\n },\n internalError: {\n code: 'KUBB_INTERNAL_ERROR',\n title: 'Internal error',\n cause: 'Kubb hit a state it does not expect. This is a bug in Kubb, not in your config.',\n fix: 'Rerun with `--reporter json` or `--verbose` to get the stack. Then report it at https://github.com/kubb-labs/kubb/issues with the spec and config that trigger it.',\n },\n performance: {\n code: 'KUBB_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 updateAvailable: {\n code: 'KUBB_UPDATE_AVAILABLE',\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} as const satisfies Record<string, { code: `KUBB_${string}`; title: string; cause: string; fix: string }>\n\n/**\n * Stable codes Kubb attaches to a `Diagnostic`, derived from {@link diagnosticCatalog}. Reference\n * these instead of inlining the string at a throw site.\n */\nexport const diagnosticCode = Object.fromEntries(Object.entries(diagnosticCatalog).map(([key, { code }]) => [key, code])) as {\n readonly [K in keyof typeof diagnosticCatalog]: (typeof diagnosticCatalog)[K]['code']\n}\n\n/**\n * Union of the stable {@link diagnosticCode} values.\n */\nexport type DiagnosticCode = (typeof diagnosticCode)[keyof typeof diagnosticCode]\n","import { stripVTControlCharacters, styleText } from 'node:util'\nimport { getErrorChain } from '@internals/utils'\nimport { type DiagnosticCode, diagnosticCode } from './diagnosticCatalog.ts'\nimport { type Diagnostic, type DiagnosticLocation, Diagnostics, type DiagnosticSeverity, type ProblemDiagnostic } from './Diagnostics.ts'\n\n/** A problem's `help`, or the catalog fix. `info` gets none: its catalog fix says no action is needed. */\nfunction getHelp(problem: ProblemDiagnostic): string | undefined {\n if (problem.help || problem.severity === 'info') return problem.help\n return Diagnostics.explain(problem.code).fix\n}\n\n/** The `cause` chain's messages, outermost first, minus those `message` already contains. */\nfunction getCauses(problem: ProblemDiagnostic): Array<string> {\n return getErrorChain(problem.cause)\n .filter((error) => !problem.message.includes(error.message))\n .map((error) => (error.name === 'Error' ? error.message : `${error.name}: ${error.message}`))\n}\n\n/**\n * Accent color per severity, which paints the icon in the `human` layout (red error, yellow\n * warning, blue info). The code itself stays dim.\n */\nconst severityStyle: Record<DiagnosticSeverity, 'red' | 'yellow' | 'blue'> = {\n error: 'red',\n warning: 'yellow',\n info: 'blue',\n}\n\nconst severityIcon: Record<DiagnosticSeverity, string> = {\n error: '✖',\n warning: '⚠',\n info: 'ℹ',\n}\n\n/**\n * How {@link format} renders a diagnostic.\n */\nexport type DiagnosticFormatOptions = {\n /**\n * Who reads the output.\n * - `'agent'` spells out every detail on labeled rows\n * - `'human'` keeps it short and links to the docs\n * @default 'agent'\n */\n audience?: 'agent' | 'human'\n /**\n * Show the root cause's full stack.\n */\n verbose?: boolean\n /**\n * Columns the `human` headline fills, so the code lines up at the right edge.\n * @default 0\n */\n width?: number\n /**\n * Where the diagnostic's pointer sits in the input file, when the host resolved it. Replaces the\n * pointer on the `at` row, and an error's `human` layout draws `frame` under it.\n */\n position?: { file: string; line: number; column: number; frame?: Array<string> }\n}\n\n/**\n * Codes for a crash, which carry the root cause's stack.\n */\nexport const crashCodes: ReadonlySet<DiagnosticCode> = new Set([\n diagnosticCode.unknown,\n diagnosticCode.internalError,\n diagnosticCode.pluginFailed,\n diagnosticCode.adapterFailed,\n diagnosticCode.parserFailed,\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). Replaces the\n * non-serializable `cause` with its message chain and drops the `kind`/`duration` bookkeeping.\n */\nexport type SerializedDiagnostic = {\n code: DiagnosticCode\n severity: DiagnosticSeverity\n message: string\n /**\n * Catalog title.\n */\n title?: string\n /**\n * Catalog cause.\n */\n cause?: string\n location?: DiagnosticLocation\n /**\n * The diagnostic's `help`, or the catalog fix.\n */\n help?: string\n plugin?: string\n issues?: string\n /**\n * Messages of the underlying errors, outermost first.\n */\n causes?: Array<string>\n /**\n * Root cause's stack, for `KUBB_UNKNOWN`, `KUBB_INTERNAL_ERROR`, and `*_FAILED` codes.\n */\n stack?: string\n /**\n * The kubb.dev docs link for the code, omitted for the unknown fallback.\n */\n docsUrl?: string\n}\n\n/**\n * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable\n * consumers, with the catalog `title`, `cause`, and fix, and the `cause` error as `causes` and\n * `stack`. Absent optional fields are omitted.\n */\nexport function serialize(diagnostic: Diagnostic): SerializedDiagnostic {\n const problem = Diagnostics.isProblem(diagnostic) ? diagnostic : undefined\n const doc = problem ? Diagnostics.explain(problem.code) : undefined\n const help = problem ? getHelp(problem) : undefined\n const causes = problem ? getCauses(problem) : []\n const stack = problem && crashCodes.has(problem.code) ? getErrorChain(problem.cause).at(-1)?.stack : undefined\n return {\n code: diagnostic.code,\n severity: diagnostic.severity,\n message: diagnostic.message,\n ...(doc ? { title: doc.title, cause: doc.cause } : {}),\n ...(problem?.location ? { location: problem.location } : {}),\n ...(help ? { help } : {}),\n ...(problem?.plugin ? { plugin: problem.plugin } : {}),\n ...(problem?.issues ? { issues: problem.issues } : {}),\n ...(causes.length ? { causes } : {}),\n ...(stack ? { stack } : {}),\n ...(diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }),\n }\n}\n\n/**\n * Renders a {@link Diagnostic} as lines: a headline, then indented detail rows. `agent` (the default)\n * prints uncolored labeled rows (`at:`, `why:`, `fix:`, `caused by:`, `stack:` for a crash,\n * `docs:`, `report:`). `human` prints an icon, the bold message, and the code aligned to `width`,\n * with `at`, `fix`, the first cause, and `Learn more` for an error, and one row for a warning.\n * `verbose` adds the full stack.\n */\nexport function format(diagnostic: Diagnostic, { audience = 'agent', verbose = false, width = 0, position }: DiagnosticFormatOptions = {}): Array<string> {\n const { code, severity, message } = diagnostic\n const problem = Diagnostics.isProblem(diagnostic) ? diagnostic : undefined\n const human = audience === 'human'\n const paint: typeof styleText = human ? styleText : (_format, text) => text\n\n const [firstLine = '', ...rest] = message.split('\\n')\n const pointer = problem?.location && 'pointer' in problem.location ? problem.location.pointer : undefined\n const at = position ? `${position.file}:${position.line}:${position.column}` : undefined\n const where = at ?? pointer\n const help = problem ? getHelp(problem) : undefined\n const causes = problem ? getCauses(problem) : []\n const crash = problem ? crashCodes.has(problem.code) : false\n const stack = problem && (verbose || (!human && crash)) ? getErrorChain(problem.cause).at(-1)?.stack : undefined\n const frames = stack\n ?.split('\\n')\n .slice(1, verbose ? undefined : 4)\n .map((frame) => ` ${paint('dim', frame.trim())}`)\n\n if (!human) {\n const details = rest.filter((line) => line.trim()).map((line) => ` ${line}`)\n const row = (label: string, value: string | undefined) => {\n if (value) details.push(` ${label}: ${value}`)\n }\n row('at', at && pointer ? `${at} (${pointer})` : pointer)\n if (problem && severity !== 'info') row('why', Diagnostics.explain(problem.code).cause)\n row('fix', help)\n for (const cause of causes) row('caused by', cause)\n if (frames?.length) details.push(' stack:', ...frames)\n if (code !== diagnosticCode.unknown) row('docs', Diagnostics.docsUrl(code))\n row('report', problem?.issues)\n\n return [`${severity} ${code}${problem?.plugin ? ` [${problem.plugin}]` : ''}: ${firstLine}`, ...details]\n }\n\n const left = `${paint(severityStyle[severity], severityIcon[severity])} ${paint('bold', firstLine)}`\n const gap = width - stripVTControlCharacters(left).length - code.length\n // A headline too long to share its row with the code would wrap mid-code, so the code drops to its own right-aligned row.\n const headline =\n width && gap < 2\n ? [left, `${' '.repeat(Math.max(0, width - code.length))}${paint('dim', code)}`]\n : [`${left}${' '.repeat(Math.max(2, gap))}${paint('dim', code)}`]\n\n const frame = rest.filter((line) => line.trim()).map((line) => ` ${paint('dim', line)}`)\n const label = (name: string) => paint('dim', name.length < 4 ? name.padEnd(4) : `${name} `)\n const rows: Array<[label: string, value: string | undefined]> = [\n ['at', where && paint('cyan', where)],\n ['fix', help],\n ]\n if (severity !== 'error') {\n const first = rows.find(([, value]) => value)\n return [...headline, ...frame, ...(first ? [` ${label(first[0])} ${first[1]}`] : [])]\n }\n rows.push(['caused by', causes[0]], ['report', problem?.issues && paint('cyan', problem.issues)])\n\n const codeFrame = (position?.frame ?? []).map((line) => ` ${line}`)\n const details = [...frame, ...rows.flatMap(([name, value]) => (value ? [` ${label(name)} ${value}`, ...(name === 'at' ? codeFrame : [])] : []))]\n if (frames?.length) details.push(` ${paint('dim', 'stack')}`, ...frames)\n if (code !== diagnosticCode.unknown) {\n details.push(` ${paint('dim', '↳ Learn more')} ${paint('cyan', Diagnostics.docsUrl(code).replace(/^https:\\/\\//, ''))}`)\n }\n\n return [...headline, ...details]\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { getErrorChain, getErrorMessage, toError } from '@internals/utils'\nimport { version } from '../package.json'\nimport { type DiagnosticCode, diagnosticCatalog, diagnosticCode } from './diagnosticCatalog.ts'\nimport { crashCodes, format, serialize } from './formatDiagnostic.ts'\nimport type { ExtensionKind, ExtensionNamed } from './defineExtension.ts'\nimport type { KubbHooks } from './types.ts'\nimport type { Hookable } from './Hookable.ts'\n\n/**\n * Docs major version, derived from the package version so the link tracks the published major.\n */\nconst docsMajor = version.split('.')[0] ?? '5'\n\n/**\n * How serious a diagnostic is. `error` fails the build, `warning` and `info`\n * are reported but do not.\n */\nexport type DiagnosticSeverity = 'error' | 'warning' | 'info'\n\n/**\n * A human-readable explanation of a diagnostic code: a short title, what triggers it, and how\n * to resolve it. This is the source of truth the kubb.dev `/reference/diagnostics#<slug>` sections 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 /** Issue tracker URL of the extension that crashed, from its `meta.issues`. */\n issues?: string\n /**\n * The underlying error, when the diagnostic wraps a thrown one.\n */\n cause?: Error\n}\n\n/**\n * A per-plugin performance record, built with {@link Diagnostics.performance}. The `performance`\n * kind keeps it out of the problem list. It feeds the per-plugin timing bars, and reporters sum\n * these into the run total.\n */\nexport type PerformanceDiagnostic = {\n kind: 'performance'\n code: typeof diagnosticCode.performance\n severity: 'info'\n message: string\n /**\n * The plugin this measurement belongs to.\n */\n plugin: string\n /**\n * Elapsed milliseconds.\n */\n duration: number\n}\n\n/**\n * A notice that a newer Kubb version is available on npm, built with {@link Diagnostics.update}.\n * It renders like any info diagnostic.\n */\nexport type UpdateDiagnostic = {\n kind: 'update'\n code: typeof diagnosticCode.updateAvailable\n severity: 'info'\n message: string\n /**\n * The running Kubb version.\n */\n currentVersion: string\n /**\n * The newest version published on npm.\n */\n latestVersion: string\n}\n\n/**\n * A structured record collected during a build, discriminated on `kind`: a\n * {@link ProblemDiagnostic} for an issue, a {@link PerformanceDiagnostic} for a per-plugin\n * timing, or an {@link UpdateDiagnostic} for a version notice.\n */\nexport type Diagnostic = ProblemDiagnostic | PerformanceDiagnostic | UpdateDiagnostic\n\n/**\n * Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic\n * with no `kind` is treated as a `problem`.\n */\nfunction isKind<T extends Diagnostic>(kind: DiagnosticKind) {\n return (diagnostic: Diagnostic): diagnostic is T => (diagnostic.kind ?? 'problem') === kind\n}\n\n/**\n * Returns `true` when the diagnostic is a build {@link ProblemDiagnostic}.\n *\n * @example\n * ```ts\n * if (isProblem(diagnostic)) {\n * console.log(diagnostic.location)\n * }\n * ```\n */\nconst isProblem = isKind<ProblemDiagnostic>('problem')\n\n/**\n * Returns `true` when the diagnostic is a per-plugin {@link PerformanceDiagnostic}.\n *\n * @example\n * ```ts\n * const timings = diagnostics.filter(isPerformance)\n * ```\n */\nconst isPerformance = isKind<PerformanceDiagnostic>('performance')\n\n/**\n * Returns `true` when the diagnostic is a version-update {@link UpdateDiagnostic}.\n *\n * @example\n * ```ts\n * if (isUpdate(diagnostic)) {\n * console.log(diagnostic.latestVersion)\n * }\n * ```\n */\nconst isUpdate = isKind<UpdateDiagnostic>('update')\n\nconst failedCode = {\n plugin: diagnosticCode.pluginFailed,\n adapter: diagnosticCode.adapterFailed,\n parser: diagnosticCode.parserFailed,\n} as const satisfies Record<ExtensionKind, ProblemCode>\n\nconst docsByCode = new Map<DiagnosticCode, DiagnosticDoc>(Object.values(diagnosticCatalog).map((doc) => [doc.code, doc]))\n\nconst reporterKey = Symbol.for('kubb.diagnostics.reporter')\n\ntype ReporterHost = typeof globalThis & { [reporterKey]?: AsyncLocalStorage<(diagnostic: Diagnostic) => void> }\n\nconst countKey = { error: 'errors', warning: 'warnings', info: 'infos' } as const satisfies Record<DiagnosticSeverity, string>\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` on `globalThis`, shared by every copy of `@kubb/core`.\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 // A plugin that loads another copy of `@kubb/core` (the project's own, beside a host such as the\n // Studio agent) still reports into the run, as `kubbContext` does.\n static #reporterStorage: AsyncLocalStorage<(diagnostic: Diagnostic) => void> = ((globalThis as ReporterHost)[reporterKey] ??= new AsyncLocalStorage())\n\n /**\n * The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).\n */\n static code = diagnosticCode\n\n /**\n * Type guard for a build {@link ProblemDiagnostic}.\n */\n static isProblem = isProblem\n\n /**\n * Type guard for a version-update {@link UpdateDiagnostic}.\n */\n static isUpdate = isUpdate\n\n /**\n * Type guard for a per-plugin {@link PerformanceDiagnostic}.\n */\n static isPerformance = isPerformance\n\n /**\n * An `Error` that carries a {@link Diagnostic}, so structured problems can flow\n * through the existing throw/catch paths while keeping their code and location.\n *\n * @example\n * ```ts\n * throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })\n * ```\n */\n static Error = class DiagnosticError extends Error {\n diagnostic: ProblemDiagnostic\n\n constructor(diagnostic: ProblemDiagnostic) {\n super(diagnostic.message, { cause: diagnostic.cause })\n this.name = 'DiagnosticError'\n this.diagnostic = diagnostic\n }\n }\n\n /**\n * Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated\n * `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`\n * that carries a `code`.\n */\n static isError(error: unknown): error is InstanceType<typeof Diagnostics.Error> {\n if (error instanceof Diagnostics.Error) return true\n if (!(error instanceof Error) || error.name !== 'DiagnosticError') return false\n\n const { diagnostic } = error as { diagnostic?: { code?: unknown } }\n return typeof diagnostic === 'object' && diagnostic !== null && typeof diagnostic.code === 'string'\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, or any thrown value, on the run's hooks so the loggers render it live.\n * A coded problem or an update goes to `kubb:diagnostic`. An uncoded one goes to `kubb:error`\n * whole, so every wrapper's message, its help, and the stack survive. To collect a diagnostic into\n * the build result from deep in a run, use {@link Diagnostics.report} instead.\n */\n static async emit(hooks: Hookable<KubbHooks>, value: ProblemDiagnostic | UpdateDiagnostic | unknown): Promise<void> {\n const thrown = value instanceof Error || typeof (value as Diagnostic | undefined)?.code !== 'string'\n const diagnostic = thrown ? Diagnostics.from(value) : (value as ProblemDiagnostic | UpdateDiagnostic)\n if (!isProblem(diagnostic) || diagnostic.code !== diagnosticCode.unknown) {\n await hooks.callHook('kubb:diagnostic', { diagnostic })\n return\n }\n const { cause, help, message } = diagnostic\n const bare = cause && !help && cause.message === message\n await hooks.callHook('kubb:error', { error: thrown ? toError(value) : bare ? cause : new Diagnostics.Error(diagnostic) })\n }\n\n /**\n * Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}\n * keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.\n */\n static from(error: unknown): ProblemDiagnostic {\n // The hook emitter and the build's AggregateError 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 chain = getErrorChain(error)\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 // The innermost one wins: it is where the problem started, and a wrapper only adds context.\n const coded = chain.findLast((current) => Diagnostics.isError(current))\n if (coded) {\n const { diagnostic } = coded as InstanceType<typeof Diagnostics.Error>\n // A crash thrown without a cause still needs a stack, so it points at itself.\n return diagnostic.cause || !crashCodes.has(diagnostic.code) ? diagnostic : { ...diagnostic, cause: coded }\n }\n const root = chain.at(-1)\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 * Coerces an error thrown by a plugin, adapter, or parser into a diagnostic attributed to it.\n * A structured {@link Diagnostics.Error} keeps its code. Any other error is a crash: it gets the\n * kind's `*_FAILED` code and the extension's `meta.issues` link, so the user reports it to the\n * extension's maintainers instead of to Kubb.\n */\n static fromExtension(error: unknown, { kind, extension }: { kind: ExtensionKind; extension: ExtensionNamed }): ProblemDiagnostic {\n const diagnostic = Diagnostics.from(error)\n const name = extension.meta?.name ?? extension.name\n // `plugin` feeds the failed-plugin count, so an adapter or parser is named in the message instead.\n const owner = kind === 'plugin' ? { plugin: diagnostic.plugin ?? name } : {}\n // An abort is the user canceling the run, not a crash.\n const crashed = diagnostic.code === diagnosticCode.unknown && diagnostic.cause?.name !== 'AbortError'\n const failed = Object.values<DiagnosticCode>(failedCode).includes(diagnostic.code)\n if (!crashed && !failed) {\n return { ...diagnostic, ...owner }\n }\n\n const issues = extension.meta?.issues\n return {\n ...diagnostic,\n ...owner,\n code: crashed ? failedCode[kind] : diagnostic.code,\n message: crashed && kind !== 'plugin' ? `${kind} \"${name}\" crashed: ${diagnostic.message}` : diagnostic.message,\n ...(issues ? { issues } : {}),\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 return [...new Set(diagnostics.flatMap((diagnostic) => (diagnostic.severity === 'error' && diagnostic.plugin ? [diagnostic.plugin] : [])))]\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 const counts = { errors: 0, warnings: 0, infos: 0 }\n for (const diagnostic of diagnostics.filter(isProblem)) {\n counts[countKey[diagnostic.severity]] += 1\n }\n return counts\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 * `/reference/diagnostics#<slug>` section.\n */\n static explain(code: DiagnosticCode): DiagnosticDoc {\n return docsByCode.get(code)!\n }\n\n /**\n * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable\n * consumers, with the catalog `title`, `cause`, and fix, and the `cause` error as `causes` and\n * `stack`. Absent optional fields are omitted.\n */\n static serialize = serialize\n\n /**\n * Renders a diagnostic as lines for an `agent` (the default) or a `human`. See {@link format}.\n */\n static format = format\n}\n","import { satisfies } from 'verkit'\nimport { version as kubbVersion } from '../package.json'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { Adapter, AdapterDefinition, AdapterFactory, AdapterFactoryOptions } from './createAdapter.ts'\nimport type { Parser, ParserBuild, ParserFactory } from './defineParser.ts'\nimport type { Plugin, PluginDefinition, PluginFactory, PluginType, PluginName } from './definePlugin.ts'\nimport type { Config } from './types.ts'\n\n/**\n * What an extension extends: a plugin generates code, an adapter reads the input, a parser prints files.\n */\nexport type ExtensionKind = 'plugin' | 'adapter' | 'parser'\n\n/**\n * Identity and registry data for an extension. Kubb reads `name` and `compatibility` at runtime.\n * Studio, the kubb.dev registry, and the docs read the rest.\n */\nexport type ExtensionMeta<TName extends string = string> = {\n /**\n * Unique name, such as `'plugin-ts'`. Becomes the plugin's `name`.\n */\n name: TName\n /**\n * Package version. Dependents check their `version` range against it.\n */\n version?: string\n displayName?: string\n /**\n * One-sentence summary of what the extension generates or does.\n */\n description?: string\n category?: string\n icon?: { light: string; dark?: string }\n /** HTTPS image or video URLs. */\n media?: Array<string>\n tags?: Array<string>\n /**\n * Semver ranges the extension supports. A mismatch fails the run with `KUBB_INCOMPATIBLE_EXTENSION`.\n */\n compatibility?: {\n kubb?: string\n node?: string\n }\n docs?: string\n /** Issue tracker URL. Kubb prints it when the extension crashes, so users report the bug to its maintainers. */\n issues?: string\n}\n\n/**\n * An extension's identity: `meta`, a `name`, or both. `name` is deprecated in favor of `meta.name`.\n */\nexport type ExtensionNamed = { name?: string; meta?: ExtensionMeta }\n\n/**\n * Returns `meta`, or `{ name }` for an extension that only sets the deprecated `name`. Throws `KUBB_INVALID_PLUGIN_OPTIONS` when it has neither.\n */\nexport function resolveMeta(extension: ExtensionNamed): ExtensionMeta {\n const { name, meta } = extension\n if (meta) return meta\n if (name) return { name }\n\n const keys = Object.keys(extension)\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `An extension has neither \\`meta.name\\` nor \\`name\\`. Received keys: ${keys.length ? keys.join(', ') : 'none'}.`,\n help: 'Set `meta: { name }` on the plugin or parser.',\n location: { kind: 'config' },\n })\n}\n\n/**\n * Sets how Kubb checks one entry in a `dependencies` record.\n */\nexport type ExtensionDependency = {\n /**\n * Semver range the dependency's `meta.version` must satisfy. Skipped when the dependency has no `meta.version`.\n */\n version?: string\n /**\n * When `true`, Kubb skips the entry if the plugin is missing, but still checks `version` on an installed one.\n * Otherwise a missing plugin fails the run with `KUBB_MISSING_DEPENDENCY`.\n */\n optional?: boolean\n}\n\n/**\n * Plugins an extension builds on, keyed by name, or a function that picks them from the user's options.\n */\nexport type ExtensionDependencies<TOptions = object> =\n | ExtensionDependencyRecord\n // Method syntax keeps `options` bivariant, so a `Plugin<PluginTs>` still fits `Config['plugins']`.\n | { resolve(options: TOptions, kubb: { config: Config }): ExtensionDependencyRecord }['resolve']\n\n/**\n * Maps each dependency's plugin name to how Kubb checks it.\n */\nexport type ExtensionDependencyRecord = Partial<Record<PluginName, ExtensionDependency>>\n\n/**\n * Throws `KUBB_INCOMPATIBLE_EXTENSION` when the running Kubb or Node.js version is outside `meta.compatibility`.\n */\nexport function checkCompatibility(meta: ExtensionMeta): void {\n const checks = [\n { target: 'Kubb', range: meta.compatibility?.kubb, version: kubbVersion },\n { target: 'Node.js', range: meta.compatibility?.node, version: process.versions.node },\n ]\n\n for (const { target, range, version } of checks) {\n if (!range || satisfies(version, range, { includePrerelease: true })) continue\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.incompatibleExtension,\n severity: 'error',\n message: `\"${meta.name}\" requires ${target} ${range}, but ${version} is running.`,\n help: `Use a ${target} version that satisfies ${range}, or a version of \"${meta.name}\" that supports ${target} ${version}.`,\n location: { kind: 'config' },\n plugin: meta.name,\n })\n }\n}\n\n/**\n * Throws `KUBB_MISSING_DEPENDENCY` for a missing required entry in a `dependencies` record, and\n * `KUBB_INCOMPATIBLE_DEPENDENCY` when an entry's `meta.version` is out of range. Arrays are not checked.\n */\nexport function checkDependencies({\n name,\n dependencies,\n plugins,\n}: {\n name: string\n dependencies: Array<PluginName> | ExtensionDependencyRecord | undefined\n plugins: ReadonlyMap<string, { meta?: ExtensionMeta }>\n}): void {\n if (!dependencies || Array.isArray(dependencies)) return\n\n for (const [dependencyName, dependency] of Object.entries(dependencies)) {\n const target = plugins.get(dependencyName)\n\n if (!target) {\n if (dependency?.optional) continue\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.missingDependency,\n severity: 'error',\n message: `Plugin \"${dependencyName}\" is required by \"${name}\" but not found.`,\n help: `Add \"${dependencyName}\" to the \\`plugins\\` array in kubb.config.ts.`,\n location: { kind: 'config' },\n plugin: name,\n })\n }\n\n const range = dependency?.version\n const version = target.meta?.version\n if (!range || !version || satisfies(version, range, { includePrerelease: true })) continue\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.incompatibleDependency,\n severity: 'error',\n message: `\"${name}\" requires \"${dependencyName}\" ${range}, but ${version} is configured.`,\n help: `Install a version of \"${dependencyName}\" that satisfies ${range}.`,\n location: { kind: 'config' },\n plugin: name,\n })\n }\n}\n\n/**\n * The function an extension definition returns. Call it with user options to get the extension.\n */\nexport type ExtensionFactory<TKind extends ExtensionKind, TOptions, TExtension, TName extends string = string> = {\n (options?: TOptions): TExtension\n kind: TKind\n meta: ExtensionMeta<TName>\n}\n\n/**\n * Builds the factory behind `defineExtension`. It passes `{}` when called without options, and carries `kind` and\n * `meta` so tools can read them without calling it.\n *\n * @internal\n */\nexport function createExtensionFactory<TKind extends ExtensionKind, TOptions extends object, TExtension, TName extends string>({\n kind,\n meta,\n build,\n}: {\n kind: TKind\n meta: ExtensionMeta<TName>\n build: (options: TOptions) => TExtension\n}): ExtensionFactory<TKind, TOptions, TExtension, TName> {\n return Object.assign((options: TOptions = {} as TOptions) => build(options), { kind, meta })\n}\n\n// Parser comes first and takes only `build`: TypeScript fixes a parameterless `build()` return type from the first\n// overload that types it, and `extNames` only keeps its literal types under the parser's.\n\n/**\n * Defines a parser and returns a factory that takes the user's options. `build` returns the parser methods.\n */\nexport function defineExtension<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(definition: {\n kind: 'parser'\n meta: ExtensionMeta\n build: ParserBuild<TOptions, TMeta, TNode>\n}): ParserFactory<TOptions, TMeta, TNode>\n/**\n * Defines an adapter and returns a factory that takes the user's options. `parse` must return an `InputNode`.\n */\nexport function defineExtension<T extends AdapterFactoryOptions = AdapterFactoryOptions>(\n definition: { kind: 'adapter' } & AdapterDefinition<T>,\n): AdapterFactory<T>\n/**\n * Defines a plugin and returns a factory that takes the user's options. Name plugins `plugin-<feature>`.\n *\n * @example\n * ```ts\n * defineExtension<PluginZod>({ kind: 'plugin', meta: { name: 'plugin-zod' }, setup: (options) => options })\n * ```\n */\nexport function defineExtension<TFactory extends PluginType = PluginType>(definition: { kind: 'plugin' } & PluginDefinition<TFactory>): PluginFactory<TFactory>\nexport function defineExtension(\n definition:\n | ({ kind: 'plugin' } & PluginDefinition)\n | ({ kind: 'adapter' } & AdapterDefinition)\n | { kind: 'parser'; meta: ExtensionMeta; build: ParserBuild<object, object, unknown> },\n) {\n switch (definition.kind) {\n case 'plugin': {\n const { meta, dependencies, enforce, hooks = {}, setup } = definition\n // Keeps the raw options: Studio and config merging read them back.\n return createExtensionFactory({\n kind: 'plugin',\n meta,\n build: (options: object): Plugin => ({ name: meta.name, meta, options, dependencies, enforce, hooks, setup }),\n })\n }\n case 'adapter': {\n const { meta, setup, build } = definition\n return createExtensionFactory({\n kind: 'adapter',\n meta,\n build: (raw: object): Adapter => {\n const options = setup ? setup(raw) : raw\n // Assigned onto the built object instead of spread, so getters such as `document` stay live.\n return Object.assign(build(options), { name: meta.name, meta, options: raw })\n },\n })\n }\n case 'parser': {\n const { meta, build } = definition\n return createExtensionFactory({\n kind: 'parser',\n meta,\n build: (options: object): Parser => ({ ...build(options), name: meta.name, meta, options }),\n })\n }\n }\n}\n","import type { PossiblePromise } from '@internals/utils'\nimport type { InputNode } from '@kubb/ast'\nimport { defineExtension } from './defineExtension.ts'\nimport type { ExtensionFactory, ExtensionMeta } from './defineExtension.ts'\nimport type { DiagnosticLocation } from './Diagnostics.ts'\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 `defineExtension` with `kind: 'adapter'` and the resulting `Adapter` type.\n *\n * - `TName`: unique adapter identifier (`'oas'`, `'asyncapi'`, ...).\n * - `TOptions`: user-facing options accepted by the adapter factory.\n * - `TResolvedOptions`: options after defaults are applied.\n * - `TDocument`: type of the parsed source document.\n */\nexport type AdapterFactoryOptions<\n TName extends string = string,\n TOptions extends object = object,\n TResolvedOptions extends object = TOptions,\n TDocument = unknown,\n> = {\n name: TName\n options: TOptions\n resolvedOptions: TResolvedOptions\n document: TDocument\n}\n\n/**\n * Converts input files or inline data into Kubb's universal AST `InputNode`.\n *\n * Adapters live between the spec format and the plugins. The built-in\n * `@kubb/adapter-oas` handles OpenAPI 2.0, 3.0, and 3.1. A custom adapter can\n * support GraphQL, gRPC, or another schema language.\n *\n * @example\n * ```ts\n * import { defineConfig } from 'kubb'\n * import { adapterOas } from '@kubb/adapter-oas'\n * import { pluginTs } from '@kubb/plugin-ts'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * adapter: adapterOas(),\n * plugins: [pluginTs()],\n * })\n * ```\n */\nexport type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {\n /**\n * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).\n */\n name: TOptions['name']\n meta?: ExtensionMeta<TOptions['name']>\n /**\n * The options the adapter was created with, before `setup` applied defaults, as a plugin keeps its\n * own. Kubb Studio merges its overrides onto these, so a default derived from another option, such\n * as `emptySchemaType` from `unknownType`, follows a change to it.\n */\n options: TOptions['options']\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 * An adapter that renames schemas (e.g. collision handling) must stamp `targetName` on\n * every ref node pointing at a renamed schema, so `resolveRefName` and `resolver.imports`\n * resolve a `$ref` to the file that is actually generated. Refs that keep their pointer's\n * last segment need no stamp.\n */\n parse: (source: AdapterSource, options?: { signal?: AbortSignal }) => PossiblePromise<InputNode>\n /**\n * Validate the document at the given path or URL.\n */\n validate: (input: string, options?: { throwOnError?: boolean }) => Promise<void>\n /**\n * Zero-based UTF-16 offsets of a diagnostic in `source` for a code frame, `end` exclusive; `undefined` when it cannot be found.\n */\n locate?: (source: string, location: DiagnosticLocation) => { start: number; end: number } | undefined\n}\n\n/**\n * The object passed to `defineExtension` with `kind: 'adapter'`.\n */\nexport type AdapterDefinition<T extends AdapterFactoryOptions = AdapterFactoryOptions> = {\n meta: ExtensionMeta<T['name']>\n /**\n * Takes the user's options and returns the resolved options, which `build` receives and the adapter exposes as `options`.\n * Without `setup`, the user's options are the resolved options.\n */\n setup?(options: T['options']): T['resolvedOptions']\n /**\n * Returns the adapter's document and methods for the resolved options.\n */\n build(options: T['resolvedOptions']): Omit<Adapter<T>, 'name' | 'meta' | 'options'>\n}\n\n/**\n * The function `defineExtension` returns for an adapter. Call it with user options to get an `Adapter`.\n */\nexport type AdapterFactory<T extends AdapterFactoryOptions = AdapterFactoryOptions> = ExtensionFactory<'adapter', T['options'], Adapter<T>, T['name']>\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 * @deprecated Use `defineExtension` with `kind: 'adapter'` instead.\n */\nexport function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(definition: AdapterDefinition<T>): AdapterFactory<T> {\n return defineExtension({ kind: 'adapter', ...definition })\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { Macro, UserFileNode } from '@kubb/ast'\nimport type { Generator } from './defineGenerator.ts'\nimport type { KubbPluginSetupContext, NormalizedPlugin, PluginType, PluginName, ResolvePluginOptions } from './definePlugin.ts'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { Resolver, ResolverPatch } from './Resolver.ts'\nimport type { Config } from './types.ts'\n\nconst kubbContextKey = Symbol.for('kubb.context')\n\ntype KubbContextHost = typeof globalThis & { [kubbContextKey]?: AsyncLocalStorage<KubbPluginSetupContext> }\n\nconst host = globalThis as KubbContextHost\n\n/**\n * Holds the setup context of the plugin whose `setup` or `kubb:plugin:setup` is running. `KubbDriver` sets it for each plugin.\n *\n * The store lives on `globalThis`, so the ESM and CommonJS builds of `@kubb/core` share one. A plugin that a\n * CommonJS config loads would otherwise read an empty store and fail with `KUBB_NO_CONTEXT`.\n */\nexport const kubbContext: AsyncLocalStorage<KubbPluginSetupContext> = (host[kubbContextKey] ??= new AsyncLocalStorage<KubbPluginSetupContext>())\n\nfunction requireContext(caller: string): KubbPluginSetupContext {\n const ctx = kubbContext.getStore()\n if (ctx) return ctx\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.noContext,\n severity: 'error',\n message: `\\`${caller}()\\` was called outside a plugin setup.`,\n help: `Call \\`${caller}()\\` inside \\`setup\\` or \\`kubb:plugin:setup\\`, including in code that setup awaits.`,\n })\n}\n\n/**\n * Returns the context of the plugin whose `kubb:plugin:setup` is running. It stays available after an `await`.\n * Throws `KUBB_NO_CONTEXT` outside setup.\n */\nexport function useKubb<TFactory extends PluginType = PluginType>(): KubbPluginSetupContext<TFactory> {\n return requireContext('useKubb') as KubbPluginSetupContext<TFactory>\n}\n\n/**\n * Returns the same context as {@link useKubb}, or `undefined` outside `setup` and `kubb:plugin:setup`.\n */\nexport function tryUseKubb<TFactory extends PluginType = PluginType>(): KubbPluginSetupContext<TFactory> | undefined {\n return kubbContext.getStore() as KubbPluginSetupContext<TFactory> | undefined\n}\n\n/**\n * Registers generators on the plugin being set up, like `ctx.addGenerator`.\n *\n * @example\n * `addGenerator(typeGenerator, enumGenerator)`\n */\nexport function addGenerator<TFactory extends PluginType = PluginType, TElement = unknown>(...generators: Array<Generator<TFactory, TElement>>): void {\n requireContext('addGenerator').addGenerator(...generators)\n}\n\n/**\n * Sets the resolver of the plugin being set up, like `ctx.setResolver`.\n */\nexport function setResolver<TResolver extends Resolver = Resolver>(resolver: ResolverPatch<TResolver> | TResolver): void {\n requireContext('setResolver').setResolver(resolver)\n}\n\n/**\n * Adds a macro to the plugin being set up, like `ctx.addMacro`.\n */\nexport function addMacro(macro: Macro): void {\n requireContext('addMacro').addMacro(macro)\n}\n\n/**\n * Replaces the macros of the plugin being set up, like `ctx.setMacros`.\n */\nexport function setMacros(macros: ReadonlyArray<Macro>): void {\n requireContext('setMacros').setMacros(macros)\n}\n\n/**\n * Adds a raw file to the build output, like `ctx.injectFile`.\n */\nexport function injectFile(file: UserFileNode): void {\n requireContext('injectFile').injectFile(file)\n}\n\n/**\n * Returns the options the user passed to the plugin being set up, like `ctx.options`.\n */\nexport function useOptions<TFactory extends PluginType = PluginType>(): TFactory['options'] {\n return requireContext('useOptions').options as TFactory['options']\n}\n\n/**\n * Sets the resolved options of the plugin being set up, like `ctx.setOptions`.\n */\nexport function setOptions<TFactory extends PluginType = PluginType>(options: TFactory['resolvedOptions']): void {\n requireContext('setOptions').setOptions(options)\n}\n\n/**\n * Returns the resolved build configuration, like `ctx.config`.\n */\nexport function useConfig(): Config {\n return requireContext('useConfig').config\n}\n\n/**\n * Returns another plugin from the config, typed through `Kubb.PluginRegistry`, like `ctx.requirePlugin`.\n */\nexport function requirePlugin<TName extends PluginName>(name: TName): NormalizedPlugin<ResolvePluginOptions<TName>> {\n return requireContext('requirePlugin').requirePlugin(name) as NormalizedPlugin<ResolvePluginOptions<TName>>\n}\n","import path from 'node:path'\nimport type { LiteralUnion } from '@internals/utils'\nimport type { Enforce, HttpMethod, Macro, UserFileNode } from '@kubb/ast'\nimport type { Generator } from './defineGenerator.ts'\nimport { defineExtension } from './defineExtension.ts'\nimport type { ExtensionDependencies, ExtensionDependencyRecord, ExtensionFactory, ExtensionMeta, ExtensionNamed } from './defineExtension.ts'\nimport type { BannerMeta, Resolver, ResolverPatch } from './Resolver.ts'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { Config, FilesContext, KubbHooks } from './types.ts'\n\n/** Reads key `K` from a registry interface, or `{}` when no package has augmented it. @internal */\nexport type ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {}\n\n/**\n * A plugin name as accepted by `getPlugin`/`requirePlugin`/`getResolver`. Registered names from\n * `Kubb.PluginRegistry` autocomplete, and any other string is still allowed.\n */\nexport type PluginName = LiteralUnion<keyof Kubb.PluginRegistry>\n\n/**\n * Resolves a plugin name to its `PluginType`. A name registered in `Kubb.PluginRegistry`\n * maps to its exact factory options, any other string falls back to the generic options.\n */\nexport type ResolvePluginOptions<TName> = TName extends keyof Kubb.PluginRegistry ? Kubb.PluginRegistry[TName] : PluginType\n\n/**\n * How a plugin consolidates its generated code into files.\n * - `'file'` writes everything into a single file.\n * - `'directory'` writes one file per operation or schema under `path`.\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 * - `'file'` writes everything into a single file. The `path` must include the file extension.\n * - `'directory'` writes one file per operation or schema under `path`.\n *\n * Defaults to `'file'` when `path` carries an extension and `'directory'` when it does not.\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 first path segment as written in the spec 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 * - An explicit `mode: 'file'` forbids `group` (a single file has nothing to group).\n * - Omitting `mode`, or setting it to `'directory'`, allows an optional `group`.\n *\n * `mode` is normally inferred from `output.path` (an extension means `'file'`, anything\n * else `'directory'`), so `group` rarely needs `mode` spelled out alongside it. Set\n * `mode: 'directory'` explicitly only to override that inference, such as a directory\n * name that carries a dot (`path: 'clients.v2'`).\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 *\n * An omitted `mode` follows the shape of `path`: an extension means a single file, anything\n * else is a directory. Plugin defaults such as `path: 'types'` name a directory, so they\n * generate without the caller spelling out `mode`.\n */\nexport function normalizeOutput({ output, group, pluginName }: { output: Output; group?: Group | null; pluginName: string }): Output {\n const mode = output.mode ?? (path.extname(output.path) ? 'file' : 'directory')\n\n if (mode === 'file' && group) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `Plugin \"${pluginName}\" resolves \\`output.mode\\` to 'file' but also configures a \\`group\\` option.`,\n help: \"A single-file output has nothing to group. Remove the `group` option, give `output.path` an extensionless directory name, or set `output.mode: 'directory'` explicitly.\",\n location: { kind: 'config' },\n plugin: pluginName,\n })\n }\n\n return { ...output, mode }\n}\n\n/** Throws `KUBB_INVALID_PLUGIN_OPTIONS`, listing the allowed values, when `value` is not one of `allowed`. */\nexport function assertPluginOption({\n plugin,\n option,\n value,\n allowed,\n}: {\n plugin: string\n option: string\n value: unknown\n allowed: ReadonlyArray<unknown>\n}): void {\n if (allowed.includes(value)) return\n\n const format = (item: unknown) => (typeof item === 'string' ? JSON.stringify(item) : String(item))\n const expected = allowed.map(format).join(', ')\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `Plugin \"${plugin}\" option \\`${option}\\` is ${format(value)}, but it must be one of ${expected}.`,\n help: `Set \\`${option}\\` to one of ${expected}.`,\n location: { kind: 'config' },\n plugin,\n })\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'`, `'QUERY'`.\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'`, `'QUERY'`) 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\ntype ByExtension = {\n /** Filter operations by a vendor extension (`x-*` key) on the source operation. Does not apply to schemas. */\n type: 'extension'\n /** Extension key, including the `x-` prefix. */\n key: `x-${string}`\n /** Value the extension must strictly equal. When omitted, the key being present is enough. */\n value?: unknown\n}\n\n/**\n * Pattern filter for include, exclude, and override rules. Matches operations or schemas\n * by tag, operationId, path, method, content type, schema name, or vendor extension.\n */\nexport type Filter = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName | ByExtension\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 * { type: 'extension', key: 'x-internal', value: true },\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 PluginType<\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 PluginType = PluginType> = {\n /**\n * Register one or more generators dynamically. Generators fire during the AST walk\n * (schema/operation/operations) just like generators declared statically on `createPlugin`.\n *\n * Pass generators as separate arguments. Spread an existing list to register it in one call.\n *\n * @example\n * ```ts\n * ctx.addGenerator(myGenerator)\n * ctx.addGenerator(schemaGenerator, operationGenerator)\n * ctx.addGenerator(...selectedGenerators)\n * ```\n */\n addGenerator<TElement = unknown>(...generators: Array<Generator<TFactory, TElement>>): void\n /**\n * Set or override the resolver for this plugin.\n * The resolver controls file naming and path resolution. Overrides merge over the built-in\n * defaults, so a partial `core` or a single namespace method replaces only what it names.\n */\n setResolver(resolver: ResolverPatch<TFactory['resolver']> | TFactory['resolver']): void\n /**\n * Add a macro that rewrites AST nodes before they reach generators. Macros run in the order they\n * are added, after any macros from earlier `addMacro` calls.\n */\n addMacro(macro: Macro): void\n /**\n * Replace this plugin's macros with `macros`.\n */\n setMacros(macros: ReadonlyArray<Macro>): void\n /**\n * Set resolved options merged into the normalized plugin's `options`.\n * Call this in `kubb:plugin:setup` to provide options generators need.\n */\n setOptions(options: TFactory['resolvedOptions']): void\n /**\n * Inject a raw file into the build output, bypassing the generation pipeline.\n *\n * Pass `copy` with an absolute path to emit a real source file (a shipped template) into the\n * generated folder, instead of building its content from `sources`.\n */\n injectFile(userFileNode: UserFileNode): void\n /** Returns a plugin this one needs, or fails the run with `KUBB_PLUGIN_NOT_FOUND` when the config lacks it. */\n requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>\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 `defineExtension`. Its lifecycle handlers live under a single\n * `hooks` property rather than flat methods.\n */\nexport type Plugin<TFactory extends PluginType = PluginType> = ExtensionNamed & {\n /**\n * Plugins this one builds on. They run first when the config has them. An array only orders\n * plugins. A record also fails the run when a required entry is missing or out of range.\n */\n dependencies?: Array<PluginName> | ExtensionDependencies<TFactory['options']>\n /**\n * Controls the execution order of this plugin relative to others.\n *\n * - `'pre'` runs before all normal plugins.\n * - `'post'` runs after all normal plugins.\n * - `undefined` (default) runs in declaration order among normal plugins.\n *\n * Dependency constraints always take precedence over `enforce`.\n */\n enforce?: Enforce\n /**\n * The options passed by the user when calling the plugin factory.\n */\n options?: TFactory['options']\n /**\n * Lifecycle hook handlers for this plugin.\n * Any hook from the global `KubbHooks` map can be subscribed to here.\n */\n hooks: {\n [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void>\n } & {\n 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>\n }\n /**\n * Runs before `kubb:plugin:setup`. Takes the user's options and returns the resolved options.\n */\n setup?(options: TFactory['options'], kubb: KubbPluginSetupContext<TFactory>): TFactory['resolvedOptions'] | Promise<TFactory['resolvedOptions']>\n}\n\n/**\n * The object passed to `defineExtension` with `kind: 'plugin'`.\n */\nexport type PluginDefinition<TFactory extends PluginType = PluginType> = Pick<Plugin<TFactory>, 'dependencies' | 'enforce' | 'setup'> & {\n meta: ExtensionMeta<TFactory['name']>\n hooks?: Plugin<TFactory>['hooks']\n}\n\n/**\n * The function `defineExtension` returns for a plugin. Call it with user options to get a `Plugin`.\n */\nexport type PluginFactory<TFactory extends PluginType = PluginType> = ExtensionFactory<'plugin', TFactory['options'], Plugin<TFactory>, TFactory['name']>\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 PluginType = PluginType> = Plugin<TOptions> & {\n name: string\n meta: ExtensionMeta\n dependencies?: Array<PluginName> | ExtensionDependencyRecord\n options: TOptions['resolvedOptions'] & {\n output: Output\n include?: Array<Include>\n exclude: Array<Exclude>\n override: Array<Override<TOptions['resolvedOptions']>>\n }\n resolver: TOptions['resolver']\n macros?: Array<Macro>\n generators?: Array<Generator>\n}\n\nexport type KubbPluginStartContext = {\n plugin: NormalizedPlugin\n}\n\nexport type KubbPluginEndContext = FilesContext & {\n plugin: NormalizedPlugin\n duration: number\n success: boolean\n error?: Error\n config: Config\n}\n\n/**\n * Defines a plugin from one object and returns a factory that takes the user's options.\n *\n * @deprecated Use `defineExtension` with `kind: 'plugin'` instead.\n */\nexport function definePlugin<TFactory extends PluginType = PluginType>(definition: PluginDefinition<TFactory>): PluginFactory<TFactory> {\n return defineExtension({ kind: 'plugin', ...definition })\n}\n","import net from 'node:net'\n\nfunction createBlockList(): net.BlockList {\n const list = new net.BlockList()\n for (const [address, prefix] of [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.0.0.0', 24],\n ['192.168.0.0', 16],\n ['198.18.0.0', 15],\n ['224.0.0.0', 3],\n ] as const) {\n list.addSubnet(address, prefix, 'ipv4')\n }\n for (const [address, prefix] of [\n ['::', 128],\n ['::1', 128],\n ['64:ff9b::', 96],\n ['fc00::', 7],\n ['fe80::', 10],\n ['ff00::', 8],\n ] as const) {\n list.addSubnet(address, prefix, 'ipv6')\n }\n return list\n}\n\nconst privateAddresses = createBlockList()\n\n/**\n * Whether `address` is a routable public IP. Loopback, private, link-local, cloud metadata, and\n * multicast ranges are not, and an IPv4-mapped IPv6 address counts as the IPv4 address it wraps.\n * Pass `blocked` to replace the ranges.\n */\nexport function isPublicAddress(address: string, blocked: net.BlockList = privateAddresses): boolean {\n const family = net.isIP(address)\n return family !== 0 && !blocked.check(address, family === 4 ? 'ipv4' : 'ipv6')\n}\n","import dns from 'node:dns'\nimport { mkdtemp, rm } from 'node:fs/promises'\nimport net from 'node:net'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport process from 'node:process'\nimport { getErrorMessage, toError } from '@internals/utils'\nimport { x } from 'tinyexec'\nimport { Diagnostics } from './Diagnostics.ts'\nimport { isPublicAddress } from './publicAddress.ts'\n\n/**\n * A git `input` split into its parts: `git+<repo>#<ref>:<path>`, where `<ref>:` is optional.\n */\nexport type GitInput = {\n /** Repository URL passed to `git fetch`, without the `git+` prefix. */\n repo: string\n /** Branch, tag, or commit SHA. `undefined` fetches the default branch. */\n ref: string | undefined\n /** Spec file inside the repository. */\n path: string\n}\n\n/** Matches a git `input`: the `git+` prefix npm uses for git dependencies. */\nexport const gitInputRegExp = /^git\\+/i\n\nfunction gitError(message: string, cause?: unknown): InstanceType<typeof Diagnostics.Error> {\n return new Diagnostics.Error({\n code: Diagnostics.code.gitInputFailed,\n severity: 'error',\n message,\n help: 'Write a git `input` as `git+<repo>#<ref>:<path>`, for example `git+https://github.com/org/api.git#main:specs/openapi.yaml`. Check that `git` is installed and that `git fetch` can reach the repository with your credentials.',\n location: { kind: 'config' },\n cause: cause === undefined ? undefined : toError(cause),\n })\n}\n\n/** The repository URL without a user or password, safe to print. */\nfunction redact(repo: string): string {\n if (!URL.canParse(repo)) return repo\n const url = new URL(repo)\n url.username = ''\n url.password = ''\n return url.href\n}\n\n/**\n * Splits `git+<repo>#<ref>:<path>` into its parts. Git refs cannot contain `:`, so the first one\n * in the fragment ends the ref. Throws `KUBB_GIT_INPUT_FAILED` when the fragment or path is missing.\n */\nexport function parseGitInput(input: string): GitInput {\n const hashIndex = input.indexOf('#')\n const repo = input.slice(4, hashIndex === -1 ? undefined : hashIndex)\n const fragment = hashIndex === -1 ? '' : input.slice(hashIndex + 1)\n const colonIndex = fragment.indexOf(':')\n const ref = colonIndex === -1 ? undefined : fragment.slice(0, colonIndex)\n const path = colonIndex === -1 ? fragment : fragment.slice(colonIndex + 1)\n\n if (!repo || !path || ref === '') {\n throw gitError(`The git \\`input\\` for ${redact(repo)} has no repository, ref, or spec path after \\`#\\`.`)\n }\n\n return { repo, ref, path }\n}\n\n/**\n * The `git -c` settings that confine a fetch to https and to `addresses`: the connection goes to\n * the addresses already checked, whatever the host answers to a second lookup, and a redirect to\n * another host is an error. Needs git 2.37 for the pinning.\n *\n * @internal\n */\nexport function publicFetchConfig({ host, port, addresses }: { host: string; port: string; addresses: Array<string> }): Array<string> {\n const pinned = addresses.map((address) => (net.isIPv6(address) ? `[${address}]` : address)).join(',')\n const config = ['http.followRedirects=false', 'protocol.allow=never', 'protocol.https.allow=always']\n // An IP literal needs no pinning, since git does not look it up.\n if (!net.isIP(host)) config.push(`http.curloptResolve=${host}:${port}:${pinned}`)\n return config.flatMap((setting) => ['-c', setting])\n}\n\nasync function resolvePublicFetchConfig(repo: string, signal?: AbortSignal): Promise<Array<string>> {\n if (!URL.canParse(repo) || new URL(repo).protocol !== 'https:') {\n throw gitError('A public git `input` must be an https repository URL, not an ssh, git, or file address.')\n }\n const url = new URL(repo)\n const host = url.hostname.replace(/^\\[|\\]$/g, '')\n const isLiteral = net.isIP(host) !== 0\n const addresses = isLiteral ? [host] : (await dns.promises.lookup(host, { all: true })).map(({ address }) => address)\n if (!addresses.length || addresses.some((address) => !isPublicAddress(address))) {\n throw gitError(`${host} is not a public address, so this git \\`input\\` is not fetched.`)\n }\n if (!isLiteral) {\n const { stdout } = await x('git', ['--version'], { nodeOptions: { signal }, throwOnError: true })\n const [, major = 0, minor = 0] = /(\\d+)\\.(\\d+)/.exec(stdout)?.map(Number) ?? []\n if (major < 2 || (major === 2 && minor < 37)) throw gitError(`Fetching a public git \\`input\\` needs git 2.37 or newer, found ${stdout.trim()}.`)\n }\n return publicFetchConfig({ host, port: url.port || '443', addresses })\n}\n\n/**\n * Fetches one commit of a git repository into a temporary directory with a shallow `git fetch`,\n * so any host and the user's own git credentials work, and relative `$ref` files resolve.\n * Resolves to the spec path on disk and a `dispose` that deletes the checkout.\n *\n * With `publicOnly`, the repository must be an https URL on public addresses, the fetch connects to\n * the addresses checked, and it does not follow a redirect.\n */\nexport async function checkoutGitInput(\n input: string,\n signal?: AbortSignal,\n { publicOnly = false }: { publicOnly?: boolean } = {},\n): Promise<{ path: string; dispose: () => Promise<void> }> {\n const { repo, ref, path } = parseGitInput(input)\n const fetchConfig = publicOnly ? await resolvePublicFetchConfig(repo, signal) : []\n const dir = await mkdtemp(join(tmpdir(), 'kubb-git-'))\n const dispose = () => rm(dir, { recursive: true, force: true })\n const specPath = resolve(dir, path)\n\n const relativePath = relative(dir, specPath)\n if (relativePath === '..' || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {\n await dispose()\n throw gitError(`The spec path \"${path}\" in the git \\`input\\` points outside the repository.`)\n }\n\n const label = `${redact(repo)}${ref ? ` at ${ref}` : ''}`\n // A prompt would hang the run, so git fails instead; credential helpers and SSH keys still work.\n const env = { ...process.env, GIT_TERMINAL_PROMPT: '0' }\n // `--end-of-options` keeps a repo or ref that starts with `-` from being read as a git flag.\n const steps = [\n ['init', '--quiet'],\n // Symlinks become plain files, so a link in the repo cannot point the adapter at a file outside it.\n ['config', 'core.symlinks', 'false'],\n [...fetchConfig, 'fetch', '--quiet', '--depth', '1', '--end-of-options', repo, ref ?? 'HEAD'],\n ['checkout', '--quiet', 'FETCH_HEAD'],\n ]\n\n try {\n for (const args of steps) {\n const result = await x('git', args, { nodeOptions: { cwd: dir, env, signal }, throwOnError: false })\n if (result.exitCode !== 0) {\n const stderr = result.stderr.replaceAll(repo, redact(repo)).trim()\n throw gitError(`\\`git ${args[0]}\\` failed for ${label}: ${stderr || `exit code ${result.exitCode}`}`)\n }\n }\n } catch (error) {\n await dispose()\n if (Diagnostics.isError(error)) throw error\n throw gitError(`Cannot run \\`git\\` for ${label}: ${getErrorMessage(error)}`, error)\n }\n\n return { path: specPath, dispose }\n}\n","import { resolve } from 'node:path'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { Config, Input } from './types.ts'\nimport type { AdapterSource } from './createAdapter.ts'\nimport { gitInputRegExp } from './gitInput.ts'\n\n/**\n * What an `input` value points at, once Kubb has looked at it.\n *\n * - `file` is a local file path, absolute or relative to the config file.\n * - `url` is a remote document to fetch.\n * - `git` is a spec file in a git repository, written as `git+<repo>#<ref>:<path>`.\n * - `inline` is OpenAPI content held in the string itself (JSON or YAML).\n * - `object` is an already-parsed spec.\n */\nexport type InputKind = 'file' | 'url' | 'git' | 'inline' | 'object'\n\n/**\n * Classifies an `input` value so callers branch on it once instead of repeating the checks.\n *\n * A non-string is a parsed spec (`object`). A string is `inline` when it holds OpenAPI content,\n * meaning it starts with `{` or `[`, spans multiple lines, or opens with a YAML `openapi:` or\n * `swagger:` key. Otherwise a string is `git` when it starts with `git+`, a `url` when it parses as\n * one, or a `file` path.\n */\nexport function getInputKind(input: NonNullable<Input>): InputKind {\n if (typeof input !== 'string') return 'object'\n\n const trimmed = input.trimStart()\n const isInline = trimmed.startsWith('{') || trimmed.startsWith('[') || input.includes('\\n') || /^(openapi|swagger)\\s*:/i.test(trimmed)\n if (isInline) return 'inline'\n if (gitInputRegExp.test(input)) return 'git'\n\n if (URL.canParse(input)) return 'url'\n\n return 'file'\n}\n\n/**\n * The v4 `input` wrapper keys. v4 typed `input` as `{ path }` or `{ data }`; v5 takes the value\n * directly, so the wrapper now matches the \"already-parsed document\" branch and silently yields\n * an empty build.\n */\nconst legacyInputKeys = ['path', 'data']\n\n/**\n * Detects the v4 `{ path }` / `{ data }` wrapper so it fails loudly instead of being read as a\n * document. A real spec always carries more than these keys, so an object whose keys are drawn\n * only from them is the old shape rather than a document that happens to have a `path` property.\n */\nfunction isLegacyInput(input: unknown): boolean {\n if (Array.isArray(input)) {\n return input.some(isLegacyInput)\n }\n\n if (typeof input !== 'object' || input === null) return false\n\n const keys = Object.keys(input)\n\n return keys.length > 0 && keys.every((key) => legacyInputKeys.includes(key))\n}\n\n/**\n * Normalizes `config.input` into an `AdapterSource` the adapter can parse.\n *\n * A parsed object and inline content become `{ type: 'data' }`; a URL or git input is kept\n * verbatim and a local path is resolved against `config.root`, all as `{ type: 'path' }`. The\n * driver checks out a git input before the adapter parses it.\n */\nexport function inputToAdapterSource(config: Config): AdapterSource {\n const input = config.input\n\n if (input && isLegacyInput(input)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.legacyInput,\n severity: 'error',\n message: 'The `input` option uses the v4 `{ path }` / `{ data }` wrapper.',\n help: 'Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`.',\n location: { kind: 'config' },\n })\n }\n\n if (!input) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputRequired,\n severity: 'error',\n message: 'An adapter is configured without an input.',\n help: 'Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.',\n location: { kind: 'config' },\n })\n }\n\n if (typeof input !== 'string') {\n return { type: 'data', data: input }\n }\n\n const kind = getInputKind(input)\n if (kind === 'inline') return { type: 'data', data: input }\n if (kind === 'url' || kind === 'git') return { type: 'path', path: input }\n\n return { type: 'path', path: resolve(config.root, input) }\n}\n","import path from 'node:path'\nimport { camelCase } from '@internals/utils'\nimport { ast, collectImportedRefNames, type FileNode, type ImportNode, type InputMeta, type Node, type OperationNode, type SchemaNode } from '@kubb/ast'\nimport { Diagnostics } from './Diagnostics.ts'\nimport { getInputKind } from './input.ts'\nimport type { Filter, Override, Group, Output } from './definePlugin.ts'\nimport type { Config } from './types.ts'\n\n/**\n * Context for resolving filtered options for a given operation or schema node.\n *\n * @internal\n */\nexport type ResolveOptionsContext<TOptions> = {\n options: TOptions\n exclude?: Array<Filter>\n include?: Array<Filter>\n override?: Array<Override<TOptions>>\n}\n\n/**\n * The built-in resolution machinery exposed on every resolver as `resolver.default`.\n * Plugins delegate to it via `this.default.*` and set their own conventions through\n * the top-level `name` and `file` entries.\n */\nexport type ResolverDefault = {\n /**\n * Built-in camelCase casing for a generated identifier.\n */\n name(name: string): string\n options<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null\n path(options: ResolvePathOptions): string\n file(options: ResolveFileOptions): FileNode\n banner(meta: InputMeta | undefined, context: ResolveBannerContext): string | null\n footer(meta: InputMeta | undefined, context: ResolveBannerContext): string | null\n}\n\n/**\n * The name request for `resolver.default.path`: a `baseName` plus the optional `tag`/`path` that\n * grouping keys off.\n */\nexport type ResolverPathParams = Omit<ResolverFileParams, 'name' | 'extname'> & {\n baseName: FileNode['baseName']\n}\n\n/**\n * Options for `resolver.default.path`: the name request (`baseName`, `tag`, `path`) plus where the\n * output goes (`root`, `output`, `group`).\n *\n * @example\n * ```ts\n * resolver.default.path({ baseName: 'petTypes.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })\n * // → '/src/types/pets/petTypes.ts'\n * ```\n */\nexport type ResolvePathOptions = ResolverPathParams & {\n /**\n * Absolute project root that the output path is resolved against.\n */\n root: string\n /**\n * Active output config; `output.path` is the base directory.\n */\n output: Output\n /**\n * Optional grouping strategy applied to `tag` (tag grouping) or `path` (path grouping).\n */\n group?: Group\n}\n\n/**\n * The file request for `resolver.file` and `resolver.default.file`: the `name` and `extname` plus\n * the optional `tag`/`path` that grouping keys off.\n */\nexport type ResolverFileParams = {\n name: string\n extname: FileNode['extname']\n /**\n * Tag value used when `group.type === 'tag'`.\n */\n tag?: string\n /**\n * Path value used when `group.type === 'path'`.\n */\n path?: string\n}\n\n/**\n * Options for `resolver.file` and `resolver.default.file`: the file request (`name`, `extname`,\n * `tag`, `path`) plus where the output goes (`root`, `output`, `group`).\n *\n * @example\n * ```ts\n * resolver.default.file({ name: 'listPets', extname: '.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })\n * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }\n * ```\n */\nexport type ResolveFileOptions = ResolverFileParams & {\n root: string\n output: Output\n group?: Group\n}\n\n/**\n * Options for `resolver.imports`: the schema tree to scan (`node`) and where the generated\n * files live (`root`, `output`, `group`). Pass `name` to override how a referenced schema\n * name becomes the imported identifier; it defaults to the resolver's top-level `name`.\n *\n * @example\n * ```ts\n * resolver.imports({ node, root, output, group })\n * // → [{ kind: 'Import', name: ['pet'], path: '/src/types/pet.ts' }]\n * ```\n */\nexport type ResolveImportsOptions = {\n /**\n * Schema tree scanned for `$ref` occurrences. Each ref contributes one import entry.\n */\n node: SchemaNode\n root: string\n output: Output\n group?: Group\n /**\n * Extension of the generated files the imports point at.\n *\n * @default '.ts'\n */\n extname?: FileNode['extname']\n /**\n * Overrides how a referenced schema name becomes the imported identifier, for example to\n * point enum refs at a suffixed type name. Defaults to the resolver's top-level `name`.\n */\n name?: (schemaName: string) => string\n}\n\n/**\n * The `file` field of a resolver: decides what a generated file is called and, optionally, where\n * it lives. This is how a resolver renames or relocates its files, replacing the older per-call\n * `resolveName` hook.\n *\n * @example Suffix every generated file\n * ```ts\n * file: {\n * baseName({ name, extname }) {\n * return `${name}Faker${extname}`\n * },\n * }\n * ```\n *\n * @example Own the full path\n * ```ts\n * file: {\n * path({ baseName, output }) {\n * return `${output.path}/mocks/${baseName}`\n * },\n * }\n * ```\n */\nexport type ResolverFile = {\n /**\n * Builds the file's complete base name, extension included, from the identifier and the target\n * `extname`. Defaults to `toFilePath(name)` with `extname` appended. Reaches sibling resolver\n * helpers through `this`.\n */\n baseName?(params: Pick<ResolverFileParams, 'name' | 'extname'>): FileNode['baseName']\n /**\n * Returns the file's complete path, resolved against the project `root`. Bypasses `output.path`\n * and `group`, so the resolver owns the layout. The returned path may not escape `root`. Reaches\n * sibling resolver helpers through `this`.\n */\n path?(params: ResolverFilePathParams): string\n}\n\n/**\n * The argument to a resolver's `file.path`: the resolved `baseName` (what `file.baseName` produced,\n * with the extension already appended) and the active `output`. `tag`, `path`, and `group` are\n * omitted because `file.path` owns the whole path and bypasses grouping, and `root` because the\n * returned path is resolved against it.\n */\nexport type ResolverFilePathParams = {\n baseName: FileNode['baseName']\n output: Output\n}\n\n/**\n * Per-file context describing the file a banner/footer is being resolved for, so a\n * `banner`/`footer` function can branch on the file kind (e.g. skip a `'use server'`\n * directive on re-export files).\n */\nexport type ResolveBannerFile = {\n /**\n * Full output path of the file being generated.\n */\n path: string\n /**\n * File name only, e.g. `'stocks.ts'`.\n */\n baseName: string\n /**\n * `true` for `index.ts` re-export barrels.\n */\n isBarrel?: boolean\n /**\n * `true` for group `[dir]/[dir].ts` aggregation files.\n */\n isAggregation?: boolean\n}\n\n/**\n * Document metadata extended with per-file context, passed to a `banner`/`footer` function.\n *\n * @example Skip a directive on re-export files\n * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : \"'use server'\"`\n */\nexport type BannerMeta = InputMeta & {\n /**\n * Full output path of the file being generated.\n */\n filePath: string\n /**\n * File name only, e.g. `'stocks.ts'`.\n */\n baseName: string\n /**\n * `true` for `index.ts` re-export barrels.\n */\n isBarrel: boolean\n /**\n * `true` for group `[dir]/[dir].ts` aggregation files.\n */\n isAggregation: boolean\n}\n\n/**\n * Context passed to `resolver.default.banner` and `resolver.default.footer`.\n * `output` is optional since not every plugin configures a banner/footer, and `config`\n * carries the global Kubb config used to derive the default Kubb banner.\n */\nexport type ResolveBannerContext = {\n output?: Pick<Output, 'banner' | 'footer'>\n config: Config\n file?: ResolveBannerFile\n}\n\n/**\n * Raw resolver fields passed to `createResolver` or patched through `Resolver.merge`.\n * `default` is the built-in machinery and is not user-settable.\n */\nexport type ResolverBuildOptions = {\n pluginName: string\n name?: (name: string) => string\n file?: ResolverFile\n}\n\n/**\n * Partial resolver fields accepted by `Resolver.merge` and `setResolver`. Parameterize with a\n * concrete resolver type (e.g. `ResolverPatch<ResolverTs>`) to type-check overrides and bind\n * `this` to the full resolver. Namespaces are partial, so a patch may override a single method\n * (`query.name`) and the rest keep the plugin defaults. Overriding a whole resolver is not the\n * job of this patch, that is what a custom plugin is for.\n */\nexport type ResolverPatch<T extends Resolver = Resolver> = {\n [K in keyof Omit<T, keyof Resolver>]?: T[K] extends (...args: Array<never>) => unknown ? T[K] : Partial<T[K]>\n} & {\n imports?: T['imports']\n name?: T['name']\n file?: ResolverFile\n} & ThisType<T>\n\nfunction isNamespace(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of\n * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own\n * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay\n * reachable and a `file` override is never dropped.\n */\nconst resolverOptions: unique symbol = Symbol.for('@kubb/core/resolver/options')\n\n/**\n * Builds a nested file path from a dotted name. Splits on dots that precede a letter\n * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases\n * every segment, and joins with `/`.\n *\n * Empty segments are dropped before joining. They arise when the name starts with a dot\n * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to\n * an empty string). Without this a leading `/` would form, which `path.resolve` reads as an\n * absolute path, letting generated files escape the configured output directory.\n *\n * @example Nested path from a dotted name\n * `toFilePath('pet.petId') // 'pet/petId'`\n */\nexport function toFilePath(name: string): string {\n return name\n .split(/\\.(?=[a-zA-Z])/)\n .map((part) => camelCase(part))\n .filter(Boolean)\n .join('/')\n}\n\n/** Throws `KUBB_PATH_TRAVERSAL` when `target` lies outside `parent`; `target === parent` stays allowed. */\nfunction assertInside({ target, parent, message, help }: { target: string; parent: string; message: string; help: string }): void {\n const parentWithSep = parent.endsWith(path.sep) ? parent : `${parent}${path.sep}`\n if (target === parent || target.startsWith(parentWithSep)) return\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message,\n help,\n location: { kind: 'config' },\n })\n}\n\n/**\n * Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.\n */\nfunction toBaseName({ name, extname }: Pick<ResolverFileParams, 'name' | 'extname'>): FileNode['baseName'] {\n return `${toFilePath(name)}${extname}` as FileNode['baseName']\n}\n\n/**\n * Base constraint for all plugin resolver objects.\n *\n * The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,\n * and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with\n * top-level helpers (`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 /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */\n readonly default: ResolverDefault\n #options: ResolverBuildOptions\n // Base-name builder from `options.file.baseName`, bound to the resolver so it can reach `this`.\n // Defaults to `toBaseName` when a resolver sets no `file.baseName`.\n #baseName: (params: Pick<ResolverFileParams, 'name' | 'extname'>) => FileNode['baseName']\n // Full-path override from `options.file.path`, bound to the resolver. Absent by default, in which\n // case the built-in `output.path`/`group` layout is used.\n #filePath: ((params: ResolverFilePathParams) => string) | undefined\n\n constructor(options: ResolverBuildOptions) {\n this.pluginName = options.pluginName\n this.#options = options\n this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName\n this.#filePath = options.file?.path ? options.file.path.bind(this) : undefined\n this.default = {\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 this.#apply(options)\n }\n\n /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */\n get [resolverOptions](): ResolverBuildOptions {\n return this.#options\n }\n\n name(name: string): string {\n return this.default.name(name)\n }\n\n file(options: ResolveFileOptions): FileNode {\n return this.#resolveFile(options)\n }\n\n /**\n * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence\n * order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed\n * schemas (`targetName`) import the emitted name. Names and paths go through the top-level\n * `name` and `file`, so import entries follow the plugin's conventions, and a per-call\n * `name` override wins over both.\n *\n * The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a\n * schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver\n * reads the same ref set instead of re-scanning it per plugin.\n */\n imports(options: ResolveImportsOptions): Array<ImportNode> {\n const { node, root, output, group, extname = '.ts', name } = options\n const resolveName = name ?? ((schemaName: string) => this.name(schemaName))\n\n return collectImportedRefNames(node).map((schemaName) =>\n ast.factory.createImport({\n name: [resolveName(schemaName)],\n path: this.file({ name: schemaName, extname, root, output, group }).path,\n }),\n )\n }\n\n /**\n * Folds each `override` over `base`, left to right, and returns a new resolver with helpers\n * re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding\n * `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying\n * `setResolver` partial overrides, and to compose shared resolver fragments without spreading each\n * namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,\n * so a `file` override survives even when `base` and `override` come from different `@kubb/core`\n * copies.\n *\n * @example Fold several partial overrides onto a resolver\n * ```ts\n * const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })\n * ```\n */\n static merge<T extends Resolver>(base: T, ...overrides: Array<ResolverPatch<T> | Resolver>): T {\n const merged = overrides.reduce<Record<string, unknown>>(\n (acc, override) => {\n const patch = resolverOptions in override ? override[resolverOptions] : override\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue\n const current = acc[key]\n acc[key] = isNamespace(value) && isNamespace(current) ? { ...current, ...value } : value\n }\n return acc\n },\n { ...base[resolverOptions] },\n )\n return new Resolver(merged as ResolverBuildOptions) as T\n }\n\n /**\n * Binds each entry of `options` onto the resolver, so `this.name`, `this.default`, and\n * `this.file` resolve there for top-level helpers and namespace methods alike. `default`\n * is skipped so it can't be shadowed.\n */\n #apply(options: ResolverBuildOptions): void {\n const root = this as Resolver & Record<string, unknown>\n const bind = (value: unknown) => (typeof value === 'function' ? value.bind(root) : value)\n\n for (const [key, value] of Object.entries(options)) {\n // `file` drives file naming through `#baseName`, not a top-level method, so it must not be\n // assigned here (it would shadow the `file` method with a plain `{ name }` object).\n if (key === 'pluginName' || key === 'default' || key === 'file' || value === undefined) continue\n root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value)\n }\n }\n\n static #testPattern(value: string, pattern: string | RegExp): boolean {\n if (typeof pattern === 'string') {\n let regex = Resolver.#patternCache.get(pattern)\n regex ??= new RegExp(pattern)\n Resolver.#patternCache.set(pattern, regex)\n return regex.test(value)\n }\n // Use .match() for user-supplied RegExp to preserve semantics regardless of `g`/`y` flags.\n return value.match(pattern) !== null\n }\n\n static #matchesOperation(node: OperationNode, filter: Filter): boolean {\n if (filter.type === 'extension') {\n const { extensions } = node\n return extensions !== undefined && Object.hasOwn(extensions, filter.key) && (filter.value === undefined || extensions[filter.key] === filter.value)\n }\n\n const { type, pattern } = filter\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, filter: Filter): boolean | null {\n if (filter.type === 'schemaName') return node.name ? Resolver.#testPattern(node.name, filter.pattern) : false\n return null\n }\n\n static #computeOptions<TOptions>(node: Node, { options, exclude = [], include, override = [] }: ResolveOptionsContext<TOptions>): TOptions | null {\n if (node.kind === 'Operation') {\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 (node.kind === 'Schema') {\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'` (default) resolves directly to `output.path`. `mode: 'directory'` resolves\n * to `output.path/{baseName}`, or into a subdirectory when `group` and a `tag`/`path` value\n * are provided.\n */\n #resolvePath({ baseName, tag, path: groupPath, root, output, group }: ResolvePathOptions): string {\n if (output.mode !== 'directory') {\n return path.resolve(root, output.path)\n }\n\n const outputDir = path.resolve(root, output.path)\n // A file without the value its group needs (an SDK class per tag, grouped by path) is not grouped.\n const groupValue = group?.type === 'path' ? groupPath : tag\n const result = group && groupValue ? path.resolve(outputDir, Resolver.#resolveGroupDir(group, groupValue), baseName) : path.resolve(outputDir, baseName)\n\n assertInside({\n target: result,\n parent: outputDir,\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 })\n\n return result\n }\n\n /**\n * Resolves a resolver-supplied full path (`file.path`) against `root`, bypassing `output.path`\n * and `group`. The path may not escape `root`, which keeps a `file.path` that interpolates\n * spec-derived values from writing outside the project.\n */\n #resolveOverridePath(filePath: string, root: string): string {\n const resolved = path.resolve(root, filePath)\n assertInside({\n target: resolved,\n parent: root,\n message: `Resolved path \"${resolved}\" is outside the project root \"${root}\".`,\n help: 'A resolver `file.path` must return a path inside the project root.',\n })\n\n return resolved\n }\n\n /**\n * Builds a `FileNode`. When `#filePath` (the resolver's `file.path`) is set it owns the whole\n * path; otherwise the base name (from `#baseName`, the resolver's `file.baseName` or the\n * built-in `toBaseName`) is placed by the `output.path`/`group` layout. The resolved file starts\n * with empty `sources`, `imports`, and `exports`, which consumers populate separately.\n */\n #resolveFile(options: ResolveFileOptions): FileNode {\n const { name, extname, tag, path: groupPath, root, output, group } = options\n const baseName = this.#baseName({ name, extname })\n const filePath = this.#filePath\n ? this.#resolveOverridePath(this.#filePath({ baseName, output }), root)\n : this.#resolvePath({ baseName, tag, path: groupPath, root, output, group })\n\n return ast.factory.createFile({\n path: filePath,\n baseName: path.basename(filePath) as `${string}.${string}`,\n meta: {\n pluginName: this.pluginName,\n },\n sources: [],\n imports: [],\n exports: [],\n })\n }\n\n /**\n * Missing fields default to empty/`false` so the `BannerMeta` shape stays stable even when\n * a caller (e.g. the barrel plugin) has no document metadata.\n */\n static #buildBannerMeta(meta: InputMeta | undefined, file: ResolveBannerFile | undefined): BannerMeta {\n return {\n title: meta?.title,\n description: meta?.description,\n version: meta?.version,\n baseURL: meta?.baseURL,\n circularNames: meta?.circularNames ?? [],\n enumNames: meta?.enumNames ?? [],\n filePath: file?.path ?? '',\n baseName: file?.baseName ?? '',\n isBarrel: file?.isBarrel ?? false,\n isAggregation: file?.isAggregation ?? false,\n }\n }\n\n /**\n * Resolves a user-configured banner/footer value. `undefined` means not configured.\n */\n static #resolveUserText(\n value: string | ((meta: BannerMeta) => string) | undefined,\n meta: InputMeta | undefined,\n file: ResolveBannerFile | undefined,\n ): string | undefined {\n if (typeof value === 'function') return value(Resolver.#buildBannerMeta(meta, file))\n if (typeof value === 'string') return value\n return undefined\n }\n\n static #buildDefaultBanner({ title, version, config }: { title?: string; version?: string; config: Config }): string {\n const lines = ['/**', '* Generated by Kubb (https://kubb.dev/).', '* Do not edit manually.']\n\n if (config.output.defaultBanner !== 'simple') {\n const input = config.input\n const source = typeof input === 'string' ? (getInputKind(input) === 'inline' ? 'text content' : path.basename(input)) : 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","import type { PluginType } from './definePlugin.ts'\nimport { Resolver, type ResolverBuildOptions, type ResolverFile } from './Resolver.ts'\n\n/**\n * The plugin-specific resolver fields handed to `createResolver`. `name` and `file` fall\n * back to the built-ins when omitted. Every method reaches sibling helpers through `this`,\n * which `ThisType` types as the full resolver.\n */\ntype ResolverOptions<T extends PluginType> = Omit<T['resolver'], keyof Resolver> & {\n pluginName: T['name']\n name?: T['resolver']['name']\n file?: ResolverFile\n} & ThisType<T['resolver']>\n\n/**\n * Defines a plugin resolver, the object that decides what every generated symbol and file\n * path is called. Override the top-level `name` and `file` to set the plugin's conventions,\n * and add your own naming helpers, top-level (`typeName`, …) or grouped in namespaces\n * (`query`, `schema`, …). Every method reaches sibling helpers and the built-in machinery\n * through `this.name`, `this.file`, and `this.default`.\n *\n * @example Custom identifier casing\n * ```ts\n * export const resolverTs = createResolver<PluginTs>({\n * pluginName: 'plugin-ts',\n * name(name) {\n * return ensureValidVarName(pascalCase(name))\n * },\n * })\n * ```\n *\n * @example Rename generated files with `file.baseName`\n * ```ts\n * export const resolverFaker = createResolver<PluginFaker>({\n * pluginName: 'plugin-faker',\n * name(name) {\n * return camelCase(name, { prefix: 'create' })\n * },\n * file: {\n * baseName({ name, extname }) {\n * return `${camelCase(name, { prefix: 'create' })}${extname}`\n * },\n * },\n * })\n * ```\n *\n * @example Own the full path with `file.path`\n * ```ts\n * export const resolverFaker = createResolver<PluginFaker>({\n * pluginName: 'plugin-faker',\n * file: {\n * path({ baseName, output }) {\n * return `${output.path}/mocks/${baseName}`\n * },\n * },\n * })\n * ```\n */\nexport function createResolver<T extends PluginType>(options: ResolverOptions<T>): T['resolver'] {\n return new Resolver(options as unknown as ResolverBuildOptions) as T['resolver']\n}\n","import { readFile } from 'node:fs/promises'\nimport { inParallel, matchesStored, toError } from '@internals/utils'\nimport { ast, extractStringsFromNodes, type CodeNode, type FileNode } from '@kubb/ast'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { Storage } from './createStorage.ts'\nimport type { Parser } from './defineParser.ts'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { OutputManifest } from './outputManifest.ts'\nimport type { Hookable } from './Hookable.ts'\nimport type { Config, KubbFileProcessingUpdate, KubbHooks } from './types.ts'\n\n/** Files kept in flight at once, writing the output and reading it back for the manifest. */\nexport const FILE_CONCURRENCY = 50\n\ntype ParseOptions = {\n parsers?: Map<FileNode['extname'], Parser>\n}\n\ntype WriteOptions = ParseOptions & {\n storage: Storage\n signal?: AbortSignal\n /**\n * Consulted before each write so a file the output passes already normalized is recognized as\n * unchanged. Omitted when no formatter, linter, or `postGenerate` step is configured.\n */\n manifest?: OutputManifest\n /**\n * Receives `kubb:files:processing:start`, `:update` (in input order, as files finish) and `:end` for the write. `config` fills the update rows.\n */\n hooks?: Hookable<KubbHooks>\n config?: Config\n}\n\nfunction joinSources(file: FileNode): string {\n return file.sources\n .map((source) => extractStringsFromNodes(source.nodes as Array<CodeNode>))\n .filter(Boolean)\n .join('\\n\\n')\n}\n\n/** Runs a parser call and turns a crash into a `KUBB_PARSER_FAILED` diagnostic that names the parser. */\nfunction runParser(parser: Parser, print: () => string): string {\n try {\n return print()\n } catch (error) {\n throw new Diagnostics.Error(Diagnostics.fromExtension(error, { kind: 'parser', extension: parser }))\n }\n}\n\n/**\n * Reads a `copy` file and prints it through the parser's `copy` hook, or verbatim with `banner`/`footer` when there is none.\n */\nasync function parseCopy(file: FileNode, parser: Parser | undefined): Promise<string> {\n const content = await readFile(file.copy as string, 'utf8').catch((err) => {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pluginFailed,\n severity: 'error',\n message: `Could not copy file into output: ${file.copy}`,\n help: 'Check that the file a plugin copies into the output exists and is readable.',\n cause: toError(err),\n })\n })\n\n if (parser?.copy) {\n return runParser(parser, () => parser.parse(ast.factory.createFile(parser.copy!(file, content))))\n }\n\n return [file.banner, content, file.footer]\n .filter((segment): segment is string => Boolean(segment))\n .map((segment) => segment.trimEnd())\n .join('\\n')\n}\n\nfunction mergeFile<TMeta extends object = object>(a: FileNode<TMeta>, b: FileNode<TMeta>): FileNode<TMeta> {\n return {\n ...a,\n // Incoming file (b) takes precedence for banner/footer so a barrel file (whose\n // banner/footer the barrel plugin resolves last) wins over a plugin-generated\n // file at the same path.\n banner: b.banner,\n footer: b.footer,\n // A verbatim-copy file cannot be merged with rendered content; the incoming `copy` wins.\n copy: b.copy ?? a.copy,\n sources: [...a.sources, ...b.sources],\n imports: [...a.imports, ...b.imports],\n exports: [...a.exports, ...b.exports],\n }\n}\n\nfunction isIndexPath(path: string): boolean {\n return path.endsWith('/index.ts') || path === 'index.ts'\n}\n\n// Sort order: shortest path first. Within a length bucket, index.ts barrels last.\nfunction compareFiles(a: FileNode, b: FileNode): number {\n return a.path.length - b.path.length || Number(isIndexPath(a.path)) - Number(isIndexPath(b.path))\n}\n\n/**\n * Writes `source` to `file.path` unless the storage already holds it, either verbatim or, per the\n * manifest, as what the output passes make of it. Checking here rather than in a driver gives a\n * storage writing to S3 or a database the same guarantee `fsStorage` has. `false` when skipped.\n */\nasync function writeChanged({\n storage,\n manifest,\n file,\n source,\n signal,\n}: Pick<WriteOptions, 'storage' | 'manifest' | 'signal'> & { file: FileNode; source: string }): Promise<boolean> {\n signal?.throwIfAborted()\n const stored = await storage.readItem(file.path)\n if (stored !== null && (matchesStored({ stored, source }) || manifest?.isUpToDate({ key: file.path, source, disk: stored }))) return false\n signal?.throwIfAborted()\n await storage.writeItem(file.path, source, { stored })\n // Only a file that was written can have been changed by the output passes.\n manifest?.track({ key: file.path, source })\n return true\n}\n\n/** Reports finished files in input order: each finished file flushes the run of finished files ahead of it as one update. */\nfunction createProgress(files: Array<FileNode>, config: Config, hooks: Hookable<KubbHooks>): (index: number) => Promise<void> {\n const finished: Array<boolean> = []\n let flushed = 0\n return async (index) => {\n finished[index] = true\n // Rows leave `source` out: buffering it would hold every generated file in memory.\n const updates: Array<KubbFileProcessingUpdate> = []\n while (finished[flushed]) {\n flushed++\n updates.push({ file: files[flushed - 1]!, processed: flushed, total: files.length, percentage: (flushed / files.length) * 100, config })\n }\n if (updates.length) await hooks.callHook('kubb:files:processing:update', { files: updates })\n }\n}\n\n/**\n * In-memory file store for generated files, and the writer that turns them into source\n * strings on `storage`. Files sharing a `path` are merged (sources/imports/exports\n * concatenated). The `files` getter is sorted by path length (barrel `index.ts` last\n * within a bucket).\n *\n * @example\n * ```ts\n * const manager = new FileManager()\n * manager.upsert(myFile)\n * manager.files // sorted view\n * await manager.write(manager.files, { storage: fsStorage() })\n * ```\n */\nexport class FileManager {\n readonly #cache = new Map<string, FileNode>()\n // Cached sorted view, rebuilt lazily on the next `files` read. Nulled (not mutated) on every\n // write so callers holding a prior reference keep their snapshot, `dispose()` included.\n #sorted: Array<FileNode> | null = null\n\n add(...files: Array<FileNode>): Array<FileNode> {\n return this.#store(files, false)\n }\n\n upsert(...files: Array<FileNode>): Array<FileNode> {\n return this.#store(files, true)\n }\n\n /** Stores a generator result: a file array is upserted as is, an element renders through `renderer` first, falsy is a no-op. */\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.upsert(...(result as Array<FileNode>))\n return\n }\n\n if (!renderer) return\n\n using instance = renderer()\n await instance.render(result)\n\n this.upsert(...instance.files)\n }\n\n #store(files: ReadonlyArray<FileNode>, mergeExisting: boolean): Array<FileNode> {\n // Same-path files in one batch always merge; an existing file only on upsert.\n const batch = new Set<string>()\n const resolved = files.map((file) => {\n const existing = this.#cache.get(file.path)\n const merged = ast.factory.createFile(existing && (mergeExisting || batch.has(file.path)) ? mergeFile(existing, file) : file)\n this.#cache.set(merged.path, merged)\n batch.add(merged.path)\n return merged\n })\n if (resolved.length > 0) this.#sorted = null\n return resolved\n }\n\n /**\n * Releases all stored files. Called by the core after `kubb:build:end`.\n */\n dispose(): void {\n this.#cache.clear()\n this.#sorted = null\n }\n\n /**\n * All stored files in stable sort order (shortest path first, barrel files\n * last within a length bucket). Returns a cached view, do not mutate.\n */\n get files(): Array<FileNode> {\n return (this.#sorted ??= [...this.#cache.values()].sort(compareFiles))\n }\n\n /**\n * Converts a file's AST sources (or its `copy` source) into the final on-disk string.\n */\n async parse(file: FileNode, { parsers }: ParseOptions = {}): Promise<string> {\n const parser = parsers?.get(file.extname)\n\n if (file.copy) {\n return parseCopy(file, parser)\n }\n\n if (!parser) {\n return joinSources(file)\n }\n\n return runParser(parser, () => parser.parse(file))\n }\n\n /**\n * Parses and writes every file through a bounded pool of workers. A small spec runs all its files\n * at once; a spec with thousands of files keeps at most {@link FILE_CONCURRENCY} parsed sources in\n * memory rather than holding every source, while still overlapping each file's write with the\n * next file's parse. Files finish in whatever order they parse, so each finished file flushes the\n * run of finished files ahead of it as one `kubb:files:processing:update`, keeping rows in input order.\n *\n * A file the storage already holds is skipped, so a rebuild that generates identical output\n * writes nothing and leaves every mtime where it was. `kubb:files:processing:end` lists the\n * skipped paths as `unchanged`.\n */\n async write(files: Array<FileNode>, { storage, parsers, manifest, signal, hooks, config }: WriteOptions): Promise<void> {\n if (files.length === 0) return\n\n await hooks?.callHook('kubb:files:processing:start', { files })\n const unchanged: Array<string> = []\n const progress = hooks && config ? createProgress(files, config, hooks) : undefined\n\n await inParallel({\n items: files,\n limit: FILE_CONCURRENCY,\n run: async (file, index) => {\n signal?.throwIfAborted()\n const source = await this.parse(file, { parsers })\n if (source && !(await writeChanged({ storage, manifest, file, source, signal }))) unchanged.push(file.path)\n await progress?.(index)\n },\n })\n\n await hooks?.callHook('kubb:files:processing:end', { files, unchanged })\n }\n}\n","/**\n * Per-node memo shared by every plugin that generates from the same schema or operation node in\n * one generate pass. The driver creates one `NodeCache` per node during the walk and hands the\n * same instance to each plugin's generator context, so work derived purely from the node (its\n * resolved name, imports, parameters) is computed by the first plugin that needs it and reused by\n * the rest instead of being recomputed per plugin.\n *\n * Keys are namespaced by convention (`'plugin-ts:imports'`) so two plugins caching different\n * derivations of the same node never collide.\n *\n * @example Fill on first read, reuse afterwards\n * ```ts\n * const imports = ctx.cache.ensureItem('plugin-ts:imports', () => ctx.resolver.imports({ node, root, output }))\n * ```\n */\nexport type NodeCache = {\n /**\n * Returns the value stored under `key`, or `undefined` when nothing is stored yet.\n */\n readItem<TValue>(key: string): TValue | undefined\n /**\n * Stores `value` under `key`, overwriting any previous value, and returns it.\n */\n writeItem<TValue>(key: string, value: TValue): TValue\n /**\n * Returns the value stored under `key`, computing and storing it with `factory` on the first\n * call. Later calls with the same key return the stored value without running `factory` again.\n */\n ensureItem<TValue>(key: string, factory: () => TValue): TValue\n}\n\n/**\n * Builds an empty {@link NodeCache} backed by a plain `Map`. Called once per node in the generate\n * walk.\n */\nexport function createNodeCache(): NodeCache {\n const store = new Map<string, unknown>()\n\n return {\n readItem<TValue>(key: string): TValue | undefined {\n return store.get(key) as TValue | undefined\n },\n writeItem<TValue>(key: string, value: TValue): TValue {\n store.set(key, value)\n return value\n },\n ensureItem<TValue>(key: string, factory: () => TValue): TValue {\n if (store.has(key)) return store.get(key) as TValue\n\n const value = factory()\n store.set(key, value)\n return value\n },\n }\n}\n","import { resolve } from 'node:path'\nimport { escapePointerToken, getElapsedMs, toError } from '@internals/utils'\nimport { ast, collectUsedSchemaNames, type Enforce, type FileNode, type InputMeta, type InputNode, type OperationNode, type SchemaNode } from '@kubb/ast'\nimport { type Diagnostic, type DiagnosticLocation, Diagnostics, type ProblemDiagnostic } from './Diagnostics.ts'\nimport type { Generator, GeneratorContext } from './defineGenerator.ts'\nimport type { Parser } from './defineParser.ts'\nimport type { KubbPluginSetupContext, Plugin, PluginName, ResolvePluginOptions, Group, NormalizedPlugin, PluginType } from './definePlugin.ts'\nimport { normalizeOutput } from './definePlugin.ts'\nimport { checkCompatibility, checkDependencies, resolveMeta } from './defineExtension.ts'\nimport { kubbContext } from './composables.ts'\nimport { createResolver } from './createResolver.ts'\nimport { Resolver } from './Resolver.ts'\nimport { FileManager } from './FileManager.ts'\nimport { createNodeCache } from './nodeCache.ts'\nimport type { OutputManifest } from './outputManifest.ts'\nimport { checkoutGitInput, gitInputRegExp } from './gitInput.ts'\nimport { inputToAdapterSource } from './input.ts'\n\nimport type { Config, KubbHooks } from './types.ts'\nimport type { Adapter, AdapterSource } from './createAdapter.ts'\nimport type { Hookable } from './Hookable.ts'\n\ntype Options = {\n hooks: Hookable<KubbHooks>\n signal?: AbortSignal\n /**\n * Passed to `fileManager.write` so files the output passes already normalized are left alone.\n */\n manifest?: OutputManifest\n /**\n * The output directory `output.clean` empties. Emptied right before the files are written, so a\n * run that fails earlier leaves the previous output in place.\n */\n cleanPath?: string\n}\n\ntype RequirePluginContext = {\n /**\n * Name of the plugin that declared the dependency, included in the error so users can\n * trace which plugin needs the missing one.\n */\n requiredBy?: string\n}\n\nconst ENFORCE_ORDER = { pre: -1, post: 1 } satisfies Record<Enforce, number>\n\n/** `include` filter types that select operations, and so prune the schemas they do not reach. */\nconst OPERATION_FILTER_TYPES: ReadonlySet<string> = new Set(['tag', 'operationId', 'path', 'method', 'contentType', 'extension'])\n\nconst enforceWeight = (plugin: NormalizedPlugin): number => (plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0)\n\n/**\n * The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output\n * at the plugin root and empty filter lists.\n */\nconst defaultPluginOptions = (): NormalizedPlugin['options'] => ({ output: { path: '.', mode: 'directory' }, exclude: [], override: [] })\n\n/**\n * Fills in the `output`, `exclude`, and `override` a `NormalizedPlugin` needs from a plugin's raw\n * options, running `output` through `normalizeOutput`. Idempotent, so the driver can apply it after\n * `setOptions` has already run without disturbing an already-normalized bag.\n */\nfunction normalizePluginOptions(rawOptions: Plugin['options'], pluginName: string): NormalizedPlugin['options'] {\n const options: NormalizedPlugin['options'] = { ...defaultPluginOptions(), ...(rawOptions ?? {}) }\n const group = 'group' in options ? (options.group as Group | null | undefined) : undefined\n options.output = normalizeOutput({ output: options.output, group, pluginName })\n return options\n}\n\n/**\n * Throws `KUBB_INVALID_PLUGIN_OPTIONS` when a `plugins` entry is not a plugin object, such as a\n * factory passed without calling it.\n */\nfunction assertPluginEntry(entry: unknown, index: number): asserts entry is Plugin {\n if (typeof entry === 'function') {\n const name = entry.name || 'pluginName'\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `plugins[${index}] is a function (\"${name}\"), not a plugin.`,\n help: `Call it: ${name}()`,\n location: { kind: 'config' },\n })\n }\n if (typeof entry !== 'object' || entry === null) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `plugins[${index}] is ${entry === null ? 'null' : typeof entry}, not a plugin.`,\n help: 'Pass the result of a plugin factory, for example `pluginTs()`, or remove the entry.',\n location: { kind: 'config' },\n })\n }\n}\n\n/**\n * Where a generator crashed: a label naming the node and, when the node has one, a JSON pointer\n * to it. Built from the node fields so core stays adapter-agnostic.\n */\nfunction getCrashSite(node: SchemaNode | OperationNode): { label: string; location?: DiagnosticLocation } {\n if (node.kind === 'Schema') {\n return node.name\n ? { label: `schema \"${node.name}\"`, location: { kind: 'schema', pointer: `#/components/schemas/${escapePointerToken(node.name)}` } }\n : { label: 'an inline schema' }\n }\n if (!node.method || !node.path) return { label: `operation \"${node.operationId}\"` }\n return {\n label: `operation \"${node.operationId}\" (${node.method.toUpperCase()} ${node.path})`,\n location: { kind: 'operation', pointer: `#/paths/${escapePointerToken(node.path)}/${node.method.toLowerCase()}` },\n }\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 * Removers for every listener the driver added (plugin, generator) so `dispose()` can detach\n * them in one pass. External `hooks.hook(...)` listeners are not tracked.\n */\n readonly #unhooks: Array<() => void> = []\n\n constructor(config: Config, options: Options) {\n this.config = config\n this.options = options\n this.adapter = config.adapter ?? null\n }\n\n /**\n * Checks the adapter's and parsers' `meta.compatibility`, then normalizes and checks 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 this.options.signal?.throwIfAborted()\n for (const extension of [this.config.adapter, ...this.config.parsers]) {\n if (extension?.meta) checkCompatibility(extension.meta)\n }\n\n // Plugins are keyed by name, so a second entry with the same name would silently replace the first.\n const names = new Set<string>()\n const normalized = this.#sortPlugins(\n this.config.plugins.map((rawPlugin, index) => {\n assertPluginEntry(rawPlugin, index)\n if (rawPlugin.meta) checkCompatibility(rawPlugin.meta)\n\n const meta = resolveMeta(rawPlugin)\n if (names.has(meta.name)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `Plugin \"${meta.name}\" appears twice in \\`plugins\\`.`,\n help: 'Remove the duplicate, or merge its options.',\n location: { kind: 'config' },\n })\n }\n names.add(meta.name)\n const normalizedPlugin: NormalizedPlugin = {\n name: meta.name,\n meta,\n dependencies:\n typeof rawPlugin.dependencies === 'function' ? rawPlugin.dependencies(rawPlugin.options ?? {}, { config: this.config }) : rawPlugin.dependencies,\n enforce: rawPlugin.enforce,\n hooks: rawPlugin.hooks,\n setup: rawPlugin.setup,\n // `rawPlugin.options` is the user-supplied shape. The normalized `output`/`exclude`/`override`\n // bag is filled in by the post-setup `normalizePluginOptions` pass, after `setOptions` runs.\n options: (rawPlugin.options ?? defaultPluginOptions()) as NormalizedPlugin['options'],\n resolver: createResolver<PluginType>({ pluginName: meta.name }),\n }\n return normalizedPlugin\n }),\n )\n\n const byName = new Map(normalized.map((plugin) => [plugin.name, plugin]))\n for (const plugin of normalized) {\n checkDependencies({ name: plugin.name, dependencies: plugin.dependencies, plugins: byName })\n }\n\n for (const plugin of normalized) {\n this.#registerPlugin(plugin)\n this.plugins.set(plugin.name, plugin)\n }\n\n if (this.config.adapter) {\n this.#adapterSource = inputToAdapterSource(this.config)\n }\n }\n\n /**\n * Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with\n * `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks.\n * A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive\n * at the comparator level, so a chain where A depends on B and B depends on C could come out\n * wrong when A and C are never compared directly. Dependencies on plugins missing from the\n * config are ignored here and surface later through `requirePlugin`.\n */\n #sortPlugins(plugins: Array<NormalizedPlugin>): Array<NormalizedPlugin> {\n const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b))\n const names = new Set(queue.map((plugin) => plugin.name))\n const blockedBy = new Map(\n queue.map((plugin) => {\n const dependencies = Array.isArray(plugin.dependencies) ? plugin.dependencies : Object.keys(plugin.dependencies ?? {})\n return [plugin.name, new Set(dependencies.filter((name) => names.has(name) && name !== plugin.name))]\n }),\n )\n\n // One plugin leaves `queue` per pass, so iterating once per plugin drains it. Each pass takes\n // the lowest-index plugin with no remaining blockers, preserving enforce and declaration order.\n const sorted: Array<NormalizedPlugin> = []\n for (const _ of plugins) {\n const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0)\n if (index === -1) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(' → ')}.`,\n help: 'Remove one of the `dependencies` entries so the plugins can be ordered.',\n location: { kind: 'config' },\n })\n }\n\n const [plugin] = queue.splice(index, 1)\n if (!plugin) break\n\n sorted.push(plugin)\n for (const blockers of blockedBy.values()) blockers.delete(plugin.name)\n }\n\n return sorted\n }\n\n get hooks() {\n return this.options.hooks\n }\n\n /**\n * Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from\n * `run` do not re-parse.\n */\n async #parseInput(): Promise<void> {\n if (this.inputNode || !this.adapter || !this.#adapterSource) return\n\n this.options.signal?.throwIfAborted()\n const source = this.#adapterSource\n const checkout = source.type === 'path' && gitInputRegExp.test(source.path) ? await checkoutGitInput(source.path, this.options.signal) : undefined\n try {\n this.inputNode = await this.adapter.parse(checkout ? { type: 'path', path: checkout.path } : source, { signal: this.options.signal })\n } catch (caughtError) {\n throw new Diagnostics.Error(Diagnostics.fromExtension(caughtError, { kind: 'adapter', extension: this.adapter }))\n } finally {\n await checkout?.dispose()\n }\n }\n\n /**\n * Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that\n * external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for\n * `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a\n * plugin-scoped context.\n *\n * @internal\n */\n #registerPlugin(plugin: NormalizedPlugin): void {\n const { hooks } = plugin\n\n if (!hooks) return\n\n const { 'kubb:plugin:setup': _setup, ...configHooks } = hooks\n\n this.#unhooks.push(this.hooks.addHooks(configHooks))\n }\n\n /**\n * Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that\n * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its\n * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so\n * plugins can configure generators, resolvers, macros, and options before `buildStart`.\n */\n async setupHooks(): Promise<void> {\n for (const plugin of this.plugins.values()) {\n const setupHook = plugin.hooks?.['kubb:plugin:setup']\n if (!plugin.setup && !setupHook) continue\n\n const ctx: KubbPluginSetupContext = {\n config: this.config,\n options: plugin.options ?? {},\n addGenerator: (...generators) => {\n plugin.generators = [...(plugin.generators ?? []), ...generators]\n },\n setResolver: (resolver) => {\n plugin.resolver = Resolver.merge(createResolver<PluginType>({ pluginName: plugin.name }), resolver)\n },\n addMacro: (macro) => {\n plugin.macros = [...(plugin.macros ?? []), macro]\n },\n setMacros: (macros) => {\n plugin.macros = [...macros]\n },\n setOptions: (opts) => {\n plugin.options = normalizePluginOptions({ ...plugin.options, ...opts }, plugin.name)\n },\n injectFile: (userFileNode) => {\n this.fileManager.add(ast.factory.createFile(userFileNode))\n },\n requirePlugin: ((name: string) => this.requirePlugin(name, { requiredBy: plugin.name })) as KubbPluginSetupContext['requirePlugin'],\n }\n\n try {\n // Composables such as `addGenerator()` read `ctx` from `kubbContext`, also after an `await` in setup.\n await kubbContext.run(ctx, async () => {\n if (plugin.setup) {\n plugin.options = normalizePluginOptions(await plugin.setup(ctx.options, ctx), plugin.name)\n }\n await setupHook?.(ctx)\n })\n } catch (caughtError) {\n // Attributed to the plugin, so the run summary counts it as a failed plugin.\n throw new Diagnostics.Error(Diagnostics.fromExtension(caughtError, { kind: 'plugin', extension: plugin }))\n }\n }\n }\n\n /**\n * Runs the full plugin pipeline. Returns the diagnostics collected so far even\n * when an outer hook throws, since the orchestrator preserves partial state by capturing\n * the failure as a {@link Diagnostic} instead of propagating. Each plugin also\n * contributes a `timing` diagnostic for the run summary.\n */\n async run(): Promise<{ diagnostics: Array<Diagnostic> }> {\n const { hooks, config, fileManager } = this\n const diagnostics: Array<Diagnostic> = []\n const parsersMap = new Map<FileNode['extname'], Parser>()\n\n for (const parser of config.parsers) {\n if (parser.extNames) {\n for (const ext of parser.extNames) parsersMap.set(ext, parser)\n }\n }\n\n // 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 this.options.signal?.throwIfAborted()\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 await this.setupHooks()\n\n // Normalize each plugin's options once setup hooks have run, so the generate loop always\n // sees a filled-in bag whether or not the plugin called `setOptions`.\n for (const plugin of this.plugins.values()) {\n this.options.signal?.throwIfAborted()\n plugin.options = normalizePluginOptions(plugin.options, plugin.name)\n }\n\n if (this.adapter && this.inputNode) {\n const { meta, schemas, operations } = this.inputNode\n const buildStartContext = this.#withFiles({\n config,\n adapter: this.adapter,\n meta,\n nodeCounts: { schemas: schemas.length, operations: operations.length },\n getPlugin: this.getPlugin.bind(this),\n })\n await hooks.callHook('kubb:build:start', buildStartContext)\n }\n\n const generatorPlugins: Array<{\n plugin: NormalizedPlugin\n context: Omit<GeneratorContext, 'options' | 'cache'>\n hrStart: ReturnType<typeof process.hrtime>\n }> = []\n\n for (const plugin of this.plugins.values()) {\n const context = this.getContext(plugin)\n const hrStart = process.hrtime()\n\n try {\n await hooks.callHook('kubb:plugin:start', { plugin })\n } catch (caughtError) {\n const error = toError(caughtError)\n const duration = getElapsedMs(hrStart)\n\n await this.#emitPluginEnd({ plugin, duration, success: false, error })\n\n diagnostics.push(\n Diagnostics.fromExtension(error, { kind: 'plugin', extension: plugin }),\n Diagnostics.performance({ plugin: plugin.name, duration }),\n )\n\n continue\n }\n\n if ((plugin.generators?.length ?? 0) > 0) {\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 each plugin's macros and generators.\n diagnostics.push(...(await this.#runGenerators(generatorPlugins)))\n\n await hooks.callHook('kubb:plugins:end', this.#withFiles({ config }))\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 if (this.options.cleanPath) await config.storage.empty(this.options.cleanPath)\n\n await fileManager.write(fileManager.files, {\n storage: config.storage,\n parsers: parsersMap,\n manifest: this.options.manifest,\n signal: this.options.signal,\n hooks,\n config,\n })\n\n await hooks.callHook('kubb:build:end', { files: this.fileManager.files, config, outputDir: outputRoot })\n\n return { diagnostics: Diagnostics.dedupe(diagnostics) }\n } catch (caughtError) {\n diagnostics.push(Diagnostics.from(caughtError))\n return { diagnostics: Diagnostics.dedupe(diagnostics) }\n }\n },\n )\n }\n\n /**\n * Widens `extra` with the files present at emit time and a bound `upsertFile`, the shape every\n * file-carrying hook context shares. Building it here in one place keeps the `files` and\n * `upsertFile` keys from being dropped by a stray spread at the call site.\n */\n #withFiles<T extends object>(extra: T): T & { files: Array<FileNode>; upsertFile: (...files: Array<FileNode>) => Array<FileNode> } {\n return {\n ...extra,\n files: this.fileManager.files,\n upsertFile: (...files: Array<FileNode>) => this.fileManager.upsert(...files),\n }\n }\n\n #emitPluginEnd({ plugin, duration, success, error }: { plugin: NormalizedPlugin; duration: number; success: boolean; error?: Error }): Promise<void> | void {\n return this.hooks.callHook('kubb:plugin:end', this.#withFiles({ plugin, duration, success, ...(error ? { error } : {}), config: this.config }))\n }\n\n /**\n * Runs schemas and operations through every plugin's generators. The walk is node-outer: each\n * schema is visited once and each operation once, and the node fans out to the matching\n * generators of every plugin in dependency order. A per-node cache (`createNodeCache`) is created\n * once per node and shared by all of that node's plugins, so node-derived work is computed once\n * and reused instead of recomputed per plugin. Each node still runs through the plugin's macros\n * and its exclude/include/override filters before that plugin's\n * generator sees it, so plugins stay isolated. Schemas run before operations so file output\n * stays deterministic across runs. A generator with a `match` predicate that resolves `false`\n * for a node is skipped for that node, without calling `schema`/`operation`.\n *\n * A failing plugin is dropped from the remaining walk, contributes an error diagnostic, and no\n * longer aborts the other plugins. `kubb:plugin:end` and each plugin's `timing` diagnostic fire\n * in dependency order once the walk finishes, driving the CLI's `Plugins N/M` counter. The\n * `operations` batch fires once per plugin after the single operation walk.\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' | 'cache'>; 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 { schemas, operations } = this.inputNode\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 // Freeze each plugin's per-run state once so the node-outer walk stays cheap. A plugin's\n // `error` drops it from every remaining node without touching the others.\n const states = entries.map(({ plugin, context, hrStart }) => {\n const generatorContext = { ...context, resolver: this.getResolver(plugin.name) }\n const { exclude, include, override } = plugin.options\n const generators = plugin.generators ?? []\n return {\n plugin,\n hrStart,\n generatorContext,\n exclude,\n include,\n override,\n optionsAreStatic: !exclude?.length && !include?.length && !override?.length,\n allowedSchemaNames: allowedSchemaNamesByPlugin.get(plugin.name) ?? null,\n schemaGenerators: generators.filter((generator) => generator.schema),\n operationGenerators: generators.filter((generator) => generator.operation),\n operationsGenerators: generators.filter((generator) => generator.operations),\n pluginOperations: [] as Array<OperationNode>,\n error: null as Error | null,\n // The node a generator crashed on, so the diagnostic can name it.\n crashSite: undefined as ReturnType<typeof getCrashSite> | undefined,\n }\n })\n\n type PluginState = (typeof states)[number]\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. The\n // per-node dispatch and the collected-operations batch both go through this so they agree on\n // what the plugin sees.\n const resolveForPlugin = <TNode extends SchemaNode | OperationNode>(\n state: PluginState,\n node: TNode,\n ): { transformedNode: TNode; options: NormalizedPlugin['options'] } | null => {\n const transformedNode = ast.applyMacros(node, state.plugin.macros ?? [])\n if (state.optionsAreStatic) return { transformedNode, options: state.plugin.options }\n\n const options = state.generatorContext.resolver.default.options<NormalizedPlugin['options']>(transformedNode, {\n options: state.plugin.options,\n exclude: state.exclude,\n include: state.include,\n override: state.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. For each\n // node the plugins fan out in dependency order and share one cache. A caught error drops that\n // plugin from the rest of the walk but not the others, so its remaining nodes are skipped\n // rather than retried. Generators run directly; `kubb:generate:*` still fires for observers.\n for (const node of schemas) {\n const cache = createNodeCache()\n for (const state of states) {\n if (state.error || !state.schemaGenerators.length) continue\n try {\n const resolved = resolveForPlugin(state, node)\n if (!resolved) continue\n\n const { transformedNode, options } = resolved\n if (state.allowedSchemaNames !== null && transformedNode.name && !state.allowedSchemaNames.has(transformedNode.name)) continue\n\n const ctx = { ...state.generatorContext, options, cache }\n await this.#dispatchNode({\n generators: state.schemaGenerators,\n node: transformedNode,\n ctx,\n generate: (generator) => generator.schema!(transformedNode, ctx),\n })\n await this.hooks.callHook('kubb:generate:schema', transformedNode, ctx)\n } catch (caughtError) {\n state.error = toError(caughtError)\n state.crashSite = getCrashSite(node)\n }\n }\n }\n\n // One pass over operations feeds both the per-operation generators and the batch each plugin's\n // `operations` receives, so every node is transformed and filtered exactly once. A plugin with\n // only an `operations` generator still collects its filtered nodes here.\n for (const node of operations) {\n const cache = createNodeCache()\n for (const state of states) {\n if (state.error || (!state.operationGenerators.length && !state.operationsGenerators.length)) continue\n try {\n const resolved = resolveForPlugin(state, node)\n if (!resolved) continue\n\n state.pluginOperations.push(resolved.transformedNode)\n\n if (state.operationGenerators.length) {\n const { transformedNode } = resolved\n const ctx = { ...state.generatorContext, options: resolved.options, cache }\n await this.#dispatchNode({\n generators: state.operationGenerators,\n node: transformedNode,\n ctx,\n generate: (generator) => generator.operation!(transformedNode, ctx),\n })\n await this.hooks.callHook('kubb:generate:operation', transformedNode, ctx)\n }\n } catch (caughtError) {\n state.error = toError(caughtError)\n state.crashSite = getCrashSite(node)\n }\n }\n }\n\n // The `operations` batch fires once per plugin after the single operation walk, in dependency\n // order, with a fresh cache since it spans every node rather than one.\n for (const state of states) {\n if (state.error || !state.operationsGenerators.length) continue\n try {\n const ctx = { ...state.generatorContext, options: state.plugin.options, cache: createNodeCache() }\n for (const generator of state.operationsGenerators) {\n await this.fileManager.dispatch({ result: await generator.operations!(state.pluginOperations, ctx), renderer: generator.renderer })\n }\n await this.hooks.callHook('kubb:generate:operations', state.pluginOperations, ctx)\n } catch (caughtError) {\n state.error = toError(caughtError)\n }\n }\n\n // Close out every plugin in dependency order, so `kubb:plugin:end` and the timing diagnostics\n // still count up in plugin order for the CLI's `Plugins N/M` line.\n for (const state of states) {\n const duration = getElapsedMs(state.hrStart)\n await this.#emitPluginEnd({ plugin: state.plugin, duration, success: !state.error, error: state.error ?? undefined })\n\n if (state.error) {\n const diagnostic = Diagnostics.fromExtension(state.error, { kind: 'plugin', extension: state.plugin })\n // Only a crash gains the node it failed on. A coded error already says where it is.\n const site = diagnostic.code === Diagnostics.code.pluginFailed && !diagnostic.location ? state.crashSite : undefined\n diagnostics.push(\n site\n ? { ...diagnostic, message: `While generating ${site.label}: ${diagnostic.message}`, ...(site.location ? { location: site.location } : {}) }\n : diagnostic,\n )\n }\n diagnostics.push(Diagnostics.performance({ plugin: state.plugin.name, duration }))\n }\n\n return diagnostics\n }\n\n /**\n * Runs `node` through the generators whose `match` accepts it; `generate` picks the method for the\n * node kind.\n */\n async #dispatchNode({\n generators,\n node,\n ctx,\n generate,\n }: {\n generators: Array<Generator>\n node: SchemaNode | OperationNode\n ctx: GeneratorContext\n generate: (generator: Generator) => ReturnType<NonNullable<Generator['schema']>>\n }): Promise<void> {\n for (const generator of generators) {\n const matches = generator.match ? await generator.match(node, ctx) : true\n if (!matches) continue\n await this.fileManager.dispatch({ result: await generate(generator), renderer: generator.renderer })\n }\n }\n\n /**\n * Removes every listener the driver added. Listeners attached directly to `hooks` from outside\n * the driver survive. Called at the end of a build to prevent leaks across repeated builds.\n *\n * @internal\n */\n dispose(): void {\n for (const unhook of this.#unhooks) unhook()\n this.#unhooks.length = 0\n // 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 /** Reads `plugin.resolver`, falling back to a fresh default for a name that is not a registered plugin. */\n getResolver<TName extends PluginName>(pluginName: TName): ResolvePluginOptions<TName>['resolver']\n getResolver(pluginName: string): Resolver {\n return this.plugins.get(pluginName)?.resolver ?? createResolver<PluginType>({ pluginName })\n }\n\n getContext<TOptions extends PluginType>(plugin: NormalizedPlugin<TOptions>): Omit<GeneratorContext<TOptions>, 'options' | 'cache'> {\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 signal: driver.options.signal,\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, options) {\n report({ code: Diagnostics.code.pluginWarning, severity: 'warning', message, ...options })\n },\n error(error, options) {\n if (Diagnostics.isError(error)) {\n report({ ...options, ...error.diagnostic })\n return\n }\n const cause = typeof error === 'string' ? undefined : error\n report({ code: Diagnostics.code.pluginFailed, severity: 'error', message: typeof error === 'string' ? error : error.message, cause, ...options })\n },\n info(message, options) {\n report({ code: Diagnostics.code.pluginInfo, severity: 'info', message, ...options })\n },\n }\n }\n\n getPlugin<TName extends PluginName>(pluginName: TName): Plugin<ResolvePluginOptions<TName>> | 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 PluginName>(pluginName: TName, context?: RequirePluginContext): Plugin<ResolvePluginOptions<TName>>\n requirePlugin(pluginName: string, context?: RequirePluginContext): Plugin {\n const plugin = this.getPlugin(pluginName)\n if (plugin) return plugin\n\n throw pluginNotFoundError({ pluginName, requiredBy: context?.requiredBy })\n }\n}\n\n/** The `KUBB_PLUGIN_NOT_FOUND` error `requirePlugin` throws, naming the plugin that needed it. */\nexport function pluginNotFoundError({ pluginName, requiredBy }: { pluginName: string; requiredBy?: string }): InstanceType<typeof Diagnostics.Error> {\n const by = requiredBy ? ` by \"${requiredBy}\"` : ''\n const help = requiredBy ? ` (required by \"${requiredBy}\")` : ''\n\n return new Diagnostics.Error({\n code: Diagnostics.code.pluginNotFound,\n severity: 'error',\n message: `Plugin \"${pluginName}\" is required${by} but not found. Make sure it is included in your Kubb config.`,\n help: `Add \"${pluginName}\" to the \\`plugins\\` array in kubb.config.ts${help}, or remove the dependency on it.`,\n location: { kind: 'config' },\n ...(requiredBy ? { plugin: requiredBy } : {}),\n })\n}\n","import { hash } from 'node:crypto'\nimport { inParallel } from '@internals/utils'\nimport type { Storage } from './createStorage.ts'\nimport { FILE_CONCURRENCY } from './FileManager.ts'\n\n/**\n * Bumped when the stored shape changes, so an older cache is discarded instead of misread.\n */\nconst VERSION = 1\n\n/**\n * How one generated file looked on either side of the output passes.\n */\ntype OutputManifestEntry = {\n /**\n * Hash of the content Kubb handed to the storage.\n */\n source: string\n /**\n * Hash of what the storage held once the output passes were done with it.\n */\n output: string\n}\n\ntype ManifestData = {\n version: number\n entries: Record<string, OutputManifestEntry>\n}\n\n/**\n * Remembers what the output passes did to each generated file, so the next run can tell \"the\n * formatter already turned this exact source into what is stored\" apart from a real change.\n * Without it the storage compares Kubb's bytes against the formatter's, never matches, and\n * rewrites the whole output tree on every build.\n */\nexport type OutputManifest = {\n /**\n * `true` when `source` is known to come out of the output passes as exactly the content stored,\n * meaning the write can be skipped.\n */\n isUpToDate(options: { key: string; source: string; disk: string }): boolean\n /**\n * Records the source Kubb wrote for `key`, marking it as the only kind of file the output passes\n * can have changed and so the only kind `commit` has to re-read.\n */\n track(options: { key: string; source: string }): void\n /**\n * Re-reads the files written this run and persists their source/output pairs on top of what is\n * stored. Nothing is pruned: a run generating a different set of files, or writing to a different\n * storage in the same root, must not evict what another run recorded.\n */\n commit(): Promise<void>\n}\n\nconst MANIFEST_KEY = 'output-manifest.json'\n\nasync function loadEntries({ cache }: { cache: Storage }): Promise<Record<string, OutputManifestEntry>> {\n try {\n const stored = await cache.readItem(MANIFEST_KEY)\n if (stored === null) return {}\n\n const data = JSON.parse(stored) as ManifestData\n if (data.version !== VERSION) return {}\n if (typeof data.entries !== 'object' || data.entries === null || Array.isArray(data.entries)) return {}\n\n return data.entries\n } catch {\n return {}\n }\n}\n\n/**\n * Loads the stored manifest, starting empty when it is missing, unreadable, or from an older\n * version. `storage` holds the generated files, `cache` holds the manifest itself.\n *\n * @example\n * ```ts\n * const manifest = await createOutputManifest({ storage: config.storage, cache: cacheStorage({ root: config.root }) })\n * ```\n */\nexport async function createOutputManifest({ storage, cache }: { storage: Storage; cache: Storage }): Promise<OutputManifest> {\n const entries = await loadEntries({ cache })\n const tracked = new Map<string, string>()\n\n return {\n isUpToDate({ key, source, disk }) {\n const entry = entries[key]\n if (!entry) return false\n\n return entry.source === hash('sha256', source) && entry.output === hash('sha256', disk)\n },\n track({ key, source }) {\n tracked.set(key, hash('sha256', source))\n },\n async commit() {\n try {\n const next = { ...entries }\n\n // Reads the tree back through the same pool that wrote it, rather than one file at a time.\n await inParallel({\n items: [...tracked],\n limit: FILE_CONCURRENCY,\n run: async ([key, source]) => {\n const stored = await storage.readItem(key)\n if (stored === null) return\n\n next[key] = { source, output: hash('sha256', stored) }\n },\n })\n\n await cache.writeItem(MANIFEST_KEY, JSON.stringify({ version: VERSION, entries: next } satisfies ManifestData))\n } catch {\n /* the record is an optimization, so a storage failure here must not fail a finished build */\n }\n },\n }\n}\n","/**\n * Backend that persists generated files. Kubb ships with `fsStorage` (writes\n * to disk) and `memoryStorage` (keeps everything in RAM). Implement this\n * interface to write somewhere else, such as S3 or a database.\n *\n * Method names follow Node's filesystem vocabulary, so `readItem` reads like\n * `readFile` and `writeItem` like `writeFile`.\n */\nexport type Storage = {\n /**\n * Identifier used in logs and diagnostics (`'fs'`, `'memory'`, `'s3'`).\n */\n readonly name: string\n /**\n * Reads the stored string. Returns `null` when the key is missing.\n */\n readItem(key: string): Promise<string | null>\n /**\n * Stores `value` under `key`, creating any required structure (directories,\n * buckets, ...).\n *\n * Pass `stored` when the caller already read the previous value to avoid\n * reading it again in storage implementations that support the optimization.\n */\n writeItem(key: string, value: string, options?: { stored?: string | null }): 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 readKeys(base?: string): Promise<Array<string>>\n /**\n * Removes stored entries. Pass `base` to scope the wipe to a key prefix.\n *\n * Omitting `base` is implementation-defined: in-memory stores wipe every\n * entry, while filesystem-backed stores treat a missing `base` as a no-op so\n * a bare `empty()` can never delete outside a known output directory.\n */\n empty(base?: string): Promise<void>\n}\n\n/**\n * Defines a custom storage backend. The builder receives user options and\n * returns a `Storage` implementation. Kubb ships with filesystem and in-memory\n * storages. A custom backend writes generated files elsewhere, such as cloud\n * storage or a database.\n *\n * @example In-memory storage (the built-in implementation)\n * ```ts\n * import { createStorage } from '@kubb/core'\n *\n * export const memoryStorage = createStorage(() => {\n * const store = new Map<string, string>()\n *\n * return {\n * name: 'memory',\n * async readItem(key) {\n * return store.get(key) ?? null\n * },\n * async writeItem(key, value) {\n * store.set(key, value)\n * },\n * async removeItem(key) {\n * store.delete(key)\n * },\n * async readKeys(base) {\n * const keys = [...store.keys()]\n * return base ? keys.filter((k) => k.startsWith(base)) : keys\n * },\n * async empty(base) {\n * if (!base) store.clear()\n * },\n * }\n * })\n * ```\n */\nexport const createStorage =\n <TOptions = Record<string, never>>(build: (options: TOptions) => Storage) =>\n (options?: TOptions): Storage =>\n build((options ?? {}) as TOptions)\n","import { resolve } from 'node:path'\nimport { listFiles, read, rm, 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 already holds that content, ignoring any trailing newline\n * a formatter left behind\n * - missing parent directories are created automatically\n * - `FileManager.write` bounds in-flight writes, so this driver does not pace itself\n *\n * @example\n * ```ts\n * import { fsStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * storage: fsStorage(),\n * })\n * ```\n */\nexport const fsStorage = createStorage(() => ({\n name: 'fs',\n async readItem(key: string) {\n try {\n return await read(resolve(key))\n } catch (_error) {\n return null\n }\n },\n async writeItem(key: string, value: string, options?: { stored?: string | null }) {\n await write(resolve(key), value, { sanity: false, stored: options?.stored })\n },\n async removeItem(key: string) {\n await rm(resolve(key), { force: true })\n },\n async readKeys(base?: string) {\n const resolvedBase = resolve(base ?? process.cwd())\n const keys: Array<string> = []\n\n try {\n for await (const path of listFiles(resolvedBase)) keys.push(path)\n } catch (_error) {\n // base directory does not exist yet\n }\n\n return keys\n },\n async empty(base?: string) {\n if (!base) {\n return\n }\n\n await rm(resolve(base), { recursive: true, force: true })\n },\n}))\n","import { hash } from 'node:crypto'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { existsSync, writeRaw } from '@internals/utils'\nimport { createStorage } from '../createStorage.ts'\nimport { fsStorage } from './fsStorage.ts'\n\ntype CacheStorageOptions = {\n /**\n * Project root the cache directory is derived from.\n *\n * @default process.cwd()\n */\n root?: string\n}\n\n/**\n * Directory Kubb keeps build caches in. A project with a `node_modules` gets\n * `node_modules/.cache/kubb`, the convention babel and eslint already use, so the cache stays out\n * of version control. Without one it falls back to the OS temp directory, keyed by root so two\n * projects sharing that directory keep their own cache.\n *\n * @example Inside a project\n * `resolveCacheDir('/project') // '/project/node_modules/.cache/kubb'`\n */\nexport function resolveCacheDir(root: string): string {\n const nodeModules = join(root, 'node_modules')\n if (existsSync(nodeModules)) return join(nodeModules, '.cache', 'kubb')\n\n return join(tmpdir(), 'kubb', hash('sha256', root).slice(0, 16))\n}\n\n/**\n * Filesystem storage for build caches rather than generated code. Keys are plain names resolved\n * inside {@link resolveCacheDir}, so a caller stores `'x.json'` without knowing where the cache\n * lives. Kept apart from the configured output storage, which may not be a local disk at all.\n *\n * @example\n * ```ts\n * const cache = cacheStorage({ root: config.root })\n * await cache.writeItem('output-manifest.json', JSON.stringify(entries))\n * ```\n */\nexport const cacheStorage = createStorage(({ root = process.cwd() }: CacheStorageOptions) => {\n const dir = resolveCacheDir(root)\n const fs = fsStorage()\n const toPath = (key: string) => join(dir, key)\n\n return {\n name: 'cache',\n readItem: (key) => fs.readItem(toPath(key)),\n async writeItem(key, value) {\n const filePath = toPath(key)\n await writeRaw(filePath, value)\n },\n removeItem: (key) => fs.removeItem(toPath(key)),\n readKeys: (base) => fs.readKeys(base ? toPath(base) : dir),\n // Same rule as `fsStorage`: a bare `empty()` deletes nothing, so storage-generic code cannot wipe the cache directory by accident.\n empty: async (base) => (base ? fs.empty(toPath(base)) : undefined),\n }\n})\n","import { toError } from '@internals/utils'\n\n/**\n * A function that can be registered as a hook listener, synchronous or async. Any return value is\n * allowed and ignored, so handlers that return a result for their own callers still register.\n */\ntype AsyncListener<TArgs extends Array<unknown>> = (...args: TArgs) => unknown\n\n/**\n * Typed hook emitter that awaits all async listeners before resolving.\n *\n * @example\n * ```ts\n * const hooks = new Hookable<{ build: [name: string] }>()\n * hooks.hook('build', async (name) => { console.log(name) })\n * await hooks.callHook('build', 'petstore') // all listeners awaited\n * ```\n */\nexport class Hookable<THooks extends { [K in keyof THooks]: Array<unknown> }> {\n readonly #listeners = new Map<string, Set<AsyncListener<Array<unknown>>>>()\n\n /**\n * Calls `hookName` and awaits all registered listeners sequentially.\n * Throws if any listener rejects, wrapping the cause in an error that names the hook.\n *\n * @example\n * ```ts\n * await hooks.callHook('build', 'petstore')\n * ```\n */\n callHook<THookName extends keyof THooks & string>(hookName: THookName, ...hookArgs: THooks[THookName]): Promise<void> | void {\n const listeners = this.#listeners.get(hookName)\n if (!listeners?.size) return\n\n return this.#emitAll(hookName, [...listeners], hookArgs)\n }\n\n async #emitAll(hookName: string, listeners: Array<AsyncListener<Array<unknown>>>, hookArgs: Array<unknown>): Promise<void> {\n for (const listener of listeners) {\n try {\n await listener(...hookArgs)\n } catch (err) {\n // Only the hook name goes in the message: the args can be a whole `Config` or AST subtree.\n throw new Error(`Error in async listener for \"${hookName}\"`, { cause: toError(err) })\n }\n }\n }\n\n /**\n * Registers a persistent listener for `hookName` and returns a function that removes it.\n *\n * @example\n * ```ts\n * const unhook = hooks.hook('build', async (name) => { console.log(name) })\n * unhook() // removes it\n * ```\n */\n hook<THookName extends keyof THooks & string>(hookName: THookName, handler: AsyncListener<THooks[THookName]>): () => void {\n let listeners = this.#listeners.get(hookName)\n if (!listeners) this.#listeners.set(hookName, (listeners = new Set()))\n listeners.add(handler as AsyncListener<Array<unknown>>)\n return () => this.removeHook(hookName, handler)\n }\n\n /**\n * Registers every handler in `configHooks` at once and returns a function that removes them\n * all. Undefined entries are skipped, so a partial hook object registers only its present keys.\n *\n * @example\n * ```ts\n * const unhook = hooks.addHooks({ build: onBuild, done: onDone })\n * unhook() // removes both\n * ```\n */\n addHooks(configHooks: Partial<{ [K in keyof THooks & string]: AsyncListener<THooks[K]> }>): () => void {\n const unhooks = (Object.keys(configHooks) as Array<keyof THooks & string>)\n .filter((name) => configHooks[name])\n .map((name) => this.hook(name, configHooks[name]!))\n\n return () => {\n for (const unhook of unhooks) unhook()\n }\n }\n\n /**\n * Removes a previously registered listener.\n *\n * @example\n * ```ts\n * hooks.removeHook('build', handler)\n * ```\n */\n removeHook<THookName extends keyof THooks & string>(hookName: THookName, handler: AsyncListener<THooks[THookName]>): void {\n this.#listeners.get(hookName)?.delete(handler as AsyncListener<Array<unknown>>)\n }\n\n /**\n * Returns the number of listeners registered for `hookName`.\n *\n * @example\n * ```ts\n * hooks.hook('build', handler)\n * hooks.listenerCount('build') // 1\n * ```\n */\n listenerCount<THookName extends keyof THooks & string>(hookName: THookName): number {\n return this.#listeners.get(hookName)?.size ?? 0\n }\n\n /**\n * No-op kept for callers written against the `EventEmitter`-backed version. Listeners are unbounded.\n *\n * @deprecated There is no listener ceiling anymore.\n */\n setMaxListeners(_max: number): void {}\n\n /**\n * Removes all listeners from every hook channel.\n *\n * @example\n * ```ts\n * hooks.removeAllHooks()\n * ```\n */\n removeAllHooks(): void {\n this.#listeners.clear()\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport process from 'node:process'\nimport { createInterface } from 'node:readline'\nimport { toError } from '@internals/utils'\nimport { type Result, x } from 'tinyexec'\nimport type { Hookable } from '../Hookable.ts'\nimport type { KubbHooks } from '../types.ts'\n\n/**\n * Outcome of one hook subprocess, also carried by the `kubb:hook:end` hook it emits.\n */\nexport type HookResult = { success: true; error: null } | { success: false; error: Error; stdout?: string; stderr?: string }\n\nexport type RunHookOptions = {\n hooks: Hookable<KubbHooks>\n /** Executable to run, resolved on `PATH` and in every `node_modules/.bin` above `cwd`. */\n command: string\n args?: ReadonlyArray<string>\n /** Label shown instead of the command line, for example a `postGenerate` step name. */\n name?: string\n /** Working directory for the command. Defaults to the current process directory. */\n cwd?: string\n signal?: AbortSignal\n}\n\nconst KILL_GRACE_MS = 2_000\n\nasync function settle(proc: Result, hooks: Hookable<KubbHooks>, id: string, commandWithArgs: string): Promise<HookResult> {\n let childError: Error | null = null\n let lineError: Error | null = null\n let lines: Promise<void> = Promise.resolve()\n let killTimer: NodeJS.Timeout | undefined\n proc.process?.once('error', (error) => {\n childError = error\n // An abort only asks the child to stop; one that swallows SIGTERM would otherwise hang the run.\n killTimer = setTimeout(() => proc.kill('SIGKILL'), KILL_GRACE_MS).unref()\n })\n // Lines are only read when a logger listens, so a quiet host does not pay to iterate them.\n if (hooks.listenerCount('kubb:hook:line') > 0) {\n for (const input of [proc.process?.stdout, proc.process?.stderr]) {\n if (!input) continue\n createInterface({ input }).on('line', (line) => {\n lines = lines\n .then(() => hooks.callHook('kubb:hook:line', { id, line }))\n .catch((error) => {\n lineError ??= toError(error)\n })\n })\n }\n }\n const output = await Promise.resolve(proc).catch(() => null)\n clearTimeout(killTimer)\n await lines\n\n const error = childError ?? lineError\n if (error) return { success: false, error }\n if (output?.exitCode === 0) return { success: true, error: null }\n return { success: false, error: new Error(`Hook execute failed: ${commandWithArgs}`), stdout: output?.stdout, stderr: output?.stderr }\n}\n\n/**\n * Spawns a command and returns its outcome, announcing it through `kubb:hook:start`,\n * `kubb:hook:line` (one per stdout or stderr line, only while a listener is attached) and\n * `kubb:hook:end`. A non-zero exit, a spawn failure, an abort or a throwing line listener returns\n * `success: false` instead of throwing. The failure travels on the result and `kubb:hook:end`\n * only, and the caller emits `kubb:success` or a diagnostic, so nothing is reported twice.\n */\nexport async function runHook({ hooks, command, args = [], name, cwd = process.cwd(), signal }: RunHookOptions): Promise<HookResult> {\n const id = randomUUID()\n await hooks.callHook('kubb:hook:start', { id, command, name, args })\n\n const proc = x(command, [...args], {\n signal,\n throwOnError: false,\n nodeOptions: { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32' },\n })\n const result = await settle(proc, hooks, id, [command, ...args].join(' '))\n await hooks.callHook('kubb:hook:end', { id, command, name, args, ...result })\n\n return result\n}\n","import { existsSync } from 'node:fs'\nimport { styleText } from 'node:util'\nimport { detectTool, FORMATTER_PREFERENCE, formatters, LINTER_PREFERENCE, linters, type ToolCommand, tokenize } from '@internals/utils'\nimport { Diagnostics } from '../Diagnostics.ts'\nimport type { Hookable } from '../Hookable.ts'\nimport type { Config, KubbHooks } from '../types.ts'\nimport type { Diagnostic, ProblemDiagnostic } from '../Diagnostics.ts'\nimport { runHook } from './runHook.ts'\n\nexport type RunOutputPassesOptions = {\n config: Config\n /**\n * Absolute directory the formatter and linter run over.\n */\n outputPath: string\n hooks: Hookable<KubbHooks>\n signal?: AbortSignal\n}\n\ntype ToolPass = {\n kind: 'format' | 'lint'\n label: string\n verb: string\n tools: Record<string, ToolCommand>\n preference: ReadonlyArray<string>\n code: ProblemDiagnostic['code']\n}\n\n/**\n * Format and lint are one pass over the output directory that differs only in these values.\n * `label` and `verb` are spelled out: deriving them from `kind` gives \"lintter\" and \"lintting\".\n */\nconst TOOL_PASSES: ReadonlyArray<ToolPass> = [\n { kind: 'format', label: 'formatter', verb: 'Formatting', tools: formatters, preference: FORMATTER_PREFERENCE, code: Diagnostics.code.formatFailed },\n { kind: 'lint', label: 'linter', verb: 'Linting', tools: linters, preference: LINTER_PREFERENCE, code: Diagnostics.code.lintFailed },\n]\n\ntype ToolPassRun = Pick<RunOutputPassesOptions, 'hooks' | 'outputPath' | 'signal'> & { pass: ToolPass; setting: string; cwd: string }\n\n/**\n * Resolves `auto` to an installed tool and runs it. Returns the failure instead of throwing.\n */\nasync function runToolPass({ pass, setting, outputPath, hooks, cwd, signal }: ToolPassRun): Promise<Error | null> {\n const detected = setting === 'auto' ? await detectTool(pass.preference, cwd) : setting\n if (!detected) {\n await hooks.callHook('kubb:warn', { message: `No ${pass.label} found (${pass.preference.join(', ')}). Skipping ${pass.verb.toLowerCase()}.` })\n return null\n }\n if (setting === 'auto') {\n await hooks.callHook('kubb:info', { message: `Auto-detected ${pass.label}: ${styleText('dim', detected)}` })\n }\n\n const tool = pass.tools[detected]\n // Nothing to run over when the output directory was never written: the tool would fail on an\n // empty target (oxlint with --no-ignore reports \"No files found to lint\").\n if (!tool || !existsSync(outputPath)) return null\n\n const result = await runHook({ hooks, command: tool.command, args: tool.args(outputPath), cwd, signal })\n if (result.success) {\n await hooks.callHook('kubb:success', { message: `${pass.verb} with ${styleText('dim', detected)} on ${styleText('dim', outputPath)} successfully` })\n return null\n }\n return result.error\n}\n\n/**\n * Runs `output.format`, `output.lint` and `output.postGenerate` over the generated output and\n * returns the diagnostics they produced. Each failure is emitted through `Diagnostics.emit` and\n * returned, so it reaches the summary, the reporters and the exit code; the passes keep going so\n * one failing tool does not hide the next. `Kubb.generate()` runs this after an error-free build\n * unless the host passes its own `processOutput`.\n *\n * @example\n * ```ts\n * const diagnostics = await runOutputPasses({ config, outputPath: '/repo/src/gen', hooks })\n * ```\n */\nexport async function runOutputPasses({ config, outputPath, hooks, signal }: RunOutputPassesOptions): Promise<Array<Diagnostic>> {\n const diagnostics: Array<Diagnostic> = []\n const report = async (code: ProblemDiagnostic['code'], label: string, error: Error) => {\n const diagnostic: ProblemDiagnostic = {\n code,\n severity: 'error',\n message: `${label} failed: ${error.message}`,\n help: 'Check that the tool is installed and that the command and its config are correct.',\n location: { kind: 'config' },\n cause: error,\n }\n diagnostics.push(diagnostic)\n await Diagnostics.emit(hooks, diagnostic)\n }\n\n for (const pass of TOOL_PASSES) {\n const setting = config.output[pass.kind]\n if (!setting) continue\n\n await hooks.callHook(`kubb:${pass.kind}:start`)\n const error = await runToolPass({ pass, setting, outputPath, hooks, cwd: config.root, signal })\n if (error) await report(pass.code, pass.label, error)\n await hooks.callHook(`kubb:${pass.kind}:end`)\n signal?.throwIfAborted()\n }\n\n const commands = config.output.postGenerate ?? []\n if (commands.length === 0) return diagnostics\n\n await hooks.callHook('kubb:hooks:start')\n for (const entry of commands) {\n const { command, name } = typeof entry === 'string' ? { command: entry, name: undefined } : entry\n const [executable, ...args] = tokenize(command)\n if (!executable) continue\n\n const result = await runHook({ hooks, command: executable, args, name, cwd: config.root, signal })\n if (result.success) await hooks.callHook('kubb:success', { message: `${styleText('dim', name ?? command)} successfully executed` })\n if (!result.success) await report(Diagnostics.code.postGenerateFailed, 'Post-generate command', result.error)\n signal?.throwIfAborted()\n }\n await hooks.callHook('kubb:hooks:end')\n\n return diagnostics\n}\n","import { resolve } from 'node:path'\nimport { isPathInside } from '@internals/utils'\nimport type { FileNode } from '@kubb/ast'\nimport { type Diagnostic, Diagnostics } from './Diagnostics.ts'\nimport type { Storage } from './createStorage.ts'\nimport { KubbDriver } from './KubbDriver.ts'\nimport { createOutputManifest, type OutputManifest } from './outputManifest.ts'\nimport { cacheStorage } from './storages/cacheStorage.ts'\nimport { fsStorage } from './storages/fsStorage.ts'\nimport type { BuildOutput, Config, KubbHooks, UserConfig } from './types.ts'\nimport { Hookable } from './Hookable.ts'\nimport { runOutputPasses, type RunOutputPassesOptions } from './output/runOutputPasses.ts'\n\nfunction resolveConfig(userConfig: UserConfig): Config {\n return {\n ...userConfig,\n root: userConfig.root || process.cwd(),\n parsers: userConfig.parsers ?? [],\n output: {\n format: false,\n lint: false,\n defaultBanner: 'simple',\n ...userConfig.output,\n },\n storage: userConfig.storage ?? fsStorage(),\n reporters: userConfig.reporters ?? [],\n plugins: userConfig.plugins ?? [],\n }\n}\n\n/**\n * Only the fs storage writes `output.path`, so only then do the passes have fresh files to run\n * over; a memory or custom storage would leave them formatting whatever an earlier run left there.\n */\nfunction writesOutputDirectory(storage: Storage): boolean {\n return storage.name === 'fs'\n}\n\n/**\n * Whether anything runs over the output directory after the files are written. Only then can the\n * bytes on disk stop matching what Kubb wrote, which is what the manifest exists to track.\n */\nfunction hasOutputPasses({ output, storage }: Pick<Config, 'output' | 'storage'>): boolean {\n return writesOutputDirectory(storage) && Boolean(output.format || output.lint || output.postGenerate?.length)\n}\n\nexport type CreateKubbOptions = {\n /**\n * Receives Kubb lifecycle hooks for the run.\n */\n hooks?: Hookable<KubbHooks>\n /**\n * Stops the build at the next safe checkpoint.\n */\n signal?: AbortSignal\n}\n\n/**\n * Host hooks for a single {@link Kubb.generate} call. All optional. Progress narration rides the\n * `kubb:*` lifecycle hooks on `.hooks`, so hosts subscribe there rather than pass a callback.\n */\nexport type GenerateOptions = {\n /**\n * Replaces the output passes that run after an error-free build. The default,\n * {@link runOutputPasses}, formats, lints and runs `output.postGenerate` over the generated\n * output and returns the diagnostics they emitted.\n */\n processOutput?: (context: RunOutputPassesOptions) => Promise<Array<Diagnostic>>\n}\n\n/**\n * What a {@link Kubb.generate} call produced, for the host to map onto its own result shape.\n */\nexport type GenerateResult = {\n /**\n * `true` when the build and every output pass completed without an error-level diagnostic.\n */\n success: boolean\n /**\n * All files generated during the build.\n */\n files: Array<FileNode>\n /**\n * Build diagnostics plus any collected from the output passes.\n */\n diagnostics: Array<Diagnostic>\n}\n\n/**\n * Kubb code-generation instance bound to a single config entry. Resolves the user\n * config in the constructor, so `config` is available right away, and shares `hooks`,\n * `storage`, and `driver` across the `setup → build` lifecycle.\n *\n * `createKubb` takes a plain config object (the shape `defineConfig` produces),\n * not a fluent builder.\n *\n * Attach hook listeners to `.hooks` before calling `setup()` or `build()`.\n *\n * @example\n * ```ts\n * const kubb = createKubb(userConfig)\n * kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => console.log(plugin.name, duration))\n * const { files, diagnostics } = await kubb.safeBuild()\n * ```\n */\nexport class Kubb {\n readonly hooks: Hookable<KubbHooks>\n readonly config: Config\n #driver: KubbDriver | null = null\n #manifest: OutputManifest | null = null\n readonly #signal: AbortSignal | undefined\n\n constructor(userConfig: UserConfig, options: CreateKubbOptions = {}) {\n this.config = resolveConfig(userConfig)\n this.hooks = options.hooks ?? new Hookable<KubbHooks>()\n this.#signal = options.signal\n }\n\n get storage(): Storage {\n return this.config.storage\n }\n\n get driver(): KubbDriver {\n if (!this.#driver)\n throw new Diagnostics.Error({ code: Diagnostics.code.internalError, severity: 'error', message: '[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 signal = this.#signal\n signal?.throwIfAborted()\n const config = this.config\n const manifest = hasOutputPasses(config) ? await createOutputManifest({ storage: config.storage, cache: cacheStorage({ root: config.root }) }) : undefined\n\n const cleanPath = config.output.clean ? resolve(config.root, config.output.path) : undefined\n\n // clean only removes generated code. Refuse when the output resolves to the project root or\n // an ancestor of it, otherwise the wipe would delete kubb.config and every source file.\n if (cleanPath && isPathInside(config.root, cleanPath)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.cleanRoot,\n severity: 'error',\n message: `output.clean cannot delete \"${cleanPath}\" because it is the project root or a parent of it.`,\n help: 'Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code.',\n location: { kind: 'config' },\n })\n }\n\n // The driver empties `cleanPath` right before it writes the new files, so a run that fails\n // earlier, on an invalid spec or a plugin that throws, leaves the previous output in place.\n const driver = new KubbDriver(config, { hooks: this.hooks, manifest, signal, cleanPath })\n await driver.setup()\n\n this.#driver = driver\n this.#manifest = manifest ?? null\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 AggregateError(errors, `Build failed with ${errors.length} ${errors.length === 1 ? 'error' : '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 this.#signal?.throwIfAborted()\n if (!this.#driver) await this.setup()\n using self = this\n const driver = self.driver\n const storage = self.storage\n const { diagnostics } = await driver.run()\n\n return { diagnostics, files: driver.fileManager.files, driver, storage }\n }\n\n /**\n * Run one build and its output passes end to end, emitting the surrounding `kubb:generation:*`\n * hooks. Never throws on a build error: the outcome comes back in {@link GenerateResult} so the\n * host decides how failures surface. Telemetry and progress narration stay with the host, which\n * reads the result and subscribes to the `kubb:*` hooks.\n *\n * @example\n * ```ts\n * const result = await createKubb(config, { hooks }).generate()\n * if (!result.success) process.exitCode = 1\n * ```\n */\n async generate(options: GenerateOptions = {}): Promise<GenerateResult> {\n const signal = this.#signal\n signal?.throwIfAborted()\n const { hooks, config } = this\n const hrStart = process.hrtime()\n\n await hooks.callHook('kubb:generation:start', { config })\n\n // A setup failure, such as an invalid plugin entry, becomes a diagnostic like any build\n // problem, so reporters still get a failed `kubb:generation:end` for this config.\n let output: Pick<BuildOutput, 'files' | 'diagnostics'>\n try {\n await hooks.callHook('kubb:setup:start')\n await this.setup()\n await hooks.callHook('kubb:setup:end')\n\n output = await this.safeBuild()\n } catch (caughtError) {\n if (signal?.aborted) throw caughtError\n output = { files: [], diagnostics: [Diagnostics.from(caughtError)] }\n }\n const { files, diagnostics } = output\n const storage = this.storage\n signal?.throwIfAborted()\n\n // Surface every problem on the hooks. `performance` diagnostics feed the summary, not the\n // log, so they are skipped.\n for (const diagnostic of diagnostics) {\n if (Diagnostics.isProblem(diagnostic)) await Diagnostics.emit(hooks, diagnostic)\n }\n\n if (Diagnostics.hasError(diagnostics)) {\n await hooks.callHook('kubb:generation:end', { config, storage, diagnostics, filesCreated: files.length, status: 'failed', hrStart })\n return { success: false, files, diagnostics }\n }\n\n const processOutput = options.processOutput ?? runOutputPasses\n const outputDiagnostics = writesOutputDirectory(config.storage)\n ? await processOutput({ config, outputPath: resolve(config.root, config.output.path), hooks, signal })\n : []\n\n const finalDiagnostics = [...diagnostics, ...outputDiagnostics]\n const failed = Diagnostics.hasError(outputDiagnostics)\n\n // The formatter and linter have had their turn, so what sits on disk now is what the next run\n // has to recognize as unchanged. Only record it when they finished: a pass that failed halfway\n // leaves files Kubb has to stay free to regenerate.\n if (!failed) await this.#manifest?.commit()\n\n await hooks.callHook('kubb:generation:end', {\n config,\n storage,\n diagnostics: finalDiagnostics,\n filesCreated: files.length,\n status: failed ? 'failed' : 'success',\n hrStart,\n })\n\n return { success: !failed, files, diagnostics: finalDiagnostics }\n }\n\n dispose(): void {\n this.#driver?.dispose()\n }\n\n [Symbol.dispose](): void {\n this.dispose()\n }\n}\n\n/**\n * Constructs a {@link Kubb} build orchestrator from a user config. Equivalent\n * to `new Kubb(userConfig, options)` and the canonical public entry point.\n *\n * @example\n * ```ts\n * import { createKubb } from '@kubb/core'\n * import { adapterOas } from '@kubb/adapter-oas'\n * import { pluginTs } from '@kubb/plugin-ts'\n *\n * const kubb = createKubb({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * adapter: adapterOas(),\n * plugins: [pluginTs()],\n * })\n *\n * await kubb.build()\n * ```\n */\nexport function createKubb(userConfig: UserConfig, options: CreateKubbOptions = {}): Kubb {\n return new Kubb(userConfig, options)\n}\n","import type { LiteralUnion } from '@internals/utils'\nimport 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 * - `html` writes a browsable report directory to `.kubb/kubb-<name>-<timestamp>/`.\n */\nexport type ReporterName = 'cli' | 'json' | 'file' | 'html'\n\n/**\n * Files attributed to the plugin that first added them.\n */\nexport type ReporterPluginFiles = Array<{\n /** Plugin name. */\n plugin: string\n /** Generated file paths. */\n files: Array<string>\n}>\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 generated files for this config, including unchanged files.\n */\n filesCreated: number\n /**\n * Number of generated files whose content matches the previous output.\n */\n filesUnchanged?: number\n /**\n * Changes compared with the output before this run, when the host collected them.\n * Line totals include added and deleted files.\n */\n fileChanges?: {\n added: number\n modified: number\n deleted: number\n linesAdded: number\n linesRemoved: number\n }\n /**\n * The result previews generation without writing output.\n */\n dryRun?: boolean\n status: 'success' | 'failed'\n /**\n * `process.hrtime()` snapshot taken when this config started generating.\n */\n hrStart: [number, number]\n /**\n * Files attributed to the plugin that first added them, when requested by a reporter.\n */\n pluginFiles?: ReporterPluginFiles\n}\n\n/**\n * Render settings passed alongside the {@link GenerationResult}. These are not part of the run\n * data, such as the output verbosity.\n */\nexport type ReporterContext = {\n /**\n * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`\n * (`silent`, `error`, `warn`, `info`, `verbose`).\n */\n logLevel: (typeof logLevel)[keyof typeof logLevel]\n}\n\n/**\n * Host-facing reporter, as installed onto a run. Unlike a Logger (the live TUI view), a reporter\n * never sees the hook emitter. `report` runs once per config. `drain`, when present, runs once\n * after the last config.\n */\nexport type Reporter = {\n /**\n * Display name, matching a {@link ReporterName} for the built-ins.\n */\n name: LiteralUnion<ReporterName>\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 * Runs once after the run's last config, on `kubb:lifecycle:end`. Only a reporter that collects\n * its configs' reports into one document, such as `json`, has one.\n */\n drain?: (context: ReporterContext) => void | Promise<void>\n /**\n * Whether the host should collect files from `kubb:plugin:end` hooks.\n */\n needsPluginFiles?: boolean\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: LiteralUnion<ReporterName>\n /**\n * Whether the host should collect files from `kubb:plugin:end` hooks.\n */\n needsPluginFiles?: boolean\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. The returned reporter buffers each value `report` returns in order and, when\n * the definition has a `drain`, hands the array to `drain` once and then clears it. Wiring the\n * reporter onto the run's hooks is the host's job, so the reporter only ever deals with a\n * {@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 { name, needsPluginFiles, drain } = reporter\n if (!drain) {\n return {\n name,\n needsPluginFiles,\n async report(result, context) {\n await reporter.report(result, context)\n },\n }\n }\n\n const reports: Array<T> = []\n return {\n name,\n needsPluginFiles,\n async report(result, context) {\n reports.push(await reporter.report(result, context))\n },\n async drain(context) {\n await drain(context, reports.splice(0))\n },\n }\n}\n","import { resolve } from 'node:path'\nimport { getElapsedMs } from '@internals/utils'\nimport type { GenerationResult } from '../createReporter.ts'\nimport { Diagnostics } from '../Diagnostics.ts'\nimport type { SerializedDiagnostic } from '../formatDiagnostic.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 * Generated files whose content matches the previous output.\n */\n filesUnchanged: number\n fileChanges?: GenerationResult['fileChanges']\n dryRun?: boolean\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, filesUnchanged = 0, 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 // A failed run without timings stopped before any plugin ran, such as on an invalid plugin entry.\n plugins: { passed: status === 'failed' && timings.length === 0 ? 0 : total - failed.length, failed, total },\n counts,\n filesCreated,\n filesUnchanged,\n fileChanges: result.fileChanges,\n dryRun: result.dryRun,\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 { isAbsolute, relative } from 'node:path'\nimport { styleText } from 'node:util'\nimport { formatMs } from '@internals/utils'\nimport type { Report } from './report.ts'\n\n/**\n * Writes the summary through the host's output, or plain console lines by default.\n */\nexport type SummaryRenderer = (lines: ReadonlyArray<string>, meta: { title: string; status: 'success' | 'failed' }) => void\n\n/**\n * Puts the outcome first, followed by file counts, labeled plugin results, and the output path.\n * Hosts that collect file changes get a compact diff section. Verbose output adds plugin timings.\n */\nexport function formatSummary(report: Report, { showTimings }: { showTimings: boolean }): Array<string> {\n const { status, plugins, counts, filesCreated, filesUnchanged, fileChanges, dryRun, durationMs, output, timings } = report\n const failed = status === 'failed'\n const successTone = counts.warnings ? 'yellow' : 'green'\n const tone = failed ? 'red' : successTone\n const title = (() => {\n if (failed) return '✗ Generation failed'\n if (dryRun) return '◇ Dry run complete'\n if (counts.warnings) return '✓ Generation complete with warnings'\n if (filesCreated > 0 && filesCreated === filesUnchanged) return '✓ Already up to date'\n return '✓ Generation complete'\n })()\n const separator = styleText('dim', ' · ')\n const generated = Math.max(0, filesCreated - filesUnchanged)\n const fileLabel = `${generated} ${generated === 1 ? 'file' : 'files'} ${dryRun ? 'planned' : 'generated'}`\n const lines = [\n `${styleText(tone, title)} ${styleText('dim', formatMs(durationMs))}`,\n '',\n ` ${styleText(generated ? 'bold' : 'dim', fileLabel)}${filesUnchanged ? separator + styleText('dim', `${filesUnchanged} unchanged`) : ''}`,\n ]\n\n const notRun = plugins.total - plugins.passed - plugins.failed.length\n const pluginCounts = [\n plugins.passed > 0 ? styleText('green', `${plugins.passed} passed`) : undefined,\n plugins.failed.length > 0 ? styleText('red', `${plugins.failed.length} failed`) : undefined,\n notRun > 0 ? styleText('dim', `${notRun} not run`) : undefined,\n ].filter(Boolean)\n lines.push(` ${styleText('dim', 'Plugins')} ${pluginCounts.join(separator) || styleText('dim', 'none configured')}`)\n\n if (plugins.failed.length) lines.push(` ${styleText('dim', 'Failed plugins')} ${styleText('red', plugins.failed.join(', '))}`)\n\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 ].filter(Boolean)\n if (issues.length) lines.push(` ${styleText('dim', 'Issues')} ${issues.join(separator)}`)\n\n const destination = relative(process.cwd(), output)\n const displayPath = destination.startsWith('..') || isAbsolute(destination) ? output : `./${destination}`\n lines.push(` ${styleText('dim', failed || dryRun ? 'Target' : 'Output')} ${styleText(failed ? 'dim' : 'cyan', displayPath)}`)\n if (dryRun) lines.push(` ${styleText('dim', 'Nothing was written.')}`)\n\n if (fileChanges) {\n lines.push(\n '',\n styleText('bold', dryRun ? 'Planned file changes' : 'File changes'),\n ` ${styleText(fileChanges.added ? 'green' : 'dim', `${fileChanges.added} added`)}${separator}${styleText(fileChanges.modified ? 'yellow' : 'dim', `${fileChanges.modified} modified`)}${separator}${styleText(fileChanges.deleted ? 'red' : 'dim', `${fileChanges.deleted} deleted`)}`,\n ` ${styleText('dim', 'Lines')} ${styleText(fileChanges.linesAdded ? 'green' : 'dim', `+${fileChanges.linesAdded}`)} ${styleText(fileChanges.linesRemoved ? 'red' : 'dim', `−${fileChanges.linesRemoved}`)}`,\n )\n }\n\n if (showTimings && timings.length > 0) {\n const nameWidth = Math.max(...timings.map((timing) => timing.plugin.length))\n lines.push('', styleText('dim', 'Plugin timings'))\n for (const timing of timings) lines.push(` ${timing.plugin.padEnd(nameWidth)} ${styleText('dim', formatMs(timing.durationMs))}`)\n }\n\n return lines\n}\n","import { styleText } from 'node:util'\nimport { createReporter, logLevel as logLevelMap, type Reporter } from '../createReporter.ts'\nimport { buildReport } from './report.ts'\nimport { formatSummary, type SummaryRenderer } from './summary.ts'\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 */\nconst consoleRenderer: SummaryRenderer = (lines, { title, status }) => {\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 * Builds a `cli` reporter that renders the {@link Report} for each config as it finishes.\n * Suppressed at `silent`. The `verbose` level adds the per-plugin timings.\n *\n * Pass `render` to send the summary through output the host already owns, so it lands inside that\n * host's grouping instead of alongside it. Omit it for the plain `console.log` writer.\n *\n * @example\n * ```ts\n * const reporter = createCliReporter({ render: (lines) => lines.forEach((line) => clack.log.message(line)) })\n * ```\n */\nexport function createCliReporter({ render = consoleRenderer }: { render?: SummaryRenderer } = {}): Reporter {\n return createReporter({\n name: 'cli',\n report(result, { logLevel }) {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const report = buildReport(result)\n\n render(formatSummary(report, { showTimings: logLevel >= logLevelMap.verbose }), { title: report.name, status: report.status })\n },\n })\n}\n\n/**\n * The default `cli` reporter, writing its summary straight to the console. Independent of the live\n * logger view.\n */\nexport const cliReporter = createCliReporter()\n","import { hash } from 'node:crypto'\nimport { chmodSync, mkdirSync } from 'node:fs'\nimport { homedir, tmpdir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport process from 'node:process'\nimport { createStorage as createUnstorage } from 'unstorage'\nimport fsDriver from 'unstorage/drivers/fs'\n\ntype KubbStorageOptions = {\n /**\n * Folder inside the Kubb home, or an absolute path such as `<cwd>/.kubb`.\n */\n base?: string\n}\n\nfunction ensurePrivateDir(dir: string): string {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n chmodSync(dir, 0o700)\n return dir\n}\n\n/**\n * Folder Kubb keeps its own files in, created with mode 0700. `base` resolves inside `KUBB_HOME`\n * (default `~/.kubb`). When that folder is not writable, it falls back to a folder in the OS temp directory.\n *\n * @example\n * `resolveKubbDir('cache') // '/home/me/.kubb/cache'`\n */\nexport function resolveKubbDir(base = ''): string {\n const dir = resolve(process.env.KUBB_HOME ?? join(homedir(), '.kubb'), base)\n try {\n return ensurePrivateDir(dir)\n } catch {\n return ensurePrivateDir(join(tmpdir(), 'kubb', hash('sha256', dir).slice(0, 16)))\n }\n}\n\n/**\n * unstorage on the fs driver, rooted at {@link resolveKubbDir}. The fs driver cannot set a file\n * mode, so the 0700 folder keeps files such as a stored token private.\n *\n * @example\n * ```ts\n * const storage = kubbStorage({ base: 'cache' })\n * await storage.setItem('machine-secret', secret)\n * ```\n */\nexport function kubbStorage({ base }: KubbStorageOptions = {}) {\n return createUnstorage({ driver: fsDriver({ base: resolveKubbDir(base) }) })\n}\n","import { join, relative, resolve } from 'node:path'\nimport process from 'node:process'\nimport { stripVTControlCharacters } from 'node:util'\nimport { createReporter } from '../createReporter.ts'\nimport { type Diagnostic, Diagnostics } from '../Diagnostics.ts'\nimport { kubbStorage, resolveKubbDir } from '../storages/kubbStorage.ts'\nimport { buildReport } from './report.ts'\nimport { formatSummary } from './summary.ts'\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 // The full stack, since a log file is what a bug report attaches.\n const blocks = problems.map((diagnostic) => Diagnostics.format(diagnostic, { verbose: true }).join('\\n'))\n return ['## Problems', '', blocks.join('\\n\\n')]\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 lines the\n * cli reporter prints (timings included), and a `## Problems` section in the miette block format.\n * Selected with `--reporter file` (or `reporters: ['file']`).\n *\n * @note It captures the collected diagnostics once a config finishes, not the live\n * `kubb:info`/`kubb:plugin` hook stream. Color is stripped so the file stays plain text even when\n * the run is attached to a TTY.\n */\nexport const fileReporter = createReporter({\n name: 'file',\n async report(result) {\n const { diagnostics, config } = result\n if (diagnostics.length === 0) {\n return\n }\n\n const report = buildReport(result)\n const header = config.name ? `# ${config.name} — ${new Date().toISOString()}` : `# ${new Date().toISOString()}`\n const summary = ['## Summary', '', ...formatSummary(report, { showTimings: true })]\n const sections = [summary, buildProblemSection(diagnostics)].filter((section) => section.length > 0)\n const content = stripVTControlCharacters([header, ...sections.map((section) => section.join('\\n'))].join('\\n\\n'))\n\n const name = config.name?.replace(/[^a-zA-Z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')\n const baseName = `${['kubb', name, Date.now()].filter(Boolean).join('-')}.log`\n const dir = resolveKubbDir(resolve(process.cwd(), '.kubb'))\n\n await kubbStorage({ base: dir }).setItem(baseName, `${content}\\n`)\n console.error(`Debug log written to ${relative(process.cwd(), join(dir, baseName))}`)\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 { join, relative, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { openInBrowser, read } from '@internals/utils'\nimport { createReporter, type GenerationResult } from '../createReporter.ts'\nimport { kubbStorage, resolveKubbDir } from '../storages/kubbStorage.ts'\nimport { buildReport } from './report.ts'\n\nfunction serializeReport(result: GenerationResult): string {\n const data = JSON.stringify({ generatedAt: new Date().toISOString(), report: buildReport(result), pluginFiles: result.pluginFiles ?? [] })\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/&/g, '\\\\u0026')\n return `globalThis.__KUBB_REPORT__ = ${data}\\n`\n}\n\n/**\n * Writes a static HTML report directory selected with `--reporter html`.\n */\nexport const htmlReporter = createReporter({\n name: 'html',\n needsPluginFiles: true,\n async report(result) {\n const name = result.config.name?.replace(/[^a-zA-Z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')\n const baseName = ['kubb', name, Date.now()].filter(Boolean).join('-')\n const dir = resolveKubbDir(resolve(process.cwd(), '.kubb'))\n const storage = kubbStorage({ base: dir })\n const assets = new URL('./html/', import.meta.url)\n const [html, ui] = await Promise.all([read(fileURLToPath(new URL('index.html', assets))), read(fileURLToPath(new URL('ui.iife.js', assets)))])\n\n await Promise.all([\n storage.setItem(`${baseName}/index.html`, html),\n storage.setItem(`${baseName}/ui.iife.js`, ui),\n storage.setItem(`${baseName}/data.js`, serializeReport(result)),\n ])\n const reportPath = join(dir, baseName, 'index.html')\n console.error(`HTML report written to ${relative(process.cwd(), reportPath)}`)\n openInBrowser(reportPath)\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 { ProblemDiagnostic } from './Diagnostics.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { KubbHooks } from './types.ts'\nimport type { KubbDriver } from './KubbDriver.ts'\nimport type { ExtensionMeta } from './defineExtension.ts'\nimport type { Plugin, PluginType, PluginName, ResolvePluginOptions } from './definePlugin.ts'\nimport type { NodeCache } from './nodeCache.ts'\nimport type { Config } from './types.ts'\nimport type { Hookable } from './Hookable.ts'\n\n/**\n * Context passed to a generator's `schema`, `operation`, and `operations` methods.\n *\n * The driver sets `adapter` on the context before it runs a generator, so methods can read it\n * without a null check. `ctx.options` carries the per-node options after exclude/include/override\n * filtering for `schema` and `operation`, or the plugin-level options for `operations`.\n */\nexport type GeneratorContext<TOptions extends PluginType = PluginType> = {\n /**\n * Stops cooperative generation work at the next safe checkpoint.\n */\n signal?: AbortSignal\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 PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined\n /**\n * Get a plugin by name, throws an error if not found.\n */\n requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>\n /**\n * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.\n */\n getResolver<TName extends PluginName>(name: TName): ResolvePluginOptions<TName>['resolver']\n /**\n * Add files only if they don't exist.\n */\n addFile: (...file: Array<FileNode>) => Promise<void>\n /**\n * Merge sources into the same output file.\n */\n upsertFile: (...file: Array<FileNode>) => Promise<void>\n /**\n * The build's hook bus. Emit or listen to any `KubbHooks` hook, for example to react to\n * `kubb:build:end` from inside a generator.\n */\n hooks: Hookable<KubbHooks>\n /**\n * The current plugin instance.\n */\n plugin: Plugin<TOptions> & { name: string; meta: ExtensionMeta }\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. Pass `options` to set\n * the `code`, the `help` text, or the source `location`.\n *\n * @example\n * `ctx.warn('Enum has no values', { help: 'Add values to the enum.', location: { kind: 'schema', pointer: '#/components/schemas/Status' } })`\n */\n warn: (message: string, options?: Partial<Pick<ProblemDiagnostic, 'code' | 'help' | 'location'>>) => void\n /**\n * Report an error. Collected as an `error` diagnostic attributed to the current\n * plugin, which fails the build. A `Diagnostics.Error` keeps its own code, help, and location.\n * Pass `options` to set them for a plain message or error.\n */\n error: (error: string | Error, options?: Partial<Pick<ProblemDiagnostic, 'code' | 'help' | 'location'>>) => void\n /**\n * Report an informational message. Collected as an `info` diagnostic attributed to\n * the current plugin. Pass `options` to set the `code`, the `help` text, or the source `location`.\n */\n info: (message: string, options?: Partial<Pick<ProblemDiagnostic, 'code' | 'help' | 'location'>>) => 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 * Cache scoped to the node being generated, shared by every plugin that generates from that\n * same node in the current pass. Use it to compute node-derived work (resolved names, imports,\n * parameters) once and let the other plugins reuse it. For the `operations` batch call, where\n * there is no single node, the cache is a fresh scratch scope for that call.\n */\n cache: NodeCache\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 PluginType = PluginType, 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 * Predicate checked before `schema` or `operation` runs for a node, mirroring `Macro['match']`\n * in `@kubb/ast`. Returning `false` skips the call for that node entirely, with no context work\n * beyond what the driver already builds per node and no render call, instead of the generator\n * itself being invoked and returning early. Omit it to run for every node, the default when\n * unset.\n *\n * Does not gate `operations`, which already runs once per plugin on the full batch rather than\n * per node.\n *\n * @example Only match GET operations\n * ```ts\n * match(node, ctx) {\n * return ast.isHttpOperationNode(node) && node.method.toLowerCase() === 'get'\n * }\n * ```\n */\n match?: (node: SchemaNode | OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<boolean>\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 `PluginType`. 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 PluginType = PluginType, TElement = unknown>(\n generator: Generator<TOptions, TElement>,\n): Generator<TOptions, TElement> {\n return generator\n}\n","import type { FileNode, UserFileNode } from '@kubb/ast'\nimport { defineExtension } from './defineExtension.ts'\nimport type { ExtensionFactory, ExtensionMeta, ExtensionNamed } from './defineExtension.ts'\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, TOptions extends object = object> = ExtensionNamed & {\n /**\n * The options passed to the parser factory.\n */\n options?: TOptions\n /**\n * File extensions this parser handles. The driver registers the parser for each\n * extension in this list. A parser with `undefined` here is not registered, so\n * files of an unclaimed extension fall back to joining their sources verbatim.\n *\n * @example\n * `['.ts', '.js']`\n */\n extNames: Array<FileNode['extname']> | undefined\n /**\n * Serialize the file's AST into source code.\n */\n parse(file: FileNode<TMeta>): string\n /**\n * Turn the content of a `copy` file into a file node that `parse` prints. Omit to copy the file verbatim.\n */\n copy?(file: FileNode<TMeta>, source: string): UserFileNode<TMeta>\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 * Takes the user's options and returns the parser methods.\n */\nexport type ParserBuild<TOptions extends object, TMeta extends object, TNode> = (options: TOptions) => Omit<Parser<TMeta, TNode>, 'name' | 'meta' | 'options'>\n\n/**\n * The object passed to `defineExtension` with `kind: 'parser'`. `build` receives the user's options and returns the parser methods.\n */\nexport type ParserDefinition<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = {\n meta: ExtensionMeta\n build: ParserBuild<TOptions, TMeta, TNode>\n}\n\n/**\n * The function `defineExtension` returns for a parser. Call it with user options to get a `Parser`.\n */\nexport type ParserFactory<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = ExtensionFactory<\n 'parser',\n TOptions,\n Parser<TMeta, TNode, TOptions>\n>\n\n/**\n * Defines a parser from one object and returns a factory that takes the user's options.\n * Register the result in the `parsers` array on `defineConfig`.\n *\n * @deprecated Use `defineExtension` with `kind: 'parser'` instead.\n */\nexport function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(\n definition: ParserDefinition<TOptions, TMeta, TNode>,\n): ParserFactory<TOptions, TMeta, TNode> {\n return defineExtension({ kind: 'parser', ...definition })\n}\n","import { createStorage } from '../createStorage.ts'\n\n/**\n * In-memory storage driver. Useful for testing and dry-run scenarios where\n * generated output should be captured without touching the filesystem.\n *\n * All data lives in a `Map` scoped to the storage instance and is discarded\n * when the instance is garbage-collected.\n *\n * @example\n * ```ts\n * import { memoryStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * storage: memoryStorage(),\n * })\n * ```\n */\nexport const memoryStorage = createStorage(() => {\n const store = new Map<string, string>()\n\n return {\n name: 'memory',\n async readItem(key: string) {\n return store.get(key) ?? null\n },\n async writeItem(key: string, value: string) {\n store.set(key, value)\n },\n async removeItem(key: string) {\n store.delete(key)\n },\n async readKeys(base?: string) {\n const keys = [...store.keys()]\n return base ? keys.filter((k) => k.startsWith(base)) : keys\n },\n async empty(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","import { isValid } from 'verkit'\nimport type { ExtensionKind } from './defineExtension.ts'\n\n/** A value that survives `JSON.stringify` and `JSON.parse` unchanged. */\nexport type JSONValue = string | number | boolean | null | Array<JSONValue> | { [key: string]: JSONValue }\n\n/**\n * One form field Studio renders for an extension. It edits the value at `path` in the options\n * object the user passes to the factory.\n */\nexport type ExtensionManifestOption = {\n /** Stable UI key, unique within the manifest. */\n key: string\n /** Where the value lives, such as `['output', 'path']`. */\n path: Array<string>\n label: string\n description?: string\n type: 'select' | 'boolean' | 'text' | 'number' | 'list'\n /** The extension's runtime default, shown when the option is unset. */\n default?: JSONValue\n /** For `select`. A choice with value `null` leaves the option unset. */\n choices?: Array<{ label?: string; value: JSONValue }>\n /** For `boolean`: the value written for `true`, `true` when unset. */\n trueValue?: JSONValue\n /** For `boolean`: the value written for `false`, `false` when unset. */\n falseValue?: JSONValue\n /** For `list`: template for each entry, where every `\"$item\"` string is replaced by the entry. */\n item?: JSONValue\n /** For `list`: upper-case each entry before writing it. */\n itemCase?: 'upper'\n}\n\n/**\n * The `kubb-extension.json` file an extension package ships at its root. Studio, the kubb.dev\n * registry, and `kubb add` read it.\n */\nexport type ExtensionManifest = {\n $schema?: string\n kind: ExtensionKind\n /** Equals the extension's `meta.name`. */\n name: string\n /** The factory export users call in `kubb.config.ts`, such as `pluginZod`. */\n export: string\n displayName: string\n description: string\n category?: string\n icon?: { light: string; dark?: string }\n /** HTTPS image or video URLs. */\n media?: Array<string>\n tags?: Array<string>\n docs?: string\n /** People who maintain the extension, shown on its kubb.dev page. */\n maintainers?: Array<{ name: string; github?: string }>\n /** Names of the extensions that must be in the same config, such as `['plugin-ts']`. */\n dependencies?: Array<string>\n /** Names of the extensions used when they are in the config, or needed only for some option values, such as `['plugin-faker']`. */\n optionalDependencies?: Array<string>\n compatibility?: { kubb?: string; node?: string }\n /** Plugins only: `client` ships the HTTP client runtime, `consumer` calls one but ships none. */\n role?: 'client' | 'consumer'\n options?: Array<ExtensionManifestOption>\n}\n\n/** What `kubb add` installs: a reviewed npm version, or a GitHub release tag and the commit it points to. */\nexport type RegistryArtifact =\n | { kind: 'npm'; package: string; version: string }\n | {\n kind: 'github'\n /** The `name` in the root `package.json`, so the package installs under this name. */\n package: string\n /** The release version, equal to `tag` without a leading `v`. */\n version: string\n owner: string\n repo: string\n tag: string\n /** The full commit SHA the tag points to. */\n commit: string\n }\n\n/** One extension in a registry's `index.json`. */\nexport type RegistryEntry = {\n /** `<owner>/<slug>`, such as `kubb-labs/plugin-zod`. */\n id: string\n kind: ExtensionKind\n type: 'official' | 'community'\n artifact: RegistryArtifact\n repository?: { url: string }\n manifest: ExtensionManifest\n stats?: { downloads?: number; weekly?: number; stars?: number }\n submittedAt: string\n publishedAt: string\n reviewedAt: string\n}\n\n/** The registry's `index.json`. */\nexport type RegistryIndex = { version: 1; generatedAt: string; extensions: Array<RegistryEntry> }\n\n/** One `docs/guides/<id>.md`: `id` is the file name, `title` its `#` heading, `description` the first paragraph. */\nexport type RegistryGuide = {\n id: string\n title: string\n description: string\n content: string\n}\n\n/** The registry's `<owner>/<slug>.json`: an entry plus the Markdown docs its pinned version ships. */\nexport type RegistryDetail = RegistryEntry & { overview: string | null; options?: string | null; guides?: Array<RegistryGuide> }\n\nconst EXTENSION_KINDS = new Set<unknown>(['plugin', 'adapter', 'parser'] satisfies Array<ExtensionKind>)\nconst OPTION_TYPES = new Set<unknown>(['select', 'boolean', 'text', 'number', 'list'] satisfies Array<ExtensionManifestOption['type']>)\nconst PACKAGE_NAME = /^(?:@[a-z0-9~][a-z0-9._~-]*\\/)?[a-z0-9~][a-z0-9._~-]*$/\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/\nconst REGISTRY_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*\\/[a-z0-9]+(?:-[a-z0-9]+)*$/\nconst GITHUB_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/\nconst GITHUB_REPO = /^(?!\\.\\.?$)[A-Za-z0-9._-]{1,100}$/\nconst COMMIT = /^[0-9a-f]{40}$/\n/** Option path segments that would reach an object's prototype when Studio writes the value by path. */\nconst UNSAFE_KEYS = new Set<unknown>(['__proto__', 'constructor', 'prototype'])\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\nconst isOptionalString = (value: unknown) => value === undefined || typeof value === 'string'\nconst isFilledString = (value: unknown) => typeof value === 'string' && value !== ''\nconst matches = (pattern: RegExp, value: unknown) => typeof value === 'string' && pattern.test(value)\n/** Serializes with sorted object keys, so equal JSON values give equal strings whatever their key order. */\nconst canonicalJSON = (value: unknown) =>\n JSON.stringify(value, (_key, item: unknown) =>\n isObject(item)\n ? Object.fromEntries(\n Object.keys(item)\n .sort()\n .map((key) => [key, item[key]]),\n )\n : item,\n )\n\n/**\n * Whether `name` is a valid npm package name, such as `@kubb/plugin-ts`. Rejects paths, URLs,\n * `node:` specifiers, and names that start with `-`, so the result is safe to pass to `import()` or\n * a package manager.\n */\nexport function isPackageName(name: unknown): name is string {\n return typeof name === 'string' && name.length <= 214 && PACKAGE_NAME.test(name)\n}\n\nfunction isMaintainer(value: unknown): boolean {\n return (\n isObject(value) &&\n Object.keys(value).every((key) => key === 'name' || key === 'github') &&\n isFilledString(value.name) &&\n (value.github === undefined || isFilledString(value.github))\n )\n}\n\n/** Checks the shape of one manifest option, including that its path cannot reach a prototype. */\nfunction isOption(value: unknown): value is ExtensionManifestOption {\n if (!isObject(value)) return false\n const { key, path, label, description, type, choices, itemCase } = value\n return (\n isFilledString(key) &&\n Array.isArray(path) &&\n path.length > 0 &&\n path.every((segment) => isFilledString(segment) && !UNSAFE_KEYS.has(segment)) &&\n isFilledString(label) &&\n isOptionalString(description) &&\n OPTION_TYPES.has(type) &&\n (choices === undefined || (Array.isArray(choices) && choices.every((choice) => isObject(choice) && 'value' in choice && isOptionalString(choice.label)))) &&\n (itemCase === undefined || itemCase === 'upper')\n )\n}\n\n/**\n * What is wrong with the options of a well-formed manifest, beyond their shape: keys are unique, a\n * select has choices, and a select's default is one of its choice values. Empty when they pass.\n */\nexport function manifestProblems({ options = [] }: ExtensionManifest): Array<string> {\n const seen = new Set<string>()\n return options.flatMap((option) => {\n const problems = seen.has(option.key) ? [`option \"${option.key}\" is declared more than once`] : []\n seen.add(option.key)\n if (option.type !== 'select') return problems\n if (!option.choices?.length) return [...problems, `option \"${option.key}\" is a select without choices`]\n const knownDefault = !('default' in option) || option.choices.some((choice) => canonicalJSON(choice.value) === canonicalJSON(option.default))\n return knownDefault ? problems : [...problems, `option \"${option.key}\" has a default that is not one of its choices`]\n })\n}\n\n/**\n * Checks a parsed `kubb-extension.json` or a registry response before Kubb or Studio uses it: the\n * fields Kubb reads, every option's shape (including option paths that cannot reach a prototype),\n * and `manifestProblems`. A malformed manifest is skipped instead of trusted.\n */\nexport function isExtensionManifest(value: unknown): value is ExtensionManifest {\n if (!isObject(value)) return false\n const { kind, name, export: exportName, displayName, description, maintainers, dependencies, optionalDependencies, compatibility, role, options } = value\n return (\n EXTENSION_KINDS.has(kind) &&\n isPackageName(name) &&\n typeof exportName === 'string' &&\n IDENTIFIER.test(exportName) &&\n typeof displayName === 'string' &&\n typeof description === 'string' &&\n (maintainers === undefined || (Array.isArray(maintainers) && maintainers.every(isMaintainer))) &&\n (dependencies === undefined || (Array.isArray(dependencies) && dependencies.every(isPackageName))) &&\n (optionalDependencies === undefined || (Array.isArray(optionalDependencies) && optionalDependencies.every(isPackageName))) &&\n (compatibility === undefined ||\n (isObject(compatibility) && Object.entries(compatibility).every(([key, range]) => (key === 'kubb' || key === 'node') && typeof range === 'string'))) &&\n (role === undefined || role === 'client' || role === 'consumer') &&\n (options === undefined || (Array.isArray(options) && options.every(isOption))) &&\n manifestProblems(value as ExtensionManifest).length === 0\n )\n}\n\n/** Checks that no artifact field can reach a package manager as a flag or path, and that a GitHub tag names the version. */\nfunction isRegistryArtifact(value: unknown): value is RegistryArtifact {\n if (!isObject(value) || !isPackageName(value.package) || typeof value.version !== 'string' || !isValid(value.version)) return false\n if (value.kind === 'npm') return true\n return (\n value.kind === 'github' &&\n matches(GITHUB_OWNER, value.owner) &&\n matches(GITHUB_REPO, value.repo) &&\n (value.tag === value.version || value.tag === `v${value.version}`) &&\n matches(COMMIT, value.commit)\n )\n}\n\n/**\n * Checks one entry of a registry's `index.json` or `<owner>/<slug>.json`: a full `<owner>/<slug>` id,\n * an npm or GitHub artifact pinned to a valid version, and a valid manifest of the entry's kind.\n */\nexport function isRegistryEntry(value: unknown): value is RegistryEntry {\n if (!isObject(value)) return false\n const { id, kind, type, artifact, manifest } = value\n return (\n typeof id === 'string' &&\n REGISTRY_ID.test(id) &&\n EXTENSION_KINDS.has(kind) &&\n (type === 'official' || type === 'community') &&\n isRegistryArtifact(artifact) &&\n isExtensionManifest(manifest) &&\n manifest.kind === kind\n )\n}\n","import { existsSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { type ExtensionManifest, isExtensionManifest, isPackageName } from './manifest.ts'\n\nexport type InstalledPackage = { package: string; version?: string; manifest?: ExtensionManifest }\n\n/** Reads and parses a JSON file. Throws when it is missing or not JSON. */\nconst readJSON = async (file: string): Promise<unknown> => JSON.parse(await readFile(file, 'utf8'))\n\n/**\n * The `dependencies` and `devDependencies` of the project at `root`, plus `packages`, with the\n * installed version and the valid `kubb-extension.json` each one ships, when it does. A package\n * also counts as installed when it resolves from one of the `resolveFrom` packages, such as `kubb`\n * for the extensions it ships with.\n */\nexport async function readInstalledPackages({\n root,\n packages = [],\n resolveFrom = [],\n}: {\n root: string\n packages?: Iterable<string>\n resolveFrom?: Array<string>\n}): Promise<Array<InstalledPackage>> {\n const project = createRequire(path.resolve(root, 'package.json'))\n const requires = [\n project,\n ...resolveFrom.flatMap((name) => {\n try {\n return [createRequire(project.resolve(`${name}/package.json`))]\n } catch {\n return []\n }\n }),\n ]\n const packageJSON = (await readJSON(path.join(root, 'package.json')).catch(() => null)) as { dependencies?: unknown; devDependencies?: unknown } | null\n const dependencies = [packageJSON?.dependencies, packageJSON?.devDependencies].flatMap((record) =>\n typeof record === 'object' && record !== null ? Object.keys(record) : [],\n )\n\n return Promise.all(\n [...new Set([...dependencies, ...packages])].filter(isPackageName).map(async (name): Promise<InstalledPackage> => {\n // Found on disk rather than resolved, because an `exports` map may hide `package.json` and the manifest.\n const dir = requires\n .flatMap((require) => require.resolve.paths(name) ?? [])\n .map((dir) => path.join(dir, name))\n .find((dir) => existsSync(path.join(dir, 'package.json')))\n if (!dir) return { package: name }\n try {\n const { version } = (await readJSON(path.join(dir, 'package.json'))) as { version?: unknown }\n const manifest = await readJSON(path.join(dir, 'kubb-extension.json')).catch(() => undefined)\n return { package: name, version: typeof version === 'string' ? version : undefined, manifest: isExtensionManifest(manifest) ? manifest : undefined }\n } catch {\n return { package: name }\n }\n }),\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACkBA,SAAS,gBAAgB,MAAc,QAAyB;CAC9D,OAAO,KACJ,KAAK,CAAC,CACN,QAAQ,qBAAqB,OAAO,CAAC,CACrC,QAAQ,yBAAyB,OAAO,CAAC,CACzC,QAAQ,gBAAgB,OAAO,CAAC,CAChC,MAAM,eAAe,CAAC,CACtB,OAAO,OAAO,CAAC,CACf,KAAK,MAAM,MAAM;EAChB,IAAI,KAAK,SAAS,KAAK,SAAS,KAAK,YAAY,GAAG,OAAO;EAE3D,QADa,MAAM,KAAK,CAAC,SAAS,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,KAC9E,KAAK,MAAM,CAAC;CAC5B,CAAC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AAK,MAAS,IAAA,CAAM,QAAQ,CACrB,EAAE;CAG1B,IAAI,MAAM,KACR,OAAO,IAAI,KAAK,IAAA,CAAM,QAAQ,CAAC,EAAE;CAEnC,OAAO,GAAG,KAAK,MAAM,EAAE,EAAE;AAC3B;;;;;;;;ACjCA,MAAa,oBAAoB;CAC/B,SAAS;EACP,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,eAAe;EACb,MAAM;EACN,OAAO;EACP,OACE;EACF,KAAK;CACP;CACA,oBAAoB;EAClB,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,kBAAkB;EAChB,MAAM;EACN,OAAO;EACP,OACE;EACF,KAAK;CACP;CACA,gBAAgB;EACd,MAAM;EACN,OAAO;EACP,OACE;EACF,KAAK;CACP;CACA,eAAe;EACb,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,aAAa;EACX,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,iBAAiB;EACf,MAAM;EACN,OAAO;EACP,OACE;EACF,KAAK;CACP;CACA,aAAa;EACX,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,aAAa;EACX,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,uBAAuB;EACrB,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,gBAAgB;EACd,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,uBAAuB;EACrB,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,mBAAmB;EACjB,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,wBAAwB;EACtB,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,cAAc;EACZ,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,eAAe;EACb,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,c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AAO,KAAK,MAAM,IAAI,CAAC,CACzE;CAEA,OAAO,QAAQ,IACb,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,cAAc,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,OAAO,aAAa,CAAC,CAAC,IAAI,OAAO,SAAoC;EAEhH,MAAM,MAAM,SACT,SAAS,cAAYC,UAAQ,QAAQ,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,CACvD,KAAK,QAAQD,UAAAA,QAAK,KAAK,KAAK,IAAI,CAAC,CAAC,CAClC,MAAM,SAAA,GAAQE,QAAAA,WAAAA,CAAWF,UAAAA,QAAK,KAAK,KAAK,cAAc,CAAC,CAAC;EAC3D,IAAI,CAAC,KAAK,OAAO,EAAE,SAAS,KAAK;EACjC,IAAI;GACF,MAAM,EAAE,YAAa,MAAM,SAASA,UAAAA,QAAK,KAAK,KAAK,cAAc,CAAC;GAClE,MAAM,WAAW,MAAM,SAASA,UAAAA,QAAK,KAAK,KAAK,qBAAqB,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS;GAC5F,OAAO;IAAE,SAAS;IAAM,SAAS,OAAO,YAAY,WAAW,UAAU,KAAA;IAAW,UAAU,oBAAoB,QAAQ,IAAI,WAAW,KAAA;GAAU;EACrJ,QAAQ;GACN,OAAO,EAAE,SAAS,KAAK;EACzB;CACF,CAAC,CACH;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["process","process","readFile","resolve","writeFile","mkdir","dirname","globNode","relative","join","isAbsolute","x","styleText","stripVTControlCharacters","AsyncLocalStorage","kubbVersion","satisfies","AsyncLocalStorage","path","net","net","dns","x","process","mkdtemp","join","tmpdir","rm","resolve","relative","sep","isAbsolute","resolve","path","collectImportedRefNames","ast","extractStringsFromNodes","readFile","ast","ast","resolve","collectUsedSchemaNames","hash","resolve","rm","join","existsSync","tmpdir","hash","process","randomUUID","x","styleText","existsSync","resolve","resolve","styleText","relative","isAbsolute","styleText","logLevel","logLevelMap","resolve","process","join","homedir","tmpdir","hash","createUnstorage","fsDriver","stripVTControlCharacters","resolve","process","relative","join","resolve","fileURLToPath","join","relative","isValid","readFile","createRequire","path","require","existsSync"],"sources":["../package.json","../../../internals/utils/src/casing.ts","../../../internals/utils/src/errors.ts","../../../internals/utils/src/isCIEnvironment.ts","../../../internals/utils/src/jsonPointer.ts","../../../internals/utils/src/openInBrowser.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/promise.ts","../../../internals/utils/src/tools.ts","../../../internals/utils/src/time.ts","../src/diagnosticCatalog.ts","../src/formatDiagnostic.ts","../src/Diagnostics.ts","../src/defineExtension.ts","../src/createAdapter.ts","../src/composables.ts","../src/definePlugin.ts","../src/publicAddress.ts","../src/gitInput.ts","../src/input.ts","../src/Resolver.ts","../src/createResolver.ts","../src/FileManager.ts","../src/nodeCache.ts","../src/KubbDriver.ts","../src/outputManifest.ts","../src/createStorage.ts","../src/storages/fsStorage.ts","../src/storages/cacheStorage.ts","../src/Hookable.ts","../src/output/runHook.ts","../src/output/runOutputPasses.ts","../src/createKubb.ts","../src/createReporter.ts","../src/reporters/report.ts","../src/reporters/summary.ts","../src/reporters/cliReporter.ts","../src/storages/kubbStorage.ts","../src/reporters/fileReporter.ts","../src/reporters/jsonReporter.ts","../src/reporters/htmlReporter.ts","../src/createRenderer.ts","../src/defineGenerator.ts","../src/defineParser.ts","../src/storages/memoryStorage.ts","../src/manifest.ts","../src/installedPackages.ts"],"sourcesContent":["","type Options = {\n /**\n * Text prepended before casing is applied.\n */\n prefix?: string\n /**\n * Text appended before casing is applied.\n */\n suffix?: string\n}\n\n/**\n * Shared implementation for camelCase and PascalCase conversion.\n * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)\n * and capitalizes each word according to `pascal`.\n *\n * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.\n */\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n return text\n .trim()\n .replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/(\\d)([a-z])/g, '$1 $2')\n .split(/[\\s\\-_./\\\\:]+/)\n .filter(Boolean)\n .map((word, i) => {\n if (word.length > 1 && word === word.toUpperCase()) return word\n const head = i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()\n return head + word.slice(1)\n })\n .join('')\n .replace(/[^a-zA-Z0-9]/g, '')\n}\n\n/**\n * Converts `text` to camelCase.\n *\n * @example Word boundaries\n * `camelCase('hello-world') // 'helloWorld'`\n *\n * @example With a prefix\n * `camelCase('tag', { prefix: 'create' }) // 'createTag'`\n */\nexport function camelCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n *\n * @example Word boundaries\n * `pascalCase('hello-world') // 'HelloWorld'`\n *\n * @example With a suffix\n * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`\n */\nexport function pascalCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n","/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new Error('Build failed', { cause: toError(err) })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Returns `error` followed by every error in its `cause` chain, outermost first. Stops at a\n * non-`Error` cause or a cycle.\n *\n * @example\n * ```ts\n * getErrorChain(new Error('Config failed loading', { cause: new Error('boom') })).map((error) => error.message)\n * // ['Config failed loading', 'boom']\n * ```\n */\nexport function getErrorChain(error: unknown): Array<Error> {\n const chain: Array<Error> = []\n for (let current = error; current instanceof Error && !chain.includes(current); current = current.cause) {\n chain.push(current)\n }\n return chain\n}\n","import process from 'node:process'\n\n/**\n * Returns `true` when a known CI provider has set its environment variable.\n * `CI=false` and `CI=0` count as not CI, so a user can opt out locally.\n */\nexport function isCIEnvironment(): boolean {\n const ci = process.env.CI\n return !!(\n (ci && ci !== 'false' && ci !== '0') ||\n process.env.GITHUB_ACTIONS ||\n process.env.GITLAB_CI ||\n process.env.BITBUCKET_BUILD_NUMBER ||\n process.env.JENKINS_URL ||\n process.env.CIRCLECI ||\n process.env.TRAVIS ||\n process.env.TEAMCITY_VERSION ||\n process.env.BUILDKITE ||\n process.env.TF_BUILD\n )\n}\n","/**\n * Escapes a single JSON pointer reference token per RFC 6901 (`~` → `~0`, `/` → `~1`), so a\n * name holding those characters maps to a distinct pointer.\n *\n * @example\n * ```ts\n * escapePointerToken('/pets/{id}') // '~1pets~1{id}'\n * ```\n */\nexport function escapePointerToken(token: string): string {\n return token.replaceAll('~', '~0').replaceAll('/', '~1')\n}\n","import process from 'node:process'\nimport { x } from 'tinyexec'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\n\nconst ignore = () => {}\n\n/**\n * Opens a URL or local file in the default browser, unless running in CI.\n */\nexport function openInBrowser(target: string): void {\n if (isCIEnvironment()) return\n\n if (process.platform === 'win32') {\n x('cmd', ['/c', 'start', '', target]).then(ignore, ignore)\n return\n }\n x(process.platform === 'darwin' ? 'open' : 'xdg-open', [target]).then(ignore, ignore)\n}\n","// Bun polyfills `process.versions.node`, so detection keys off the globals instead.\nconst isBun = typeof Bun !== 'undefined'\nconst isDeno = 'Deno' in globalThis\n\n/**\n * The JavaScript runtime executing the current process: its name, version and whether it is Bun.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\nexport const runtime = { isBun, ...detect() } as const\n\nfunction detect(): { name: 'bun' | 'deno' | 'node'; version: string } {\n if (isBun) return { name: 'bun', version: process.versions.bun ?? '' }\n if (isDeno) return { name: 'deno', version: (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? '' }\n return { name: 'node', version: process.versions?.node ?? '' }\n}\n","import { access, glob as globNode, mkdir, readFile, writeFile } from 'node:fs/promises'\n\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\nexport { existsSync } from 'node:fs'\nexport { mkdir, mkdtemp, rm } from 'node:fs/promises'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n await writeRaw(resolved, content)\n\n if (options.sanity) {\n const savedData = await read(resolved)\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Writes UTF-8 content verbatim, including empty files and surrounding whitespace.\n * Uses Bun.write under Bun and creates missing parent directories under either runtime.\n *\n * @example\n * await writeRaw('./cache/output.ts', ' // keep these bytes\\n\\n')\n */\nexport async function writeRaw(path: string, content: string): Promise<void> {\n const resolved = resolve(path)\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return\n }\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n}\n\n/**\n * Lists non-hidden regular files below `directory` as relative POSIX paths, excluding directories and symlinks.\n * Uses Bun.Glob under Bun because its Node glob compatibility API lacks directory-entry support.\n *\n * @example\n * for await (const path of listFiles('./src')) console.log(path)\n */\nexport async function* listFiles(directory: string): AsyncGenerator<string> {\n const cwd = resolve(directory)\n if (runtime.isBun) {\n yield* new Bun.Glob('**/*').scan({ cwd, dot: false, onlyFiles: true, followSymlinks: false })\n return\n }\n for await (const entry of globNode('**/*', { cwd, withFileTypes: true })) {\n if (entry.isFile()) yield toPosixPath(relative(cwd, join(entry.parentPath, entry.name)))\n }\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\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\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 ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { x } from 'tinyexec'\n\n/**\n * How one formatter or linter is invoked: the executable, the argv it takes for an output\n * directory, and what to report when it is not installed.\n */\nexport type ToolCommand = {\n command: string\n args: (outputPath: string) => Array<string>\n errorMessage: string\n}\n\n/**\n * CLI command descriptors for each supported code formatter.\n */\nexport const formatters = {\n prettier: {\n command: 'prettier',\n args: (outputPath: string) => ['--ignore-unknown', '--write', outputPath],\n errorMessage: 'Prettier not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['format', '--write', outputPath],\n errorMessage: 'Biome not found',\n },\n oxfmt: {\n command: 'oxfmt',\n args: (outputPath: string) => [outputPath],\n errorMessage: 'Oxfmt not found',\n },\n} as const satisfies Record<string, ToolCommand>\n\n/**\n * CLI command descriptors for each supported linter.\n */\nexport const linters = {\n eslint: {\n command: 'eslint',\n args: (outputPath: string) => [outputPath, '--fix'],\n errorMessage: 'Eslint not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['lint', '--fix', outputPath],\n errorMessage: 'Biome not found',\n },\n oxlint: {\n command: 'oxlint',\n // --no-ignore so oxlint lints the folder even when it's gitignored (generated output dirs usually are).\n args: (outputPath: string) => ['--fix', '--no-ignore', outputPath],\n errorMessage: 'Oxlint not found',\n },\n} as const satisfies Record<string, ToolCommand>\n\n/**\n * Preference order for `format: 'auto'`, most-preferred first. Spelled out rather than taken from\n * the table's key order, which is arbitrary and would silently change what `auto` picks.\n */\nexport const FORMATTER_PREFERENCE = ['oxfmt', 'biome', 'prettier'] as const\n\n/**\n * Preference order for `lint: 'auto'`, most-preferred first.\n */\nexport const LINTER_PREFERENCE = ['oxlint', 'biome', 'eslint'] as const\n\n/**\n * Whether `name` is on PATH or in a `node_modules/.bin` above `cwd` and answers `--version` with a zero exit.\n */\nasync function isToolAvailable(name: string, cwd?: string): Promise<boolean> {\n return x(name, ['--version'], { throwOnError: false, nodeOptions: { cwd, stdio: 'ignore' } }).then(\n ({ exitCode }) => exitCode === 0,\n () => false,\n )\n}\n\n/**\n * Returns the first installed executable from `candidates`, or `null` when none are found.\n *\n * Not memoized: a long-running host that probes repeatedly should cache the result itself, and a\n * `--watch` build should keep noticing a tool installed mid-session.\n */\nexport async function detectTool<TName extends string>(candidates: ReadonlyArray<TName>, cwd?: string): Promise<TName | null> {\n for (const candidate of candidates) {\n if (await isToolAvailable(candidate, cwd)) {\n return candidate\n }\n }\n\n return null\n}\n\n/**\n * Tokenizes a shell command string, respecting single and double quotes.\n *\n * @example\n * ```ts\n * tokenize('git commit -m \"initial commit\"')\n * // → ['git', 'commit', '-m', 'initial commit']\n * ```\n */\nexport function tokenize(command: string): Array<string> {\n return (command.match(/[^\\s\"']+|\"([^\"]*)\"|'([^']*)'/g) ?? []).map((token) => token.replace(/^[\"']|[\"']$/g, ''))\n}\n","/**\n * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.\n * Rounds to 2 decimal places for sub-millisecond precision without noise.\n *\n * @example\n * ```ts\n * const start = process.hrtime()\n * doWork()\n * getElapsedMs(start) // 42.35\n * ```\n */\nexport function getElapsedMs(hrStart: [number, number]): number {\n const [seconds, nanoseconds] = process.hrtime(hrStart)\n const ms = seconds * 1000 + nanoseconds / 1e6\n return Math.round(ms * 100) / 100\n}\n\n/**\n * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).\n *\n * @example\n * ```ts\n * formatMs(250) // '250ms'\n * formatMs(1500) // '1.50s'\n * formatMs(90000) // '1m 30.0s'\n * ```\n */\nexport function formatMs(ms: number): string {\n if (ms >= 60000) {\n const mins = Math.floor(ms / 60000)\n const secs = ((ms % 60000) / 1000).toFixed(1)\n return `${mins}m ${secs}s`\n }\n\n if (ms >= 1000) {\n return `${(ms / 1000).toFixed(2)}s`\n }\n return `${Math.round(ms)}ms`\n}\n","/**\n * Every diagnostic code with its docs entry: a short title, what triggers it, and how to resolve\n * it. The source of truth for {@link diagnosticCode}, and the kubb.dev `/reference/diagnostics`\n * sections mirror it.\n */\nexport const diagnosticCatalog = {\n unknown: {\n code: 'KUBB_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 inputNotFound: {\n code: 'KUBB_INPUT_NOT_FOUND',\n title: 'Input not found',\n cause:\n 'The file set as `input` (or passed as `kubb generate PATH`) could not be read. A URL reports `KUBB_INPUT_REQUEST_FAILED` or `KUBB_INPUT_UNREACHABLE` instead.',\n fix: 'Check that the path exists and is readable, then set it as `input` or pass it on the CLI.',\n },\n inputRequestFailed: {\n code: 'KUBB_INPUT_REQUEST_FAILED',\n title: 'Input request failed',\n cause: 'A URL set as `input` (or reached through a `$ref`) answered with a 4xx or 5xx status instead of the document.',\n fix: 'Open the URL to see what the server returns. A 401 or 403 needs credentials Kubb does not send, so download the document and point `input` at the local file. A 404 means the path is wrong, and a 5xx means the server itself failed.',\n },\n inputUnreachable: {\n code: 'KUBB_INPUT_UNREACHABLE',\n title: 'Input unreachable',\n cause:\n 'A URL set as `input` (or reached through a `$ref`) never answered, so the request failed before a status came back. A refused connection, an unknown host, an expired certificate, and a timeout all land here.',\n fix: 'Check that the host is running and reachable from this machine. For a local server, start it and confirm the port matches the one in `input`.',\n },\n gitInputFailed: {\n code: 'KUBB_GIT_INPUT_FAILED',\n title: 'Git input failed',\n cause:\n 'A git `input` (`git+<repo>#<ref>:<path>`) is malformed, or `git` could not fetch it: git is not installed, the repository or ref does not exist, or the credentials were refused.',\n fix: 'Write the input as `git+<repo>#<ref>:<path>`. Run `git fetch --depth 1 <repo> <ref>` yourself to see the git error, and set up a credential helper or SSH key for a private repository.',\n },\n inputRequired: {\n code: 'KUBB_INPUT_REQUIRED',\n title: 'Input required',\n cause: 'An adapter is configured but no `input` was provided.',\n fix: 'Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.',\n },\n legacyInput: {\n code: 'KUBB_LEGACY_INPUT',\n title: 'Legacy input shape',\n cause: '`input` is a `{ path }` or `{ data }` wrapper, which v4 used to point at a document and v5 reads as the document itself.',\n fix: 'Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`.',\n },\n invalidDocument: {\n code: 'KUBB_INVALID_DOCUMENT',\n title: 'Invalid document',\n cause:\n 'The `input` cannot be read as an OpenAPI or Swagger document: its JSON or YAML has a syntax error, it declares no `openapi` or `swagger` version field, or its version cannot be upgraded to OpenAPI 3.1.',\n fix: 'Fix the syntax at the reported line, and check that `input` points at the spec and not an HTML page. Point `input` at a Swagger 2.0, OpenAPI 3.0, or OpenAPI 3.1 document, and check that a passed object is the spec itself rather than a wrapper around it.',\n },\n invalidSpec: {\n code: 'KUBB_INVALID_SPEC',\n title: 'Invalid spec',\n cause: 'The document does not pass OpenAPI schema validation. Kubb still generates from it, but the output can be incomplete or wrong.',\n fix: 'Fix the reported problem in the spec. Run `kubb validate` to list every error, or set `validate: false` on the adapter to skip the check.',\n },\n refNotFound: {\n code: 'KUBB_REF_NOT_FOUND',\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 invalidServerVariable: {\n code: 'KUBB_INVALID_SERVER_VARIABLE',\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 pluginNotFound: {\n code: 'KUBB_PLUGIN_NOT_FOUND',\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 incompatibleExtension: {\n code: 'KUBB_INCOMPATIBLE_EXTENSION',\n title: 'Incompatible extension',\n cause: 'A plugin sets `meta.compatibility.kubb` or `meta.compatibility.node` to a range the running Kubb or Node.js version does not satisfy.',\n fix: 'Upgrade Kubb or Node.js to a version in the range, or install a version of the plugin that supports your current Kubb and Node.js.',\n },\n missingDependency: {\n code: 'KUBB_MISSING_DEPENDENCY',\n title: 'Missing dependency',\n cause: 'A plugin lists another plugin in its `dependencies` record without `optional: true`, and the config does not include it.',\n fix: 'Add the missing plugin to the `plugins` array in kubb.config.ts.',\n },\n incompatibleDependency: {\n code: 'KUBB_INCOMPATIBLE_DEPENDENCY',\n title: 'Incompatible dependency',\n cause: \"A plugin's `dependencies` record sets a `version` range, and the configured plugin's `meta.version` falls outside it.\",\n fix: 'Install a version of the dependency inside the range, or a version of the dependent plugin that supports the installed dependency.',\n },\n pluginFailed: {\n code: 'KUBB_PLUGIN_FAILED',\n title: 'Plugin failed',\n cause: 'A plugin threw while generating, or reported an error through `ctx.error`.',\n fix: 'Check the plugin options and the node at `at:`. If it is a bug, report it with the stack at `report:`.',\n },\n adapterFailed: {\n code: 'KUBB_ADAPTER_FAILED',\n title: 'Adapter failed',\n cause: 'The adapter threw an unexpected error while parsing the input.',\n fix: 'Check the input and the adapter options. If it is a bug, report it with the stack at `report:`.',\n },\n parserFailed: {\n code: 'KUBB_PARSER_FAILED',\n title: 'Parser failed',\n cause: 'A parser threw an unexpected error while printing a generated file.',\n fix: 'Check the parser options. If it is a bug, report it with the stack at `report:`.',\n },\n pluginWarning: {\n code: 'KUBB_PLUGIN_WARNING',\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 pluginInfo: {\n code: 'KUBB_PLUGIN_INFO',\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 noContext: {\n code: 'KUBB_NO_CONTEXT',\n title: 'No plugin context',\n cause:\n 'A `kubb/kit` composable such as `useKubb()` or `addGenerator()` ran outside the `setup` and `kubb:plugin:setup` of a plugin, so there is no plugin to apply it to.',\n fix: 'Call the composable inside `setup` or `kubb:plugin:setup`, including in code that setup awaits.',\n },\n unsupportedFormat: {\n code: 'KUBB_UNSUPPORTED_FORMAT',\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 deprecated: {\n code: 'KUBB_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 adapterRequired: {\n code: 'KUBB_ADAPTER_REQUIRED',\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 pathTraversal: {\n code: 'KUBB_PATH_TRAVERSAL',\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 cleanRoot: {\n code: 'KUBB_CLEAN_ROOT',\n title: 'Clean targets the project root',\n cause:\n '`output.clean` is enabled and `output.path` resolves to the project root or a parent of it, so cleaning would delete `kubb.config` and every source file.',\n fix: 'Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code, or disable `output.clean`.',\n },\n invalidPluginOptions: {\n code: 'KUBB_INVALID_PLUGIN_OPTIONS',\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 postGenerateFailed: {\n code: 'KUBB_POST_GENERATE_FAILED',\n title: 'Post-generate command failed',\n cause: 'A post-generate command (`output.postGenerate`) exited with a non-zero status.',\n fix: 'Check the command is installed and correct, and run it manually to see the error.',\n },\n formatFailed: {\n code: 'KUBB_FORMAT_FAILED',\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 lintFailed: {\n code: 'KUBB_LINT_FAILED',\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 barrelDuplicateExport: {\n code: 'KUBB_BARREL_DUPLICATE_EXPORT',\n title: 'Duplicate barrel export',\n cause: 'Two generated modules export the same name, so the barrel cannot re-export both.',\n fix: 'Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names.',\n },\n internalError: {\n code: 'KUBB_INTERNAL_ERROR',\n title: 'Internal error',\n cause: 'Kubb hit a state it does not expect. This is a bug in Kubb, not in your config.',\n fix: 'Rerun with `--reporter json` or `--verbose` to get the stack. Then report it at https://github.com/kubb-labs/kubb/issues with the spec and config that trigger it.',\n },\n performance: {\n code: 'KUBB_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 updateAvailable: {\n code: 'KUBB_UPDATE_AVAILABLE',\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} as const satisfies Record<string, { code: `KUBB_${string}`; title: string; cause: string; fix: string }>\n\n/**\n * Stable codes Kubb attaches to a `Diagnostic`, derived from {@link diagnosticCatalog}. Reference\n * these instead of inlining the string at a throw site.\n */\nexport const diagnosticCode = Object.fromEntries(Object.entries(diagnosticCatalog).map(([key, { code }]) => [key, code])) as {\n readonly [K in keyof typeof diagnosticCatalog]: (typeof diagnosticCatalog)[K]['code']\n}\n\n/**\n * Union of the stable {@link diagnosticCode} values.\n */\nexport type DiagnosticCode = (typeof diagnosticCode)[keyof typeof diagnosticCode]\n","import { stripVTControlCharacters, styleText } from 'node:util'\nimport { getErrorChain } from '@internals/utils'\nimport { type DiagnosticCode, diagnosticCode } from './diagnosticCatalog.ts'\nimport { type Diagnostic, type DiagnosticLocation, Diagnostics, type DiagnosticSeverity, type ProblemDiagnostic } from './Diagnostics.ts'\n\n/** A problem's `help`, or the catalog fix. `info` gets none: its catalog fix says no action is needed. */\nfunction getHelp(problem: ProblemDiagnostic): string | undefined {\n if (problem.help || problem.severity === 'info') return problem.help\n return Diagnostics.explain(problem.code).fix\n}\n\n/** The `cause` chain's messages, outermost first, minus those `message` already contains. */\nfunction getCauses(problem: ProblemDiagnostic): Array<string> {\n return getErrorChain(problem.cause)\n .filter((error) => !problem.message.includes(error.message))\n .map((error) => (error.name === 'Error' ? error.message : `${error.name}: ${error.message}`))\n}\n\n/**\n * Accent color per severity, which paints the icon in the `human` layout (red error, yellow\n * warning, blue info). The code itself stays dim.\n */\nconst severityStyle: Record<DiagnosticSeverity, 'red' | 'yellow' | 'blue'> = {\n error: 'red',\n warning: 'yellow',\n info: 'blue',\n}\n\nconst severityIcon: Record<DiagnosticSeverity, string> = {\n error: '✖',\n warning: '⚠',\n info: 'ℹ',\n}\n\n/**\n * How {@link format} renders a diagnostic.\n */\nexport type DiagnosticFormatOptions = {\n /**\n * Who reads the output.\n * - `'agent'` spells out every detail on labeled rows\n * - `'human'` keeps it short and links to the docs\n * @default 'agent'\n */\n audience?: 'agent' | 'human'\n /**\n * Show the root cause's full stack.\n */\n verbose?: boolean\n /**\n * Columns the `human` headline fills, so the code lines up at the right edge.\n * @default 0\n */\n width?: number\n /**\n * Where the diagnostic's pointer sits in the input file, when the host resolved it. Replaces the\n * pointer on the `at` row, and an error's `human` layout draws `frame` under it.\n */\n position?: { file: string; line: number; column: number; frame?: Array<string> }\n}\n\n/**\n * Codes for a crash, which carry the root cause's stack.\n */\nexport const crashCodes: ReadonlySet<DiagnosticCode> = new Set([\n diagnosticCode.unknown,\n diagnosticCode.internalError,\n diagnosticCode.pluginFailed,\n diagnosticCode.adapterFailed,\n diagnosticCode.parserFailed,\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). Replaces the\n * non-serializable `cause` with its message chain and drops the `kind`/`duration` bookkeeping.\n */\nexport type SerializedDiagnostic = {\n code: DiagnosticCode\n severity: DiagnosticSeverity\n message: string\n /**\n * Catalog title.\n */\n title?: string\n /**\n * Catalog cause.\n */\n cause?: string\n location?: DiagnosticLocation\n /**\n * The diagnostic's `help`, or the catalog fix.\n */\n help?: string\n plugin?: string\n issues?: string\n /**\n * Messages of the underlying errors, outermost first.\n */\n causes?: Array<string>\n /**\n * Root cause's stack, for `KUBB_UNKNOWN`, `KUBB_INTERNAL_ERROR`, and `*_FAILED` codes.\n */\n stack?: string\n /**\n * The kubb.dev docs link for the code, omitted for the unknown fallback.\n */\n docsUrl?: string\n}\n\n/**\n * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable\n * consumers, with the catalog `title`, `cause`, and fix, and the `cause` error as `causes` and\n * `stack`. Absent optional fields are omitted.\n */\nexport function serialize(diagnostic: Diagnostic): SerializedDiagnostic {\n const problem = Diagnostics.isProblem(diagnostic) ? diagnostic : undefined\n const doc = problem ? Diagnostics.explain(problem.code) : undefined\n const help = problem ? getHelp(problem) : undefined\n const causes = problem ? getCauses(problem) : []\n const stack = problem && crashCodes.has(problem.code) ? getErrorChain(problem.cause).at(-1)?.stack : undefined\n return {\n code: diagnostic.code,\n severity: diagnostic.severity,\n message: diagnostic.message,\n ...(doc ? { title: doc.title, cause: doc.cause } : {}),\n ...(problem?.location ? { location: problem.location } : {}),\n ...(help ? { help } : {}),\n ...(problem?.plugin ? { plugin: problem.plugin } : {}),\n ...(problem?.issues ? { issues: problem.issues } : {}),\n ...(causes.length ? { causes } : {}),\n ...(stack ? { stack } : {}),\n ...(diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }),\n }\n}\n\n/**\n * Renders a {@link Diagnostic} as lines: a headline, then indented detail rows. `agent` (the default)\n * prints uncolored labeled rows (`at:`, `why:`, `fix:`, `caused by:`, `stack:` for a crash,\n * `docs:`, `report:`). `human` prints an icon, the bold message, and the code aligned to `width`,\n * with `at`, `fix`, the first cause, and `Learn more` for an error, and one row for a warning.\n * `verbose` adds the full stack.\n */\nexport function format(diagnostic: Diagnostic, { audience = 'agent', verbose = false, width = 0, position }: DiagnosticFormatOptions = {}): Array<string> {\n const { code, severity, message } = diagnostic\n const problem = Diagnostics.isProblem(diagnostic) ? diagnostic : undefined\n const human = audience === 'human'\n const paint: typeof styleText = human ? styleText : (_format, text) => text\n\n const [firstLine = '', ...rest] = message.split('\\n')\n const pointer = problem?.location && 'pointer' in problem.location ? problem.location.pointer : undefined\n const at = position ? `${position.file}:${position.line}:${position.column}` : undefined\n const where = at ?? pointer\n const help = problem ? getHelp(problem) : undefined\n const causes = problem ? getCauses(problem) : []\n const crash = problem ? crashCodes.has(problem.code) : false\n const stack = problem && (verbose || (!human && crash)) ? getErrorChain(problem.cause).at(-1)?.stack : undefined\n const frames = stack\n ?.split('\\n')\n .slice(1, verbose ? undefined : 4)\n .map((frame) => ` ${paint('dim', frame.trim())}`)\n\n if (!human) {\n const details = rest.filter((line) => line.trim()).map((line) => ` ${line}`)\n const row = (label: string, value: string | undefined) => {\n if (value) details.push(` ${label}: ${value}`)\n }\n row('at', at && pointer ? `${at} (${pointer})` : pointer)\n if (problem && severity !== 'info') row('why', Diagnostics.explain(problem.code).cause)\n row('fix', help)\n for (const cause of causes) row('caused by', cause)\n if (frames?.length) details.push(' stack:', ...frames)\n if (code !== diagnosticCode.unknown) row('docs', Diagnostics.docsUrl(code))\n row('report', problem?.issues)\n\n return [`${severity} ${code}${problem?.plugin ? ` [${problem.plugin}]` : ''}: ${firstLine}`, ...details]\n }\n\n const left = `${paint(severityStyle[severity], severityIcon[severity])} ${paint('bold', firstLine)}`\n const gap = width - stripVTControlCharacters(left).length - code.length\n // A headline too long to share its row with the code would wrap mid-code, so the code drops to its own right-aligned row.\n const headline =\n width && gap < 2\n ? [left, `${' '.repeat(Math.max(0, width - code.length))}${paint('dim', code)}`]\n : [`${left}${' '.repeat(Math.max(2, gap))}${paint('dim', code)}`]\n\n const frame = rest.filter((line) => line.trim()).map((line) => ` ${paint('dim', line)}`)\n const label = (name: string) => paint('dim', name.length < 4 ? name.padEnd(4) : `${name} `)\n const rows: Array<[label: string, value: string | undefined]> = [\n ['at', where && paint('cyan', where)],\n ['fix', help],\n ]\n if (severity !== 'error') {\n const first = rows.find(([, value]) => value)\n return [...headline, ...frame, ...(first ? [` ${label(first[0])} ${first[1]}`] : [])]\n }\n rows.push(['caused by', causes[0]], ['report', problem?.issues && paint('cyan', problem.issues)])\n\n const codeFrame = (position?.frame ?? []).map((line) => ` ${line}`)\n const details = [...frame, ...rows.flatMap(([name, value]) => (value ? [` ${label(name)} ${value}`, ...(name === 'at' ? codeFrame : [])] : []))]\n if (frames?.length) details.push(` ${paint('dim', 'stack')}`, ...frames)\n if (code !== diagnosticCode.unknown) {\n details.push(` ${paint('dim', '↳ Learn more')} ${paint('cyan', Diagnostics.docsUrl(code).replace(/^https:\\/\\//, ''))}`)\n }\n\n return [...headline, ...details]\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { getErrorChain, getErrorMessage, toError } from '@internals/utils'\nimport { version } from '../package.json'\nimport { type DiagnosticCode, diagnosticCatalog, diagnosticCode } from './diagnosticCatalog.ts'\nimport { crashCodes, format, serialize } from './formatDiagnostic.ts'\nimport type { ExtensionKind, ExtensionNamed } from './defineExtension.ts'\nimport type { KubbHooks } from './types.ts'\nimport type { Hookable } from './Hookable.ts'\n\n/**\n * Docs major version, derived from the package version so the link tracks the published major.\n */\nconst docsMajor = version.split('.')[0] ?? '5'\n\n/**\n * How serious a diagnostic is. `error` fails the build, `warning` and `info`\n * are reported but do not.\n */\nexport type DiagnosticSeverity = 'error' | 'warning' | 'info'\n\n/**\n * A human-readable explanation of a diagnostic code: a short title, what triggers it, and how\n * to resolve it. This is the source of truth the kubb.dev `/reference/diagnostics#<slug>` sections 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 /** Issue tracker URL of the extension that crashed, from its `meta.issues`. */\n issues?: string\n /**\n * The underlying error, when the diagnostic wraps a thrown one.\n */\n cause?: Error\n}\n\n/**\n * A per-plugin performance record, built with {@link Diagnostics.performance}. The `performance`\n * kind keeps it out of the problem list. It feeds the per-plugin timing bars, and reporters sum\n * these into the run total.\n */\nexport type PerformanceDiagnostic = {\n kind: 'performance'\n code: typeof diagnosticCode.performance\n severity: 'info'\n message: string\n /**\n * The plugin this measurement belongs to.\n */\n plugin: string\n /**\n * Elapsed milliseconds.\n */\n duration: number\n}\n\n/**\n * A notice that a newer Kubb version is available on npm, built with {@link Diagnostics.update}.\n * It renders like any info diagnostic.\n */\nexport type UpdateDiagnostic = {\n kind: 'update'\n code: typeof diagnosticCode.updateAvailable\n severity: 'info'\n message: string\n /**\n * The running Kubb version.\n */\n currentVersion: string\n /**\n * The newest version published on npm.\n */\n latestVersion: string\n}\n\n/**\n * A structured record collected during a build, discriminated on `kind`: a\n * {@link ProblemDiagnostic} for an issue, a {@link PerformanceDiagnostic} for a per-plugin\n * timing, or an {@link UpdateDiagnostic} for a version notice.\n */\nexport type Diagnostic = ProblemDiagnostic | PerformanceDiagnostic | UpdateDiagnostic\n\n/**\n * Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic\n * with no `kind` is treated as a `problem`.\n */\nfunction isKind<T extends Diagnostic>(kind: DiagnosticKind) {\n return (diagnostic: Diagnostic): diagnostic is T => (diagnostic.kind ?? 'problem') === kind\n}\n\n/**\n * Returns `true` when the diagnostic is a build {@link ProblemDiagnostic}.\n *\n * @example\n * ```ts\n * if (isProblem(diagnostic)) {\n * console.log(diagnostic.location)\n * }\n * ```\n */\nconst isProblem = isKind<ProblemDiagnostic>('problem')\n\n/**\n * Returns `true` when the diagnostic is a per-plugin {@link PerformanceDiagnostic}.\n *\n * @example\n * ```ts\n * const timings = diagnostics.filter(isPerformance)\n * ```\n */\nconst isPerformance = isKind<PerformanceDiagnostic>('performance')\n\n/**\n * Returns `true` when the diagnostic is a version-update {@link UpdateDiagnostic}.\n *\n * @example\n * ```ts\n * if (isUpdate(diagnostic)) {\n * console.log(diagnostic.latestVersion)\n * }\n * ```\n */\nconst isUpdate = isKind<UpdateDiagnostic>('update')\n\nconst failedCode = {\n plugin: diagnosticCode.pluginFailed,\n adapter: diagnosticCode.adapterFailed,\n parser: diagnosticCode.parserFailed,\n} as const satisfies Record<ExtensionKind, ProblemCode>\n\nconst docsByCode = new Map<DiagnosticCode, DiagnosticDoc>(Object.values(diagnosticCatalog).map((doc) => [doc.code, doc]))\n\nconst reporterKey = Symbol.for('kubb.diagnostics.reporter')\n\ntype ReporterHost = typeof globalThis & { [reporterKey]?: AsyncLocalStorage<(diagnostic: Diagnostic) => void> }\n\nconst countKey = { error: 'errors', warning: 'warnings', info: 'infos' } as const satisfies Record<DiagnosticSeverity, string>\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` on `globalThis`, shared by every copy of `@kubb/core`.\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 // A plugin that loads another copy of `@kubb/core` (the project's own, beside a host such as the\n // Studio agent) still reports into the run, as `kubbContext` does.\n static #reporterStorage: AsyncLocalStorage<(diagnostic: Diagnostic) => void> = ((globalThis as ReporterHost)[reporterKey] ??= new AsyncLocalStorage())\n\n /**\n * The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).\n */\n static code = diagnosticCode\n\n /**\n * Type guard for a build {@link ProblemDiagnostic}.\n */\n static isProblem = isProblem\n\n /**\n * Type guard for a version-update {@link UpdateDiagnostic}.\n */\n static isUpdate = isUpdate\n\n /**\n * Type guard for a per-plugin {@link PerformanceDiagnostic}.\n */\n static isPerformance = isPerformance\n\n /**\n * An `Error` that carries a {@link Diagnostic}, so structured problems can flow\n * through the existing throw/catch paths while keeping their code and location.\n *\n * @example\n * ```ts\n * throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })\n * ```\n */\n static Error = class DiagnosticError extends Error {\n diagnostic: ProblemDiagnostic\n\n constructor(diagnostic: ProblemDiagnostic) {\n super(diagnostic.message, { cause: diagnostic.cause })\n this.name = 'DiagnosticError'\n this.diagnostic = diagnostic\n }\n }\n\n /**\n * Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated\n * `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`\n * that carries a `code`.\n */\n static isError(error: unknown): error is InstanceType<typeof Diagnostics.Error> {\n if (error instanceof Diagnostics.Error) return true\n if (!(error instanceof Error) || error.name !== 'DiagnosticError') return false\n\n const { diagnostic } = error as { diagnostic?: { code?: unknown } }\n return typeof diagnostic === 'object' && diagnostic !== null && typeof diagnostic.code === 'string'\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, or any thrown value, on the run's hooks so the loggers render it live.\n * A coded problem or an update goes to `kubb:diagnostic`. An uncoded one goes to `kubb:error`\n * whole, so every wrapper's message, its help, and the stack survive. To collect a diagnostic into\n * the build result from deep in a run, use {@link Diagnostics.report} instead.\n */\n static async emit(hooks: Hookable<KubbHooks>, value: ProblemDiagnostic | UpdateDiagnostic | unknown): Promise<void> {\n const thrown = value instanceof Error || typeof (value as Diagnostic | undefined)?.code !== 'string'\n const diagnostic = thrown ? Diagnostics.from(value) : (value as ProblemDiagnostic | UpdateDiagnostic)\n if (!isProblem(diagnostic) || diagnostic.code !== diagnosticCode.unknown) {\n await hooks.callHook('kubb:diagnostic', { diagnostic })\n return\n }\n const { cause, help, message } = diagnostic\n const bare = cause && !help && cause.message === message\n await hooks.callHook('kubb:error', { error: thrown ? toError(value) : bare ? cause : new Diagnostics.Error(diagnostic) })\n }\n\n /**\n * Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}\n * keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.\n */\n static from(error: unknown): ProblemDiagnostic {\n // The hook emitter and the build's AggregateError 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 chain = getErrorChain(error)\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 // The innermost one wins: it is where the problem started, and a wrapper only adds context.\n const coded = chain.findLast((current) => Diagnostics.isError(current))\n if (coded) {\n const { diagnostic } = coded as InstanceType<typeof Diagnostics.Error>\n // A crash thrown without a cause still needs a stack, so it points at itself.\n return diagnostic.cause || !crashCodes.has(diagnostic.code) ? diagnostic : { ...diagnostic, cause: coded }\n }\n const root = chain.at(-1)\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 * Coerces an error thrown by a plugin, adapter, or parser into a diagnostic attributed to it.\n * A structured {@link Diagnostics.Error} keeps its code. Any other error is a crash: it gets the\n * kind's `*_FAILED` code and the extension's `meta.issues` link, so the user reports it to the\n * extension's maintainers instead of to Kubb.\n */\n static fromExtension(error: unknown, { kind, extension }: { kind: ExtensionKind; extension: ExtensionNamed }): ProblemDiagnostic {\n const diagnostic = Diagnostics.from(error)\n const name = extension.meta?.name ?? extension.name\n // `plugin` feeds the failed-plugin count, so an adapter or parser is named in the message instead.\n const owner = kind === 'plugin' ? { plugin: diagnostic.plugin ?? name } : {}\n // An abort is the user canceling the run, not a crash.\n const crashed = diagnostic.code === diagnosticCode.unknown && diagnostic.cause?.name !== 'AbortError'\n const failed = Object.values<DiagnosticCode>(failedCode).includes(diagnostic.code)\n if (!crashed && !failed) {\n return { ...diagnostic, ...owner }\n }\n\n const issues = extension.meta?.issues\n return {\n ...diagnostic,\n ...owner,\n code: crashed ? failedCode[kind] : diagnostic.code,\n message: crashed && kind !== 'plugin' ? `${kind} \"${name}\" crashed: ${diagnostic.message}` : diagnostic.message,\n ...(issues ? { issues } : {}),\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 return [...new Set(diagnostics.flatMap((diagnostic) => (diagnostic.severity === 'error' && diagnostic.plugin ? [diagnostic.plugin] : [])))]\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 const counts = { errors: 0, warnings: 0, infos: 0 }\n for (const diagnostic of diagnostics.filter(isProblem)) {\n counts[countKey[diagnostic.severity]] += 1\n }\n return counts\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 * `/reference/diagnostics#<slug>` section.\n */\n static explain(code: DiagnosticCode): DiagnosticDoc {\n return docsByCode.get(code)!\n }\n\n /**\n * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable\n * consumers, with the catalog `title`, `cause`, and fix, and the `cause` error as `causes` and\n * `stack`. Absent optional fields are omitted.\n */\n static serialize = serialize\n\n /**\n * Renders a diagnostic as lines for an `agent` (the default) or a `human`. See {@link format}.\n */\n static format = format\n}\n","import { satisfies } from 'verkit'\nimport { version as kubbVersion } from '../package.json'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { Adapter, AdapterDefinition, AdapterFactory, AdapterFactoryOptions } from './createAdapter.ts'\nimport type { Parser, ParserBuild, ParserFactory } from './defineParser.ts'\nimport type { Plugin, PluginDefinition, PluginFactory, PluginType, PluginName } from './definePlugin.ts'\nimport type { Config } from './types.ts'\n\n/**\n * What an extension extends: a plugin generates code, an adapter reads the input, a parser prints files.\n */\nexport type ExtensionKind = 'plugin' | 'adapter' | 'parser'\n\n/**\n * Identity and registry data for an extension. Kubb reads `name` and `compatibility` at runtime.\n * Studio, the kubb.dev registry, and the docs read the rest.\n */\nexport type ExtensionMeta<TName extends string = string> = {\n /**\n * Unique name, such as `'plugin-ts'`. Becomes the plugin's `name`.\n */\n name: TName\n /**\n * Package version. Dependents check their `version` range against it.\n */\n version?: string\n displayName?: string\n /**\n * One-sentence summary of what the extension generates or does.\n */\n description?: string\n category?: string\n icon?: { light: string; dark?: string }\n /** HTTPS image or video URLs. */\n media?: Array<string>\n tags?: Array<string>\n /**\n * Semver ranges the extension supports. A mismatch fails the run with `KUBB_INCOMPATIBLE_EXTENSION`.\n */\n compatibility?: {\n kubb?: string\n node?: string\n }\n docs?: string\n /** Issue tracker URL. Kubb prints it when the extension crashes, so users report the bug to its maintainers. */\n issues?: string\n}\n\n/**\n * An extension's identity: `meta`, a `name`, or both. `name` is deprecated in favor of `meta.name`.\n */\nexport type ExtensionNamed = { name?: string; meta?: ExtensionMeta }\n\n/**\n * Returns `meta`, or `{ name }` for an extension that only sets the deprecated `name`. Throws `KUBB_INVALID_PLUGIN_OPTIONS` when it has neither.\n */\nexport function resolveMeta(extension: ExtensionNamed): ExtensionMeta {\n const { name, meta } = extension\n if (meta) return meta\n if (name) return { name }\n\n const keys = Object.keys(extension)\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `An extension has neither \\`meta.name\\` nor \\`name\\`. Received keys: ${keys.length ? keys.join(', ') : 'none'}.`,\n help: 'Set `meta: { name }` on the plugin or parser.',\n location: { kind: 'config' },\n })\n}\n\n/**\n * Sets how Kubb checks one entry in a `dependencies` record.\n */\nexport type ExtensionDependency = {\n /**\n * Semver range the dependency's `meta.version` must satisfy. Skipped when the dependency has no `meta.version`.\n */\n version?: string\n /**\n * When `true`, Kubb skips the entry if the plugin is missing, but still checks `version` on an installed one.\n * Otherwise a missing plugin fails the run with `KUBB_MISSING_DEPENDENCY`.\n */\n optional?: boolean\n}\n\n/**\n * Plugins an extension builds on, keyed by name, or a function that picks them from the user's options.\n */\nexport type ExtensionDependencies<TOptions = object> =\n | ExtensionDependencyRecord\n // Method syntax keeps `options` bivariant, so a `Plugin<PluginTs>` still fits `Config['plugins']`.\n | { resolve(options: TOptions, kubb: { config: Config }): ExtensionDependencyRecord }['resolve']\n\n/**\n * Maps each dependency's plugin name to how Kubb checks it.\n */\nexport type ExtensionDependencyRecord = Partial<Record<PluginName, ExtensionDependency>>\n\n/**\n * Throws `KUBB_INCOMPATIBLE_EXTENSION` when the running Kubb or Node.js version is outside `meta.compatibility`.\n */\nexport function checkCompatibility(meta: ExtensionMeta): void {\n const checks = [\n { target: 'Kubb', range: meta.compatibility?.kubb, version: kubbVersion },\n { target: 'Node.js', range: meta.compatibility?.node, version: process.versions.node },\n ]\n\n for (const { target, range, version } of checks) {\n if (!range || satisfies(version, range, { includePrerelease: true })) continue\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.incompatibleExtension,\n severity: 'error',\n message: `\"${meta.name}\" requires ${target} ${range}, but ${version} is running.`,\n help: `Use a ${target} version that satisfies ${range}, or a version of \"${meta.name}\" that supports ${target} ${version}.`,\n location: { kind: 'config' },\n plugin: meta.name,\n })\n }\n}\n\n/**\n * Throws `KUBB_MISSING_DEPENDENCY` for a missing required entry in a `dependencies` record, and\n * `KUBB_INCOMPATIBLE_DEPENDENCY` when an entry's `meta.version` is out of range. Arrays are not checked.\n */\nexport function checkDependencies({\n name,\n dependencies,\n plugins,\n}: {\n name: string\n dependencies: Array<PluginName> | ExtensionDependencyRecord | undefined\n plugins: ReadonlyMap<string, { meta?: ExtensionMeta }>\n}): void {\n if (!dependencies || Array.isArray(dependencies)) return\n\n for (const [dependencyName, dependency] of Object.entries(dependencies)) {\n const target = plugins.get(dependencyName)\n\n if (!target) {\n if (dependency?.optional) continue\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.missingDependency,\n severity: 'error',\n message: `Plugin \"${dependencyName}\" is required by \"${name}\" but not found.`,\n help: `Add \"${dependencyName}\" to the \\`plugins\\` array in kubb.config.ts.`,\n location: { kind: 'config' },\n plugin: name,\n })\n }\n\n const range = dependency?.version\n const version = target.meta?.version\n if (!range || !version || satisfies(version, range, { includePrerelease: true })) continue\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.incompatibleDependency,\n severity: 'error',\n message: `\"${name}\" requires \"${dependencyName}\" ${range}, but ${version} is configured.`,\n help: `Install a version of \"${dependencyName}\" that satisfies ${range}.`,\n location: { kind: 'config' },\n plugin: name,\n })\n }\n}\n\n/**\n * The function an extension definition returns. Call it with user options to get the extension.\n */\nexport type ExtensionFactory<TKind extends ExtensionKind, TOptions, TExtension, TName extends string = string> = {\n (options?: TOptions): TExtension\n kind: TKind\n meta: ExtensionMeta<TName>\n}\n\n/**\n * Builds the factory behind `defineExtension`. It passes `{}` when called without options, and carries `kind` and\n * `meta` so tools can read them without calling it.\n *\n * @internal\n */\nexport function createExtensionFactory<TKind extends ExtensionKind, TOptions extends object, TExtension, TName extends string>({\n kind,\n meta,\n build,\n}: {\n kind: TKind\n meta: ExtensionMeta<TName>\n build: (options: TOptions) => TExtension\n}): ExtensionFactory<TKind, TOptions, TExtension, TName> {\n return Object.assign((options: TOptions = {} as TOptions) => build(options), { kind, meta })\n}\n\n// Parser comes first and takes only `build`: TypeScript fixes a parameterless `build()` return type from the first\n// overload that types it, and `extNames` only keeps its literal types under the parser's.\n\n/**\n * Defines a parser and returns a factory that takes the user's options. `build` returns the parser methods.\n */\nexport function defineExtension<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(definition: {\n kind: 'parser'\n meta: ExtensionMeta\n build: ParserBuild<TOptions, TMeta, TNode>\n}): ParserFactory<TOptions, TMeta, TNode>\n/**\n * Defines an adapter and returns a factory that takes the user's options. `parse` must return an `InputNode`.\n */\nexport function defineExtension<T extends AdapterFactoryOptions = AdapterFactoryOptions>(\n definition: { kind: 'adapter' } & AdapterDefinition<T>,\n): AdapterFactory<T>\n/**\n * Defines a plugin and returns a factory that takes the user's options. Name plugins `plugin-<feature>`.\n *\n * @example\n * ```ts\n * defineExtension<PluginZod>({ kind: 'plugin', meta: { name: 'plugin-zod' }, setup: (options) => options })\n * ```\n */\nexport function defineExtension<TFactory extends PluginType = PluginType>(definition: { kind: 'plugin' } & PluginDefinition<TFactory>): PluginFactory<TFactory>\nexport function defineExtension(\n definition:\n | ({ kind: 'plugin' } & PluginDefinition)\n | ({ kind: 'adapter' } & AdapterDefinition)\n | { kind: 'parser'; meta: ExtensionMeta; build: ParserBuild<object, object, unknown> },\n) {\n switch (definition.kind) {\n case 'plugin': {\n const { meta, dependencies, enforce, hooks = {}, setup } = definition\n // Keeps the raw options: Studio and config merging read them back.\n return createExtensionFactory({\n kind: 'plugin',\n meta,\n build: (options: object): Plugin => ({ name: meta.name, meta, options, dependencies, enforce, hooks, setup }),\n })\n }\n case 'adapter': {\n const { meta, setup, build } = definition\n return createExtensionFactory({\n kind: 'adapter',\n meta,\n build: (raw: object): Adapter => {\n const options = setup ? setup(raw) : raw\n // Assigned onto the built object instead of spread, so getters such as `document` stay live.\n return Object.assign(build(options), { name: meta.name, meta, options: raw })\n },\n })\n }\n case 'parser': {\n const { meta, build } = definition\n return createExtensionFactory({\n kind: 'parser',\n meta,\n build: (options: object): Parser => ({ ...build(options), name: meta.name, meta, options }),\n })\n }\n }\n}\n","import type { PossiblePromise } from '@internals/utils'\nimport type { InputNode } from '@kubb/ast'\nimport { defineExtension } from './defineExtension.ts'\nimport type { ExtensionFactory, ExtensionMeta } from './defineExtension.ts'\nimport type { DiagnosticLocation } from './Diagnostics.ts'\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 `defineExtension` with `kind: 'adapter'` and the resulting `Adapter` type.\n *\n * - `TName`: unique adapter identifier (`'oas'`, `'asyncapi'`, ...).\n * - `TOptions`: user-facing options accepted by the adapter factory.\n * - `TResolvedOptions`: options after defaults are applied.\n * - `TDocument`: type of the parsed source document.\n */\nexport type AdapterFactoryOptions<\n TName extends string = string,\n TOptions extends object = object,\n TResolvedOptions extends object = TOptions,\n TDocument = unknown,\n> = {\n name: TName\n options: TOptions\n resolvedOptions: TResolvedOptions\n document: TDocument\n}\n\n/**\n * Converts input files or inline data into Kubb's universal AST `InputNode`.\n *\n * Adapters live between the spec format and the plugins. The built-in\n * `@kubb/adapter-oas` handles OpenAPI 2.0, 3.0, and 3.1. A custom adapter can\n * support GraphQL, gRPC, or another schema language.\n *\n * @example\n * ```ts\n * import { defineConfig } from 'kubb'\n * import { adapterOas } from '@kubb/adapter-oas'\n * import { pluginTs } from '@kubb/plugin-ts'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * adapter: adapterOas(),\n * plugins: [pluginTs()],\n * })\n * ```\n */\nexport type Adapter<TOptions extends AdapterFactoryOptions = AdapterFactoryOptions> = {\n /**\n * Human-readable adapter identifier (e.g. `'oas'`, `'asyncapi'`).\n */\n name: TOptions['name']\n meta?: ExtensionMeta<TOptions['name']>\n /**\n * The options the adapter was created with, before `setup` applied defaults, as a plugin keeps its\n * own. Kubb Studio merges its overrides onto these, so a default derived from another option, such\n * as `emptySchemaType` from `unknownType`, follows a change to it.\n */\n options: TOptions['options']\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 * An adapter that renames schemas (e.g. collision handling) must stamp `targetName` on\n * every ref node pointing at a renamed schema, so `resolveRefName` and `resolver.imports`\n * resolve a `$ref` to the file that is actually generated. Refs that keep their pointer's\n * last segment need no stamp.\n */\n parse: (source: AdapterSource, options?: { signal?: AbortSignal }) => PossiblePromise<InputNode>\n /**\n * Validate the document at the given path or URL.\n */\n validate: (input: string, options?: { throwOnError?: boolean }) => Promise<void>\n /**\n * Zero-based UTF-16 offsets of a diagnostic in `source` for a code frame, `end` exclusive; `undefined` when it cannot be found.\n */\n locate?: (source: string, location: DiagnosticLocation) => { start: number; end: number } | undefined\n}\n\n/**\n * The object passed to `defineExtension` with `kind: 'adapter'`.\n */\nexport type AdapterDefinition<T extends AdapterFactoryOptions = AdapterFactoryOptions> = {\n meta: ExtensionMeta<T['name']>\n /**\n * Takes the user's options and returns the resolved options, which `build` receives and the adapter exposes as `options`.\n * Without `setup`, the user's options are the resolved options.\n */\n setup?(options: T['options']): T['resolvedOptions']\n /**\n * Returns the adapter's document and methods for the resolved options.\n */\n build(options: T['resolvedOptions']): Omit<Adapter<T>, 'name' | 'meta' | 'options'>\n}\n\n/**\n * The function `defineExtension` returns for an adapter. Call it with user options to get an `Adapter`.\n */\nexport type AdapterFactory<T extends AdapterFactoryOptions = AdapterFactoryOptions> = ExtensionFactory<'adapter', T['options'], Adapter<T>, T['name']>\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 * @deprecated Use `defineExtension` with `kind: 'adapter'` instead.\n */\nexport function createAdapter<T extends AdapterFactoryOptions = AdapterFactoryOptions>(definition: AdapterDefinition<T>): AdapterFactory<T> {\n return defineExtension({ kind: 'adapter', ...definition })\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { Macro, UserFileNode } from '@kubb/ast'\nimport type { Generator } from './defineGenerator.ts'\nimport type { KubbPluginSetupContext, NormalizedPlugin, PluginType, PluginName, ResolvePluginOptions } from './definePlugin.ts'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { Resolver, ResolverPatch } from './Resolver.ts'\nimport type { Config } from './types.ts'\n\nconst kubbContextKey = Symbol.for('kubb.context')\n\ntype KubbContextHost = typeof globalThis & { [kubbContextKey]?: AsyncLocalStorage<KubbPluginSetupContext> }\n\nconst host = globalThis as KubbContextHost\n\n/**\n * Holds the setup context of the plugin whose `setup` or `kubb:plugin:setup` is running. `KubbDriver` sets it for each plugin.\n *\n * The store lives on `globalThis`, so the ESM and CommonJS builds of `@kubb/core` share one. A plugin that a\n * CommonJS config loads would otherwise read an empty store and fail with `KUBB_NO_CONTEXT`.\n */\nexport const kubbContext: AsyncLocalStorage<KubbPluginSetupContext> = (host[kubbContextKey] ??= new AsyncLocalStorage<KubbPluginSetupContext>())\n\nfunction requireContext(caller: string): KubbPluginSetupContext {\n const ctx = kubbContext.getStore()\n if (ctx) return ctx\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.noContext,\n severity: 'error',\n message: `\\`${caller}()\\` was called outside a plugin setup.`,\n help: `Call \\`${caller}()\\` inside \\`setup\\` or \\`kubb:plugin:setup\\`, including in code that setup awaits.`,\n })\n}\n\n/**\n * Returns the context of the plugin whose `kubb:plugin:setup` is running. It stays available after an `await`.\n * Throws `KUBB_NO_CONTEXT` outside setup.\n */\nexport function useKubb<TFactory extends PluginType = PluginType>(): KubbPluginSetupContext<TFactory> {\n return requireContext('useKubb') as KubbPluginSetupContext<TFactory>\n}\n\n/**\n * Returns the same context as {@link useKubb}, or `undefined` outside `setup` and `kubb:plugin:setup`.\n */\nexport function tryUseKubb<TFactory extends PluginType = PluginType>(): KubbPluginSetupContext<TFactory> | undefined {\n return kubbContext.getStore() as KubbPluginSetupContext<TFactory> | undefined\n}\n\n/**\n * Registers generators on the plugin being set up, like `ctx.addGenerator`.\n *\n * @example\n * `addGenerator(typeGenerator, enumGenerator)`\n */\nexport function addGenerator<TFactory extends PluginType = PluginType, TElement = unknown>(...generators: Array<Generator<TFactory, TElement>>): void {\n requireContext('addGenerator').addGenerator(...generators)\n}\n\n/**\n * Sets the resolver of the plugin being set up, like `ctx.setResolver`.\n */\nexport function setResolver<TResolver extends Resolver = Resolver>(resolver: ResolverPatch<TResolver> | TResolver): void {\n requireContext('setResolver').setResolver(resolver)\n}\n\n/**\n * Adds a macro to the plugin being set up, like `ctx.addMacro`.\n */\nexport function addMacro(macro: Macro): void {\n requireContext('addMacro').addMacro(macro)\n}\n\n/**\n * Replaces the macros of the plugin being set up, like `ctx.setMacros`.\n */\nexport function setMacros(macros: ReadonlyArray<Macro>): void {\n requireContext('setMacros').setMacros(macros)\n}\n\n/**\n * Adds a raw file to the build output, like `ctx.injectFile`.\n */\nexport function injectFile(file: UserFileNode): void {\n requireContext('injectFile').injectFile(file)\n}\n\n/**\n * Returns the options the user passed to the plugin being set up, like `ctx.options`.\n */\nexport function useOptions<TFactory extends PluginType = PluginType>(): TFactory['options'] {\n return requireContext('useOptions').options as TFactory['options']\n}\n\n/**\n * Sets the resolved options of the plugin being set up, like `ctx.setOptions`.\n */\nexport function setOptions<TFactory extends PluginType = PluginType>(options: TFactory['resolvedOptions']): void {\n requireContext('setOptions').setOptions(options)\n}\n\n/**\n * Returns the resolved build configuration, like `ctx.config`.\n */\nexport function useConfig(): Config {\n return requireContext('useConfig').config\n}\n\n/**\n * Returns another plugin from the config, typed through `Kubb.PluginRegistry`, like `ctx.requirePlugin`.\n */\nexport function requirePlugin<TName extends PluginName>(name: TName): NormalizedPlugin<ResolvePluginOptions<TName>> {\n return requireContext('requirePlugin').requirePlugin(name) as NormalizedPlugin<ResolvePluginOptions<TName>>\n}\n","import path from 'node:path'\nimport type { LiteralUnion } from '@internals/utils'\nimport type { Enforce, HttpMethod, Macro, UserFileNode } from '@kubb/ast'\nimport type { Generator } from './defineGenerator.ts'\nimport { defineExtension } from './defineExtension.ts'\nimport type { ExtensionDependencies, ExtensionDependencyRecord, ExtensionFactory, ExtensionMeta, ExtensionNamed } from './defineExtension.ts'\nimport type { BannerMeta, Resolver, ResolverPatch } from './Resolver.ts'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { Config, FilesContext, KubbHooks } from './types.ts'\n\n/** Reads key `K` from a registry interface, or `{}` when no package has augmented it. @internal */\nexport type ExtractRegistryKey<T, K extends PropertyKey> = K extends keyof T ? T[K] : {}\n\n/**\n * A plugin name as accepted by `getPlugin`/`requirePlugin`/`getResolver`. Registered names from\n * `Kubb.PluginRegistry` autocomplete, and any other string is still allowed.\n */\nexport type PluginName = LiteralUnion<keyof Kubb.PluginRegistry>\n\n/**\n * Resolves a plugin name to its `PluginType`. A name registered in `Kubb.PluginRegistry`\n * maps to its exact factory options, any other string falls back to the generic options.\n */\nexport type ResolvePluginOptions<TName> = TName extends keyof Kubb.PluginRegistry ? Kubb.PluginRegistry[TName] : PluginType\n\n/**\n * How a plugin consolidates its generated code into files.\n * - `'file'` writes everything into a single file.\n * - `'directory'` writes one file per operation or schema under `path`.\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 * - `'file'` writes everything into a single file. The `path` must include the file extension.\n * - `'directory'` writes one file per operation or schema under `path`.\n *\n * Defaults to `'file'` when `path` carries an extension and `'directory'` when it does not.\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 first path segment as written in the spec 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 * - An explicit `mode: 'file'` forbids `group` (a single file has nothing to group).\n * - Omitting `mode`, or setting it to `'directory'`, allows an optional `group`.\n *\n * `mode` is normally inferred from `output.path` (an extension means `'file'`, anything\n * else `'directory'`), so `group` rarely needs `mode` spelled out alongside it. Set\n * `mode: 'directory'` explicitly only to override that inference, such as a directory\n * name that carries a dot (`path: 'clients.v2'`).\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 *\n * An omitted `mode` follows the shape of `path`: an extension means a single file, anything\n * else is a directory. Plugin defaults such as `path: 'types'` name a directory, so they\n * generate without the caller spelling out `mode`.\n */\nexport function normalizeOutput({ output, group, pluginName }: { output: Output; group?: Group | null; pluginName: string }): Output {\n const mode = output.mode ?? (path.extname(output.path) ? 'file' : 'directory')\n\n if (mode === 'file' && group) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `Plugin \"${pluginName}\" resolves \\`output.mode\\` to 'file' but also configures a \\`group\\` option.`,\n help: \"A single-file output has nothing to group. Remove the `group` option, give `output.path` an extensionless directory name, or set `output.mode: 'directory'` explicitly.\",\n location: { kind: 'config' },\n plugin: pluginName,\n })\n }\n\n return { ...output, mode }\n}\n\n/** Throws `KUBB_INVALID_PLUGIN_OPTIONS`, listing the allowed values, when `value` is not one of `allowed`. */\nexport function assertPluginOption({\n plugin,\n option,\n value,\n allowed,\n}: {\n plugin: string\n option: string\n value: unknown\n allowed: ReadonlyArray<unknown>\n}): void {\n if (allowed.includes(value)) return\n\n const format = (item: unknown) => (typeof item === 'string' ? JSON.stringify(item) : String(item))\n const expected = allowed.map(format).join(', ')\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `Plugin \"${plugin}\" option \\`${option}\\` is ${format(value)}, but it must be one of ${expected}.`,\n help: `Set \\`${option}\\` to one of ${expected}.`,\n location: { kind: 'config' },\n plugin,\n })\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'`, `'QUERY'`.\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'`, `'QUERY'`) 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\ntype ByExtension = {\n /** Filter operations by a vendor extension (`x-*` key) on the source operation. Does not apply to schemas. */\n type: 'extension'\n /** Extension key, including the `x-` prefix. */\n key: `x-${string}`\n /** Value the extension must strictly equal. When omitted, the key being present is enough. */\n value?: unknown\n}\n\n/**\n * Pattern filter for include, exclude, and override rules. Matches operations or schemas\n * by tag, operationId, path, method, content type, schema name, or vendor extension.\n */\nexport type Filter = ByTag | ByOperationId | ByPath | ByMethod | ByContentType | BySchemaName | ByExtension\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 * { type: 'extension', key: 'x-internal', value: true },\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 PluginType<\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 PluginType = PluginType> = {\n /**\n * Register one or more generators dynamically. Generators fire during the AST walk\n * (schema/operation/operations) just like generators declared statically on `createPlugin`.\n *\n * Pass generators as separate arguments. Spread an existing list to register it in one call.\n *\n * @example\n * ```ts\n * ctx.addGenerator(myGenerator)\n * ctx.addGenerator(schemaGenerator, operationGenerator)\n * ctx.addGenerator(...selectedGenerators)\n * ```\n */\n addGenerator<TElement = unknown>(...generators: Array<Generator<TFactory, TElement>>): void\n /**\n * Set or override the resolver for this plugin.\n * The resolver controls file naming and path resolution. Overrides merge over the built-in\n * defaults, so a partial `core` or a single namespace method replaces only what it names.\n */\n setResolver(resolver: ResolverPatch<TFactory['resolver']> | TFactory['resolver']): void\n /**\n * Add a macro that rewrites AST nodes before they reach generators. Macros run in the order they\n * are added, after any macros from earlier `addMacro` calls.\n */\n addMacro(macro: Macro): void\n /**\n * Replace this plugin's macros with `macros`.\n */\n setMacros(macros: ReadonlyArray<Macro>): void\n /**\n * Set resolved options merged into the normalized plugin's `options`.\n * Call this in `kubb:plugin:setup` to provide options generators need.\n */\n setOptions(options: TFactory['resolvedOptions']): void\n /**\n * Inject a raw file into the build output, bypassing the generation pipeline.\n *\n * Pass `copy` with an absolute path to emit a real source file (a shipped template) into the\n * generated folder, instead of building its content from `sources`.\n */\n injectFile(userFileNode: UserFileNode): void\n /** Returns a plugin this one needs, or fails the run with `KUBB_PLUGIN_NOT_FOUND` when the config lacks it. */\n requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>\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 `defineExtension`. Its lifecycle handlers live under a single\n * `hooks` property rather than flat methods.\n */\nexport type Plugin<TFactory extends PluginType = PluginType> = ExtensionNamed & {\n /**\n * Plugins this one builds on. They run first when the config has them. An array only orders\n * plugins. A record also fails the run when a required entry is missing or out of range.\n */\n dependencies?: Array<PluginName> | ExtensionDependencies<TFactory['options']>\n /**\n * Controls the execution order of this plugin relative to others.\n *\n * - `'pre'` runs before all normal plugins.\n * - `'post'` runs after all normal plugins.\n * - `undefined` (default) runs in declaration order among normal plugins.\n *\n * Dependency constraints always take precedence over `enforce`.\n */\n enforce?: Enforce\n /**\n * The options passed by the user when calling the plugin factory.\n */\n options?: TFactory['options']\n /**\n * Lifecycle hook handlers for this plugin.\n * Any hook from the global `KubbHooks` map can be subscribed to here.\n */\n hooks: {\n [K in keyof KubbHooks as K extends 'kubb:plugin:setup' ? never : K]?: (...args: KubbHooks[K]) => void | Promise<void>\n } & {\n 'kubb:plugin:setup'?(ctx: KubbPluginSetupContext<TFactory>): void | Promise<void>\n }\n /**\n * Runs before `kubb:plugin:setup`. Takes the user's options and returns the resolved options.\n */\n setup?(options: TFactory['options'], kubb: KubbPluginSetupContext<TFactory>): TFactory['resolvedOptions'] | Promise<TFactory['resolvedOptions']>\n}\n\n/**\n * The object passed to `defineExtension` with `kind: 'plugin'`.\n */\nexport type PluginDefinition<TFactory extends PluginType = PluginType> = Pick<Plugin<TFactory>, 'dependencies' | 'enforce' | 'setup'> & {\n meta: ExtensionMeta<TFactory['name']>\n hooks?: Plugin<TFactory>['hooks']\n}\n\n/**\n * The function `defineExtension` returns for a plugin. Call it with user options to get a `Plugin`.\n */\nexport type PluginFactory<TFactory extends PluginType = PluginType> = ExtensionFactory<'plugin', TFactory['options'], Plugin<TFactory>, TFactory['name']>\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 PluginType = PluginType> = Plugin<TOptions> & {\n name: string\n meta: ExtensionMeta\n dependencies?: Array<PluginName> | ExtensionDependencyRecord\n options: TOptions['resolvedOptions'] & {\n output: Output\n include?: Array<Include>\n exclude: Array<Exclude>\n override: Array<Override<TOptions['resolvedOptions']>>\n }\n resolver: TOptions['resolver']\n macros?: Array<Macro>\n generators?: Array<Generator>\n}\n\nexport type KubbPluginStartContext = {\n plugin: NormalizedPlugin\n}\n\nexport type KubbPluginEndContext = FilesContext & {\n plugin: NormalizedPlugin\n duration: number\n success: boolean\n error?: Error\n config: Config\n}\n\n/**\n * Defines a plugin from one object and returns a factory that takes the user's options.\n *\n * @deprecated Use `defineExtension` with `kind: 'plugin'` instead.\n */\nexport function definePlugin<TFactory extends PluginType = PluginType>(definition: PluginDefinition<TFactory>): PluginFactory<TFactory> {\n return defineExtension({ kind: 'plugin', ...definition })\n}\n","import net from 'node:net'\n\nfunction createBlockList(): net.BlockList {\n const list = new net.BlockList()\n for (const [address, prefix] of [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.0.0.0', 24],\n ['192.168.0.0', 16],\n ['198.18.0.0', 15],\n ['224.0.0.0', 3],\n ] as const) {\n list.addSubnet(address, prefix, 'ipv4')\n }\n for (const [address, prefix] of [\n ['::', 128],\n ['::1', 128],\n ['64:ff9b::', 96],\n ['fc00::', 7],\n ['fe80::', 10],\n ['ff00::', 8],\n ] as const) {\n list.addSubnet(address, prefix, 'ipv6')\n }\n return list\n}\n\nconst privateAddresses = createBlockList()\n\n/**\n * Whether `address` is a routable public IP. Loopback, private, link-local, cloud metadata, and\n * multicast ranges are not, and an IPv4-mapped IPv6 address counts as the IPv4 address it wraps.\n * Pass `blocked` to replace the ranges.\n */\nexport function isPublicAddress(address: string, blocked: net.BlockList = privateAddresses): boolean {\n const family = net.isIP(address)\n return family !== 0 && !blocked.check(address, family === 4 ? 'ipv4' : 'ipv6')\n}\n","import dns from 'node:dns'\nimport { mkdtemp, rm } from 'node:fs/promises'\nimport net from 'node:net'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path'\nimport process from 'node:process'\nimport { getErrorMessage, toError } from '@internals/utils'\nimport { x } from 'tinyexec'\nimport { Diagnostics } from './Diagnostics.ts'\nimport { isPublicAddress } from './publicAddress.ts'\n\n/**\n * A git `input` split into its parts: `git+<repo>#<ref>:<path>`, where `<ref>:` is optional.\n */\nexport type GitInput = {\n /** Repository URL passed to `git fetch`, without the `git+` prefix. */\n repo: string\n /** Branch, tag, or commit SHA. `undefined` fetches the default branch. */\n ref: string | undefined\n /** Spec file inside the repository. */\n path: string\n}\n\n/** Matches a git `input`: the `git+` prefix npm uses for git dependencies. */\nexport const gitInputRegExp = /^git\\+/i\n\nfunction gitError(message: string, cause?: unknown): InstanceType<typeof Diagnostics.Error> {\n return new Diagnostics.Error({\n code: Diagnostics.code.gitInputFailed,\n severity: 'error',\n message,\n help: 'Write a git `input` as `git+<repo>#<ref>:<path>`, for example `git+https://github.com/org/api.git#main:specs/openapi.yaml`. Check that `git` is installed and that `git fetch` can reach the repository with your credentials.',\n location: { kind: 'config' },\n cause: cause === undefined ? undefined : toError(cause),\n })\n}\n\n/** The repository URL without a user or password, safe to print. */\nfunction redact(repo: string): string {\n if (!URL.canParse(repo)) return repo\n const url = new URL(repo)\n url.username = ''\n url.password = ''\n return url.href\n}\n\n/**\n * Splits `git+<repo>#<ref>:<path>` into its parts. Git refs cannot contain `:`, so the first one\n * in the fragment ends the ref. Throws `KUBB_GIT_INPUT_FAILED` when the fragment or path is missing.\n */\nexport function parseGitInput(input: string): GitInput {\n const hashIndex = input.indexOf('#')\n const repo = input.slice(4, hashIndex === -1 ? undefined : hashIndex)\n const fragment = hashIndex === -1 ? '' : input.slice(hashIndex + 1)\n const colonIndex = fragment.indexOf(':')\n const ref = colonIndex === -1 ? undefined : fragment.slice(0, colonIndex)\n const path = colonIndex === -1 ? fragment : fragment.slice(colonIndex + 1)\n\n if (!repo || !path || ref === '') {\n throw gitError(`The git \\`input\\` for ${redact(repo)} has no repository, ref, or spec path after \\`#\\`.`)\n }\n\n return { repo, ref, path }\n}\n\n/**\n * The `git -c` settings that confine a fetch to https and to `addresses`: the connection goes to\n * the addresses already checked, whatever the host answers to a second lookup, and a redirect to\n * another host is an error. Needs git 2.37 for the pinning.\n *\n * @internal\n */\nexport function publicFetchConfig({ host, port, addresses }: { host: string; port: string; addresses: Array<string> }): Array<string> {\n const pinned = addresses.map((address) => (net.isIPv6(address) ? `[${address}]` : address)).join(',')\n const config = ['http.followRedirects=false', 'protocol.allow=never', 'protocol.https.allow=always']\n // An IP literal needs no pinning, since git does not look it up.\n if (!net.isIP(host)) config.push(`http.curloptResolve=${host}:${port}:${pinned}`)\n return config.flatMap((setting) => ['-c', setting])\n}\n\nasync function resolvePublicFetchConfig(repo: string, signal?: AbortSignal): Promise<Array<string>> {\n if (!URL.canParse(repo) || new URL(repo).protocol !== 'https:') {\n throw gitError('A public git `input` must be an https repository URL, not an ssh, git, or file address.')\n }\n const url = new URL(repo)\n const host = url.hostname.replace(/^\\[|\\]$/g, '')\n const isLiteral = net.isIP(host) !== 0\n const addresses = isLiteral ? [host] : (await dns.promises.lookup(host, { all: true })).map(({ address }) => address)\n if (!addresses.length || addresses.some((address) => !isPublicAddress(address))) {\n throw gitError(`${host} is not a public address, so this git \\`input\\` is not fetched.`)\n }\n if (!isLiteral) {\n const { stdout } = await x('git', ['--version'], { nodeOptions: { signal }, throwOnError: true })\n const [, major = 0, minor = 0] = /(\\d+)\\.(\\d+)/.exec(stdout)?.map(Number) ?? []\n if (major < 2 || (major === 2 && minor < 37)) throw gitError(`Fetching a public git \\`input\\` needs git 2.37 or newer, found ${stdout.trim()}.`)\n }\n return publicFetchConfig({ host, port: url.port || '443', addresses })\n}\n\n/** Adds an `Authorization` header for `repo`'s origin as the `GIT_CONFIG_*` pair after those in `env`, keeping the token out of the arguments; throws on a line break. */\nexport function gitAuthEnv(env: NodeJS.ProcessEnv, { repo, authorization }: { repo: string; authorization: string }): Record<string, string> {\n if (/[\\r\\n]/.test(authorization) || !URL.canParse(repo)) throw gitError('The authorization for a git `input` must be one line, for an https repository.')\n const index = Math.max(0, Number.parseInt(env.GIT_CONFIG_COUNT ?? '', 10) || 0)\n\n return {\n GIT_CONFIG_COUNT: String(index + 1),\n [`GIT_CONFIG_KEY_${index}`]: `http.${new URL(repo).origin}/.extraheader`,\n [`GIT_CONFIG_VALUE_${index}`]: `Authorization: ${authorization}`,\n }\n}\n\n/**\n * Fetches one commit of a git repository into a temporary directory with a shallow `git fetch`,\n * so any host and the user's own git credentials work, and relative `$ref` files resolve.\n * Resolves to the spec path on disk and a `dispose` that deletes the checkout.\n *\n * With `publicOnly`, the repository must be an https URL on public addresses, the fetch connects to\n * the addresses checked, and it does not follow a redirect. `authorization` adds that header to this\n * fetch only, through {@link gitAuthEnv}.\n */\nexport async function checkoutGitInput(\n input: string,\n signal?: AbortSignal,\n { publicOnly = false, authorization }: { publicOnly?: boolean; authorization?: string } = {},\n): Promise<{ path: string; dispose: () => Promise<void> }> {\n const { repo, ref, path } = parseGitInput(input)\n const authEnv = authorization ? gitAuthEnv(process.env, { repo, authorization }) : {}\n const fetchConfig = publicOnly ? await resolvePublicFetchConfig(repo, signal) : []\n const dir = await mkdtemp(join(tmpdir(), 'kubb-git-'))\n const dispose = () => rm(dir, { recursive: true, force: true })\n const specPath = resolve(dir, path)\n\n const relativePath = relative(dir, specPath)\n if (relativePath === '..' || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {\n await dispose()\n throw gitError(`The spec path \"${path}\" in the git \\`input\\` points outside the repository.`)\n }\n\n const label = `${redact(repo)}${ref ? ` at ${ref}` : ''}`\n // A prompt would hang the run, so git fails instead; credential helpers and SSH keys still work.\n const env = { ...process.env, ...authEnv, GIT_TERMINAL_PROMPT: '0' }\n // `--end-of-options` keeps a repo or ref that starts with `-` from being read as a git flag.\n const steps = [\n ['init', '--quiet'],\n // Symlinks become plain files, so a link in the repo cannot point the adapter at a file outside it.\n ['config', 'core.symlinks', 'false'],\n [...fetchConfig, 'fetch', '--quiet', '--depth', '1', '--end-of-options', repo, ref ?? 'HEAD'],\n ['checkout', '--quiet', 'FETCH_HEAD'],\n ]\n\n try {\n for (const args of steps) {\n const result = await x('git', args, { nodeOptions: { cwd: dir, env, signal }, throwOnError: false })\n if (result.exitCode !== 0) {\n const stderr = result.stderr.replaceAll(repo, redact(repo)).trim()\n throw gitError(`\\`git ${args[0]}\\` failed for ${label}: ${stderr || `exit code ${result.exitCode}`}`)\n }\n }\n } catch (error) {\n await dispose()\n if (Diagnostics.isError(error)) throw error\n throw gitError(`Cannot run \\`git\\` for ${label}: ${getErrorMessage(error)}`, error)\n }\n\n return { path: specPath, dispose }\n}\n","import { resolve } from 'node:path'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { Config, Input } from './types.ts'\nimport type { AdapterSource } from './createAdapter.ts'\nimport { gitInputRegExp } from './gitInput.ts'\n\n/**\n * What an `input` value points at, once Kubb has looked at it.\n *\n * - `file` is a local file path, absolute or relative to the config file.\n * - `url` is a remote document to fetch.\n * - `git` is a spec file in a git repository, written as `git+<repo>#<ref>:<path>`.\n * - `inline` is OpenAPI content held in the string itself (JSON or YAML).\n * - `object` is an already-parsed spec.\n */\nexport type InputKind = 'file' | 'url' | 'git' | 'inline' | 'object'\n\n/**\n * Classifies an `input` value so callers branch on it once instead of repeating the checks.\n *\n * A non-string is a parsed spec (`object`). A string is `inline` when it holds OpenAPI content,\n * meaning it starts with `{` or `[`, spans multiple lines, or opens with a YAML `openapi:` or\n * `swagger:` key. Otherwise a string is `git` when it starts with `git+`, a `url` when it parses as\n * one, or a `file` path.\n */\nexport function getInputKind(input: NonNullable<Input>): InputKind {\n if (typeof input !== 'string') return 'object'\n\n const trimmed = input.trimStart()\n const isInline = trimmed.startsWith('{') || trimmed.startsWith('[') || input.includes('\\n') || /^(openapi|swagger)\\s*:/i.test(trimmed)\n if (isInline) return 'inline'\n if (gitInputRegExp.test(input)) return 'git'\n\n if (URL.canParse(input)) return 'url'\n\n return 'file'\n}\n\n/**\n * The v4 `input` wrapper keys. v4 typed `input` as `{ path }` or `{ data }`; v5 takes the value\n * directly, so the wrapper now matches the \"already-parsed document\" branch and silently yields\n * an empty build.\n */\nconst legacyInputKeys = ['path', 'data']\n\n/**\n * Detects the v4 `{ path }` / `{ data }` wrapper so it fails loudly instead of being read as a\n * document. A real spec always carries more than these keys, so an object whose keys are drawn\n * only from them is the old shape rather than a document that happens to have a `path` property.\n */\nfunction isLegacyInput(input: unknown): boolean {\n if (Array.isArray(input)) {\n return input.some(isLegacyInput)\n }\n\n if (typeof input !== 'object' || input === null) return false\n\n const keys = Object.keys(input)\n\n return keys.length > 0 && keys.every((key) => legacyInputKeys.includes(key))\n}\n\n/**\n * Normalizes `config.input` into an `AdapterSource` the adapter can parse.\n *\n * A parsed object and inline content become `{ type: 'data' }`; a URL or git input is kept\n * verbatim and a local path is resolved against `config.root`, all as `{ type: 'path' }`. The\n * driver checks out a git input before the adapter parses it.\n */\nexport function inputToAdapterSource(config: Config): AdapterSource {\n const input = config.input\n\n if (input && isLegacyInput(input)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.legacyInput,\n severity: 'error',\n message: 'The `input` option uses the v4 `{ path }` / `{ data }` wrapper.',\n help: 'Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`.',\n location: { kind: 'config' },\n })\n }\n\n if (!input) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputRequired,\n severity: 'error',\n message: 'An adapter is configured without an input.',\n help: 'Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.',\n location: { kind: 'config' },\n })\n }\n\n if (typeof input !== 'string') {\n return { type: 'data', data: input }\n }\n\n const kind = getInputKind(input)\n if (kind === 'inline') return { type: 'data', data: input }\n if (kind === 'url' || kind === 'git') return { type: 'path', path: input }\n\n return { type: 'path', path: resolve(config.root, input) }\n}\n","import path from 'node:path'\nimport { camelCase } from '@internals/utils'\nimport { ast, collectImportedRefNames, type FileNode, type ImportNode, type InputMeta, type Node, type OperationNode, type SchemaNode } from '@kubb/ast'\nimport { Diagnostics } from './Diagnostics.ts'\nimport { getInputKind } from './input.ts'\nimport type { Filter, Override, Group, Output } from './definePlugin.ts'\nimport type { Config } from './types.ts'\n\n/**\n * Context for resolving filtered options for a given operation or schema node.\n *\n * @internal\n */\nexport type ResolveOptionsContext<TOptions> = {\n options: TOptions\n exclude?: Array<Filter>\n include?: Array<Filter>\n override?: Array<Override<TOptions>>\n}\n\n/**\n * The built-in resolution machinery exposed on every resolver as `resolver.default`.\n * Plugins delegate to it via `this.default.*` and set their own conventions through\n * the top-level `name` and `file` entries.\n */\nexport type ResolverDefault = {\n /**\n * Built-in camelCase casing for a generated identifier.\n */\n name(name: string): string\n options<TOptions>(node: Node, context: ResolveOptionsContext<TOptions>): TOptions | null\n path(options: ResolvePathOptions): string\n file(options: ResolveFileOptions): FileNode\n banner(meta: InputMeta | undefined, context: ResolveBannerContext): string | null\n footer(meta: InputMeta | undefined, context: ResolveBannerContext): string | null\n}\n\n/**\n * The name request for `resolver.default.path`: a `baseName` plus the optional `tag`/`path` that\n * grouping keys off.\n */\nexport type ResolverPathParams = Omit<ResolverFileParams, 'name' | 'extname'> & {\n baseName: FileNode['baseName']\n}\n\n/**\n * Options for `resolver.default.path`: the name request (`baseName`, `tag`, `path`) plus where the\n * output goes (`root`, `output`, `group`).\n *\n * @example\n * ```ts\n * resolver.default.path({ baseName: 'petTypes.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })\n * // → '/src/types/pets/petTypes.ts'\n * ```\n */\nexport type ResolvePathOptions = ResolverPathParams & {\n /**\n * Absolute project root that the output path is resolved against.\n */\n root: string\n /**\n * Active output config; `output.path` is the base directory.\n */\n output: Output\n /**\n * Optional grouping strategy applied to `tag` (tag grouping) or `path` (path grouping).\n */\n group?: Group\n}\n\n/**\n * The file request for `resolver.file` and `resolver.default.file`: the `name` and `extname` plus\n * the optional `tag`/`path` that grouping keys off.\n */\nexport type ResolverFileParams = {\n name: string\n extname: FileNode['extname']\n /**\n * Tag value used when `group.type === 'tag'`.\n */\n tag?: string\n /**\n * Path value used when `group.type === 'path'`.\n */\n path?: string\n}\n\n/**\n * Options for `resolver.file` and `resolver.default.file`: the file request (`name`, `extname`,\n * `tag`, `path`) plus where the output goes (`root`, `output`, `group`).\n *\n * @example\n * ```ts\n * resolver.default.file({ name: 'listPets', extname: '.ts', tag: 'pets', root: '/src', output: { path: 'types' }, group: { type: 'tag' } })\n * // → { baseName: 'listPets.ts', path: '/src/types/pets/listPets.ts', ... }\n * ```\n */\nexport type ResolveFileOptions = ResolverFileParams & {\n root: string\n output: Output\n group?: Group\n}\n\n/**\n * Options for `resolver.imports`: the schema tree to scan (`node`) and where the generated\n * files live (`root`, `output`, `group`). Pass `name` to override how a referenced schema\n * name becomes the imported identifier; it defaults to the resolver's top-level `name`.\n *\n * @example\n * ```ts\n * resolver.imports({ node, root, output, group })\n * // → [{ kind: 'Import', name: ['pet'], path: '/src/types/pet.ts' }]\n * ```\n */\nexport type ResolveImportsOptions = {\n /**\n * Schema tree scanned for `$ref` occurrences. Each ref contributes one import entry.\n */\n node: SchemaNode\n root: string\n output: Output\n group?: Group\n /**\n * Extension of the generated files the imports point at.\n *\n * @default '.ts'\n */\n extname?: FileNode['extname']\n /**\n * Overrides how a referenced schema name becomes the imported identifier, for example to\n * point enum refs at a suffixed type name. Defaults to the resolver's top-level `name`.\n */\n name?: (schemaName: string) => string\n}\n\n/**\n * The `file` field of a resolver: decides what a generated file is called and, optionally, where\n * it lives. This is how a resolver renames or relocates its files, replacing the older per-call\n * `resolveName` hook.\n *\n * @example Suffix every generated file\n * ```ts\n * file: {\n * baseName({ name, extname }) {\n * return `${name}Faker${extname}`\n * },\n * }\n * ```\n *\n * @example Own the full path\n * ```ts\n * file: {\n * path({ baseName, output }) {\n * return `${output.path}/mocks/${baseName}`\n * },\n * }\n * ```\n */\nexport type ResolverFile = {\n /**\n * Builds the file's complete base name, extension included, from the identifier and the target\n * `extname`. Defaults to `toFilePath(name)` with `extname` appended. Reaches sibling resolver\n * helpers through `this`.\n */\n baseName?(params: Pick<ResolverFileParams, 'name' | 'extname'>): FileNode['baseName']\n /**\n * Returns the file's complete path, resolved against the project `root`. Bypasses `output.path`\n * and `group`, so the resolver owns the layout. The returned path may not escape `root`. Reaches\n * sibling resolver helpers through `this`.\n */\n path?(params: ResolverFilePathParams): string\n}\n\n/**\n * The argument to a resolver's `file.path`: the resolved `baseName` (what `file.baseName` produced,\n * with the extension already appended) and the active `output`. `tag`, `path`, and `group` are\n * omitted because `file.path` owns the whole path and bypasses grouping, and `root` because the\n * returned path is resolved against it.\n */\nexport type ResolverFilePathParams = {\n baseName: FileNode['baseName']\n output: Output\n}\n\n/**\n * Per-file context describing the file a banner/footer is being resolved for, so a\n * `banner`/`footer` function can branch on the file kind (e.g. skip a `'use server'`\n * directive on re-export files).\n */\nexport type ResolveBannerFile = {\n /**\n * Full output path of the file being generated.\n */\n path: string\n /**\n * File name only, e.g. `'stocks.ts'`.\n */\n baseName: string\n /**\n * `true` for `index.ts` re-export barrels.\n */\n isBarrel?: boolean\n /**\n * `true` for group `[dir]/[dir].ts` aggregation files.\n */\n isAggregation?: boolean\n}\n\n/**\n * Document metadata extended with per-file context, passed to a `banner`/`footer` function.\n *\n * @example Skip a directive on re-export files\n * `banner: (meta) => (meta.isBarrel || meta.isAggregation) ? '' : \"'use server'\"`\n */\nexport type BannerMeta = InputMeta & {\n /**\n * Full output path of the file being generated.\n */\n filePath: string\n /**\n * File name only, e.g. `'stocks.ts'`.\n */\n baseName: string\n /**\n * `true` for `index.ts` re-export barrels.\n */\n isBarrel: boolean\n /**\n * `true` for group `[dir]/[dir].ts` aggregation files.\n */\n isAggregation: boolean\n}\n\n/**\n * Context passed to `resolver.default.banner` and `resolver.default.footer`.\n * `output` is optional since not every plugin configures a banner/footer, and `config`\n * carries the global Kubb config used to derive the default Kubb banner.\n */\nexport type ResolveBannerContext = {\n output?: Pick<Output, 'banner' | 'footer'>\n config: Config\n file?: ResolveBannerFile\n}\n\n/**\n * Raw resolver fields passed to `createResolver` or patched through `Resolver.merge`.\n * `default` is the built-in machinery and is not user-settable.\n */\nexport type ResolverBuildOptions = {\n pluginName: string\n name?: (name: string) => string\n file?: ResolverFile\n}\n\n/**\n * Partial resolver fields accepted by `Resolver.merge` and `setResolver`. Parameterize with a\n * concrete resolver type (e.g. `ResolverPatch<ResolverTs>`) to type-check overrides and bind\n * `this` to the full resolver. Namespaces are partial, so a patch may override a single method\n * (`query.name`) and the rest keep the plugin defaults. Overriding a whole resolver is not the\n * job of this patch, that is what a custom plugin is for.\n */\nexport type ResolverPatch<T extends Resolver = Resolver> = {\n [K in keyof Omit<T, keyof Resolver>]?: T[K] extends (...args: Array<never>) => unknown ? T[K] : Partial<T[K]>\n} & {\n imports?: T['imports']\n name?: T['name']\n file?: ResolverFile\n} & ThisType<T>\n\nfunction isNamespace(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of\n * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own\n * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay\n * reachable and a `file` override is never dropped.\n */\nconst resolverOptions: unique symbol = Symbol.for('@kubb/core/resolver/options')\n\n/**\n * Builds a nested file path from a dotted name. Splits on dots that precede a letter\n * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases\n * every segment, and joins with `/`.\n *\n * Empty segments are dropped before joining. They arise when the name starts with a dot\n * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to\n * an empty string). Without this a leading `/` would form, which `path.resolve` reads as an\n * absolute path, letting generated files escape the configured output directory.\n *\n * @example Nested path from a dotted name\n * `toFilePath('pet.petId') // 'pet/petId'`\n */\nexport function toFilePath(name: string): string {\n return name\n .split(/\\.(?=[a-zA-Z])/)\n .map((part) => camelCase(part))\n .filter(Boolean)\n .join('/')\n}\n\n/** Throws `KUBB_PATH_TRAVERSAL` when `target` lies outside `parent`; `target === parent` stays allowed. */\nfunction assertInside({ target, parent, message, help }: { target: string; parent: string; message: string; help: string }): void {\n const parentWithSep = parent.endsWith(path.sep) ? parent : `${parent}${path.sep}`\n if (target === parent || target.startsWith(parentWithSep)) return\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message,\n help,\n location: { kind: 'config' },\n })\n}\n\n/**\n * Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.\n */\nfunction toBaseName({ name, extname }: Pick<ResolverFileParams, 'name' | 'extname'>): FileNode['baseName'] {\n return `${toFilePath(name)}${extname}` as FileNode['baseName']\n}\n\n/**\n * Base constraint for all plugin resolver objects.\n *\n * The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,\n * and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with\n * top-level helpers (`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 /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */\n readonly default: ResolverDefault\n #options: ResolverBuildOptions\n // Base-name builder from `options.file.baseName`, bound to the resolver so it can reach `this`.\n // Defaults to `toBaseName` when a resolver sets no `file.baseName`.\n #baseName: (params: Pick<ResolverFileParams, 'name' | 'extname'>) => FileNode['baseName']\n // Full-path override from `options.file.path`, bound to the resolver. Absent by default, in which\n // case the built-in `output.path`/`group` layout is used.\n #filePath: ((params: ResolverFilePathParams) => string) | undefined\n\n constructor(options: ResolverBuildOptions) {\n this.pluginName = options.pluginName\n this.#options = options\n this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName\n this.#filePath = options.file?.path ? options.file.path.bind(this) : undefined\n this.default = {\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 this.#apply(options)\n }\n\n /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */\n get [resolverOptions](): ResolverBuildOptions {\n return this.#options\n }\n\n name(name: string): string {\n return this.default.name(name)\n }\n\n file(options: ResolveFileOptions): FileNode {\n return this.#resolveFile(options)\n }\n\n /**\n * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence\n * order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed\n * schemas (`targetName`) import the emitted name. Names and paths go through the top-level\n * `name` and `file`, so import entries follow the plugin's conventions, and a per-call\n * `name` override wins over both.\n *\n * The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a\n * schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver\n * reads the same ref set instead of re-scanning it per plugin.\n */\n imports(options: ResolveImportsOptions): Array<ImportNode> {\n const { node, root, output, group, extname = '.ts', name } = options\n const resolveName = name ?? ((schemaName: string) => this.name(schemaName))\n\n return collectImportedRefNames(node).map((schemaName) =>\n ast.factory.createImport({\n name: [resolveName(schemaName)],\n path: this.file({ name: schemaName, extname, root, output, group }).path,\n }),\n )\n }\n\n /**\n * Folds each `override` over `base`, left to right, and returns a new resolver with helpers\n * re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding\n * `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying\n * `setResolver` partial overrides, and to compose shared resolver fragments without spreading each\n * namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,\n * so a `file` override survives even when `base` and `override` come from different `@kubb/core`\n * copies.\n *\n * @example Fold several partial overrides onto a resolver\n * ```ts\n * const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })\n * ```\n */\n static merge<T extends Resolver>(base: T, ...overrides: Array<ResolverPatch<T> | Resolver>): T {\n const merged = overrides.reduce<Record<string, unknown>>(\n (acc, override) => {\n const patch = resolverOptions in override ? override[resolverOptions] : override\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue\n const current = acc[key]\n acc[key] = isNamespace(value) && isNamespace(current) ? { ...current, ...value } : value\n }\n return acc\n },\n { ...base[resolverOptions] },\n )\n return new Resolver(merged as ResolverBuildOptions) as T\n }\n\n /**\n * Binds each entry of `options` onto the resolver, so `this.name`, `this.default`, and\n * `this.file` resolve there for top-level helpers and namespace methods alike. `default`\n * is skipped so it can't be shadowed.\n */\n #apply(options: ResolverBuildOptions): void {\n const root = this as Resolver & Record<string, unknown>\n const bind = (value: unknown) => (typeof value === 'function' ? value.bind(root) : value)\n\n for (const [key, value] of Object.entries(options)) {\n // `file` drives file naming through `#baseName`, not a top-level method, so it must not be\n // assigned here (it would shadow the `file` method with a plain `{ name }` object).\n if (key === 'pluginName' || key === 'default' || key === 'file' || value === undefined) continue\n root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value)\n }\n }\n\n static #testPattern(value: string, pattern: string | RegExp): boolean {\n if (typeof pattern === 'string') {\n let regex = Resolver.#patternCache.get(pattern)\n regex ??= new RegExp(pattern)\n Resolver.#patternCache.set(pattern, regex)\n return regex.test(value)\n }\n // Use .match() for user-supplied RegExp to preserve semantics regardless of `g`/`y` flags.\n return value.match(pattern) !== null\n }\n\n static #matchesOperation(node: OperationNode, filter: Filter): boolean {\n if (filter.type === 'extension') {\n const { extensions } = node\n return extensions !== undefined && Object.hasOwn(extensions, filter.key) && (filter.value === undefined || extensions[filter.key] === filter.value)\n }\n\n const { type, pattern } = filter\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, filter: Filter): boolean | null {\n if (filter.type === 'schemaName') return node.name ? Resolver.#testPattern(node.name, filter.pattern) : false\n return null\n }\n\n static #computeOptions<TOptions>(node: Node, { options, exclude = [], include, override = [] }: ResolveOptionsContext<TOptions>): TOptions | null {\n if (node.kind === 'Operation') {\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 (node.kind === 'Schema') {\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'` (default) resolves directly to `output.path`. `mode: 'directory'` resolves\n * to `output.path/{baseName}`, or into a subdirectory when `group` and a `tag`/`path` value\n * are provided.\n */\n #resolvePath({ baseName, tag, path: groupPath, root, output, group }: ResolvePathOptions): string {\n if (output.mode !== 'directory') {\n return path.resolve(root, output.path)\n }\n\n const outputDir = path.resolve(root, output.path)\n // A file without the value its group needs (an SDK class per tag, grouped by path) is not grouped.\n const groupValue = group?.type === 'path' ? groupPath : tag\n const result = group && groupValue ? path.resolve(outputDir, Resolver.#resolveGroupDir(group, groupValue), baseName) : path.resolve(outputDir, baseName)\n\n assertInside({\n target: result,\n parent: outputDir,\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 })\n\n return result\n }\n\n /**\n * Resolves a resolver-supplied full path (`file.path`) against `root`, bypassing `output.path`\n * and `group`. The path may not escape `root`, which keeps a `file.path` that interpolates\n * spec-derived values from writing outside the project.\n */\n #resolveOverridePath(filePath: string, root: string): string {\n const resolved = path.resolve(root, filePath)\n assertInside({\n target: resolved,\n parent: root,\n message: `Resolved path \"${resolved}\" is outside the project root \"${root}\".`,\n help: 'A resolver `file.path` must return a path inside the project root.',\n })\n\n return resolved\n }\n\n /**\n * Builds a `FileNode`. When `#filePath` (the resolver's `file.path`) is set it owns the whole\n * path; otherwise the base name (from `#baseName`, the resolver's `file.baseName` or the\n * built-in `toBaseName`) is placed by the `output.path`/`group` layout. The resolved file starts\n * with empty `sources`, `imports`, and `exports`, which consumers populate separately.\n */\n #resolveFile(options: ResolveFileOptions): FileNode {\n const { name, extname, tag, path: groupPath, root, output, group } = options\n const baseName = this.#baseName({ name, extname })\n const filePath = this.#filePath\n ? this.#resolveOverridePath(this.#filePath({ baseName, output }), root)\n : this.#resolvePath({ baseName, tag, path: groupPath, root, output, group })\n\n return ast.factory.createFile({\n path: filePath,\n baseName: path.basename(filePath) as `${string}.${string}`,\n meta: {\n pluginName: this.pluginName,\n },\n sources: [],\n imports: [],\n exports: [],\n })\n }\n\n /**\n * Missing fields default to empty/`false` so the `BannerMeta` shape stays stable even when\n * a caller (e.g. the barrel plugin) has no document metadata.\n */\n static #buildBannerMeta(meta: InputMeta | undefined, file: ResolveBannerFile | undefined): BannerMeta {\n return {\n title: meta?.title,\n description: meta?.description,\n version: meta?.version,\n baseURL: meta?.baseURL,\n circularNames: meta?.circularNames ?? [],\n enumNames: meta?.enumNames ?? [],\n filePath: file?.path ?? '',\n baseName: file?.baseName ?? '',\n isBarrel: file?.isBarrel ?? false,\n isAggregation: file?.isAggregation ?? false,\n }\n }\n\n /**\n * Resolves a user-configured banner/footer value. `undefined` means not configured.\n */\n static #resolveUserText(\n value: string | ((meta: BannerMeta) => string) | undefined,\n meta: InputMeta | undefined,\n file: ResolveBannerFile | undefined,\n ): string | undefined {\n if (typeof value === 'function') return value(Resolver.#buildBannerMeta(meta, file))\n if (typeof value === 'string') return value\n return undefined\n }\n\n static #buildDefaultBanner({ title, version, config }: { title?: string; version?: string; config: Config }): string {\n const lines = ['/**', '* Generated by Kubb (https://kubb.dev/).', '* Do not edit manually.']\n\n if (config.output.defaultBanner !== 'simple') {\n const input = config.input\n const source = typeof input === 'string' ? (getInputKind(input) === 'inline' ? 'text content' : path.basename(input)) : 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","import type { PluginType } from './definePlugin.ts'\nimport { Resolver, type ResolverBuildOptions, type ResolverFile } from './Resolver.ts'\n\n/**\n * The plugin-specific resolver fields handed to `createResolver`. `name` and `file` fall\n * back to the built-ins when omitted. Every method reaches sibling helpers through `this`,\n * which `ThisType` types as the full resolver.\n */\ntype ResolverOptions<T extends PluginType> = Omit<T['resolver'], keyof Resolver> & {\n pluginName: T['name']\n name?: T['resolver']['name']\n file?: ResolverFile\n} & ThisType<T['resolver']>\n\n/**\n * Defines a plugin resolver, the object that decides what every generated symbol and file\n * path is called. Override the top-level `name` and `file` to set the plugin's conventions,\n * and add your own naming helpers, top-level (`typeName`, …) or grouped in namespaces\n * (`query`, `schema`, …). Every method reaches sibling helpers and the built-in machinery\n * through `this.name`, `this.file`, and `this.default`.\n *\n * @example Custom identifier casing\n * ```ts\n * export const resolverTs = createResolver<PluginTs>({\n * pluginName: 'plugin-ts',\n * name(name) {\n * return ensureValidVarName(pascalCase(name))\n * },\n * })\n * ```\n *\n * @example Rename generated files with `file.baseName`\n * ```ts\n * export const resolverFaker = createResolver<PluginFaker>({\n * pluginName: 'plugin-faker',\n * name(name) {\n * return camelCase(name, { prefix: 'create' })\n * },\n * file: {\n * baseName({ name, extname }) {\n * return `${camelCase(name, { prefix: 'create' })}${extname}`\n * },\n * },\n * })\n * ```\n *\n * @example Own the full path with `file.path`\n * ```ts\n * export const resolverFaker = createResolver<PluginFaker>({\n * pluginName: 'plugin-faker',\n * file: {\n * path({ baseName, output }) {\n * return `${output.path}/mocks/${baseName}`\n * },\n * },\n * })\n * ```\n */\nexport function createResolver<T extends PluginType>(options: ResolverOptions<T>): T['resolver'] {\n return new Resolver(options as unknown as ResolverBuildOptions) as T['resolver']\n}\n","import { readFile } from 'node:fs/promises'\nimport { inParallel, matchesStored, toError } from '@internals/utils'\nimport { ast, extractStringsFromNodes, type CodeNode, type FileNode } from '@kubb/ast'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { Storage } from './createStorage.ts'\nimport type { Parser } from './defineParser.ts'\nimport { Diagnostics } from './Diagnostics.ts'\nimport type { OutputManifest } from './outputManifest.ts'\nimport type { Hookable } from './Hookable.ts'\nimport type { Config, KubbFileProcessingUpdate, KubbHooks } from './types.ts'\n\n/** Files kept in flight at once, writing the output and reading it back for the manifest. */\nexport const FILE_CONCURRENCY = 50\n\ntype ParseOptions = {\n parsers?: Map<FileNode['extname'], Parser>\n}\n\ntype WriteOptions = ParseOptions & {\n storage: Storage\n signal?: AbortSignal\n /**\n * Consulted before each write so a file the output passes already normalized is recognized as\n * unchanged. Omitted when no formatter, linter, or `postGenerate` step is configured.\n */\n manifest?: OutputManifest\n /**\n * Receives `kubb:files:processing:start`, `:update` (in input order, as files finish) and `:end` for the write. `config` fills the update rows.\n */\n hooks?: Hookable<KubbHooks>\n config?: Config\n}\n\nfunction joinSources(file: FileNode): string {\n return file.sources\n .map((source) => extractStringsFromNodes(source.nodes as Array<CodeNode>))\n .filter(Boolean)\n .join('\\n\\n')\n}\n\n/** Runs a parser call and turns a crash into a `KUBB_PARSER_FAILED` diagnostic that names the parser. */\nfunction runParser(parser: Parser, print: () => string): string {\n try {\n return print()\n } catch (error) {\n throw new Diagnostics.Error(Diagnostics.fromExtension(error, { kind: 'parser', extension: parser }))\n }\n}\n\n/**\n * Reads a `copy` file and prints it through the parser's `copy` hook, or verbatim with `banner`/`footer` when there is none.\n */\nasync function parseCopy(file: FileNode, parser: Parser | undefined): Promise<string> {\n const content = await readFile(file.copy as string, 'utf8').catch((err) => {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pluginFailed,\n severity: 'error',\n message: `Could not copy file into output: ${file.copy}`,\n help: 'Check that the file a plugin copies into the output exists and is readable.',\n cause: toError(err),\n })\n })\n\n if (parser?.copy) {\n return runParser(parser, () => parser.parse(ast.factory.createFile(parser.copy!(file, content))))\n }\n\n return [file.banner, content, file.footer]\n .filter((segment): segment is string => Boolean(segment))\n .map((segment) => segment.trimEnd())\n .join('\\n')\n}\n\nfunction mergeFile<TMeta extends object = object>(a: FileNode<TMeta>, b: FileNode<TMeta>): FileNode<TMeta> {\n return {\n ...a,\n // Incoming file (b) takes precedence for banner/footer so a barrel file (whose\n // banner/footer the barrel plugin resolves last) wins over a plugin-generated\n // file at the same path.\n banner: b.banner,\n footer: b.footer,\n // A verbatim-copy file cannot be merged with rendered content; the incoming `copy` wins.\n copy: b.copy ?? a.copy,\n sources: [...a.sources, ...b.sources],\n imports: [...a.imports, ...b.imports],\n exports: [...a.exports, ...b.exports],\n }\n}\n\nfunction isIndexPath(path: string): boolean {\n return path.endsWith('/index.ts') || path === 'index.ts'\n}\n\n// Sort order: shortest path first. Within a length bucket, index.ts barrels last.\nfunction compareFiles(a: FileNode, b: FileNode): number {\n return a.path.length - b.path.length || Number(isIndexPath(a.path)) - Number(isIndexPath(b.path))\n}\n\n/**\n * Writes `source` to `file.path` unless the storage already holds it, either verbatim or, per the\n * manifest, as what the output passes make of it. Checking here rather than in a driver gives a\n * storage writing to S3 or a database the same guarantee `fsStorage` has. `false` when skipped.\n */\nasync function writeChanged({\n storage,\n manifest,\n file,\n source,\n signal,\n}: Pick<WriteOptions, 'storage' | 'manifest' | 'signal'> & { file: FileNode; source: string }): Promise<boolean> {\n signal?.throwIfAborted()\n const stored = await storage.readItem(file.path)\n if (stored !== null && (matchesStored({ stored, source }) || manifest?.isUpToDate({ key: file.path, source, disk: stored }))) return false\n signal?.throwIfAborted()\n await storage.writeItem(file.path, source, { stored })\n // Only a file that was written can have been changed by the output passes.\n manifest?.track({ key: file.path, source })\n return true\n}\n\n/** Reports finished files in input order: each finished file flushes the run of finished files ahead of it as one update. */\nfunction createProgress(files: Array<FileNode>, config: Config, hooks: Hookable<KubbHooks>): (index: number) => Promise<void> {\n const finished: Array<boolean> = []\n let flushed = 0\n return async (index) => {\n finished[index] = true\n // Rows leave `source` out: buffering it would hold every generated file in memory.\n const updates: Array<KubbFileProcessingUpdate> = []\n while (finished[flushed]) {\n flushed++\n updates.push({ file: files[flushed - 1]!, processed: flushed, total: files.length, percentage: (flushed / files.length) * 100, config })\n }\n if (updates.length) await hooks.callHook('kubb:files:processing:update', { files: updates })\n }\n}\n\n/**\n * In-memory file store for generated files, and the writer that turns them into source\n * strings on `storage`. Files sharing a `path` are merged (sources/imports/exports\n * concatenated). The `files` getter is sorted by path length (barrel `index.ts` last\n * within a bucket).\n *\n * @example\n * ```ts\n * const manager = new FileManager()\n * manager.upsert(myFile)\n * manager.files // sorted view\n * await manager.write(manager.files, { storage: fsStorage() })\n * ```\n */\nexport class FileManager {\n readonly #cache = new Map<string, FileNode>()\n // Cached sorted view, rebuilt lazily on the next `files` read. Nulled (not mutated) on every\n // write so callers holding a prior reference keep their snapshot, `dispose()` included.\n #sorted: Array<FileNode> | null = null\n\n add(...files: Array<FileNode>): Array<FileNode> {\n return this.#store(files, false)\n }\n\n upsert(...files: Array<FileNode>): Array<FileNode> {\n return this.#store(files, true)\n }\n\n /** Stores a generator result: a file array is upserted as is, an element renders through `renderer` first, falsy is a no-op. */\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.upsert(...(result as Array<FileNode>))\n return\n }\n\n if (!renderer) return\n\n using instance = renderer()\n await instance.render(result)\n\n this.upsert(...instance.files)\n }\n\n #store(files: ReadonlyArray<FileNode>, mergeExisting: boolean): Array<FileNode> {\n // Same-path files in one batch always merge; an existing file only on upsert.\n const batch = new Set<string>()\n const resolved = files.map((file) => {\n const existing = this.#cache.get(file.path)\n const merged = ast.factory.createFile(existing && (mergeExisting || batch.has(file.path)) ? mergeFile(existing, file) : file)\n this.#cache.set(merged.path, merged)\n batch.add(merged.path)\n return merged\n })\n if (resolved.length > 0) this.#sorted = null\n return resolved\n }\n\n /**\n * Releases all stored files. Called by the core after `kubb:build:end`.\n */\n dispose(): void {\n this.#cache.clear()\n this.#sorted = null\n }\n\n /**\n * All stored files in stable sort order (shortest path first, barrel files\n * last within a length bucket). Returns a cached view, do not mutate.\n */\n get files(): Array<FileNode> {\n return (this.#sorted ??= [...this.#cache.values()].sort(compareFiles))\n }\n\n /**\n * Converts a file's AST sources (or its `copy` source) into the final on-disk string.\n */\n async parse(file: FileNode, { parsers }: ParseOptions = {}): Promise<string> {\n const parser = parsers?.get(file.extname)\n\n if (file.copy) {\n return parseCopy(file, parser)\n }\n\n if (!parser) {\n return joinSources(file)\n }\n\n return runParser(parser, () => parser.parse(file))\n }\n\n /**\n * Parses and writes every file through a bounded pool of workers. A small spec runs all its files\n * at once; a spec with thousands of files keeps at most {@link FILE_CONCURRENCY} parsed sources in\n * memory rather than holding every source, while still overlapping each file's write with the\n * next file's parse. Files finish in whatever order they parse, so each finished file flushes the\n * run of finished files ahead of it as one `kubb:files:processing:update`, keeping rows in input order.\n *\n * A file the storage already holds is skipped, so a rebuild that generates identical output\n * writes nothing and leaves every mtime where it was. `kubb:files:processing:end` lists the\n * skipped paths as `unchanged`.\n */\n async write(files: Array<FileNode>, { storage, parsers, manifest, signal, hooks, config }: WriteOptions): Promise<void> {\n if (files.length === 0) return\n\n await hooks?.callHook('kubb:files:processing:start', { files })\n const unchanged: Array<string> = []\n const progress = hooks && config ? createProgress(files, config, hooks) : undefined\n\n await inParallel({\n items: files,\n limit: FILE_CONCURRENCY,\n run: async (file, index) => {\n signal?.throwIfAborted()\n const source = await this.parse(file, { parsers })\n if (source && !(await writeChanged({ storage, manifest, file, source, signal }))) unchanged.push(file.path)\n await progress?.(index)\n },\n })\n\n await hooks?.callHook('kubb:files:processing:end', { files, unchanged })\n }\n}\n","/**\n * Per-node memo shared by every plugin that generates from the same schema or operation node in\n * one generate pass. The driver creates one `NodeCache` per node during the walk and hands the\n * same instance to each plugin's generator context, so work derived purely from the node (its\n * resolved name, imports, parameters) is computed by the first plugin that needs it and reused by\n * the rest instead of being recomputed per plugin.\n *\n * Keys are namespaced by convention (`'plugin-ts:imports'`) so two plugins caching different\n * derivations of the same node never collide.\n *\n * @example Fill on first read, reuse afterwards\n * ```ts\n * const imports = ctx.cache.ensureItem('plugin-ts:imports', () => ctx.resolver.imports({ node, root, output }))\n * ```\n */\nexport type NodeCache = {\n /**\n * Returns the value stored under `key`, or `undefined` when nothing is stored yet.\n */\n readItem<TValue>(key: string): TValue | undefined\n /**\n * Stores `value` under `key`, overwriting any previous value, and returns it.\n */\n writeItem<TValue>(key: string, value: TValue): TValue\n /**\n * Returns the value stored under `key`, computing and storing it with `factory` on the first\n * call. Later calls with the same key return the stored value without running `factory` again.\n */\n ensureItem<TValue>(key: string, factory: () => TValue): TValue\n}\n\n/**\n * Builds an empty {@link NodeCache} backed by a plain `Map`. Called once per node in the generate\n * walk.\n */\nexport function createNodeCache(): NodeCache {\n const store = new Map<string, unknown>()\n\n return {\n readItem<TValue>(key: string): TValue | undefined {\n return store.get(key) as TValue | undefined\n },\n writeItem<TValue>(key: string, value: TValue): TValue {\n store.set(key, value)\n return value\n },\n ensureItem<TValue>(key: string, factory: () => TValue): TValue {\n if (store.has(key)) return store.get(key) as TValue\n\n const value = factory()\n store.set(key, value)\n return value\n },\n }\n}\n","import { resolve } from 'node:path'\nimport { escapePointerToken, getElapsedMs, toError } from '@internals/utils'\nimport { ast, collectUsedSchemaNames, type Enforce, type FileNode, type InputMeta, type InputNode, type OperationNode, type SchemaNode } from '@kubb/ast'\nimport { type Diagnostic, type DiagnosticLocation, Diagnostics, type ProblemDiagnostic } from './Diagnostics.ts'\nimport type { Generator, GeneratorContext } from './defineGenerator.ts'\nimport type { Parser } from './defineParser.ts'\nimport type { KubbPluginSetupContext, Plugin, PluginName, ResolvePluginOptions, Group, NormalizedPlugin, PluginType } from './definePlugin.ts'\nimport { normalizeOutput } from './definePlugin.ts'\nimport { checkCompatibility, checkDependencies, resolveMeta } from './defineExtension.ts'\nimport { kubbContext } from './composables.ts'\nimport { createResolver } from './createResolver.ts'\nimport { Resolver } from './Resolver.ts'\nimport { FileManager } from './FileManager.ts'\nimport { createNodeCache } from './nodeCache.ts'\nimport type { OutputManifest } from './outputManifest.ts'\nimport { checkoutGitInput, gitInputRegExp } from './gitInput.ts'\nimport { inputToAdapterSource } from './input.ts'\n\nimport type { Config, KubbHooks } from './types.ts'\nimport type { Adapter, AdapterSource } from './createAdapter.ts'\nimport type { Hookable } from './Hookable.ts'\n\ntype Options = {\n hooks: Hookable<KubbHooks>\n signal?: AbortSignal\n /**\n * Passed to `fileManager.write` so files the output passes already normalized are left alone.\n */\n manifest?: OutputManifest\n /**\n * The output directory `output.clean` empties. Emptied right before the files are written, so a\n * run that fails earlier leaves the previous output in place.\n */\n cleanPath?: string\n}\n\ntype RequirePluginContext = {\n /**\n * Name of the plugin that declared the dependency, included in the error so users can\n * trace which plugin needs the missing one.\n */\n requiredBy?: string\n}\n\nconst ENFORCE_ORDER = { pre: -1, post: 1 } satisfies Record<Enforce, number>\n\n/** `include` filter types that select operations, and so prune the schemas they do not reach. */\nconst OPERATION_FILTER_TYPES: ReadonlySet<string> = new Set(['tag', 'operationId', 'path', 'method', 'contentType', 'extension'])\n\nconst enforceWeight = (plugin: NormalizedPlugin): number => (plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0)\n\n/**\n * The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output\n * at the plugin root and empty filter lists.\n */\nconst defaultPluginOptions = (): NormalizedPlugin['options'] => ({ output: { path: '.', mode: 'directory' }, exclude: [], override: [] })\n\n/**\n * Fills in the `output`, `exclude`, and `override` a `NormalizedPlugin` needs from a plugin's raw\n * options, running `output` through `normalizeOutput`. Idempotent, so the driver can apply it after\n * `setOptions` has already run without disturbing an already-normalized bag.\n */\nfunction normalizePluginOptions(rawOptions: Plugin['options'], pluginName: string): NormalizedPlugin['options'] {\n const options: NormalizedPlugin['options'] = { ...defaultPluginOptions(), ...(rawOptions ?? {}) }\n const group = 'group' in options ? (options.group as Group | null | undefined) : undefined\n options.output = normalizeOutput({ output: options.output, group, pluginName })\n return options\n}\n\n/**\n * Throws `KUBB_INVALID_PLUGIN_OPTIONS` when a `plugins` entry is not a plugin object, such as a\n * factory passed without calling it.\n */\nfunction assertPluginEntry(entry: unknown, index: number): asserts entry is Plugin {\n if (typeof entry === 'function') {\n const name = entry.name || 'pluginName'\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `plugins[${index}] is a function (\"${name}\"), not a plugin.`,\n help: `Call it: ${name}()`,\n location: { kind: 'config' },\n })\n }\n if (typeof entry !== 'object' || entry === null) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `plugins[${index}] is ${entry === null ? 'null' : typeof entry}, not a plugin.`,\n help: 'Pass the result of a plugin factory, for example `pluginTs()`, or remove the entry.',\n location: { kind: 'config' },\n })\n }\n}\n\n/**\n * Where a generator crashed: a label naming the node and, when the node has one, a JSON pointer\n * to it. Built from the node fields so core stays adapter-agnostic.\n */\nfunction getCrashSite(node: SchemaNode | OperationNode): { label: string; location?: DiagnosticLocation } {\n if (node.kind === 'Schema') {\n return node.name\n ? { label: `schema \"${node.name}\"`, location: { kind: 'schema', pointer: `#/components/schemas/${escapePointerToken(node.name)}` } }\n : { label: 'an inline schema' }\n }\n if (!node.method || !node.path) return { label: `operation \"${node.operationId}\"` }\n return {\n label: `operation \"${node.operationId}\" (${node.method.toUpperCase()} ${node.path})`,\n location: { kind: 'operation', pointer: `#/paths/${escapePointerToken(node.path)}/${node.method.toLowerCase()}` },\n }\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 * Removers for every listener the driver added (plugin, generator) so `dispose()` can detach\n * them in one pass. External `hooks.hook(...)` listeners are not tracked.\n */\n readonly #unhooks: Array<() => void> = []\n\n constructor(config: Config, options: Options) {\n this.config = config\n this.options = options\n this.adapter = config.adapter ?? null\n }\n\n /**\n * Checks the adapter's and parsers' `meta.compatibility`, then normalizes and checks 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 this.options.signal?.throwIfAborted()\n for (const extension of [this.config.adapter, ...this.config.parsers]) {\n if (extension?.meta) checkCompatibility(extension.meta)\n }\n\n // Plugins are keyed by name, so a second entry with the same name would silently replace the first.\n const names = new Set<string>()\n const normalized = this.#sortPlugins(\n this.config.plugins.map((rawPlugin, index) => {\n assertPluginEntry(rawPlugin, index)\n if (rawPlugin.meta) checkCompatibility(rawPlugin.meta)\n\n const meta = resolveMeta(rawPlugin)\n if (names.has(meta.name)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `Plugin \"${meta.name}\" appears twice in \\`plugins\\`.`,\n help: 'Remove the duplicate, or merge its options.',\n location: { kind: 'config' },\n })\n }\n names.add(meta.name)\n const normalizedPlugin: NormalizedPlugin = {\n name: meta.name,\n meta,\n dependencies:\n typeof rawPlugin.dependencies === 'function' ? rawPlugin.dependencies(rawPlugin.options ?? {}, { config: this.config }) : rawPlugin.dependencies,\n enforce: rawPlugin.enforce,\n hooks: rawPlugin.hooks,\n setup: rawPlugin.setup,\n // `rawPlugin.options` is the user-supplied shape. The normalized `output`/`exclude`/`override`\n // bag is filled in by the post-setup `normalizePluginOptions` pass, after `setOptions` runs.\n options: (rawPlugin.options ?? defaultPluginOptions()) as NormalizedPlugin['options'],\n resolver: createResolver<PluginType>({ pluginName: meta.name }),\n }\n return normalizedPlugin\n }),\n )\n\n const byName = new Map(normalized.map((plugin) => [plugin.name, plugin]))\n for (const plugin of normalized) {\n checkDependencies({ name: plugin.name, dependencies: plugin.dependencies, plugins: byName })\n }\n\n for (const plugin of normalized) {\n this.#registerPlugin(plugin)\n this.plugins.set(plugin.name, plugin)\n }\n\n if (this.config.adapter) {\n this.#adapterSource = inputToAdapterSource(this.config)\n }\n }\n\n /**\n * Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with\n * `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks.\n * A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive\n * at the comparator level, so a chain where A depends on B and B depends on C could come out\n * wrong when A and C are never compared directly. Dependencies on plugins missing from the\n * config are ignored here and surface later through `requirePlugin`.\n */\n #sortPlugins(plugins: Array<NormalizedPlugin>): Array<NormalizedPlugin> {\n const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b))\n const names = new Set(queue.map((plugin) => plugin.name))\n const blockedBy = new Map(\n queue.map((plugin) => {\n const dependencies = Array.isArray(plugin.dependencies) ? plugin.dependencies : Object.keys(plugin.dependencies ?? {})\n return [plugin.name, new Set(dependencies.filter((name) => names.has(name) && name !== plugin.name))]\n }),\n )\n\n // One plugin leaves `queue` per pass, so iterating once per plugin drains it. Each pass takes\n // the lowest-index plugin with no remaining blockers, preserving enforce and declaration order.\n const sorted: Array<NormalizedPlugin> = []\n for (const _ of plugins) {\n const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0)\n if (index === -1) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidPluginOptions,\n severity: 'error',\n message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(' → ')}.`,\n help: 'Remove one of the `dependencies` entries so the plugins can be ordered.',\n location: { kind: 'config' },\n })\n }\n\n const [plugin] = queue.splice(index, 1)\n if (!plugin) break\n\n sorted.push(plugin)\n for (const blockers of blockedBy.values()) blockers.delete(plugin.name)\n }\n\n return sorted\n }\n\n get hooks() {\n return this.options.hooks\n }\n\n /**\n * Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from\n * `run` do not re-parse.\n */\n async #parseInput(): Promise<void> {\n if (this.inputNode || !this.adapter || !this.#adapterSource) return\n\n this.options.signal?.throwIfAborted()\n const source = this.#adapterSource\n const checkout = source.type === 'path' && gitInputRegExp.test(source.path) ? await checkoutGitInput(source.path, this.options.signal) : undefined\n try {\n this.inputNode = await this.adapter.parse(checkout ? { type: 'path', path: checkout.path } : source, { signal: this.options.signal })\n } catch (caughtError) {\n throw new Diagnostics.Error(Diagnostics.fromExtension(caughtError, { kind: 'adapter', extension: this.adapter }))\n } finally {\n await checkout?.dispose()\n }\n }\n\n /**\n * Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that\n * external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for\n * `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a\n * plugin-scoped context.\n *\n * @internal\n */\n #registerPlugin(plugin: NormalizedPlugin): void {\n const { hooks } = plugin\n\n if (!hooks) return\n\n const { 'kubb:plugin:setup': _setup, ...configHooks } = hooks\n\n this.#unhooks.push(this.hooks.addHooks(configHooks))\n }\n\n /**\n * Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that\n * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its\n * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so\n * plugins can configure generators, resolvers, macros, and options before `buildStart`.\n */\n async setupHooks(): Promise<void> {\n for (const plugin of this.plugins.values()) {\n const setupHook = plugin.hooks?.['kubb:plugin:setup']\n if (!plugin.setup && !setupHook) continue\n\n const ctx: KubbPluginSetupContext = {\n config: this.config,\n options: plugin.options ?? {},\n addGenerator: (...generators) => {\n plugin.generators = [...(plugin.generators ?? []), ...generators]\n },\n setResolver: (resolver) => {\n plugin.resolver = Resolver.merge(createResolver<PluginType>({ pluginName: plugin.name }), resolver)\n },\n addMacro: (macro) => {\n plugin.macros = [...(plugin.macros ?? []), macro]\n },\n setMacros: (macros) => {\n plugin.macros = [...macros]\n },\n setOptions: (opts) => {\n plugin.options = normalizePluginOptions({ ...plugin.options, ...opts }, plugin.name)\n },\n injectFile: (userFileNode) => {\n this.fileManager.add(ast.factory.createFile(userFileNode))\n },\n requirePlugin: ((name: string) => this.requirePlugin(name, { requiredBy: plugin.name })) as KubbPluginSetupContext['requirePlugin'],\n }\n\n try {\n // Composables such as `addGenerator()` read `ctx` from `kubbContext`, also after an `await` in setup.\n await kubbContext.run(ctx, async () => {\n if (plugin.setup) {\n plugin.options = normalizePluginOptions(await plugin.setup(ctx.options, ctx), plugin.name)\n }\n await setupHook?.(ctx)\n })\n } catch (caughtError) {\n // Attributed to the plugin, so the run summary counts it as a failed plugin.\n throw new Diagnostics.Error(Diagnostics.fromExtension(caughtError, { kind: 'plugin', extension: plugin }))\n }\n }\n }\n\n /**\n * Runs the full plugin pipeline. Returns the diagnostics collected so far even\n * when an outer hook throws, since the orchestrator preserves partial state by capturing\n * the failure as a {@link Diagnostic} instead of propagating. Each plugin also\n * contributes a `timing` diagnostic for the run summary.\n */\n async run(): Promise<{ diagnostics: Array<Diagnostic> }> {\n const { hooks, config, fileManager } = this\n const diagnostics: Array<Diagnostic> = []\n const parsersMap = new Map<FileNode['extname'], Parser>()\n\n for (const parser of config.parsers) {\n if (parser.extNames) {\n for (const ext of parser.extNames) parsersMap.set(ext, parser)\n }\n }\n\n // 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 this.options.signal?.throwIfAborted()\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 await this.setupHooks()\n\n // Normalize each plugin's options once setup hooks have run, so the generate loop always\n // sees a filled-in bag whether or not the plugin called `setOptions`.\n for (const plugin of this.plugins.values()) {\n this.options.signal?.throwIfAborted()\n plugin.options = normalizePluginOptions(plugin.options, plugin.name)\n }\n\n if (this.adapter && this.inputNode) {\n const { meta, schemas, operations } = this.inputNode\n const buildStartContext = this.#withFiles({\n config,\n adapter: this.adapter,\n meta,\n nodeCounts: { schemas: schemas.length, operations: operations.length },\n getPlugin: this.getPlugin.bind(this),\n })\n await hooks.callHook('kubb:build:start', buildStartContext)\n }\n\n const generatorPlugins: Array<{\n plugin: NormalizedPlugin\n context: Omit<GeneratorContext, 'options' | 'cache'>\n hrStart: ReturnType<typeof process.hrtime>\n }> = []\n\n for (const plugin of this.plugins.values()) {\n const context = this.getContext(plugin)\n const hrStart = process.hrtime()\n\n try {\n await hooks.callHook('kubb:plugin:start', { plugin })\n } catch (caughtError) {\n const error = toError(caughtError)\n const duration = getElapsedMs(hrStart)\n\n await this.#emitPluginEnd({ plugin, duration, success: false, error })\n\n diagnostics.push(\n Diagnostics.fromExtension(error, { kind: 'plugin', extension: plugin }),\n Diagnostics.performance({ plugin: plugin.name, duration }),\n )\n\n continue\n }\n\n if ((plugin.generators?.length ?? 0) > 0) {\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 each plugin's macros and generators.\n diagnostics.push(...(await this.#runGenerators(generatorPlugins)))\n\n await hooks.callHook('kubb:plugins:end', this.#withFiles({ config }))\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 if (this.options.cleanPath) await config.storage.empty(this.options.cleanPath)\n\n await fileManager.write(fileManager.files, {\n storage: config.storage,\n parsers: parsersMap,\n manifest: this.options.manifest,\n signal: this.options.signal,\n hooks,\n config,\n })\n\n await hooks.callHook('kubb:build:end', { files: this.fileManager.files, config, outputDir: outputRoot })\n\n return { diagnostics: Diagnostics.dedupe(diagnostics) }\n } catch (caughtError) {\n diagnostics.push(Diagnostics.from(caughtError))\n return { diagnostics: Diagnostics.dedupe(diagnostics) }\n }\n },\n )\n }\n\n /**\n * Widens `extra` with the files present at emit time and a bound `upsertFile`, the shape every\n * file-carrying hook context shares. Building it here in one place keeps the `files` and\n * `upsertFile` keys from being dropped by a stray spread at the call site.\n */\n #withFiles<T extends object>(extra: T): T & { files: Array<FileNode>; upsertFile: (...files: Array<FileNode>) => Array<FileNode> } {\n return {\n ...extra,\n files: this.fileManager.files,\n upsertFile: (...files: Array<FileNode>) => this.fileManager.upsert(...files),\n }\n }\n\n #emitPluginEnd({ plugin, duration, success, error }: { plugin: NormalizedPlugin; duration: number; success: boolean; error?: Error }): Promise<void> | void {\n return this.hooks.callHook('kubb:plugin:end', this.#withFiles({ plugin, duration, success, ...(error ? { error } : {}), config: this.config }))\n }\n\n /**\n * Runs schemas and operations through every plugin's generators. The walk is node-outer: each\n * schema is visited once and each operation once, and the node fans out to the matching\n * generators of every plugin in dependency order. A per-node cache (`createNodeCache`) is created\n * once per node and shared by all of that node's plugins, so node-derived work is computed once\n * and reused instead of recomputed per plugin. Each node still runs through the plugin's macros\n * and its exclude/include/override filters before that plugin's\n * generator sees it, so plugins stay isolated. Schemas run before operations so file output\n * stays deterministic across runs. A generator with a `match` predicate that resolves `false`\n * for a node is skipped for that node, without calling `schema`/`operation`.\n *\n * A failing plugin is dropped from the remaining walk, contributes an error diagnostic, and no\n * longer aborts the other plugins. `kubb:plugin:end` and each plugin's `timing` diagnostic fire\n * in dependency order once the walk finishes, driving the CLI's `Plugins N/M` counter. The\n * `operations` batch fires once per plugin after the single operation walk.\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' | 'cache'>; 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 { schemas, operations } = this.inputNode\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 // Freeze each plugin's per-run state once so the node-outer walk stays cheap. A plugin's\n // `error` drops it from every remaining node without touching the others.\n const states = entries.map(({ plugin, context, hrStart }) => {\n const generatorContext = { ...context, resolver: this.getResolver(plugin.name) }\n const { exclude, include, override } = plugin.options\n const generators = plugin.generators ?? []\n return {\n plugin,\n hrStart,\n generatorContext,\n exclude,\n include,\n override,\n optionsAreStatic: !exclude?.length && !include?.length && !override?.length,\n allowedSchemaNames: allowedSchemaNamesByPlugin.get(plugin.name) ?? null,\n schemaGenerators: generators.filter((generator) => generator.schema),\n operationGenerators: generators.filter((generator) => generator.operation),\n operationsGenerators: generators.filter((generator) => generator.operations),\n pluginOperations: [] as Array<OperationNode>,\n error: null as Error | null,\n // The node a generator crashed on, so the diagnostic can name it.\n crashSite: undefined as ReturnType<typeof getCrashSite> | undefined,\n }\n })\n\n type PluginState = (typeof states)[number]\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. The\n // per-node dispatch and the collected-operations batch both go through this so they agree on\n // what the plugin sees.\n const resolveForPlugin = <TNode extends SchemaNode | OperationNode>(\n state: PluginState,\n node: TNode,\n ): { transformedNode: TNode; options: NormalizedPlugin['options'] } | null => {\n const transformedNode = ast.applyMacros(node, state.plugin.macros ?? [])\n if (state.optionsAreStatic) return { transformedNode, options: state.plugin.options }\n\n const options = state.generatorContext.resolver.default.options<NormalizedPlugin['options']>(transformedNode, {\n options: state.plugin.options,\n exclude: state.exclude,\n include: state.include,\n override: state.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. For each\n // node the plugins fan out in dependency order and share one cache. A caught error drops that\n // plugin from the rest of the walk but not the others, so its remaining nodes are skipped\n // rather than retried. Generators run directly; `kubb:generate:*` still fires for observers.\n for (const node of schemas) {\n const cache = createNodeCache()\n for (const state of states) {\n if (state.error || !state.schemaGenerators.length) continue\n try {\n const resolved = resolveForPlugin(state, node)\n if (!resolved) continue\n\n const { transformedNode, options } = resolved\n if (state.allowedSchemaNames !== null && transformedNode.name && !state.allowedSchemaNames.has(transformedNode.name)) continue\n\n const ctx = { ...state.generatorContext, options, cache }\n await this.#dispatchNode({\n generators: state.schemaGenerators,\n node: transformedNode,\n ctx,\n generate: (generator) => generator.schema!(transformedNode, ctx),\n })\n await this.hooks.callHook('kubb:generate:schema', transformedNode, ctx)\n } catch (caughtError) {\n state.error = toError(caughtError)\n state.crashSite = getCrashSite(node)\n }\n }\n }\n\n // One pass over operations feeds both the per-operation generators and the batch each plugin's\n // `operations` receives, so every node is transformed and filtered exactly once. A plugin with\n // only an `operations` generator still collects its filtered nodes here.\n for (const node of operations) {\n const cache = createNodeCache()\n for (const state of states) {\n if (state.error || (!state.operationGenerators.length && !state.operationsGenerators.length)) continue\n try {\n const resolved = resolveForPlugin(state, node)\n if (!resolved) continue\n\n state.pluginOperations.push(resolved.transformedNode)\n\n if (state.operationGenerators.length) {\n const { transformedNode } = resolved\n const ctx = { ...state.generatorContext, options: resolved.options, cache }\n await this.#dispatchNode({\n generators: state.operationGenerators,\n node: transformedNode,\n ctx,\n generate: (generator) => generator.operation!(transformedNode, ctx),\n })\n await this.hooks.callHook('kubb:generate:operation', transformedNode, ctx)\n }\n } catch (caughtError) {\n state.error = toError(caughtError)\n state.crashSite = getCrashSite(node)\n }\n }\n }\n\n // The `operations` batch fires once per plugin after the single operation walk, in dependency\n // order, with a fresh cache since it spans every node rather than one.\n for (const state of states) {\n if (state.error || !state.operationsGenerators.length) continue\n try {\n const ctx = { ...state.generatorContext, options: state.plugin.options, cache: createNodeCache() }\n for (const generator of state.operationsGenerators) {\n await this.fileManager.dispatch({ result: await generator.operations!(state.pluginOperations, ctx), renderer: generator.renderer })\n }\n await this.hooks.callHook('kubb:generate:operations', state.pluginOperations, ctx)\n } catch (caughtError) {\n state.error = toError(caughtError)\n }\n }\n\n // Close out every plugin in dependency order, so `kubb:plugin:end` and the timing diagnostics\n // still count up in plugin order for the CLI's `Plugins N/M` line.\n for (const state of states) {\n const duration = getElapsedMs(state.hrStart)\n await this.#emitPluginEnd({ plugin: state.plugin, duration, success: !state.error, error: state.error ?? undefined })\n\n if (state.error) {\n const diagnostic = Diagnostics.fromExtension(state.error, { kind: 'plugin', extension: state.plugin })\n // Only a crash gains the node it failed on. A coded error already says where it is.\n const site = diagnostic.code === Diagnostics.code.pluginFailed && !diagnostic.location ? state.crashSite : undefined\n diagnostics.push(\n site\n ? { ...diagnostic, message: `While generating ${site.label}: ${diagnostic.message}`, ...(site.location ? { location: site.location } : {}) }\n : diagnostic,\n )\n }\n diagnostics.push(Diagnostics.performance({ plugin: state.plugin.name, duration }))\n }\n\n return diagnostics\n }\n\n /**\n * Runs `node` through the generators whose `match` accepts it; `generate` picks the method for the\n * node kind.\n */\n async #dispatchNode({\n generators,\n node,\n ctx,\n generate,\n }: {\n generators: Array<Generator>\n node: SchemaNode | OperationNode\n ctx: GeneratorContext\n generate: (generator: Generator) => ReturnType<NonNullable<Generator['schema']>>\n }): Promise<void> {\n for (const generator of generators) {\n const matches = generator.match ? await generator.match(node, ctx) : true\n if (!matches) continue\n await this.fileManager.dispatch({ result: await generate(generator), renderer: generator.renderer })\n }\n }\n\n /**\n * Removes every listener the driver added. Listeners attached directly to `hooks` from outside\n * the driver survive. Called at the end of a build to prevent leaks across repeated builds.\n *\n * @internal\n */\n dispose(): void {\n for (const unhook of this.#unhooks) unhook()\n this.#unhooks.length = 0\n // 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 /** Reads `plugin.resolver`, falling back to a fresh default for a name that is not a registered plugin. */\n getResolver<TName extends PluginName>(pluginName: TName): ResolvePluginOptions<TName>['resolver']\n getResolver(pluginName: string): Resolver {\n return this.plugins.get(pluginName)?.resolver ?? createResolver<PluginType>({ pluginName })\n }\n\n getContext<TOptions extends PluginType>(plugin: NormalizedPlugin<TOptions>): Omit<GeneratorContext<TOptions>, 'options' | 'cache'> {\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 signal: driver.options.signal,\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, options) {\n report({ code: Diagnostics.code.pluginWarning, severity: 'warning', message, ...options })\n },\n error(error, options) {\n if (Diagnostics.isError(error)) {\n report({ ...options, ...error.diagnostic })\n return\n }\n const cause = typeof error === 'string' ? undefined : error\n report({ code: Diagnostics.code.pluginFailed, severity: 'error', message: typeof error === 'string' ? error : error.message, cause, ...options })\n },\n info(message, options) {\n report({ code: Diagnostics.code.pluginInfo, severity: 'info', message, ...options })\n },\n }\n }\n\n getPlugin<TName extends PluginName>(pluginName: TName): Plugin<ResolvePluginOptions<TName>> | 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 PluginName>(pluginName: TName, context?: RequirePluginContext): Plugin<ResolvePluginOptions<TName>>\n requirePlugin(pluginName: string, context?: RequirePluginContext): Plugin {\n const plugin = this.getPlugin(pluginName)\n if (plugin) return plugin\n\n throw pluginNotFoundError({ pluginName, requiredBy: context?.requiredBy })\n }\n}\n\n/** The `KUBB_PLUGIN_NOT_FOUND` error `requirePlugin` throws, naming the plugin that needed it. */\nexport function pluginNotFoundError({ pluginName, requiredBy }: { pluginName: string; requiredBy?: string }): InstanceType<typeof Diagnostics.Error> {\n const by = requiredBy ? ` by \"${requiredBy}\"` : ''\n const help = requiredBy ? ` (required by \"${requiredBy}\")` : ''\n\n return new Diagnostics.Error({\n code: Diagnostics.code.pluginNotFound,\n severity: 'error',\n message: `Plugin \"${pluginName}\" is required${by} but not found. Make sure it is included in your Kubb config.`,\n help: `Add \"${pluginName}\" to the \\`plugins\\` array in kubb.config.ts${help}, or remove the dependency on it.`,\n location: { kind: 'config' },\n ...(requiredBy ? { plugin: requiredBy } : {}),\n })\n}\n","import { hash } from 'node:crypto'\nimport { inParallel } from '@internals/utils'\nimport type { Storage } from './createStorage.ts'\nimport { FILE_CONCURRENCY } from './FileManager.ts'\n\n/**\n * Bumped when the stored shape changes, so an older cache is discarded instead of misread.\n */\nconst VERSION = 1\n\n/**\n * How one generated file looked on either side of the output passes.\n */\ntype OutputManifestEntry = {\n /**\n * Hash of the content Kubb handed to the storage.\n */\n source: string\n /**\n * Hash of what the storage held once the output passes were done with it.\n */\n output: string\n}\n\ntype ManifestData = {\n version: number\n entries: Record<string, OutputManifestEntry>\n}\n\n/**\n * Remembers what the output passes did to each generated file, so the next run can tell \"the\n * formatter already turned this exact source into what is stored\" apart from a real change.\n * Without it the storage compares Kubb's bytes against the formatter's, never matches, and\n * rewrites the whole output tree on every build.\n */\nexport type OutputManifest = {\n /**\n * `true` when `source` is known to come out of the output passes as exactly the content stored,\n * meaning the write can be skipped.\n */\n isUpToDate(options: { key: string; source: string; disk: string }): boolean\n /**\n * Records the source Kubb wrote for `key`, marking it as the only kind of file the output passes\n * can have changed and so the only kind `commit` has to re-read.\n */\n track(options: { key: string; source: string }): void\n /**\n * Re-reads the files written this run and persists their source/output pairs on top of what is\n * stored. Nothing is pruned: a run generating a different set of files, or writing to a different\n * storage in the same root, must not evict what another run recorded.\n */\n commit(): Promise<void>\n}\n\nconst MANIFEST_KEY = 'output-manifest.json'\n\nasync function loadEntries({ cache }: { cache: Storage }): Promise<Record<string, OutputManifestEntry>> {\n try {\n const stored = await cache.readItem(MANIFEST_KEY)\n if (stored === null) return {}\n\n const data = JSON.parse(stored) as ManifestData\n if (data.version !== VERSION) return {}\n if (typeof data.entries !== 'object' || data.entries === null || Array.isArray(data.entries)) return {}\n\n return data.entries\n } catch {\n return {}\n }\n}\n\n/**\n * Loads the stored manifest, starting empty when it is missing, unreadable, or from an older\n * version. `storage` holds the generated files, `cache` holds the manifest itself.\n *\n * @example\n * ```ts\n * const manifest = await createOutputManifest({ storage: config.storage, cache: cacheStorage({ root: config.root }) })\n * ```\n */\nexport async function createOutputManifest({ storage, cache }: { storage: Storage; cache: Storage }): Promise<OutputManifest> {\n const entries = await loadEntries({ cache })\n const tracked = new Map<string, string>()\n\n return {\n isUpToDate({ key, source, disk }) {\n const entry = entries[key]\n if (!entry) return false\n\n return entry.source === hash('sha256', source) && entry.output === hash('sha256', disk)\n },\n track({ key, source }) {\n tracked.set(key, hash('sha256', source))\n },\n async commit() {\n try {\n const next = { ...entries }\n\n // Reads the tree back through the same pool that wrote it, rather than one file at a time.\n await inParallel({\n items: [...tracked],\n limit: FILE_CONCURRENCY,\n run: async ([key, source]) => {\n const stored = await storage.readItem(key)\n if (stored === null) return\n\n next[key] = { source, output: hash('sha256', stored) }\n },\n })\n\n await cache.writeItem(MANIFEST_KEY, JSON.stringify({ version: VERSION, entries: next } satisfies ManifestData))\n } catch {\n /* the record is an optimization, so a storage failure here must not fail a finished build */\n }\n },\n }\n}\n","/**\n * Backend that persists generated files. Kubb ships with `fsStorage` (writes\n * to disk) and `memoryStorage` (keeps everything in RAM). Implement this\n * interface to write somewhere else, such as S3 or a database.\n *\n * Method names follow Node's filesystem vocabulary, so `readItem` reads like\n * `readFile` and `writeItem` like `writeFile`.\n */\nexport type Storage = {\n /**\n * Identifier used in logs and diagnostics (`'fs'`, `'memory'`, `'s3'`).\n */\n readonly name: string\n /**\n * Reads the stored string. Returns `null` when the key is missing.\n */\n readItem(key: string): Promise<string | null>\n /**\n * Stores `value` under `key`, creating any required structure (directories,\n * buckets, ...).\n *\n * Pass `stored` when the caller already read the previous value to avoid\n * reading it again in storage implementations that support the optimization.\n */\n writeItem(key: string, value: string, options?: { stored?: string | null }): 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 readKeys(base?: string): Promise<Array<string>>\n /**\n * Removes stored entries. Pass `base` to scope the wipe to a key prefix.\n *\n * Omitting `base` is implementation-defined: in-memory stores wipe every\n * entry, while filesystem-backed stores treat a missing `base` as a no-op so\n * a bare `empty()` can never delete outside a known output directory.\n */\n empty(base?: string): Promise<void>\n}\n\n/**\n * Defines a custom storage backend. The builder receives user options and\n * returns a `Storage` implementation. Kubb ships with filesystem and in-memory\n * storages. A custom backend writes generated files elsewhere, such as cloud\n * storage or a database.\n *\n * @example In-memory storage (the built-in implementation)\n * ```ts\n * import { createStorage } from '@kubb/core'\n *\n * export const memoryStorage = createStorage(() => {\n * const store = new Map<string, string>()\n *\n * return {\n * name: 'memory',\n * async readItem(key) {\n * return store.get(key) ?? null\n * },\n * async writeItem(key, value) {\n * store.set(key, value)\n * },\n * async removeItem(key) {\n * store.delete(key)\n * },\n * async readKeys(base) {\n * const keys = [...store.keys()]\n * return base ? keys.filter((k) => k.startsWith(base)) : keys\n * },\n * async empty(base) {\n * if (!base) store.clear()\n * },\n * }\n * })\n * ```\n */\nexport const createStorage =\n <TOptions = Record<string, never>>(build: (options: TOptions) => Storage) =>\n (options?: TOptions): Storage =>\n build((options ?? {}) as TOptions)\n","import { resolve } from 'node:path'\nimport { listFiles, read, rm, 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 already holds that content, ignoring any trailing newline\n * a formatter left behind\n * - missing parent directories are created automatically\n * - `FileManager.write` bounds in-flight writes, so this driver does not pace itself\n *\n * @example\n * ```ts\n * import { fsStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * storage: fsStorage(),\n * })\n * ```\n */\nexport const fsStorage = createStorage(() => ({\n name: 'fs',\n async readItem(key: string) {\n try {\n return await read(resolve(key))\n } catch (_error) {\n return null\n }\n },\n async writeItem(key: string, value: string, options?: { stored?: string | null }) {\n await write(resolve(key), value, { sanity: false, stored: options?.stored })\n },\n async removeItem(key: string) {\n await rm(resolve(key), { force: true })\n },\n async readKeys(base?: string) {\n const resolvedBase = resolve(base ?? process.cwd())\n const keys: Array<string> = []\n\n try {\n for await (const path of listFiles(resolvedBase)) keys.push(path)\n } catch (_error) {\n // base directory does not exist yet\n }\n\n return keys\n },\n async empty(base?: string) {\n if (!base) {\n return\n }\n\n await rm(resolve(base), { recursive: true, force: true })\n },\n}))\n","import { hash } from 'node:crypto'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { existsSync, writeRaw } from '@internals/utils'\nimport { createStorage } from '../createStorage.ts'\nimport { fsStorage } from './fsStorage.ts'\n\ntype CacheStorageOptions = {\n /**\n * Project root the cache directory is derived from.\n *\n * @default process.cwd()\n */\n root?: string\n}\n\n/**\n * Directory Kubb keeps build caches in. A project with a `node_modules` gets\n * `node_modules/.cache/kubb`, the convention babel and eslint already use, so the cache stays out\n * of version control. Without one it falls back to the OS temp directory, keyed by root so two\n * projects sharing that directory keep their own cache.\n *\n * @example Inside a project\n * `resolveCacheDir('/project') // '/project/node_modules/.cache/kubb'`\n */\nexport function resolveCacheDir(root: string): string {\n const nodeModules = join(root, 'node_modules')\n if (existsSync(nodeModules)) return join(nodeModules, '.cache', 'kubb')\n\n return join(tmpdir(), 'kubb', hash('sha256', root).slice(0, 16))\n}\n\n/**\n * Filesystem storage for build caches rather than generated code. Keys are plain names resolved\n * inside {@link resolveCacheDir}, so a caller stores `'x.json'` without knowing where the cache\n * lives. Kept apart from the configured output storage, which may not be a local disk at all.\n *\n * @example\n * ```ts\n * const cache = cacheStorage({ root: config.root })\n * await cache.writeItem('output-manifest.json', JSON.stringify(entries))\n * ```\n */\nexport const cacheStorage = createStorage(({ root = process.cwd() }: CacheStorageOptions) => {\n const dir = resolveCacheDir(root)\n const fs = fsStorage()\n const toPath = (key: string) => join(dir, key)\n\n return {\n name: 'cache',\n readItem: (key) => fs.readItem(toPath(key)),\n async writeItem(key, value) {\n const filePath = toPath(key)\n await writeRaw(filePath, value)\n },\n removeItem: (key) => fs.removeItem(toPath(key)),\n readKeys: (base) => fs.readKeys(base ? toPath(base) : dir),\n // Same rule as `fsStorage`: a bare `empty()` deletes nothing, so storage-generic code cannot wipe the cache directory by accident.\n empty: async (base) => (base ? fs.empty(toPath(base)) : undefined),\n }\n})\n","import { toError } from '@internals/utils'\n\n/**\n * A function that can be registered as a hook listener, synchronous or async. Any return value is\n * allowed and ignored, so handlers that return a result for their own callers still register.\n */\ntype AsyncListener<TArgs extends Array<unknown>> = (...args: TArgs) => unknown\n\n/**\n * Typed hook emitter that awaits all async listeners before resolving.\n *\n * @example\n * ```ts\n * const hooks = new Hookable<{ build: [name: string] }>()\n * hooks.hook('build', async (name) => { console.log(name) })\n * await hooks.callHook('build', 'petstore') // all listeners awaited\n * ```\n */\nexport class Hookable<THooks extends { [K in keyof THooks]: Array<unknown> }> {\n readonly #listeners = new Map<string, Set<AsyncListener<Array<unknown>>>>()\n\n /**\n * Calls `hookName` and awaits all registered listeners sequentially.\n * Throws if any listener rejects, wrapping the cause in an error that names the hook.\n *\n * @example\n * ```ts\n * await hooks.callHook('build', 'petstore')\n * ```\n */\n callHook<THookName extends keyof THooks & string>(hookName: THookName, ...hookArgs: THooks[THookName]): Promise<void> | void {\n const listeners = this.#listeners.get(hookName)\n if (!listeners?.size) return\n\n return this.#emitAll(hookName, [...listeners], hookArgs)\n }\n\n async #emitAll(hookName: string, listeners: Array<AsyncListener<Array<unknown>>>, hookArgs: Array<unknown>): Promise<void> {\n for (const listener of listeners) {\n try {\n await listener(...hookArgs)\n } catch (err) {\n // Only the hook name goes in the message: the args can be a whole `Config` or AST subtree.\n throw new Error(`Error in async listener for \"${hookName}\"`, { cause: toError(err) })\n }\n }\n }\n\n /**\n * Registers a persistent listener for `hookName` and returns a function that removes it.\n *\n * @example\n * ```ts\n * const unhook = hooks.hook('build', async (name) => { console.log(name) })\n * unhook() // removes it\n * ```\n */\n hook<THookName extends keyof THooks & string>(hookName: THookName, handler: AsyncListener<THooks[THookName]>): () => void {\n let listeners = this.#listeners.get(hookName)\n if (!listeners) this.#listeners.set(hookName, (listeners = new Set()))\n listeners.add(handler as AsyncListener<Array<unknown>>)\n return () => this.removeHook(hookName, handler)\n }\n\n /**\n * Registers every handler in `configHooks` at once and returns a function that removes them\n * all. Undefined entries are skipped, so a partial hook object registers only its present keys.\n *\n * @example\n * ```ts\n * const unhook = hooks.addHooks({ build: onBuild, done: onDone })\n * unhook() // removes both\n * ```\n */\n addHooks(configHooks: Partial<{ [K in keyof THooks & string]: AsyncListener<THooks[K]> }>): () => void {\n const unhooks = (Object.keys(configHooks) as Array<keyof THooks & string>)\n .filter((name) => configHooks[name])\n .map((name) => this.hook(name, configHooks[name]!))\n\n return () => {\n for (const unhook of unhooks) unhook()\n }\n }\n\n /**\n * Removes a previously registered listener.\n *\n * @example\n * ```ts\n * hooks.removeHook('build', handler)\n * ```\n */\n removeHook<THookName extends keyof THooks & string>(hookName: THookName, handler: AsyncListener<THooks[THookName]>): void {\n this.#listeners.get(hookName)?.delete(handler as AsyncListener<Array<unknown>>)\n }\n\n /**\n * Returns the number of listeners registered for `hookName`.\n *\n * @example\n * ```ts\n * hooks.hook('build', handler)\n * hooks.listenerCount('build') // 1\n * ```\n */\n listenerCount<THookName extends keyof THooks & string>(hookName: THookName): number {\n return this.#listeners.get(hookName)?.size ?? 0\n }\n\n /**\n * No-op kept for callers written against the `EventEmitter`-backed version. Listeners are unbounded.\n *\n * @deprecated There is no listener ceiling anymore.\n */\n setMaxListeners(_max: number): void {}\n\n /**\n * Removes all listeners from every hook channel.\n *\n * @example\n * ```ts\n * hooks.removeAllHooks()\n * ```\n */\n removeAllHooks(): void {\n this.#listeners.clear()\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport process from 'node:process'\nimport { createInterface } from 'node:readline'\nimport { toError } from '@internals/utils'\nimport { type Result, x } from 'tinyexec'\nimport type { Hookable } from '../Hookable.ts'\nimport type { KubbHooks } from '../types.ts'\n\n/**\n * Outcome of one hook subprocess, also carried by the `kubb:hook:end` hook it emits.\n */\nexport type HookResult = { success: true; error: null } | { success: false; error: Error; stdout?: string; stderr?: string }\n\nexport type RunHookOptions = {\n hooks: Hookable<KubbHooks>\n /** Executable to run, resolved on `PATH` and in every `node_modules/.bin` above `cwd`. */\n command: string\n args?: ReadonlyArray<string>\n /** Label shown instead of the command line, for example a `postGenerate` step name. */\n name?: string\n /** Working directory for the command. Defaults to the current process directory. */\n cwd?: string\n signal?: AbortSignal\n}\n\nconst KILL_GRACE_MS = 2_000\n\nasync function settle(proc: Result, hooks: Hookable<KubbHooks>, id: string, commandWithArgs: string): Promise<HookResult> {\n let childError: Error | null = null\n let lineError: Error | null = null\n let lines: Promise<void> = Promise.resolve()\n let killTimer: NodeJS.Timeout | undefined\n proc.process?.once('error', (error) => {\n childError = error\n // An abort only asks the child to stop; one that swallows SIGTERM would otherwise hang the run.\n killTimer = setTimeout(() => proc.kill('SIGKILL'), KILL_GRACE_MS).unref()\n })\n // Lines are only read when a logger listens, so a quiet host does not pay to iterate them.\n if (hooks.listenerCount('kubb:hook:line') > 0) {\n for (const input of [proc.process?.stdout, proc.process?.stderr]) {\n if (!input) continue\n createInterface({ input }).on('line', (line) => {\n lines = lines\n .then(() => hooks.callHook('kubb:hook:line', { id, line }))\n .catch((error) => {\n lineError ??= toError(error)\n })\n })\n }\n }\n const output = await Promise.resolve(proc).catch(() => null)\n clearTimeout(killTimer)\n await lines\n\n const error = childError ?? lineError\n if (error) return { success: false, error }\n if (output?.exitCode === 0) return { success: true, error: null }\n return { success: false, error: new Error(`Hook execute failed: ${commandWithArgs}`), stdout: output?.stdout, stderr: output?.stderr }\n}\n\n/**\n * Spawns a command and returns its outcome, announcing it through `kubb:hook:start`,\n * `kubb:hook:line` (one per stdout or stderr line, only while a listener is attached) and\n * `kubb:hook:end`. A non-zero exit, a spawn failure, an abort or a throwing line listener returns\n * `success: false` instead of throwing. The failure travels on the result and `kubb:hook:end`\n * only, and the caller emits `kubb:success` or a diagnostic, so nothing is reported twice.\n */\nexport async function runHook({ hooks, command, args = [], name, cwd = process.cwd(), signal }: RunHookOptions): Promise<HookResult> {\n const id = randomUUID()\n await hooks.callHook('kubb:hook:start', { id, command, name, args })\n\n const proc = x(command, [...args], {\n signal,\n throwOnError: false,\n nodeOptions: { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32' },\n })\n const result = await settle(proc, hooks, id, [command, ...args].join(' '))\n await hooks.callHook('kubb:hook:end', { id, command, name, args, ...result })\n\n return result\n}\n","import { existsSync } from 'node:fs'\nimport { styleText } from 'node:util'\nimport { detectTool, FORMATTER_PREFERENCE, formatters, LINTER_PREFERENCE, linters, type ToolCommand, tokenize } from '@internals/utils'\nimport { Diagnostics } from '../Diagnostics.ts'\nimport type { Hookable } from '../Hookable.ts'\nimport type { Config, KubbHooks } from '../types.ts'\nimport type { Diagnostic, ProblemDiagnostic } from '../Diagnostics.ts'\nimport { runHook } from './runHook.ts'\n\nexport type RunOutputPassesOptions = {\n config: Config\n /**\n * Absolute directory the formatter and linter run over.\n */\n outputPath: string\n hooks: Hookable<KubbHooks>\n signal?: AbortSignal\n}\n\ntype ToolPass = {\n kind: 'format' | 'lint'\n label: string\n verb: string\n tools: Record<string, ToolCommand>\n preference: ReadonlyArray<string>\n code: ProblemDiagnostic['code']\n}\n\n/**\n * Format and lint are one pass over the output directory that differs only in these values.\n * `label` and `verb` are spelled out: deriving them from `kind` gives \"lintter\" and \"lintting\".\n */\nconst TOOL_PASSES: ReadonlyArray<ToolPass> = [\n { kind: 'format', label: 'formatter', verb: 'Formatting', tools: formatters, preference: FORMATTER_PREFERENCE, code: Diagnostics.code.formatFailed },\n { kind: 'lint', label: 'linter', verb: 'Linting', tools: linters, preference: LINTER_PREFERENCE, code: Diagnostics.code.lintFailed },\n]\n\ntype ToolPassRun = Pick<RunOutputPassesOptions, 'hooks' | 'outputPath' | 'signal'> & { pass: ToolPass; setting: string; cwd: string }\n\n/**\n * Resolves `auto` to an installed tool and runs it. Returns the failure instead of throwing.\n */\nasync function runToolPass({ pass, setting, outputPath, hooks, cwd, signal }: ToolPassRun): Promise<Error | null> {\n const detected = setting === 'auto' ? await detectTool(pass.preference, cwd) : setting\n if (!detected) {\n await hooks.callHook('kubb:warn', { message: `No ${pass.label} found (${pass.preference.join(', ')}). Skipping ${pass.verb.toLowerCase()}.` })\n return null\n }\n if (setting === 'auto') {\n await hooks.callHook('kubb:info', { message: `Auto-detected ${pass.label}: ${styleText('dim', detected)}` })\n }\n\n const tool = pass.tools[detected]\n // Nothing to run over when the output directory was never written: the tool would fail on an\n // empty target (oxlint with --no-ignore reports \"No files found to lint\").\n if (!tool || !existsSync(outputPath)) return null\n\n const result = await runHook({ hooks, command: tool.command, args: tool.args(outputPath), cwd, signal })\n if (result.success) {\n await hooks.callHook('kubb:success', { message: `${pass.verb} with ${styleText('dim', detected)} on ${styleText('dim', outputPath)} successfully` })\n return null\n }\n return result.error\n}\n\n/**\n * Runs `output.format`, `output.lint` and `output.postGenerate` over the generated output and\n * returns the diagnostics they produced. Each failure is emitted through `Diagnostics.emit` and\n * returned, so it reaches the summary, the reporters and the exit code; the passes keep going so\n * one failing tool does not hide the next. `Kubb.generate()` runs this after an error-free build\n * unless the host passes its own `processOutput`.\n *\n * @example\n * ```ts\n * const diagnostics = await runOutputPasses({ config, outputPath: '/repo/src/gen', hooks })\n * ```\n */\nexport async function runOutputPasses({ config, outputPath, hooks, signal }: RunOutputPassesOptions): Promise<Array<Diagnostic>> {\n const diagnostics: Array<Diagnostic> = []\n const report = async (code: ProblemDiagnostic['code'], label: string, error: Error) => {\n const diagnostic: ProblemDiagnostic = {\n code,\n severity: 'error',\n message: `${label} failed: ${error.message}`,\n help: 'Check that the tool is installed and that the command and its config are correct.',\n location: { kind: 'config' },\n cause: error,\n }\n diagnostics.push(diagnostic)\n await Diagnostics.emit(hooks, diagnostic)\n }\n\n for (const pass of TOOL_PASSES) {\n const setting = config.output[pass.kind]\n if (!setting) continue\n\n await hooks.callHook(`kubb:${pass.kind}:start`)\n const error = await runToolPass({ pass, setting, outputPath, hooks, cwd: config.root, signal })\n if (error) await report(pass.code, pass.label, error)\n await hooks.callHook(`kubb:${pass.kind}:end`)\n signal?.throwIfAborted()\n }\n\n const commands = config.output.postGenerate ?? []\n if (commands.length === 0) return diagnostics\n\n await hooks.callHook('kubb:hooks:start')\n for (const entry of commands) {\n const { command, name } = typeof entry === 'string' ? { command: entry, name: undefined } : entry\n const [executable, ...args] = tokenize(command)\n if (!executable) continue\n\n const result = await runHook({ hooks, command: executable, args, name, cwd: config.root, signal })\n if (result.success) await hooks.callHook('kubb:success', { message: `${styleText('dim', name ?? command)} successfully executed` })\n if (!result.success) await report(Diagnostics.code.postGenerateFailed, 'Post-generate command', result.error)\n signal?.throwIfAborted()\n }\n await hooks.callHook('kubb:hooks:end')\n\n return diagnostics\n}\n","import { resolve } from 'node:path'\nimport { isPathInside } from '@internals/utils'\nimport type { FileNode } from '@kubb/ast'\nimport { type Diagnostic, Diagnostics } from './Diagnostics.ts'\nimport type { Storage } from './createStorage.ts'\nimport { KubbDriver } from './KubbDriver.ts'\nimport { createOutputManifest, type OutputManifest } from './outputManifest.ts'\nimport { cacheStorage } from './storages/cacheStorage.ts'\nimport { fsStorage } from './storages/fsStorage.ts'\nimport type { BuildOutput, Config, KubbHooks, UserConfig } from './types.ts'\nimport { Hookable } from './Hookable.ts'\nimport { runOutputPasses, type RunOutputPassesOptions } from './output/runOutputPasses.ts'\n\nfunction resolveConfig(userConfig: UserConfig): Config {\n return {\n ...userConfig,\n root: userConfig.root || process.cwd(),\n parsers: userConfig.parsers ?? [],\n output: {\n format: false,\n lint: false,\n defaultBanner: 'simple',\n ...userConfig.output,\n },\n storage: userConfig.storage ?? fsStorage(),\n reporters: userConfig.reporters ?? [],\n plugins: userConfig.plugins ?? [],\n }\n}\n\n/**\n * Only the fs storage writes `output.path`, so only then do the passes have fresh files to run\n * over; a memory or custom storage would leave them formatting whatever an earlier run left there.\n */\nfunction writesOutputDirectory(storage: Storage): boolean {\n return storage.name === 'fs'\n}\n\n/**\n * Whether anything runs over the output directory after the files are written. Only then can the\n * bytes on disk stop matching what Kubb wrote, which is what the manifest exists to track.\n */\nfunction hasOutputPasses({ output, storage }: Pick<Config, 'output' | 'storage'>): boolean {\n return writesOutputDirectory(storage) && Boolean(output.format || output.lint || output.postGenerate?.length)\n}\n\nexport type CreateKubbOptions = {\n /**\n * Receives Kubb lifecycle hooks for the run.\n */\n hooks?: Hookable<KubbHooks>\n /**\n * Stops the build at the next safe checkpoint.\n */\n signal?: AbortSignal\n}\n\n/**\n * Host hooks for a single {@link Kubb.generate} call. All optional. Progress narration rides the\n * `kubb:*` lifecycle hooks on `.hooks`, so hosts subscribe there rather than pass a callback.\n */\nexport type GenerateOptions = {\n /**\n * Replaces the output passes that run after an error-free build. The default,\n * {@link runOutputPasses}, formats, lints and runs `output.postGenerate` over the generated\n * output and returns the diagnostics they emitted.\n */\n processOutput?: (context: RunOutputPassesOptions) => Promise<Array<Diagnostic>>\n}\n\n/**\n * What a {@link Kubb.generate} call produced, for the host to map onto its own result shape.\n */\nexport type GenerateResult = {\n /**\n * `true` when the build and every output pass completed without an error-level diagnostic.\n */\n success: boolean\n /**\n * All files generated during the build.\n */\n files: Array<FileNode>\n /**\n * Build diagnostics plus any collected from the output passes.\n */\n diagnostics: Array<Diagnostic>\n}\n\n/**\n * Kubb code-generation instance bound to a single config entry. Resolves the user\n * config in the constructor, so `config` is available right away, and shares `hooks`,\n * `storage`, and `driver` across the `setup → build` lifecycle.\n *\n * `createKubb` takes a plain config object (the shape `defineConfig` produces),\n * not a fluent builder.\n *\n * Attach hook listeners to `.hooks` before calling `setup()` or `build()`.\n *\n * @example\n * ```ts\n * const kubb = createKubb(userConfig)\n * kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => console.log(plugin.name, duration))\n * const { files, diagnostics } = await kubb.safeBuild()\n * ```\n */\nexport class Kubb {\n readonly hooks: Hookable<KubbHooks>\n readonly config: Config\n #driver: KubbDriver | null = null\n #manifest: OutputManifest | null = null\n readonly #signal: AbortSignal | undefined\n\n constructor(userConfig: UserConfig, options: CreateKubbOptions = {}) {\n this.config = resolveConfig(userConfig)\n this.hooks = options.hooks ?? new Hookable<KubbHooks>()\n this.#signal = options.signal\n }\n\n get storage(): Storage {\n return this.config.storage\n }\n\n get driver(): KubbDriver {\n if (!this.#driver)\n throw new Diagnostics.Error({ code: Diagnostics.code.internalError, severity: 'error', message: '[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 signal = this.#signal\n signal?.throwIfAborted()\n const config = this.config\n const manifest = hasOutputPasses(config) ? await createOutputManifest({ storage: config.storage, cache: cacheStorage({ root: config.root }) }) : undefined\n\n const cleanPath = config.output.clean ? resolve(config.root, config.output.path) : undefined\n\n // clean only removes generated code. Refuse when the output resolves to the project root or\n // an ancestor of it, otherwise the wipe would delete kubb.config and every source file.\n if (cleanPath && isPathInside(config.root, cleanPath)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.cleanRoot,\n severity: 'error',\n message: `output.clean cannot delete \"${cleanPath}\" because it is the project root or a parent of it.`,\n help: 'Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code.',\n location: { kind: 'config' },\n })\n }\n\n // The driver empties `cleanPath` right before it writes the new files, so a run that fails\n // earlier, on an invalid spec or a plugin that throws, leaves the previous output in place.\n const driver = new KubbDriver(config, { hooks: this.hooks, manifest, signal, cleanPath })\n await driver.setup()\n\n this.#driver = driver\n this.#manifest = manifest ?? null\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 AggregateError(errors, `Build failed with ${errors.length} ${errors.length === 1 ? 'error' : '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 this.#signal?.throwIfAborted()\n if (!this.#driver) await this.setup()\n using self = this\n const driver = self.driver\n const storage = self.storage\n const { diagnostics } = await driver.run()\n\n return { diagnostics, files: driver.fileManager.files, driver, storage }\n }\n\n /**\n * Run one build and its output passes end to end, emitting the surrounding `kubb:generation:*`\n * hooks. Never throws on a build error: the outcome comes back in {@link GenerateResult} so the\n * host decides how failures surface. Telemetry and progress narration stay with the host, which\n * reads the result and subscribes to the `kubb:*` hooks.\n *\n * @example\n * ```ts\n * const result = await createKubb(config, { hooks }).generate()\n * if (!result.success) process.exitCode = 1\n * ```\n */\n async generate(options: GenerateOptions = {}): Promise<GenerateResult> {\n const signal = this.#signal\n signal?.throwIfAborted()\n const { hooks, config } = this\n const hrStart = process.hrtime()\n\n await hooks.callHook('kubb:generation:start', { config })\n\n // A setup failure, such as an invalid plugin entry, becomes a diagnostic like any build\n // problem, so reporters still get a failed `kubb:generation:end` for this config.\n let output: Pick<BuildOutput, 'files' | 'diagnostics'>\n try {\n await hooks.callHook('kubb:setup:start')\n await this.setup()\n await hooks.callHook('kubb:setup:end')\n\n output = await this.safeBuild()\n } catch (caughtError) {\n if (signal?.aborted) throw caughtError\n output = { files: [], diagnostics: [Diagnostics.from(caughtError)] }\n }\n const { files, diagnostics } = output\n const storage = this.storage\n signal?.throwIfAborted()\n\n // Surface every problem on the hooks. `performance` diagnostics feed the summary, not the\n // log, so they are skipped.\n for (const diagnostic of diagnostics) {\n if (Diagnostics.isProblem(diagnostic)) await Diagnostics.emit(hooks, diagnostic)\n }\n\n if (Diagnostics.hasError(diagnostics)) {\n await hooks.callHook('kubb:generation:end', { config, storage, diagnostics, filesCreated: files.length, status: 'failed', hrStart })\n return { success: false, files, diagnostics }\n }\n\n const processOutput = options.processOutput ?? runOutputPasses\n const outputDiagnostics = writesOutputDirectory(config.storage)\n ? await processOutput({ config, outputPath: resolve(config.root, config.output.path), hooks, signal })\n : []\n\n const finalDiagnostics = [...diagnostics, ...outputDiagnostics]\n const failed = Diagnostics.hasError(outputDiagnostics)\n\n // The formatter and linter have had their turn, so what sits on disk now is what the next run\n // has to recognize as unchanged. Only record it when they finished: a pass that failed halfway\n // leaves files Kubb has to stay free to regenerate.\n if (!failed) await this.#manifest?.commit()\n\n await hooks.callHook('kubb:generation:end', {\n config,\n storage,\n diagnostics: finalDiagnostics,\n filesCreated: files.length,\n status: failed ? 'failed' : 'success',\n hrStart,\n })\n\n return { success: !failed, files, diagnostics: finalDiagnostics }\n }\n\n dispose(): void {\n this.#driver?.dispose()\n }\n\n [Symbol.dispose](): void {\n this.dispose()\n }\n}\n\n/**\n * Constructs a {@link Kubb} build orchestrator from a user config. Equivalent\n * to `new Kubb(userConfig, options)` and the canonical public entry point.\n *\n * @example\n * ```ts\n * import { createKubb } from '@kubb/core'\n * import { adapterOas } from '@kubb/adapter-oas'\n * import { pluginTs } from '@kubb/plugin-ts'\n *\n * const kubb = createKubb({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * adapter: adapterOas(),\n * plugins: [pluginTs()],\n * })\n *\n * await kubb.build()\n * ```\n */\nexport function createKubb(userConfig: UserConfig, options: CreateKubbOptions = {}): Kubb {\n return new Kubb(userConfig, options)\n}\n","import type { LiteralUnion } from '@internals/utils'\nimport 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 * - `html` writes a browsable report directory to `.kubb/kubb-<name>-<timestamp>/`.\n */\nexport type ReporterName = 'cli' | 'json' | 'file' | 'html'\n\n/**\n * Files attributed to the plugin that first added them.\n */\nexport type ReporterPluginFiles = Array<{\n /** Plugin name. */\n plugin: string\n /** Generated file paths. */\n files: Array<string>\n}>\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 generated files for this config, including unchanged files.\n */\n filesCreated: number\n /**\n * Number of generated files whose content matches the previous output.\n */\n filesUnchanged?: number\n /**\n * Changes compared with the output before this run, when the host collected them.\n * Line totals include added and deleted files.\n */\n fileChanges?: {\n added: number\n modified: number\n deleted: number\n linesAdded: number\n linesRemoved: number\n }\n /**\n * The result previews generation without writing output.\n */\n dryRun?: boolean\n status: 'success' | 'failed'\n /**\n * `process.hrtime()` snapshot taken when this config started generating.\n */\n hrStart: [number, number]\n /**\n * Files attributed to the plugin that first added them, when requested by a reporter.\n */\n pluginFiles?: ReporterPluginFiles\n}\n\n/**\n * Render settings passed alongside the {@link GenerationResult}. These are not part of the run\n * data, such as the output verbosity.\n */\nexport type ReporterContext = {\n /**\n * Output verbosity. Use the `logLevel` constants exported from `@kubb/core`\n * (`silent`, `error`, `warn`, `info`, `verbose`).\n */\n logLevel: (typeof logLevel)[keyof typeof logLevel]\n}\n\n/**\n * Host-facing reporter, as installed onto a run. Unlike a Logger (the live TUI view), a reporter\n * never sees the hook emitter. `report` runs once per config. `drain`, when present, runs once\n * after the last config.\n */\nexport type Reporter = {\n /**\n * Display name, matching a {@link ReporterName} for the built-ins.\n */\n name: LiteralUnion<ReporterName>\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 * Runs once after the run's last config, on `kubb:lifecycle:end`. Only a reporter that collects\n * its configs' reports into one document, such as `json`, has one.\n */\n drain?: (context: ReporterContext) => void | Promise<void>\n /**\n * Whether the host should collect files from `kubb:plugin:end` hooks.\n */\n needsPluginFiles?: boolean\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: LiteralUnion<ReporterName>\n /**\n * Whether the host should collect files from `kubb:plugin:end` hooks.\n */\n needsPluginFiles?: boolean\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. The returned reporter buffers each value `report` returns in order and, when\n * the definition has a `drain`, hands the array to `drain` once and then clears it. Wiring the\n * reporter onto the run's hooks is the host's job, so the reporter only ever deals with a\n * {@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 { name, needsPluginFiles, drain } = reporter\n if (!drain) {\n return {\n name,\n needsPluginFiles,\n async report(result, context) {\n await reporter.report(result, context)\n },\n }\n }\n\n const reports: Array<T> = []\n return {\n name,\n needsPluginFiles,\n async report(result, context) {\n reports.push(await reporter.report(result, context))\n },\n async drain(context) {\n await drain(context, reports.splice(0))\n },\n }\n}\n","import { resolve } from 'node:path'\nimport { getElapsedMs } from '@internals/utils'\nimport type { GenerationResult } from '../createReporter.ts'\nimport { Diagnostics } from '../Diagnostics.ts'\nimport type { SerializedDiagnostic } from '../formatDiagnostic.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 * Generated files whose content matches the previous output.\n */\n filesUnchanged: number\n fileChanges?: GenerationResult['fileChanges']\n dryRun?: boolean\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, filesUnchanged = 0, 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 // A failed run without timings stopped before any plugin ran, such as on an invalid plugin entry.\n plugins: { passed: status === 'failed' && timings.length === 0 ? 0 : total - failed.length, failed, total },\n counts,\n filesCreated,\n filesUnchanged,\n fileChanges: result.fileChanges,\n dryRun: result.dryRun,\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 { isAbsolute, relative } from 'node:path'\nimport { styleText } from 'node:util'\nimport { formatMs } from '@internals/utils'\nimport type { Report } from './report.ts'\n\n/**\n * Writes the summary through the host's output, or plain console lines by default.\n */\nexport type SummaryRenderer = (lines: ReadonlyArray<string>, meta: { title: string; status: 'success' | 'failed' }) => void\n\n/**\n * Puts the outcome first, followed by file counts, labeled plugin results, and the output path.\n * Hosts that collect file changes get a compact diff section. Verbose output adds plugin timings.\n */\nexport function formatSummary(report: Report, { showTimings }: { showTimings: boolean }): Array<string> {\n const { status, plugins, counts, filesCreated, filesUnchanged, fileChanges, dryRun, durationMs, output, timings } = report\n const failed = status === 'failed'\n const successTone = counts.warnings ? 'yellow' : 'green'\n const tone = failed ? 'red' : successTone\n const title = (() => {\n if (failed) return '✗ Generation failed'\n if (dryRun) return '◇ Dry run complete'\n if (counts.warnings) return '✓ Generation complete with warnings'\n if (filesCreated > 0 && filesCreated === filesUnchanged) return '✓ Already up to date'\n return '✓ Generation complete'\n })()\n const separator = styleText('dim', ' · ')\n const generated = Math.max(0, filesCreated - filesUnchanged)\n const fileLabel = `${generated} ${generated === 1 ? 'file' : 'files'} ${dryRun ? 'planned' : 'generated'}`\n const lines = [\n `${styleText(tone, title)} ${styleText('dim', formatMs(durationMs))}`,\n '',\n ` ${styleText(generated ? 'bold' : 'dim', fileLabel)}${filesUnchanged ? separator + styleText('dim', `${filesUnchanged} unchanged`) : ''}`,\n ]\n\n const notRun = plugins.total - plugins.passed - plugins.failed.length\n const pluginCounts = [\n plugins.passed > 0 ? styleText('green', `${plugins.passed} passed`) : undefined,\n plugins.failed.length > 0 ? styleText('red', `${plugins.failed.length} failed`) : undefined,\n notRun > 0 ? styleText('dim', `${notRun} not run`) : undefined,\n ].filter(Boolean)\n lines.push(` ${styleText('dim', 'Plugins')} ${pluginCounts.join(separator) || styleText('dim', 'none configured')}`)\n\n if (plugins.failed.length) lines.push(` ${styleText('dim', 'Failed plugins')} ${styleText('red', plugins.failed.join(', '))}`)\n\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 ].filter(Boolean)\n if (issues.length) lines.push(` ${styleText('dim', 'Issues')} ${issues.join(separator)}`)\n\n const destination = relative(process.cwd(), output)\n const displayPath = destination.startsWith('..') || isAbsolute(destination) ? output : `./${destination}`\n lines.push(` ${styleText('dim', failed || dryRun ? 'Target' : 'Output')} ${styleText(failed ? 'dim' : 'cyan', displayPath)}`)\n if (dryRun) lines.push(` ${styleText('dim', 'Nothing was written.')}`)\n\n if (fileChanges) {\n lines.push(\n '',\n styleText('bold', dryRun ? 'Planned file changes' : 'File changes'),\n ` ${styleText(fileChanges.added ? 'green' : 'dim', `${fileChanges.added} added`)}${separator}${styleText(fileChanges.modified ? 'yellow' : 'dim', `${fileChanges.modified} modified`)}${separator}${styleText(fileChanges.deleted ? 'red' : 'dim', `${fileChanges.deleted} deleted`)}`,\n ` ${styleText('dim', 'Lines')} ${styleText(fileChanges.linesAdded ? 'green' : 'dim', `+${fileChanges.linesAdded}`)} ${styleText(fileChanges.linesRemoved ? 'red' : 'dim', `−${fileChanges.linesRemoved}`)}`,\n )\n }\n\n if (showTimings && timings.length > 0) {\n const nameWidth = Math.max(...timings.map((timing) => timing.plugin.length))\n lines.push('', styleText('dim', 'Plugin timings'))\n for (const timing of timings) lines.push(` ${timing.plugin.padEnd(nameWidth)} ${styleText('dim', formatMs(timing.durationMs))}`)\n }\n\n return lines\n}\n","import { styleText } from 'node:util'\nimport { createReporter, logLevel as logLevelMap, type Reporter } from '../createReporter.ts'\nimport { buildReport } from './report.ts'\nimport { formatSummary, type SummaryRenderer } from './summary.ts'\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 */\nconst consoleRenderer: SummaryRenderer = (lines, { title, status }) => {\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 * Builds a `cli` reporter that renders the {@link Report} for each config as it finishes.\n * Suppressed at `silent`. The `verbose` level adds the per-plugin timings.\n *\n * Pass `render` to send the summary through output the host already owns, so it lands inside that\n * host's grouping instead of alongside it. Omit it for the plain `console.log` writer.\n *\n * @example\n * ```ts\n * const reporter = createCliReporter({ render: (lines) => lines.forEach((line) => clack.log.message(line)) })\n * ```\n */\nexport function createCliReporter({ render = consoleRenderer }: { render?: SummaryRenderer } = {}): Reporter {\n return createReporter({\n name: 'cli',\n report(result, { logLevel }) {\n if (logLevel <= logLevelMap.silent) {\n return\n }\n\n const report = buildReport(result)\n\n render(formatSummary(report, { showTimings: logLevel >= logLevelMap.verbose }), { title: report.name, status: report.status })\n },\n })\n}\n\n/**\n * The default `cli` reporter, writing its summary straight to the console. Independent of the live\n * logger view.\n */\nexport const cliReporter = createCliReporter()\n","import { hash } from 'node:crypto'\nimport { chmodSync, mkdirSync } from 'node:fs'\nimport { homedir, tmpdir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport process from 'node:process'\nimport { createStorage as createUnstorage } from 'unstorage'\nimport fsDriver from 'unstorage/drivers/fs'\n\ntype KubbStorageOptions = {\n /**\n * Folder inside the Kubb home, or an absolute path such as `<cwd>/.kubb`.\n */\n base?: string\n}\n\nfunction ensurePrivateDir(dir: string): string {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n chmodSync(dir, 0o700)\n return dir\n}\n\n/**\n * Folder Kubb keeps its own files in, created with mode 0700. `base` resolves inside `KUBB_HOME`\n * (default `~/.kubb`). When that folder is not writable, it falls back to a folder in the OS temp directory.\n *\n * @example\n * `resolveKubbDir('cache') // '/home/me/.kubb/cache'`\n */\nexport function resolveKubbDir(base = ''): string {\n const dir = resolve(process.env.KUBB_HOME ?? join(homedir(), '.kubb'), base)\n try {\n return ensurePrivateDir(dir)\n } catch {\n return ensurePrivateDir(join(tmpdir(), 'kubb', hash('sha256', dir).slice(0, 16)))\n }\n}\n\n/**\n * unstorage on the fs driver, rooted at {@link resolveKubbDir}. The fs driver cannot set a file\n * mode, so the 0700 folder keeps files such as a stored token private.\n *\n * @example\n * ```ts\n * const storage = kubbStorage({ base: 'cache' })\n * await storage.setItem('machine-secret', secret)\n * ```\n */\nexport function kubbStorage({ base }: KubbStorageOptions = {}) {\n return createUnstorage({ driver: fsDriver({ base: resolveKubbDir(base) }) })\n}\n","import { join, relative, resolve } from 'node:path'\nimport process from 'node:process'\nimport { stripVTControlCharacters } from 'node:util'\nimport { createReporter } from '../createReporter.ts'\nimport { type Diagnostic, Diagnostics } from '../Diagnostics.ts'\nimport { kubbStorage, resolveKubbDir } from '../storages/kubbStorage.ts'\nimport { buildReport } from './report.ts'\nimport { formatSummary } from './summary.ts'\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 // The full stack, since a log file is what a bug report attaches.\n const blocks = problems.map((diagnostic) => Diagnostics.format(diagnostic, { verbose: true }).join('\\n'))\n return ['## Problems', '', blocks.join('\\n\\n')]\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 lines the\n * cli reporter prints (timings included), and a `## Problems` section in the miette block format.\n * Selected with `--reporter file` (or `reporters: ['file']`).\n *\n * @note It captures the collected diagnostics once a config finishes, not the live\n * `kubb:info`/`kubb:plugin` hook stream. Color is stripped so the file stays plain text even when\n * the run is attached to a TTY.\n */\nexport const fileReporter = createReporter({\n name: 'file',\n async report(result) {\n const { diagnostics, config } = result\n if (diagnostics.length === 0) {\n return\n }\n\n const report = buildReport(result)\n const header = config.name ? `# ${config.name} — ${new Date().toISOString()}` : `# ${new Date().toISOString()}`\n const summary = ['## Summary', '', ...formatSummary(report, { showTimings: true })]\n const sections = [summary, buildProblemSection(diagnostics)].filter((section) => section.length > 0)\n const content = stripVTControlCharacters([header, ...sections.map((section) => section.join('\\n'))].join('\\n\\n'))\n\n const name = config.name?.replace(/[^a-zA-Z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')\n const baseName = `${['kubb', name, Date.now()].filter(Boolean).join('-')}.log`\n const dir = resolveKubbDir(resolve(process.cwd(), '.kubb'))\n\n await kubbStorage({ base: dir }).setItem(baseName, `${content}\\n`)\n console.error(`Debug log written to ${relative(process.cwd(), join(dir, baseName))}`)\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 { join, relative, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { openInBrowser, read } from '@internals/utils'\nimport { createReporter, type GenerationResult } from '../createReporter.ts'\nimport { kubbStorage, resolveKubbDir } from '../storages/kubbStorage.ts'\nimport { buildReport } from './report.ts'\n\nfunction serializeReport(result: GenerationResult): string {\n const data = JSON.stringify({ generatedAt: new Date().toISOString(), report: buildReport(result), pluginFiles: result.pluginFiles ?? [] })\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/&/g, '\\\\u0026')\n return `globalThis.__KUBB_REPORT__ = ${data}\\n`\n}\n\n/**\n * Writes a static HTML report directory selected with `--reporter html`.\n */\nexport const htmlReporter = createReporter({\n name: 'html',\n needsPluginFiles: true,\n async report(result) {\n const name = result.config.name?.replace(/[^a-zA-Z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')\n const baseName = ['kubb', name, Date.now()].filter(Boolean).join('-')\n const dir = resolveKubbDir(resolve(process.cwd(), '.kubb'))\n const storage = kubbStorage({ base: dir })\n const assets = new URL('./html/', import.meta.url)\n const [html, ui] = await Promise.all([read(fileURLToPath(new URL('index.html', assets))), read(fileURLToPath(new URL('ui.iife.js', assets)))])\n\n await Promise.all([\n storage.setItem(`${baseName}/index.html`, html),\n storage.setItem(`${baseName}/ui.iife.js`, ui),\n storage.setItem(`${baseName}/data.js`, serializeReport(result)),\n ])\n const reportPath = join(dir, baseName, 'index.html')\n console.error(`HTML report written to ${relative(process.cwd(), reportPath)}`)\n openInBrowser(reportPath)\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 { ProblemDiagnostic } from './Diagnostics.ts'\nimport type { RendererFactory } from './createRenderer.ts'\nimport type { KubbHooks } from './types.ts'\nimport type { KubbDriver } from './KubbDriver.ts'\nimport type { ExtensionMeta } from './defineExtension.ts'\nimport type { Plugin, PluginType, PluginName, ResolvePluginOptions } from './definePlugin.ts'\nimport type { NodeCache } from './nodeCache.ts'\nimport type { Config } from './types.ts'\nimport type { Hookable } from './Hookable.ts'\n\n/**\n * Context passed to a generator's `schema`, `operation`, and `operations` methods.\n *\n * The driver sets `adapter` on the context before it runs a generator, so methods can read it\n * without a null check. `ctx.options` carries the per-node options after exclude/include/override\n * filtering for `schema` and `operation`, or the plugin-level options for `operations`.\n */\nexport type GeneratorContext<TOptions extends PluginType = PluginType> = {\n /**\n * Stops cooperative generation work at the next safe checkpoint.\n */\n signal?: AbortSignal\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 PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>> | undefined\n /**\n * Get a plugin by name, throws an error if not found.\n */\n requirePlugin<TName extends PluginName>(name: TName): Plugin<ResolvePluginOptions<TName>>\n /**\n * Get a resolver by plugin name, typed via `Kubb.PluginRegistry` when registered.\n */\n getResolver<TName extends PluginName>(name: TName): ResolvePluginOptions<TName>['resolver']\n /**\n * Add files only if they don't exist.\n */\n addFile: (...file: Array<FileNode>) => Promise<void>\n /**\n * Merge sources into the same output file.\n */\n upsertFile: (...file: Array<FileNode>) => Promise<void>\n /**\n * The build's hook bus. Emit or listen to any `KubbHooks` hook, for example to react to\n * `kubb:build:end` from inside a generator.\n */\n hooks: Hookable<KubbHooks>\n /**\n * The current plugin instance.\n */\n plugin: Plugin<TOptions> & { name: string; meta: ExtensionMeta }\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. Pass `options` to set\n * the `code`, the `help` text, or the source `location`.\n *\n * @example\n * `ctx.warn('Enum has no values', { help: 'Add values to the enum.', location: { kind: 'schema', pointer: '#/components/schemas/Status' } })`\n */\n warn: (message: string, options?: Partial<Pick<ProblemDiagnostic, 'code' | 'help' | 'location'>>) => void\n /**\n * Report an error. Collected as an `error` diagnostic attributed to the current\n * plugin, which fails the build. A `Diagnostics.Error` keeps its own code, help, and location.\n * Pass `options` to set them for a plain message or error.\n */\n error: (error: string | Error, options?: Partial<Pick<ProblemDiagnostic, 'code' | 'help' | 'location'>>) => void\n /**\n * Report an informational message. Collected as an `info` diagnostic attributed to\n * the current plugin. Pass `options` to set the `code`, the `help` text, or the source `location`.\n */\n info: (message: string, options?: Partial<Pick<ProblemDiagnostic, 'code' | 'help' | 'location'>>) => 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 * Cache scoped to the node being generated, shared by every plugin that generates from that\n * same node in the current pass. Use it to compute node-derived work (resolved names, imports,\n * parameters) once and let the other plugins reuse it. For the `operations` batch call, where\n * there is no single node, the cache is a fresh scratch scope for that call.\n */\n cache: NodeCache\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 PluginType = PluginType, 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 * Predicate checked before `schema` or `operation` runs for a node, mirroring `Macro['match']`\n * in `@kubb/ast`. Returning `false` skips the call for that node entirely, with no context work\n * beyond what the driver already builds per node and no render call, instead of the generator\n * itself being invoked and returning early. Omit it to run for every node, the default when\n * unset.\n *\n * Does not gate `operations`, which already runs once per plugin on the full batch rather than\n * per node.\n *\n * @example Only match GET operations\n * ```ts\n * match(node, ctx) {\n * return ast.isHttpOperationNode(node) && node.method.toLowerCase() === 'get'\n * }\n * ```\n */\n match?: (node: SchemaNode | OperationNode, ctx: GeneratorContext<TOptions>) => PossiblePromise<boolean>\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 `PluginType`. 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 PluginType = PluginType, TElement = unknown>(\n generator: Generator<TOptions, TElement>,\n): Generator<TOptions, TElement> {\n return generator\n}\n","import type { FileNode, UserFileNode } from '@kubb/ast'\nimport { defineExtension } from './defineExtension.ts'\nimport type { ExtensionFactory, ExtensionMeta, ExtensionNamed } from './defineExtension.ts'\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, TOptions extends object = object> = ExtensionNamed & {\n /**\n * The options passed to the parser factory.\n */\n options?: TOptions\n /**\n * File extensions this parser handles. The driver registers the parser for each\n * extension in this list. A parser with `undefined` here is not registered, so\n * files of an unclaimed extension fall back to joining their sources verbatim.\n *\n * @example\n * `['.ts', '.js']`\n */\n extNames: Array<FileNode['extname']> | undefined\n /**\n * Serialize the file's AST into source code.\n */\n parse(file: FileNode<TMeta>): string\n /**\n * Turn the content of a `copy` file into a file node that `parse` prints. Omit to copy the file verbatim.\n */\n copy?(file: FileNode<TMeta>, source: string): UserFileNode<TMeta>\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 * Takes the user's options and returns the parser methods.\n */\nexport type ParserBuild<TOptions extends object, TMeta extends object, TNode> = (options: TOptions) => Omit<Parser<TMeta, TNode>, 'name' | 'meta' | 'options'>\n\n/**\n * The object passed to `defineExtension` with `kind: 'parser'`. `build` receives the user's options and returns the parser methods.\n */\nexport type ParserDefinition<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = {\n meta: ExtensionMeta\n build: ParserBuild<TOptions, TMeta, TNode>\n}\n\n/**\n * The function `defineExtension` returns for a parser. Call it with user options to get a `Parser`.\n */\nexport type ParserFactory<TOptions extends object = object, TMeta extends object = object, TNode = unknown> = ExtensionFactory<\n 'parser',\n TOptions,\n Parser<TMeta, TNode, TOptions>\n>\n\n/**\n * Defines a parser from one object and returns a factory that takes the user's options.\n * Register the result in the `parsers` array on `defineConfig`.\n *\n * @deprecated Use `defineExtension` with `kind: 'parser'` instead.\n */\nexport function defineParser<TOptions extends object = object, TMeta extends object = object, TNode = unknown>(\n definition: ParserDefinition<TOptions, TMeta, TNode>,\n): ParserFactory<TOptions, TMeta, TNode> {\n return defineExtension({ kind: 'parser', ...definition })\n}\n","import { createStorage } from '../createStorage.ts'\n\n/**\n * In-memory storage driver. Useful for testing and dry-run scenarios where\n * generated output should be captured without touching the filesystem.\n *\n * All data lives in a `Map` scoped to the storage instance and is discarded\n * when the instance is garbage-collected.\n *\n * @example\n * ```ts\n * import { memoryStorage } from '@kubb/core'\n * import { defineConfig } from 'kubb'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: './src/gen' },\n * storage: memoryStorage(),\n * })\n * ```\n */\nexport const memoryStorage = createStorage(() => {\n const store = new Map<string, string>()\n\n return {\n name: 'memory',\n async readItem(key: string) {\n return store.get(key) ?? null\n },\n async writeItem(key: string, value: string) {\n store.set(key, value)\n },\n async removeItem(key: string) {\n store.delete(key)\n },\n async readKeys(base?: string) {\n const keys = [...store.keys()]\n return base ? keys.filter((k) => k.startsWith(base)) : keys\n },\n async empty(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","import { isValid } from 'verkit'\nimport type { ExtensionKind } from './defineExtension.ts'\n\n/** A value that survives `JSON.stringify` and `JSON.parse` unchanged. */\nexport type JSONValue = string | number | boolean | null | Array<JSONValue> | { [key: string]: JSONValue }\n\n/**\n * One form field Studio renders for an extension. It edits the value at `path` in the options\n * object the user passes to the factory.\n */\nexport type ExtensionManifestOption = {\n /** Stable UI key, unique within the manifest. */\n key: string\n /** Where the value lives, such as `['output', 'path']`. */\n path: Array<string>\n label: string\n description?: string\n type: 'select' | 'boolean' | 'text' | 'number' | 'list'\n /** The extension's runtime default, shown when the option is unset. */\n default?: JSONValue\n /** For `select`. A choice with value `null` leaves the option unset. */\n choices?: Array<{ label?: string; value: JSONValue }>\n /** For `boolean`: the value written for `true`, `true` when unset. */\n trueValue?: JSONValue\n /** For `boolean`: the value written for `false`, `false` when unset. */\n falseValue?: JSONValue\n /** For `list`: template for each entry, where every `\"$item\"` string is replaced by the entry. */\n item?: JSONValue\n /** For `list`: upper-case each entry before writing it. */\n itemCase?: 'upper'\n}\n\n/**\n * The `kubb-extension.json` file an extension package ships at its root. Studio, the kubb.dev\n * registry, and `kubb add` read it.\n */\nexport type ExtensionManifest = {\n $schema?: string\n kind: ExtensionKind\n /** Equals the extension's `meta.name`. */\n name: string\n /** The factory export users call in `kubb.config.ts`, such as `pluginZod`. */\n export: string\n displayName: string\n description: string\n category?: string\n icon?: { light: string; dark?: string }\n /** HTTPS image or video URLs. */\n media?: Array<string>\n tags?: Array<string>\n docs?: string\n /** People who maintain the extension, shown on its kubb.dev page. */\n maintainers?: Array<{ name: string; github?: string }>\n /** Names of the extensions that must be in the same config, such as `['plugin-ts']`. */\n dependencies?: Array<string>\n /** Names of the extensions used when they are in the config, or needed only for some option values, such as `['plugin-faker']`. */\n optionalDependencies?: Array<string>\n compatibility?: { kubb?: string; node?: string }\n /** Plugins only: `client` ships the HTTP client runtime, `consumer` calls one but ships none. */\n role?: 'client' | 'consumer'\n options?: Array<ExtensionManifestOption>\n}\n\n/** What `kubb add` installs: a reviewed npm version, or a GitHub release tag and the commit it points to. */\nexport type RegistryArtifact =\n | { kind: 'npm'; package: string; version: string }\n | {\n kind: 'github'\n /** The `name` in the root `package.json`, so the package installs under this name. */\n package: string\n /** The release version, equal to `tag` without a leading `v`. */\n version: string\n owner: string\n repo: string\n tag: string\n /** The full commit SHA the tag points to. */\n commit: string\n }\n\n/** One extension in a registry's `index.json`. */\nexport type RegistryEntry = {\n /** `<owner>/<slug>`, such as `kubb-labs/plugin-zod`. */\n id: string\n kind: ExtensionKind\n type: 'official' | 'community'\n artifact: RegistryArtifact\n repository?: { url: string }\n manifest: ExtensionManifest\n stats?: { downloads?: number; weekly?: number; stars?: number }\n submittedAt: string\n publishedAt: string\n reviewedAt: string\n}\n\n/** The registry's `index.json`. */\nexport type RegistryIndex = { version: 1; generatedAt: string; extensions: Array<RegistryEntry> }\n\n/** One `docs/guides/<id>.md`: `id` is the file name, `title` its `#` heading, `description` the first paragraph. */\nexport type RegistryGuide = {\n id: string\n title: string\n description: string\n content: string\n}\n\n/** The registry's `<owner>/<slug>.json`: an entry plus the Markdown docs its pinned version ships. */\nexport type RegistryDetail = RegistryEntry & { overview: string | null; options?: string | null; guides?: Array<RegistryGuide> }\n\nconst EXTENSION_KINDS = new Set<unknown>(['plugin', 'adapter', 'parser'] satisfies Array<ExtensionKind>)\nconst OPTION_TYPES = new Set<unknown>(['select', 'boolean', 'text', 'number', 'list'] satisfies Array<ExtensionManifestOption['type']>)\nconst PACKAGE_NAME = /^(?:@[a-z0-9~][a-z0-9._~-]*\\/)?[a-z0-9~][a-z0-9._~-]*$/\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/\nconst REGISTRY_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*\\/[a-z0-9]+(?:-[a-z0-9]+)*$/\nconst GITHUB_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/\nconst GITHUB_REPO = /^(?!\\.\\.?$)[A-Za-z0-9._-]{1,100}$/\nconst COMMIT = /^[0-9a-f]{40}$/\n/** Option path segments that would reach an object's prototype when Studio writes the value by path. */\nconst UNSAFE_KEYS = new Set<unknown>(['__proto__', 'constructor', 'prototype'])\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)\nconst isOptionalString = (value: unknown) => value === undefined || typeof value === 'string'\nconst isFilledString = (value: unknown) => typeof value === 'string' && value !== ''\nconst matches = (pattern: RegExp, value: unknown) => typeof value === 'string' && pattern.test(value)\n/** Serializes with sorted object keys, so equal JSON values give equal strings whatever their key order. */\nconst canonicalJSON = (value: unknown) =>\n JSON.stringify(value, (_key, item: unknown) =>\n isObject(item)\n ? Object.fromEntries(\n Object.keys(item)\n .sort()\n .map((key) => [key, item[key]]),\n )\n : item,\n )\n\n/**\n * Whether `name` is a valid npm package name, such as `@kubb/plugin-ts`. Rejects paths, URLs,\n * `node:` specifiers, and names that start with `-`, so the result is safe to pass to `import()` or\n * a package manager.\n */\nexport function isPackageName(name: unknown): name is string {\n return typeof name === 'string' && name.length <= 214 && PACKAGE_NAME.test(name)\n}\n\nfunction isMaintainer(value: unknown): boolean {\n return (\n isObject(value) &&\n Object.keys(value).every((key) => key === 'name' || key === 'github') &&\n isFilledString(value.name) &&\n (value.github === undefined || isFilledString(value.github))\n )\n}\n\n/** Checks the shape of one manifest option, including that its path cannot reach a prototype. */\nfunction isOption(value: unknown): value is ExtensionManifestOption {\n if (!isObject(value)) return false\n const { key, path, label, description, type, choices, itemCase } = value\n return (\n isFilledString(key) &&\n Array.isArray(path) &&\n path.length > 0 &&\n path.every((segment) => isFilledString(segment) && !UNSAFE_KEYS.has(segment)) &&\n isFilledString(label) &&\n isOptionalString(description) &&\n OPTION_TYPES.has(type) &&\n (choices === undefined || (Array.isArray(choices) && choices.every((choice) => isObject(choice) && 'value' in choice && isOptionalString(choice.label)))) &&\n (itemCase === undefined || itemCase === 'upper')\n )\n}\n\n/**\n * What is wrong with the options of a well-formed manifest, beyond their shape: keys are unique, a\n * select has choices, and a select's default is one of its choice values. Empty when they pass.\n */\nexport function manifestProblems({ options = [] }: ExtensionManifest): Array<string> {\n const seen = new Set<string>()\n return options.flatMap((option) => {\n const problems = seen.has(option.key) ? [`option \"${option.key}\" is declared more than once`] : []\n seen.add(option.key)\n if (option.type !== 'select') return problems\n if (!option.choices?.length) return [...problems, `option \"${option.key}\" is a select without choices`]\n const knownDefault = !('default' in option) || option.choices.some((choice) => canonicalJSON(choice.value) === canonicalJSON(option.default))\n return knownDefault ? problems : [...problems, `option \"${option.key}\" has a default that is not one of its choices`]\n })\n}\n\n/**\n * Checks a parsed `kubb-extension.json` or a registry response before Kubb or Studio uses it: the\n * fields Kubb reads, every option's shape (including option paths that cannot reach a prototype),\n * and `manifestProblems`. A malformed manifest is skipped instead of trusted.\n */\nexport function isExtensionManifest(value: unknown): value is ExtensionManifest {\n if (!isObject(value)) return false\n const { kind, name, export: exportName, displayName, description, maintainers, dependencies, optionalDependencies, compatibility, role, options } = value\n return (\n EXTENSION_KINDS.has(kind) &&\n isPackageName(name) &&\n typeof exportName === 'string' &&\n IDENTIFIER.test(exportName) &&\n typeof displayName === 'string' &&\n typeof description === 'string' &&\n (maintainers === undefined || (Array.isArray(maintainers) && maintainers.every(isMaintainer))) &&\n (dependencies === undefined || (Array.isArray(dependencies) && dependencies.every(isPackageName))) &&\n (optionalDependencies === undefined || (Array.isArray(optionalDependencies) && optionalDependencies.every(isPackageName))) &&\n (compatibility === undefined ||\n (isObject(compatibility) && Object.entries(compatibility).every(([key, range]) => (key === 'kubb' || key === 'node') && typeof range === 'string'))) &&\n (role === undefined || role === 'client' || role === 'consumer') &&\n (options === undefined || (Array.isArray(options) && options.every(isOption))) &&\n manifestProblems(value as ExtensionManifest).length === 0\n )\n}\n\n/** Checks that no artifact field can reach a package manager as a flag or path, and that a GitHub tag names the version. */\nfunction isRegistryArtifact(value: unknown): value is RegistryArtifact {\n if (!isObject(value) || !isPackageName(value.package) || typeof value.version !== 'string' || !isValid(value.version)) return false\n if (value.kind === 'npm') return true\n return (\n value.kind === 'github' &&\n matches(GITHUB_OWNER, value.owner) &&\n matches(GITHUB_REPO, value.repo) &&\n (value.tag === value.version || value.tag === `v${value.version}`) &&\n matches(COMMIT, value.commit)\n )\n}\n\n/**\n * Checks one entry of a registry's `index.json` or `<owner>/<slug>.json`: a full `<owner>/<slug>` id,\n * an npm or GitHub artifact pinned to a valid version, and a valid manifest of the entry's kind.\n */\nexport function isRegistryEntry(value: unknown): value is RegistryEntry {\n if (!isObject(value)) return false\n const { id, kind, type, artifact, manifest } = value\n return (\n typeof id === 'string' &&\n REGISTRY_ID.test(id) &&\n EXTENSION_KINDS.has(kind) &&\n (type === 'official' || type === 'community') &&\n isRegistryArtifact(artifact) &&\n isExtensionManifest(manifest) &&\n manifest.kind === kind\n )\n}\n","import { existsSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { type ExtensionManifest, isExtensionManifest, isPackageName } from './manifest.ts'\n\nexport type InstalledPackage = { package: string; version?: string; manifest?: ExtensionManifest }\n\n/** Reads and parses a JSON file. Throws when it is missing or not JSON. */\nconst readJSON = async (file: string): Promise<unknown> => JSON.parse(await readFile(file, 'utf8'))\n\n/**\n * The `dependencies` and `devDependencies` of the project at `root`, plus `packages`, with the\n * installed version and the valid `kubb-extension.json` each one ships, when it does. A package\n * also counts as installed when it resolves from one of the `resolveFrom` packages, such as `kubb`\n * for the extensions it ships with.\n */\nexport async function readInstalledPackages({\n root,\n packages = [],\n resolveFrom = [],\n}: {\n root: string\n packages?: Iterable<string>\n resolveFrom?: Array<string>\n}): Promise<Array<InstalledPackage>> {\n const project = createRequire(path.resolve(root, 'package.json'))\n const requires = [\n project,\n ...resolveFrom.flatMap((name) => {\n try {\n return [createRequire(project.resolve(`${name}/package.json`))]\n } catch {\n return []\n }\n }),\n ]\n const packageJSON = (await readJSON(path.join(root, 'package.json')).catch(() => null)) as { dependencies?: unknown; devDependencies?: unknown } | null\n const dependencies = [packageJSON?.dependencies, packageJSON?.devDependencies].flatMap((record) =>\n typeof record === 'object' && record !== null ? Object.keys(record) : [],\n )\n\n return Promise.all(\n [...new Set([...dependencies, ...packages])].filter(isPackageName).map(async (name): Promise<InstalledPackage> => {\n // Found on disk rather than resolved, because an `exports` map may hide `package.json` and the manifest.\n const dir = requires\n .flatMap((require) => require.resolve.paths(name) ?? [])\n .map((dir) => path.join(dir, name))\n .find((dir) => existsSync(path.join(dir, 'package.json')))\n if (!dir) return { package: name }\n try {\n const { version } = (await readJSON(path.join(dir, 'package.json'))) as { version?: unknown }\n const manifest = await readJSON(path.join(dir, 'kubb-extension.json')).catch(() => undefined)\n return { package: name, version: typeof version === 'string' ? version : undefined, manifest: isExtensionManifest(manifest) ? manifest : undefined }\n } catch {\n return { package: name }\n }\n }),\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACkBA,SAAS,gBAAgB,MAAc,QAAyB;CAC9D,OAAO,KACJ,KAAK,CAAC,CACN,QAAQ,qBAAqB,OAAO,CAAC,CACrC,QAAQ,yBAAyB,OAAO,CAAC,CACzC,QAAQ,gBAAgB,OAAO,CAAC,CAChC,MAAM,eAAe,CAAC,CACtB,OAAO,OAAO,CAAC,CACf,KAAK,MAAM,MAAM;EAChB,IAAI,KAAK,SAAS,KAAK,SAAS,KAAK,YAAY,GAAG,OAAO;EAE3D,QADa,MAAM,KAAK,CAAC,SAAS,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,K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AO;EACP,OAAO;EACP,KAAK;CACP;CACA,cAAc;EACZ,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,eAAe;EACb,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,YAAY;EACV,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,WAAW;EACT,MAAM;EACN,OAAO;EACP,OACE;EACF,KAAK;CACP;CACA,mBAAmB;EACjB,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,YAAY;EACV,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,iBAAiB;EACf,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,eAAe;EACb,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,WAAW;EACT,MAAM;EACN,OAAO;EACP,OACE;EACF,KAAK;CACP;CACA,sBAAsB;EACpB,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,oBAAoB;EAClB,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,cAAc;EACZ,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,YAAY;EACV,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,uBAAuB;EACrB,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,eAAe;EACb,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,aAAa;EACX,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;CACA,iBAAiB;EACf,MAAM;EACN,OAAO;EACP,OAAO;EACP,KAAK;CACP;AACF;;;;;AAMA,MAAa,iBAAiB,OAAO,YAAY,OAAO,QAAQ,iBAAiB,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,YAAY,CAAC,KAAK,IAAI,CAAC,CAAC;;;;ACxNxH,SAAS,QAAQ,SAAgD;CAC/D,IAAI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