@kubb/adapter-oas 5.0.5 → 5.1.0

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":["ast","access","readFile","Diagnostics","parse","bundle","upgrade","parse","path","Diagnostics","Diagnostics","ast","ast","extractRefName","macroDiscriminatorEnum","extractRefName","ast","mergeAdjacentObjectsLazy","macroSimplifyUnion","ast","ast","macroEnumName","childName","enumPropName","macroDiscriminatorEnum","Diagnostics","ast","ast","resolveRefName","Diagnostics","createAdapter","narrowSchema","findCircularSchemasFromGraph","ast"],"sources":["../src/constants.ts","../src/emit/discriminator/propagate.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/errors.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/fs.ts","../src/load/source.ts","../src/load/normalize.ts","../src/oas.ts","../src/model/components.ts","../src/model/server.ts","../src/operation.ts","../src/emit/schemaShape.ts","../src/emit/createNode.ts","../src/emit/discriminator/preserve.ts","../src/emit/converters/composition.ts","../src/emit/converters/scalar.ts","../src/emit/converters/structural.ts","../src/emit/parseSchema.ts","../src/refs.ts","../src/model/operations.ts","../src/parser.ts","../src/promoteEnums.ts","../src/schemaDiagnostics.ts","../src/adapter.ts"],"sourcesContent":["import type { ast } from '@kubb/ast'\n\n/**\n * Default parser options applied when no explicit options are provided.\n */\nexport const DEFAULT_PARSER_OPTIONS = {\n dateType: 'string',\n integerType: 'bigint',\n unknownType: 'unknown',\n emptySchemaType: 'unknown',\n enumSuffix: 'enum',\n} as const satisfies ast.ParserOptions\n\n/**\n * JSON-Pointer prefix for schemas declared under `components.schemas` in an OpenAPI document.\n *\n * Used when building or parsing `$ref` strings.\n *\n * @example\n * ```ts\n * `${SCHEMA_REF_PREFIX}Pet` // '#/components/schemas/Pet'\n * ```\n */\nexport const SCHEMA_REF_PREFIX = '#/components/schemas/' as const\n\n/**\n * HTTP methods that count as operations on an OpenAPI path item. Other keys\n * (`parameters`, `summary`, `$ref`, vendor extensions) are skipped when iterating operations.\n */\nexport const SUPPORTED_METHODS: ReadonlySet<string> = new Set(['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'])\n\n/**\n * Set of JSON Schema keywords that prevent a schema fragment from being inlined during `allOf` flattening.\n *\n * A fragment that contains any of these keys carries structural meaning of its own and must stay as a separate\n * intersection member rather than being merged into the parent.\n */\nexport const structuralKeys = new Set(['properties', 'items', 'additionalProperties', 'oneOf', 'anyOf', 'allOf', 'not'] as const)\n\n/**\n * Formats `convertFormat` maps to a dedicated type without going through `formatMap`:\n * `int64`, `uint64` and the date/time family. Keep this in sync with the `convertFormat`\n * special-cases in `parser.ts`. `isHandledFormat` reads it so the\n * `KUBB_UNSUPPORTED_FORMAT` diagnostic and the parser agree on what is handled.\n */\nexport const specialCasedFormats: ReadonlySet<string> = new Set(['int64', 'uint64', 'date-time', 'date', 'time'])\n\n/**\n * Formats that describe a number, whether they resolve through `formatMap` or through the\n * `convertFormat` special cases. On a `type: 'string'` schema these do not make the value a\n * number: gRPC-gateway and other ProtoJSON producers send 64-bit integers as JSON strings.\n *\n * @see https://protobuf.dev/programming-guides/json/#int64-strings\n */\nexport const numericFormats: ReadonlySet<string> = new Set(['int32', 'int64', 'uint64', 'float', 'double'])\n\n/**\n * Static map from OAS `format` strings to Kubb `SchemaType` values.\n *\n * Only formats whose AST type differs from the OAS `type` field appear here.\n * Formats that depend on runtime options (`int64`, `date-time`, `date`, `time`) are handled\n * separately in the parser. `ipv4` and `ipv6` map to their own dedicated schema types. `hostname`\n * and `idn-hostname` map to `'url'` as the closest generic string-format type.\n */\nexport const formatMap = {\n uuid: 'uuid',\n email: 'email',\n 'idn-email': 'email',\n uri: 'url',\n 'uri-reference': 'url',\n url: 'url',\n ipv4: 'ipv4',\n ipv6: 'ipv6',\n hostname: 'url',\n 'idn-hostname': 'url',\n binary: 'blob',\n byte: 'blob',\n // Numeric formats override the OAS `type` because format is more specific.\n // See https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.7\n int32: 'integer',\n float: 'number',\n double: 'number',\n} as const satisfies Record<string, ast.SchemaType>\n\n/**\n * Vendor extension keys that attach human-readable labels to enum values, checked in priority order.\n */\nexport const enumExtensionKeys = ['x-enumNames', 'x-enum-varnames'] as const\n\n/**\n * Vendor extension keys that attach human-readable descriptions to enum values, checked in priority order.\n */\nexport const enumDescriptionKeys = ['x-enumDescriptions', 'x-enum-descriptions'] as const\n","import { ast, type SchemaNodeByType } from '@kubb/ast'\n\nexport type DiscriminatorTarget = {\n propertyName: string\n enumValues: Array<string | number | boolean>\n}\n\n/**\n * Maps each child schema name to its discriminator patch data by scanning the given\n * top-level AST schema nodes for union schemas that carry a `discriminatorPropertyName`.\n *\n * Called on a small pre-parsed subset of schemas (only the discriminator parents)\n * rather than on all schemas at once.\n */\nexport function buildDiscriminatorChildMap(schemas: Array<ast.SchemaNode>): Map<string, DiscriminatorTarget> {\n const childMap = new Map<string, DiscriminatorTarget>()\n\n for (const schema of schemas) {\n // Case 1: top-level schema is a union (oneOf/anyOf with discriminator)\n // Case 2: top-level schema is an intersection wrapping a union (oneOf/anyOf + shared properties)\n let unionNode = ast.narrowSchema(schema, 'union')\n\n if (!unionNode) {\n const intersectionMembers = ast.narrowSchema(schema, 'intersection')?.members\n if (intersectionMembers) {\n for (const m of intersectionMembers) {\n const u = ast.narrowSchema(m, 'union')\n if (u) {\n unionNode = u\n break\n }\n }\n }\n }\n\n if (!unionNode?.discriminatorPropertyName || !unionNode.members) continue\n\n const { discriminatorPropertyName, members } = unionNode\n\n for (const member of members) {\n // Members with a discriminant value are intersections: [RefSchemaNode, ObjectSchemaNode]\n const intersectionNode = ast.narrowSchema(member, 'intersection')\n if (!intersectionNode?.members) continue\n\n let refNode: SchemaNodeByType['ref'] | null = null\n let objNode: SchemaNodeByType['object'] | null = null\n\n for (const m of intersectionNode.members) {\n refNode ??= ast.narrowSchema(m, 'ref')\n objNode ??= ast.narrowSchema(m, 'object')\n }\n\n if (!refNode?.name || !objNode) continue\n\n const prop = objNode.properties.find((p) => p.name === discriminatorPropertyName)\n const enumNode = prop ? ast.narrowSchema(prop.schema, 'enum') : null\n if (!enumNode?.enumValues?.length) continue\n\n const enumValues = enumNode.enumValues.filter((v): v is string | number | boolean => v !== null)\n if (!enumValues.length) continue\n\n const existing = childMap.get(refNode.name)\n if (!existing) {\n childMap.set(refNode.name, { propertyName: discriminatorPropertyName, enumValues: [...new Set(enumValues)] })\n continue\n }\n existing.enumValues = [...new Set([...existing.enumValues, ...enumValues])]\n }\n }\n\n return childMap\n}\n\n/**\n * Patches a single top-level `SchemaNode` with its discriminator entry (adds or replaces\n * the discriminant property).\n *\n * A child declared with `allOf` parses to an intersection rather than an object, so the\n * discriminant is intersected on as an extra member instead.\n */\nexport function patchDiscriminatorNode(node: ast.SchemaNode, entry: { propertyName: string; enumValues: Array<string | number | boolean> }): ast.SchemaNode {\n const { propertyName, enumValues } = entry\n const enumSchema = ast.factory.createSchema({ type: 'enum', enumValues })\n const newProp = ast.factory.createProperty({ name: propertyName, required: true, schema: enumSchema })\n\n const objectNode = ast.narrowSchema(node, 'object')\n if (objectNode) {\n const existingIdx = objectNode.properties.findIndex((p) => p.name === propertyName)\n const newProperties = existingIdx >= 0 ? objectNode.properties.map((p, i) => (i === existingIdx ? newProp : p)) : [...objectNode.properties, newProp]\n\n return { ...objectNode, properties: newProperties }\n }\n\n const intersectionNode = ast.narrowSchema(node, 'intersection')\n if (!intersectionNode?.members) return node\n\n const discriminantNode = ast.factory.createSchema({ type: 'object', primitive: 'object', properties: [newProp] })\n const patchedIdx = intersectionNode.members.findIndex((member) => ast.narrowSchema(member, 'object')?.properties.some((p) => p.name === propertyName))\n\n const newMembers =\n patchedIdx >= 0\n ? intersectionNode.members.map((member, i) => (i === patchedIdx ? patchDiscriminatorNode(member, entry) : member))\n : [...intersectionNode.members, discriminantNode]\n\n return { ...intersectionNode, members: newMembers }\n}\n","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 * Thrown when one or more errors occur during a Kubb build.\n * Carries the full list of underlying errors on `errors`.\n *\n * @example\n * ```ts\n * throw new BuildError('Build failed', { errors: [err1, err2] })\n * ```\n */\nexport class BuildError extends Error {\n errors: Array<Error>\n\n constructor(message: string, options: { cause?: Error; errors: Array<Error> }) {\n super(message, { cause: options.cause })\n this.name = 'BuildError'\n this.errors = options.errors\n }\n}\n\n/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new BuildError('Build failed', { cause: toError(err), errors: [] })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Extracts the `.cause` of an `Error` as an `Error`, or `undefined` when absent or not an `Error`.\n *\n * @example\n * ```ts\n * const cause = toCause(buildError) // Error | undefined\n * ```\n */\nexport function toCause(error: Error): Error | undefined {\n return error.cause instanceof Error ? error.cause : undefined\n}\n","/**\n * Name of the JavaScript runtime executing the current process.\n */\ntype RuntimeName = 'bun' | 'deno' | 'node'\n\n/**\n * Detects the JavaScript runtime executing the current process and exposes its name and version.\n *\n * Prefer the shared {@link runtime} instance over constructing your own.\n */\nclass Runtime {\n /**\n * `true` when the current process is running under Bun.\n *\n * Detection keys off the global `Bun` object rather than `process.versions`,\n * because Bun polyfills `process.versions.node` for Node compatibility and would\n * otherwise look like Node.\n *\n * @example\n * ```ts\n * if (runtime.isBun) {\n * await Bun.write(path, data)\n * }\n * ```\n */\n get isBun(): boolean {\n return typeof Bun !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Deno.\n */\n get isDeno(): boolean {\n return typeof (globalThis as { Deno?: unknown }).Deno !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Node.\n *\n * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.\n */\n get isNode(): boolean {\n return !this.isBun && !this.isDeno && typeof process !== 'undefined' && process.versions?.node != null\n }\n\n /**\n * Name of the runtime executing the current process.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\n get name(): RuntimeName {\n if (this.isBun) return 'bun'\n if (this.isDeno) return 'deno'\n\n return 'node'\n }\n\n /**\n * Version of the active runtime, or an empty string when it cannot be read.\n *\n * @example\n * ```ts\n * runtime.version // '1.3.11' under Bun, '22.22.2' under Node\n * ```\n */\n get version(): string {\n if (this.isBun) return process.versions.bun ?? ''\n if (this.isDeno) return (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? ''\n\n return process.versions?.node ?? ''\n }\n}\n\n/**\n * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.\n */\nexport const runtime = new Runtime()\n","import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { camelCase } from './casing.ts'\nimport { runtime } from './runtime.ts'\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 if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\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 * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\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 destructive operations: before wiping an output directory, check that it does not contain\n * the project root, otherwise a `clean` would delete `kubb.config` and every source file.\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) return true\n\n const rel = relative(resolvedParent, resolvedPath)\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\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 * 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 earlier segment, applies `caseLast` to the final 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 *\n * @example PascalCase the final segment\n * `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`\n *\n * @example Suffix applied to the final segment only\n * `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`\n */\nexport function toFilePath(name: string, caseLast: (part: string) => string = camelCase): string {\n const parts = name.split(/\\.(?=[a-zA-Z])/)\n return parts\n .map((part, i) => (i === parts.length - 1 ? caseLast(part) : camelCase(part)))\n .filter(Boolean)\n .join('/')\n}\n","import { exists, getErrorMessage, read } from '@internals/utils'\nimport { Diagnostics } from '@kubb/core'\nimport { parse } from 'yaml'\n\nconst urlRegExp = /^https?:\\/+/i\n\n/**\n * Node reports every connection failure as `TypeError: fetch failed` and keeps the useful part\n * (`connect ECONNREFUSED 127.0.0.1:8000`) on `cause`, one level deeper again when a host resolves\n * to several addresses and the attempts collect into an `AggregateError`.\n */\nfunction describeFetchFailure(error: unknown): string {\n if (error instanceof AggregateError && error.errors.length > 0) {\n return describeFetchFailure(error.errors[0])\n }\n if (error instanceof Error && error.cause instanceof Error) {\n return describeFetchFailure(error.cause) || error.message\n }\n\n return getErrorMessage(error)\n}\n\nfunction helpForStatus(status: number): string {\n if (status === 401 || status === 403) {\n return 'The server refused the request. Kubb sends no credentials, so serve the document without authentication or download it and set `input` to the local file.'\n }\n if (status === 404) {\n return 'Check the URL. Open it in a browser or with `curl` to confirm it serves the OpenAPI document.'\n }\n if (status >= 500) {\n return 'The server failed while serving the document. Check that it is healthy, then run Kubb again.'\n }\n\n return 'Open the URL in a browser or with `curl` to see what the server returns, then point `input` at a URL that serves the OpenAPI document.'\n}\n\nasync function fetchSource(url: URL): Promise<Response> {\n try {\n return await fetch(url)\n } catch (error) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputUnreachable,\n severity: 'error',\n message: `Cannot reach ${url.href}: ${describeFetchFailure(error)}`,\n help: '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 location: { kind: 'config' },\n cause: error instanceof Error ? error : undefined,\n })\n }\n}\n\nasync function readSource(sourcePath: string): Promise<string> {\n if (urlRegExp.test(sourcePath)) {\n // api-ref-bundler joins relative refs with posix normalization, collapsing `https://` to\n // `https:/`. The WHATWG URL parser restores the double slash.\n const url = new URL(sourcePath)\n const response = await fetchSource(url)\n\n if (!response.ok) {\n const status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status)\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputRequestFailed,\n severity: 'error',\n message: `The server at ${url.href} answered with HTTP ${status} instead of the OpenAPI document.`,\n help: helpForStatus(response.status),\n location: { kind: 'config' },\n })\n }\n\n return response.text()\n }\n\n return read(sourcePath)\n}\n\n/**\n * Reads and parses one source file or URL referenced during bundling: YAML/JSON is parsed into an\n * object, Markdown is returned as-is (bundled inline rather than dereferenced).\n *\n * JSON is valid YAML, so `yaml`'s `parse` handles both, but its general-purpose parser (comments,\n * anchors, block scalars, multi-document streams) does much more work than `JSON.parse` needs to.\n * `JSON.parse` runs first and fails fast on the first non-JSON character, so a real YAML document\n * falls through to `parse` at negligible cost.\n */\nexport async function resolveSource(sourcePath: string): Promise<object | string> {\n const data = await readSource(sourcePath)\n\n if (sourcePath.toLowerCase().endsWith('.md')) {\n return data\n }\n\n try {\n return JSON.parse(data) as object\n } catch {\n return parse(data) as object\n }\n}\n\n/**\n * Throws a coded `KUBB_INPUT_NOT_FOUND` diagnostic when a local input path does not exist.\n * URLs are skipped: a remote input reports `KUBB_INPUT_REQUEST_FAILED` or `KUBB_INPUT_UNREACHABLE`\n * from the request itself. A malformed but readable file is left for `parseDocument` to surface\n * its parse error instead.\n */\nexport async function assertInputExists(input: string): Promise<void> {\n if (URL.canParse(input)) {\n return\n }\n if (!(await exists(input))) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputNotFound,\n severity: 'error',\n message: `Cannot read the file set as \\`input\\` (or via \\`kubb generate PATH\\`): ${input}`,\n help: 'Check that the path exists and is readable, then set it as `input` or pass it as `kubb generate PATH`.',\n location: { kind: 'config' },\n })\n }\n}\n\nexport { urlRegExp }\n","import path from 'node:path'\nimport { Diagnostics } from '@kubb/core'\nimport type { AdapterSource } from '@kubb/core'\nimport { upgrade } from '@scalar/openapi-upgrader'\nimport { bundle } from 'api-ref-bundler'\nimport { parse } from 'yaml'\nimport type { Document } from '../types.ts'\nimport { assertInputExists, resolveSource, urlRegExp } from './source.ts'\n\n/**\n * True when `node` contains a `$ref` pointing outside the current document (a relative path,\n * absolute path, or URL). An internal `#/...` fragment does not count.\n *\n * `Object.values` reads array elements and object property values alike, so the same recursion\n * walks both without a separate array branch.\n */\nexport function hasExternalRef(node: unknown): boolean {\n if (!node || typeof node !== 'object') {\n return false\n }\n\n const ref = (node as { $ref?: unknown }).$ref\n if (typeof ref === 'string' && !ref.startsWith('#')) {\n return true\n }\n\n return Object.values(node).some(hasExternalRef)\n}\n\n/**\n * Bundles a multi-file OpenAPI document into a single document via `api-ref-bundler`.\n *\n * External file schemas are hoisted into named `components.schemas` entries, so a property\n * pointing at `./schemas/User.yaml` ends up referencing `#/components/schemas/User`. Generators\n * can then emit a named type with an import instead of inlining the shape. Sources are read with\n * the Bun-aware `read` util for local YAML and JSON files, and with `fetch` for HTTP(S) URLs.\n *\n * A document with no `$ref` outside itself has nothing to bundle, so it skips `api-ref-bundler`\n * and returns as parsed. `bundle` only rewrites external refs into internal ones; on an\n * all-internal document it is a no-op that still walks the whole tree to confirm that, which\n * costs real time on a large spec.\n *\n * @example Local file\n * `const document = await bundleDocument('./openapi.yaml')`\n *\n * @example Remote URL\n * `const document = await bundleDocument('https://example.com/openapi.yaml')`\n */\nexport async function bundleDocument(pathOrUrl: string): Promise<Document> {\n const cache = new Map<string, Promise<object | string>>()\n\n const resolver = (sourcePath: string) => {\n // api-ref-bundler refers to the same URL as both `https://` and the posix-normalized\n // `https:/`, so cache on the canonical href to fetch each source once.\n const key = urlRegExp.test(sourcePath) ? new URL(sourcePath).href : sourcePath\n const cached = cache.get(key)\n if (cached) {\n return cached\n }\n\n const result = resolveSource(sourcePath)\n cache.set(key, result)\n return result\n }\n\n // api-ref-bundler swallows resolver errors and leaves refs unresolved, so surface an\n // unreadable input document as a hard error before bundling.\n const root = await resolver(pathOrUrl)\n\n if (typeof root === 'object' && root !== null && !hasExternalRef(root)) {\n return root as Document\n }\n\n return (await bundle(pathOrUrl, resolver)) as Document\n}\n\n/**\n * Loads and bundles an OpenAPI document, returning the raw `Document`.\n *\n * A string is a file path or URL: it is bundled via `api-ref-bundler`, hoisting external file\n * schemas into named `components.schemas` entries so generators can emit named types and imports.\n * An object is treated as an already-parsed document. Swagger 2.0 and OpenAPI 3.0 documents are\n * up-converted to OpenAPI 3.1 via `@scalar/openapi-upgrader`.\n *\n * @example\n * ```ts\n * const document = await parseDocument('./openapi.yaml')\n * const document = await parseDocument(rawDocumentObject)\n * ```\n */\nexport async function parseDocument(pathOrApi: string | Document): Promise<Document> {\n if (typeof pathOrApi === 'string') {\n const bundled = await bundleDocument(pathOrApi)\n\n return parseDocument(bundled)\n }\n\n // `upgrade` chains Swagger 2.0 -> 3.0 -> 3.1, leaving documents already on 3.1 untouched.\n return upgrade(pathOrApi, '3.1') as Document\n}\n\n/**\n * Creates a `Document` from an `AdapterSource`.\n *\n * - `{ type: 'path' }` resolves and bundles a local file path or remote URL.\n * - `{ type: 'data' }` parses an inline string (YAML/JSON) or raw object.\n *\n * @example\n * ```ts\n * const document = await parseFromConfig({ type: 'path', path: './openapi.yaml' })\n * const document = await parseFromConfig({ type: 'data', data: '{\"openapi\":\"3.0.0\",...}' })\n * ```\n */\nexport async function parseFromConfig(source: AdapterSource): Promise<Document> {\n if (source.type === 'data') {\n // Inline data is a parsed object or a raw YAML/JSON string. Parse the string here so\n // `parseDocument` never mistakes inline content for a file path. `parse` also handles JSON.\n const data = typeof source.data === 'string' ? parse(source.data) : structuredClone(source.data)\n return parseDocument(data as Document)\n }\n\n // type === 'path'\n if (URL.canParse(source.path)) {\n return parseDocument(source.path)\n }\n\n const resolved = path.resolve(path.dirname(source.path), source.path)\n await assertInputExists(resolved)\n return parseDocument(resolved)\n}\n\n/**\n * Asserts the parsed input is an OpenAPI or Swagger document.\n *\n * {@link validateDocument} keeps spec violations non-fatal so imperfect but usable documents still\n * generate. That leniency also swallowed input that is not a document at all, which then produced\n * an empty build with a success exit code. A missing version field is the one failure that cannot\n * be a usable document, so it is fatal regardless of the `validate` option.\n */\nexport function assertDocument(document: Document): void {\n if (document && ('openapi' in document || 'swagger' in document)) return\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidDocument,\n severity: 'error',\n message: 'The resolved `input` is not an OpenAPI or Swagger document: it declares no `openapi` or `swagger` version.',\n help: 'Point `input` at a document that declares `openapi` or `swagger`. If you pass an object, pass the spec itself rather than a wrapper such as `{ path }` or `{ data }`.',\n location: { kind: 'config' },\n })\n}\n\n/**\n * Validates an OpenAPI document using `@readme/openapi-parser` with colorized error output.\n *\n * @example\n * ```ts\n * await validateDocument(document)\n * ```\n */\nexport async function validateDocument(document: Document, { throwOnError = false }: { throwOnError?: boolean } = {}): Promise<void> {\n // The heaviest dependency in the package, and every config importing `@kubb/adapter-oas` would\n // pay for it even with `validate` off.\n const { compileErrors, validate } = await import('@readme/openapi-parser')\n\n try {\n // `validate` dereferences its input in place, so clone to keep the cached document intact.\n const result = await validate(structuredClone(document), {\n validate: {\n errors: { colorize: true },\n },\n })\n\n if (!result.valid) {\n throw new Error(compileErrors(result))\n }\n } catch (error) {\n if (throwOnError) {\n throw error\n }\n\n // Validation failures are non-fatal, mirror plugin-oas behavior\n }\n}\n","import type { DiscriminatorObject, ReferenceObject, SchemaObject } from './types.ts'\n\n/**\n * Returns `true` when a schema should be treated as nullable.\n *\n * Recognizes all nullable signals across OAS versions: `nullable: true` (OAS 3.0),\n * `x-nullable: true` (vendor extension), `type: 'null'`, and `type: ['null', ...]` (OAS 3.1).\n */\nexport function isNullable(schema?: SchemaObject & { 'x-nullable'?: boolean }): boolean {\n const explicitNullable = schema?.nullable ?? schema?.['x-nullable']\n if (explicitNullable === true) return true\n\n const schemaType = schema?.type\n if (schemaType === 'null') return true\n if (Array.isArray(schemaType)) return schemaType.includes('null')\n\n return false\n}\n\n/**\n * Returns `true` when `obj` is an OpenAPI `$ref` pointer object.\n */\nexport function isReference(obj?: unknown): obj is ReferenceObject {\n return !!obj && typeof obj === 'object' && '$ref' in obj\n}\n\n/**\n * Returns `true` when `obj` is a schema with a structured OAS 3.x `discriminator` object,\n * excluding the Swagger 2 string form.\n */\nexport function isDiscriminator(obj?: unknown): obj is SchemaObject & { discriminator: DiscriminatorObject } {\n const record = obj as Record<string, unknown>\n return !!obj && !!record['discriminator'] && typeof record['discriminator'] !== 'string'\n}\n\n/**\n * Returns `true` when a schema is a binary payload: an octet-stream string body.\n */\nexport function isBinary(schema: SchemaObject): boolean {\n return schema.type === 'string' && schema.contentMediaType === 'application/octet-stream'\n}\n\n/**\n * MIME type fragments that mark a media type as JSON-like.\n *\n * A content type is JSON when it contains any of these substrings. The `+json` entry catches\n * structured-syntax suffixes such as `application/vnd.api+json`.\n */\nconst jsonMimeFragments = ['application/json', 'application/x-json', 'text/json', 'text/x-json', '+json'] as const\n\n/**\n * Returns `true` when a media type string is JSON-like.\n *\n * @example\n * ```ts\n * isJsonMimeType('application/json') // true\n * isJsonMimeType('application/vnd.api+json') // true\n * isJsonMimeType('multipart/form-data') // false\n * ```\n */\nexport function isJsonMimeType(mimeType: string): boolean {\n return jsonMimeFragments.some((fragment) => mimeType.includes(fragment))\n}\n\n/**\n * Picks a media-type entry from a `content` map: the first JSON-like media type, falling back to\n * the first declared one. Returns `false` when `content` has no entries.\n *\n * @example\n * ```ts\n * pickContentEntry({ 'application/xml': xmlEntry, 'application/json': jsonEntry })\n * // ['application/json', jsonEntry]\n * ```\n */\nexport function pickContentEntry<T>(content: Record<string, T>): [string, T] | false {\n const mediaTypes = Object.keys(content)\n const available = mediaTypes.find(isJsonMimeType) ?? mediaTypes[0]\n return available ? [available, content[available]!] : false\n}\n","import { pascalCase } from '@internals/utils'\nimport { SCHEMA_REF_PREFIX } from '../constants.ts'\nimport { isReference } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport type { ContentType, ContentTypeOptions, Document, SchemaObject } from '../types.ts'\n\n/**\n * The three component sections Kubb reads schemas from.\n */\ntype SchemaSourceMode = 'schemas' | 'responses' | 'requestBodies'\n\n/**\n * A schema annotated with its component section source and original name. `getSchemas` uses this\n * to resolve name collisions across sources.\n */\ntype SchemaWithMetadata = {\n schema: SchemaObject\n source: SchemaSourceMode\n originalName: string\n}\n\nexport type GetSchemasResult = {\n schemas: Record<string, SchemaObject>\n /**\n * Maps a renamed component pointer (`#/components/<source>/<name>`) to the\n * collision-resolved unique name used as the key in `schemas`. Components that keep\n * their original name are not recorded, so the map stays empty for documents\n * without collisions.\n */\n renames: Map<string, string>\n}\n\n/**\n * Extracts the inline schema from a media-type `content` map.\n *\n * Prefers `preferredContentType` when given, otherwise uses the first key in the map.\n * Returns `null` when `content` is absent, the schema is missing, or the schema is a `$ref`.\n *\n * @example\n * ```ts\n * extractSchemaFromContent(operation.content, 'application/json')\n * // SchemaObject | null\n * ```\n */\nexport function extractSchemaFromContent(content: Record<string, unknown> | undefined, preferredContentType?: ContentType): SchemaObject | null {\n if (!content) return null\n\n const firstContentType = Object.keys(content)[0] ?? 'application/json'\n const targetContentType = preferredContentType ?? firstContentType\n const contentSchema = content[targetContentType] as { schema?: SchemaObject } | undefined\n const schema = contentSchema?.schema\n\n if (isReference(schema)) return null\n return schema ?? null\n}\n\n/**\n * Walks a schema tree and collects the names of all `#/components/schemas/<name>` `$ref`s.\n */\nfunction* collectRefs(schema: unknown): Generator<string, void, undefined> {\n if (Array.isArray(schema)) {\n for (const item of schema) yield* collectRefs(item)\n return\n }\n\n if (schema && typeof schema === 'object') {\n for (const key in schema) {\n const value = (schema as Record<string, unknown>)[key]\n if (!(key === '$ref' && typeof value === 'string')) {\n yield* collectRefs(value)\n continue\n }\n if (value.startsWith(SCHEMA_REF_PREFIX)) {\n const name = value.slice(SCHEMA_REF_PREFIX.length)\n if (name) yield name\n }\n }\n }\n}\n\n/**\n * Returns a copy of `schemas` topologically sorted by `$ref` dependency.\n *\n * Referenced schemas appear before the schemas that depend on them, so code generators\n * can emit types in the correct order. Cycles are silently skipped.\n *\n * @example\n * ```ts\n * const sorted = sortSchemas({ Order: orderSchema, Pet: petSchema })\n * // Pet appears before Order when Order.$ref points at Pet\n * ```\n */\nexport function sortSchemas(schemas: Record<string, SchemaObject>): Record<string, SchemaObject> {\n const deps = new Map<string, Array<string>>()\n\n for (const [name, schema] of Object.entries(schemas)) {\n deps.set(name, [...new Set(collectRefs(schema))])\n }\n\n const sorted: Array<string> = []\n const visited = new Set<string>()\n\n function visit(name: string, stack: Set<string>) {\n if (visited.has(name) || stack.has(name)) return\n stack.add(name)\n for (const child of deps.get(name) ?? []) {\n if (deps.has(child)) visit(child, stack)\n }\n stack.delete(name)\n visited.add(name)\n sorted.push(name)\n }\n\n for (const name of Object.keys(schemas)) {\n visit(name, new Set())\n }\n\n const result: Record<string, SchemaObject> = {}\n for (const name of sorted) result[name] = schemas[name]!\n return result\n}\n\nconst semanticSuffixes: Record<SchemaSourceMode, string> = {\n schemas: 'Schema',\n responses: 'Response',\n requestBodies: 'Request',\n}\n\n/**\n * Picks the collision suffix for one name-colliding schema: none when the name is unique,\n * a semantic suffix (`Schema`, `Response`, `Request`) when the collision spans sources, otherwise\n * a numeric suffix (`2`, `3`, …) for same-source collisions.\n */\nfunction collisionSuffix({\n isSingle,\n hasMultipleSources,\n source,\n index,\n}: {\n isSingle: boolean\n hasMultipleSources: boolean\n source: SchemaSourceMode\n index: number\n}): string {\n if (isSingle) return ''\n if (hasMultipleSources) return semanticSuffixes[source]\n if (index === 0) return ''\n return String(index + 1)\n}\n\n/**\n * Collects component schemas from one or more sources and resolves name collisions.\n *\n * Sources default to `['schemas', 'requestBodies', 'responses']`. Returned schemas are\n * topologically sorted by `$ref` dependency so generators emit types in the correct order.\n *\n * When two or more schemas normalize to the same PascalCase name:\n * - Same source → numeric suffix (`2`, `3`, …).\n * - Different sources → semantic suffix (`Schema`, `Response`, `Request`).\n *\n * @example\n * ```ts\n * const { schemas, renames } = getSchemas(document, { contentType: 'application/json' }, refs)\n * ```\n */\nexport function getSchemas(document: Document, { contentType }: ContentTypeOptions, refs: Refs): GetSchemasResult {\n const components = document.components\n\n function resolveSchemaRef(schema: SchemaObject): SchemaObject {\n if (!isReference(schema)) return schema\n const resolved = refs.resolve<SchemaObject>(schema.$ref)\n return resolved && !isReference(resolved) ? resolved : schema\n }\n\n const candidates: Array<SchemaWithMetadata> = [\n ...Object.entries((components?.schemas as Record<string, SchemaObject>) ?? {}).map(([name, schema]) => ({\n schema: resolveSchemaRef(schema),\n source: 'schemas' as const,\n originalName: name,\n })),\n ...(['responses', 'requestBodies'] as const).flatMap((source) =>\n Object.entries(components?.[source] ?? {}).flatMap(([name, item]) => {\n const schema = extractSchemaFromContent((item as { content?: Record<string, unknown> }).content, contentType)\n return schema\n ? [\n {\n schema: resolveSchemaRef(schema),\n source,\n originalName: name,\n },\n ]\n : []\n }),\n ),\n ]\n\n const normalizedNames = new Map<string, Array<SchemaWithMetadata>>()\n for (const item of candidates) {\n const key = pascalCase(item.originalName)\n const bucket = normalizedNames.get(key) ?? []\n bucket.push(item)\n normalizedNames.set(key, bucket)\n }\n\n const schemas: Record<string, SchemaObject> = {}\n const renames = new Map<string, string>()\n\n for (const [, items] of normalizedNames) {\n const isSingle = items.length === 1\n const hasMultipleSources = !isSingle && new Set(items.map((item) => item.source)).size > 1\n\n items.forEach((item, index) => {\n const suffix = collisionSuffix({ isSingle, hasMultipleSources, source: item.source, index })\n const uniqueName = item.originalName + suffix\n schemas[uniqueName] = item.schema\n if (suffix) renames.set(`#/components/${item.source}/${item.originalName}`, uniqueName)\n })\n }\n\n return { schemas: sortSchemas(schemas), renames }\n}\n","import { Diagnostics } from '@kubb/core'\nimport type { Document, ServerObject, ServerOptions } from '../types.ts'\n\n/**\n * Reads the server URL from the document's `servers` array at `server.index`,\n * interpolating any `server.variables` into the URL template.\n *\n * Returns `null` when `server.index` is omitted or out of range.\n *\n * @example Resolve the first server\n * `resolveBaseUrl({ document, server: { index: 0 } })`\n *\n * @example Override a path variable\n * `resolveBaseUrl({ document, server: { index: 0, variables: { version: 'v2' } } })`\n */\nexport function resolveBaseUrl({ document, server }: { document: Document; server?: ServerOptions }): string | null {\n const index = server?.index\n const entry = index !== undefined ? document.servers?.at(index) : undefined\n\n return entry?.url ? resolveServerUrl(entry, server?.variables) : null\n}\n\n/**\n * Replaces `{variable}` placeholders in an OpenAPI server URL with provided values.\n * Resolution order: `overrides[key]` → `variable.default` → left unreplaced.\n * Throws if an override value is not in the variable's `enum` list.\n *\n * @example\n * ```ts\n * resolveServerUrl(\n * { url: 'https://{env}.api.example.com', variables: { env: { default: 'dev', enum: ['dev', 'prod'] } } },\n * { env: 'prod' },\n * )\n * // 'https://prod.api.example.com'\n * ```\n */\nexport function resolveServerUrl(server: ServerObject, overrides?: Record<string, string>): string {\n if (!server.variables) {\n return server.url\n }\n\n let url = server.url\n for (const [key, variable] of Object.entries(server.variables)) {\n const value = overrides?.[key] ?? (variable.default != null ? String(variable.default) : undefined)\n if (value === undefined) {\n continue\n }\n\n if (variable.enum?.length && !variable.enum.some((e) => String(e) === value)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidServerVariable,\n severity: 'error',\n message: `Invalid server variable value '${value}' for '${key}' when resolving ${server.url}. Valid values are: ${variable.enum.join(', ')}.`,\n help: `Use one of the allowed enum values, or drop the enum on the '${key}' server variable.`,\n location: { kind: 'document', pointer: '#/servers' },\n })\n }\n\n url = url.replaceAll(`{${key}}`, value)\n }\n\n return url\n}\n","import { SUPPORTED_METHODS } from './constants.ts'\nimport { isJsonMimeType, isReference, pickContentEntry } from './oas.ts'\nimport type { Refs } from './refs.ts'\nimport type { Document, MediaTypeObject, OperationObject, PathItemObject, ReferenceObject, RequestBodyObject, ResponseObject } from './types.ts'\n\n/**\n * A single OpenAPI operation: its URL path, HTTP method, and the raw operation object.\n *\n * `schema` is a live reference into the document. Unlike earlier versions of this adapter, nothing\n * resolves a `$ref` in place here anymore — every accessor below resolves through `refs` instead.\n * `pathItem` is the already-resolved path item this operation was read from, so a caller that\n * also needs path-level data (parameters, summary, description) doesn't re-resolve it.\n */\nexport type Operation = {\n path: string\n method: string\n schema: OperationObject\n pathItem: PathItemObject\n}\n\n/**\n * The operation being read plus the `$ref` service to resolve against.\n */\ntype OperationContext = {\n operation: Operation\n refs: Refs\n}\n\n/**\n * Slugifies a path for the `operationId` fallback: non-alphanumerics collapse to single dashes,\n * with no leading or trailing dash.\n */\nfunction slugify(value: string): string {\n return value\n .replace(/[^a-zA-Z0-9]/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^-|-$/g, '')\n}\n\n/**\n * Returns the operation's `operationId`, falling back to `<method>_<slugified-path>` when absent.\n */\nexport function getOperationId({ path, method, schema }: Operation): string {\n const { operationId } = schema\n if (typeof operationId === 'string' && operationId.length > 0) {\n return operationId\n }\n\n return `${method}_${slugify(path).toLowerCase()}`\n}\n\n/**\n * Returns the declared response status codes, skipping `x-` extensions and non-object entries.\n */\nexport function getResponseStatusCodes({ schema }: Operation): Array<string> {\n const responses = schema.responses as Record<string, unknown> | undefined\n if (!responses || isReference(responses)) {\n return []\n }\n\n return Object.keys(responses).filter((key) => !key.startsWith('x-') && !!responses[key] && typeof responses[key] === 'object')\n}\n\n/**\n * Returns the response object for a status code, resolving a `$ref` through `refs`. `false` when absent.\n */\nexport function getResponseByStatusCode({ operation, refs, statusCode }: OperationContext & { statusCode: string | number }): ResponseObject | false {\n const responses = operation.schema.responses as Record<string, ResponseObject | ReferenceObject> | undefined\n if (!responses || isReference(responses)) {\n return false\n }\n\n return refs.deref<ResponseObject>(responses[statusCode]) ?? false\n}\n\n/**\n * Resolves the operation's request body, dereferencing a `$ref` through `refs`. Returns `null`\n * when the operation has no request body or it cannot be resolved.\n */\nexport function getRequestBody({ operation, refs }: OperationContext): RequestBodyObject | null {\n return refs.deref<RequestBodyObject>(operation.schema.requestBody)\n}\n\n/**\n * Resolves the request body (a `$ref` through `refs`) and returns its content map, or\n * `undefined` when the operation has no request body.\n */\nfunction getRequestBodyContent({ operation, refs }: OperationContext): Record<string, MediaTypeObject> | undefined {\n return getRequestBody({ operation, refs })?.content\n}\n\n/**\n * Returns the request body media type. With `mediaType` set, returns that entry or `false`.\n * Otherwise picks the first JSON-like media type, then the first declared one, as a\n * `[mediaType, object]` tuple.\n */\nexport function getRequestContent({\n operation,\n refs,\n mediaType,\n}: OperationContext & { mediaType?: string }): MediaTypeObject | false | [string, MediaTypeObject] {\n const content = getRequestBodyContent({ operation, refs })\n\n if (!content) {\n return false\n }\n\n if (mediaType) {\n return mediaType in content ? content[mediaType]! : false\n }\n\n return pickContentEntry(content)\n}\n\n/**\n * Returns the primary request content type. Prefers a JSON-like media type (the last one wins\n * when several are declared), then the first declared one, defaulting to `'application/json'`.\n */\nexport function getRequestContentType({ operation, refs }: OperationContext): string {\n const content = getRequestBodyContent({ operation, refs })\n const mediaTypes = content ? Object.keys(content) : []\n\n let result = mediaTypes[0] ?? 'application/json'\n for (const mt of mediaTypes) {\n if (isJsonMimeType(mt)) {\n result = mt\n }\n }\n\n return result\n}\n\n/**\n * Builds an `Operation` for every supported HTTP method on every path, in document order.\n * `x-` path keys and unresolvable path-item `$ref`s are skipped.\n *\n * @example\n * ```ts\n * for (const operation of getOperations(document, refs)) {\n * parseOperation(options, operation)\n * }\n * ```\n */\nexport function getOperations(document: Document, refs: Refs): Array<Operation> {\n const operations: Array<Operation> = []\n const paths = document.paths\n if (!paths) {\n return operations\n }\n\n for (const path of Object.keys(paths)) {\n if (path.startsWith('x-')) {\n continue\n }\n\n const pathItem = refs.deref<PathItemObject>(paths[path])\n if (!pathItem) {\n continue\n }\n\n const item = pathItem as unknown as Record<string, unknown>\n for (const method of Object.keys(item)) {\n if (!SUPPORTED_METHODS.has(method)) {\n continue\n }\n const schema = item[method]\n if (!schema || typeof schema !== 'object') {\n continue\n }\n operations.push({ path, method, schema: schema as OperationObject, pathItem })\n }\n }\n\n return operations\n}\n","import type { ast } from '@kubb/ast'\nimport { formatMap, specialCasedFormats, structuralKeys } from '../constants.ts'\nimport { isReference } from '../oas.ts'\nimport type { SchemaObject } from '../types.ts'\n\n/**\n * Returns the Kubb `SchemaType` for a given OAS `format` string, or `null` if not found.\n * Formats not in `formatMap` (e.g., `int64`, `uint64`, `date-time`) are handled separately by parser options.\n */\nexport function getSchemaType(format: string): ast.SchemaType | null {\n return formatMap[format as keyof typeof formatMap] ?? null\n}\n\n/**\n * Whether the parser maps `format` to a dedicated type. True for any `formatMap` entry, plus the\n * `specialCasedFormats` that `convertFormat` handles directly (int64, uint64, date-time, date, time). False means the format falls back to\n * the base type, which is what `KUBB_UNSUPPORTED_FORMAT` flags. Reading both sources keeps the\n * diagnostic in step with the parser as `formatMap` grows.\n */\nexport function isHandledFormat(format: string): boolean {\n return getSchemaType(format) !== null || specialCasedFormats.has(format)\n}\n\n/**\n * Converts an OAS primitive type string to its `PrimitiveSchemaType` equivalent.\n * Numeric types (`number`, `integer`, `bigint`) pass through unchanged. `boolean` maps to `'boolean'`. Everything else becomes `'string'`.\n */\nexport function getPrimitiveType(type: string | undefined): ast.PrimitiveSchemaType {\n if (type === 'number' || type === 'integer' || type === 'bigint') return type\n if (type === 'boolean') return 'boolean'\n\n return 'string'\n}\n\n/**\n * Resolves the AST type descriptor for a date/time format, honoring the `dateType` option.\n * Returns `null` when `dateType: false`, so the format falls through to `string`.\n */\nexport function getDateType(\n options: ast.ParserOptions,\n format: 'date-time' | 'date' | 'time',\n): { type: 'datetime'; offset?: boolean; local?: boolean } | { type: 'date' | 'time'; representation: 'date' | 'string' } | null {\n if (!options.dateType) {\n return null\n }\n\n if (format === 'date-time') {\n if (options.dateType === 'date') {\n return { type: 'date', representation: 'date' }\n }\n if (options.dateType === 'stringOffset') {\n return { type: 'datetime', offset: true }\n }\n if (options.dateType === 'stringLocal') {\n return { type: 'datetime', local: true }\n }\n return { type: 'datetime', offset: false }\n }\n\n if (format === 'date') {\n return {\n type: 'date',\n representation: options.dateType === 'date' ? 'date' : 'string',\n }\n }\n\n // time\n return {\n type: 'time',\n representation: options.dateType === 'date' ? 'date' : 'string',\n }\n}\n\n/**\n * Reads a schema's numeric `exclusiveMinimum`/`exclusiveMaximum` bounds (the OAS 3.1 numeric\n * form). Either key is `undefined` when absent or, for the legacy OAS 3.0 boolean form, not a\n * number.\n */\nexport function getExclusiveBounds(schema: SchemaObject): { exclusiveMinimum: number | undefined; exclusiveMaximum: number | undefined } {\n return {\n exclusiveMinimum: typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined,\n exclusiveMaximum: typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : undefined,\n }\n}\n\n/**\n * Reads schema examples as an array. OAS 3.1 uses an `examples` array, but specs (including ones\n * labeled 3.1) still use the singular OAS 3.0 `example`, which the upgrader only converts on the\n * 3.0 -> 3.1 hop. Normalize both into one array so the AST node exposes only `examples`.\n */\nexport function extractExamples(schema: SchemaObject): Array<unknown> | undefined {\n if (Array.isArray(schema.examples)) return schema.examples\n return schema.example !== undefined ? [schema.example] : undefined\n}\n\n/**\n * Returns `true` when `fragment` carries any JSON Schema keyword that makes it\n * structurally significant on its own (see `structuralKeys`).\n *\n * A fragment with a structural keyword can't be safely merged into a parent schema.\n */\nfunction hasStructuralKeywords(fragment: SchemaObject): boolean {\n return Object.keys(fragment).some((key) => structuralKeys.has(key as 'properties'))\n}\n\n/**\n * Flattens a keyword-only `allOf` into its parent schema.\n *\n * Only flattens when every member is a plain fragment, with no `$ref` and no structural keywords\n * (see `structuralKeys`). Outer schema values take precedence over fragment values.\n * Returns `null` for a `null` input, and the original schema unchanged when flattening is unsafe.\n *\n * @example\n * ```ts\n * flattenSchema({ allOf: [{ description: 'A pet' }], type: 'object', properties: {} })\n * // { type: 'object', properties: {}, description: 'A pet' }\n * ```\n *\n * @example\n * ```ts\n * flattenSchema({ allOf: [{ $ref: '#/components/schemas/Pet' }] })\n * // returned unchanged, contains a $ref\n * ```\n */\nexport function flattenSchema(schema: SchemaObject | null): SchemaObject | null {\n if (!schema?.allOf || schema.allOf.length === 0) return schema ?? null\n\n const allOfFragments = schema.allOf as Array<SchemaObject>\n if (allOfFragments.some((item) => isReference(item))) return schema\n if (allOfFragments.some(hasStructuralKeywords)) return schema\n\n // Destructure `allOf` out instead of `delete merged.allOf`: a `delete` transitions the freshly\n // spread object into V8 dictionary (slow) mode, and this runs per `allOf` schema during parsing.\n const { allOf: _allOf, ...rest } = schema\n const merged = rest as SchemaObject\n\n for (const fragment of allOfFragments) {\n for (const [key, value] of Object.entries(fragment)) {\n merged[key as keyof SchemaObject] ??= value as SchemaObject[keyof SchemaObject]\n }\n }\n\n return merged\n}\n","import { ast } from '@kubb/ast'\nimport { extractExamples } from './schemaShape.ts'\nimport type { SchemaContext } from './parseSchema.ts'\n\n/**\n * The `schema`/`name`/`nullable`/`defaultValue` slice of a context, the only part\n * {@link createNode} needs to fill in a node's shared base fields.\n */\ntype NodeBaseContext = Pick<SchemaContext, 'schema' | 'name' | 'nullable' | 'defaultValue'>\n\n/**\n * Input shape accepted by `ast.factory.createSchema`, recovered from its own signature so\n * {@link createNode} stays in sync with the AST layer without redeclaring the union.\n */\ntype CreateSchemaProps = Parameters<typeof ast.factory.createSchema>[0]\n\n/**\n * Builds a schema node from a converter's base context plus its type-specific fields. Every\n * converter needs the same metadata fields (`title`, `description`, `examples`, ...) alongside\n * whatever makes its node distinct; this folds both into one call.\n */\nexport function createNode({ schema, name, nullable, defaultValue }: NodeBaseContext, extras: CreateSchemaProps): ast.SchemaNode {\n return ast.factory.createSchema({\n name,\n nullable,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n readOnly: schema.readOnly,\n writeOnly: schema.writeOnly,\n default: defaultValue,\n examples: extractExamples(schema),\n format: schema.format,\n ...extras,\n })\n}\n","import { ast } from '@kubb/ast'\nimport { extractRefName, macroDiscriminatorEnum } from '@kubb/kit'\nimport { SCHEMA_REF_PREFIX } from '../../constants.ts'\nimport { isDiscriminator, isReference } from '../../oas.ts'\nimport type { Refs } from '../../refs.ts'\nimport type { DiscriminatorObject, ReferenceObject, SchemaObject } from '../../types.ts'\nimport type { ParseFn } from '../parseSchema.ts'\n\n/**\n * Creates a single-property object schema used as a discriminator literal.\n *\n * @example\n * ```ts\n * createDiscriminantNode({ propertyName: 'type', values: ['dog'] })\n * // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }\n * ```\n */\nexport function createDiscriminantNode({ propertyName, values }: { propertyName: string; values: Array<string> }): ast.SchemaNode {\n return ast.factory.createSchema({\n type: 'object',\n primitive: 'object',\n properties: [\n ast.factory.createProperty({\n name: propertyName,\n schema: ast.factory.createSchema({\n type: 'enum',\n primitive: 'string',\n enumValues: values,\n }),\n required: true,\n }),\n ],\n })\n}\n\n/**\n * Returns every discriminator key whose mapping value matches `ref`, in mapping order.\n *\n * A mapping may point several keys at the same schema, in which case the member has to be\n * narrowed to all of them — keeping only the first would drop the rest from the union.\n *\n * @example\n * ```ts\n * findDiscriminators({ dog: '#/components/schemas/Dog', hound: '#/components/schemas/Dog' }, '#/components/schemas/Dog') // ['dog', 'hound']\n * ```\n */\nexport function findDiscriminators(mapping: Record<string, string> | undefined, ref: string | undefined): Array<string> {\n if (!mapping || !ref) return []\n return Object.entries(mapping)\n .filter(([, value]) => value === ref)\n .map(([key]) => key)\n}\n\n/**\n * Narrows each `oneOf`/`anyOf` member with its discriminant value, intersecting the member's own\n * node with either the shared-properties slice carrying that value, or a synthetic discriminant\n * literal. The referenced child schema's own definition is left untouched — narrowing happens only\n * at this union usage site, which is what makes this mode \"preserve\" (as opposed to `propagate`,\n * which additionally patches the child schema's own definition in a post-pass).\n */\nexport function narrowUnionMembers({\n unionMembers,\n discriminator,\n sharedPropertiesNode,\n parse,\n rawOptions,\n name,\n refs,\n}: {\n unionMembers: Array<unknown>\n discriminator: DiscriminatorObject | undefined\n sharedPropertiesNode: ast.SchemaNode | undefined\n parse: ParseFn\n rawOptions: Partial<ast.ParserOptions> | undefined\n name: string | null | undefined\n refs: Refs\n}): Array<ast.SchemaNode> {\n function pickDiscriminatorPropertyNode(node: ast.SchemaNode, propertyName: string): ast.SchemaNode | null {\n const objectNode = ast.narrowSchema(node, 'object')\n const discriminatorProperty = objectNode?.properties?.find((property) => property.name === propertyName)\n\n if (!discriminatorProperty) {\n return null\n }\n\n return ast.factory.createSchema({\n type: 'object',\n primitive: 'object',\n properties: [discriminatorProperty],\n })\n }\n\n function implicitDiscriminantValue(member: unknown): string | null {\n if (!discriminator || discriminator.mapping || !isReference(member)) return null\n const value = extractRefName(member.$ref)\n if (!value) return null\n // Silent walk — the reporting resolve() would flag missing refs as errors during speculative lookup.\n const variant = refs.resolve<SchemaObject>(member.$ref, { report: false })\n if (!variant) return null\n\n const propertyName = discriminator.propertyName\n // Intersecting two different literals on the same property collapses it to `never`,\n // so skip folding the implicit name when the variant already pins the discriminator.\n const seen = new Set([member.$ref])\n\n function constrains(v: SchemaObject): boolean {\n const prop = v.properties?.[propertyName]\n const resolved = prop && isReference(prop) ? refs.resolve<SchemaObject>(prop.$ref, { report: false }) : (prop as SchemaObject | undefined)\n if (resolved && (Array.isArray(resolved.enum) || resolved.const !== undefined)) return true\n const composition = v.allOf ?? v.oneOf ?? v.anyOf\n if (!composition) return false\n\n return composition.some((m) => {\n if (!isReference(m)) return constrains(m as SchemaObject)\n if (seen.has(m.$ref)) return false\n seen.add(m.$ref)\n const r = refs.resolve<SchemaObject>(m.$ref, { report: false })\n return r ? constrains(r) : false\n })\n }\n\n return constrains(variant) ? null : value\n }\n\n return unionMembers.map((s) => {\n const ref = isReference(s) ? s.$ref : undefined\n const mappedValues = findDiscriminators(discriminator?.mapping, ref)\n const implicitValue = mappedValues.length ? null : implicitDiscriminantValue(s)\n const discriminatorValues = mappedValues.length ? mappedValues : implicitValue ? [implicitValue] : []\n const memberNode = parse({ schema: s as SchemaObject, name }, rawOptions)\n\n if (!discriminatorValues.length || !discriminator) {\n return memberNode\n }\n\n const narrowedDiscriminatorNode = sharedPropertiesNode\n ? pickDiscriminatorPropertyNode(\n ast.applyMacros(sharedPropertiesNode, [macroDiscriminatorEnum({ propertyName: discriminator.propertyName, values: discriminatorValues })], {\n depth: 'shallow',\n }),\n discriminator.propertyName,\n )\n : undefined\n\n return ast.factory.createSchema({\n type: 'intersection',\n members: [\n memberNode,\n narrowedDiscriminatorNode ??\n createDiscriminantNode({\n propertyName: discriminator.propertyName,\n values: discriminatorValues,\n }),\n ],\n })\n })\n}\n\n/**\n * Filters the discriminated members out of an `allOf` list: an `allOf` member that `$ref`s a\n * discriminated union's parent, where this schema is itself one of that union's children, is\n * dropped from `members` and its discriminant value collected instead — the same synthetic\n * literal `narrowUnionMembers` produces, so the emitted node stays a plain intersection rather\n * than nesting the whole parent union one level deeper.\n */\nexport function extractDiscriminatedAllOfMembers({\n allOfMembers,\n name,\n refs,\n}: {\n allOfMembers: Array<SchemaObject | ReferenceObject>\n name: string | null | undefined\n refs: Refs\n}): {\n members: Array<SchemaObject | ReferenceObject>\n discriminantValues: Array<{ propertyName: string; values: Array<string> }>\n} {\n const discriminantValues: Array<{ propertyName: string; values: Array<string> }> = []\n\n const members = allOfMembers.filter((item) => {\n if (!isReference(item) || !name) return true\n const deref = refs.resolve<SchemaObject>(item.$ref)\n if (!deref || !isDiscriminator(deref)) return true\n const parentUnion = deref.oneOf ?? deref.anyOf\n if (!parentUnion) return true\n const childRef = `${SCHEMA_REF_PREFIX}${name}`\n const inOneOf = parentUnion.some((oneOfItem) => isReference(oneOfItem) && oneOfItem.$ref === childRef)\n const inMapping = Object.values(deref.discriminator.mapping ?? {}).some((v) => v === childRef)\n if (inOneOf || inMapping) {\n const values = findDiscriminators(deref.discriminator.mapping, childRef)\n if (values.length) {\n discriminantValues.push({\n propertyName: deref.discriminator.propertyName,\n values,\n })\n }\n return false\n }\n return true\n })\n\n return { members, discriminantValues }\n}\n","import { ast } from '@kubb/ast'\nimport { extractRefName, macroSimplifyUnion, mergeAdjacentObjectsLazy } from '@kubb/kit'\nimport { isDiscriminator, isReference } from '../../oas.ts'\nimport type { ReferenceObject, SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport { createDiscriminantNode, extractDiscriminatedAllOfMembers, narrowUnionMembers } from '../discriminator/preserve.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\nimport { extractExamples } from '../schemaShape.ts'\n\n/**\n * Converts a `$ref` schema into a `RefSchemaNode`.\n *\n * The resolved schema is stored in `node.schema`. Usage-site sibling fields\n * (description, readOnly, nullable, etc.) are stored directly on the ref node.\n * Use `syncSchemaRef(node)` in printers to get a merged view of both.\n * Circular refs are detected in `refs.resolveNode` and leave `schema` as `null`.\n */\nexport function convertRef({ schema, name, nullable, defaultValue, rawOptions, document, parse, refs, renames }: ConvertContext): ast.SchemaNode {\n const refPath = schema.$ref\n const resolvedSchema = refPath ? refs.resolveNode(refPath, parse, rawOptions) : null\n const ctx = { schema, name, nullable, defaultValue }\n\n // A `$ref` to a component the document never defines (a malformed spec) would otherwise emit an\n // import to a module that is never generated, leaving the output uncompilable. Fall back to\n // `unknown` so the rest of the schema still resolves. Only do this for a document that declares a\n // component registry — a registry-less fragment (e.g. a minimal `parse` call) parses refs\n // leniently, since the target is expected to live outside the fragment.\n if (refPath && document.components && !refs.exists(refPath)) {\n return createNode(ctx, { type: 'unknown' })\n }\n\n const targetName = renames?.get(schema.$ref!)\n\n return createNode(ctx, {\n type: 'ref',\n name: extractRefName(schema.$ref!),\n ref: schema.$ref,\n ...(targetName ? { targetName } : {}),\n schema: resolvedSchema,\n })\n}\n\n/**\n * Converts an `allOf` schema into a flattened node or an `IntersectionSchemaNode`.\n */\nexport function convertAllOf({ schema, name, nullable, defaultValue, rawOptions, parse, refs }: ConvertContext): ast.SchemaNode {\n if (\n schema.allOf!.length === 1 &&\n !schema.properties &&\n !(Array.isArray(schema.required) && schema.required.length) &&\n schema.additionalProperties === undefined\n ) {\n const [memberSchema] = schema.allOf as Array<SchemaObject | ReferenceObject>\n const memberNode = parse({ schema: memberSchema! as SchemaObject, name }, rawOptions)\n const { kind: _kind, ...memberNodeProps } = memberNode\n const mergedNullable = nullable || memberNode.nullable || undefined\n const mergedDefault = schema.default === null && mergedNullable ? undefined : (schema.default ?? memberNode.default)\n\n return ast.factory.createSchema({\n ...memberNodeProps,\n name,\n title: schema.title ?? memberNode.title,\n description: schema.description ?? memberNode.description,\n deprecated: schema.deprecated ?? memberNode.deprecated,\n nullable: mergedNullable,\n readOnly: schema.readOnly ?? memberNode.readOnly,\n writeOnly: schema.writeOnly ?? memberNode.writeOnly,\n default: mergedDefault,\n examples: extractExamples(schema) ?? memberNode.examples,\n pattern: schema.pattern ?? ('pattern' in memberNode ? memberNode.pattern : undefined),\n format: schema.format ?? memberNode.format,\n } as ast.DistributiveOmit<ast.SchemaNode, 'kind'>)\n }\n\n const { members: discriminatedAllOf, discriminantValues } = extractDiscriminatedAllOfMembers({\n allOfMembers: schema.allOf as Array<SchemaObject | ReferenceObject>,\n name,\n refs,\n })\n const allOfMembers: Array<ast.SchemaNode> = discriminatedAllOf.map((s) => parse({ schema: s as SchemaObject, name }, rawOptions))\n\n const syntheticStart = allOfMembers.length\n\n if (Array.isArray(schema.required) && schema.required.length) {\n const outerKeys = schema.properties ? new Set(Object.keys(schema.properties)) : new Set<string>()\n const missingRequired = schema.required.filter((key) => !outerKeys.has(key))\n\n if (missingRequired.length) {\n const resolvedMembers = (schema.allOf as Array<SchemaObject | ReferenceObject>).flatMap((item) => {\n if (!isReference(item)) return [item as SchemaObject]\n const deref = refs.resolve<SchemaObject>(item.$ref)\n return deref && !isReference(deref) ? [deref] : []\n })\n\n for (const key of missingRequired) {\n for (const resolved of resolvedMembers) {\n const prop = resolved.properties?.[key]\n if (prop) {\n const raw = { properties: { [key]: prop }, required: [key] }\n const memberSchema = raw as SchemaObject\n allOfMembers.push(parse({ schema: memberSchema, name }, rawOptions))\n break\n }\n }\n }\n }\n }\n\n if (schema.properties) {\n const { allOf: _allOf, ...schemaWithoutAllOf } = schema\n // Don't pass `name` here, the result must stay anonymous so it can be merged with the\n // adjacent synthetic object in `mergeAdjacentObjectsLazy`. Nested enum qualification\n // happens upstream via `convertObject`'s `setEnumName` propagation.\n allOfMembers.push(parse({ schema: schemaWithoutAllOf }, rawOptions))\n }\n\n for (const { propertyName, values } of discriminantValues) {\n allOfMembers.push(createDiscriminantNode({ propertyName, values }))\n }\n\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'intersection',\n members: [...mergeAdjacentObjectsLazy(allOfMembers.slice(0, syntheticStart)), ...mergeAdjacentObjectsLazy(allOfMembers.slice(syntheticStart))],\n },\n )\n}\n\n/**\n * Converts a `oneOf` / `anyOf` schema into a `UnionSchemaNode`.\n */\nexport function convertUnion({ schema, name, nullable, defaultValue, rawOptions, parse, refs }: ConvertContext): ast.SchemaNode {\n const ctx = { schema, name, nullable, defaultValue }\n const unionMembers = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]\n const strategy: 'one' | 'any' = schema.oneOf ? 'one' : 'any'\n const unionExtras = {\n discriminatorPropertyName: isDiscriminator(schema) ? schema.discriminator.propertyName : undefined,\n strategy,\n }\n const discriminator = isDiscriminator(schema) ? schema.discriminator : undefined\n const { oneOf: _o, anyOf: _a, discriminator: _d, ...memberBaseSchema } = schema\n const sharedPropertiesNode = schema.properties ? parse({ schema: memberBaseSchema as SchemaObject, name }, rawOptions) : undefined\n\n if (sharedPropertiesNode || discriminator) {\n const members = narrowUnionMembers({ unionMembers, discriminator, sharedPropertiesNode, parse, rawOptions, name, refs })\n const unionNode = createNode(ctx, { type: 'union', ...unionExtras, members })\n\n if (!sharedPropertiesNode) {\n return unionNode\n }\n\n return createNode(ctx, { type: 'intersection', members: [unionNode, sharedPropertiesNode] })\n }\n\n const unionNode = createNode(ctx, {\n type: 'union',\n ...unionExtras,\n members: unionMembers.map((s) => parse({ schema: s as SchemaObject, name }, rawOptions)),\n })\n\n return ast.applyMacros(unionNode, [macroSimplifyUnion], { depth: 'shallow' })\n}\n\n/**\n * Converts an OAS 3.1 multi-type array (e.g. `type: ['string', 'number']`) into a `UnionSchemaNode`.\n * Only called once the multi-type rule's `match` has confirmed more than one non-`null` type\n * remains; a single remaining type (e.g. `['string', 'null']`) is handled as that type instead,\n * with nullability already folded in.\n */\nexport function convertMultiType({ schema, name, nullable, defaultValue, rawOptions, parse }: ConvertContext): ast.SchemaNode {\n const types = schema.type as Array<string>\n const nonNullTypes = types.filter((t) => t !== 'null')\n\n const arrayNullable = types.includes('null') || nullable || undefined\n return createNode(\n { schema, name, nullable: arrayNullable, defaultValue },\n {\n type: 'union',\n members: nonNullTypes.map((t) => {\n const raw = { ...schema, type: t }\n const memberSchema = raw as SchemaObject\n return parse({ schema: memberSchema, name }, rawOptions)\n }),\n },\n )\n}\n","import { ast } from '@kubb/ast'\nimport { enumDescriptionKeys, enumExtensionKeys, numericFormats } from '../../constants.ts'\nimport type { SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\nimport { getDateType, getExclusiveBounds, getPrimitiveType, getSchemaType } from '../schemaShape.ts'\n\n/**\n * Normalizes malformed `{ type: 'array', enum: [...] }` schemas by moving enum values into items.\n *\n * This pattern violates the OpenAPI spec but appears in real specs. The fix moves enum values\n * from the array to its items sub-schema, so they are valid for downstream processing.\n *\n * @note A defensive measure for non-compliant specs.\n */\nfunction normalizeArrayEnum(schema: SchemaObject): SchemaObject {\n const isItemsObject = typeof schema.items === 'object' && !Array.isArray(schema.items)\n const normalizedItems: SchemaObject = {\n ...(isItemsObject ? (schema.items as SchemaObject) : {}),\n enum: schema.enum,\n }\n const { enum: _enum, ...schemaWithoutEnum } = schema\n // `SchemaObject` is a discriminated union; the spread can't be verified against every member\n // structurally, so the merge result is asserted rather than annotated.\n const merged = { ...schemaWithoutEnum, items: normalizedItems }\n\n return merged as SchemaObject\n}\n\n/**\n * Builds a `null` scalar node carrying the schema's documentation. Shared by the `const: null`\n * and the drf-spectacular `NullEnum` (`{ enum: [null] }`) branches, which render identically.\n */\nexport function createNullNode(schema: SchemaObject, name: string | null | undefined, nullable?: true): ast.SchemaNode {\n return ast.factory.createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n nullable,\n format: schema.format,\n })\n}\n\n/**\n * Converts an OAS 3.1 `const` schema into a null scalar or a single-value `EnumSchemaNode`.\n */\nexport function convertConst({ schema, name, nullable, defaultValue }: ConvertContext): ast.SchemaNode {\n const constValue = schema.const\n\n if (constValue === null) {\n return createNullNode(schema, name)\n }\n\n const constPrimitive = getPrimitiveType(typeof constValue === 'number' ? 'number' : typeof constValue === 'boolean' ? 'boolean' : 'string')\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'enum',\n primitive: constPrimitive,\n enumValues: [constValue as string | number | boolean],\n },\n )\n}\n\n/**\n * Converts a format-annotated schema into a special-type `SchemaNode`. Only called once the\n * `format` rule's `match` has confirmed the format is handled (see `isHandledFormat`) and, for\n * a date-ish format, that `dateType` is not `false`.\n */\nexport function convertFormat(context: ConvertContext): ast.SchemaNode {\n const { schema, name, nullable, defaultValue, options, type } = context\n const ctx = { schema, name, nullable, defaultValue }\n\n // A numeric format on a `type: 'string'` schema describes how the number is spelled, not that\n // the value is a number, so the declared type wins. The format stays on the node for plugins\n // that want to validate the digits.\n if (type === 'string' && numericFormats.has(schema.format!)) {\n return convertString(context)\n }\n\n if (schema.format === 'int64' || schema.format === 'uint64') {\n return createNode(ctx, {\n type: options.integerType === 'bigint' ? 'bigint' : 'integer',\n primitive: 'integer',\n min: schema.minimum,\n max: schema.maximum,\n ...getExclusiveBounds(schema),\n })\n }\n\n if (schema.format === 'date-time' || schema.format === 'date' || schema.format === 'time') {\n const dateType = getDateType(options, schema.format)!\n\n if (dateType.type === 'datetime') {\n return createNode(ctx, {\n primitive: 'string' as const,\n type: 'datetime',\n offset: dateType.offset,\n local: dateType.local,\n })\n }\n return createNode(ctx, {\n primitive: 'string' as const,\n type: dateType.type,\n representation: dateType.representation,\n })\n }\n\n const specialType = getSchemaType(schema.format!)!\n\n const specialPrimitive: ast.PrimitiveSchemaType = specialType === 'number' || specialType === 'integer' || specialType === 'bigint' ? specialType : 'string'\n const hasLength = specialType === 'url' || specialType === 'uuid' || specialType === 'email'\n\n return createNode(ctx, {\n primitive: specialPrimitive,\n type: specialType as ast.ScalarSchemaType,\n ...(hasLength ? { min: schema.minLength, max: schema.maxLength } : {}),\n })\n}\n\n/**\n * Converts an `enum` schema into an `EnumSchemaNode`.\n */\nexport function convertEnum({ schema, name, nullable, type, rawOptions, parse }: ConvertContext): ast.SchemaNode {\n if (type === 'array') {\n return parse({ schema: normalizeArrayEnum(schema), name }, rawOptions)\n }\n\n const nullInEnum = schema.enum!.includes(null)\n const filteredValues = (nullInEnum ? schema.enum!.filter((v) => v !== null) : schema.enum!) as Array<string | number | boolean>\n\n // drf-spectacular `NullEnum` ({ enum: [null] }) is just `null`. An empty enum node would\n // render as `never` (plugin-ts) / invalid `z.enum([])` (plugin-zod). Mirror the `const: null`\n // branch so it renders as a clean `null` (not `z.null().nullable()`).\n if (nullInEnum && filteredValues.length === 0) {\n return createNullNode(schema, name)\n }\n\n const enumNullable = nullable || nullInEnum || undefined\n const enumDefault = schema.default === null && enumNullable ? undefined : schema.default\n const enumPrimitive = getPrimitiveType(type)\n\n const ctx = { schema, name, nullable: enumNullable as true | undefined, defaultValue: enumDefault }\n const enumExtras = {\n type: 'enum' as const,\n primitive: enumPrimitive,\n }\n\n const extensionKey = enumExtensionKeys.find((key) => key in schema)\n const descriptionKey = enumDescriptionKeys.find((key) => key in schema)\n if (extensionKey || descriptionKey || enumPrimitive === 'number' || enumPrimitive === 'integer' || enumPrimitive === 'boolean') {\n let enumPrimitiveType: 'number' | 'boolean' | 'string' = 'string'\n if (enumPrimitive === 'number' || enumPrimitive === 'integer') enumPrimitiveType = 'number'\n else if (enumPrimitive === 'boolean') enumPrimitiveType = 'boolean'\n const rawEnumNames = extensionKey ? ((schema as Record<string, unknown>)[extensionKey] as Array<string | number>) : undefined\n const rawEnumDescriptions = descriptionKey ? ((schema as Record<string, unknown>)[descriptionKey] as Array<string>) : undefined\n const uniqueValues = [...new Set(filteredValues)]\n const seenNames = new Set<string>()\n\n return createNode(ctx, {\n ...enumExtras,\n primitive: enumPrimitiveType,\n namedEnumValues: uniqueValues\n .map((value, index) => ({\n name: String(rawEnumNames?.[index] ?? value),\n value,\n primitive: enumPrimitiveType,\n description: rawEnumDescriptions?.[index],\n }))\n .filter((entry) => {\n if (seenNames.has(entry.name)) return false\n seenNames.add(entry.name)\n return true\n }),\n })\n }\n\n return createNode(ctx, {\n ...enumExtras,\n enumValues: [...new Set(filteredValues)],\n })\n}\n\n/**\n * Converts a `type: 'string'` schema into a `StringSchemaNode`.\n */\nexport function convertString({ schema, name, nullable, defaultValue }: ConvertContext): ast.SchemaNode {\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'string',\n primitive: 'string',\n min: schema.minLength,\n max: schema.maxLength,\n pattern: schema.pattern,\n },\n )\n}\n\n/**\n * Converts a `type: 'number'` or `type: 'integer'` schema.\n */\nexport function convertNumeric({ schema, name, nullable, defaultValue }: ConvertContext, type: 'number' | 'integer'): ast.SchemaNode {\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type,\n primitive: type,\n min: schema.minimum,\n max: schema.maximum,\n ...getExclusiveBounds(schema),\n multipleOf: schema.multipleOf,\n },\n )\n}\n\n/**\n * Converts a `type: 'boolean'` schema.\n */\nexport function convertBoolean({ schema, name, nullable, defaultValue }: ConvertContext): ast.SchemaNode {\n return createNode({ schema, name, nullable, defaultValue }, { type: 'boolean', primitive: 'boolean' })\n}\n\n/**\n * Converts a binary string schema (`type: 'string'`, `contentMediaType: 'application/octet-stream'`)\n * into a `blob` node.\n */\nexport function convertBinary({ schema, name, nullable, defaultValue }: ConvertContext): ast.SchemaNode {\n return createNode({ schema, name, nullable, defaultValue }, { type: 'blob', primitive: 'string' })\n}\n","import { ast } from '@kubb/ast'\nimport { childName, enumPropName, macroDiscriminatorEnum, macroEnumName } from '@kubb/kit'\nimport { isDiscriminator, isNullable } from '../../oas.ts'\nimport type { SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\n\n/**\n * Resolves a `true` or empty-object map schema (`additionalProperties`/`patternProperties`) to\n * `options.unknownType`, otherwise parses it as a regular schema.\n */\nfunction resolveMapSchema(\n mapSchema: unknown,\n options: ConvertContext['options'],\n parse: ConvertContext['parse'],\n rawOptions: ConvertContext['rawOptions'],\n): ast.SchemaNode {\n if (mapSchema === true || (typeof mapSchema === 'object' && Object.keys(mapSchema as object).length === 0)) {\n return ast.factory.createSchema({ type: options.unknownType })\n }\n return parse({ schema: mapSchema as SchemaObject }, rawOptions)\n}\n\n/**\n * Names the inline enums on a property's schema, and on each item when the property is a tuple, from\n * the parent and property name. Wraps `macroEnumName` at the property construction site.\n */\nfunction nameEnums(node: ast.SchemaNode, options: { parentName: string | null | undefined; propName: string; enumSuffix: string }): ast.SchemaNode {\n const macro = macroEnumName(options)\n const named = ast.applyMacros(node, [macro], { depth: 'shallow' })\n const tupleNode = ast.narrowSchema(named, 'tuple')\n if (tupleNode?.items) {\n const namedItems = tupleNode.items.map((item) => ast.applyMacros(item, [macro], { depth: 'shallow' }))\n if (namedItems.some((item, i) => item !== tupleNode.items![i])) {\n return { ...tupleNode, items: namedItems }\n }\n }\n return named\n}\n\n/**\n * Converts an object-like schema into an `ObjectSchemaNode`.\n */\nexport function convertObject({ schema, name, nullable, defaultValue, rawOptions, options, parse }: ConvertContext): ast.SchemaNode {\n const properties: Array<ast.PropertyNode> = schema.properties\n ? Object.entries(schema.properties).map(([propName, propSchema]) => {\n const required = Array.isArray(schema.required) ? schema.required.includes(propName) : !!schema.required\n const resolvedPropSchema = propSchema as SchemaObject\n const propNullable = isNullable(resolvedPropSchema)\n\n const resolvedChildName = childName(name, propName)\n const propNode = parse({ schema: resolvedPropSchema, name: resolvedChildName }, rawOptions)\n const schemaNode = nameEnums(propNode, { parentName: name, propName, enumSuffix: options.enumSuffix })\n\n return ast.factory.createProperty({\n name: propName,\n schema: {\n ...schemaNode,\n nullable: schemaNode.type === 'null' ? undefined : propNullable || undefined,\n },\n required,\n })\n })\n : []\n\n const additionalProperties = schema.additionalProperties\n let additionalPropertiesNode: ast.SchemaNode | boolean | undefined\n if (additionalProperties === true) additionalPropertiesNode = true\n else if (additionalProperties) additionalPropertiesNode = resolveMapSchema(additionalProperties, options, parse, rawOptions)\n else additionalPropertiesNode = additionalProperties\n\n const rawPatternProperties = 'patternProperties' in schema ? schema.patternProperties : undefined\n\n const patternProperties = rawPatternProperties\n ? Object.fromEntries(\n Object.entries(rawPatternProperties).map(([pattern, patternSchema]) => [pattern, resolveMapSchema(patternSchema, options, parse, rawOptions)]),\n )\n : undefined\n\n const objectNode: ast.SchemaNode = createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'object',\n primitive: 'object',\n properties,\n additionalProperties: additionalPropertiesNode,\n patternProperties,\n minProperties: schema.minProperties,\n maxProperties: schema.maxProperties,\n },\n )\n\n if (isDiscriminator(schema) && schema.discriminator.mapping) {\n const discPropName = schema.discriminator.propertyName\n const values = Object.keys(schema.discriminator.mapping)\n const enumName = name ? enumPropName(name, discPropName, options.enumSuffix) : undefined\n return ast.applyMacros(objectNode, [macroDiscriminatorEnum({ propertyName: discPropName, values, enumName })], { depth: 'shallow' })\n }\n\n return objectNode\n}\n\n/**\n * Converts an OAS 3.1 `prefixItems` tuple into a `TupleSchemaNode`.\n */\nexport function convertTuple({ schema, name, nullable, defaultValue, rawOptions, options, parse }: ConvertContext): ast.SchemaNode {\n const tupleItems = (schema.prefixItems ?? []).map((item) => parse({ schema: item as SchemaObject }, rawOptions))\n // items: false closes the tuple; absent/true widens the tail to unknownType.\n const rest =\n schema.items === false\n ? undefined\n : !schema.items || schema.items === true\n ? ast.factory.createSchema({ type: options.unknownType })\n : parse({ schema: schema.items as SchemaObject }, rawOptions)\n\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'tuple',\n primitive: 'array',\n items: tupleItems,\n rest,\n min: schema.minItems,\n max: schema.maxItems,\n },\n )\n}\n\n/**\n * Converts a `type: 'array'` schema into an `ArraySchemaNode`.\n */\nexport function convertArray({ schema, name, nullable, defaultValue, rawOptions, options, parse }: ConvertContext): ast.SchemaNode {\n const rawItems = schema.items as SchemaObject | undefined\n const itemName = rawItems?.enum?.length && name ? enumPropName(null, name, options.enumSuffix) : name\n const items = rawItems ? [parse({ schema: rawItems, name: itemName }, rawOptions)] : []\n\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'array',\n primitive: 'array',\n items,\n min: schema.minItems,\n max: schema.maxItems,\n unique: schema.uniqueItems ?? undefined,\n },\n )\n}\n","import type { ast } from '@kubb/ast'\nimport { isBinary, isReference } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport type { Document, SchemaObject } from '../types.ts'\nimport { convertAllOf, convertMultiType, convertRef, convertUnion } from './converters/composition.ts'\nimport { convertBinary, convertBoolean, convertConst, convertEnum, convertFormat, convertNumeric, convertString, createNullNode } from './converters/scalar.ts'\nimport { convertArray, convertObject, convertTuple } from './converters/structural.ts'\nimport { isHandledFormat } from './schemaShape.ts'\n\n/**\n * Pre-computed per-schema context passed to every schema converter.\n *\n * Centralizes schema derivations (type resolution, defaults, options) to avoid repeated\n * computation across all conversion branches. The `type` field is normalized from OAS 3.1\n * multi-type arrays to a single string.\n */\nexport type SchemaContext = {\n schema: SchemaObject\n name: string | null | undefined\n nullable: true | undefined\n defaultValue: unknown\n /**\n * Normalized single type string (first non-`null` element when OAS 3.1 multi-type array, so\n * `['null', 'string']` and `['string', 'null']` both normalize to `string` with `nullable` set).\n */\n type: string | undefined\n rawOptions: Partial<ast.ParserOptions> | undefined\n options: ast.ParserOptions\n}\n\n/**\n * Recurses into a nested schema. Converters call this instead of capturing the parser closure,\n * so each converter stays a standalone function.\n */\nexport type ParseFn = (entry: { schema: SchemaObject; name?: string | null }, rawOptions?: Partial<ast.ParserOptions>) => ast.SchemaNode\n\n/**\n * What a converter needs from the parser instance beyond the schema: how to recurse, the source\n * document, and the `$ref` service bound to it.\n */\nexport type ConverterDeps = {\n parse: ParseFn\n document: Document\n refs: Refs\n /**\n * Collision renames keyed by the original component pointer, used to stamp `targetName`\n * on ref nodes whose target the adapter renamed.\n */\n renames?: ReadonlyMap<string, string>\n}\n\n/**\n * Everything a converter receives: the per-schema context plus what it needs from the parser instance.\n */\nexport type ConvertContext = SchemaContext & ConverterDeps\n\n/**\n * One entry in the ordered schema rule table: a predicate paired with a converter. `match`\n * fully decides whether this rule owns the context, so `convert` always produces a node.\n */\nexport type SchemaRule = {\n /**\n * Returns `true` when this rule is responsible for the given context.\n */\n match: (context: ConvertContext) => boolean\n /**\n * Produces a node for the context.\n */\n convert: (context: ConvertContext) => ast.SchemaNode\n}\n\n/**\n * Ordered schema rule table. Order is significant: composition keywords (`$ref`, `allOf`,\n * `oneOf`/`anyOf`) take precedence over `const`, which takes precedence over a genuine OAS 3.1\n * multi-type array (more than one non-`null` type), which takes precedence over `format`/`type`.\n * A multi-type array must split into its per-type members before `format` runs, otherwise\n * `format` collapses the whole schema to one type (e.g. `type: ['null', 'integer', 'string'],\n * format: 'int32'` would drop `string` and emit just `integer`); each split-off member still\n * carries the original `format` and re-enters this table, so `format` still applies per member.\n * The first matching rule that produces a node wins. See {@link SchemaRule} for the\n * match/convert/fall-through contract.\n */\nexport const schemaRules: Array<SchemaRule> = [\n { match: ({ schema }) => isReference(schema), convert: convertRef },\n { match: ({ schema }) => !!schema.allOf?.length, convert: convertAllOf },\n { match: ({ schema }) => !!(schema.oneOf?.length || schema.anyOf?.length), convert: convertUnion },\n { match: ({ schema }) => 'const' in schema && schema.const !== undefined, convert: convertConst },\n { match: ({ schema }) => Array.isArray(schema.type) && schema.type.filter((t) => t !== 'null').length > 1, convert: convertMultiType },\n {\n match: ({ schema, options }) => {\n if (!schema.format) return false\n if (schema.format === 'date-time' || schema.format === 'date' || schema.format === 'time') return options.dateType !== false\n return isHandledFormat(schema.format)\n },\n convert: convertFormat,\n },\n { match: ({ schema }) => isBinary(schema), convert: convertBinary },\n {\n match: ({ schema, type }) => !type && (schema.minLength !== undefined || schema.maxLength !== undefined || schema.pattern !== undefined),\n convert: convertString,\n },\n {\n match: ({ schema, type }) => !type && (schema.minimum !== undefined || schema.maximum !== undefined),\n convert: (ctx) => convertNumeric(ctx, 'number'),\n },\n { match: ({ schema }) => !!schema.enum?.length, convert: convertEnum },\n {\n match: ({ schema, type }) => type === 'object' || !!schema.properties || !!schema.additionalProperties || 'patternProperties' in schema,\n convert: convertObject,\n },\n { match: ({ schema }) => 'prefixItems' in schema, convert: convertTuple },\n { match: ({ schema, type }) => type === 'array' || 'items' in schema, convert: convertArray },\n { match: ({ type }) => type === 'string', convert: convertString },\n { match: ({ type }) => type === 'number', convert: (ctx) => convertNumeric(ctx, 'number') },\n { match: ({ type }) => type === 'integer', convert: (ctx) => convertNumeric(ctx, 'integer') },\n { match: ({ type }) => type === 'boolean', convert: convertBoolean },\n { match: ({ type }) => type === 'null', convert: ({ schema, name, nullable }) => createNullNode(schema, name, nullable) },\n]\n","import type { ast } from '@kubb/ast'\nimport { type Diagnostic, Diagnostics } from '@kubb/core'\nimport { isReference } from './oas.ts'\nimport type { Document, SchemaObject } from './types.ts'\n\nconst _refCache = new WeakMap<Document, Map<string, unknown>>()\n\n/**\n * Walks a local `#/...` JSON pointer against `document`, memoized per document. `applicable` is\n * `false` for an empty or non-local ref (the caller should not treat that as a failed lookup).\n * Shared by `resolveRef`'s reporting walk and `createRefs().resolve`'s silent walk, so both use\n * the same trimming and caching instead of two separate implementations.\n */\nfunction walkPointer<T>(document: Document, $ref: string): { applicable: boolean; value: T | null } {\n const trimmed = $ref.trim()\n if (trimmed === '' || !trimmed.startsWith('#')) {\n return { applicable: false, value: null }\n }\n const pointer = globalThis.decodeURIComponent(trimmed.substring(1))\n\n let docCache = _refCache.get(document)\n if (!docCache) {\n docCache = new Map()\n _refCache.set(document, docCache)\n }\n\n if (docCache.has(pointer)) {\n return { applicable: true, value: docCache.get(pointer) as T }\n }\n\n const current = pointer\n .split('/')\n .filter(Boolean)\n .reduce((obj: unknown, key: string) => (obj as Record<string, unknown>)?.[key], document as unknown)\n\n if (current) {\n docCache.set(pointer, current)\n }\n\n return { applicable: true, value: (current as T) ?? null }\n}\n\n/**\n * Resolves a local JSON pointer reference from a document.\n *\n * Accepts `#/...` refs. Returns `null` for an empty or non-local ref. When the pointer cannot be\n * resolved, reports a `refNotFound` diagnostic into the active build and returns `null`. Outside a\n * build there is no sink to collect it, so it throws instead.\n *\n * @example\n * ```ts\n * resolveRef<SchemaObject>(document, '#/components/schemas/Pet')\n * ```\n */\nexport function resolveRef<T = unknown>(document: Document, $ref: string): T | null {\n const { applicable, value } = walkPointer<T>(document, $ref)\n if (!applicable) return null\n if (value) return value\n\n const diagnostic: Diagnostic = {\n code: Diagnostics.code.refNotFound,\n severity: 'error',\n message: `Could not find a definition for ${$ref}.`,\n help: 'Add the schema under `components.schemas`, or fix the `$ref`. Run `kubb validate` to check the spec.',\n location: { kind: 'schema', pointer: $ref, ref: $ref },\n }\n // Report the unresolved ref into the active build and resolve to null, like any\n // other unresolvable ref. The build collects it and keeps going. Outside a build there is no\n // sink, so throw rather than silently returning null.\n if (!Diagnostics.report(diagnostic)) {\n throw new Diagnostics.Error(diagnostic)\n }\n return null\n}\n\n/**\n * Resolves a `$ref` object while preserving the original `$ref` field on the result.\n *\n * Useful for parser flows that need both dereferenced fields and pointer\n * identity (for naming/import purposes). Non-reference values are returned as-is.\n *\n * @example\n * ```ts\n * dereferenceWithRef(document, { $ref: '#/components/schemas/Pet' })\n * // { $ref: '#/components/schemas/Pet', type: 'object', properties: { ... } }\n * ```\n */\nexport function dereferenceWithRef<T = unknown>(document: Document, schema?: T): T {\n if (isReference(schema)) {\n return {\n ...schema,\n ...resolveRef(document, schema.$ref),\n $ref: schema.$ref,\n }\n }\n\n return schema as T\n}\n\n/**\n * Parses a schema for a resolved `$ref` target. Passed in at call time (rather than imported)\n * so `refs.ts` stays independent of the parser/converter layer.\n */\ntype RefNodeParser = (entry: { schema: SchemaObject; name?: string | null }, rawOptions?: Partial<ast.ParserOptions>) => ast.SchemaNode\n\n/**\n * The `$ref` service bound to one document: pointer resolution, existence checks, and\n * resolved-node parsing, each with its own instance-scoped memoization.\n */\nexport type Refs = ReturnType<typeof createRefs>\n\n/**\n * Creates the `$ref` resolution service for one document.\n *\n * Replaces what used to be six overlapping resolvers (a reporting walk, a silent walk, an\n * existence check, and a resolve-then-parse-into-a-node step, each with its own cache) with one\n * pointer walk and one explicit `report` contract for a missing ref: `report: true` (the default)\n * reports a `refNotFound` diagnostic (or throws outside a build), `report: false` resolves to\n * `null` silently for a speculative lookup.\n *\n * @example\n * ```ts\n * const refs = createRefs(document)\n * refs.resolve<SchemaObject>('#/components/schemas/Pet')\n * refs.resolve<SchemaObject>('#/components/schemas/Pet', { report: false })\n * refs.exists('#/components/schemas/Pet')\n * refs.resolveNode('#/components/schemas/Pet', parseSchema)\n * refs.deref<ResponseObject>(operation.schema.responses?.['200'])\n * ```\n */\nexport function createRefs(document: Document) {\n const resolvedNodeCache = new Map<string, ast.SchemaNode | null>()\n const existenceCache = new Map<string, boolean>()\n const resolvingRefs = new Set<string>()\n\n /**\n * Resolves a local `#/...` JSON pointer. Returns `null` for an empty or non-local ref.\n * `report: true` (default) reports a `refNotFound` diagnostic into the active build (or throws\n * outside one) when the pointer cannot be resolved. `report: false` resolves to `null` silently,\n * for a speculative lookup where a missing ref is not an error.\n */\n function resolve<T = unknown>(refPath: string, options?: { report?: boolean }): T | null {\n if (options?.report === false) {\n const { applicable, value } = walkPointer<T>(document, refPath)\n return applicable ? value : null\n }\n\n return resolveRef<T>(document, refPath)\n }\n\n /**\n * Returns `true` when a `$ref` path resolves to a component the document actually defines.\n * A circular ref still resolves to an existing target, so this stays `true` for cycles and only\n * goes `false` for a `$ref` that points at a component the spec never declares. Memoized.\n */\n function exists(refPath: string): boolean {\n if (!existenceCache.has(refPath)) {\n existenceCache.set(refPath, !!resolve(refPath, { report: false }))\n }\n return existenceCache.get(refPath) ?? false\n }\n\n /**\n * Resolves a `$ref` to its parsed node via `parse`, guarding against cycles and memoizing per\n * instance. Returns `null` when the ref is currently being resolved (a cycle) or cannot be\n * resolved (e.g. a minimal document in a unit test).\n */\n function resolveNode(refPath: string, parse: RefNodeParser, rawOptions?: Partial<ast.ParserOptions>): ast.SchemaNode | null {\n if (resolvingRefs.has(refPath)) return null\n\n if (!resolvedNodeCache.has(refPath)) {\n let resolved: ast.SchemaNode | null = null\n try {\n const referenced = resolve<SchemaObject>(refPath)\n if (referenced) {\n resolvingRefs.add(refPath)\n resolved = parse({ schema: referenced }, rawOptions)\n resolvingRefs.delete(refPath)\n }\n } catch {\n // Ref cannot be resolved in this document (e.g. unit tests with minimal documents).\n }\n resolvedNodeCache.set(refPath, resolved)\n }\n\n return resolvedNodeCache.get(refPath) ?? null\n }\n\n /**\n * Resolves a `$ref` value without mutating anything: when `value` holds a `$ref`, returns the\n * resolved target. Returns `null` when the value is empty, cannot be resolved, or is still a\n * `$ref` after resolving (e.g. a document with no component registry). A non-`$ref` value is\n * returned as-is.\n *\n * @example\n * ```ts\n * refs.deref<ResponseObject>(operation.schema.responses?.['200'])\n * ```\n */\n function deref<T = unknown>(value: unknown): T | null {\n if (!isReference(value)) {\n return value ? (value as T) : null\n }\n\n const resolved = resolve<T>(value.$ref)\n return resolved && !isReference(resolved) ? resolved : null\n }\n\n return { resolve, exists, resolveNode, deref }\n}\n","import { isReference, pickContentEntry } from '../oas.ts'\nimport { getRequestBody, getRequestContent, getResponseByStatusCode } from '../operation.ts'\nimport { dereferenceWithRef } from '../refs.ts'\nimport type { Refs } from '../refs.ts'\nimport type { ContentTypeOptions, Document, MediaTypeObject, Operation, ParameterObject, ResponseObject, SchemaObject } from '../types.ts'\n\n/**\n * Returns all parameters for an operation, merging path-level and operation-level entries.\n * Operation-level parameters override path-level ones with the same `in:name` key.\n * Each `$ref` parameter is dereferenced via `dereferenceWithRef` before merging.\n *\n * @example\n * ```ts\n * getParameters({ document, operation })\n * // [{ name: 'petId', in: 'path', required: true, schema: { type: 'integer' } }]\n * ```\n */\nexport function getParameters({ document, operation }: { document: Document; operation: Operation }): Array<ParameterObject> {\n const resolveParams = (params: Array<unknown>): Array<ParameterObject> =>\n params.map((p) => dereferenceWithRef(document, p)).filter((p): p is ParameterObject => !!p && typeof p === 'object' && 'in' in p && 'name' in p)\n\n const operationParams = resolveParams(operation.schema?.parameters || [])\n const pathLevelParams = resolveParams((operation.pathItem as { parameters?: Array<unknown> }).parameters ?? [])\n\n const paramMap = new Map<string, ParameterObject>()\n for (const p of pathLevelParams) {\n if (p.name && p.in) {\n paramMap.set(`${p.in}:${p.name}`, p)\n }\n }\n for (const p of operationParams) {\n if (p.name && p.in) {\n paramMap.set(`${p.in}:${p.name}`, p)\n }\n }\n\n return Array.from(paramMap.values())\n}\n\nfunction getResponseBody(responseBody: boolean | ResponseObject, contentType?: string): MediaTypeObject | false {\n if (!responseBody) return false\n if (isReference(responseBody)) return false\n\n const body = responseBody as ResponseObject\n if (!body.content) return false\n\n if (contentType) {\n return contentType in body.content ? body.content[contentType]! : false\n }\n\n const picked = pickContentEntry(body.content)\n return picked ? picked[1] : false\n}\n\n/**\n * Returns the response schema for a given operation and HTTP status code.\n *\n * Returns an empty object `{}` when no response body schema is available.\n *\n * @example\n * ```ts\n * getResponseSchema({ document, operation, refs, statusCode: 200 }) // SchemaObject\n * getResponseSchema({ document, operation, refs, statusCode: '4XX' }) // {}\n * ```\n */\nexport function getResponseSchema({\n document,\n operation,\n refs,\n statusCode,\n options = {},\n}: {\n document: Document\n operation: Operation\n refs: Refs\n statusCode: string | number\n options?: ContentTypeOptions\n}): SchemaObject {\n const responseBody = getResponseBody(getResponseByStatusCode({ operation, refs, statusCode }), options.contentType)\n\n if (responseBody === false) {\n return {}\n }\n\n const schema = responseBody.schema\n\n if (!schema) {\n return {}\n }\n\n return dereferenceWithRef(document, schema)\n}\n\n/**\n * Returns the request body schema for an operation, or `null` when absent.\n *\n * @example\n * ```ts\n * getRequestSchema({ document, operation, refs }) // SchemaObject | null\n * ```\n */\nexport function getRequestSchema({\n document,\n operation,\n refs,\n options = {},\n}: {\n document: Document\n operation: Operation\n refs: Refs\n options?: ContentTypeOptions\n}): SchemaObject | null {\n const requestBody = getRequestContent({ operation, refs, mediaType: options.contentType })\n\n if (requestBody === false) {\n return null\n }\n\n const mediaType = Array.isArray(requestBody) ? requestBody[0] : options.contentType\n const schema = Array.isArray(requestBody) ? requestBody[1].schema : requestBody.schema\n\n // OAS 3.1 (and the 3.0 -> 3.1 upgrade) drops the schema for an `application/octet-stream` body,\n // leaving an empty media type object. Synthesize the binary schema so generators still emit a\n // request body type for the operation.\n if (mediaType === 'application/octet-stream' && (!schema || Object.keys(schema).length === 0)) {\n return { type: 'string', contentMediaType: 'application/octet-stream' }\n }\n\n if (!schema) {\n return null\n }\n\n return dereferenceWithRef(document, schema)\n}\n\n/**\n * Returns all request body content type keys for an operation, resolving a `$ref` requestBody\n * through `refs`.\n *\n * @example\n * ```ts\n * getRequestBodyContentTypes(operation, refs)\n * // ['application/json', 'multipart/form-data']\n * ```\n */\nexport function getRequestBodyContentTypes(operation: Operation, refs: Refs): Array<string> {\n const body = getRequestBody({ operation, refs })\n\n return body?.content ? Object.keys(body.content) : []\n}\n\n/**\n * Returns all response content type keys for an operation at a given status code, resolving the\n * response `$ref` through `refs`.\n *\n * @example\n * ```ts\n * getResponseBodyContentTypes(operation, refs, 200)\n * // ['application/json', 'application/xml']\n * ```\n */\nexport function getResponseBodyContentTypes(operation: Operation, refs: Refs, statusCode: string | number): Array<string> {\n const responseObj = getResponseByStatusCode({ operation, refs, statusCode })\n if (!responseObj || typeof responseObj !== 'object' || isReference(responseObj)) return []\n\n const body = responseObj as { content?: Record<string, unknown> }\n return body.content ? Object.keys(body.content) : []\n}\n","import { pascalCase } from '@internals/utils'\nimport { ast, type StatusCode } from '@kubb/ast'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { type ConvertContext, schemaRules } from './emit/parseSchema.ts'\nimport { flattenSchema } from './emit/schemaShape.ts'\nimport { getParameters, getRequestBodyContentTypes, getRequestSchema, getResponseBodyContentTypes, getResponseSchema } from './model/operations.ts'\nimport { isNullable, isReference } from './oas.ts'\nimport { getOperationId, getRequestBody, getRequestContentType, getResponseByStatusCode, getResponseStatusCodes } from './operation.ts'\nimport type { Refs } from './refs.ts'\nimport type { ContentTypeOptions, Document, Operation, SchemaObject } from './types.ts'\n\n/**\n * Parser context holding the raw OpenAPI document and optional content-type override.\n *\n * Passed to schema and operation converters to access the full specification\n * and handle content negotiation when multiple media types are available.\n */\nexport type OasParserContext = ContentTypeOptions & {\n document: Document\n refs: Refs\n /**\n * Collision renames from `getSchemas`, keyed by the original component pointer. `convertRef`\n * stamps `targetName` from it at ref creation, so refs to renamed schemas resolve to the\n * emitted name without a post-parse pass.\n */\n renames?: ReadonlyMap<string, string>\n}\n\n/**\n * Creates the schema and operation converters bound to one OpenAPI document.\n *\n * Takes the `$ref` service for this document (shared with the rest of the pipeline, see\n * `adapter.ts`) and owns the `parseSchema` recursion seam, then dispatches each schema through\n * the ordered `schemaRules` table from `emit/parseSchema.ts`. Every converter is a standalone\n * function that recurses through the `parse` function passed to it, so this file only wires\n * state to the converters.\n *\n * @internal\n */\nexport function createSchemaParser(ctx: OasParserContext) {\n const document = ctx.document\n const refs = ctx.refs\n\n /**\n * Converts an OAS `SchemaObject` into a `SchemaNode`.\n *\n * Builds the per-schema context, then walks the ordered {@link schemaRules} table and returns\n * the first converter that produces a node. When none match, falls back to the configured\n * `emptySchemaType`.\n */\n function parseSchema({ schema, name }: { schema: SchemaObject; name?: string | null }, rawOptions?: Partial<ast.ParserOptions>): ast.SchemaNode {\n const options: ast.ParserOptions = {\n ...DEFAULT_PARSER_OPTIONS,\n ...rawOptions,\n }\n const flattenedSchema = flattenSchema(schema)\n if (flattenedSchema && flattenedSchema !== schema) {\n return parseSchema({ schema: flattenedSchema, name }, rawOptions)\n }\n\n const nullable = isNullable(schema) || undefined\n const defaultValue = schema.default === null && nullable ? undefined : schema.default\n const type = Array.isArray(schema.type) ? (schema.type.find((t) => t !== 'null') ?? schema.type[0]) : schema.type\n\n const context: ConvertContext = {\n schema,\n name,\n nullable,\n defaultValue,\n type,\n rawOptions,\n options,\n parse: parseSchema,\n document,\n refs,\n renames: ctx.renames,\n }\n\n for (const rule of schemaRules) {\n if (rule.match(context)) return rule.convert(context)\n }\n\n const emptyType = options.emptySchemaType\n return ast.factory.createSchema({\n type: emptyType as ast.ScalarSchemaType,\n name,\n title: schema.title,\n description: schema.description,\n format: schema.format,\n })\n }\n\n /**\n * Converts a dereferenced OAS parameter object into a `ParameterNode`.\n */\n function parseParameter(options: ast.ParserOptions, param: Record<string, unknown>, parentName?: string): ast.ParameterNode {\n const required = (param['required'] as boolean | undefined) ?? false\n const paramName = param['name'] as string\n const schemaName = parentName && paramName ? pascalCase(`${parentName} ${paramName}`) : undefined\n\n const schema: ast.SchemaNode = param['schema']\n ? parseSchema({ schema: param['schema'] as SchemaObject, name: schemaName }, options)\n : ast.factory.createSchema({ type: options.unknownType })\n\n const style = param['style'] as ast.ParameterStyle | undefined\n const explode = param['explode'] as boolean | undefined\n\n return ast.factory.createParameter({\n name: paramName,\n in: param['in'] as ast.ParameterLocation,\n schema: {\n ...schema,\n description: (param['description'] as string | undefined) ?? schema.description,\n },\n required,\n ...(style !== undefined ? { style } : {}),\n ...(explode !== undefined ? { explode } : {}),\n })\n }\n\n /**\n * Reads the inline `requestBody` metadata (description / required) that OAS exposes\n * outside the schema itself, resolving a `$ref` requestBody through `refs`. Returns an\n * empty object when the request body is missing or cannot be resolved.\n */\n function getRequestBodyMeta(operation: Operation): {\n description?: string\n required: boolean\n } {\n const body = getRequestBody({ operation, refs })\n if (!body) return { required: false }\n\n return {\n description: body.description,\n required: body.required === true,\n }\n }\n\n /**\n * Collects property names whose schema has a truthy boolean flag (`readOnly` or `writeOnly`).\n * `$ref` entries are skipped since their flags live on the dereferenced target.\n */\n function collectPropertyKeysByFlag(schema: SchemaObject | null, flag: 'readOnly' | 'writeOnly'): Array<string> | null {\n if (!schema?.properties) return null\n\n const keys: Array<string> = []\n for (const key in schema.properties) {\n const prop = schema.properties[key]\n if (prop && !isReference(prop) && (prop as Record<string, unknown>)[flag]) {\n keys.push(key)\n }\n }\n return keys.length ? keys : null\n }\n\n /**\n * Converts an OAS `Operation` into an `OperationNode`.\n */\n function parseOperation(options: ast.ParserOptions, operation: Operation): ast.OperationNode {\n const operationId = getOperationId(operation)\n const operationName = operationId ? pascalCase(operationId) : undefined\n const parameters: Array<ast.ParameterNode> = getParameters({ document, operation }).map((param) =>\n parseParameter(options, param as unknown as Record<string, unknown>, operationName),\n )\n\n // Determine which content types to include in requestBody.content.\n // When a global contentType is configured, restrict to that single type.\n // Otherwise include every content type declared in the spec.\n const allContentTypes = ctx.contentType ? [ctx.contentType] : getRequestBodyContentTypes(operation, refs)\n\n const requestBodyMeta = getRequestBodyMeta(operation)\n const requestBodyName = operationName ? `${operationName}Request` : undefined\n\n const content = allContentTypes.flatMap((ct) => {\n const schema = getRequestSchema({ document, operation, refs, options: { contentType: ct } })\n if (!schema) return []\n return [\n ast.factory.createContent({\n contentType: ct,\n schema: ast.optionality(parseSchema({ schema, name: requestBodyName }, options), requestBodyMeta.required),\n keysToOmit: collectPropertyKeysByFlag(schema, 'readOnly'),\n }),\n ]\n })\n\n const requestBody =\n content.length > 0 || requestBodyMeta.description\n ? {\n description: requestBodyMeta.description,\n required: requestBodyMeta.required || undefined,\n content: content.length > 0 ? content : undefined,\n }\n : undefined\n\n const responses: Array<ast.ResponseNode> = getResponseStatusCodes(operation).map((statusCode) => {\n const responseObj = getResponseByStatusCode({ operation, refs, statusCode })\n\n // Use `Status<code>` (matching plugin-ts's resolveResponseStatusName convention) so the\n // qualified names for nested enums don't collide with top-level component schemas that\n // happen to be named `<operation><statusCode>` (e.g. `GetMaintenance200`).\n const responseName = operationName ? `${operationName}Status${statusCode}` : undefined\n const description = typeof responseObj === 'object' && responseObj !== null ? (responseObj as { description?: string }).description : undefined\n\n const parseEntrySchema = (contentType?: string) => {\n const raw = getResponseSchema({ document, operation, refs, statusCode, options: { contentType } })\n const node =\n raw && Object.keys(raw).length > 0\n ? parseSchema({ schema: raw, name: responseName }, options)\n : ast.factory.createSchema({ type: options.emptySchemaType })\n return { schema: node, keysToOmit: collectPropertyKeysByFlag(raw, 'writeOnly') }\n }\n\n // Build one entry per declared response content type so plugins can union the variants.\n // When a global contentType is configured, restrict to that single type (mirrors requestBody).\n const responseContentTypes = ctx.contentType ? [ctx.contentType] : getResponseBodyContentTypes(operation, refs, statusCode)\n const content = responseContentTypes.map((contentType) => ast.factory.createContent({ contentType, ...parseEntrySchema(contentType) }))\n\n // Body-less responses keep a single fallback entry so the response still resolves to a\n // (void/any) schema, matching how `requestBody` only carries schemas inside `content`.\n if (content.length === 0) {\n content.push(\n ast.factory.createContent({\n contentType: getRequestContentType({ operation, refs }) || 'application/json',\n ...parseEntrySchema(ctx.contentType),\n }),\n )\n }\n\n return ast.factory.createResponse({\n statusCode: statusCode as StatusCode,\n description,\n content,\n })\n })\n\n const pickDoc = (key: 'summary' | 'description'): string | undefined => {\n const own = operation.schema[key]\n if (typeof own === 'string') return own\n const fallback = (operation.pathItem as Record<string, unknown>)[key]\n return typeof fallback === 'string' ? fallback : undefined\n }\n\n return ast.factory.createOperation({\n operationId,\n protocol: 'http',\n method: operation.method.toUpperCase() as ast.HttpMethod,\n path: operation.path,\n tags: Array.isArray(operation.schema.tags) ? operation.schema.tags.map(String) : [],\n summary: pickDoc('summary') || undefined,\n description: pickDoc('description') || undefined,\n deprecated: operation.schema.deprecated || undefined,\n parameters,\n requestBody,\n responses,\n })\n }\n\n return { parseSchema, parseOperation, parseParameter }\n}\n","import { ast } from '@kubb/ast'\nimport { SCHEMA_REF_PREFIX } from './constants.ts'\n\n/**\n * Collects inline enums to lift to the top level, keyed by the name the parser derived for them\n * (e.g. `PetStatusEnum`). An enum already defined as a top-level component is left as-is, and a\n * name that recurs maps to the first definition so each name yields one shared type.\n */\nexport function collectInlineEnums(roots: ReadonlyArray<ast.Node>, topLevelNames: ReadonlySet<string>): Map<string, ast.SchemaNode> {\n const promoted = new Map<string, ast.SchemaNode>()\n\n for (const root of roots) {\n const isSchemaRoot = root.kind === 'Schema'\n for (const node of ast.collect<ast.SchemaNode>(root, { schema: (schemaNode) => schemaNode })) {\n if (node.type !== 'enum' || !node.name) continue\n // Skip a top-level enum component (it is already its own type) and any enum whose name a\n // component already owns.\n if (isSchemaRoot && node === root) continue\n if (topLevelNames.has(node.name)) continue\n if (!promoted.has(node.name)) promoted.set(node.name, { ...node, optional: undefined, nullish: undefined })\n }\n }\n\n return promoted\n}\n\n/**\n * Replaces every promoted inline enum in `node` with a `ref` to its lifted definition, keeping the\n * occurrence's usage-slot and documentation fields.\n */\nexport function refPromotedEnums<T extends ast.Node>(node: T, promoted: ReadonlyMap<string, ast.SchemaNode>): T {\n if (promoted.size === 0) return node\n\n return ast.transform(node, {\n schema(schemaNode) {\n if (schemaNode.type !== 'enum' || !schemaNode.name || !promoted.has(schemaNode.name)) return undefined\n\n return ast.factory.createSchema({\n type: 'ref',\n name: schemaNode.name,\n ref: `${SCHEMA_REF_PREFIX}${schemaNode.name}`,\n optional: schemaNode.optional,\n nullish: schemaNode.nullish,\n readOnly: schemaNode.readOnly,\n writeOnly: schemaNode.writeOnly,\n deprecated: schemaNode.deprecated,\n description: schemaNode.description,\n default: schemaNode.default,\n examples: schemaNode.examples,\n })\n },\n }) as T\n}\n","import { resolveRefName } from '@kubb/ast'\nimport type { ast } from '@kubb/ast'\nimport { Diagnostics } from '@kubb/core'\nimport { isHandledFormat } from './emit/schemaShape.ts'\n\n/**\n * Scans one freshly converted top-level schema in a single walk, so the post-convert pass never\n * sweeps the same nodes twice. It reports the advisory diagnostics (`KUBB_UNSUPPORTED_FORMAT`,\n * `KUBB_DEPRECATED`) and returns the names of every schema the node references, ready to feed the\n * circular-dependency graph.\n *\n * Walks the node the parser produced, threading the RFC 6901 pointer as it descends so a nested\n * field reports against its full path (`#/components/schemas/Pet/properties/owner/properties/name`).\n * Refs are recorded by name and not followed, so the resolved schema is reported under its own walk.\n * Reports land in the active build run, are a no-op outside one, and repeats are deduped by the build.\n */\nexport function scanSchema({ node, name }: { node: ast.SchemaNode; name: string }): Set<string> {\n const refs = new Set<string>()\n visit(node, `#/components/schemas/${escapePointerToken(name)}`, refs)\n return refs\n}\n\n/**\n * Escapes a single JSON pointer reference token per RFC 6901 (`~` → `~0`, `/` → `~1`), so a\n * property name with those characters maps to a distinct pointer instead of colliding in the dedupe.\n */\nfunction escapePointerToken(token: string): string {\n return token.replace(/~/g, '~0').replace(/\\//g, '~1')\n}\n\nfunction visit(node: ast.SchemaNode, pointer: string, refs: Set<string>): void {\n if (node.type === 'ref') {\n const refName = resolveRefName(node)\n if (refName) refs.add(refName)\n }\n\n if (node.deprecated) {\n Diagnostics.report({\n code: Diagnostics.code.deprecated,\n severity: 'info',\n message: 'This schema is marked as deprecated.',\n location: { kind: 'schema', pointer },\n })\n }\n\n if (typeof node.format === 'string' && !isHandledFormat(node.format)) {\n Diagnostics.report({\n code: Diagnostics.code.unsupportedFormat,\n severity: 'warning',\n message: `Kubb does not map the format \"${node.format}\" to a specific type, so it falls back to the base type.`,\n help: `Use a format Kubb supports, or handle \"${node.format}\" with a custom parser or plugin.`,\n location: { kind: 'schema', pointer },\n })\n }\n\n if (node.type === 'object') {\n for (const property of node.properties) {\n visit(property.schema, `${pointer}/properties/${escapePointerToken(property.name)}`, refs)\n }\n if (node.additionalProperties && typeof node.additionalProperties === 'object') {\n visit(node.additionalProperties, `${pointer}/additionalProperties`, refs)\n }\n return\n }\n\n if (node.type === 'array') {\n for (const item of node.items ?? []) {\n visit(item, `${pointer}/items`, refs)\n }\n return\n }\n\n if (node.type === 'tuple') {\n // Each tuple position has its own pointer, so index them. A shared `/items` would collapse\n // distinct diagnostics in the dedupe.\n for (const [index, item] of (node.items ?? []).entries()) {\n visit(item, `${pointer}/items/${index}`, refs)\n }\n return\n }\n\n if (node.type === 'union' || node.type === 'intersection') {\n for (const [index, member] of (node.members ?? []).entries()) {\n visit(member, `${pointer}/members/${index}`, refs)\n }\n }\n}\n","import { ast, findCircularSchemasFromGraph, narrowSchema } from '@kubb/ast'\nimport { createAdapter } from '@kubb/core'\nimport type { AdapterSource } from '@kubb/core'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { buildDiscriminatorChildMap, patchDiscriminatorNode } from './emit/discriminator/propagate.ts'\nimport type { DiscriminatorTarget } from './emit/discriminator/propagate.ts'\nimport { assertInputExists } from './load/source.ts'\nimport { assertDocument, parseDocument, parseFromConfig, validateDocument } from './load/normalize.ts'\nimport { getSchemas } from './model/components.ts'\nimport { resolveBaseUrl } from './model/server.ts'\nimport { getOperations } from './operation.ts'\nimport { createSchemaParser } from './parser.ts'\nimport { collectInlineEnums, refPromotedEnums } from './promoteEnums.ts'\nimport { createRefs } from './refs.ts'\nimport { scanSchema } from './schemaDiagnostics.ts'\nimport type { AdapterOas, Document, SchemaObject } from './types.ts'\n\n/**\n * The `name` of `@kubb/adapter-oas`, used to identify this adapter in a Kubb config.\n */\nexport const adapterOasName = 'oas' satisfies AdapterOas['name']\n\n/**\n * Default Kubb adapter for OpenAPI 2.0, 3.0, and 3.1 specifications. Reads the\n * spec from `input` (a file path, URL, inline content, or parsed object), validates\n * it, resolves the base URL, and converts every schema and operation into the\n * universal AST that every downstream plugin consumes.\n *\n * Configure once on `defineConfig`. The adapter's choices (date representation,\n * integer width, server URL) apply to every plugin in the build.\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 * server: { index: 0 },\n * discriminator: 'propagate',\n * dateType: 'date',\n * }),\n * plugins: [pluginTs()],\n * })\n * ```\n */\nexport const adapterOas = createAdapter<AdapterOas>((options) => {\n const {\n validate = true,\n contentType,\n server,\n discriminator = 'preserve',\n enums = 'inline',\n dateType = DEFAULT_PARSER_OPTIONS.dateType,\n integerType = DEFAULT_PARSER_OPTIONS.integerType,\n unknownType = DEFAULT_PARSER_OPTIONS.unknownType,\n enumSuffix = DEFAULT_PARSER_OPTIONS.enumSuffix,\n emptySchemaType = unknownType || DEFAULT_PARSER_OPTIONS.emptySchemaType,\n } = options\n\n const parserOptions: ast.ParserOptions = {\n ...DEFAULT_PARSER_OPTIONS,\n dateType,\n integerType,\n unknownType,\n emptySchemaType,\n enumSuffix,\n }\n\n let parsedDocument: Document | null = null\n\n // One cache per source: reusing one adapter instance across a `defineConfig` array must parse\n // each config's spec instead of replaying the first one, and a repeat `.parse()` call for the\n // same source must not redo the work. The `$ref` memo lives inside the `Refs` instance created\n // fresh for each document, scoped to this one pass.\n const inputCache = new WeakMap<AdapterSource, Promise<ast.InputNode>>()\n\n // Parses every schema and operation once. Ref aliases and discriminator children are\n // resolved from the schemas already parsed in this same pass rather than re-parsed.\n function parseInput({\n document,\n refs,\n schemas,\n parser,\n }: {\n document: Document\n refs: ReturnType<typeof createRefs>\n schemas: Record<string, SchemaObject>\n parser: ReturnType<typeof createSchemaParser>\n }): ast.InputNode {\n const { parseSchema, parseOperation } = parser\n\n const parsedByName = new Map<string, ast.SchemaNode>()\n const refAliasMap = new Map<string, ast.SchemaNode>()\n const enumNames: Array<string> = []\n const discriminatorParentNodes: Array<ast.SchemaNode> = []\n // Built from the same walk that reports diagnostics: each schema maps to the names it references,\n // so circular detection reads this graph instead of sweeping the nodes again.\n const refGraph = new Map<string, Set<string>>()\n\n for (const [name, schema] of Object.entries(schemas)) {\n const node = parseSchema({ schema, name }, parserOptions)\n parsedByName.set(name, node)\n const refs = scanSchema({ node, name })\n if (node.name) refGraph.set(node.name, refs)\n if (node.type === 'ref' && node.name && node.name !== name) {\n refAliasMap.set(name, node)\n }\n if (narrowSchema(node, 'enum') && node.name) {\n enumNames.push(node.name)\n }\n if (discriminator === 'propagate' && (schema.oneOf ?? schema.anyOf) && schema.discriminator?.propertyName) {\n discriminatorParentNodes.push(node)\n }\n }\n\n const circularNames = [...findCircularSchemasFromGraph(refGraph)]\n const discriminatorChildMap: Map<string, DiscriminatorTarget> | null =\n discriminatorParentNodes.length > 0 ? buildDiscriminatorChildMap(discriminatorParentNodes) : null\n\n const operationNodes: Array<ast.OperationNode> = []\n for (const operation of getOperations(document, refs)) {\n const operationNode = parseOperation(parserOptions, operation)\n if (operationNode) operationNodes.push(operationNode)\n }\n\n let promotedEnums: Map<string, ast.SchemaNode> | null = null\n if (enums === 'root') {\n promotedEnums = collectInlineEnums([...parsedByName.values(), ...operationNodes], new Set(Object.keys(schemas)))\n for (const name of promotedEnums.keys()) enumNames.push(name)\n }\n\n const schemaNodes: Array<ast.SchemaNode> = promotedEnums ? [...promotedEnums.values()] : []\n for (const name of Object.keys(schemas)) {\n const alias = refAliasMap.get(name)\n\n let node: ast.SchemaNode\n if (alias?.name && parsedByName.has(alias.name)) {\n node = { ...parsedByName.get(alias.name)!, name }\n } else {\n const parsed = parsedByName.get(name)!\n const child = discriminatorChildMap?.get(name)\n node = child ? patchDiscriminatorNode(parsed, child) : parsed\n }\n\n schemaNodes.push(promotedEnums ? refPromotedEnums(node, promotedEnums) : node)\n }\n\n const operations = promotedEnums ? operationNodes.map((node) => refPromotedEnums(node, promotedEnums!)) : operationNodes\n\n return ast.factory.createInput({\n schemas: schemaNodes,\n operations,\n meta: {\n title: document.info?.title,\n description: document.info?.description,\n version: document.info?.version,\n baseURL: resolveBaseUrl({ document, server }),\n circularNames,\n enumNames,\n },\n })\n }\n\n return {\n name: adapterOasName,\n get options() {\n return {\n validate,\n contentType,\n server,\n discriminator,\n enums,\n dateType,\n integerType,\n unknownType,\n emptySchemaType,\n enumSuffix,\n }\n },\n get document() {\n return parsedDocument\n },\n async validate(input, options) {\n await assertInputExists(input)\n const document = await parseDocument(input)\n assertDocument(document)\n await validateDocument(document, options)\n },\n async parse(source) {\n const cached = inputCache.get(source)\n if (cached) return cached\n\n const promise = (async () => {\n const document = await parseFromConfig(source)\n assertDocument(document)\n if (validate) await validateDocument(document)\n parsedDocument = document\n\n const refs = createRefs(document)\n const { schemas, renames } = getSchemas(document, { contentType }, refs)\n const parser = createSchemaParser({ document, refs, contentType, renames })\n\n return parseInput({ document, refs, schemas, parser })\n })()\n inputCache.set(source, promise)\n return promise\n },\n }\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAa,yBAAyB;CACpC,UAAU;CACV,aAAa;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KAAU;KAAM;KAAS,QAF9B,mBAAmB;MAAE;MAAU;MAAM;MAAa;KAAQ,CAEvB;IAAE,CAAC;GACvD,EAAA,CAAG;GACH,WAAW,IAAI,QAAQ,OAAO;GAC9B,OAAO;EACT;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["ast","access","readFile","Diagnostics","parse","bundle","upgrade","parse","path","Diagnostics","Diagnostics","ast","ast","extractRefName","macroDiscriminatorEnum","extractRefName","ast","mergeAdjacentObjectsLazy","macroSimplifyUnion","ast","ast","macroEnumName","childName","enumPropName","macroDiscriminatorEnum","Diagnostics","ast","ast","resolveRefName","Diagnostics","createAdapter","narrowSchema","findCircularSchemasFromGraph","ast"],"sources":["../src/constants.ts","../src/emit/discriminator/propagate.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/errors.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/fs.ts","../src/load/source.ts","../src/load/normalize.ts","../src/oas.ts","../src/model/components.ts","../src/model/server.ts","../src/operation.ts","../src/emit/schemaShape.ts","../src/emit/createNode.ts","../src/emit/discriminator/preserve.ts","../src/emit/converters/composition.ts","../src/emit/converters/scalar.ts","../src/emit/converters/structural.ts","../src/emit/parseSchema.ts","../src/refs.ts","../src/model/operations.ts","../src/parser.ts","../src/promoteEnums.ts","../src/schemaDiagnostics.ts","../src/adapter.ts"],"sourcesContent":["import type { ast } from '@kubb/ast'\n\n/**\n * Default parser options applied when no explicit options are provided.\n */\nexport const DEFAULT_PARSER_OPTIONS = {\n dateType: 'string',\n integerType: 'bigint',\n unknownType: 'unknown',\n emptySchemaType: 'unknown',\n enumSuffix: 'enum',\n} as const satisfies ast.ParserOptions\n\n/**\n * JSON-Pointer prefix for schemas declared under `components.schemas` in an OpenAPI document.\n *\n * Used when building or parsing `$ref` strings.\n *\n * @example\n * ```ts\n * `${SCHEMA_REF_PREFIX}Pet` // '#/components/schemas/Pet'\n * ```\n */\nexport const SCHEMA_REF_PREFIX = '#/components/schemas/' as const\n\n/**\n * HTTP methods that count as operations on an OpenAPI path item. Other keys\n * (`parameters`, `summary`, `$ref`, vendor extensions) are skipped when iterating operations.\n */\nexport const SUPPORTED_METHODS: ReadonlySet<string> = new Set(['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'])\n\n/**\n * Set of JSON Schema keywords that prevent a schema fragment from being inlined during `allOf` flattening.\n *\n * A fragment that contains any of these keys carries structural meaning of its own and must stay as a separate\n * intersection member rather than being merged into the parent.\n */\nexport const structuralKeys = new Set(['properties', 'items', 'additionalProperties', 'oneOf', 'anyOf', 'allOf', 'not'] as const)\n\n/**\n * Formats `convertFormat` maps to a dedicated type without going through `formatMap`:\n * `int64`, `uint64` and the date/time family. Keep this in sync with the `convertFormat`\n * special-cases in `parser.ts`. `isHandledFormat` reads it so the\n * `KUBB_UNSUPPORTED_FORMAT` diagnostic and the parser agree on what is handled.\n */\nexport const specialCasedFormats: ReadonlySet<string> = new Set(['int64', 'uint64', 'date-time', 'date', 'time'])\n\n/**\n * Formats that describe a number, whether they resolve through `formatMap` or through the\n * `convertFormat` special cases. On a `type: 'string'` schema these do not make the value a\n * number: gRPC-gateway and other ProtoJSON producers send 64-bit integers as JSON strings.\n *\n * @see https://protobuf.dev/programming-guides/json/#int64-strings\n */\nexport const numericFormats: ReadonlySet<string> = new Set(['int32', 'int64', 'uint64', 'float', 'double'])\n\n/**\n * Static map from OAS `format` strings to Kubb `SchemaType` values.\n *\n * Only formats whose AST type differs from the OAS `type` field appear here.\n * Formats that depend on runtime options (`int64`, `date-time`, `date`, `time`) are handled\n * separately in the parser. `ipv4` and `ipv6` map to their own dedicated schema types. `hostname`\n * and `idn-hostname` map to `'url'` as the closest generic string-format type.\n */\nexport const formatMap = {\n uuid: 'uuid',\n email: 'email',\n 'idn-email': 'email',\n uri: 'url',\n 'uri-reference': 'url',\n url: 'url',\n ipv4: 'ipv4',\n ipv6: 'ipv6',\n hostname: 'url',\n 'idn-hostname': 'url',\n binary: 'blob',\n byte: 'blob',\n // Numeric formats override the OAS `type` because format is more specific.\n // See https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.7\n int32: 'integer',\n float: 'number',\n double: 'number',\n} as const satisfies Record<string, ast.SchemaType>\n\n/**\n * Vendor extension keys that attach human-readable labels to enum values, checked in priority order.\n */\nexport const enumExtensionKeys = ['x-enumNames', 'x-enum-varnames'] as const\n\n/**\n * Vendor extension keys that attach human-readable descriptions to enum values, checked in priority order.\n */\nexport const enumDescriptionKeys = ['x-enumDescriptions', 'x-enum-descriptions'] as const\n","import { ast, type SchemaNodeByType } from '@kubb/ast'\n\nexport type DiscriminatorTarget = {\n propertyName: string\n enumValues: Array<string | number | boolean>\n}\n\n/**\n * Maps each child schema name to its discriminator patch data by scanning the given\n * top-level AST schema nodes for union schemas that carry a `discriminatorPropertyName`.\n *\n * Called on a small pre-parsed subset of schemas (only the discriminator parents)\n * rather than on all schemas at once.\n */\nexport function buildDiscriminatorChildMap(schemas: Array<ast.SchemaNode>): Map<string, DiscriminatorTarget> {\n const childMap = new Map<string, DiscriminatorTarget>()\n\n for (const schema of schemas) {\n // Case 1: top-level schema is a union (oneOf/anyOf with discriminator)\n // Case 2: top-level schema is an intersection wrapping a union (oneOf/anyOf + shared properties)\n let unionNode = ast.narrowSchema(schema, 'union')\n\n if (!unionNode) {\n const intersectionMembers = ast.narrowSchema(schema, 'intersection')?.members\n if (intersectionMembers) {\n for (const m of intersectionMembers) {\n const u = ast.narrowSchema(m, 'union')\n if (u) {\n unionNode = u\n break\n }\n }\n }\n }\n\n if (!unionNode?.discriminatorPropertyName || !unionNode.members) continue\n\n const { discriminatorPropertyName, members } = unionNode\n\n for (const member of members) {\n // Members with a discriminant value are intersections: [RefSchemaNode, ObjectSchemaNode]\n const intersectionNode = ast.narrowSchema(member, 'intersection')\n if (!intersectionNode?.members) continue\n\n let refNode: SchemaNodeByType['ref'] | null = null\n let objNode: SchemaNodeByType['object'] | null = null\n\n for (const m of intersectionNode.members) {\n refNode ??= ast.narrowSchema(m, 'ref')\n objNode ??= ast.narrowSchema(m, 'object')\n }\n\n if (!refNode?.name || !objNode) continue\n\n const prop = objNode.properties.find((p) => p.name === discriminatorPropertyName)\n const enumNode = prop ? ast.narrowSchema(prop.schema, 'enum') : null\n if (!enumNode?.enumValues?.length) continue\n\n const enumValues = enumNode.enumValues.filter((v): v is string | number | boolean => v !== null)\n if (!enumValues.length) continue\n\n const existing = childMap.get(refNode.name)\n if (!existing) {\n childMap.set(refNode.name, { propertyName: discriminatorPropertyName, enumValues: [...new Set(enumValues)] })\n continue\n }\n existing.enumValues = [...new Set([...existing.enumValues, ...enumValues])]\n }\n }\n\n return childMap\n}\n\n/**\n * Patches a single top-level `SchemaNode` with its discriminator entry (adds or replaces\n * the discriminant property).\n *\n * A child declared with `allOf` parses to an intersection rather than an object, so the\n * discriminant is intersected on as an extra member instead.\n */\nexport function patchDiscriminatorNode(node: ast.SchemaNode, entry: { propertyName: string; enumValues: Array<string | number | boolean> }): ast.SchemaNode {\n const { propertyName, enumValues } = entry\n const enumSchema = ast.factory.createSchema({ type: 'enum', enumValues })\n const newProp = ast.factory.createProperty({ name: propertyName, required: true, schema: enumSchema })\n\n const objectNode = ast.narrowSchema(node, 'object')\n if (objectNode) {\n const existingIdx = objectNode.properties.findIndex((p) => p.name === propertyName)\n const newProperties = existingIdx >= 0 ? objectNode.properties.map((p, i) => (i === existingIdx ? newProp : p)) : [...objectNode.properties, newProp]\n\n return { ...objectNode, properties: newProperties }\n }\n\n const intersectionNode = ast.narrowSchema(node, 'intersection')\n if (!intersectionNode?.members) return node\n\n const discriminantNode = ast.factory.createSchema({ type: 'object', primitive: 'object', properties: [newProp] })\n const patchedIdx = intersectionNode.members.findIndex((member) => ast.narrowSchema(member, 'object')?.properties.some((p) => p.name === propertyName))\n\n const newMembers =\n patchedIdx >= 0\n ? intersectionNode.members.map((member, i) => (i === patchedIdx ? patchDiscriminatorNode(member, entry) : member))\n : [...intersectionNode.members, discriminantNode]\n\n return { ...intersectionNode, members: newMembers }\n}\n","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 * Thrown when one or more errors occur during a Kubb build.\n * Carries the full list of underlying errors on `errors`.\n *\n * @example\n * ```ts\n * throw new BuildError('Build failed', { errors: [err1, err2] })\n * ```\n */\nexport class BuildError extends Error {\n errors: Array<Error>\n\n constructor(message: string, options: { cause?: Error; errors: Array<Error> }) {\n super(message, { cause: options.cause })\n this.name = 'BuildError'\n this.errors = options.errors\n }\n}\n\n/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new BuildError('Build failed', { cause: toError(err), errors: [] })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Extracts the `.cause` of an `Error` as an `Error`, or `undefined` when absent or not an `Error`.\n *\n * @example\n * ```ts\n * const cause = toCause(buildError) // Error | undefined\n * ```\n */\nexport function toCause(error: Error): Error | undefined {\n return error.cause instanceof Error ? error.cause : undefined\n}\n","/**\n * Name of the JavaScript runtime executing the current process.\n */\ntype RuntimeName = 'bun' | 'deno' | 'node'\n\n/**\n * Detects the JavaScript runtime executing the current process and exposes its name and version.\n *\n * Prefer the shared {@link runtime} instance over constructing your own.\n */\nclass Runtime {\n /**\n * `true` when the current process is running under Bun.\n *\n * Detection keys off the global `Bun` object rather than `process.versions`,\n * because Bun polyfills `process.versions.node` for Node compatibility and would\n * otherwise look like Node.\n *\n * @example\n * ```ts\n * if (runtime.isBun) {\n * await Bun.write(path, data)\n * }\n * ```\n */\n get isBun(): boolean {\n return typeof Bun !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Deno.\n */\n get isDeno(): boolean {\n return typeof (globalThis as { Deno?: unknown }).Deno !== 'undefined'\n }\n\n /**\n * `true` when the current process is running under Node.\n *\n * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.\n */\n get isNode(): boolean {\n return !this.isBun && !this.isDeno && typeof process !== 'undefined' && process.versions?.node != null\n }\n\n /**\n * Name of the runtime executing the current process.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\n get name(): RuntimeName {\n if (this.isBun) return 'bun'\n if (this.isDeno) return 'deno'\n\n return 'node'\n }\n\n /**\n * Version of the active runtime, or an empty string when it cannot be read.\n *\n * @example\n * ```ts\n * runtime.version // '1.3.11' under Bun, '22.22.2' under Node\n * ```\n */\n get version(): string {\n if (this.isBun) return process.versions.bun ?? ''\n if (this.isDeno) return (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? ''\n\n return process.versions?.node ?? ''\n }\n}\n\n/**\n * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.\n */\nexport const runtime = new Runtime()\n","import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { camelCase } from './casing.ts'\nimport { runtime } from './runtime.ts'\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 if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\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 * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\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 destructive operations: before wiping an output directory, check that it does not contain\n * the project root, otherwise a `clean` would delete `kubb.config` and every source file.\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) return true\n\n const rel = relative(resolvedParent, resolvedPath)\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\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 * 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 earlier segment, applies `caseLast` to the final 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 *\n * @example PascalCase the final segment\n * `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`\n *\n * @example Suffix applied to the final segment only\n * `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`\n */\nexport function toFilePath(name: string, caseLast: (part: string) => string = camelCase): string {\n const parts = name.split(/\\.(?=[a-zA-Z])/)\n return parts\n .map((part, i) => (i === parts.length - 1 ? caseLast(part) : camelCase(part)))\n .filter(Boolean)\n .join('/')\n}\n","import { exists, getErrorMessage, read } from '@internals/utils'\nimport { Diagnostics } from '@kubb/core'\nimport { parse } from 'yaml'\n\nconst urlRegExp = /^https?:\\/+/i\n\n/**\n * Node reports every connection failure as `TypeError: fetch failed` and keeps the useful part\n * (`connect ECONNREFUSED 127.0.0.1:8000`) on `cause`, one level deeper again when a host resolves\n * to several addresses and the attempts collect into an `AggregateError`.\n */\nfunction describeFetchFailure(error: unknown): string {\n if (error instanceof AggregateError && error.errors.length > 0) {\n return describeFetchFailure(error.errors[0])\n }\n if (error instanceof Error && error.cause instanceof Error) {\n return describeFetchFailure(error.cause) || error.message\n }\n\n return getErrorMessage(error)\n}\n\nfunction helpForStatus(status: number): string {\n if (status === 401 || status === 403) {\n return 'The server refused the request. Kubb sends no credentials, so serve the document without authentication or download it and set `input` to the local file.'\n }\n if (status === 404) {\n return 'Check the URL. Open it in a browser or with `curl` to confirm it serves the OpenAPI document.'\n }\n if (status >= 500) {\n return 'The server failed while serving the document. Check that it is healthy, then run Kubb again.'\n }\n\n return 'Open the URL in a browser or with `curl` to see what the server returns, then point `input` at a URL that serves the OpenAPI document.'\n}\n\nasync function fetchSource(url: URL): Promise<Response> {\n try {\n return await fetch(url)\n } catch (error) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputUnreachable,\n severity: 'error',\n message: `Cannot reach ${url.href}: ${describeFetchFailure(error)}`,\n help: '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 location: { kind: 'config' },\n cause: error instanceof Error ? error : undefined,\n })\n }\n}\n\nasync function readSource(sourcePath: string): Promise<string> {\n if (urlRegExp.test(sourcePath)) {\n // api-ref-bundler joins relative refs with posix normalization, collapsing `https://` to\n // `https:/`. The WHATWG URL parser restores the double slash.\n const url = new URL(sourcePath)\n const response = await fetchSource(url)\n\n if (!response.ok) {\n const status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status)\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputRequestFailed,\n severity: 'error',\n message: `The server at ${url.href} answered with HTTP ${status} instead of the OpenAPI document.`,\n help: helpForStatus(response.status),\n location: { kind: 'config' },\n })\n }\n\n return response.text()\n }\n\n return read(sourcePath)\n}\n\n/**\n * Reads and parses one source file or URL referenced during bundling: YAML/JSON is parsed into an\n * object, Markdown is returned as-is (bundled inline rather than dereferenced).\n *\n * JSON is valid YAML, so `yaml`'s `parse` handles both, but its general-purpose parser (comments,\n * anchors, block scalars, multi-document streams) does much more work than `JSON.parse` needs to.\n * `JSON.parse` runs first and fails fast on the first non-JSON character, so a real YAML document\n * falls through to `parse` at negligible cost.\n */\nexport async function resolveSource(sourcePath: string): Promise<object | string> {\n const data = await readSource(sourcePath)\n\n if (sourcePath.toLowerCase().endsWith('.md')) {\n return data\n }\n\n try {\n return JSON.parse(data) as object\n } catch {\n return parse(data) as object\n }\n}\n\n/**\n * Throws a coded `KUBB_INPUT_NOT_FOUND` diagnostic when a local input path does not exist.\n * URLs are skipped: a remote input reports `KUBB_INPUT_REQUEST_FAILED` or `KUBB_INPUT_UNREACHABLE`\n * from the request itself. A malformed but readable file is left for `parseDocument` to surface\n * its parse error instead.\n */\nexport async function assertInputExists(input: string): Promise<void> {\n if (URL.canParse(input)) {\n return\n }\n if (!(await exists(input))) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputNotFound,\n severity: 'error',\n message: `Cannot read the file set as \\`input\\` (or via \\`kubb generate PATH\\`): ${input}`,\n help: 'Check that the path exists and is readable, then set it as `input` or pass it as `kubb generate PATH`.',\n location: { kind: 'config' },\n })\n }\n}\n\nexport { urlRegExp }\n","import path from 'node:path'\nimport { Diagnostics } from '@kubb/core'\nimport type { AdapterSource } from '@kubb/core'\nimport { upgrade } from '@scalar/openapi-upgrader'\nimport { bundle } from 'api-ref-bundler'\nimport { parse } from 'yaml'\nimport type { Document } from '../types.ts'\nimport { assertInputExists, resolveSource, urlRegExp } from './source.ts'\n\n/**\n * True when `node` contains a `$ref` pointing outside the current document (a relative path,\n * absolute path, or URL). An internal `#/...` fragment does not count.\n *\n * `Object.values` reads array elements and object property values alike, so the same recursion\n * walks both without a separate array branch.\n */\nexport function hasExternalRef(node: unknown): boolean {\n if (!node || typeof node !== 'object') {\n return false\n }\n\n const ref = (node as { $ref?: unknown }).$ref\n if (typeof ref === 'string' && !ref.startsWith('#')) {\n return true\n }\n\n return Object.values(node).some(hasExternalRef)\n}\n\n/**\n * Bundles a multi-file OpenAPI document into a single document via `api-ref-bundler`.\n *\n * External file schemas are hoisted into named `components.schemas` entries, so a property\n * pointing at `./schemas/User.yaml` ends up referencing `#/components/schemas/User`. Generators\n * can then emit a named type with an import instead of inlining the shape. Sources are read with\n * the Bun-aware `read` util for local YAML and JSON files, and with `fetch` for HTTP(S) URLs.\n *\n * A document with no `$ref` outside itself has nothing to bundle, so it skips `api-ref-bundler`\n * and returns as parsed. `bundle` only rewrites external refs into internal ones; on an\n * all-internal document it is a no-op that still walks the whole tree to confirm that, which\n * costs real time on a large spec.\n *\n * @example Local file\n * `const document = await bundleDocument('./openapi.yaml')`\n *\n * @example Remote URL\n * `const document = await bundleDocument('https://example.com/openapi.yaml')`\n */\nexport async function bundleDocument(pathOrUrl: string): Promise<Document> {\n const cache = new Map<string, Promise<object | string>>()\n\n const resolver = (sourcePath: string) => {\n // api-ref-bundler refers to the same URL as both `https://` and the posix-normalized\n // `https:/`, so cache on the canonical href to fetch each source once.\n const key = urlRegExp.test(sourcePath) ? new URL(sourcePath).href : sourcePath\n const cached = cache.get(key)\n if (cached) {\n return cached\n }\n\n const result = resolveSource(sourcePath)\n cache.set(key, result)\n return result\n }\n\n // api-ref-bundler swallows resolver errors and leaves refs unresolved, so surface an\n // unreadable input document as a hard error before bundling.\n const root = await resolver(pathOrUrl)\n\n if (typeof root === 'object' && root !== null && !hasExternalRef(root)) {\n return root as Document\n }\n\n return (await bundle(pathOrUrl, resolver)) as Document\n}\n\n/**\n * Loads and bundles an OpenAPI document, returning the raw `Document`.\n *\n * A string is a file path or URL: it is bundled via `api-ref-bundler`, hoisting external file\n * schemas into named `components.schemas` entries so generators can emit named types and imports.\n * An object is treated as an already-parsed document. Swagger 2.0 and OpenAPI 3.0 documents are\n * up-converted to OpenAPI 3.1 via `@scalar/openapi-upgrader`.\n *\n * @example\n * ```ts\n * const document = await parseDocument('./openapi.yaml')\n * const document = await parseDocument(rawDocumentObject)\n * ```\n */\nexport async function parseDocument(pathOrApi: string | Document): Promise<Document> {\n if (typeof pathOrApi === 'string') {\n const bundled = await bundleDocument(pathOrApi)\n\n return parseDocument(bundled)\n }\n\n // `upgrade` chains Swagger 2.0 -> 3.0 -> 3.1, leaving documents already on 3.1 untouched.\n return upgrade(pathOrApi, '3.1') as Document\n}\n\n/**\n * Creates a `Document` from an `AdapterSource`.\n *\n * - `{ type: 'path' }` resolves and bundles a local file path or remote URL.\n * - `{ type: 'data' }` parses an inline string (YAML/JSON) or raw object.\n *\n * @example\n * ```ts\n * const document = await parseFromConfig({ type: 'path', path: './openapi.yaml' })\n * const document = await parseFromConfig({ type: 'data', data: '{\"openapi\":\"3.0.0\",...}' })\n * ```\n */\nexport async function parseFromConfig(source: AdapterSource): Promise<Document> {\n if (source.type === 'data') {\n // Inline data is a parsed object or a raw YAML/JSON string. Parse the string here so\n // `parseDocument` never mistakes inline content for a file path. `parse` also handles JSON.\n const data = typeof source.data === 'string' ? parse(source.data) : structuredClone(source.data)\n return parseDocument(data as Document)\n }\n\n // type === 'path'\n if (URL.canParse(source.path)) {\n return parseDocument(source.path)\n }\n\n const resolved = path.resolve(path.dirname(source.path), source.path)\n await assertInputExists(resolved)\n return parseDocument(resolved)\n}\n\n/**\n * Asserts the parsed input is an OpenAPI or Swagger document.\n *\n * {@link validateDocument} keeps spec violations non-fatal so imperfect but usable documents still\n * generate. That leniency also swallowed input that is not a document at all, which then produced\n * an empty build with a success exit code. A missing version field is the one failure that cannot\n * be a usable document, so it is fatal regardless of the `validate` option.\n */\nexport function assertDocument(document: Document): void {\n if (document && ('openapi' in document || 'swagger' in document)) return\n\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidDocument,\n severity: 'error',\n message: 'The resolved `input` is not an OpenAPI or Swagger document: it declares no `openapi` or `swagger` version.',\n help: 'Point `input` at a document that declares `openapi` or `swagger`. If you pass an object, pass the spec itself rather than a wrapper such as `{ path }` or `{ data }`.',\n location: { kind: 'config' },\n })\n}\n\n/**\n * Validates an OpenAPI document using `@readme/openapi-parser` with colorized error output.\n *\n * @example\n * ```ts\n * await validateDocument(document)\n * ```\n */\nexport async function validateDocument(document: Document, { throwOnError = false }: { throwOnError?: boolean } = {}): Promise<void> {\n // The heaviest dependency in the package, and every config importing `@kubb/adapter-oas` would\n // pay for it even with `validate` off.\n const { compileErrors, validate } = await import('@readme/openapi-parser')\n\n try {\n // `validate` dereferences its input in place, so clone to keep the cached document intact.\n const result = await validate(structuredClone(document), {\n validate: {\n errors: { colorize: true },\n },\n })\n\n if (!result.valid) {\n throw new Error(compileErrors(result))\n }\n } catch (error) {\n if (throwOnError) {\n throw error\n }\n\n // Validation failures are non-fatal, mirror plugin-oas behavior\n }\n}\n","import type { DiscriminatorObject, ReferenceObject, SchemaObject } from './types.ts'\n\n/**\n * Returns `true` when a schema should be treated as nullable.\n *\n * Recognizes all nullable signals across OAS versions: `nullable: true` (OAS 3.0),\n * `x-nullable: true` (vendor extension), `type: 'null'`, and `type: ['null', ...]` (OAS 3.1).\n */\nexport function isNullable(schema?: SchemaObject & { 'x-nullable'?: boolean }): boolean {\n const explicitNullable = schema?.nullable ?? schema?.['x-nullable']\n if (explicitNullable === true) return true\n\n const schemaType = schema?.type\n if (schemaType === 'null') return true\n if (Array.isArray(schemaType)) return schemaType.includes('null')\n\n return false\n}\n\n/**\n * Returns `true` when `obj` is an OpenAPI `$ref` pointer object.\n */\nexport function isReference(obj?: unknown): obj is ReferenceObject {\n return !!obj && typeof obj === 'object' && '$ref' in obj\n}\n\n/**\n * Returns `true` when `obj` is a schema with a structured OAS 3.x `discriminator` object,\n * excluding the Swagger 2 string form.\n */\nexport function isDiscriminator(obj?: unknown): obj is SchemaObject & { discriminator: DiscriminatorObject } {\n const record = obj as Record<string, unknown>\n return !!obj && !!record['discriminator'] && typeof record['discriminator'] !== 'string'\n}\n\n/**\n * Returns `true` when a schema is a binary payload: an octet-stream string body.\n */\nexport function isBinary(schema: SchemaObject): boolean {\n return schema.type === 'string' && schema.contentMediaType === 'application/octet-stream'\n}\n\n/**\n * MIME type fragments that mark a media type as JSON-like.\n *\n * A content type is JSON when it contains any of these substrings. The `+json` entry catches\n * structured-syntax suffixes such as `application/vnd.api+json`.\n */\nconst jsonMimeFragments = ['application/json', 'application/x-json', 'text/json', 'text/x-json', '+json'] as const\n\n/**\n * Returns `true` when a media type string is JSON-like.\n *\n * @example\n * ```ts\n * isJsonMimeType('application/json') // true\n * isJsonMimeType('application/vnd.api+json') // true\n * isJsonMimeType('multipart/form-data') // false\n * ```\n */\nexport function isJsonMimeType(mimeType: string): boolean {\n return jsonMimeFragments.some((fragment) => mimeType.includes(fragment))\n}\n\n/**\n * Picks a media-type entry from a `content` map: the first JSON-like media type, falling back to\n * the first declared one. Returns `false` when `content` has no entries.\n *\n * @example\n * ```ts\n * pickContentEntry({ 'application/xml': xmlEntry, 'application/json': jsonEntry })\n * // ['application/json', jsonEntry]\n * ```\n */\nexport function pickContentEntry<T>(content: Record<string, T>): [string, T] | false {\n const mediaTypes = Object.keys(content)\n const available = mediaTypes.find(isJsonMimeType) ?? mediaTypes[0]\n return available ? [available, content[available]!] : false\n}\n","import { pascalCase } from '@internals/utils'\nimport { SCHEMA_REF_PREFIX } from '../constants.ts'\nimport { isReference } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport type { ContentType, ContentTypeOptions, Document, SchemaObject } from '../types.ts'\n\n/**\n * The three component sections Kubb reads schemas from.\n */\ntype SchemaSourceMode = 'schemas' | 'responses' | 'requestBodies'\n\n/**\n * A schema annotated with its component section source and original name. `getSchemas` uses this\n * to resolve name collisions across sources.\n */\ntype SchemaWithMetadata = {\n schema: SchemaObject\n source: SchemaSourceMode\n originalName: string\n}\n\nexport type GetSchemasResult = {\n schemas: Record<string, SchemaObject>\n /**\n * Maps a renamed component pointer (`#/components/<source>/<name>`) to the\n * collision-resolved unique name used as the key in `schemas`. Components that keep\n * their original name are not recorded, so the map stays empty for documents\n * without collisions.\n */\n renames: Map<string, string>\n}\n\n/**\n * Extracts the inline schema from a media-type `content` map.\n *\n * Prefers `preferredContentType` when given, otherwise uses the first key in the map.\n * Returns `null` when `content` is absent, the schema is missing, or the schema is a `$ref`.\n *\n * @example\n * ```ts\n * extractSchemaFromContent(operation.content, 'application/json')\n * // SchemaObject | null\n * ```\n */\nexport function extractSchemaFromContent(content: Record<string, unknown> | undefined, preferredContentType?: ContentType): SchemaObject | null {\n if (!content) return null\n\n const firstContentType = Object.keys(content)[0] ?? 'application/json'\n const targetContentType = preferredContentType ?? firstContentType\n const contentSchema = content[targetContentType] as { schema?: SchemaObject } | undefined\n const schema = contentSchema?.schema\n\n if (isReference(schema)) return null\n return schema ?? null\n}\n\n/**\n * Walks a schema tree and collects the names of all `#/components/schemas/<name>` `$ref`s.\n */\nfunction* collectRefs(schema: unknown): Generator<string, void, undefined> {\n if (Array.isArray(schema)) {\n for (const item of schema) yield* collectRefs(item)\n return\n }\n\n if (schema && typeof schema === 'object') {\n for (const key in schema) {\n const value = (schema as Record<string, unknown>)[key]\n if (!(key === '$ref' && typeof value === 'string')) {\n yield* collectRefs(value)\n continue\n }\n if (value.startsWith(SCHEMA_REF_PREFIX)) {\n const name = value.slice(SCHEMA_REF_PREFIX.length)\n if (name) yield name\n }\n }\n }\n}\n\n/**\n * Returns a copy of `schemas` topologically sorted by `$ref` dependency.\n *\n * Referenced schemas appear before the schemas that depend on them, so code generators\n * can emit types in the correct order. Cycles are silently skipped.\n *\n * @example\n * ```ts\n * const sorted = sortSchemas({ Order: orderSchema, Pet: petSchema })\n * // Pet appears before Order when Order.$ref points at Pet\n * ```\n */\nexport function sortSchemas(schemas: Record<string, SchemaObject>): Record<string, SchemaObject> {\n const deps = new Map<string, Array<string>>()\n\n for (const [name, schema] of Object.entries(schemas)) {\n deps.set(name, [...new Set(collectRefs(schema))])\n }\n\n const sorted: Array<string> = []\n const visited = new Set<string>()\n\n function visit(name: string, stack: Set<string>) {\n if (visited.has(name) || stack.has(name)) return\n stack.add(name)\n for (const child of deps.get(name) ?? []) {\n if (deps.has(child)) visit(child, stack)\n }\n stack.delete(name)\n visited.add(name)\n sorted.push(name)\n }\n\n for (const name of Object.keys(schemas)) {\n visit(name, new Set())\n }\n\n const result: Record<string, SchemaObject> = {}\n for (const name of sorted) result[name] = schemas[name]!\n return result\n}\n\nconst semanticSuffixes: Record<SchemaSourceMode, string> = {\n schemas: 'Schema',\n responses: 'Response',\n requestBodies: 'Request',\n}\n\n/**\n * Picks the collision suffix for one name-colliding schema: none when the name is unique,\n * a semantic suffix (`Schema`, `Response`, `Request`) when the collision spans sources, otherwise\n * a numeric suffix (`2`, `3`, …) for same-source collisions.\n */\nfunction collisionSuffix({\n isSingle,\n hasMultipleSources,\n source,\n index,\n}: {\n isSingle: boolean\n hasMultipleSources: boolean\n source: SchemaSourceMode\n index: number\n}): string {\n if (isSingle) return ''\n if (hasMultipleSources) return semanticSuffixes[source]\n if (index === 0) return ''\n return String(index + 1)\n}\n\n/**\n * Collects component schemas from one or more sources and resolves name collisions.\n *\n * Sources default to `['schemas', 'requestBodies', 'responses']`. Returned schemas are\n * topologically sorted by `$ref` dependency so generators emit types in the correct order.\n *\n * When two or more schemas normalize to the same PascalCase name:\n * - Same source → numeric suffix (`2`, `3`, …).\n * - Different sources → semantic suffix (`Schema`, `Response`, `Request`).\n *\n * @example\n * ```ts\n * const { schemas, renames } = getSchemas(document, { contentType: 'application/json' }, refs)\n * ```\n */\nexport function getSchemas(document: Document, { contentType }: ContentTypeOptions, refs: Refs): GetSchemasResult {\n const components = document.components\n\n function resolveSchemaRef(schema: SchemaObject): SchemaObject {\n if (!isReference(schema)) return schema\n const resolved = refs.resolve<SchemaObject>(schema.$ref)\n return resolved && !isReference(resolved) ? resolved : schema\n }\n\n const candidates: Array<SchemaWithMetadata> = [\n ...Object.entries((components?.schemas as Record<string, SchemaObject>) ?? {}).map(([name, schema]) => ({\n schema: resolveSchemaRef(schema),\n source: 'schemas' as const,\n originalName: name,\n })),\n ...(['responses', 'requestBodies'] as const).flatMap((source) =>\n Object.entries(components?.[source] ?? {}).flatMap(([name, item]) => {\n const schema = extractSchemaFromContent((item as { content?: Record<string, unknown> }).content, contentType)\n return schema\n ? [\n {\n schema: resolveSchemaRef(schema),\n source,\n originalName: name,\n },\n ]\n : []\n }),\n ),\n ]\n\n const normalizedNames = new Map<string, Array<SchemaWithMetadata>>()\n for (const item of candidates) {\n const key = pascalCase(item.originalName)\n const bucket = normalizedNames.get(key) ?? []\n bucket.push(item)\n normalizedNames.set(key, bucket)\n }\n\n const schemas: Record<string, SchemaObject> = {}\n const renames = new Map<string, string>()\n\n for (const [, items] of normalizedNames) {\n const isSingle = items.length === 1\n const hasMultipleSources = !isSingle && new Set(items.map((item) => item.source)).size > 1\n\n items.forEach((item, index) => {\n const suffix = collisionSuffix({ isSingle, hasMultipleSources, source: item.source, index })\n const uniqueName = item.originalName + suffix\n schemas[uniqueName] = item.schema\n if (suffix) renames.set(`#/components/${item.source}/${item.originalName}`, uniqueName)\n })\n }\n\n return { schemas: sortSchemas(schemas), renames }\n}\n","import { Diagnostics } from '@kubb/core'\nimport type { Document, ServerObject, ServerOptions } from '../types.ts'\n\n/**\n * Reads the server URL from the document's `servers` array at `server.index`,\n * interpolating any `server.variables` into the URL template.\n *\n * Returns `null` when `server.index` is omitted or out of range.\n *\n * @example Resolve the first server\n * `resolveBaseUrl({ document, server: { index: 0 } })`\n *\n * @example Override a path variable\n * `resolveBaseUrl({ document, server: { index: 0, variables: { version: 'v2' } } })`\n */\nexport function resolveBaseUrl({ document, server }: { document: Document; server?: ServerOptions }): string | null {\n const index = server?.index\n const entry = index !== undefined ? document.servers?.at(index) : undefined\n\n return entry?.url ? resolveServerUrl(entry, server?.variables) : null\n}\n\n/**\n * Replaces `{variable}` placeholders in an OpenAPI server URL with provided values.\n * Resolution order: `overrides[key]` → `variable.default` → left unreplaced.\n * Throws if an override value is not in the variable's `enum` list.\n *\n * @example\n * ```ts\n * resolveServerUrl(\n * { url: 'https://{env}.api.example.com', variables: { env: { default: 'dev', enum: ['dev', 'prod'] } } },\n * { env: 'prod' },\n * )\n * // 'https://prod.api.example.com'\n * ```\n */\nexport function resolveServerUrl(server: ServerObject, overrides?: Record<string, string>): string {\n if (!server.variables) {\n return server.url\n }\n\n let url = server.url\n for (const [key, variable] of Object.entries(server.variables)) {\n const value = overrides?.[key] ?? (variable.default != null ? String(variable.default) : undefined)\n if (value === undefined) {\n continue\n }\n\n if (variable.enum?.length && !variable.enum.some((e) => String(e) === value)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidServerVariable,\n severity: 'error',\n message: `Invalid server variable value '${value}' for '${key}' when resolving ${server.url}. Valid values are: ${variable.enum.join(', ')}.`,\n help: `Use one of the allowed enum values, or drop the enum on the '${key}' server variable.`,\n location: { kind: 'document', pointer: '#/servers' },\n })\n }\n\n url = url.replaceAll(`{${key}}`, value)\n }\n\n return url\n}\n","import { SUPPORTED_METHODS } from './constants.ts'\nimport { isJsonMimeType, isReference, pickContentEntry } from './oas.ts'\nimport type { Refs } from './refs.ts'\nimport type { Document, MediaTypeObject, OperationObject, PathItemObject, ReferenceObject, RequestBodyObject, ResponseObject } from './types.ts'\n\n/**\n * A single OpenAPI operation: its URL path, HTTP method, and the raw operation object.\n *\n * `schema` is a live reference into the document. Unlike earlier versions of this adapter, nothing\n * resolves a `$ref` in place here anymore — every accessor below resolves through `refs` instead.\n * `pathItem` is the already-resolved path item this operation was read from, so a caller that\n * also needs path-level data (parameters, summary, description) doesn't re-resolve it.\n */\nexport type Operation = {\n path: string\n method: string\n schema: OperationObject\n pathItem: PathItemObject\n}\n\n/**\n * The operation being read plus the `$ref` service to resolve against.\n */\ntype OperationContext = {\n operation: Operation\n refs: Refs\n}\n\n/**\n * Slugifies a path for the `operationId` fallback: non-alphanumerics collapse to single dashes,\n * with no leading or trailing dash.\n */\nfunction slugify(value: string): string {\n return value\n .replace(/[^a-zA-Z0-9]/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^-|-$/g, '')\n}\n\n/**\n * Returns the operation's `operationId`, falling back to `<method>_<slugified-path>` when absent.\n */\nexport function getOperationId({ path, method, schema }: Operation): string {\n const { operationId } = schema\n if (typeof operationId === 'string' && operationId.length > 0) {\n return operationId\n }\n\n return `${method}_${slugify(path).toLowerCase()}`\n}\n\n/**\n * Returns the declared response status codes, skipping `x-` extensions and non-object entries.\n */\nexport function getResponseStatusCodes({ schema }: Operation): Array<string> {\n const responses = schema.responses as Record<string, unknown> | undefined\n if (!responses || isReference(responses)) {\n return []\n }\n\n return Object.keys(responses).filter((key) => !key.startsWith('x-') && !!responses[key] && typeof responses[key] === 'object')\n}\n\n/**\n * Returns the response object for a status code, resolving a `$ref` through `refs`. `false` when absent.\n */\nexport function getResponseByStatusCode({ operation, refs, statusCode }: OperationContext & { statusCode: string | number }): ResponseObject | false {\n const responses = operation.schema.responses as Record<string, ResponseObject | ReferenceObject> | undefined\n if (!responses || isReference(responses)) {\n return false\n }\n\n return refs.deref<ResponseObject>(responses[statusCode]) ?? false\n}\n\n/**\n * Resolves the operation's request body, dereferencing a `$ref` through `refs`. Returns `null`\n * when the operation has no request body or it cannot be resolved.\n */\nexport function getRequestBody({ operation, refs }: OperationContext): RequestBodyObject | null {\n return refs.deref<RequestBodyObject>(operation.schema.requestBody)\n}\n\n/**\n * Resolves the request body (a `$ref` through `refs`) and returns its content map, or\n * `undefined` when the operation has no request body.\n */\nfunction getRequestBodyContent({ operation, refs }: OperationContext): Record<string, MediaTypeObject> | undefined {\n return getRequestBody({ operation, refs })?.content\n}\n\n/**\n * Returns the request body media type. With `mediaType` set, returns that entry or `false`.\n * Otherwise picks the first JSON-like media type, then the first declared one, as a\n * `[mediaType, object]` tuple.\n */\nexport function getRequestContent({\n operation,\n refs,\n mediaType,\n}: OperationContext & { mediaType?: string }): MediaTypeObject | false | [string, MediaTypeObject] {\n const content = getRequestBodyContent({ operation, refs })\n\n if (!content) {\n return false\n }\n\n if (mediaType) {\n return mediaType in content ? content[mediaType]! : false\n }\n\n return pickContentEntry(content)\n}\n\n/**\n * Returns the primary request content type. Prefers a JSON-like media type (the last one wins\n * when several are declared), then the first declared one, defaulting to `'application/json'`.\n */\nexport function getRequestContentType({ operation, refs }: OperationContext): string {\n const content = getRequestBodyContent({ operation, refs })\n const mediaTypes = content ? Object.keys(content) : []\n\n let result = mediaTypes[0] ?? 'application/json'\n for (const mt of mediaTypes) {\n if (isJsonMimeType(mt)) {\n result = mt\n }\n }\n\n return result\n}\n\n/**\n * Builds an `Operation` for every supported HTTP method on every path, in document order.\n * `x-` path keys and unresolvable path-item `$ref`s are skipped.\n *\n * @example\n * ```ts\n * for (const operation of getOperations(document, refs)) {\n * parseOperation(options, operation)\n * }\n * ```\n */\nexport function getOperations(document: Document, refs: Refs): Array<Operation> {\n const operations: Array<Operation> = []\n const paths = document.paths\n if (!paths) {\n return operations\n }\n\n for (const path of Object.keys(paths)) {\n if (path.startsWith('x-')) {\n continue\n }\n\n const pathItem = refs.deref<PathItemObject>(paths[path])\n if (!pathItem) {\n continue\n }\n\n const item = pathItem as unknown as Record<string, unknown>\n for (const method of Object.keys(item)) {\n if (!SUPPORTED_METHODS.has(method)) {\n continue\n }\n const schema = item[method]\n if (!schema || typeof schema !== 'object') {\n continue\n }\n operations.push({ path, method, schema: schema as OperationObject, pathItem })\n }\n }\n\n return operations\n}\n","import type { ast } from '@kubb/ast'\nimport { formatMap, specialCasedFormats, structuralKeys } from '../constants.ts'\nimport { isReference } from '../oas.ts'\nimport type { SchemaObject } from '../types.ts'\n\n/**\n * Returns the Kubb `SchemaType` for a given OAS `format` string, or `null` if not found.\n * Formats not in `formatMap` (e.g., `int64`, `uint64`, `date-time`) are handled separately by parser options.\n */\nexport function getSchemaType(format: string): ast.SchemaType | null {\n return formatMap[format as keyof typeof formatMap] ?? null\n}\n\n/**\n * Whether the parser maps `format` to a dedicated type. True for any `formatMap` entry, plus the\n * `specialCasedFormats` that `convertFormat` handles directly (int64, uint64, date-time, date, time). False means the format falls back to\n * the base type, which is what `KUBB_UNSUPPORTED_FORMAT` flags. Reading both sources keeps the\n * diagnostic in step with the parser as `formatMap` grows.\n */\nexport function isHandledFormat(format: string): boolean {\n return getSchemaType(format) !== null || specialCasedFormats.has(format)\n}\n\n/**\n * Converts an OAS primitive type string to its `PrimitiveSchemaType` equivalent.\n * Numeric types (`number`, `integer`, `bigint`) pass through unchanged. `boolean` maps to `'boolean'`. Everything else becomes `'string'`.\n */\nexport function getPrimitiveType(type: string | undefined): ast.PrimitiveSchemaType {\n if (type === 'number' || type === 'integer' || type === 'bigint') return type\n if (type === 'boolean') return 'boolean'\n\n return 'string'\n}\n\n/**\n * Resolves the `dateType` option down to the value for one format. The scalar form of\n * `dateType` applies to every format; the object form picks `dateTime`/`date`/`time`\n * individually and defaults an omitted key to `'string'`.\n */\nexport function resolveDateTypeValue(\n dateType: ast.ParserOptions['dateType'],\n format: 'date-time' | 'date' | 'time',\n): ast.DateTimeTypeValue | ast.DateOnlyTypeValue {\n if (typeof dateType !== 'object' || dateType === null) {\n return dateType\n }\n\n const key = format === 'date-time' ? 'dateTime' : format\n return dateType[key] ?? 'string'\n}\n\n/**\n * Resolves the AST type descriptor for a date/time format, honoring the `dateType` option.\n * Returns `null` when the resolved value is `false`, so the format falls through to `string`.\n */\nexport function getDateType(\n options: ast.ParserOptions,\n format: 'date-time' | 'date' | 'time',\n): { type: 'datetime'; offset?: boolean; local?: boolean } | { type: 'date' | 'time'; representation: 'date' | 'string' } | null {\n const value = resolveDateTypeValue(options.dateType, format)\n\n if (!value) {\n return null\n }\n\n if (format === 'date-time') {\n if (value === 'date') {\n return { type: 'date', representation: 'date' }\n }\n if (value === 'stringOffset') {\n return { type: 'datetime', offset: true }\n }\n if (value === 'stringLocal') {\n return { type: 'datetime', local: true }\n }\n return { type: 'datetime', offset: false }\n }\n\n if (format === 'date') {\n return {\n type: 'date',\n representation: value === 'date' ? 'date' : 'string',\n }\n }\n\n // time\n return {\n type: 'time',\n representation: value === 'date' ? 'date' : 'string',\n }\n}\n\n/**\n * Reads a schema's numeric `exclusiveMinimum`/`exclusiveMaximum` bounds (the OAS 3.1 numeric\n * form). Either key is `undefined` when absent or, for the legacy OAS 3.0 boolean form, not a\n * number.\n */\nexport function getExclusiveBounds(schema: SchemaObject): { exclusiveMinimum: number | undefined; exclusiveMaximum: number | undefined } {\n return {\n exclusiveMinimum: typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined,\n exclusiveMaximum: typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : undefined,\n }\n}\n\n/**\n * Reads schema examples as an array. OAS 3.1 uses an `examples` array, but specs (including ones\n * labeled 3.1) still use the singular OAS 3.0 `example`, which the upgrader only converts on the\n * 3.0 -> 3.1 hop. Normalize both into one array so the AST node exposes only `examples`.\n */\nexport function extractExamples(schema: SchemaObject): Array<unknown> | undefined {\n if (Array.isArray(schema.examples)) return schema.examples\n return schema.example !== undefined ? [schema.example] : undefined\n}\n\n/**\n * Returns `true` when `fragment` carries any JSON Schema keyword that makes it\n * structurally significant on its own (see `structuralKeys`).\n *\n * A fragment with a structural keyword can't be safely merged into a parent schema.\n */\nfunction hasStructuralKeywords(fragment: SchemaObject): boolean {\n return Object.keys(fragment).some((key) => structuralKeys.has(key as 'properties'))\n}\n\n/**\n * Flattens a keyword-only `allOf` into its parent schema.\n *\n * Only flattens when every member is a plain fragment, with no `$ref` and no structural keywords\n * (see `structuralKeys`). Outer schema values take precedence over fragment values.\n * Returns `null` for a `null` input, and the original schema unchanged when flattening is unsafe.\n *\n * @example\n * ```ts\n * flattenSchema({ allOf: [{ description: 'A pet' }], type: 'object', properties: {} })\n * // { type: 'object', properties: {}, description: 'A pet' }\n * ```\n *\n * @example\n * ```ts\n * flattenSchema({ allOf: [{ $ref: '#/components/schemas/Pet' }] })\n * // returned unchanged, contains a $ref\n * ```\n */\nexport function flattenSchema(schema: SchemaObject | null): SchemaObject | null {\n if (!schema?.allOf || schema.allOf.length === 0) return schema ?? null\n\n const allOfFragments = schema.allOf as Array<SchemaObject>\n if (allOfFragments.some((item) => isReference(item))) return schema\n if (allOfFragments.some(hasStructuralKeywords)) return schema\n\n // Destructure `allOf` out instead of `delete merged.allOf`: a `delete` transitions the freshly\n // spread object into V8 dictionary (slow) mode, and this runs per `allOf` schema during parsing.\n const { allOf: _allOf, ...rest } = schema\n const merged = rest as SchemaObject\n\n for (const fragment of allOfFragments) {\n for (const [key, value] of Object.entries(fragment)) {\n merged[key as keyof SchemaObject] ??= value as SchemaObject[keyof SchemaObject]\n }\n }\n\n return merged\n}\n","import { ast } from '@kubb/ast'\nimport { extractExamples } from './schemaShape.ts'\nimport type { SchemaContext } from './parseSchema.ts'\n\n/**\n * The `schema`/`name`/`nullable`/`defaultValue` slice of a context, the only part\n * {@link createNode} needs to fill in a node's shared base fields.\n */\ntype NodeBaseContext = Pick<SchemaContext, 'schema' | 'name' | 'nullable' | 'defaultValue'>\n\n/**\n * Input shape accepted by `ast.factory.createSchema`, recovered from its own signature so\n * {@link createNode} stays in sync with the AST layer without redeclaring the union.\n */\ntype CreateSchemaProps = Parameters<typeof ast.factory.createSchema>[0]\n\n/**\n * Builds a schema node from a converter's base context plus its type-specific fields. Every\n * converter needs the same metadata fields (`title`, `description`, `examples`, ...) alongside\n * whatever makes its node distinct; this folds both into one call.\n */\nexport function createNode({ schema, name, nullable, defaultValue }: NodeBaseContext, extras: CreateSchemaProps): ast.SchemaNode {\n return ast.factory.createSchema({\n name,\n nullable,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n readOnly: schema.readOnly,\n writeOnly: schema.writeOnly,\n default: defaultValue,\n examples: extractExamples(schema),\n format: schema.format,\n ...extras,\n })\n}\n","import { ast } from '@kubb/ast'\nimport { extractRefName, macroDiscriminatorEnum } from '@kubb/kit'\nimport { SCHEMA_REF_PREFIX } from '../../constants.ts'\nimport { isDiscriminator, isReference } from '../../oas.ts'\nimport type { Refs } from '../../refs.ts'\nimport type { DiscriminatorObject, ReferenceObject, SchemaObject } from '../../types.ts'\nimport type { ParseFn } from '../parseSchema.ts'\n\n/**\n * Creates a single-property object schema used as a discriminator literal.\n *\n * @example\n * ```ts\n * createDiscriminantNode({ propertyName: 'type', values: ['dog'] })\n * // -> { type: 'object', properties: [{ name: 'type', required: true, schema: enum('dog') }] }\n * ```\n */\nexport function createDiscriminantNode({ propertyName, values }: { propertyName: string; values: Array<string> }): ast.SchemaNode {\n return ast.factory.createSchema({\n type: 'object',\n primitive: 'object',\n properties: [\n ast.factory.createProperty({\n name: propertyName,\n schema: ast.factory.createSchema({\n type: 'enum',\n primitive: 'string',\n enumValues: values,\n }),\n required: true,\n }),\n ],\n })\n}\n\n/**\n * Returns every discriminator key whose mapping value matches `ref`, in mapping order.\n *\n * A mapping may point several keys at the same schema, in which case the member has to be\n * narrowed to all of them — keeping only the first would drop the rest from the union.\n *\n * @example\n * ```ts\n * findDiscriminators({ dog: '#/components/schemas/Dog', hound: '#/components/schemas/Dog' }, '#/components/schemas/Dog') // ['dog', 'hound']\n * ```\n */\nexport function findDiscriminators(mapping: Record<string, string> | undefined, ref: string | undefined): Array<string> {\n if (!mapping || !ref) return []\n return Object.entries(mapping)\n .filter(([, value]) => value === ref)\n .map(([key]) => key)\n}\n\n/**\n * Narrows each `oneOf`/`anyOf` member with its discriminant value, intersecting the member's own\n * node with either the shared-properties slice carrying that value, or a synthetic discriminant\n * literal. The referenced child schema's own definition is left untouched — narrowing happens only\n * at this union usage site, which is what makes this mode \"preserve\" (as opposed to `propagate`,\n * which additionally patches the child schema's own definition in a post-pass).\n */\nexport function narrowUnionMembers({\n unionMembers,\n discriminator,\n sharedPropertiesNode,\n parse,\n rawOptions,\n name,\n refs,\n}: {\n unionMembers: Array<unknown>\n discriminator: DiscriminatorObject | undefined\n sharedPropertiesNode: ast.SchemaNode | undefined\n parse: ParseFn\n rawOptions: Partial<ast.ParserOptions> | undefined\n name: string | null | undefined\n refs: Refs\n}): Array<ast.SchemaNode> {\n function pickDiscriminatorPropertyNode(node: ast.SchemaNode, propertyName: string): ast.SchemaNode | null {\n const objectNode = ast.narrowSchema(node, 'object')\n const discriminatorProperty = objectNode?.properties?.find((property) => property.name === propertyName)\n\n if (!discriminatorProperty) {\n return null\n }\n\n return ast.factory.createSchema({\n type: 'object',\n primitive: 'object',\n properties: [discriminatorProperty],\n })\n }\n\n function implicitDiscriminantValue(member: unknown): string | null {\n if (!discriminator || discriminator.mapping || !isReference(member)) return null\n const value = extractRefName(member.$ref)\n if (!value) return null\n // Silent walk — the reporting resolve() would flag missing refs as errors during speculative lookup.\n const variant = refs.resolve<SchemaObject>(member.$ref, { report: false })\n if (!variant) return null\n\n const propertyName = discriminator.propertyName\n // Intersecting two different literals on the same property collapses it to `never`,\n // so skip folding the implicit name when the variant already pins the discriminator.\n const seen = new Set([member.$ref])\n\n function constrains(v: SchemaObject): boolean {\n const prop = v.properties?.[propertyName]\n const resolved = prop && isReference(prop) ? refs.resolve<SchemaObject>(prop.$ref, { report: false }) : (prop as SchemaObject | undefined)\n if (resolved && (Array.isArray(resolved.enum) || resolved.const !== undefined)) return true\n const composition = v.allOf ?? v.oneOf ?? v.anyOf\n if (!composition) return false\n\n return composition.some((m) => {\n if (!isReference(m)) return constrains(m as SchemaObject)\n if (seen.has(m.$ref)) return false\n seen.add(m.$ref)\n const r = refs.resolve<SchemaObject>(m.$ref, { report: false })\n return r ? constrains(r) : false\n })\n }\n\n return constrains(variant) ? null : value\n }\n\n return unionMembers.map((s) => {\n const ref = isReference(s) ? s.$ref : undefined\n const mappedValues = findDiscriminators(discriminator?.mapping, ref)\n const implicitValue = mappedValues.length ? null : implicitDiscriminantValue(s)\n const discriminatorValues = mappedValues.length ? mappedValues : implicitValue ? [implicitValue] : []\n const memberNode = parse({ schema: s as SchemaObject, name }, rawOptions)\n\n if (!discriminatorValues.length || !discriminator) {\n return memberNode\n }\n\n const narrowedDiscriminatorNode = sharedPropertiesNode\n ? pickDiscriminatorPropertyNode(\n ast.applyMacros(sharedPropertiesNode, [macroDiscriminatorEnum({ propertyName: discriminator.propertyName, values: discriminatorValues })], {\n depth: 'shallow',\n }),\n discriminator.propertyName,\n )\n : undefined\n\n return ast.factory.createSchema({\n type: 'intersection',\n members: [\n memberNode,\n narrowedDiscriminatorNode ??\n createDiscriminantNode({\n propertyName: discriminator.propertyName,\n values: discriminatorValues,\n }),\n ],\n })\n })\n}\n\n/**\n * Filters the discriminated members out of an `allOf` list: an `allOf` member that `$ref`s a\n * discriminated union's parent, where this schema is itself one of that union's children, is\n * dropped from `members` and its discriminant value collected instead — the same synthetic\n * literal `narrowUnionMembers` produces, so the emitted node stays a plain intersection rather\n * than nesting the whole parent union one level deeper.\n */\nexport function extractDiscriminatedAllOfMembers({\n allOfMembers,\n name,\n refs,\n}: {\n allOfMembers: Array<SchemaObject | ReferenceObject>\n name: string | null | undefined\n refs: Refs\n}): {\n members: Array<SchemaObject | ReferenceObject>\n discriminantValues: Array<{ propertyName: string; values: Array<string> }>\n} {\n const discriminantValues: Array<{ propertyName: string; values: Array<string> }> = []\n\n const members = allOfMembers.filter((item) => {\n if (!isReference(item) || !name) return true\n const deref = refs.resolve<SchemaObject>(item.$ref)\n if (!deref || !isDiscriminator(deref)) return true\n const parentUnion = deref.oneOf ?? deref.anyOf\n if (!parentUnion) return true\n const childRef = `${SCHEMA_REF_PREFIX}${name}`\n const inOneOf = parentUnion.some((oneOfItem) => isReference(oneOfItem) && oneOfItem.$ref === childRef)\n const inMapping = Object.values(deref.discriminator.mapping ?? {}).some((v) => v === childRef)\n if (inOneOf || inMapping) {\n const values = findDiscriminators(deref.discriminator.mapping, childRef)\n if (values.length) {\n discriminantValues.push({\n propertyName: deref.discriminator.propertyName,\n values,\n })\n }\n return false\n }\n return true\n })\n\n return { members, discriminantValues }\n}\n","import { ast } from '@kubb/ast'\nimport { extractRefName, macroSimplifyUnion, mergeAdjacentObjectsLazy } from '@kubb/kit'\nimport { isDiscriminator, isReference } from '../../oas.ts'\nimport type { ReferenceObject, SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport { createDiscriminantNode, extractDiscriminatedAllOfMembers, narrowUnionMembers } from '../discriminator/preserve.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\nimport { extractExamples } from '../schemaShape.ts'\n\n/**\n * Converts a `$ref` schema into a `RefSchemaNode`.\n *\n * The resolved schema is stored in `node.schema`. Usage-site sibling fields\n * (description, readOnly, nullable, etc.) are stored directly on the ref node.\n * Use `syncSchemaRef(node)` in printers to get a merged view of both.\n * Circular refs are detected in `refs.resolveNode` and leave `schema` as `null`.\n */\nexport function convertRef({ schema, name, nullable, defaultValue, rawOptions, document, parse, refs, renames }: ConvertContext): ast.SchemaNode {\n const refPath = schema.$ref\n const resolvedSchema = refPath ? refs.resolveNode(refPath, parse, rawOptions) : null\n const ctx = { schema, name, nullable, defaultValue }\n\n // A `$ref` to a component the document never defines (a malformed spec) would otherwise emit an\n // import to a module that is never generated, leaving the output uncompilable. Fall back to\n // `unknown` so the rest of the schema still resolves. Only do this for a document that declares a\n // component registry — a registry-less fragment (e.g. a minimal `parse` call) parses refs\n // leniently, since the target is expected to live outside the fragment.\n if (refPath && document.components && !refs.exists(refPath)) {\n return createNode(ctx, { type: 'unknown' })\n }\n\n const targetName = renames?.get(schema.$ref!)\n\n return createNode(ctx, {\n type: 'ref',\n name: extractRefName(schema.$ref!),\n ref: schema.$ref,\n ...(targetName ? { targetName } : {}),\n schema: resolvedSchema,\n })\n}\n\n/**\n * Converts an `allOf` schema into a flattened node or an `IntersectionSchemaNode`.\n */\nexport function convertAllOf({ schema, name, nullable, defaultValue, rawOptions, parse, refs }: ConvertContext): ast.SchemaNode {\n if (\n schema.allOf!.length === 1 &&\n !schema.properties &&\n !(Array.isArray(schema.required) && schema.required.length) &&\n schema.additionalProperties === undefined\n ) {\n const [memberSchema] = schema.allOf as Array<SchemaObject | ReferenceObject>\n const memberNode = parse({ schema: memberSchema! as SchemaObject, name }, rawOptions)\n const { kind: _kind, ...memberNodeProps } = memberNode\n const mergedNullable = nullable || memberNode.nullable || undefined\n const mergedDefault = schema.default === null && mergedNullable ? undefined : (schema.default ?? memberNode.default)\n\n return ast.factory.createSchema({\n ...memberNodeProps,\n name,\n title: schema.title ?? memberNode.title,\n description: schema.description ?? memberNode.description,\n deprecated: schema.deprecated ?? memberNode.deprecated,\n nullable: mergedNullable,\n readOnly: schema.readOnly ?? memberNode.readOnly,\n writeOnly: schema.writeOnly ?? memberNode.writeOnly,\n default: mergedDefault,\n examples: extractExamples(schema) ?? memberNode.examples,\n pattern: schema.pattern ?? ('pattern' in memberNode ? memberNode.pattern : undefined),\n format: schema.format ?? memberNode.format,\n } as ast.DistributiveOmit<ast.SchemaNode, 'kind'>)\n }\n\n const { members: discriminatedAllOf, discriminantValues } = extractDiscriminatedAllOfMembers({\n allOfMembers: schema.allOf as Array<SchemaObject | ReferenceObject>,\n name,\n refs,\n })\n const allOfMembers: Array<ast.SchemaNode> = discriminatedAllOf.map((s) => parse({ schema: s as SchemaObject, name }, rawOptions))\n\n const syntheticStart = allOfMembers.length\n\n if (Array.isArray(schema.required) && schema.required.length) {\n const outerKeys = schema.properties ? new Set(Object.keys(schema.properties)) : new Set<string>()\n const missingRequired = schema.required.filter((key) => !outerKeys.has(key))\n\n if (missingRequired.length) {\n const resolvedMembers = (schema.allOf as Array<SchemaObject | ReferenceObject>).flatMap((item) => {\n if (!isReference(item)) return [item as SchemaObject]\n const deref = refs.resolve<SchemaObject>(item.$ref)\n return deref && !isReference(deref) ? [deref] : []\n })\n\n for (const key of missingRequired) {\n for (const resolved of resolvedMembers) {\n const prop = resolved.properties?.[key]\n if (prop) {\n const raw = { properties: { [key]: prop }, required: [key] }\n const memberSchema = raw as SchemaObject\n allOfMembers.push(parse({ schema: memberSchema, name }, rawOptions))\n break\n }\n }\n }\n }\n }\n\n if (schema.properties) {\n const { allOf: _allOf, ...schemaWithoutAllOf } = schema\n // Don't pass `name` here, the result must stay anonymous so it can be merged with the\n // adjacent synthetic object in `mergeAdjacentObjectsLazy`. Nested enum qualification\n // happens upstream via `convertObject`'s `setEnumName` propagation.\n allOfMembers.push(parse({ schema: schemaWithoutAllOf }, rawOptions))\n }\n\n for (const { propertyName, values } of discriminantValues) {\n allOfMembers.push(createDiscriminantNode({ propertyName, values }))\n }\n\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'intersection',\n members: [...mergeAdjacentObjectsLazy(allOfMembers.slice(0, syntheticStart)), ...mergeAdjacentObjectsLazy(allOfMembers.slice(syntheticStart))],\n },\n )\n}\n\n/**\n * Converts a `oneOf` / `anyOf` schema into a `UnionSchemaNode`.\n */\nexport function convertUnion({ schema, name, nullable, defaultValue, rawOptions, parse, refs }: ConvertContext): ast.SchemaNode {\n const ctx = { schema, name, nullable, defaultValue }\n const unionMembers = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]\n const strategy: 'one' | 'any' = schema.oneOf ? 'one' : 'any'\n const unionExtras = {\n discriminatorPropertyName: isDiscriminator(schema) ? schema.discriminator.propertyName : undefined,\n strategy,\n }\n const discriminator = isDiscriminator(schema) ? schema.discriminator : undefined\n const { oneOf: _o, anyOf: _a, discriminator: _d, ...memberBaseSchema } = schema\n const sharedPropertiesNode = schema.properties ? parse({ schema: memberBaseSchema as SchemaObject, name }, rawOptions) : undefined\n\n if (sharedPropertiesNode || discriminator) {\n const members = narrowUnionMembers({ unionMembers, discriminator, sharedPropertiesNode, parse, rawOptions, name, refs })\n const unionNode = createNode(ctx, { type: 'union', ...unionExtras, members })\n\n if (!sharedPropertiesNode) {\n return unionNode\n }\n\n return createNode(ctx, { type: 'intersection', members: [unionNode, sharedPropertiesNode] })\n }\n\n const unionNode = createNode(ctx, {\n type: 'union',\n ...unionExtras,\n members: unionMembers.map((s) => parse({ schema: s as SchemaObject, name }, rawOptions)),\n })\n\n return ast.applyMacros(unionNode, [macroSimplifyUnion], { depth: 'shallow' })\n}\n\n/**\n * Converts an OAS 3.1 multi-type array (e.g. `type: ['string', 'number']`) into a `UnionSchemaNode`.\n * Only called once the multi-type rule's `match` has confirmed more than one non-`null` type\n * remains; a single remaining type (e.g. `['string', 'null']`) is handled as that type instead,\n * with nullability already folded in.\n */\nexport function convertMultiType({ schema, name, nullable, defaultValue, rawOptions, parse }: ConvertContext): ast.SchemaNode {\n const types = schema.type as Array<string>\n const nonNullTypes = types.filter((t) => t !== 'null')\n\n const arrayNullable = types.includes('null') || nullable || undefined\n return createNode(\n { schema, name, nullable: arrayNullable, defaultValue },\n {\n type: 'union',\n members: nonNullTypes.map((t) => {\n const raw = { ...schema, type: t }\n const memberSchema = raw as SchemaObject\n return parse({ schema: memberSchema, name }, rawOptions)\n }),\n },\n )\n}\n","import { ast } from '@kubb/ast'\nimport { enumDescriptionKeys, enumExtensionKeys, numericFormats } from '../../constants.ts'\nimport type { SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\nimport { getDateType, getExclusiveBounds, getPrimitiveType, getSchemaType } from '../schemaShape.ts'\n\n/**\n * Normalizes malformed `{ type: 'array', enum: [...] }` schemas by moving enum values into items.\n *\n * This pattern violates the OpenAPI spec but appears in real specs. The fix moves enum values\n * from the array to its items sub-schema, so they are valid for downstream processing.\n *\n * @note A defensive measure for non-compliant specs.\n */\nfunction normalizeArrayEnum(schema: SchemaObject): SchemaObject {\n const isItemsObject = typeof schema.items === 'object' && !Array.isArray(schema.items)\n const normalizedItems: SchemaObject = {\n ...(isItemsObject ? (schema.items as SchemaObject) : {}),\n enum: schema.enum,\n }\n const { enum: _enum, ...schemaWithoutEnum } = schema\n // `SchemaObject` is a discriminated union; the spread can't be verified against every member\n // structurally, so the merge result is asserted rather than annotated.\n const merged = { ...schemaWithoutEnum, items: normalizedItems }\n\n return merged as SchemaObject\n}\n\n/**\n * Builds a `null` scalar node carrying the schema's documentation. Shared by the `const: null`\n * and the drf-spectacular `NullEnum` (`{ enum: [null] }`) branches, which render identically.\n */\nexport function createNullNode(schema: SchemaObject, name: string | null | undefined, nullable?: true): ast.SchemaNode {\n return ast.factory.createSchema({\n type: 'null',\n primitive: 'null',\n name,\n title: schema.title,\n description: schema.description,\n deprecated: schema.deprecated,\n nullable,\n format: schema.format,\n })\n}\n\n/**\n * Converts an OAS 3.1 `const` schema into a null scalar or a single-value `EnumSchemaNode`.\n */\nexport function convertConst({ schema, name, nullable, defaultValue }: ConvertContext): ast.SchemaNode {\n const constValue = schema.const\n\n if (constValue === null) {\n return createNullNode(schema, name)\n }\n\n const constPrimitive = getPrimitiveType(typeof constValue === 'number' ? 'number' : typeof constValue === 'boolean' ? 'boolean' : 'string')\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'enum',\n primitive: constPrimitive,\n enumValues: [constValue as string | number | boolean],\n },\n )\n}\n\n/**\n * Converts a format-annotated schema into a special-type `SchemaNode`. Only called once the\n * `format` rule's `match` has confirmed the format is handled (see `isHandledFormat`) and, for\n * a date-ish format, that `dateType` is not `false`.\n */\nexport function convertFormat(context: ConvertContext): ast.SchemaNode {\n const { schema, name, nullable, defaultValue, options, type } = context\n const ctx = { schema, name, nullable, defaultValue }\n\n // A numeric format on a `type: 'string'` schema describes how the number is spelled, not that\n // the value is a number, so the declared type wins. The format stays on the node for plugins\n // that want to validate the digits.\n if (type === 'string' && numericFormats.has(schema.format!)) {\n return convertString(context)\n }\n\n if (schema.format === 'int64' || schema.format === 'uint64') {\n return createNode(ctx, {\n type: options.integerType === 'bigint' ? 'bigint' : 'integer',\n primitive: 'integer',\n min: schema.minimum,\n max: schema.maximum,\n ...getExclusiveBounds(schema),\n })\n }\n\n if (schema.format === 'date-time' || schema.format === 'date' || schema.format === 'time') {\n const dateType = getDateType(options, schema.format)!\n\n if (dateType.type === 'datetime') {\n return createNode(ctx, {\n primitive: 'string' as const,\n type: 'datetime',\n offset: dateType.offset,\n local: dateType.local,\n })\n }\n return createNode(ctx, {\n primitive: 'string' as const,\n type: dateType.type,\n representation: dateType.representation,\n })\n }\n\n const specialType = getSchemaType(schema.format!)!\n\n const specialPrimitive: ast.PrimitiveSchemaType = specialType === 'number' || specialType === 'integer' || specialType === 'bigint' ? specialType : 'string'\n const hasLength = specialType === 'url' || specialType === 'uuid' || specialType === 'email'\n\n return createNode(ctx, {\n primitive: specialPrimitive,\n type: specialType as ast.ScalarSchemaType,\n ...(hasLength ? { min: schema.minLength, max: schema.maxLength } : {}),\n })\n}\n\n/**\n * Converts an `enum` schema into an `EnumSchemaNode`.\n */\nexport function convertEnum({ schema, name, nullable, type, rawOptions, parse }: ConvertContext): ast.SchemaNode {\n if (type === 'array') {\n return parse({ schema: normalizeArrayEnum(schema), name }, rawOptions)\n }\n\n const nullInEnum = schema.enum!.includes(null)\n const filteredValues = (nullInEnum ? schema.enum!.filter((v) => v !== null) : schema.enum!) as Array<string | number | boolean>\n\n // drf-spectacular `NullEnum` ({ enum: [null] }) is just `null`. An empty enum node would\n // render as `never` (plugin-ts) / invalid `z.enum([])` (plugin-zod). Mirror the `const: null`\n // branch so it renders as a clean `null` (not `z.null().nullable()`).\n if (nullInEnum && filteredValues.length === 0) {\n return createNullNode(schema, name)\n }\n\n const enumNullable = nullable || nullInEnum || undefined\n const enumDefault = schema.default === null && enumNullable ? undefined : schema.default\n const enumPrimitive = getPrimitiveType(type)\n\n const ctx = { schema, name, nullable: enumNullable as true | undefined, defaultValue: enumDefault }\n const enumExtras = {\n type: 'enum' as const,\n primitive: enumPrimitive,\n }\n\n const extensionKey = enumExtensionKeys.find((key) => key in schema)\n const descriptionKey = enumDescriptionKeys.find((key) => key in schema)\n if (extensionKey || descriptionKey || enumPrimitive === 'number' || enumPrimitive === 'integer' || enumPrimitive === 'boolean') {\n let enumPrimitiveType: 'number' | 'boolean' | 'string' = 'string'\n if (enumPrimitive === 'number' || enumPrimitive === 'integer') enumPrimitiveType = 'number'\n else if (enumPrimitive === 'boolean') enumPrimitiveType = 'boolean'\n const rawEnumNames = extensionKey ? ((schema as Record<string, unknown>)[extensionKey] as Array<string | number>) : undefined\n const rawEnumDescriptions = descriptionKey ? ((schema as Record<string, unknown>)[descriptionKey] as Array<string>) : undefined\n const uniqueValues = [...new Set(filteredValues)]\n const seenNames = new Set<string>()\n\n return createNode(ctx, {\n ...enumExtras,\n primitive: enumPrimitiveType,\n namedEnumValues: uniqueValues\n .map((value, index) => ({\n name: String(rawEnumNames?.[index] ?? value),\n value,\n primitive: enumPrimitiveType,\n description: rawEnumDescriptions?.[index],\n }))\n .filter((entry) => {\n if (seenNames.has(entry.name)) return false\n seenNames.add(entry.name)\n return true\n }),\n })\n }\n\n return createNode(ctx, {\n ...enumExtras,\n enumValues: [...new Set(filteredValues)],\n })\n}\n\n/**\n * Converts a `type: 'string'` schema into a `StringSchemaNode`.\n */\nexport function convertString({ schema, name, nullable, defaultValue }: ConvertContext): ast.SchemaNode {\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'string',\n primitive: 'string',\n min: schema.minLength,\n max: schema.maxLength,\n pattern: schema.pattern,\n },\n )\n}\n\n/**\n * Converts a `type: 'number'` or `type: 'integer'` schema.\n */\nexport function convertNumeric({ schema, name, nullable, defaultValue }: ConvertContext, type: 'number' | 'integer'): ast.SchemaNode {\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type,\n primitive: type,\n min: schema.minimum,\n max: schema.maximum,\n ...getExclusiveBounds(schema),\n multipleOf: schema.multipleOf,\n },\n )\n}\n\n/**\n * Converts a `type: 'boolean'` schema.\n */\nexport function convertBoolean({ schema, name, nullable, defaultValue }: ConvertContext): ast.SchemaNode {\n return createNode({ schema, name, nullable, defaultValue }, { type: 'boolean', primitive: 'boolean' })\n}\n\n/**\n * Converts a binary string schema (`type: 'string'`, `contentMediaType: 'application/octet-stream'`)\n * into a `blob` node.\n */\nexport function convertBinary({ schema, name, nullable, defaultValue }: ConvertContext): ast.SchemaNode {\n return createNode({ schema, name, nullable, defaultValue }, { type: 'blob', primitive: 'string' })\n}\n","import { ast } from '@kubb/ast'\nimport { childName, enumPropName, macroDiscriminatorEnum, macroEnumName } from '@kubb/kit'\nimport { isDiscriminator, isNullable } from '../../oas.ts'\nimport type { SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\n\n/**\n * Resolves a `true` or empty-object map schema (`additionalProperties`/`patternProperties`) to\n * `options.unknownType`, otherwise parses it as a regular schema.\n */\nfunction resolveMapSchema(\n mapSchema: unknown,\n options: ConvertContext['options'],\n parse: ConvertContext['parse'],\n rawOptions: ConvertContext['rawOptions'],\n): ast.SchemaNode {\n if (mapSchema === true || (typeof mapSchema === 'object' && Object.keys(mapSchema as object).length === 0)) {\n return ast.factory.createSchema({ type: options.unknownType })\n }\n return parse({ schema: mapSchema as SchemaObject }, rawOptions)\n}\n\n/**\n * Names the inline enums on a property's schema, and on each item when the property is a tuple, from\n * the parent and property name. Wraps `macroEnumName` at the property construction site.\n */\nfunction nameEnums(node: ast.SchemaNode, options: { parentName: string | null | undefined; propName: string; enumSuffix: string }): ast.SchemaNode {\n const macro = macroEnumName(options)\n const named = ast.applyMacros(node, [macro], { depth: 'shallow' })\n const tupleNode = ast.narrowSchema(named, 'tuple')\n if (tupleNode?.items) {\n const namedItems = tupleNode.items.map((item) => ast.applyMacros(item, [macro], { depth: 'shallow' }))\n if (namedItems.some((item, i) => item !== tupleNode.items![i])) {\n return { ...tupleNode, items: namedItems }\n }\n }\n return named\n}\n\n/**\n * Converts an object-like schema into an `ObjectSchemaNode`.\n */\nexport function convertObject({ schema, name, nullable, defaultValue, rawOptions, options, parse }: ConvertContext): ast.SchemaNode {\n const properties: Array<ast.PropertyNode> = schema.properties\n ? Object.entries(schema.properties).map(([propName, propSchema]) => {\n const required = Array.isArray(schema.required) ? schema.required.includes(propName) : !!schema.required\n const resolvedPropSchema = propSchema as SchemaObject\n const propNullable = isNullable(resolvedPropSchema)\n\n const resolvedChildName = childName(name, propName)\n const propNode = parse({ schema: resolvedPropSchema, name: resolvedChildName }, rawOptions)\n const schemaNode = nameEnums(propNode, { parentName: name, propName, enumSuffix: options.enumSuffix })\n\n return ast.factory.createProperty({\n name: propName,\n schema: {\n ...schemaNode,\n nullable: schemaNode.type === 'null' ? undefined : propNullable || undefined,\n },\n required,\n })\n })\n : []\n\n const additionalProperties = schema.additionalProperties\n let additionalPropertiesNode: ast.SchemaNode | boolean | undefined\n if (additionalProperties === true) additionalPropertiesNode = true\n else if (additionalProperties) additionalPropertiesNode = resolveMapSchema(additionalProperties, options, parse, rawOptions)\n else additionalPropertiesNode = additionalProperties\n\n const rawPatternProperties = 'patternProperties' in schema ? schema.patternProperties : undefined\n\n const patternProperties = rawPatternProperties\n ? Object.fromEntries(\n Object.entries(rawPatternProperties).map(([pattern, patternSchema]) => [pattern, resolveMapSchema(patternSchema, options, parse, rawOptions)]),\n )\n : undefined\n\n const objectNode: ast.SchemaNode = createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'object',\n primitive: 'object',\n properties,\n additionalProperties: additionalPropertiesNode,\n patternProperties,\n minProperties: schema.minProperties,\n maxProperties: schema.maxProperties,\n },\n )\n\n if (isDiscriminator(schema) && schema.discriminator.mapping) {\n const discPropName = schema.discriminator.propertyName\n const values = Object.keys(schema.discriminator.mapping)\n const enumName = name ? enumPropName(name, discPropName, options.enumSuffix) : undefined\n return ast.applyMacros(objectNode, [macroDiscriminatorEnum({ propertyName: discPropName, values, enumName })], { depth: 'shallow' })\n }\n\n return objectNode\n}\n\n/**\n * Converts an OAS 3.1 `prefixItems` tuple into a `TupleSchemaNode`.\n */\nexport function convertTuple({ schema, name, nullable, defaultValue, rawOptions, options, parse }: ConvertContext): ast.SchemaNode {\n const tupleItems = (schema.prefixItems ?? []).map((item) => parse({ schema: item as SchemaObject }, rawOptions))\n // items: false closes the tuple; absent/true widens the tail to unknownType.\n const rest =\n schema.items === false\n ? undefined\n : !schema.items || schema.items === true\n ? ast.factory.createSchema({ type: options.unknownType })\n : parse({ schema: schema.items as SchemaObject }, rawOptions)\n\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'tuple',\n primitive: 'array',\n items: tupleItems,\n rest,\n min: schema.minItems,\n max: schema.maxItems,\n },\n )\n}\n\n/**\n * Converts a `type: 'array'` schema into an `ArraySchemaNode`.\n */\nexport function convertArray({ schema, name, nullable, defaultValue, rawOptions, options, parse }: ConvertContext): ast.SchemaNode {\n const rawItems = schema.items as SchemaObject | undefined\n const itemName = rawItems?.enum?.length && name ? enumPropName(null, name, options.enumSuffix) : name\n const items = rawItems ? [parse({ schema: rawItems, name: itemName }, rawOptions)] : []\n\n return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: 'array',\n primitive: 'array',\n items,\n min: schema.minItems,\n max: schema.maxItems,\n unique: schema.uniqueItems ?? undefined,\n },\n )\n}\n","import type { ast } from '@kubb/ast'\nimport { isBinary, isReference } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport type { Document, SchemaObject } from '../types.ts'\nimport { convertAllOf, convertMultiType, convertRef, convertUnion } from './converters/composition.ts'\nimport { convertBinary, convertBoolean, convertConst, convertEnum, convertFormat, convertNumeric, convertString, createNullNode } from './converters/scalar.ts'\nimport { convertArray, convertObject, convertTuple } from './converters/structural.ts'\nimport { isHandledFormat, resolveDateTypeValue } from './schemaShape.ts'\n\n/**\n * Pre-computed per-schema context passed to every schema converter.\n *\n * Centralizes schema derivations (type resolution, defaults, options) to avoid repeated\n * computation across all conversion branches. The `type` field is normalized from OAS 3.1\n * multi-type arrays to a single string.\n */\nexport type SchemaContext = {\n schema: SchemaObject\n name: string | null | undefined\n nullable: true | undefined\n defaultValue: unknown\n /**\n * Normalized single type string (first non-`null` element when OAS 3.1 multi-type array, so\n * `['null', 'string']` and `['string', 'null']` both normalize to `string` with `nullable` set).\n */\n type: string | undefined\n rawOptions: Partial<ast.ParserOptions> | undefined\n options: ast.ParserOptions\n}\n\n/**\n * Recurses into a nested schema. Converters call this instead of capturing the parser closure,\n * so each converter stays a standalone function.\n */\nexport type ParseFn = (entry: { schema: SchemaObject; name?: string | null }, rawOptions?: Partial<ast.ParserOptions>) => ast.SchemaNode\n\n/**\n * What a converter needs from the parser instance beyond the schema: how to recurse, the source\n * document, and the `$ref` service bound to it.\n */\nexport type ConverterDeps = {\n parse: ParseFn\n document: Document\n refs: Refs\n /**\n * Collision renames keyed by the original component pointer, used to stamp `targetName`\n * on ref nodes whose target the adapter renamed.\n */\n renames?: ReadonlyMap<string, string>\n}\n\n/**\n * Everything a converter receives: the per-schema context plus what it needs from the parser instance.\n */\nexport type ConvertContext = SchemaContext & ConverterDeps\n\n/**\n * One entry in the ordered schema rule table: a predicate paired with a converter. `match`\n * fully decides whether this rule owns the context, so `convert` always produces a node.\n */\nexport type SchemaRule = {\n /**\n * Returns `true` when this rule is responsible for the given context.\n */\n match: (context: ConvertContext) => boolean\n /**\n * Produces a node for the context.\n */\n convert: (context: ConvertContext) => ast.SchemaNode\n}\n\n/**\n * Ordered schema rule table. Order is significant: composition keywords (`$ref`, `allOf`,\n * `oneOf`/`anyOf`) take precedence over `const`, which takes precedence over a genuine OAS 3.1\n * multi-type array (more than one non-`null` type), which takes precedence over `format`/`type`.\n * A multi-type array must split into its per-type members before `format` runs, otherwise\n * `format` collapses the whole schema to one type (e.g. `type: ['null', 'integer', 'string'],\n * format: 'int32'` would drop `string` and emit just `integer`); each split-off member still\n * carries the original `format` and re-enters this table, so `format` still applies per member.\n * The first matching rule that produces a node wins. See {@link SchemaRule} for the\n * match/convert/fall-through contract.\n */\nexport const schemaRules: Array<SchemaRule> = [\n { match: ({ schema }) => isReference(schema), convert: convertRef },\n { match: ({ schema }) => !!schema.allOf?.length, convert: convertAllOf },\n { match: ({ schema }) => !!(schema.oneOf?.length || schema.anyOf?.length), convert: convertUnion },\n { match: ({ schema }) => 'const' in schema && schema.const !== undefined, convert: convertConst },\n { match: ({ schema }) => Array.isArray(schema.type) && schema.type.filter((t) => t !== 'null').length > 1, convert: convertMultiType },\n {\n match: ({ schema, options }) => {\n if (!schema.format) return false\n if (schema.format === 'date-time' || schema.format === 'date' || schema.format === 'time')\n return resolveDateTypeValue(options.dateType, schema.format) !== false\n return isHandledFormat(schema.format)\n },\n convert: convertFormat,\n },\n { match: ({ schema }) => isBinary(schema), convert: convertBinary },\n {\n match: ({ schema, type }) => !type && (schema.minLength !== undefined || schema.maxLength !== undefined || schema.pattern !== undefined),\n convert: convertString,\n },\n {\n match: ({ schema, type }) => !type && (schema.minimum !== undefined || schema.maximum !== undefined),\n convert: (ctx) => convertNumeric(ctx, 'number'),\n },\n { match: ({ schema }) => !!schema.enum?.length, convert: convertEnum },\n {\n match: ({ schema, type }) => type === 'object' || !!schema.properties || !!schema.additionalProperties || 'patternProperties' in schema,\n convert: convertObject,\n },\n { match: ({ schema }) => 'prefixItems' in schema, convert: convertTuple },\n { match: ({ schema, type }) => type === 'array' || 'items' in schema, convert: convertArray },\n { match: ({ type }) => type === 'string', convert: convertString },\n { match: ({ type }) => type === 'number', convert: (ctx) => convertNumeric(ctx, 'number') },\n { match: ({ type }) => type === 'integer', convert: (ctx) => convertNumeric(ctx, 'integer') },\n { match: ({ type }) => type === 'boolean', convert: convertBoolean },\n { match: ({ type }) => type === 'null', convert: ({ schema, name, nullable }) => createNullNode(schema, name, nullable) },\n]\n","import type { ast } from '@kubb/ast'\nimport { type Diagnostic, Diagnostics } from '@kubb/core'\nimport { isReference } from './oas.ts'\nimport type { Document, SchemaObject } from './types.ts'\n\nconst _refCache = new WeakMap<Document, Map<string, unknown>>()\n\n/**\n * Walks a local `#/...` JSON pointer against `document`, memoized per document. `applicable` is\n * `false` for an empty or non-local ref (the caller should not treat that as a failed lookup).\n * Shared by `resolveRef`'s reporting walk and `createRefs().resolve`'s silent walk, so both use\n * the same trimming and caching instead of two separate implementations.\n */\nfunction walkPointer<T>(document: Document, $ref: string): { applicable: boolean; value: T | null } {\n const trimmed = $ref.trim()\n if (trimmed === '' || !trimmed.startsWith('#')) {\n return { applicable: false, value: null }\n }\n const pointer = globalThis.decodeURIComponent(trimmed.substring(1))\n\n let docCache = _refCache.get(document)\n if (!docCache) {\n docCache = new Map()\n _refCache.set(document, docCache)\n }\n\n if (docCache.has(pointer)) {\n return { applicable: true, value: docCache.get(pointer) as T }\n }\n\n const current = pointer\n .split('/')\n .filter(Boolean)\n .reduce((obj: unknown, key: string) => (obj as Record<string, unknown>)?.[key], document as unknown)\n\n if (current) {\n docCache.set(pointer, current)\n }\n\n return { applicable: true, value: (current as T) ?? null }\n}\n\n/**\n * Resolves a local JSON pointer reference from a document.\n *\n * Accepts `#/...` refs. Returns `null` for an empty or non-local ref. When the pointer cannot be\n * resolved, reports a `refNotFound` diagnostic into the active build and returns `null`. Outside a\n * build there is no sink to collect it, so it throws instead.\n *\n * @example\n * ```ts\n * resolveRef<SchemaObject>(document, '#/components/schemas/Pet')\n * ```\n */\nexport function resolveRef<T = unknown>(document: Document, $ref: string): T | null {\n const { applicable, value } = walkPointer<T>(document, $ref)\n if (!applicable) return null\n if (value) return value\n\n const diagnostic: Diagnostic = {\n code: Diagnostics.code.refNotFound,\n severity: 'error',\n message: `Could not find a definition for ${$ref}.`,\n help: 'Add the schema under `components.schemas`, or fix the `$ref`. Run `kubb validate` to check the spec.',\n location: { kind: 'schema', pointer: $ref, ref: $ref },\n }\n // Report the unresolved ref into the active build and resolve to null, like any\n // other unresolvable ref. The build collects it and keeps going. Outside a build there is no\n // sink, so throw rather than silently returning null.\n if (!Diagnostics.report(diagnostic)) {\n throw new Diagnostics.Error(diagnostic)\n }\n return null\n}\n\n/**\n * Resolves a `$ref` object while preserving the original `$ref` field on the result.\n *\n * Useful for parser flows that need both dereferenced fields and pointer\n * identity (for naming/import purposes). Non-reference values are returned as-is.\n *\n * @example\n * ```ts\n * dereferenceWithRef(document, { $ref: '#/components/schemas/Pet' })\n * // { $ref: '#/components/schemas/Pet', type: 'object', properties: { ... } }\n * ```\n */\nexport function dereferenceWithRef<T = unknown>(document: Document, schema?: T): T {\n if (isReference(schema)) {\n return {\n ...schema,\n ...resolveRef(document, schema.$ref),\n $ref: schema.$ref,\n }\n }\n\n return schema as T\n}\n\n/**\n * Parses a schema for a resolved `$ref` target. Passed in at call time (rather than imported)\n * so `refs.ts` stays independent of the parser/converter layer.\n */\ntype RefNodeParser = (entry: { schema: SchemaObject; name?: string | null }, rawOptions?: Partial<ast.ParserOptions>) => ast.SchemaNode\n\n/**\n * The `$ref` service bound to one document: pointer resolution, existence checks, and\n * resolved-node parsing, each with its own instance-scoped memoization.\n */\nexport type Refs = ReturnType<typeof createRefs>\n\n/**\n * Creates the `$ref` resolution service for one document.\n *\n * Replaces what used to be six overlapping resolvers (a reporting walk, a silent walk, an\n * existence check, and a resolve-then-parse-into-a-node step, each with its own cache) with one\n * pointer walk and one explicit `report` contract for a missing ref: `report: true` (the default)\n * reports a `refNotFound` diagnostic (or throws outside a build), `report: false` resolves to\n * `null` silently for a speculative lookup.\n *\n * @example\n * ```ts\n * const refs = createRefs(document)\n * refs.resolve<SchemaObject>('#/components/schemas/Pet')\n * refs.resolve<SchemaObject>('#/components/schemas/Pet', { report: false })\n * refs.exists('#/components/schemas/Pet')\n * refs.resolveNode('#/components/schemas/Pet', parseSchema)\n * refs.deref<ResponseObject>(operation.schema.responses?.['200'])\n * ```\n */\nexport function createRefs(document: Document) {\n const resolvedNodeCache = new Map<string, ast.SchemaNode | null>()\n const existenceCache = new Map<string, boolean>()\n const resolvingRefs = new Set<string>()\n\n /**\n * Resolves a local `#/...` JSON pointer. Returns `null` for an empty or non-local ref.\n * `report: true` (default) reports a `refNotFound` diagnostic into the active build (or throws\n * outside one) when the pointer cannot be resolved. `report: false` resolves to `null` silently,\n * for a speculative lookup where a missing ref is not an error.\n */\n function resolve<T = unknown>(refPath: string, options?: { report?: boolean }): T | null {\n if (options?.report === false) {\n const { applicable, value } = walkPointer<T>(document, refPath)\n return applicable ? value : null\n }\n\n return resolveRef<T>(document, refPath)\n }\n\n /**\n * Returns `true` when a `$ref` path resolves to a component the document actually defines.\n * A circular ref still resolves to an existing target, so this stays `true` for cycles and only\n * goes `false` for a `$ref` that points at a component the spec never declares. Memoized.\n */\n function exists(refPath: string): boolean {\n if (!existenceCache.has(refPath)) {\n existenceCache.set(refPath, !!resolve(refPath, { report: false }))\n }\n return existenceCache.get(refPath) ?? false\n }\n\n /**\n * Resolves a `$ref` to its parsed node via `parse`, guarding against cycles and memoizing per\n * instance. Returns `null` when the ref is currently being resolved (a cycle) or cannot be\n * resolved (e.g. a minimal document in a unit test).\n */\n function resolveNode(refPath: string, parse: RefNodeParser, rawOptions?: Partial<ast.ParserOptions>): ast.SchemaNode | null {\n if (resolvingRefs.has(refPath)) return null\n\n if (!resolvedNodeCache.has(refPath)) {\n let resolved: ast.SchemaNode | null = null\n try {\n const referenced = resolve<SchemaObject>(refPath)\n if (referenced) {\n resolvingRefs.add(refPath)\n resolved = parse({ schema: referenced }, rawOptions)\n resolvingRefs.delete(refPath)\n }\n } catch {\n // Ref cannot be resolved in this document (e.g. unit tests with minimal documents).\n }\n resolvedNodeCache.set(refPath, resolved)\n }\n\n return resolvedNodeCache.get(refPath) ?? null\n }\n\n /**\n * Resolves a `$ref` value without mutating anything: when `value` holds a `$ref`, returns the\n * resolved target. Returns `null` when the value is empty, cannot be resolved, or is still a\n * `$ref` after resolving (e.g. a document with no component registry). A non-`$ref` value is\n * returned as-is.\n *\n * @example\n * ```ts\n * refs.deref<ResponseObject>(operation.schema.responses?.['200'])\n * ```\n */\n function deref<T = unknown>(value: unknown): T | null {\n if (!isReference(value)) {\n return value ? (value as T) : null\n }\n\n const resolved = resolve<T>(value.$ref)\n return resolved && !isReference(resolved) ? resolved : null\n }\n\n return { resolve, exists, resolveNode, deref }\n}\n","import { isReference, pickContentEntry } from '../oas.ts'\nimport { getRequestBody, getRequestContent, getResponseByStatusCode } from '../operation.ts'\nimport { dereferenceWithRef } from '../refs.ts'\nimport type { Refs } from '../refs.ts'\nimport type { ContentTypeOptions, Document, MediaTypeObject, Operation, ParameterObject, ResponseObject, SchemaObject } from '../types.ts'\n\n/**\n * Returns all parameters for an operation, merging path-level and operation-level entries.\n * Operation-level parameters override path-level ones with the same `in:name` key.\n * Each `$ref` parameter is dereferenced via `dereferenceWithRef` before merging.\n *\n * @example\n * ```ts\n * getParameters({ document, operation })\n * // [{ name: 'petId', in: 'path', required: true, schema: { type: 'integer' } }]\n * ```\n */\nexport function getParameters({ document, operation }: { document: Document; operation: Operation }): Array<ParameterObject> {\n const resolveParams = (params: Array<unknown>): Array<ParameterObject> =>\n params.map((p) => dereferenceWithRef(document, p)).filter((p): p is ParameterObject => !!p && typeof p === 'object' && 'in' in p && 'name' in p)\n\n const operationParams = resolveParams(operation.schema?.parameters || [])\n const pathLevelParams = resolveParams((operation.pathItem as { parameters?: Array<unknown> }).parameters ?? [])\n\n const paramMap = new Map<string, ParameterObject>()\n for (const p of pathLevelParams) {\n if (p.name && p.in) {\n paramMap.set(`${p.in}:${p.name}`, p)\n }\n }\n for (const p of operationParams) {\n if (p.name && p.in) {\n paramMap.set(`${p.in}:${p.name}`, p)\n }\n }\n\n return Array.from(paramMap.values())\n}\n\nfunction getResponseBody(responseBody: boolean | ResponseObject, contentType?: string): MediaTypeObject | false {\n if (!responseBody) return false\n if (isReference(responseBody)) return false\n\n const body = responseBody as ResponseObject\n if (!body.content) return false\n\n if (contentType) {\n return contentType in body.content ? body.content[contentType]! : false\n }\n\n const picked = pickContentEntry(body.content)\n return picked ? picked[1] : false\n}\n\n/**\n * Returns the response schema for a given operation and HTTP status code.\n *\n * Returns an empty object `{}` when no response body schema is available.\n *\n * @example\n * ```ts\n * getResponseSchema({ document, operation, refs, statusCode: 200 }) // SchemaObject\n * getResponseSchema({ document, operation, refs, statusCode: '4XX' }) // {}\n * ```\n */\nexport function getResponseSchema({\n document,\n operation,\n refs,\n statusCode,\n options = {},\n}: {\n document: Document\n operation: Operation\n refs: Refs\n statusCode: string | number\n options?: ContentTypeOptions\n}): SchemaObject {\n const responseBody = getResponseBody(getResponseByStatusCode({ operation, refs, statusCode }), options.contentType)\n\n if (responseBody === false) {\n return {}\n }\n\n const schema = responseBody.schema\n\n if (!schema) {\n return {}\n }\n\n return dereferenceWithRef(document, schema)\n}\n\n/**\n * Returns the request body schema for an operation, or `null` when absent.\n *\n * @example\n * ```ts\n * getRequestSchema({ document, operation, refs }) // SchemaObject | null\n * ```\n */\nexport function getRequestSchema({\n document,\n operation,\n refs,\n options = {},\n}: {\n document: Document\n operation: Operation\n refs: Refs\n options?: ContentTypeOptions\n}): SchemaObject | null {\n const requestBody = getRequestContent({ operation, refs, mediaType: options.contentType })\n\n if (requestBody === false) {\n return null\n }\n\n const mediaType = Array.isArray(requestBody) ? requestBody[0] : options.contentType\n const schema = Array.isArray(requestBody) ? requestBody[1].schema : requestBody.schema\n\n // OAS 3.1 (and the 3.0 -> 3.1 upgrade) drops the schema for an `application/octet-stream` body,\n // leaving an empty media type object. Synthesize the binary schema so generators still emit a\n // request body type for the operation.\n if (mediaType === 'application/octet-stream' && (!schema || Object.keys(schema).length === 0)) {\n return { type: 'string', contentMediaType: 'application/octet-stream' }\n }\n\n if (!schema) {\n return null\n }\n\n return dereferenceWithRef(document, schema)\n}\n\n/**\n * Returns all request body content type keys for an operation, resolving a `$ref` requestBody\n * through `refs`.\n *\n * @example\n * ```ts\n * getRequestBodyContentTypes(operation, refs)\n * // ['application/json', 'multipart/form-data']\n * ```\n */\nexport function getRequestBodyContentTypes(operation: Operation, refs: Refs): Array<string> {\n const body = getRequestBody({ operation, refs })\n\n return body?.content ? Object.keys(body.content) : []\n}\n\n/**\n * Returns all response content type keys for an operation at a given status code, resolving the\n * response `$ref` through `refs`.\n *\n * @example\n * ```ts\n * getResponseBodyContentTypes(operation, refs, 200)\n * // ['application/json', 'application/xml']\n * ```\n */\nexport function getResponseBodyContentTypes(operation: Operation, refs: Refs, statusCode: string | number): Array<string> {\n const responseObj = getResponseByStatusCode({ operation, refs, statusCode })\n if (!responseObj || typeof responseObj !== 'object' || isReference(responseObj)) return []\n\n const body = responseObj as { content?: Record<string, unknown> }\n return body.content ? Object.keys(body.content) : []\n}\n","import { pascalCase } from '@internals/utils'\nimport { ast, type StatusCode } from '@kubb/ast'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { type ConvertContext, schemaRules } from './emit/parseSchema.ts'\nimport { flattenSchema } from './emit/schemaShape.ts'\nimport { getParameters, getRequestBodyContentTypes, getRequestSchema, getResponseBodyContentTypes, getResponseSchema } from './model/operations.ts'\nimport { isNullable, isReference } from './oas.ts'\nimport { getOperationId, getRequestBody, getRequestContentType, getResponseByStatusCode, getResponseStatusCodes } from './operation.ts'\nimport type { Refs } from './refs.ts'\nimport type { ContentTypeOptions, Document, Operation, SchemaObject } from './types.ts'\n\n/**\n * Parser context holding the raw OpenAPI document and optional content-type override.\n *\n * Passed to schema and operation converters to access the full specification\n * and handle content negotiation when multiple media types are available.\n */\nexport type OasParserContext = ContentTypeOptions & {\n document: Document\n refs: Refs\n /**\n * Collision renames from `getSchemas`, keyed by the original component pointer. `convertRef`\n * stamps `targetName` from it at ref creation, so refs to renamed schemas resolve to the\n * emitted name without a post-parse pass.\n */\n renames?: ReadonlyMap<string, string>\n}\n\n/**\n * Creates the schema and operation converters bound to one OpenAPI document.\n *\n * Takes the `$ref` service for this document (shared with the rest of the pipeline, see\n * `adapter.ts`) and owns the `parseSchema` recursion seam, then dispatches each schema through\n * the ordered `schemaRules` table from `emit/parseSchema.ts`. Every converter is a standalone\n * function that recurses through the `parse` function passed to it, so this file only wires\n * state to the converters.\n *\n * @internal\n */\nexport function createSchemaParser(ctx: OasParserContext) {\n const document = ctx.document\n const refs = ctx.refs\n\n /**\n * Converts an OAS `SchemaObject` into a `SchemaNode`.\n *\n * Builds the per-schema context, then walks the ordered {@link schemaRules} table and returns\n * the first converter that produces a node. When none match, falls back to the configured\n * `emptySchemaType`.\n */\n function parseSchema({ schema, name }: { schema: SchemaObject; name?: string | null }, rawOptions?: Partial<ast.ParserOptions>): ast.SchemaNode {\n const options: ast.ParserOptions = {\n ...DEFAULT_PARSER_OPTIONS,\n ...rawOptions,\n }\n const flattenedSchema = flattenSchema(schema)\n if (flattenedSchema && flattenedSchema !== schema) {\n return parseSchema({ schema: flattenedSchema, name }, rawOptions)\n }\n\n const nullable = isNullable(schema) || undefined\n const defaultValue = schema.default === null && nullable ? undefined : schema.default\n const type = Array.isArray(schema.type) ? (schema.type.find((t) => t !== 'null') ?? schema.type[0]) : schema.type\n\n const context: ConvertContext = {\n schema,\n name,\n nullable,\n defaultValue,\n type,\n rawOptions,\n options,\n parse: parseSchema,\n document,\n refs,\n renames: ctx.renames,\n }\n\n for (const rule of schemaRules) {\n if (rule.match(context)) return rule.convert(context)\n }\n\n const emptyType = options.emptySchemaType\n return ast.factory.createSchema({\n type: emptyType as ast.ScalarSchemaType,\n name,\n title: schema.title,\n description: schema.description,\n format: schema.format,\n })\n }\n\n /**\n * Converts a dereferenced OAS parameter object into a `ParameterNode`.\n */\n function parseParameter(options: ast.ParserOptions, param: Record<string, unknown>, parentName?: string): ast.ParameterNode {\n const required = (param['required'] as boolean | undefined) ?? false\n const paramName = param['name'] as string\n const schemaName = parentName && paramName ? pascalCase(`${parentName} ${paramName}`) : undefined\n\n const schema: ast.SchemaNode = param['schema']\n ? parseSchema({ schema: param['schema'] as SchemaObject, name: schemaName }, options)\n : ast.factory.createSchema({ type: options.unknownType })\n\n const style = param['style'] as ast.ParameterStyle | undefined\n const explode = param['explode'] as boolean | undefined\n\n return ast.factory.createParameter({\n name: paramName,\n in: param['in'] as ast.ParameterLocation,\n schema: {\n ...schema,\n description: (param['description'] as string | undefined) ?? schema.description,\n },\n required,\n ...(style !== undefined ? { style } : {}),\n ...(explode !== undefined ? { explode } : {}),\n })\n }\n\n /**\n * Reads the inline `requestBody` metadata (description / required) that OAS exposes\n * outside the schema itself, resolving a `$ref` requestBody through `refs`. Returns an\n * empty object when the request body is missing or cannot be resolved.\n */\n function getRequestBodyMeta(operation: Operation): {\n description?: string\n required: boolean\n } {\n const body = getRequestBody({ operation, refs })\n if (!body) return { required: false }\n\n return {\n description: body.description,\n required: body.required === true,\n }\n }\n\n /**\n * Collects property names whose schema has a truthy boolean flag (`readOnly` or `writeOnly`).\n * `$ref` entries are skipped since their flags live on the dereferenced target.\n */\n function collectPropertyKeysByFlag(schema: SchemaObject | null, flag: 'readOnly' | 'writeOnly'): Array<string> | null {\n if (!schema?.properties) return null\n\n const keys: Array<string> = []\n for (const key in schema.properties) {\n const prop = schema.properties[key]\n if (prop && !isReference(prop) && (prop as Record<string, unknown>)[flag]) {\n keys.push(key)\n }\n }\n return keys.length ? keys : null\n }\n\n /**\n * Converts an OAS `Operation` into an `OperationNode`.\n */\n function parseOperation(options: ast.ParserOptions, operation: Operation): ast.OperationNode {\n const operationId = getOperationId(operation)\n const operationName = operationId ? pascalCase(operationId) : undefined\n const parameters: Array<ast.ParameterNode> = getParameters({ document, operation }).map((param) =>\n parseParameter(options, param as unknown as Record<string, unknown>, operationName),\n )\n\n // Determine which content types to include in requestBody.content.\n // When a global contentType is configured, restrict to that single type.\n // Otherwise include every content type declared in the spec.\n const allContentTypes = ctx.contentType ? [ctx.contentType] : getRequestBodyContentTypes(operation, refs)\n\n const requestBodyMeta = getRequestBodyMeta(operation)\n const requestBodyName = operationName ? `${operationName}Request` : undefined\n\n const content = allContentTypes.flatMap((ct) => {\n const schema = getRequestSchema({ document, operation, refs, options: { contentType: ct } })\n if (!schema) return []\n return [\n ast.factory.createContent({\n contentType: ct,\n schema: ast.optionality(parseSchema({ schema, name: requestBodyName }, options), requestBodyMeta.required),\n keysToOmit: collectPropertyKeysByFlag(schema, 'readOnly'),\n }),\n ]\n })\n\n const requestBody =\n content.length > 0 || requestBodyMeta.description\n ? {\n description: requestBodyMeta.description,\n required: requestBodyMeta.required || undefined,\n content: content.length > 0 ? content : undefined,\n }\n : undefined\n\n const responses: Array<ast.ResponseNode> = getResponseStatusCodes(operation).map((statusCode) => {\n const responseObj = getResponseByStatusCode({ operation, refs, statusCode })\n\n // Use `Status<code>` (matching plugin-ts's resolveResponseStatusName convention) so the\n // qualified names for nested enums don't collide with top-level component schemas that\n // happen to be named `<operation><statusCode>` (e.g. `GetMaintenance200`).\n const responseName = operationName ? `${operationName}Status${statusCode}` : undefined\n const description = typeof responseObj === 'object' && responseObj !== null ? (responseObj as { description?: string }).description : undefined\n\n const parseEntrySchema = (contentType?: string) => {\n const raw = getResponseSchema({ document, operation, refs, statusCode, options: { contentType } })\n const node =\n raw && Object.keys(raw).length > 0\n ? parseSchema({ schema: raw, name: responseName }, options)\n : ast.factory.createSchema({ type: options.emptySchemaType })\n return { schema: node, keysToOmit: collectPropertyKeysByFlag(raw, 'writeOnly') }\n }\n\n // Build one entry per declared response content type so plugins can union the variants.\n // When a global contentType is configured, restrict to that single type (mirrors requestBody).\n const responseContentTypes = ctx.contentType ? [ctx.contentType] : getResponseBodyContentTypes(operation, refs, statusCode)\n const content = responseContentTypes.map((contentType) => ast.factory.createContent({ contentType, ...parseEntrySchema(contentType) }))\n\n // Body-less responses keep a single fallback entry so the response still resolves to a\n // (void/any) schema, matching how `requestBody` only carries schemas inside `content`.\n if (content.length === 0) {\n content.push(\n ast.factory.createContent({\n contentType: getRequestContentType({ operation, refs }) || 'application/json',\n ...parseEntrySchema(ctx.contentType),\n }),\n )\n }\n\n return ast.factory.createResponse({\n statusCode: statusCode as StatusCode,\n description,\n content,\n })\n })\n\n const pickDoc = (key: 'summary' | 'description'): string | undefined => {\n const own = operation.schema[key]\n if (typeof own === 'string') return own\n const fallback = (operation.pathItem as Record<string, unknown>)[key]\n return typeof fallback === 'string' ? fallback : undefined\n }\n\n return ast.factory.createOperation({\n operationId,\n protocol: 'http',\n method: operation.method.toUpperCase() as ast.HttpMethod,\n path: operation.path,\n tags: Array.isArray(operation.schema.tags) ? operation.schema.tags.map(String) : [],\n summary: pickDoc('summary') || undefined,\n description: pickDoc('description') || undefined,\n deprecated: operation.schema.deprecated || undefined,\n parameters,\n requestBody,\n responses,\n })\n }\n\n return { parseSchema, parseOperation, parseParameter }\n}\n","import { ast } from '@kubb/ast'\nimport { SCHEMA_REF_PREFIX } from './constants.ts'\n\n/**\n * Collects inline enums to lift to the top level, keyed by the name the parser derived for them\n * (e.g. `PetStatusEnum`). An enum already defined as a top-level component is left as-is, and a\n * name that recurs maps to the first definition so each name yields one shared type.\n */\nexport function collectInlineEnums(roots: ReadonlyArray<ast.Node>, topLevelNames: ReadonlySet<string>): Map<string, ast.SchemaNode> {\n const promoted = new Map<string, ast.SchemaNode>()\n\n for (const root of roots) {\n const isSchemaRoot = root.kind === 'Schema'\n for (const node of ast.collect<ast.SchemaNode>(root, { schema: (schemaNode) => schemaNode })) {\n if (node.type !== 'enum' || !node.name) continue\n // Skip a top-level enum component (it is already its own type) and any enum whose name a\n // component already owns.\n if (isSchemaRoot && node === root) continue\n if (topLevelNames.has(node.name)) continue\n if (!promoted.has(node.name)) promoted.set(node.name, { ...node, optional: undefined, nullish: undefined })\n }\n }\n\n return promoted\n}\n\n/**\n * Replaces every promoted inline enum in `node` with a `ref` to its lifted definition, keeping the\n * occurrence's usage-slot and documentation fields.\n */\nexport function refPromotedEnums<T extends ast.Node>(node: T, promoted: ReadonlyMap<string, ast.SchemaNode>): T {\n if (promoted.size === 0) return node\n\n return ast.transform(node, {\n schema(schemaNode) {\n if (schemaNode.type !== 'enum' || !schemaNode.name || !promoted.has(schemaNode.name)) return undefined\n\n return ast.factory.createSchema({\n type: 'ref',\n name: schemaNode.name,\n ref: `${SCHEMA_REF_PREFIX}${schemaNode.name}`,\n optional: schemaNode.optional,\n nullish: schemaNode.nullish,\n readOnly: schemaNode.readOnly,\n writeOnly: schemaNode.writeOnly,\n deprecated: schemaNode.deprecated,\n description: schemaNode.description,\n default: schemaNode.default,\n examples: schemaNode.examples,\n })\n },\n }) as T\n}\n","import { resolveRefName } from '@kubb/ast'\nimport type { ast } from '@kubb/ast'\nimport { Diagnostics } from '@kubb/core'\nimport { isHandledFormat } from './emit/schemaShape.ts'\n\n/**\n * Scans one freshly converted top-level schema in a single walk, so the post-convert pass never\n * sweeps the same nodes twice. It reports the advisory diagnostics (`KUBB_UNSUPPORTED_FORMAT`,\n * `KUBB_DEPRECATED`) and returns the names of every schema the node references, ready to feed the\n * circular-dependency graph.\n *\n * Walks the node the parser produced, threading the RFC 6901 pointer as it descends so a nested\n * field reports against its full path (`#/components/schemas/Pet/properties/owner/properties/name`).\n * Refs are recorded by name and not followed, so the resolved schema is reported under its own walk.\n * Reports land in the active build run, are a no-op outside one, and repeats are deduped by the build.\n */\nexport function scanSchema({ node, name }: { node: ast.SchemaNode; name: string }): Set<string> {\n const refs = new Set<string>()\n visit(node, `#/components/schemas/${escapePointerToken(name)}`, refs)\n return refs\n}\n\n/**\n * Escapes a single JSON pointer reference token per RFC 6901 (`~` → `~0`, `/` → `~1`), so a\n * property name with those characters maps to a distinct pointer instead of colliding in the dedupe.\n */\nfunction escapePointerToken(token: string): string {\n return token.replace(/~/g, '~0').replace(/\\//g, '~1')\n}\n\nfunction visit(node: ast.SchemaNode, pointer: string, refs: Set<string>): void {\n if (node.type === 'ref') {\n const refName = resolveRefName(node)\n if (refName) refs.add(refName)\n }\n\n if (node.deprecated) {\n Diagnostics.report({\n code: Diagnostics.code.deprecated,\n severity: 'info',\n message: 'This schema is marked as deprecated.',\n location: { kind: 'schema', pointer },\n })\n }\n\n if (typeof node.format === 'string' && !isHandledFormat(node.format)) {\n Diagnostics.report({\n code: Diagnostics.code.unsupportedFormat,\n severity: 'warning',\n message: `Kubb does not map the format \"${node.format}\" to a specific type, so it falls back to the base type.`,\n help: `Use a format Kubb supports, or handle \"${node.format}\" with a custom parser or plugin.`,\n location: { kind: 'schema', pointer },\n })\n }\n\n if (node.type === 'object') {\n for (const property of node.properties) {\n visit(property.schema, `${pointer}/properties/${escapePointerToken(property.name)}`, refs)\n }\n if (node.additionalProperties && typeof node.additionalProperties === 'object') {\n visit(node.additionalProperties, `${pointer}/additionalProperties`, refs)\n }\n return\n }\n\n if (node.type === 'array') {\n for (const item of node.items ?? []) {\n visit(item, `${pointer}/items`, refs)\n }\n return\n }\n\n if (node.type === 'tuple') {\n // Each tuple position has its own pointer, so index them. A shared `/items` would collapse\n // distinct diagnostics in the dedupe.\n for (const [index, item] of (node.items ?? []).entries()) {\n visit(item, `${pointer}/items/${index}`, refs)\n }\n return\n }\n\n if (node.type === 'union' || node.type === 'intersection') {\n for (const [index, member] of (node.members ?? []).entries()) {\n visit(member, `${pointer}/members/${index}`, refs)\n }\n }\n}\n","import { ast, findCircularSchemasFromGraph, narrowSchema } from '@kubb/ast'\nimport { createAdapter } from '@kubb/core'\nimport type { AdapterSource } from '@kubb/core'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { buildDiscriminatorChildMap, patchDiscriminatorNode } from './emit/discriminator/propagate.ts'\nimport type { DiscriminatorTarget } from './emit/discriminator/propagate.ts'\nimport { assertInputExists } from './load/source.ts'\nimport { assertDocument, parseDocument, parseFromConfig, validateDocument } from './load/normalize.ts'\nimport { getSchemas } from './model/components.ts'\nimport { resolveBaseUrl } from './model/server.ts'\nimport { getOperations } from './operation.ts'\nimport { createSchemaParser } from './parser.ts'\nimport { collectInlineEnums, refPromotedEnums } from './promoteEnums.ts'\nimport { createRefs } from './refs.ts'\nimport { scanSchema } from './schemaDiagnostics.ts'\nimport type { AdapterOas, Document, SchemaObject } from './types.ts'\n\n/**\n * The `name` of `@kubb/adapter-oas`, used to identify this adapter in a Kubb config.\n */\nexport const adapterOasName = 'oas' satisfies AdapterOas['name']\n\n/**\n * Default Kubb adapter for OpenAPI 2.0, 3.0, and 3.1 specifications. Reads the\n * spec from `input` (a file path, URL, inline content, or parsed object), validates\n * it, resolves the base URL, and converts every schema and operation into the\n * universal AST that every downstream plugin consumes.\n *\n * Configure once on `defineConfig`. The adapter's choices (date representation,\n * integer width, server URL) apply to every plugin in the build.\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 * server: { index: 0 },\n * discriminator: 'propagate',\n * dateType: 'date',\n * }),\n * plugins: [pluginTs()],\n * })\n * ```\n */\nexport const adapterOas = createAdapter<AdapterOas>((options) => {\n const {\n validate = true,\n contentType,\n server,\n discriminator = 'preserve',\n enums = 'inline',\n dateType = DEFAULT_PARSER_OPTIONS.dateType,\n integerType = DEFAULT_PARSER_OPTIONS.integerType,\n unknownType = DEFAULT_PARSER_OPTIONS.unknownType,\n enumSuffix = DEFAULT_PARSER_OPTIONS.enumSuffix,\n emptySchemaType = unknownType || DEFAULT_PARSER_OPTIONS.emptySchemaType,\n } = options\n\n const parserOptions: ast.ParserOptions = {\n ...DEFAULT_PARSER_OPTIONS,\n dateType,\n integerType,\n unknownType,\n emptySchemaType,\n enumSuffix,\n }\n\n let parsedDocument: Document | null = null\n\n // One cache per source: reusing one adapter instance across a `defineConfig` array must parse\n // each config's spec instead of replaying the first one, and a repeat `.parse()` call for the\n // same source must not redo the work. The `$ref` memo lives inside the `Refs` instance created\n // fresh for each document, scoped to this one pass.\n const inputCache = new WeakMap<AdapterSource, Promise<ast.InputNode>>()\n\n // Parses every schema and operation once. Ref aliases and discriminator children are\n // resolved from the schemas already parsed in this same pass rather than re-parsed.\n function parseInput({\n document,\n refs,\n schemas,\n parser,\n }: {\n document: Document\n refs: ReturnType<typeof createRefs>\n schemas: Record<string, SchemaObject>\n parser: ReturnType<typeof createSchemaParser>\n }): ast.InputNode {\n const { parseSchema, parseOperation } = parser\n\n const parsedByName = new Map<string, ast.SchemaNode>()\n const refAliasMap = new Map<string, ast.SchemaNode>()\n const enumNames: Array<string> = []\n const discriminatorParentNodes: Array<ast.SchemaNode> = []\n // Built from the same walk that reports diagnostics: each schema maps to the names it references,\n // so circular detection reads this graph instead of sweeping the nodes again.\n const refGraph = new Map<string, Set<string>>()\n\n for (const [name, schema] of Object.entries(schemas)) {\n const node = parseSchema({ schema, name }, parserOptions)\n parsedByName.set(name, node)\n const refs = scanSchema({ node, name })\n if (node.name) refGraph.set(node.name, refs)\n if (node.type === 'ref' && node.name && node.name !== name) {\n refAliasMap.set(name, node)\n }\n if (narrowSchema(node, 'enum') && node.name) {\n enumNames.push(node.name)\n }\n if (discriminator === 'propagate' && (schema.oneOf ?? schema.anyOf) && schema.discriminator?.propertyName) {\n discriminatorParentNodes.push(node)\n }\n }\n\n const circularNames = [...findCircularSchemasFromGraph(refGraph)]\n const discriminatorChildMap: Map<string, DiscriminatorTarget> | null =\n discriminatorParentNodes.length > 0 ? buildDiscriminatorChildMap(discriminatorParentNodes) : null\n\n const operationNodes: Array<ast.OperationNode> = []\n for (const operation of getOperations(document, refs)) {\n const operationNode = parseOperation(parserOptions, operation)\n if (operationNode) operationNodes.push(operationNode)\n }\n\n let promotedEnums: Map<string, ast.SchemaNode> | null = null\n if (enums === 'root') {\n promotedEnums = collectInlineEnums([...parsedByName.values(), ...operationNodes], new Set(Object.keys(schemas)))\n for (const name of promotedEnums.keys()) enumNames.push(name)\n }\n\n const schemaNodes: Array<ast.SchemaNode> = promotedEnums ? [...promotedEnums.values()] : []\n for (const name of Object.keys(schemas)) {\n const alias = refAliasMap.get(name)\n\n let node: ast.SchemaNode\n if (alias?.name && parsedByName.has(alias.name)) {\n node = { ...parsedByName.get(alias.name)!, name }\n } else {\n const parsed = parsedByName.get(name)!\n const child = discriminatorChildMap?.get(name)\n node = child ? patchDiscriminatorNode(parsed, child) : parsed\n }\n\n schemaNodes.push(promotedEnums ? refPromotedEnums(node, promotedEnums) : node)\n }\n\n const operations = promotedEnums ? operationNodes.map((node) => refPromotedEnums(node, promotedEnums!)) : operationNodes\n\n return ast.factory.createInput({\n schemas: schemaNodes,\n operations,\n meta: {\n title: document.info?.title,\n description: document.info?.description,\n version: document.info?.version,\n baseURL: resolveBaseUrl({ document, server }),\n circularNames,\n enumNames,\n },\n })\n }\n\n return {\n name: adapterOasName,\n get options() {\n return {\n validate,\n contentType,\n server,\n discriminator,\n enums,\n dateType,\n integerType,\n unknownType,\n emptySchemaType,\n enumSuffix,\n }\n },\n get document() {\n return parsedDocument\n },\n async validate(input, options) {\n await assertInputExists(input)\n const document = await parseDocument(input)\n assertDocument(document)\n await validateDocument(document, options)\n },\n async parse(source) {\n const cached = inputCache.get(source)\n if (cached) return cached\n\n const promise = (async () => {\n const document = await parseFromConfig(source)\n assertDocument(document)\n if (validate) await validateDocument(document)\n parsedDocument = document\n\n const refs = createRefs(document)\n const { schemas, renames } = getSchemas(document, { contentType }, refs)\n const parser = createSchemaParser({ document, refs, contentType, renames })\n\n return parseInput({ document, refs, schemas, parser })\n })()\n inputCache.set(source, promise)\n return promise\n },\n }\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAa,yBAAyB;CACpC,UAAU;CACV,aAAa;CACb,aAAa;CACb,iBAAiB;CACjB,YAAY;AACd;;;;;;;;;;;AAYA,MAAa,oBAAoB;;;;;AAMjC,MAAa,oCAAyC,IAAI,IAAI;CAAC;CAAO;CAAO;CAAQ;CAAU;CAAW;CAAQ;CAAS;AAAO,CAAC;;;;;;;AAQnI,MAAa,iCAAiB,IAAI,IAAI;CAAC;CAAc;CAAS;CAAwB;CAAS;CAAS;CAAS;AAAK,CAAU;;;;;;;AAQhI,MAAa,sCAA2C,IAAI,IAAI;CAAC;CAAS;CAAU;CAAa;CAAQ;AAAM,CAAC;;;;;;;;AAShH,MAAa,iCAAsC,IAAI,IAAI;CAAC;CAAS;CAAS;CAAU;CAAS;AAAQ,CAAC;;;;;;;;;AAU1G,MAAa,YAAY;CACvB,MAAM;CACN,OAAO;CACP,aAAa;CACb,KAAK;CACL,iBAAiB;CACjB,KAAK;CACL,MAAM;CACN,MAAM;CACN,UAAU;CACV,gBAAgB;CAChB,QAAQ;CACR,MAAM;CAGN,OAAO;CACP,OAAO;CACP,QAAQ;AACV;;;;AAKA,MAAa,oBAAoB,CAAC,eAAe,iBAAiB;;;;AAKlE,MAAa,sBAAsB,CAAC,sBAAsB,qBAAqB;;;;;;;;;;AC9E/E,SAAgB,2BAA2B,SAAkE;CAC3G,MAAM,2BAAW,IAAI,IAAiC;CAEtD,KAAK,MAAM,UAAU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