@kubb/adapter-oas 5.14.6 → 5.15.1

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","Diagnostics","load","CORE_SCHEMA","parse","bundle","Diagnostics","join","upgrade","Diagnostics","Diagnostics","ast","ast","ast","enumPrimitive","extractRefName","macroDiscriminatorEnum","ast","extractRefName","mergeAdjacentObjectsLazy","macroSimplifyUnion","ast","ast","macroEnumName","childName","enumPropName","macroDiscriminatorEnum","ast","defineExtension","ast","Diagnostics"],"sources":["../kubb-extension.json","../package.json","../src/constants.ts","../src/emit/discriminator/propagate.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/errors.ts","../../../internals/utils/src/jsonPointer.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/fs.ts","../src/oas.ts","../src/refs.ts","../src/load/source.ts","../src/load/normalize.ts","../src/model/components.ts","../src/model/server.ts","../src/emit/schemaShape.ts","../src/schemaDiagnostics.ts","../src/operation.ts","../src/emit/createNode.ts","../src/emit/discriminator/preserve.ts","../src/emit/converters/annotatedEnum.ts","../src/emit/converters/composition.ts","../src/emit/converters/scalar.ts","../src/emit/converters/structural.ts","../src/emit/parseSchema.ts","../src/parser.ts","../src/promoteEnums.ts","../src/sourceLocator.ts","../src/adapter.ts"],"sourcesContent":["","","import type { ast } from '@kubb/kit'\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 * `query` is the OpenAPI 3.2 field for the HTTP QUERY method (RFC 10008).\n */\nexport const SUPPORTED_METHODS: ReadonlySet<string> = new Set(['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace', 'query'])\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 `emit/converters/scalar.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 * Lists formats whose AST type differs from the OAS `type` field, plus string formats that\n * `KUBB_UNSUPPORTED_FORMAT` should not flag.\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.\n * `uri-reference`, `iri`, `iri-reference`, `hostname` and `idn-hostname` map to `'string'`: a relative\n * reference, a Unicode IRI or a bare host name is not a URL, so a `'url'` validator would reject valid\n * values. `base64url`, `jwt`, `ulid`, `iban` and `duration` map to `'string'` because plugins check\n * them by `format`.\n */\nexport const formatMap = {\n uuid: 'uuid',\n email: 'email',\n 'idn-email': 'email',\n uri: 'url',\n 'uri-reference': 'string',\n iri: 'string',\n 'iri-reference': 'string',\n url: 'url',\n ipv4: 'ipv4',\n ipv6: 'ipv6',\n hostname: 'string',\n 'idn-hostname': 'string',\n binary: 'blob',\n byte: 'blob',\n base64url: 'string',\n jwt: 'string',\n ulid: 'string',\n iban: 'string',\n duration: 'string',\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 } from '@kubb/kit'\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 const unionNode =\n ast.narrowSchema(schema, 'union') ??\n ast\n .narrowSchema(schema, 'intersection')\n ?.members?.map((member) => ast.narrowSchema(member, 'union'))\n .find((union) => union)\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: ast.SchemaNodeByType['ref'] | null = null\n let objNode: ast.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 convert(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// Plugins resolve the same names over and over (about 47,000 calls for a 1,000 schema spec), so\n// results are kept. Clearing at the limit bounds the memory a long-running process spends on it.\nconst cache = new Map<string, string>()\nconst cacheLimit = 10_000\n\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n const key = `${pascal ? 'P' : 'c'}${text}`\n const cached = cache.get(key)\n if (cached !== undefined) return cached\n\n const result = convert(text, pascal)\n if (cache.size >= cacheLimit) cache.clear()\n cache.set(key, result)\n return result\n}\n\n/**\n * Converts `text` to camelCase.\n *\n * @example Word boundaries\n * `camelCase('hello-world') // 'helloWorld'`\n *\n * @example With a prefix\n * `camelCase('tag', { prefix: 'create' }) // 'createTag'`\n */\nexport function camelCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n *\n * @example Word boundaries\n * `pascalCase('hello-world') // 'HelloWorld'`\n *\n * @example With a suffix\n * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`\n */\nexport function pascalCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n","/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new Error('Build failed', { cause: toError(err) })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Returns `error` followed by every error in its `cause` chain, outermost first. Stops at a\n * non-`Error` cause or a cycle.\n *\n * @example\n * ```ts\n * getErrorChain(new Error('Config failed loading', { cause: new Error('boom') })).map((error) => error.message)\n * // ['Config failed loading', 'boom']\n * ```\n */\nexport function getErrorChain(error: unknown): Array<Error> {\n const chain: Array<Error> = []\n for (let current = error; current instanceof Error && !chain.includes(current); current = current.cause) {\n chain.push(current)\n }\n return chain\n}\n","/**\n * Escapes a single JSON pointer reference token per RFC 6901 (`~` → `~0`, `/` → `~1`), so a\n * name holding those characters maps to a distinct pointer.\n *\n * @example\n * ```ts\n * escapePointerToken('/pets/{id}') // '~1pets~1{id}'\n * ```\n */\nexport function escapePointerToken(token: string): string {\n return token.replaceAll('~', '~0').replaceAll('/', '~1')\n}\n","// Bun polyfills `process.versions.node`, so detection keys off the globals instead.\nconst isBun = typeof Bun !== 'undefined'\nconst isDeno = 'Deno' in globalThis\n\n/**\n * The JavaScript runtime executing the current process: its name, version and whether it is Bun.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\nexport const runtime = { isBun, ...detect() } as const\n\nfunction detect(): { name: 'bun' | 'deno' | 'node'; version: string } {\n if (isBun) return { name: 'bun', version: process.versions.bun ?? '' }\n if (isDeno) return { name: 'deno', version: (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? '' }\n return { name: 'node', version: process.versions?.node ?? '' }\n}\n","import { access, glob as globNode, mkdir, readFile, writeFile } from 'node:fs/promises'\n\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\nexport { existsSync } from 'node:fs'\nexport { mkdir, mkdtemp, rm } from 'node:fs/promises'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n await writeRaw(resolved, content)\n\n if (options.sanity) {\n const savedData = await read(resolved)\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Writes UTF-8 content verbatim, including empty files and surrounding whitespace.\n * Uses Bun.write under Bun and creates missing parent directories under either runtime.\n *\n * @example\n * await writeRaw('./cache/output.ts', ' // keep these bytes\\n\\n')\n */\nexport async function writeRaw(path: string, content: string): Promise<void> {\n const resolved = resolve(path)\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return\n }\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n}\n\n/**\n * Lists non-hidden regular files below `directory` as relative POSIX paths, excluding directories and symlinks.\n * Uses Bun.Glob under Bun because its Node glob compatibility API lacks directory-entry support.\n *\n * @example\n * for await (const path of listFiles('./src')) console.log(path)\n */\nexport async function* listFiles(directory: string): AsyncGenerator<string> {\n const cwd = resolve(directory)\n if (runtime.isBun) {\n yield* new Bun.Glob('**/*').scan({ cwd, dot: false, onlyFiles: true, followSymlinks: false })\n return\n }\n for await (const entry of globNode('**/*', { cwd, withFileTypes: true })) {\n if (entry.isFile()) yield toPosixPath(relative(cwd, join(entry.parentPath, entry.name)))\n }\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","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 the `x-*` keys of `source` as-is, or `undefined` when there are none.\n */\nexport function pickExtensions(source: Record<string, unknown>): Record<string, unknown> | undefined {\n const entries = Object.entries(source).filter(([key]) => key.startsWith('x-'))\n return entries.length > 0 ? Object.fromEntries(entries) : undefined\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 raw binary payload.\n */\nexport function isBinary(schema: SchemaObject): boolean {\n return (\n schema.contentMediaType === 'application/octet-stream' && schema.contentEncoding === undefined && (schema.type === undefined || schema.type === 'string')\n )\n}\n\n/**\n * Returns the binary schema for a non-JSON entry the OAS 3.1 upgrade emptied out, or `undefined`\n * when the entry carries a schema of its own. The upgrade rewrites `format: 'binary'` into\n * `contentMediaType` and drops it whenever it only repeats the media type key, for any binary\n * media type (`application/octet-stream`, `application/pdf`, `image/png`, ...), not just\n * `application/octet-stream`. Without the fallback such a body resolves to the empty schema type\n * instead of a blob.\n */\nexport function getBinaryFallbackSchema(mediaType: string | undefined, schema: SchemaObject | ReferenceObject | undefined): SchemaObject | undefined {\n if (!mediaType || isJsonMimeType(mediaType)) return undefined\n if (schema && Object.keys(schema).length > 0) return undefined\n\n return { type: 'string', 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","import { type Diagnostic, Diagnostics } from '@kubb/kit'\nimport type { ast } from '@kubb/kit'\nimport type { ParseFn } from './emit/parseSchema.ts'\nimport { isReference } from './oas.ts'\nimport type { Document, SchemaObject } from './types.ts'\n\n/**\n * The `$ref` service bound to one document: pointer resolution and resolved-node parsing, each\n * with its own instance-scoped memoization.\n */\nexport type Refs = ReturnType<typeof createRefs>\n\n/**\n * Creates the `$ref` resolution service for one document. One pointer walk backs every method.\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.resolveNode('#/components/schemas/Pet', parseSchema)\n * refs.deref<ResponseObject>(operation.schema.responses?.['200'])\n * refs.derefKeepingRef(parameter)\n * ```\n */\nexport function createRefs(document: Document) {\n const pointerCache = new Map<string, unknown>()\n const resolvedNodeCache = new Map<string, ast.SchemaNode | null>()\n const resolvingRefs = new Set<string>()\n\n function walkPointer<T>($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 = trimmed.substring(1)\n\n if (pointerCache.has(pointer)) {\n return { applicable: true, value: pointerCache.get(pointer) as T }\n }\n\n // Split before decoding so an encoded `%2F` stays inside its token, then unescape `~1` and `~0` (RFC 6901).\n const current = pointer\n .split('/')\n .filter(Boolean)\n .map((token) => globalThis.decodeURIComponent(token).replaceAll('~1', '/').replaceAll('~0', '~'))\n .reduce((obj: unknown, key: string) => (obj as Record<string, unknown>)?.[key], document as unknown)\n\n if (current) {\n pointerCache.set(pointer, current)\n }\n\n return { applicable: true, value: (current as T) ?? null }\n }\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 const { applicable, value } = walkPointer<T>(refPath)\n if (!applicable || value || options?.report === false) return value\n\n const diagnostic: Diagnostic = {\n code: Diagnostics.code.refNotFound,\n severity: 'error',\n message: `Could not find a definition for ${refPath}.`,\n help: 'Add the schema under `components.schemas`, or fix the `$ref`. Run `kubb validate` to check the spec.',\n location: { kind: 'schema', pointer: refPath, ref: refPath },\n }\n if (!Diagnostics.report(diagnostic)) {\n throw new Diagnostics.Error(diagnostic)\n }\n return null\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: ParseFn): 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 })\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 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 /** Resolves a `$ref` object but keeps the `$ref` field on the result; other values pass through. */\n function derefKeepingRef<T = unknown>(value?: T): T {\n if (isReference(value)) {\n return { ...value, ...resolve(value.$ref), $ref: value.$ref }\n }\n\n return value as T\n }\n\n return { resolve, resolveNode, deref, derefKeepingRef }\n}\n","import { exists, getErrorMessage, read, toError } from '@internals/utils'\nimport { Diagnostics } from '@kubb/kit'\nimport { CORE_SCHEMA, load } from 'js-yaml'\nimport { parse } from 'yaml'\n\nexport const 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 */\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 return parseYaml(data, {\n origin: sourcePath,\n help: 'Fix the syntax at the reported line, or check that `input` points at the spec and not an HTML page.',\n })\n}\n\n/**\n * Parses a YAML (or JSON) spec. A syntax error throws `KUBB_INVALID_DOCUMENT` naming `origin`,\n * with the parser message, which keeps the line and column.\n *\n * JSON is valid YAML, so one parser handles both. `js-yaml` parses about ten times faster than\n * `yaml`, and unlike `JSON.parse` it rejects duplicate keys instead of keeping the last one. Its\n * core schema keeps timestamps as strings and `<<` as a plain key, as `yaml` does for YAML 1.2.\n */\nexport function parseYaml(data: string, { origin, help }: { origin: string; help: string }): object {\n try {\n const document = load(data, { schema: CORE_SCHEMA })\n if (document !== undefined) return document as object\n } catch {\n // `yaml` parses it again below to report the error with its line and column.\n }\n try {\n return parse(data) as object\n } catch (error) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidDocument,\n severity: 'error',\n message: `Cannot parse ${origin} as JSON or YAML: ${getErrorMessage(error)}`,\n help,\n location: { kind: 'config' },\n cause: toError(error),\n })\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 (urlRegExp.test(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","import { join } from 'node:path'\nimport { escapePointerToken, getErrorMessage, toError } from '@internals/utils'\nimport { Diagnostics } from '@kubb/kit'\nimport type { AdapterSource, Diagnostic } from '@kubb/kit'\nimport { upgrade } from '@scalar/openapi-upgrader'\nimport { bundle } from 'api-ref-bundler'\nimport { createRefs } from '../refs.ts'\nimport type { Document } from '../types.ts'\nimport type { ValidationErrors, WorkerResult } from './validateWorker.ts'\nimport { assertInputExists, parseYaml, 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 * Replaces each `$ref` into `#/paths/...` with a copy of its target, in place.\n *\n * The Swagger 2.0 upgrade moves `responses/200/schema` under `content`, so a ref to the old location\n * would no longer resolve. A ref that points back into itself is kept, since inlining it never ends.\n */\nfunction inlinePathRefs(node: unknown, resolve: (ref: string) => unknown, visiting: Array<string> = []): unknown {\n if (!node || typeof node !== 'object') {\n return node\n }\n\n const ref = (node as { $ref?: unknown }).$ref\n if (typeof ref === 'string' && ref.startsWith('#/paths/') && !visiting.includes(ref)) {\n const target = resolve(ref)\n return target && typeof target === 'object' ? inlinePathRefs(structuredClone(target), resolve, [...visiting, ref]) : node\n }\n\n for (const [key, value] of Object.entries(node)) {\n ;(node as Record<string, unknown>)[key] = inlinePathRefs(value, resolve, visiting)\n }\n return node\n}\n\n// Keys that hold user-named entries. An `x-` name here is a real schema, header or parameter, not an extension.\nconst namedEntryKeys = new Set([\n 'properties',\n 'patternProperties',\n 'headers',\n 'schemas',\n 'responses',\n 'parameters',\n 'requestBodies',\n 'examples',\n 'links',\n 'callbacks',\n 'securitySchemes',\n 'securityDefinitions',\n 'pathItems',\n 'definitions',\n '$defs',\n])\n\n/**\n * True when `path` runs through an `x-` vendor extension. Kubb never reads an extension, so a `$ref`\n * Kubb cannot read inside one cannot change the output.\n */\nfunction isExtensionPath(path: ReadonlyArray<string | number>): boolean {\n return path.some((token, index) => String(token).startsWith('x-') && !namedEntryKeys.has(String(path[index - 1])))\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 * `document` stands in for the file at `pathOrUrl`, such as inline input. Every other file or URL\n * read, including one that fails, lands in `sources`. A `$ref` that cannot be read reports\n * `KUBB_REF_NOT_FOUND` at the key that holds it, as a warning when it sits inside an `x-` extension.\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, { document, sources = [] }: { document?: Document; sources?: Array<string> } = {}): Promise<Document> {\n const cache = new Map<string, Promise<object | string>>()\n // api-ref-bundler refers to the same URL as both `https://` and the posix-normalized\n // `https:/`, so key on the canonical href to fetch each source once and to match the input.\n const toKey = (sourcePath: string) => (urlRegExp.test(sourcePath) ? new URL(sourcePath).href : sourcePath)\n\n const resolver = (sourcePath: string) => {\n if (document && sourcePath === pathOrUrl) {\n return Promise.resolve(document)\n }\n const key = toKey(sourcePath)\n const cached = cache.get(key)\n if (cached) {\n return cached\n }\n\n sources.push(key)\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, {\n hooks: {\n onError: (message, { path, state }) => {\n // Only a `$ref` in the input itself has a key in the document to point at.\n const pointer = toKey(state.baseFile) === toKey(pathOrUrl) ? `#/${path.map((token) => escapePointerToken(String(token))).join('/')}` : undefined\n const diagnostic: Diagnostic = {\n code: Diagnostics.code.refNotFound,\n severity: isExtensionPath(path) ? 'warning' : 'error',\n message: `Could not bundle an external \\`$ref\\`. ${message}.`,\n help: 'Check that the file or URL the `$ref` points at exists and is readable, or fix the `$ref`.',\n ...(pointer && { location: { kind: 'schema', pointer } }),\n }\n if (!Diagnostics.report(diagnostic) && diagnostic.severity === 'error') {\n throw new Diagnostics.Error(diagnostic)\n }\n },\n },\n })) as Document\n}\n\n// Inline input has no file of its own, so its relative `$ref`s resolve from a stand-in name in `root`.\nconst inlineInputName = '<inline input>'\n\n/**\n * Creates a `Document` from an `AdapterSource`.\n *\n * - `{ type: 'path' }` bundles an absolute file path (core resolves `input`) or remote URL via\n * `api-ref-bundler`, hoisting external file schemas into named `components.schemas` entries so\n * generators can emit named types and imports.\n * - `{ type: 'data' }` parses an inline string (YAML/JSON) or raw object, then bundles its\n * external `$ref`s from `root` when it has any. Each file or URL read lands in `sources`.\n *\n * Swagger 2.0 and OpenAPI 3.0 documents are up-converted to OpenAPI 3.1 via `@scalar/openapi-upgrader`.\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, sources: Array<string> = []): Promise<Document> {\n const raw = await (async (): Promise<Document> => {\n // YAML parsing also handles JSON.\n if (source.type === 'data') {\n const data =\n typeof source.data === 'string'\n ? (parseYaml(source.data, {\n origin: 'the inline `input` string',\n help: 'Fix the syntax at the reported line. Kubb reads `input` as an inline spec, not a file path, because it starts with `{`, `[`, `openapi:`, or `swagger:`, or spans several lines.',\n }) as Document)\n : structuredClone(source.data as Document)\n return source.root && hasExternalRef(data) ? bundleDocument(join(source.root, inlineInputName), { document: data, sources }) : data\n }\n await assertInputExists(source.path)\n return bundleDocument(source.path, { sources })\n })()\n\n // Unquoted `swagger: 2.0` parses as the number 2, which `upgrade` does not recognise as a version.\n if (raw && typeof raw === 'object') {\n const document = raw as Record<string, unknown>\n for (const key of ['swagger', 'openapi']) {\n const version = document[key]\n if (typeof version === 'number') {\n document[key] = Number.isInteger(version) ? version.toFixed(1) : String(version)\n }\n }\n }\n\n if (raw && typeof raw === 'object' && 'swagger' in raw) {\n const refs = createRefs(raw)\n inlinePathRefs(raw, (ref) => refs.resolve(ref, { report: false }))\n }\n\n // `upgrade` chains Swagger 2.0 -> 3.0 -> 3.1, leaving documents already on 3.1 untouched.\n try {\n return upgrade(raw, '3.1') as Document\n } catch (error) {\n const declared = raw && typeof raw === 'object' ? ((raw as { openapi?: unknown }).openapi ?? (raw as { swagger?: unknown }).swagger) : undefined\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidDocument,\n severity: 'error',\n message: `Cannot upgrade the document${declared ? ` (version ${String(declared)})` : ''} to OpenAPI 3.1: ${getErrorMessage(error)}`,\n help: 'Kubb reads Swagger 2.0, OpenAPI 3.0, and OpenAPI 3.1. Set `swagger` or `openapi` to one of those versions, and fix the reported problem in the document.',\n location: { kind: 'config' },\n cause: toError(error),\n })\n }\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 // An inline string with no YAML mapping parses to a plain string, which the `in` checks would throw on.\n if (document && typeof document === 'object' && ('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/** Reports a validation problem as a `KUBB_INVALID_SPEC` warning, a no-op outside a build. */\nfunction reportInvalidSpec(message: string): void {\n Diagnostics.report({\n code: Diagnostics.code.invalidSpec,\n severity: 'warning',\n message,\n help: 'Fix the spec, or run `kubb validate` to list every error. Set `validate: false` on the adapter to skip this check.',\n })\n}\n\n/**\n * Validates an OpenAPI document using `@readme/openapi-parser`. Throws with `throwOnError`, otherwise warns.\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 let result: Awaited<ReturnType<typeof validate>>\n try {\n // `validate` dereferences its input in place, so clone to keep the cached document intact.\n result = await validate(structuredClone(document), {\n validate: {\n errors: { colorize: throwOnError },\n },\n })\n } catch (error) {\n if (throwOnError) throw error\n reportInvalidSpec(getErrorMessage(error))\n return\n }\n\n if (result.valid) return\n if (throwOnError)\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidSpec,\n severity: 'error',\n message: compileErrors(result),\n help: 'Fix each problem listed in the spec, then validate again.',\n })\n\n reportValidationErrors(result)\n}\n\nfunction reportValidationErrors({ errors, additionalErrors }: ValidationErrors): void {\n for (const { message } of errors) {\n // The code frame after the first line numbers a JSON copy of the spec, not the user's file.\n reportInvalidSpec(message.replace(/\\n.*/s, ''))\n }\n if (additionalErrors > 0) {\n reportInvalidSpec(`${additionalErrors} more validation errors are not listed.`)\n }\n}\n\n/**\n * Validates like {@link validateDocument} without `throwOnError`, but in a worker thread, so the\n * build keeps generating while `@readme/openapi-parser` dereferences and checks the spec. Await the\n * returned promise inside the build's diagnostics scope to report its warnings there. Falls back to\n * validating in place where worker threads are missing, as in edge runtimes.\n */\nexport async function validateDocumentInWorker(document: Document): Promise<void> {\n let message: WorkerResult\n try {\n const { Worker } = await import('node:worker_threads')\n // Tests run the `.ts` source; the build emits `validateWorker.js` next to the bundle.\n const workerFile = import.meta.url.endsWith('.ts') ? './validateWorker.ts' : './validateWorker.js'\n // `workerData` is a structured clone, so the worker can dereference it without touching the cached document.\n const worker = new Worker(new URL(workerFile, import.meta.url), { workerData: document })\n message = await new Promise<WorkerResult>((resolve, reject) => {\n worker.once('message', resolve)\n worker.once('error', reject)\n worker.once('exit', (code) => reject(new Error(`Validation worker exited with code ${code}`)))\n }).finally(() => worker.terminate())\n } catch {\n return validateDocument(document)\n }\n\n if ('thrown' in message) return reportInvalidSpec(message.thrown)\n if (!message.valid) reportValidationErrors(message)\n}\n","import { escapePointerToken, 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, 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 * The `$ref` target of the entry, which keys `renames`.\n */\n ref: string\n /**\n * Where the schema itself sits, when that differs from `ref`, as for a response's `content` schema.\n */\n pointer?: string\n nested?: boolean\n}\n\ntype GetSchemasResult = {\n schemas: Record<string, SchemaObject>\n /**\n * The JSON pointer each key in `schemas` was read from.\n */\n pointers: Map<string, string>\n /**\n * Maps nested schema pointers and collision-renamed component pointers to the unique\n * names used as keys in `schemas`. Components with their original names and no nested\n * definitions are not recorded.\n */\n renames: Map<string, string>\n}\n\n/**\n * Extracts the inline schema from a media-type `content` map, with the media type it sits under.\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 * // { schema: SchemaObject, contentType: 'application/json' } | null\n * ```\n */\nfunction extractSchemaFromContent(\n content: Record<string, unknown> | undefined,\n preferredContentType?: ContentType,\n): { schema: SchemaObject; contentType: string } | 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 (!schema || isReference(schema)) return null\n return { schema, contentType: targetContentType }\n}\n\n/**\n * Walks a schema tree and collects the names of all `#/components/schemas/<name>` `$ref`s.\n */\nfunction* collectRefs(schema: unknown, renames: Map<string, string>): Generator<string, void, undefined> {\n if (Array.isArray(schema)) {\n for (const item of schema) yield* collectRefs(item, renames)\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, renames)\n continue\n }\n if (value.startsWith(SCHEMA_REF_PREFIX)) {\n const name = renames.get(value) ?? value.slice(SCHEMA_REF_PREFIX.length)\n if (name) yield name\n }\n }\n }\n}\n\nconst schemaChildKeywords = [\n 'additionalProperties',\n 'allOf',\n 'anyOf',\n 'contains',\n 'contentSchema',\n 'else',\n 'if',\n 'items',\n 'not',\n 'oneOf',\n 'patternProperties',\n 'prefixItems',\n 'properties',\n 'propertyNames',\n 'then',\n] as const\n\n/** Collects definitions only from schema locations, never from examples/defaults or arbitrary data. */\nfunction* collectNestedDefinitions(\n schema: unknown,\n pointer: string,\n name: string,\n): Generator<{ schema: SchemaObject; ref: string; originalName: string }, void, undefined> {\n if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return\n const value = schema as Record<string, unknown>\n\n for (const keyword of ['$defs', 'definitions'] as const) {\n const definitions = value[keyword]\n if (!definitions || typeof definitions !== 'object' || Array.isArray(definitions)) continue\n for (const [key, definition] of Object.entries(definitions)) {\n if (!definition || typeof definition !== 'object' || Array.isArray(definition)) continue\n const definitionPointer = `${pointer}/${keyword}/${escapePointerToken(key)}`\n const nestedName = `${name}_${key}`\n yield { schema: definition as SchemaObject, ref: definitionPointer, originalName: nestedName }\n yield* collectNestedDefinitions(definition, definitionPointer, nestedName)\n }\n }\n\n for (const keyword of schemaChildKeywords) {\n const child = value[keyword]\n if (!child || typeof child !== 'object') continue\n if (Array.isArray(child)) {\n for (const [index, item] of child.entries()) yield* collectNestedDefinitions(item, `${pointer}/${keyword}/${index}`, name)\n continue\n }\n if (keyword === 'properties' || keyword === 'patternProperties') {\n for (const [key, item] of Object.entries(child)) yield* collectNestedDefinitions(item, `${pointer}/${keyword}/${escapePointerToken(key)}`, name)\n continue\n }\n yield* collectNestedDefinitions(child, `${pointer}/${keyword}`, name)\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 */\nfunction sortSchemas(schemas: Record<string, SchemaObject>, renames: Map<string, string>): 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, renames))])\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 * 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 }: { contentType?: ContentType }, 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>) ?? {}).flatMap(([name, schema]) => {\n const ref = `#/components/schemas/${escapePointerToken(name)}`\n return [\n { schema: resolveSchemaRef(schema), source: 'schemas' as const, originalName: name, ref },\n ...[...collectNestedDefinitions(schema, ref, name)].map((nested) => ({\n ...nested,\n source: 'schemas' as const,\n nested: true,\n })),\n ]\n }),\n ...(['responses', 'requestBodies'] as const).flatMap((source) =>\n Object.entries(components?.[source] ?? {}).flatMap(([name, item]) => {\n const extracted = extractSchemaFromContent((item as { content?: Record<string, unknown> }).content, contentType)\n if (!extracted) return []\n const ref = `#/components/${source}/${escapePointerToken(name)}`\n return [\n {\n schema: resolveSchemaRef(extracted.schema),\n source,\n originalName: name,\n ref,\n pointer: `${ref}/content/${escapePointerToken(extracted.contentType)}/schema`,\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 const pointers = 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 // Unique names keep theirs. A collision across sources gets a semantic suffix, within one source a numeric one.\n const suffix = isSingle ? '' : hasMultipleSources ? semanticSuffixes[item.source] : index ? String(index + 1) : ''\n const uniqueName = item.originalName + suffix\n schemas[uniqueName] = item.schema\n pointers.set(uniqueName, item.pointer ?? item.ref)\n if (suffix || item.nested) renames.set(item.ref, uniqueName)\n })\n }\n\n return { schemas: sortSchemas(schemas, renames), renames, pointers }\n}\n","import { Diagnostics } from '@kubb/kit'\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 type { ast } from '@kubb/kit'\nimport { formatMap, specialCasedFormats, structuralKeys } from '../constants.ts'\nimport { isReference } from '../oas.ts'\nimport type { SchemaObject } from '../types.ts'\n\n/**\n * Whether `format` maps to a dedicated type; `false` is what `KUBB_UNSUPPORTED_FORMAT` flags.\n */\nexport function isHandledFormat(format: string): boolean {\n return formatMap[format as keyof typeof formatMap] !== undefined || specialCasedFormats.has(format)\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 * 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\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. Returns the\n * 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 * flattenSchema({ allOf: [{ $ref: '#/components/schemas/Pet' }] })\n * // returned unchanged, contains a $ref\n * ```\n */\nexport function flattenSchema(schema: SchemaObject): SchemaObject {\n if (!schema.allOf?.length) return schema\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 { escapePointerToken } from '@internals/utils'\nimport type { ast } from '@kubb/kit'\nimport { Diagnostics } from '@kubb/kit'\nimport { isHandledFormat } from './emit/schemaShape.ts'\n\n/**\n * Links one freshly converted schema and its nested schemas to their RFC 6901 pointers\n * (`#/components/schemas/Pet/properties/owner/properties/name`), and reports the advisory\n * diagnostics (`KUBB_UNSUPPORTED_FORMAT`, `KUBB_DEPRECATED`) against them.\n * Refs are not followed, so the resolved schema is handled 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: ast.SchemaNode, pointer = node.pointer): void {\n if (pointer) visit(node, pointer)\n}\n\nfunction visit(node: ast.SchemaNode, pointer: string): void {\n node.pointer ??= pointer\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)}`)\n }\n if (node.additionalProperties && typeof node.additionalProperties === 'object') {\n visit(node.additionalProperties, `${pointer}/additionalProperties`)\n }\n return\n }\n\n if (node.type === 'array') {\n for (const item of node.items ?? []) {\n visit(item, `${pointer}/items`)\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}`)\n }\n return\n }\n\n if (node.type === 'not') {\n for (const member of node.members ?? []) visit(member, `${pointer}/not`)\n return\n }\n\n // shortcut: a member the parser adds, such as the wrapper around `not` with sibling keys, gets an index past the spec's own entries; set pointers in the converters if editors need those exact.\n if (node.type === 'union' || node.type === 'intersection') {\n const keyword = node.type === 'intersection' ? 'allOf' : node.strategy === 'any' ? 'anyOf' : 'oneOf'\n for (const [index, member] of (node.members ?? []).entries()) {\n visit(member, `${pointer}/${keyword}/${index}`)\n }\n }\n}\n","import { escapePointerToken, pascalCase } from '@internals/utils'\nimport { ast } from '@kubb/kit'\nimport { SUPPORTED_METHODS } from './constants.ts'\nimport type { ParseFn } from './emit/parseSchema.ts'\nimport { getBinaryFallbackSchema, isJsonMimeType, isReference, pickExtensions } from './oas.ts'\nimport { scanSchema } from './schemaDiagnostics.ts'\nimport type { Refs } from './refs.ts'\nimport type {\n ContentType,\n Document,\n MediaTypeObject,\n OperationObject,\n ParameterObject,\n PathItemObject,\n ReferenceObject,\n RequestBodyObject,\n ResponseObject,\n SchemaObject,\n} from './types.ts'\n\n/**\n * A single OpenAPI operation: its path, method, raw operation object and resolved path item.\n */\nexport type Operation = {\n path: string\n method: string\n schema: OperationObject\n pathItem: PathItemObject\n}\n\ntype OperationContext = {\n operation: Operation\n refs: Refs\n}\n\n/** What `parseOperation` needs beyond the operation. */\nexport type OperationParseContext = {\n refs: Refs\n contentType?: ContentType\n options: ast.ParserOptions\n parseSchema: ParseFn\n}\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`. `null` when absent.\n */\nexport function getResponseByStatusCode({ operation, refs, statusCode }: OperationContext & { statusCode: string | number }): ResponseObject | null {\n const responses = operation.schema.responses as Record<string, ResponseObject | ReferenceObject> | undefined\n if (!responses || isReference(responses)) {\n return null\n }\n\n return refs.deref<ResponseObject>(responses[statusCode])\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 * 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 = getRequestBody({ operation, refs })?.content\n const mediaTypes = content ? Object.keys(content) : []\n\n return mediaTypes.findLast(isJsonMimeType) ?? mediaTypes[0] ?? 'application/json'\n}\n\n/** Merges path-level and operation-level parameters; operation-level wins per `in:name`. */\nexport function getParameters({ operation, refs }: OperationContext): Array<{ param: ParameterObject; pointer: string }> {\n // Each parameter keeps the pointer of the entry that declares it, on the path item or the operation.\n const resolveParams = (params: Array<unknown>, pointer: string) =>\n params.flatMap((entry, index) => {\n const param = refs.derefKeepingRef(entry)\n return param && typeof param === 'object' && 'in' in param && 'name' in param\n ? [{ param: param as ParameterObject, pointer: `${pointer}/parameters/${index}` }]\n : []\n })\n\n const pathPointer = `#/paths/${escapePointerToken(operation.path)}`\n const operationParams = resolveParams(operation.schema?.parameters || [], `${pathPointer}/${operation.method.toLowerCase()}`)\n const pathLevelParams = resolveParams((operation.pathItem as { parameters?: Array<unknown> }).parameters ?? [], pathPointer)\n\n const paramMap = new Map<string, { param: ParameterObject; pointer: string }>()\n for (const entry of [...pathLevelParams, ...operationParams]) {\n if (entry.param.name && entry.param.in) {\n paramMap.set(`${entry.param.in}:${entry.param.name}`, entry)\n }\n }\n\n return Array.from(paramMap.values())\n}\n\nconst PARAMETER_STYLES = new Set(['matrix', 'label', 'form', 'simple', 'spaceDelimited', 'pipeDelimited', 'deepObject'])\n\n/** The `encoding` of a media type, reduced to the entries that set a field Kubb carries. A `style` outside the OpenAPI set is dropped. */\nfunction getEncoding(encoding: MediaTypeObject['encoding']): Record<string, ast.EncodingNode> | undefined {\n const entries = Object.entries(encoding ?? {}).flatMap(([property, { contentType, style, explode, allowReserved }]) => {\n const node: ast.EncodingNode = {\n ...(contentType !== undefined ? { contentType } : {}),\n ...(style !== undefined && PARAMETER_STYLES.has(style) ? { style: style as ast.ParameterStyle } : {}),\n ...(explode !== undefined ? { explode } : {}),\n ...(allowReserved !== undefined ? { allowReserved } : {}),\n }\n return Object.keys(node).length ? [[property, node] as const] : []\n })\n\n return entries.length ? Object.fromEntries(entries) : undefined\n}\n\n/** Schema for one media type of a `content` map, with the binary fallback for an emptied non-JSON entry. */\nexport function getBodySchema({\n content,\n contentType,\n refs,\n}: {\n content: Record<string, MediaTypeObject> | undefined\n contentType: string | undefined\n refs: Refs\n}): SchemaObject | null {\n const entry = contentType ? content?.[contentType] : undefined\n if (!entry) return null\n\n const binary = getBinaryFallbackSchema(contentType, entry.schema)\n if (binary) return binary\n\n return entry.schema ? refs.derefKeepingRef(entry.schema as SchemaObject) : null\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 */\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\n/** Property names whose schema has a truthy `readOnly` or `writeOnly` flag; `$ref` entries are skipped. */\nfunction 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\nfunction parseParameter({\n param,\n pointer,\n parentName,\n options,\n parseSchema,\n}: Pick<OperationParseContext, 'options' | 'parseSchema'> & { param: ParameterObject; pointer: string; parentName?: string }): ast.ParameterNode {\n const schemaName = parentName && param.name ? pascalCase(`${parentName} ${param.name}`) : undefined\n // A parameter defines either `schema` or `content`, and `content` holds exactly one media type.\n const contentType = param.schema ? undefined : Object.keys(param.content ?? {})[0]\n const rawSchema = param.schema ?? (contentType ? param.content?.[contentType]?.schema : undefined)\n const schema: ast.SchemaNode = rawSchema\n ? parseSchema({ schema: rawSchema as SchemaObject, name: schemaName })\n : ast.factory.createSchema({ type: options.unknownType })\n if (rawSchema) scanSchema(schema, contentType ? `${pointer}/content/${escapePointerToken(contentType)}/schema` : `${pointer}/schema`)\n const style = param.style !== undefined && PARAMETER_STYLES.has(param.style) ? (param.style as ast.ParameterStyle) : undefined\n const explode = param.explode\n const allowReserved = param.allowReserved\n\n return ast.factory.createParameter({\n pointer,\n name: param.name,\n in: param.in,\n schema: {\n ...schema,\n description: param.description ?? schema.description,\n },\n required: param.required ?? false,\n ...(style !== undefined ? { style } : {}),\n ...(explode !== undefined ? { explode } : {}),\n ...(allowReserved !== undefined ? { allowReserved } : {}),\n ...(contentType !== undefined ? { contentType } : {}),\n })\n}\n\n/**\n * Converts an OAS `Operation` into an `OperationNode`.\n */\nexport function parseOperation({ operation, ...ctx }: OperationParseContext & { operation: Operation }): ast.OperationNode {\n const { refs, contentType, options, parseSchema } = ctx\n const operationId = getOperationId(operation)\n const operationName = operationId ? pascalCase(operationId) : undefined\n const pointer = `#/paths/${escapePointerToken(operation.path)}/${operation.method.toLowerCase()}`\n const parameters = getParameters({ operation, refs }).map((entry) => parseParameter({ options, parseSchema, ...entry, parentName: operationName }))\n\n // A configured contentType restricts the body to that one media type; otherwise every declared one is kept.\n const body = getRequestBody({ operation, refs })\n const bodyRequired = body?.required === true\n const requestBodyName = operationName ? `${operationName}Request` : undefined\n const requestContentTypes = contentType ? [contentType] : Object.keys(body?.content ?? {})\n\n const content = requestContentTypes.flatMap((ct) => {\n const schema = getBodySchema({ content: body?.content, contentType: ct, refs })\n if (!schema) return []\n const node = parseSchema({ schema, name: requestBodyName })\n scanSchema(node, `${pointer}/requestBody/content/${escapePointerToken(ct)}/schema`)\n const encoding = getEncoding(body?.content?.[ct]?.encoding)\n return [\n ast.factory.createContent({\n contentType: ct,\n schema: ast.optionality(node, bodyRequired),\n keysToOmit: collectPropertyKeysByFlag(schema, 'readOnly'),\n ...(encoding && { encoding }),\n }),\n ]\n })\n\n const requestBody =\n content.length > 0 || body?.description\n ? {\n pointer: `${pointer}/requestBody`,\n description: body?.description,\n required: bodyRequired || undefined,\n content: content.length > 0 ? content : undefined,\n }\n : undefined\n\n const responses = getResponseStatusCodes(operation).map((statusCode) => {\n const response = getResponseByStatusCode({ operation, refs, statusCode })\n // `Status<code>` keeps nested enum names clear of a component schema named `<operation><statusCode>`.\n const responseName = operationName ? `${operationName}Status${statusCode}` : undefined\n\n const parseEntrySchema = (ct?: string) => {\n const raw = getBodySchema({ content: response?.content, contentType: ct, refs })\n const node =\n raw && Object.keys(raw).length > 0 ? parseSchema({ schema: raw, name: responseName }) : ast.factory.createSchema({ type: options.emptySchemaType })\n if (raw && ct) scanSchema(node, `${pointer}/responses/${statusCode}/content/${escapePointerToken(ct)}/schema`)\n return { schema: node, keysToOmit: collectPropertyKeysByFlag(raw, 'writeOnly') }\n }\n\n const responseContentTypes = contentType ? [contentType] : Object.keys(response?.content ?? {})\n const responseContent = responseContentTypes.map((ct) => ast.factory.createContent({ contentType: ct, ...parseEntrySchema(ct) }))\n\n // A body-less response keeps one fallback entry so it still resolves to a (void/any) schema.\n if (responseContent.length === 0) {\n responseContent.push(\n ast.factory.createContent({\n contentType: getRequestContentType({ operation, refs }),\n ...parseEntrySchema(contentType),\n }),\n )\n }\n\n return ast.factory.createResponse({\n pointer: `${pointer}/responses/${statusCode}`,\n statusCode: statusCode as ast.StatusCode,\n description: response?.description,\n content: responseContent,\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 pointer,\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 extensions: pickExtensions(operation.schema),\n })\n}\n","import { ast } from '@kubb/kit'\nimport { extractExamples } from './schemaShape.ts'\nimport type { ConvertContext } 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<ConvertContext, '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, enumPrimitive, 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\ntype DiscriminatorValue = string | number | boolean\n\n/**\n * Turns string mapping keys into the discriminator property's type when they parse cleanly.\n */\nexport function typedKeys({ keys, propertyType }: { keys: Array<string>; propertyType: unknown }): Array<DiscriminatorValue> {\n return keys.map((key) => {\n if (propertyType === 'integer' || propertyType === 'number') {\n const value = Number(key)\n return key.trim() !== '' && Number.isFinite(value) ? value : key\n }\n if (propertyType === 'boolean') {\n const lower = key.toLowerCase()\n return lower === 'true' ? true : lower === 'false' ? false : key\n }\n return key\n })\n}\n\n/**\n * Reads the declared `type` of `propertyName` on a schema, following `$ref`s and `allOf` members.\n * A nullable array such as `['integer', 'null']` reads as its one non-null type.\n */\nexport function propertyTypeOf({\n schema,\n propertyName,\n refs,\n seen = new Set<string>(),\n}: {\n schema: SchemaObject | ReferenceObject | undefined\n propertyName: string\n refs: Refs\n seen?: Set<string>\n}): unknown {\n const deref = (value: SchemaObject | ReferenceObject | undefined) =>\n value && isReference(value) ? refs.resolve<SchemaObject>(value.$ref, { report: false }) : value\n\n if (schema && isReference(schema)) {\n if (seen.has(schema.$ref)) return undefined\n seen.add(schema.$ref)\n }\n\n const resolved = deref(schema) as SchemaObject | undefined\n const type =\n (deref(resolved?.properties?.[propertyName] as SchemaObject | ReferenceObject | undefined) as SchemaObject | undefined)?.type ??\n resolved?.allOf?.map((member) => propertyTypeOf({ schema: member as SchemaObject | ReferenceObject, propertyName, refs, seen })).find(Boolean)\n const nonNull = Array.isArray(type) ? type.filter((t) => t !== 'null') : []\n\n return nonNull.length === 1 ? nonNull[0] : type\n}\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<DiscriminatorValue> }): 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: enumPrimitive(values),\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({ mapping: { dog: '#/components/schemas/Dog', hound: '#/components/schemas/Dog' }, ref: '#/components/schemas/Dog' }) // ['dog', 'hound']\n * ```\n */\nexport function findDiscriminators({ mapping, ref }: { 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 * Finds the discriminator a schema declares itself or through an inline `allOf` member.\n */\nfunction getDiscriminator(schema: SchemaObject): DiscriminatorObject | undefined {\n return (isDiscriminator(schema) ? schema : (schema.allOf as Array<SchemaObject> | undefined)?.find(isDiscriminator))?.discriminator\n}\n\n/**\n * Lists the mapping keys of a discriminator plus the keys of the nested discriminators its mapped\n * schemas declare on the same property, so a root `$type` accepts values from every level.\n */\nexport function getMappingKeys({\n discriminator: { propertyName, mapping },\n refs,\n seen = new Set<string>(),\n}: {\n discriminator: DiscriminatorObject\n refs: Refs\n seen?: Set<string>\n}): Array<string> {\n return Object.entries(mapping ?? {}).flatMap(([key, target]) => {\n if (seen.has(target)) return [key]\n seen.add(target)\n\n const resolved = refs.resolve<SchemaObject>(target, { report: false })\n const nested = resolved && getDiscriminator(resolved)\n\n return nested?.propertyName === propertyName ? [key, ...getMappingKeys({ discriminator: nested, refs, seen })] : [key]\n })\n}\n\n/**\n * Drops the discriminator from an inline `allOf` member when a `$ref` sibling already declares one on\n * the same property. That mapping names the schema's own children, and keeping it pins the property\n * to those keys next to the parent's, which leaves `never`.\n */\nexport function removeInheritedDiscriminator({\n members,\n refs,\n}: {\n members: Array<SchemaObject | ReferenceObject>\n refs: Refs\n}): Array<SchemaObject | ReferenceObject> {\n const inherited = new Set(\n members.flatMap((member) => {\n const parent = isReference(member) ? refs.resolve<SchemaObject>(member.$ref, { report: false }) : null\n return (parent && getDiscriminator(parent)?.propertyName) || []\n }),\n )\n\n return members.map((member) => {\n if (isReference(member) || !isDiscriminator(member) || member.oneOf || member.anyOf) return member\n if (!inherited.has(member.discriminator.propertyName)) return member\n const { discriminator: _discriminator, ...rest } = member\n\n return rest\n })\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 parentType,\n parse,\n name,\n refs,\n}: {\n unionMembers: Array<unknown>\n discriminator: DiscriminatorObject | undefined\n sharedPropertiesNode: ast.SchemaNode | undefined\n parentType?: unknown\n parse: ParseFn\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({ mapping: discriminator?.mapping, ref })\n const implicitValue = mappedValues.length ? null : implicitDiscriminantValue(s)\n const propertyType = propertyTypeOf({ schema: s as SchemaObject, propertyName: discriminator?.propertyName ?? '', refs }) ?? parentType\n const discriminatorValues = typedKeys({ keys: mappedValues.length ? mappedValues : implicitValue ? [implicitValue] : [], propertyType })\n const memberNode = parse({ schema: s as SchemaObject, name })\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<DiscriminatorValue> }>\n} {\n const discriminantValues: Array<{ propertyName: string; values: Array<DiscriminatorValue> }> = []\n\n const members = allOfMembers.filter((item) => {\n if (!isReference(item) || !name) return true\n const deref = refs.resolve<SchemaObject>(item.$ref)\n const discriminator = deref && getDiscriminator(deref)\n const parentUnion = deref?.oneOf ?? deref?.anyOf\n if (!deref || !discriminator || (isDiscriminator(deref) && !parentUnion)) return true\n\n const childRef = `${SCHEMA_REF_PREFIX}${name}`\n const values = findDiscriminators({ mapping: discriminator.mapping, ref: childRef })\n if (values.length) {\n const { propertyName } = discriminator\n const propertyType = propertyTypeOf({ schema: deref, propertyName, refs }) ?? propertyTypeOf({ schema: { $ref: childRef }, propertyName, refs })\n discriminantValues.push({ propertyName, values: typedKeys({ keys: values, propertyType }) })\n }\n\n // Only a `oneOf`/`anyOf` parent is replaced by its discriminant; any other parent stays in the intersection.\n const replaced = parentUnion && (values.length > 0 || parentUnion.some((member) => isReference(member) && member.$ref === childRef))\n\n return !replaced\n })\n\n return { members, discriminantValues }\n}\n","import type { ast } from '@kubb/kit'\nimport type { SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\n\nconst ANNOTATIONS = new Set(['title', 'description', 'default', 'deprecated', 'readOnly', 'writeOnly', 'example', 'examples', 'xml', 'externalDocs'])\nconst UNION_KEYS = new Set([...ANNOTATIONS, 'type', 'nullable', 'oneOf', 'anyOf'])\nconst MEMBER_KEYS = new Set([...ANNOTATIONS, 'type', 'const'])\n\nfunction hasOnlyKeys(schema: unknown, keys: ReadonlySet<string>): schema is SchemaObject {\n return typeof schema === 'object' && schema !== null && !Array.isArray(schema) && Object.keys(schema).every((key) => keys.has(key) || key.startsWith('x-'))\n}\n\nfunction matchesType(type: SchemaObject['type'], value: string | number): boolean {\n return type === undefined || type === typeof value || (type === 'integer' && typeof value === 'number' && Number.isInteger(value))\n}\n\n/** Recognizes annotated const unions only when replacing them cannot discard validation constraints. */\nexport function convertAnnotatedEnum(context: ConvertContext): ast.SchemaNode | undefined {\n const { schema, document } = context\n if (!document.openapi?.startsWith('3.1.')) return undefined\n if (!hasOnlyKeys(schema, UNION_KEYS) || (schema.oneOf !== undefined && schema.anyOf !== undefined)) return undefined\n const members = schema.oneOf ?? schema.anyOf\n if (!members?.length) return undefined\n\n const names = new Set<string>()\n const values = new Set<string | number>()\n const namedEnumValues: NonNullable<ast.EnumSchemaNode['namedEnumValues']> = []\n let primitive: 'string' | 'number' | undefined\n for (const member of members) {\n if (!hasOnlyKeys(member, MEMBER_KEYS)) return undefined\n const value = member.const\n if (typeof value !== 'string' && (typeof value !== 'number' || !Number.isFinite(value))) return undefined\n if (typeof member.title !== 'string' || !member.title.trim() || names.has(member.title) || values.has(value)) return undefined\n if (!matchesType(schema.type, value) || !matchesType(member.type, value)) return undefined\n const valueType = typeof value === 'number' ? 'number' : 'string'\n if (primitive !== undefined && primitive !== valueType) return undefined\n primitive = valueType\n names.add(member.title)\n values.add(value)\n namedEnumValues.push({ name: member.title, value, primitive: valueType, description: member.description })\n }\n\n return createNode(context, { type: 'enum', primitive, namedEnumValues })\n}\n","import { ast, extractRefName, macroSimplifyUnion, mergeAdjacentObjectsLazy } from '@kubb/kit'\nimport { SCHEMA_REF_PREFIX } from '../../constants.ts'\nimport { isDiscriminator, isReference } from '../../oas.ts'\nimport type { Refs } from '../../refs.ts'\nimport type { ReferenceObject, SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport {\n createDiscriminantNode,\n removeInheritedDiscriminator,\n extractDiscriminatedAllOfMembers,\n narrowUnionMembers,\n propertyTypeOf,\n} from '../discriminator/preserve.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\nimport { extractExamples } from '../schemaShape.ts'\nimport { convertAnnotatedEnum } from './annotatedEnum.ts'\n\n/**\n * Collects property schemas from all `allOf` members and outer schema properties,\n * recursively resolving `$ref` pointers.\n */\nfunction collectSiblingProperties(\n allOfMembers: Array<SchemaObject | ReferenceObject>,\n refs: Refs,\n outerProperties?: Record<string, unknown>,\n): Record<string, unknown> {\n const properties: Record<string, unknown> = { ...outerProperties }\n const visited = new Set<string>()\n\n function collectFrom(item: SchemaObject | ReferenceObject | undefined): void {\n if (!item) return\n\n if (isReference(item)) {\n if (visited.has(item.$ref)) return\n visited.add(item.$ref)\n const resolved = refs.resolve<SchemaObject>(item.$ref, { report: false })\n if (resolved && !isReference(resolved)) {\n collectFrom(resolved)\n }\n return\n }\n\n if (item.properties) {\n Object.assign(properties, item.properties)\n }\n\n if (Array.isArray(item.allOf)) {\n for (const member of item.allOf) {\n collectFrom(member as SchemaObject | ReferenceObject)\n }\n }\n }\n\n for (const item of allOfMembers) {\n collectFrom(item)\n }\n\n return properties\n}\n\n/**\n * Enriches union members that declare `required` properties without declaring corresponding\n * property schemas, populating the missing property definitions from available sibling schemas\n * (or an empty schema falling back to the configured emptySchemaType).\n */\nfunction resolveUnionMembers(members: Array<unknown>, siblingProperties: Record<string, unknown>): Array<unknown> {\n return members.map((member) => {\n if (!member || typeof member !== 'object' || isReference(member)) {\n return member\n }\n\n const obj = member as SchemaObject\n if (!Array.isArray(obj.required) || obj.required.length === 0) {\n return member\n }\n\n const existingProps = (obj.properties ?? {}) as Record<string, unknown>\n const missingKeys = obj.required.filter((key) => !Object.hasOwn(existingProps, key))\n\n if (missingKeys.length === 0) {\n return member\n }\n\n const newProperties: Record<string, unknown> = { ...existingProps }\n for (const key of missingKeys) {\n const value = Object.hasOwn(siblingProperties, key) ? siblingProperties[key] : {}\n // defineProperty: a plain assignment of a `__proto__` key would hit the prototype setter.\n Object.defineProperty(newProperties, key, { value, enumerable: true, writable: true, configurable: true })\n }\n\n return {\n type: obj.type ?? 'object',\n ...obj,\n properties: newProperties,\n }\n })\n}\n\n/**\n * Enriches a schema object, and any `oneOf` or `anyOf` branches on it, with properties from sibling schemas.\n */\nfunction resolveUnionSchema(schema: SchemaObject, siblingProperties: Record<string, unknown>): SchemaObject {\n const resolvedSchema = (resolveUnionMembers([schema], siblingProperties)[0] as SchemaObject) ?? schema\n const next: SchemaObject = { ...resolvedSchema }\n if (schema.oneOf) {\n next.oneOf = resolveUnionMembers(schema.oneOf, siblingProperties) as typeof schema.oneOf\n }\n if (schema.anyOf) {\n next.anyOf = resolveUnionMembers(schema.anyOf, siblingProperties) as typeof schema.anyOf\n }\n return next\n}\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, document, parse, refs, renames }: ConvertContext): ast.SchemaNode {\n const refPath = schema.$ref\n const resolvedSchema = refPath ? refs.resolveNode(refPath, parse) : 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 // A circular ref still resolves, so only a `$ref` to a component the spec never declares is missing.\n if (refPath && document.components && !refs.resolve(refPath, { report: false })) {\n return createNode(ctx, { type: ast.schemaTypes.unknown })\n }\n\n // A target outside `components.schemas` is never emitted as its own file, so inline it. A circular\n // ref leaves `resolvedSchema` null and still becomes a ref node.\n if (refPath && !refPath.startsWith(SCHEMA_REF_PREFIX) && resolvedSchema) {\n return ast.factory.createSchema({\n ...resolvedSchema,\n title: schema.title ?? resolvedSchema.title,\n description: schema.description ?? resolvedSchema.description,\n deprecated: schema.deprecated ?? resolvedSchema.deprecated,\n readOnly: schema.readOnly ?? resolvedSchema.readOnly,\n writeOnly: schema.writeOnly ?? resolvedSchema.writeOnly,\n default: defaultValue ?? resolvedSchema.default,\n name: name ?? resolvedSchema.name,\n nullable: nullable ?? resolvedSchema.nullable,\n })\n }\n\n const targetName = renames?.get(schema.$ref!)\n\n return createNode(ctx, {\n type: ast.schemaTypes.ref,\n name: extractRefName(schema.$ref!),\n ref: schema.$ref,\n ...(targetName ? { targetName } : {}),\n schema: resolvedSchema,\n })\n}\n\n/** Converts `{ ...rest, not: X }` into `intersection[rest, not[X]]`; a bare `required` inside `not` borrows the outer `properties`. */\nexport function convertNot({ schema, name, nullable, defaultValue, parse }: ConvertContext): ast.SchemaNode {\n const { not, ...rest } = schema as SchemaObject & { not: SchemaObject }\n const [subschema] = resolveUnionMembers([not], (rest.properties ?? {}) as Record<string, unknown>) as [SchemaObject]\n const notNode = ast.factory.createSchema({ type: ast.schemaTypes.not, members: [parse({ schema: subschema })] })\n\n return createNode({ schema, name, nullable, defaultValue }, { type: ast.schemaTypes.intersection, members: [parse({ schema: rest, name }), notNode] })\n}\n\n/**\n * Keywords that describe a schema or conditionally constrain it, but add no structure.\n */\nconst annotationKeys = new Set(['description', 'title', 'example', 'examples', 'default', 'deprecated', 'readOnly', 'writeOnly', 'if', 'then', 'else'])\n\n/**\n * Moves `allOf` members that hold only annotations or `if`/`then`/`else` onto the parent, so they do\n * not become `unknown`. The parent's own values win, and the conditional keywords are not enforced.\n */\nfunction mergeAnnotations(schema: SchemaObject): SchemaObject {\n const members = schema.allOf as Array<SchemaObject | ReferenceObject>\n const isAnnotation = (member: SchemaObject | ReferenceObject) => !isReference(member) && Object.keys(member).every((key) => annotationKeys.has(key))\n const annotations = members.filter(isAnnotation)\n const rest = members.filter((member) => !isAnnotation(member))\n\n return annotations.length && rest.length ? { ...Object.assign({}, ...annotations), ...schema, allOf: rest } : schema\n}\n\n/**\n * Converts an `allOf` schema into a flattened node or an `IntersectionSchemaNode`.\n */\nexport function convertAllOf({ schema: original, name, nullable, defaultValue, parse, refs }: ConvertContext): ast.SchemaNode {\n const schema = mergeAnnotations(original)\n\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 })\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: removeInheritedDiscriminator({ members: schema.allOf as Array<SchemaObject | ReferenceObject>, refs }),\n name,\n refs,\n })\n const siblingProperties = collectSiblingProperties(schema.allOf as Array<SchemaObject | ReferenceObject>, refs, schema.properties)\n const resolvedAllOf = discriminatedAllOf.map((s) => (isReference(s) ? s : resolveUnionSchema(s as SchemaObject, siblingProperties)))\n const allOfMembers: Array<ast.SchemaNode> = resolvedAllOf.map((s) => parse({ schema: s as SchemaObject, name }))\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 }))\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 }))\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: ast.schemaTypes.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(context: ConvertContext): ast.SchemaNode {\n const annotatedEnum = convertAnnotatedEnum(context)\n if (annotatedEnum) return annotatedEnum\n const { schema, name, nullable, defaultValue, parse, refs } = context\n const ctx = { schema, name, nullable, defaultValue }\n const unionMembers = resolveUnionMembers([...(schema.oneOf ?? []), ...(schema.anyOf ?? [])], schema.properties ?? {})\n const strategy: 'one' | 'any' = schema.oneOf ? 'one' : 'any'\n const explicitDiscriminatorPropertyName = isDiscriminator(schema) ? schema.discriminator.propertyName : undefined\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 }) : undefined\n const missingRequired = (Array.isArray(schema.required) ? schema.required : []).filter((key) => !Object.hasOwn(schema.properties ?? {}, key))\n\n if (sharedPropertiesNode || discriminator || missingRequired.length) {\n const members = narrowUnionMembers({\n unionMembers,\n discriminator,\n sharedPropertiesNode,\n parentType: discriminator && propertyTypeOf({ schema, propertyName: discriminator.propertyName, refs }),\n parse,\n name,\n refs,\n })\n const unionNode = createNode(ctx, {\n type: ast.schemaTypes.union,\n strategy,\n members,\n discriminatorPropertyName: explicitDiscriminatorPropertyName ?? ast.inferDiscriminatorPropertyName(members),\n })\n\n const requiredProperties = missingRequired.map((name) =>\n ast.factory.createProperty({ name, required: true, schema: ast.factory.createSchema({ type: ast.schemaTypes.unknown }) }),\n )\n const siblings = sharedPropertiesNode ? [sharedPropertiesNode] : []\n if (requiredProperties.length) {\n siblings.push(ast.factory.createSchema({ type: ast.schemaTypes.object, properties: requiredProperties }))\n }\n\n if (!siblings.length) {\n return unionNode\n }\n\n return createNode(ctx, { type: ast.schemaTypes.intersection, members: [unionNode, ...siblings] })\n }\n\n const members = unionMembers.map((s) => parse({ schema: s as SchemaObject, name }))\n const unionNode = createNode(ctx, {\n type: ast.schemaTypes.union,\n strategy,\n members,\n discriminatorPropertyName: explicitDiscriminatorPropertyName ?? ast.inferDiscriminatorPropertyName(members),\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, 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: ast.schemaTypes.union,\n members: nonNullTypes.map((t) => {\n const raw = { ...schema, type: t }\n const memberSchema = raw as SchemaObject\n return parse({ schema: memberSchema, name })\n }),\n },\n )\n}\n","import { ast } from '@kubb/kit'\nimport { enumDescriptionKeys, enumExtensionKeys, formatMap, numericFormats } from '../../constants.ts'\nimport type { SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\nimport { resolveDateTypeValue } 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\nfunction 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/** Shared by number, integer and bigint nodes; the exclusive bounds keep only the OAS 3.1 numeric form. */\nfunction getNumericConstraints(schema: SchemaObject): Pick<ast.NumberSchemaNode, 'min' | 'max' | 'exclusiveMinimum' | 'exclusiveMaximum' | 'multipleOf'> {\n return {\n min: schema.minimum,\n max: schema.maximum,\n exclusiveMinimum: typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined,\n exclusiveMaximum: typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : undefined,\n multipleOf: schema.multipleOf,\n }\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(context: ConvertContext): ast.SchemaNode {\n const { schema, name } = context\n const constValue = schema.const\n\n if (constValue === null) {\n return createNullNode(schema, name)\n }\n\n return createNode(context, {\n type: 'enum',\n primitive: getPrimitiveType(typeof constValue),\n enumValues: [constValue as string | number | boolean],\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, options, type } = context\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(context, {\n type: options.integerType === 'bigint' ? 'bigint' : 'integer',\n primitive: 'integer',\n ...getNumericConstraints(schema),\n })\n }\n\n if (schema.format === 'date-time' || schema.format === 'date' || schema.format === 'time') {\n const value = resolveDateTypeValue(options.dateType, schema.format)\n\n if (schema.format === 'date-time' && value !== 'date') {\n return createNode(context, { primitive: 'string', type: 'datetime', offset: value === 'stringOffset', local: value === 'stringLocal' })\n }\n return createNode(context, {\n primitive: 'string',\n type: schema.format === 'date-time' ? 'date' : schema.format,\n representation: value === 'date' ? 'date' : 'string',\n })\n }\n\n const specialType = formatMap[schema.format as keyof typeof formatMap]\n if (specialType === 'string') {\n // A numeric schema keeps its type, such as `type: integer, format: duration` in seconds.\n if (type === 'integer' || type === 'number') return convertNumeric(context, type)\n // Keeps `format` on the node, plus `minLength`, `maxLength` and `pattern`.\n return convertString(context)\n }\n\n const isNumeric = specialType === 'number' || specialType === 'integer'\n const specialPrimitive: ast.PrimitiveSchemaType = isNumeric ? specialType : 'string'\n const hasLength = specialType === 'url' || specialType === 'uuid' || specialType === 'email'\n\n return createNode(context, {\n primitive: specialPrimitive,\n type: specialType as ast.ScalarSchemaType,\n ...(hasLength ? { min: schema.minLength, max: schema.maxLength } : {}),\n ...(isNumeric ? getNumericConstraints(schema) : {}),\n })\n}\n\n/**\n * Converts an `enum` schema into an `EnumSchemaNode`.\n */\nexport function convertEnum({ schema, name, nullable, type, parse }: ConvertContext): ast.SchemaNode {\n if (type === 'array') {\n return parse({ schema: normalizeArrayEnum(schema), name })\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 primitive: 'number' | 'boolean' | 'string' = type === 'boolean' ? 'boolean' : type === 'number' || type === 'integer' ? 'number' : 'string'\n const uniqueValues = [...new Set(filteredValues)]\n\n const ctx = { schema, name, nullable: enumNullable as true | undefined, defaultValue: enumDefault }\n\n const extensionKey = enumExtensionKeys.find((key) => key in schema)\n const descriptionKey = enumDescriptionKeys.find((key) => key in schema)\n if (!extensionKey && !descriptionKey && primitive === 'string') {\n return createNode(ctx, { type: 'enum', primitive, enumValues: uniqueValues })\n }\n\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 seenNames = new Set<string>()\n\n return createNode(ctx, {\n type: 'enum',\n primitive,\n namedEnumValues: uniqueValues\n .map((value, index) => ({\n name: String(rawEnumNames?.[index] ?? value),\n value,\n primitive,\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/**\n * Converts a `type: 'string'` schema into a `StringSchemaNode`.\n */\nexport function convertString(context: ConvertContext): ast.SchemaNode {\n const { schema } = context\n\n return createNode(context, {\n type: 'string',\n primitive: 'string',\n min: schema.minLength,\n max: schema.maxLength,\n pattern: schema.pattern,\n })\n}\n\n/**\n * Converts a `type: 'number'` or `type: 'integer'` schema.\n */\nexport function convertNumeric(context: ConvertContext, type: 'number' | 'integer'): ast.SchemaNode {\n return createNode(context, {\n type,\n primitive: type,\n ...getNumericConstraints(context.schema),\n })\n}\n","import { ast, childName, enumPropName, macroDiscriminatorEnum, macroEnumName } from '@kubb/kit'\nimport { isDiscriminator, isNullable } from '../../oas.ts'\nimport { getMappingKeys, propertyTypeOf, typedKeys } from '../discriminator/preserve.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(mapSchema: unknown, { options, parse }: Pick<ConvertContext, 'options' | 'parse'>): ast.SchemaNode {\n if (mapSchema === false) return ast.factory.createSchema({ type: 'never' })\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 })\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, options, parse, refs }: 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 })\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 || schemaNode.nullable || undefined,\n },\n required,\n })\n })\n : []\n\n const additionalProperties = schema.additionalProperties\n const additionalPropertiesNode = (() => {\n if (additionalProperties === true) return true\n if (additionalProperties) return resolveMapSchema(additionalProperties, { options, parse })\n return additionalProperties\n })()\n\n const rawPatternProperties = 'patternProperties' in schema ? schema.patternProperties : undefined\n\n const patternProperties = rawPatternProperties\n ? Object.fromEntries(Object.entries(rawPatternProperties).map(([pattern, patternSchema]) => [pattern, resolveMapSchema(patternSchema, { options, parse })]))\n : undefined\n const propertyNames = 'propertyNames' in schema && schema.propertyNames !== undefined ? resolveMapSchema(schema.propertyNames, { options, parse }) : 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 propertyNames,\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 = typedKeys({\n keys: getMappingKeys({ discriminator: schema.discriminator, refs }),\n propertyType: propertyTypeOf({ schema, propertyName: discPropName, refs }),\n })\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, options, parse }: ConvertContext): ast.SchemaNode {\n const tupleItems = (schema.prefixItems ?? []).map((item) => parse({ schema: item as SchemaObject }))\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 })\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, 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 })] : []\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/kit'\nimport { isBinary, isReference } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport type { Document, SchemaObject } from '../types.ts'\nimport { convertAllOf, convertMultiType, convertNot, convertRef, convertUnion } from './converters/composition.ts'\nimport { convertConst, convertEnum, convertFormat, convertNumeric, convertString, createNullNode } from './converters/scalar.ts'\nimport { convertArray, convertObject, convertTuple } from './converters/structural.ts'\nimport { createNode } from './createNode.ts'\nimport { isHandledFormat, resolveDateTypeValue } from './schemaShape.ts'\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 }) => ast.SchemaNode\n\n/**\n * Everything a converter receives: the per-schema derivations plus the parser instance's\n * recursion seam, document, `$ref` service and collision renames.\n */\nexport type ConvertContext = {\n schema: SchemaObject\n name: string | null | undefined\n nullable: true | undefined\n defaultValue: unknown\n /** First non-`null` entry of an OAS 3.1 multi-type array, or the plain `type`. */\n type: string | undefined\n options: ast.ParserOptions\n parse: ParseFn\n document: Document\n refs: Refs\n renames?: ReadonlyMap<string, string>\n}\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 */\ntype 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 (`not`, `$ref`, `allOf`,\n * `oneOf`/`anyOf`) take precedence over `const` (except a `$ref` with a sibling `const`, where the\n * `const` wins), which takes precedence over a genuine OAS 3.1 multi-type array (more than one\n * 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 }) => typeof schema.not === 'object' && schema.not !== null, convert: convertNot },\n { match: ({ schema }) => isReference(schema) && !('const' in schema && schema.const !== undefined), 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: (ctx) => createNode(ctx, { type: 'blob', primitive: 'string' }) },\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 }) =>\n type === 'object' || !!schema.properties || !!schema.additionalProperties || 'patternProperties' in schema || 'propertyNames' 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: (ctx) => createNode(ctx, { type: 'boolean', primitive: 'boolean' }) },\n { match: ({ type }) => type === 'null', convert: ({ schema, name, nullable }) => createNullNode(schema, name, nullable) },\n]\n","import type { ast } from '@kubb/kit'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { createNode } from './emit/createNode.ts'\nimport { type ConvertContext, schemaRules } from './emit/parseSchema.ts'\nimport { flattenSchema } from './emit/schemaShape.ts'\nimport { isNullable } from './oas.ts'\nimport type { Refs } from './refs.ts'\nimport type { Document, SchemaObject } from './types.ts'\n\n/**\n * Parser context holding the raw OpenAPI document and its `$ref` service.\n */\nexport type OasParserContext = {\n document: Document\n refs: Refs\n /**\n * Renames from `getSchemas`, keyed by the collision-renamed component or nested `$defs` pointer.\n * `convertRef` stamps `targetName` from it at ref creation, so refs to renamed schemas resolve\n * to the emitted name without a post-parse pass.\n */\n renames?: ReadonlyMap<string, string>\n options?: Partial<ast.ParserOptions>\n}\n\n/**\n * Creates the schema converter bound to one OpenAPI document: `parseSchema` dispatches each\n * schema through the ordered `schemaRules` table, with the parser options merged once.\n *\n * @internal\n */\nexport function createSchemaParser(ctx: OasParserContext) {\n const { document, refs, renames } = ctx\n const options: ast.ParserOptions = { ...DEFAULT_PARSER_OPTIONS, ...ctx.options }\n\n function parseSchema({ schema, name }: { schema: SchemaObject; name?: string | null }): ast.SchemaNode {\n const flattenedSchema = flattenSchema(schema)\n if (flattenedSchema !== schema) {\n return parseSchema({ schema: flattenedSchema, name })\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 options,\n parse: parseSchema,\n document,\n refs,\n renames,\n }\n\n for (const rule of schemaRules) {\n if (rule.match(context)) return rule.convert(context)\n }\n\n return createNode(context, { type: options.emptySchemaType as ast.ScalarSchemaType })\n }\n\n return parseSchema\n}\n","import { ast } from '@kubb/kit'\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 === ast.nodeKinds.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 { escapePointerToken } from '@internals/utils'\nimport type { Adapter } from '@kubb/core'\nimport * as yaml from 'yaml'\n\ntype Range = ReturnType<NonNullable<Adapter['locate']>>\n\n// Diagnostics of one run share a source, so its parsed document, or its JSON index, is kept for the next call.\nlet cached: { source: string; document: yaml.Document } | { source: string; json: ReturnType<typeof indexJson> } | undefined\n\nconst toRange = ([start, end]: yaml.Range): Range => ({ start, end })\n\nconst unescapeToken = (token: string) => token.replaceAll('~1', '/').replaceAll('~0', '~')\n\n/** Walks a JSON pointer through maps and sequences; the range is the last key or item it reached. */\nfunction findPointer(document: yaml.Document, pointer: string): Range {\n const tokens = pointer.replace(/^#/, '').split('/').slice(1).map(unescapeToken)\n return tokens.reduce<{ node: unknown; range: Range } | undefined>(\n (at, token) => {\n if (yaml.isMap(at?.node)) {\n const pair = at.node.items.find((item) => yaml.isScalar(item.key) && String(item.key.value) === token)\n return pair && yaml.isScalar(pair.key) && pair.key.range ? { node: pair.value, range: toRange(pair.key.range) } : undefined\n }\n if (yaml.isSeq(at?.node)) {\n const item = at.node.items[Number(token)]\n return yaml.isNode(item) && item.range ? { node: item, range: toRange(item.range) } : undefined\n }\n return undefined\n },\n { node: document.contents, range: undefined },\n )?.range\n}\n\n/** The first `$ref` whose value is `ref`. */\nfunction findRefUsage(document: yaml.Document, ref: string): Range {\n const found: Array<Range> = []\n yaml.visit(document, {\n Pair(_, { key, value }) {\n if (!yaml.isScalar(key) || key.value !== '$ref' || !yaml.isScalar(value) || value.value !== ref || !value.range) return\n found.push(toRange(value.range))\n return yaml.visit.BREAK\n },\n })\n return found[0]\n}\n\n/**\n * One pass over JSON text, so a located diagnostic in a large JSON spec skips `yaml.parseDocument`.\n * Holds the range of every key and array item by pointer, and the first usage of every `$ref`, as\n * `findPointer` and `findRefUsage` return them. Throws where the text breaks JSON syntax, such as a\n * comment, an unquoted key, or an unquoted `$ref` value. Other bare values, such as `object`, pass.\n */\nfunction indexJson(source: string) {\n const pointers = new Map<string, NonNullable<Range>>()\n const refs = new Map<string, NonNullable<Range>>()\n let at = source.indexOf('{')\n\n const fail = (): never => {\n throw new SyntaxError(`Unexpected character at ${at}`)\n }\n const skipSpace = () => {\n for (let code = source.charCodeAt(at); code === 32 || code === 9 || code === 10 || code === 13; code = source.charCodeAt(++at));\n }\n const readString = () => {\n if (source[at] !== '\"') fail()\n const start = at\n for (at++; source.charCodeAt(at) !== 34; at++) {\n if (at >= source.length) fail()\n if (source.charCodeAt(at) === 92) at++\n }\n const raw = source.slice(start + 1, at++)\n return { text: raw.includes('\\\\') ? (JSON.parse(source.slice(start, at)) as string) : raw, start, end: at }\n }\n const expect = (char: string) => {\n skipSpace()\n if (source[at++] !== char) fail()\n skipSpace()\n }\n // Walks the value at `at`; `pointer` is where it sits.\n const walk = (pointer: string): void => {\n const open = source[at]\n if (open === '\"') {\n readString()\n return\n }\n if (open !== '{' && open !== '[') {\n const start = at\n while (at < source.length && !/[\\s,\\]}]/.test(source[at]!)) at++\n if (at === start) fail()\n return\n }\n const close = open === '{' ? '}' : ']'\n at++\n for (let index = 0; ; index++) {\n skipSpace()\n if (source[at] === close) break\n if (index > 0) expect(',')\n if (open === '[') {\n const start = at\n const next = `${pointer}/${index}`\n walk(next)\n if (!pointers.has(next)) pointers.set(next, { start, end: at })\n continue\n }\n const key = readString()\n const next = `${pointer}/${escapePointerToken(key.text)}`\n // A duplicate key keeps its first range, like `findPointer`.\n if (!pointers.has(next)) pointers.set(next, { start: key.start, end: key.end })\n expect(':')\n if (key.text !== '$ref' || source[at] === '{' || source[at] === '[') {\n walk(next)\n continue\n }\n // YAML reads an unquoted `$ref` value as a string, so only the YAML parser finds that usage.\n const value = readString()\n if (!refs.has(value.text)) refs.set(value.text, { start: value.start, end: value.end })\n }\n at++\n }\n walk('#')\n return { pointers, refs }\n}\n\n/** Indexes plain JSON text; anything else goes to the YAML parser. */\nfunction parse(source: string): NonNullable<typeof cached> {\n if (/^[ \\t\\n\\r]*\\{/.test(source)) {\n try {\n return { source, json: indexJson(source) }\n } catch {\n // Not plain JSON, such as YAML flow style with comments.\n }\n }\n return { source, document: yaml.parseDocument(source) }\n}\n\n/**\n * Maps OpenAPI JSON pointers and unresolved references to ranges in YAML or JSON source.\n */\nexport const locate: NonNullable<Adapter['locate']> = (source, location) => {\n if (!('pointer' in location)) return undefined\n // An equal but distinct string costs a full comparison on every check. Keeping the caller's\n // string turns the next checks into identity hits.\n cached = cached?.source === source ? { ...cached, source } : parse(source)\n const ref = 'ref' in location ? location.ref : undefined\n if ('json' in cached) {\n const { pointers, refs } = cached.json\n return pointers.get(location.pointer) ?? (ref ? refs.get(ref) : undefined)\n }\n const { document } = cached\n return findPointer(document, location.pointer) ?? (ref ? findRefUsage(document, ref) : undefined)\n}\n","import { defineExtension } from '@kubb/core'\nimport { ast, Diagnostics } from '@kubb/kit'\nimport type { AdapterSource } from '@kubb/kit'\nimport { compatibility } from '../kubb-extension.json'\nimport { version } from '../package.json'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { buildDiscriminatorChildMap, patchDiscriminatorNode } from './emit/discriminator/propagate.ts'\nimport type { DiscriminatorTarget } from './emit/discriminator/propagate.ts'\nimport { assertDocument, parseFromConfig, validateDocument, validateDocumentInWorker } from './load/normalize.ts'\nimport { getSchemas } from './model/components.ts'\nimport { resolveBaseUrl, resolveServerUrl } from './model/server.ts'\nimport { pickExtensions } from './oas.ts'\nimport { getOperations, parseOperation } 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 { locate } from './sourceLocator.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 = defineExtension<AdapterOas>({\n kind: 'adapter',\n meta: { name: adapterOasName, version, compatibility, issues: 'https://github.com/kubb-labs/kubb/issues' },\n setup: ({\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 }) => ({ validate, contentType, server, discriminator, enums, dateType, integerType, unknownType, emptySchemaType, enumSuffix }),\n build({ validate, contentType, server, discriminator, enums, ...parserOptions }) {\n let parsedDocument: Document | null = null\n let sources: Array<string> = []\n const pendingValidations: Array<Promise<void>> = []\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: Promise<ast.InputNode>; sources: Array<string> }>()\n\n /**\n * Parses every schema and operation once, resolving ref aliases and discriminator children from that same pass.\n */\n function parseInput({\n document,\n refs,\n schemas,\n pointers,\n parseSchema,\n }: {\n document: Document\n refs: ReturnType<typeof createRefs>\n schemas: Record<string, SchemaObject>\n pointers: Map<string, string>\n parseSchema: ReturnType<typeof createSchemaParser>\n }): ast.InputNode {\n const parsedByName = new Map<string, ast.SchemaNode>()\n const refAliasMap = new Map<string, ast.RefSchemaNode>()\n const enumNames: Array<string> = []\n const discriminatorParentNodes: Array<ast.SchemaNode> = []\n\n for (const [name, schema] of Object.entries(schemas)) {\n const node = { ...parseSchema({ schema, name }), pointer: pointers.get(name) }\n parsedByName.set(name, node)\n scanSchema(node)\n if (node.type === 'ref' && node.name) {\n refAliasMap.set(name, node)\n }\n if (ast.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 = [...ast.findCircularSchemas([...parsedByName.values()])]\n const discriminatorChildMap: Map<string, DiscriminatorTarget> | null =\n discriminatorParentNodes.length > 0 ? buildDiscriminatorChildMap(discriminatorParentNodes) : null\n\n const operationNodes = getOperations(document, refs).map((operation) =>\n parseOperation({ operation, refs, contentType, options: parserOptions, parseSchema }),\n )\n\n const promotedEnums = enums === 'root' ? collectInlineEnums([...parsedByName.values(), ...operationNodes], new Set(Object.keys(schemas))) : null\n if (promotedEnums) {\n for (const name of promotedEnums.keys()) enumNames.push(name)\n }\n\n // A collapsed single-member `allOf` is named after the wrapper, so the target comes from `ref`.\n const aliasTargetOf = (name: string) => {\n const node = refAliasMap.get(name)\n return node?.ref ? ast.refName(node.ref) : node?.name\n }\n\n // A chain of pure aliases that leads back to `name` has no target to print, so it becomes `unknown`.\n function isAliasCycle(name: string): boolean {\n const seen = new Set([name])\n for (let next = aliasTargetOf(name); next; next = aliasTargetOf(next)) {\n if (next === name) return true\n if (seen.has(next)) return false\n seen.add(next)\n }\n return false\n }\n\n function createCycleNode(name: string, pointer: string | undefined): ast.SchemaNode {\n Diagnostics.report({\n code: Diagnostics.code.aliasCycle,\n severity: 'warning',\n message: `${name} only refers to other schemas that lead back to it, so it is resolved to unknown.`,\n help: 'Give one of the schemas in the loop a real definition, or remove the `$ref` that closes it.',\n location: { kind: 'schema', pointer: pointer ?? `#/components/schemas/${name}` },\n })\n\n return ast.factory.createSchema({ type: 'unknown', name, pointer })\n }\n\n const schemaNodes: Array<ast.SchemaNode> = promotedEnums ? [...promotedEnums.values()] : []\n for (const name of Object.keys(schemas)) {\n const aliasTarget = refAliasMap.get(name)?.name\n const aliased = aliasTarget ? parsedByName.get(aliasTarget) : undefined\n const parsed = parsedByName.get(name)!\n const child = discriminatorChildMap?.get(name)\n const base = child ? patchDiscriminatorNode(parsed, child) : parsed\n const resolved = aliased ? { ...aliased, name, pointer: parsed.pointer } : base\n const node = isAliasCycle(name) ? createCycleNode(name, parsed.pointer) : resolved\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 servers: (document.servers ?? [])\n .filter((entry) => entry.url)\n .map(({ url, description, variables }) => {\n const declared = variables && Object.keys(variables).length > 0 ? { variables } : {}\n try {\n return { url: resolveServerUrl({ url, variables }), description, ...declared }\n } catch {\n return { url, description, ...declared }\n }\n }),\n securitySchemes: Object.entries(document.components?.securitySchemes ?? {}).flatMap(([name, value]) => {\n const scheme = refs.deref<Record<string, string>>(value)\n return scheme?.type\n ? [\n {\n name,\n type: scheme.type,\n description: scheme.description,\n scheme: scheme.scheme,\n bearerFormat: scheme.bearerFormat,\n in: scheme.in,\n parameterName: scheme.name,\n },\n ]\n : []\n }),\n circularNames,\n enumNames,\n extensions: pickExtensions(document),\n },\n })\n }\n\n return {\n get document() {\n return parsedDocument\n },\n get sources() {\n return sources\n },\n locate,\n async validate(input, options) {\n const document = await parseFromConfig({ type: 'path', path: input })\n assertDocument(document)\n await validateDocument(document, options)\n },\n async settle() {\n await Promise.all(pendingValidations.splice(0))\n },\n async parse(source, { signal } = {}) {\n signal?.throwIfAborted()\n const cached = inputCache.get(source)\n if (cached) {\n sources = cached.sources\n return cached.promise\n }\n\n const read: Array<string> = []\n sources = read\n const promise = (async () => {\n const document = await parseFromConfig(source, read)\n signal?.throwIfAborted()\n assertDocument(document)\n if (validate) pendingValidations.push(validateDocumentInWorker(document))\n parsedDocument = document\n\n const refs = createRefs(document)\n const { schemas, renames, pointers } = getSchemas(document, { contentType }, refs)\n const parseSchema = createSchemaParser({ document, refs, renames, options: parserOptions })\n\n return parseInput({ document, refs, schemas, pointers, parseSchema })\n })()\n inputCache.set(source, { promise, sources: read })\n return promise.catch((error: unknown) => {\n // A canceled parse must not poison the cache: the next call with the same source needs a fresh attempt.\n if (signal?.aborted) inputCache.delete(source)\n throw error\n })\n },\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AEKA,MAAa,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AC;KACxE,iBAAiB;KAEjB,MAAM,OAAO,WAAW,QAAQ;KAChC,MAAM,EAAE,SAAS,SAAS,aAAa,WAAW,UAAU,EAAE,YAAY,GAAG,IAAI;KAGjF,OAAO,WAAW;MAAE;MAAU;MAAM;MAAS;MAAU,aAFnC,mBAAmB;OAAE;OAAU;OAAM;OAAS,SAAS;MAAc,CAExB;KAAE,CAAC;IACtE,EAAA,CAAG;IACH,WAAW,IAAI,QAAQ;KAAE;KAAS,SAAS;IAAK,CAAC;IACjD,OAAO,QAAQ,OAAO,UAAmB;KAEvC,IAAI,QAAQ,SAAS,WAAW,OAAO,MAAM;KAC7C,MAAM;IACR,CAAC;GACH;EACF;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["ast","access","readFile","Diagnostics","Diagnostics","load","CORE_SCHEMA","parse","bundle","Diagnostics","join","upgrade","Diagnostics","Diagnostics","ast","ast","ast","enumPrimitive","extractRefName","macroDiscriminatorEnum","ast","extractRefName","mergeAdjacentObjectsLazy","macroSimplifyUnion","ast","ast","macroEnumName","childName","enumPropName","macroDiscriminatorEnum","ast","defineExtension","ast","Diagnostics"],"sources":["../kubb-extension.json","../package.json","../src/constants.ts","../src/emit/discriminator/propagate.ts","../../../internals/utils/src/casing.ts","../../../internals/utils/src/errors.ts","../../../internals/utils/src/jsonPointer.ts","../../../internals/utils/src/runtime.ts","../../../internals/utils/src/fs.ts","../src/oas.ts","../src/refs.ts","../src/load/source.ts","../src/load/normalize.ts","../src/model/components.ts","../src/model/server.ts","../src/emit/schemaShape.ts","../src/schemaDiagnostics.ts","../src/operation.ts","../src/emit/createNode.ts","../src/emit/discriminator/preserve.ts","../src/emit/converters/annotatedEnum.ts","../src/emit/converters/composition.ts","../src/emit/converters/scalar.ts","../src/emit/converters/structural.ts","../src/emit/parseSchema.ts","../src/parser.ts","../src/promoteEnums.ts","../src/sourceLocator.ts","../src/adapter.ts"],"sourcesContent":["","","import type { ast } from '@kubb/kit'\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 * `query` is the OpenAPI 3.2 field for the HTTP QUERY method (RFC 10008).\n */\nexport const SUPPORTED_METHODS: ReadonlySet<string> = new Set(['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace', 'query'])\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 `emit/converters/scalar.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 * Lists formats whose AST type differs from the OAS `type` field, plus string formats that\n * `KUBB_UNSUPPORTED_FORMAT` should not flag.\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.\n * `uri-reference`, `iri`, `iri-reference`, `hostname` and `idn-hostname` map to `'string'`: a relative\n * reference, a Unicode IRI or a bare host name is not a URL, so a `'url'` validator would reject valid\n * values. `base64url`, `jwt`, `ulid`, `iban` and `duration` map to `'string'` because plugins check\n * them by `format`.\n */\nexport const formatMap = {\n uuid: 'uuid',\n email: 'email',\n 'idn-email': 'email',\n uri: 'url',\n 'uri-reference': 'string',\n iri: 'string',\n 'iri-reference': 'string',\n url: 'url',\n ipv4: 'ipv4',\n ipv6: 'ipv6',\n hostname: 'string',\n 'idn-hostname': 'string',\n binary: 'blob',\n byte: 'blob',\n base64url: 'string',\n jwt: 'string',\n ulid: 'string',\n iban: 'string',\n duration: 'string',\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 } from '@kubb/kit'\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 const unionNode =\n ast.narrowSchema(schema, 'union') ??\n ast\n .narrowSchema(schema, 'intersection')\n ?.members?.map((member) => ast.narrowSchema(member, 'union'))\n .find((union) => union)\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: ast.SchemaNodeByType['ref'] | null = null\n let objNode: ast.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 convert(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// Plugins case the same names on every visit. Clearing at the limit bounds a long-running host.\nconst cache = new Map<string, string>()\nconst cacheLimit = 100_000\n\nfunction toCamelOrPascal(text: string, pascal: boolean): string {\n const key = `${pascal ? 'P' : 'c'}${text}`\n const cached = cache.get(key)\n if (cached !== undefined) return cached\n\n const result = convert(text, pascal)\n if (cache.size >= cacheLimit) cache.clear()\n cache.set(key, result)\n return result\n}\n\n/**\n * Converts `text` to camelCase.\n *\n * @example Word boundaries\n * `camelCase('hello-world') // 'helloWorld'`\n *\n * @example With a prefix\n * `camelCase('tag', { prefix: 'create' }) // 'createTag'`\n */\nexport function camelCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false)\n}\n\n/**\n * Converts `text` to PascalCase.\n *\n * @example Word boundaries\n * `pascalCase('hello-world') // 'HelloWorld'`\n *\n * @example With a suffix\n * `pascalCase('tag', { suffix: 'schema' }) // 'TagSchema'`\n */\nexport function pascalCase(text: string, { prefix = '', suffix = '' }: Options = {}): string {\n return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true)\n}\n","/**\n * Coerces an unknown thrown value to an `Error` instance.\n * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.\n *\n * @example\n * ```ts\n * try { ... } catch(err) {\n * throw new Error('Build failed', { cause: toError(err) })\n * }\n * ```\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\n/**\n * Extracts a human-readable message from any thrown value.\n *\n * @example\n * ```ts\n * getErrorMessage(new Error('oops')) // 'oops'\n * getErrorMessage('plain string') // 'plain string'\n * ```\n */\nexport function getErrorMessage(value: unknown): string {\n return value instanceof Error ? value.message : String(value)\n}\n\n/**\n * Returns `error` followed by every error in its `cause` chain, outermost first. Stops at a\n * non-`Error` cause or a cycle.\n *\n * @example\n * ```ts\n * getErrorChain(new Error('Config failed loading', { cause: new Error('boom') })).map((error) => error.message)\n * // ['Config failed loading', 'boom']\n * ```\n */\nexport function getErrorChain(error: unknown): Array<Error> {\n const chain: Array<Error> = []\n for (let current = error; current instanceof Error && !chain.includes(current); current = current.cause) {\n chain.push(current)\n }\n return chain\n}\n","/**\n * Escapes a single JSON pointer reference token per RFC 6901 (`~` → `~0`, `/` → `~1`), so a\n * name holding those characters maps to a distinct pointer.\n *\n * @example\n * ```ts\n * escapePointerToken('/pets/{id}') // '~1pets~1{id}'\n * ```\n */\nexport function escapePointerToken(token: string): string {\n return token.replaceAll('~', '~0').replaceAll('/', '~1')\n}\n","// Bun polyfills `process.versions.node`, so detection keys off the globals instead.\nconst isBun = typeof Bun !== 'undefined'\nconst isDeno = 'Deno' in globalThis\n\n/**\n * The JavaScript runtime executing the current process: its name, version and whether it is Bun.\n *\n * @example\n * ```ts\n * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise\n * ```\n */\nexport const runtime = { isBun, ...detect() } as const\n\nfunction detect(): { name: 'bun' | 'deno' | 'node'; version: string } {\n if (isBun) return { name: 'bun', version: process.versions.bun ?? '' }\n if (isDeno) return { name: 'deno', version: (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno ?? '' }\n return { name: 'node', version: process.versions?.node ?? '' }\n}\n","import { access, glob as globNode, mkdir, readFile, writeFile } from 'node:fs/promises'\n\nimport { dirname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\nexport { existsSync } from 'node:fs'\nexport { mkdir, mkdtemp, rm } from 'node:fs/promises'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n await writeRaw(resolved, content)\n\n if (options.sanity) {\n const savedData = await read(resolved)\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Writes UTF-8 content verbatim, including empty files and surrounding whitespace.\n * Uses Bun.write under Bun and creates missing parent directories under either runtime.\n *\n * @example\n * await writeRaw('./cache/output.ts', ' // keep these bytes\\n\\n')\n */\nexport async function writeRaw(path: string, content: string): Promise<void> {\n const resolved = resolve(path)\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return\n }\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n}\n\n/**\n * Lists non-hidden regular files below `directory` as relative POSIX paths, excluding directories and symlinks.\n * Uses Bun.Glob under Bun because its Node glob compatibility API lacks directory-entry support.\n *\n * @example\n * for await (const path of listFiles('./src')) console.log(path)\n */\nexport async function* listFiles(directory: string): AsyncGenerator<string> {\n const cwd = resolve(directory)\n if (runtime.isBun) {\n yield* new Bun.Glob('**/*').scan({ cwd, dot: false, onlyFiles: true, followSymlinks: false })\n return\n }\n for await (const entry of globNode('**/*', { cwd, withFileTypes: true })) {\n if (entry.isFile()) yield toPosixPath(relative(cwd, join(entry.parentPath, entry.name)))\n }\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","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 the `x-*` keys of `source` as-is, or `undefined` when there are none.\n */\nexport function pickExtensions(source: Record<string, unknown>): Record<string, unknown> | undefined {\n const entries = Object.entries(source).filter(([key]) => key.startsWith('x-'))\n return entries.length > 0 ? Object.fromEntries(entries) : undefined\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 raw binary payload.\n */\nexport function isBinary(schema: SchemaObject): boolean {\n return (\n schema.contentMediaType === 'application/octet-stream' && schema.contentEncoding === undefined && (schema.type === undefined || schema.type === 'string')\n )\n}\n\n/**\n * Returns the binary schema for a non-JSON entry the OAS 3.1 upgrade emptied out, or `undefined`\n * when the entry carries a schema of its own. The upgrade rewrites `format: 'binary'` into\n * `contentMediaType` and drops it whenever it only repeats the media type key, for any binary\n * media type (`application/octet-stream`, `application/pdf`, `image/png`, ...), not just\n * `application/octet-stream`. Without the fallback such a body resolves to the empty schema type\n * instead of a blob.\n */\nexport function getBinaryFallbackSchema(mediaType: string | undefined, schema: SchemaObject | ReferenceObject | undefined): SchemaObject | undefined {\n if (!mediaType || isJsonMimeType(mediaType)) return undefined\n if (schema && Object.keys(schema).length > 0) return undefined\n\n return { type: 'string', 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","import { type Diagnostic, Diagnostics } from '@kubb/kit'\nimport type { ast } from '@kubb/kit'\nimport type { ParseFn } from './emit/parseSchema.ts'\nimport { isReference } from './oas.ts'\nimport type { Document, SchemaObject } from './types.ts'\n\n/**\n * The `$ref` service bound to one document: pointer resolution and resolved-node parsing, each\n * with its own instance-scoped memoization.\n */\nexport type Refs = ReturnType<typeof createRefs>\n\n/**\n * Creates the `$ref` resolution service for one document. One pointer walk backs every method.\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.resolveNode('#/components/schemas/Pet', parseSchema)\n * refs.deref<ResponseObject>(operation.schema.responses?.['200'])\n * refs.derefKeepingRef(parameter)\n * ```\n */\nexport function createRefs(document: Document) {\n const pointerCache = new Map<string, unknown>()\n const resolvedNodeCache = new Map<string, ast.SchemaNode | null>()\n const resolvingRefs = new Set<string>()\n\n function walkPointer<T>($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 = trimmed.substring(1)\n\n if (pointerCache.has(pointer)) {\n return { applicable: true, value: pointerCache.get(pointer) as T }\n }\n\n // Split before decoding so an encoded `%2F` stays inside its token, then unescape `~1` and `~0` (RFC 6901).\n const current = pointer\n .split('/')\n .filter(Boolean)\n .map((token) => globalThis.decodeURIComponent(token).replaceAll('~1', '/').replaceAll('~0', '~'))\n .reduce((obj: unknown, key: string) => (obj as Record<string, unknown>)?.[key], document as unknown)\n\n if (current) {\n pointerCache.set(pointer, current)\n }\n\n return { applicable: true, value: (current as T) ?? null }\n }\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 const { applicable, value } = walkPointer<T>(refPath)\n if (!applicable || value || options?.report === false) return value\n\n const diagnostic: Diagnostic = {\n code: Diagnostics.code.refNotFound,\n severity: 'error',\n message: `Could not find a definition for ${refPath}.`,\n help: 'Add the schema under `components.schemas`, or fix the `$ref`. Run `kubb validate` to check the spec.',\n location: { kind: 'schema', pointer: refPath, ref: refPath },\n }\n if (!Diagnostics.report(diagnostic)) {\n throw new Diagnostics.Error(diagnostic)\n }\n return null\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: ParseFn): 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 })\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 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 /** Resolves a `$ref` object but keeps the `$ref` field on the result; other values pass through. */\n function derefKeepingRef<T = unknown>(value?: T): T {\n if (isReference(value)) {\n return { ...value, ...resolve(value.$ref), $ref: value.$ref }\n }\n\n return value as T\n }\n\n return { resolve, resolveNode, deref, derefKeepingRef }\n}\n","import { exists, getErrorMessage, read, toError } from '@internals/utils'\nimport { Diagnostics } from '@kubb/kit'\nimport { CORE_SCHEMA, load } from 'js-yaml'\nimport { parse } from 'yaml'\n\nexport const 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 */\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 return parseYaml(data, {\n origin: sourcePath,\n help: 'Fix the syntax at the reported line, or check that `input` points at the spec and not an HTML page.',\n })\n}\n\n/**\n * Parses a YAML (or JSON) spec. A syntax error throws `KUBB_INVALID_DOCUMENT` naming `origin`,\n * with the parser message, which keeps the line and column.\n *\n * JSON is valid YAML, so one parser handles both. `js-yaml` parses about ten times faster than\n * `yaml`, and unlike `JSON.parse` it rejects duplicate keys instead of keeping the last one. Its\n * core schema keeps timestamps as strings and `<<` as a plain key, as `yaml` does for YAML 1.2.\n */\nexport function parseYaml(data: string, { origin, help }: { origin: string; help: string }): object {\n try {\n const document = load(data, { schema: CORE_SCHEMA })\n if (document !== undefined) return document as object\n } catch {\n // `yaml` parses it again below to report the error with its line and column.\n }\n try {\n return parse(data) as object\n } catch (error) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidDocument,\n severity: 'error',\n message: `Cannot parse ${origin} as JSON or YAML: ${getErrorMessage(error)}`,\n help,\n location: { kind: 'config' },\n cause: toError(error),\n })\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 (urlRegExp.test(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","import { join } from 'node:path'\nimport { escapePointerToken, getErrorMessage, toError } from '@internals/utils'\nimport { Diagnostics } from '@kubb/kit'\nimport type { AdapterSource, Diagnostic } from '@kubb/kit'\nimport { upgrade } from '@scalar/openapi-upgrader'\nimport { bundle } from 'api-ref-bundler'\nimport { createRefs } from '../refs.ts'\nimport type { Document } from '../types.ts'\nimport type { ValidationErrors, WorkerResult } from './validateWorker.ts'\nimport { assertInputExists, parseYaml, 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 * Replaces each `$ref` into `#/paths/...` with a copy of its target, in place.\n *\n * The Swagger 2.0 upgrade moves `responses/200/schema` under `content`, so a ref to the old location\n * would no longer resolve. A ref that points back into itself is kept, since inlining it never ends.\n */\nfunction inlinePathRefs(node: unknown, resolve: (ref: string) => unknown, visiting: Array<string> = []): unknown {\n if (!node || typeof node !== 'object') {\n return node\n }\n\n const ref = (node as { $ref?: unknown }).$ref\n if (typeof ref === 'string' && ref.startsWith('#/paths/') && !visiting.includes(ref)) {\n const target = resolve(ref)\n return target && typeof target === 'object' ? inlinePathRefs(structuredClone(target), resolve, [...visiting, ref]) : node\n }\n\n for (const [key, value] of Object.entries(node)) {\n ;(node as Record<string, unknown>)[key] = inlinePathRefs(value, resolve, visiting)\n }\n return node\n}\n\n// Keys that hold user-named entries. An `x-` name here is a real schema, header or parameter, not an extension.\nconst namedEntryKeys = new Set([\n 'properties',\n 'patternProperties',\n 'headers',\n 'schemas',\n 'responses',\n 'parameters',\n 'requestBodies',\n 'examples',\n 'links',\n 'callbacks',\n 'securitySchemes',\n 'securityDefinitions',\n 'pathItems',\n 'definitions',\n '$defs',\n])\n\n/**\n * True when `path` runs through an `x-` vendor extension. Kubb never reads an extension, so a `$ref`\n * Kubb cannot read inside one cannot change the output.\n */\nfunction isExtensionPath(path: ReadonlyArray<string | number>): boolean {\n return path.some((token, index) => String(token).startsWith('x-') && !namedEntryKeys.has(String(path[index - 1])))\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 * `document` stands in for the file at `pathOrUrl`, such as inline input. Every other file or URL\n * read, including one that fails, lands in `sources`. A `$ref` that cannot be read reports\n * `KUBB_REF_NOT_FOUND` at the key that holds it, as a warning when it sits inside an `x-` extension.\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, { document, sources = [] }: { document?: Document; sources?: Array<string> } = {}): Promise<Document> {\n const cache = new Map<string, Promise<object | string>>()\n // api-ref-bundler refers to the same URL as both `https://` and the posix-normalized\n // `https:/`, so key on the canonical href to fetch each source once and to match the input.\n const toKey = (sourcePath: string) => (urlRegExp.test(sourcePath) ? new URL(sourcePath).href : sourcePath)\n\n const resolver = (sourcePath: string) => {\n if (document && sourcePath === pathOrUrl) {\n return Promise.resolve(document)\n }\n const key = toKey(sourcePath)\n const cached = cache.get(key)\n if (cached) {\n return cached\n }\n\n sources.push(key)\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, {\n hooks: {\n onError: (message, { path, state }) => {\n // Only a `$ref` in the input itself has a key in the document to point at.\n const pointer = toKey(state.baseFile) === toKey(pathOrUrl) ? `#/${path.map((token) => escapePointerToken(String(token))).join('/')}` : undefined\n const diagnostic: Diagnostic = {\n code: Diagnostics.code.refNotFound,\n severity: isExtensionPath(path) ? 'warning' : 'error',\n message: `Could not bundle an external \\`$ref\\`. ${message}.`,\n help: 'Check that the file or URL the `$ref` points at exists and is readable, or fix the `$ref`.',\n ...(pointer && { location: { kind: 'schema', pointer } }),\n }\n if (!Diagnostics.report(diagnostic) && diagnostic.severity === 'error') {\n throw new Diagnostics.Error(diagnostic)\n }\n },\n },\n })) as Document\n}\n\n// Inline input has no file of its own, so its relative `$ref`s resolve from a stand-in name in `root`.\nconst inlineInputName = '<inline input>'\n\n/**\n * Creates a `Document` from an `AdapterSource`.\n *\n * - `{ type: 'path' }` bundles an absolute file path (core resolves `input`) or remote URL via\n * `api-ref-bundler`, hoisting external file schemas into named `components.schemas` entries so\n * generators can emit named types and imports.\n * - `{ type: 'data' }` parses an inline string (YAML/JSON) or raw object, then bundles its\n * external `$ref`s from `root` when it has any. Each file or URL read lands in `sources`.\n *\n * Swagger 2.0 and OpenAPI 3.0 documents are up-converted to OpenAPI 3.1 via `@scalar/openapi-upgrader`.\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, sources: Array<string> = []): Promise<Document> {\n const raw = await (async (): Promise<Document> => {\n // YAML parsing also handles JSON.\n if (source.type === 'data') {\n const data =\n typeof source.data === 'string'\n ? (parseYaml(source.data, {\n origin: 'the inline `input` string',\n help: 'Fix the syntax at the reported line. Kubb reads `input` as an inline spec, not a file path, because it starts with `{`, `[`, `openapi:`, or `swagger:`, or spans several lines.',\n }) as Document)\n : structuredClone(source.data as Document)\n return source.root && hasExternalRef(data) ? bundleDocument(join(source.root, inlineInputName), { document: data, sources }) : data\n }\n await assertInputExists(source.path)\n return bundleDocument(source.path, { sources })\n })()\n\n // Unquoted `swagger: 2.0` parses as the number 2, which `upgrade` does not recognise as a version.\n if (raw && typeof raw === 'object') {\n const document = raw as Record<string, unknown>\n for (const key of ['swagger', 'openapi']) {\n const version = document[key]\n if (typeof version === 'number') {\n document[key] = Number.isInteger(version) ? version.toFixed(1) : String(version)\n }\n }\n }\n\n if (raw && typeof raw === 'object' && 'swagger' in raw) {\n const refs = createRefs(raw)\n inlinePathRefs(raw, (ref) => refs.resolve(ref, { report: false }))\n }\n\n // `upgrade` chains Swagger 2.0 -> 3.0 -> 3.1, leaving documents already on 3.1 untouched.\n try {\n return upgrade(raw, '3.1') as Document\n } catch (error) {\n const declared = raw && typeof raw === 'object' ? ((raw as { openapi?: unknown }).openapi ?? (raw as { swagger?: unknown }).swagger) : undefined\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidDocument,\n severity: 'error',\n message: `Cannot upgrade the document${declared ? ` (version ${String(declared)})` : ''} to OpenAPI 3.1: ${getErrorMessage(error)}`,\n help: 'Kubb reads Swagger 2.0, OpenAPI 3.0, and OpenAPI 3.1. Set `swagger` or `openapi` to one of those versions, and fix the reported problem in the document.',\n location: { kind: 'config' },\n cause: toError(error),\n })\n }\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 // An inline string with no YAML mapping parses to a plain string, which the `in` checks would throw on.\n if (document && typeof document === 'object' && ('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/** Reports a validation problem as a `KUBB_INVALID_SPEC` warning, a no-op outside a build. */\nfunction reportInvalidSpec(message: string): void {\n Diagnostics.report({\n code: Diagnostics.code.invalidSpec,\n severity: 'warning',\n message,\n help: 'Fix the spec, or run `kubb validate` to list every error. Set `validate: false` on the adapter to skip this check.',\n })\n}\n\n/**\n * Validates an OpenAPI document using `@readme/openapi-parser`. Throws with `throwOnError`, otherwise warns.\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 let result: Awaited<ReturnType<typeof validate>>\n try {\n // `validate` dereferences its input in place, so clone to keep the cached document intact.\n result = await validate(structuredClone(document), {\n validate: {\n errors: { colorize: throwOnError },\n },\n })\n } catch (error) {\n if (throwOnError) throw error\n reportInvalidSpec(getErrorMessage(error))\n return\n }\n\n if (result.valid) return\n if (throwOnError)\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidSpec,\n severity: 'error',\n message: compileErrors(result),\n help: 'Fix each problem listed in the spec, then validate again.',\n })\n\n reportValidationErrors(result)\n}\n\nfunction reportValidationErrors({ errors, additionalErrors }: ValidationErrors): void {\n for (const { message } of errors) {\n // The code frame after the first line numbers a JSON copy of the spec, not the user's file.\n reportInvalidSpec(message.replace(/\\n.*/s, ''))\n }\n if (additionalErrors > 0) {\n reportInvalidSpec(`${additionalErrors} more validation errors are not listed.`)\n }\n}\n\n/**\n * Validates like {@link validateDocument} without `throwOnError`, but in a worker thread, so the\n * build keeps generating while `@readme/openapi-parser` dereferences and checks the spec. Await the\n * returned promise inside the build's diagnostics scope to report its warnings there. Falls back to\n * validating in place where worker threads are missing, as in edge runtimes.\n */\nexport async function validateDocumentInWorker(document: Document): Promise<void> {\n let message: WorkerResult\n try {\n const { Worker } = await import('node:worker_threads')\n // Tests run the `.ts` source; the build emits `validateWorker.js` next to the bundle.\n const workerFile = import.meta.url.endsWith('.ts') ? './validateWorker.ts' : './validateWorker.js'\n // `workerData` is a structured clone, so the worker can dereference it without touching the cached document.\n const worker = new Worker(new URL(workerFile, import.meta.url), { workerData: document })\n message = await new Promise<WorkerResult>((resolve, reject) => {\n worker.once('message', resolve)\n worker.once('error', reject)\n worker.once('exit', (code) => reject(new Error(`Validation worker exited with code ${code}`)))\n }).finally(() => worker.terminate())\n } catch {\n return validateDocument(document)\n }\n\n if ('thrown' in message) return reportInvalidSpec(message.thrown)\n if (!message.valid) reportValidationErrors(message)\n}\n","import { escapePointerToken, 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, 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 * The `$ref` target of the entry, which keys `renames`.\n */\n ref: string\n /**\n * Where the schema itself sits, when that differs from `ref`, as for a response's `content` schema.\n */\n pointer?: string\n nested?: boolean\n}\n\ntype GetSchemasResult = {\n schemas: Record<string, SchemaObject>\n /**\n * The JSON pointer each key in `schemas` was read from.\n */\n pointers: Map<string, string>\n /**\n * Maps nested schema pointers and collision-renamed component pointers to the unique\n * names used as keys in `schemas`. Components with their original names and no nested\n * definitions are not recorded.\n */\n renames: Map<string, string>\n}\n\n/**\n * Extracts the inline schema from a media-type `content` map, with the media type it sits under.\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 * // { schema: SchemaObject, contentType: 'application/json' } | null\n * ```\n */\nfunction extractSchemaFromContent(\n content: Record<string, unknown> | undefined,\n preferredContentType?: ContentType,\n): { schema: SchemaObject; contentType: string } | 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 (!schema || isReference(schema)) return null\n return { schema, contentType: targetContentType }\n}\n\n/**\n * Walks a schema tree and collects the names of all `#/components/schemas/<name>` `$ref`s.\n */\nfunction* collectRefs(schema: unknown, renames: Map<string, string>): Generator<string, void, undefined> {\n if (Array.isArray(schema)) {\n for (const item of schema) yield* collectRefs(item, renames)\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, renames)\n continue\n }\n if (value.startsWith(SCHEMA_REF_PREFIX)) {\n const name = renames.get(value) ?? value.slice(SCHEMA_REF_PREFIX.length)\n if (name) yield name\n }\n }\n }\n}\n\nconst schemaChildKeywords = [\n 'additionalProperties',\n 'allOf',\n 'anyOf',\n 'contains',\n 'contentSchema',\n 'else',\n 'if',\n 'items',\n 'not',\n 'oneOf',\n 'patternProperties',\n 'prefixItems',\n 'properties',\n 'propertyNames',\n 'then',\n] as const\n\n/** Collects definitions only from schema locations, never from examples/defaults or arbitrary data. */\nfunction* collectNestedDefinitions(\n schema: unknown,\n pointer: string,\n name: string,\n): Generator<{ schema: SchemaObject; ref: string; originalName: string }, void, undefined> {\n if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return\n const value = schema as Record<string, unknown>\n\n for (const keyword of ['$defs', 'definitions'] as const) {\n const definitions = value[keyword]\n if (!definitions || typeof definitions !== 'object' || Array.isArray(definitions)) continue\n for (const [key, definition] of Object.entries(definitions)) {\n if (!definition || typeof definition !== 'object' || Array.isArray(definition)) continue\n const definitionPointer = `${pointer}/${keyword}/${escapePointerToken(key)}`\n const nestedName = `${name}_${key}`\n yield { schema: definition as SchemaObject, ref: definitionPointer, originalName: nestedName }\n yield* collectNestedDefinitions(definition, definitionPointer, nestedName)\n }\n }\n\n for (const keyword of schemaChildKeywords) {\n const child = value[keyword]\n if (!child || typeof child !== 'object') continue\n if (Array.isArray(child)) {\n for (const [index, item] of child.entries()) yield* collectNestedDefinitions(item, `${pointer}/${keyword}/${index}`, name)\n continue\n }\n if (keyword === 'properties' || keyword === 'patternProperties') {\n for (const [key, item] of Object.entries(child)) yield* collectNestedDefinitions(item, `${pointer}/${keyword}/${escapePointerToken(key)}`, name)\n continue\n }\n yield* collectNestedDefinitions(child, `${pointer}/${keyword}`, name)\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 */\nfunction sortSchemas(schemas: Record<string, SchemaObject>, renames: Map<string, string>): 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, renames))])\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 * 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 }: { contentType?: ContentType }, 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>) ?? {}).flatMap(([name, schema]) => {\n const ref = `#/components/schemas/${escapePointerToken(name)}`\n return [\n { schema: resolveSchemaRef(schema), source: 'schemas' as const, originalName: name, ref },\n ...[...collectNestedDefinitions(schema, ref, name)].map((nested) => ({\n ...nested,\n source: 'schemas' as const,\n nested: true,\n })),\n ]\n }),\n ...(['responses', 'requestBodies'] as const).flatMap((source) =>\n Object.entries(components?.[source] ?? {}).flatMap(([name, item]) => {\n const extracted = extractSchemaFromContent((item as { content?: Record<string, unknown> }).content, contentType)\n if (!extracted) return []\n const ref = `#/components/${source}/${escapePointerToken(name)}`\n return [\n {\n schema: resolveSchemaRef(extracted.schema),\n source,\n originalName: name,\n ref,\n pointer: `${ref}/content/${escapePointerToken(extracted.contentType)}/schema`,\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 const pointers = 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 // Unique names keep theirs. A collision across sources gets a semantic suffix, within one source a numeric one.\n const suffix = isSingle ? '' : hasMultipleSources ? semanticSuffixes[item.source] : index ? String(index + 1) : ''\n const uniqueName = item.originalName + suffix\n schemas[uniqueName] = item.schema\n pointers.set(uniqueName, item.pointer ?? item.ref)\n if (suffix || item.nested) renames.set(item.ref, uniqueName)\n })\n }\n\n return { schemas: sortSchemas(schemas, renames), renames, pointers }\n}\n","import { Diagnostics } from '@kubb/kit'\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 type { ast } from '@kubb/kit'\nimport { formatMap, specialCasedFormats, structuralKeys } from '../constants.ts'\nimport { isReference } from '../oas.ts'\nimport type { SchemaObject } from '../types.ts'\n\n/**\n * Whether `format` maps to a dedicated type; `false` is what `KUBB_UNSUPPORTED_FORMAT` flags.\n */\nexport function isHandledFormat(format: string): boolean {\n return formatMap[format as keyof typeof formatMap] !== undefined || specialCasedFormats.has(format)\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 * 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\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. Returns the\n * 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 * flattenSchema({ allOf: [{ $ref: '#/components/schemas/Pet' }] })\n * // returned unchanged, contains a $ref\n * ```\n */\nexport function flattenSchema(schema: SchemaObject): SchemaObject {\n if (!schema.allOf?.length) return schema\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 { escapePointerToken } from '@internals/utils'\nimport type { ast } from '@kubb/kit'\nimport { Diagnostics } from '@kubb/kit'\nimport { isHandledFormat } from './emit/schemaShape.ts'\n\n/**\n * Links one freshly converted schema and its nested schemas to their RFC 6901 pointers\n * (`#/components/schemas/Pet/properties/owner/properties/name`), and reports the advisory\n * diagnostics (`KUBB_UNSUPPORTED_FORMAT`, `KUBB_DEPRECATED`) against them.\n * Refs are not followed, so the resolved schema is handled 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: ast.SchemaNode, pointer = node.pointer): void {\n if (pointer) visit(node, pointer)\n}\n\nfunction visit(node: ast.SchemaNode, pointer: string): void {\n node.pointer ??= pointer\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)}`)\n }\n if (node.additionalProperties && typeof node.additionalProperties === 'object') {\n visit(node.additionalProperties, `${pointer}/additionalProperties`)\n }\n return\n }\n\n if (node.type === 'array') {\n for (const item of node.items ?? []) {\n visit(item, `${pointer}/items`)\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}`)\n }\n return\n }\n\n if (node.type === 'not') {\n for (const member of node.members ?? []) visit(member, `${pointer}/not`)\n return\n }\n\n // shortcut: a member the parser adds, such as the wrapper around `not` with sibling keys, gets an index past the spec's own entries; set pointers in the converters if editors need those exact.\n if (node.type === 'union' || node.type === 'intersection') {\n const keyword = node.type === 'intersection' ? 'allOf' : node.strategy === 'any' ? 'anyOf' : 'oneOf'\n for (const [index, member] of (node.members ?? []).entries()) {\n visit(member, `${pointer}/${keyword}/${index}`)\n }\n }\n}\n","import { escapePointerToken, pascalCase } from '@internals/utils'\nimport { ast } from '@kubb/kit'\nimport { SUPPORTED_METHODS } from './constants.ts'\nimport type { ParseFn } from './emit/parseSchema.ts'\nimport { getBinaryFallbackSchema, isJsonMimeType, isReference, pickExtensions } from './oas.ts'\nimport { scanSchema } from './schemaDiagnostics.ts'\nimport type { Refs } from './refs.ts'\nimport type {\n ContentType,\n Document,\n MediaTypeObject,\n OperationObject,\n ParameterObject,\n PathItemObject,\n ReferenceObject,\n RequestBodyObject,\n ResponseObject,\n SchemaObject,\n} from './types.ts'\n\n/**\n * A single OpenAPI operation: its path, method, raw operation object and resolved path item.\n */\nexport type Operation = {\n path: string\n method: string\n schema: OperationObject\n pathItem: PathItemObject\n}\n\ntype OperationContext = {\n operation: Operation\n refs: Refs\n}\n\n/** What `parseOperation` needs beyond the operation. */\nexport type OperationParseContext = {\n refs: Refs\n contentType?: ContentType\n options: ast.ParserOptions\n parseSchema: ParseFn\n}\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`. `null` when absent.\n */\nexport function getResponseByStatusCode({ operation, refs, statusCode }: OperationContext & { statusCode: string | number }): ResponseObject | null {\n const responses = operation.schema.responses as Record<string, ResponseObject | ReferenceObject> | undefined\n if (!responses || isReference(responses)) {\n return null\n }\n\n return refs.deref<ResponseObject>(responses[statusCode])\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 * 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 = getRequestBody({ operation, refs })?.content\n const mediaTypes = content ? Object.keys(content) : []\n\n return mediaTypes.findLast(isJsonMimeType) ?? mediaTypes[0] ?? 'application/json'\n}\n\n/** Merges path-level and operation-level parameters; operation-level wins per `in:name`. */\nexport function getParameters({ operation, refs }: OperationContext): Array<{ param: ParameterObject; pointer: string }> {\n // Each parameter keeps the pointer of the entry that declares it, on the path item or the operation.\n const resolveParams = (params: Array<unknown>, pointer: string) =>\n params.flatMap((entry, index) => {\n const param = refs.derefKeepingRef(entry)\n return param && typeof param === 'object' && 'in' in param && 'name' in param\n ? [{ param: param as ParameterObject, pointer: `${pointer}/parameters/${index}` }]\n : []\n })\n\n const pathPointer = `#/paths/${escapePointerToken(operation.path)}`\n const operationParams = resolveParams(operation.schema?.parameters || [], `${pathPointer}/${operation.method.toLowerCase()}`)\n const pathLevelParams = resolveParams((operation.pathItem as { parameters?: Array<unknown> }).parameters ?? [], pathPointer)\n\n const paramMap = new Map<string, { param: ParameterObject; pointer: string }>()\n for (const entry of [...pathLevelParams, ...operationParams]) {\n if (entry.param.name && entry.param.in) {\n paramMap.set(`${entry.param.in}:${entry.param.name}`, entry)\n }\n }\n\n return Array.from(paramMap.values())\n}\n\nconst PARAMETER_STYLES = new Set(['matrix', 'label', 'form', 'simple', 'spaceDelimited', 'pipeDelimited', 'deepObject'])\n\n/** The `encoding` of a media type, reduced to the entries that set a field Kubb carries. A `style` outside the OpenAPI set is dropped. */\nfunction getEncoding(encoding: MediaTypeObject['encoding']): Record<string, ast.EncodingNode> | undefined {\n const entries = Object.entries(encoding ?? {}).flatMap(([property, { contentType, style, explode, allowReserved }]) => {\n const node: ast.EncodingNode = {\n ...(contentType !== undefined ? { contentType } : {}),\n ...(style !== undefined && PARAMETER_STYLES.has(style) ? { style: style as ast.ParameterStyle } : {}),\n ...(explode !== undefined ? { explode } : {}),\n ...(allowReserved !== undefined ? { allowReserved } : {}),\n }\n return Object.keys(node).length ? [[property, node] as const] : []\n })\n\n return entries.length ? Object.fromEntries(entries) : undefined\n}\n\n/** Schema for one media type of a `content` map, with the binary fallback for an emptied non-JSON entry. */\nexport function getBodySchema({\n content,\n contentType,\n refs,\n}: {\n content: Record<string, MediaTypeObject> | undefined\n contentType: string | undefined\n refs: Refs\n}): SchemaObject | null {\n const entry = contentType ? content?.[contentType] : undefined\n if (!entry) return null\n\n const binary = getBinaryFallbackSchema(contentType, entry.schema)\n if (binary) return binary\n\n return entry.schema ? refs.derefKeepingRef(entry.schema as SchemaObject) : null\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 */\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\n/** Property names whose schema has a truthy `readOnly` or `writeOnly` flag; `$ref` entries are skipped. */\nfunction 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\nfunction parseParameter({\n param,\n pointer,\n parentName,\n options,\n parseSchema,\n}: Pick<OperationParseContext, 'options' | 'parseSchema'> & { param: ParameterObject; pointer: string; parentName?: string }): ast.ParameterNode {\n const schemaName = parentName && param.name ? pascalCase(`${parentName} ${param.name}`) : undefined\n // A parameter defines either `schema` or `content`, and `content` holds exactly one media type.\n const contentType = param.schema ? undefined : Object.keys(param.content ?? {})[0]\n const rawSchema = param.schema ?? (contentType ? param.content?.[contentType]?.schema : undefined)\n const schema: ast.SchemaNode = rawSchema\n ? parseSchema({ schema: rawSchema as SchemaObject, name: schemaName })\n : ast.factory.createSchema({ type: options.unknownType })\n if (rawSchema) scanSchema(schema, contentType ? `${pointer}/content/${escapePointerToken(contentType)}/schema` : `${pointer}/schema`)\n const style = param.style !== undefined && PARAMETER_STYLES.has(param.style) ? (param.style as ast.ParameterStyle) : undefined\n const explode = param.explode\n const allowReserved = param.allowReserved\n\n return ast.factory.createParameter({\n pointer,\n name: param.name,\n in: param.in,\n schema: {\n ...schema,\n description: param.description ?? schema.description,\n },\n required: param.required ?? false,\n ...(style !== undefined ? { style } : {}),\n ...(explode !== undefined ? { explode } : {}),\n ...(allowReserved !== undefined ? { allowReserved } : {}),\n ...(contentType !== undefined ? { contentType } : {}),\n })\n}\n\n/**\n * Converts an OAS `Operation` into an `OperationNode`.\n */\nexport function parseOperation({ operation, ...ctx }: OperationParseContext & { operation: Operation }): ast.OperationNode {\n const { refs, contentType, options, parseSchema } = ctx\n const operationId = getOperationId(operation)\n const operationName = operationId ? pascalCase(operationId) : undefined\n const pointer = `#/paths/${escapePointerToken(operation.path)}/${operation.method.toLowerCase()}`\n const parameters = getParameters({ operation, refs }).map((entry) => parseParameter({ options, parseSchema, ...entry, parentName: operationName }))\n\n // A configured contentType restricts the body to that one media type; otherwise every declared one is kept.\n const body = getRequestBody({ operation, refs })\n const bodyRequired = body?.required === true\n const requestBodyName = operationName ? `${operationName}Request` : undefined\n const requestContentTypes = contentType ? [contentType] : Object.keys(body?.content ?? {})\n\n const content = requestContentTypes.flatMap((ct) => {\n const schema = getBodySchema({ content: body?.content, contentType: ct, refs })\n if (!schema) return []\n const node = parseSchema({ schema, name: requestBodyName })\n scanSchema(node, `${pointer}/requestBody/content/${escapePointerToken(ct)}/schema`)\n const encoding = getEncoding(body?.content?.[ct]?.encoding)\n return [\n ast.factory.createContent({\n contentType: ct,\n schema: ast.optionality(node, bodyRequired),\n keysToOmit: collectPropertyKeysByFlag(schema, 'readOnly'),\n ...(encoding && { encoding }),\n }),\n ]\n })\n\n const requestBody =\n content.length > 0 || body?.description\n ? {\n pointer: `${pointer}/requestBody`,\n description: body?.description,\n required: bodyRequired || undefined,\n content: content.length > 0 ? content : undefined,\n }\n : undefined\n\n const responses = getResponseStatusCodes(operation).map((statusCode) => {\n const response = getResponseByStatusCode({ operation, refs, statusCode })\n // `Status<code>` keeps nested enum names clear of a component schema named `<operation><statusCode>`.\n const responseName = operationName ? `${operationName}Status${statusCode}` : undefined\n\n const parseEntrySchema = (ct?: string) => {\n const raw = getBodySchema({ content: response?.content, contentType: ct, refs })\n const node =\n raw && Object.keys(raw).length > 0 ? parseSchema({ schema: raw, name: responseName }) : ast.factory.createSchema({ type: options.emptySchemaType })\n if (raw && ct) scanSchema(node, `${pointer}/responses/${statusCode}/content/${escapePointerToken(ct)}/schema`)\n return { schema: node, keysToOmit: collectPropertyKeysByFlag(raw, 'writeOnly') }\n }\n\n const responseContentTypes = contentType ? [contentType] : Object.keys(response?.content ?? {})\n const responseContent = responseContentTypes.map((ct) => ast.factory.createContent({ contentType: ct, ...parseEntrySchema(ct) }))\n\n // A body-less response keeps one fallback entry so it still resolves to a (void/any) schema.\n if (responseContent.length === 0) {\n responseContent.push(\n ast.factory.createContent({\n contentType: getRequestContentType({ operation, refs }),\n ...parseEntrySchema(contentType),\n }),\n )\n }\n\n return ast.factory.createResponse({\n pointer: `${pointer}/responses/${statusCode}`,\n statusCode: statusCode as ast.StatusCode,\n description: response?.description,\n content: responseContent,\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 pointer,\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 extensions: pickExtensions(operation.schema),\n })\n}\n","import { ast } from '@kubb/kit'\nimport { extractExamples } from './schemaShape.ts'\nimport type { ConvertContext } 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<ConvertContext, '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, enumPrimitive, 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\ntype DiscriminatorValue = string | number | boolean\n\n/**\n * Turns string mapping keys into the discriminator property's type when they parse cleanly.\n */\nexport function typedKeys({ keys, propertyType }: { keys: Array<string>; propertyType: unknown }): Array<DiscriminatorValue> {\n return keys.map((key) => {\n if (propertyType === 'integer' || propertyType === 'number') {\n const value = Number(key)\n return key.trim() !== '' && Number.isFinite(value) ? value : key\n }\n if (propertyType === 'boolean') {\n const lower = key.toLowerCase()\n return lower === 'true' ? true : lower === 'false' ? false : key\n }\n return key\n })\n}\n\n/**\n * Reads the declared `type` of `propertyName` on a schema, following `$ref`s and `allOf` members.\n * A nullable array such as `['integer', 'null']` reads as its one non-null type.\n */\nexport function propertyTypeOf({\n schema,\n propertyName,\n refs,\n seen = new Set<string>(),\n}: {\n schema: SchemaObject | ReferenceObject | undefined\n propertyName: string\n refs: Refs\n seen?: Set<string>\n}): unknown {\n const deref = (value: SchemaObject | ReferenceObject | undefined) =>\n value && isReference(value) ? refs.resolve<SchemaObject>(value.$ref, { report: false }) : value\n\n if (schema && isReference(schema)) {\n if (seen.has(schema.$ref)) return undefined\n seen.add(schema.$ref)\n }\n\n const resolved = deref(schema) as SchemaObject | undefined\n const type =\n (deref(resolved?.properties?.[propertyName] as SchemaObject | ReferenceObject | undefined) as SchemaObject | undefined)?.type ??\n resolved?.allOf?.map((member) => propertyTypeOf({ schema: member as SchemaObject | ReferenceObject, propertyName, refs, seen })).find(Boolean)\n const nonNull = Array.isArray(type) ? type.filter((t) => t !== 'null') : []\n\n return nonNull.length === 1 ? nonNull[0] : type\n}\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<DiscriminatorValue> }): 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: enumPrimitive(values),\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({ mapping: { dog: '#/components/schemas/Dog', hound: '#/components/schemas/Dog' }, ref: '#/components/schemas/Dog' }) // ['dog', 'hound']\n * ```\n */\nexport function findDiscriminators({ mapping, ref }: { 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 * Finds the discriminator a schema declares itself or through an inline `allOf` member.\n */\nfunction getDiscriminator(schema: SchemaObject): DiscriminatorObject | undefined {\n return (isDiscriminator(schema) ? schema : (schema.allOf as Array<SchemaObject> | undefined)?.find(isDiscriminator))?.discriminator\n}\n\n/**\n * Lists the mapping keys of a discriminator plus the keys of the nested discriminators its mapped\n * schemas declare on the same property, so a root `$type` accepts values from every level.\n */\nexport function getMappingKeys({\n discriminator: { propertyName, mapping },\n refs,\n seen = new Set<string>(),\n}: {\n discriminator: DiscriminatorObject\n refs: Refs\n seen?: Set<string>\n}): Array<string> {\n return Object.entries(mapping ?? {}).flatMap(([key, target]) => {\n if (seen.has(target)) return [key]\n seen.add(target)\n\n const resolved = refs.resolve<SchemaObject>(target, { report: false })\n const nested = resolved && getDiscriminator(resolved)\n\n return nested?.propertyName === propertyName ? [key, ...getMappingKeys({ discriminator: nested, refs, seen })] : [key]\n })\n}\n\n/**\n * Drops the discriminator from an inline `allOf` member when a `$ref` sibling already declares one on\n * the same property. That mapping names the schema's own children, and keeping it pins the property\n * to those keys next to the parent's, which leaves `never`.\n */\nexport function removeInheritedDiscriminator({\n members,\n refs,\n}: {\n members: Array<SchemaObject | ReferenceObject>\n refs: Refs\n}): Array<SchemaObject | ReferenceObject> {\n const inherited = new Set(\n members.flatMap((member) => {\n const parent = isReference(member) ? refs.resolve<SchemaObject>(member.$ref, { report: false }) : null\n return (parent && getDiscriminator(parent)?.propertyName) || []\n }),\n )\n\n return members.map((member) => {\n if (isReference(member) || !isDiscriminator(member) || member.oneOf || member.anyOf) return member\n if (!inherited.has(member.discriminator.propertyName)) return member\n const { discriminator: _discriminator, ...rest } = member\n\n return rest\n })\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 parentType,\n parse,\n name,\n refs,\n}: {\n unionMembers: Array<unknown>\n discriminator: DiscriminatorObject | undefined\n sharedPropertiesNode: ast.SchemaNode | undefined\n parentType?: unknown\n parse: ParseFn\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({ mapping: discriminator?.mapping, ref })\n const implicitValue = mappedValues.length ? null : implicitDiscriminantValue(s)\n const propertyType = propertyTypeOf({ schema: s as SchemaObject, propertyName: discriminator?.propertyName ?? '', refs }) ?? parentType\n const discriminatorValues = typedKeys({ keys: mappedValues.length ? mappedValues : implicitValue ? [implicitValue] : [], propertyType })\n const memberNode = parse({ schema: s as SchemaObject, name })\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<DiscriminatorValue> }>\n} {\n const discriminantValues: Array<{ propertyName: string; values: Array<DiscriminatorValue> }> = []\n\n const members = allOfMembers.filter((item) => {\n if (!isReference(item) || !name) return true\n const deref = refs.resolve<SchemaObject>(item.$ref)\n const discriminator = deref && getDiscriminator(deref)\n const parentUnion = deref?.oneOf ?? deref?.anyOf\n if (!deref || !discriminator || (isDiscriminator(deref) && !parentUnion)) return true\n\n const childRef = `${SCHEMA_REF_PREFIX}${name}`\n const values = findDiscriminators({ mapping: discriminator.mapping, ref: childRef })\n if (values.length) {\n const { propertyName } = discriminator\n const propertyType = propertyTypeOf({ schema: deref, propertyName, refs }) ?? propertyTypeOf({ schema: { $ref: childRef }, propertyName, refs })\n discriminantValues.push({ propertyName, values: typedKeys({ keys: values, propertyType }) })\n }\n\n // Only a `oneOf`/`anyOf` parent is replaced by its discriminant; any other parent stays in the intersection.\n const replaced = parentUnion && (values.length > 0 || parentUnion.some((member) => isReference(member) && member.$ref === childRef))\n\n return !replaced\n })\n\n return { members, discriminantValues }\n}\n","import type { ast } from '@kubb/kit'\nimport type { SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\n\nconst ANNOTATIONS = new Set(['title', 'description', 'default', 'deprecated', 'readOnly', 'writeOnly', 'example', 'examples', 'xml', 'externalDocs'])\nconst UNION_KEYS = new Set([...ANNOTATIONS, 'type', 'nullable', 'oneOf', 'anyOf'])\nconst MEMBER_KEYS = new Set([...ANNOTATIONS, 'type', 'const'])\n\nfunction hasOnlyKeys(schema: unknown, keys: ReadonlySet<string>): schema is SchemaObject {\n return typeof schema === 'object' && schema !== null && !Array.isArray(schema) && Object.keys(schema).every((key) => keys.has(key) || key.startsWith('x-'))\n}\n\nfunction matchesType(type: SchemaObject['type'], value: string | number): boolean {\n return type === undefined || type === typeof value || (type === 'integer' && typeof value === 'number' && Number.isInteger(value))\n}\n\n/** Recognizes annotated const unions only when replacing them cannot discard validation constraints. */\nexport function convertAnnotatedEnum(context: ConvertContext): ast.SchemaNode | undefined {\n const { schema, document } = context\n if (!document.openapi?.startsWith('3.1.')) return undefined\n if (!hasOnlyKeys(schema, UNION_KEYS) || (schema.oneOf !== undefined && schema.anyOf !== undefined)) return undefined\n const members = schema.oneOf ?? schema.anyOf\n if (!members?.length) return undefined\n\n const names = new Set<string>()\n const values = new Set<string | number>()\n const namedEnumValues: NonNullable<ast.EnumSchemaNode['namedEnumValues']> = []\n let primitive: 'string' | 'number' | undefined\n for (const member of members) {\n if (!hasOnlyKeys(member, MEMBER_KEYS)) return undefined\n const value = member.const\n if (typeof value !== 'string' && (typeof value !== 'number' || !Number.isFinite(value))) return undefined\n if (typeof member.title !== 'string' || !member.title.trim() || names.has(member.title) || values.has(value)) return undefined\n if (!matchesType(schema.type, value) || !matchesType(member.type, value)) return undefined\n const valueType = typeof value === 'number' ? 'number' : 'string'\n if (primitive !== undefined && primitive !== valueType) return undefined\n primitive = valueType\n names.add(member.title)\n values.add(value)\n namedEnumValues.push({ name: member.title, value, primitive: valueType, description: member.description })\n }\n\n return createNode(context, { type: 'enum', primitive, namedEnumValues })\n}\n","import { ast, extractRefName, macroSimplifyUnion, mergeAdjacentObjectsLazy } from '@kubb/kit'\nimport { SCHEMA_REF_PREFIX } from '../../constants.ts'\nimport { isDiscriminator, isReference } from '../../oas.ts'\nimport type { Refs } from '../../refs.ts'\nimport type { ReferenceObject, SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport {\n createDiscriminantNode,\n removeInheritedDiscriminator,\n extractDiscriminatedAllOfMembers,\n narrowUnionMembers,\n propertyTypeOf,\n} from '../discriminator/preserve.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\nimport { extractExamples } from '../schemaShape.ts'\nimport { convertAnnotatedEnum } from './annotatedEnum.ts'\n\n/**\n * Collects property schemas from all `allOf` members and outer schema properties,\n * recursively resolving `$ref` pointers.\n */\nfunction collectSiblingProperties(\n allOfMembers: Array<SchemaObject | ReferenceObject>,\n refs: Refs,\n outerProperties?: Record<string, unknown>,\n): Record<string, unknown> {\n const properties: Record<string, unknown> = { ...outerProperties }\n const visited = new Set<string>()\n\n function collectFrom(item: SchemaObject | ReferenceObject | undefined): void {\n if (!item) return\n\n if (isReference(item)) {\n if (visited.has(item.$ref)) return\n visited.add(item.$ref)\n const resolved = refs.resolve<SchemaObject>(item.$ref, { report: false })\n if (resolved && !isReference(resolved)) {\n collectFrom(resolved)\n }\n return\n }\n\n if (item.properties) {\n Object.assign(properties, item.properties)\n }\n\n if (Array.isArray(item.allOf)) {\n for (const member of item.allOf) {\n collectFrom(member as SchemaObject | ReferenceObject)\n }\n }\n }\n\n for (const item of allOfMembers) {\n collectFrom(item)\n }\n\n return properties\n}\n\n/**\n * Enriches union members that declare `required` properties without declaring corresponding\n * property schemas, populating the missing property definitions from available sibling schemas\n * (or an empty schema falling back to the configured emptySchemaType).\n */\nfunction resolveUnionMembers(members: Array<unknown>, siblingProperties: Record<string, unknown>): Array<unknown> {\n return members.map((member) => {\n if (!member || typeof member !== 'object' || isReference(member)) {\n return member\n }\n\n const obj = member as SchemaObject\n if (!Array.isArray(obj.required) || obj.required.length === 0) {\n return member\n }\n\n const existingProps = (obj.properties ?? {}) as Record<string, unknown>\n const missingKeys = obj.required.filter((key) => !Object.hasOwn(existingProps, key))\n\n if (missingKeys.length === 0) {\n return member\n }\n\n const newProperties: Record<string, unknown> = { ...existingProps }\n for (const key of missingKeys) {\n const value = Object.hasOwn(siblingProperties, key) ? siblingProperties[key] : {}\n // defineProperty: a plain assignment of a `__proto__` key would hit the prototype setter.\n Object.defineProperty(newProperties, key, { value, enumerable: true, writable: true, configurable: true })\n }\n\n return {\n type: obj.type ?? 'object',\n ...obj,\n properties: newProperties,\n }\n })\n}\n\n/**\n * Enriches a schema object, and any `oneOf` or `anyOf` branches on it, with properties from sibling schemas.\n */\nfunction resolveUnionSchema(schema: SchemaObject, siblingProperties: Record<string, unknown>): SchemaObject {\n const resolvedSchema = (resolveUnionMembers([schema], siblingProperties)[0] as SchemaObject) ?? schema\n const next: SchemaObject = { ...resolvedSchema }\n if (schema.oneOf) {\n next.oneOf = resolveUnionMembers(schema.oneOf, siblingProperties) as typeof schema.oneOf\n }\n if (schema.anyOf) {\n next.anyOf = resolveUnionMembers(schema.anyOf, siblingProperties) as typeof schema.anyOf\n }\n return next\n}\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, document, parse, refs, renames }: ConvertContext): ast.SchemaNode {\n const refPath = schema.$ref\n const resolvedSchema = refPath ? refs.resolveNode(refPath, parse) : 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 // A circular ref still resolves, so only a `$ref` to a component the spec never declares is missing.\n if (refPath && document.components && !refs.resolve(refPath, { report: false })) {\n return createNode(ctx, { type: ast.schemaTypes.unknown })\n }\n\n // A target outside `components.schemas` is never emitted as its own file, so inline it. A circular\n // ref leaves `resolvedSchema` null and still becomes a ref node.\n if (refPath && !refPath.startsWith(SCHEMA_REF_PREFIX) && resolvedSchema) {\n return ast.factory.createSchema({\n ...resolvedSchema,\n title: schema.title ?? resolvedSchema.title,\n description: schema.description ?? resolvedSchema.description,\n deprecated: schema.deprecated ?? resolvedSchema.deprecated,\n readOnly: schema.readOnly ?? resolvedSchema.readOnly,\n writeOnly: schema.writeOnly ?? resolvedSchema.writeOnly,\n default: defaultValue ?? resolvedSchema.default,\n name: name ?? resolvedSchema.name,\n nullable: nullable ?? resolvedSchema.nullable,\n })\n }\n\n const targetName = renames?.get(schema.$ref!)\n\n return createNode(ctx, {\n type: ast.schemaTypes.ref,\n name: extractRefName(schema.$ref!),\n ref: schema.$ref,\n ...(targetName ? { targetName } : {}),\n schema: resolvedSchema,\n })\n}\n\n/** Converts `{ ...rest, not: X }` into `intersection[rest, not[X]]`; a bare `required` inside `not` borrows the outer `properties`. */\nexport function convertNot({ schema, name, nullable, defaultValue, parse }: ConvertContext): ast.SchemaNode {\n const { not, ...rest } = schema as SchemaObject & { not: SchemaObject }\n const [subschema] = resolveUnionMembers([not], (rest.properties ?? {}) as Record<string, unknown>) as [SchemaObject]\n const notNode = ast.factory.createSchema({ type: ast.schemaTypes.not, members: [parse({ schema: subschema })] })\n\n return createNode({ schema, name, nullable, defaultValue }, { type: ast.schemaTypes.intersection, members: [parse({ schema: rest, name }), notNode] })\n}\n\n/**\n * Keywords that describe a schema or conditionally constrain it, but add no structure.\n */\nconst annotationKeys = new Set(['description', 'title', 'example', 'examples', 'default', 'deprecated', 'readOnly', 'writeOnly', 'if', 'then', 'else'])\n\n/**\n * Moves `allOf` members that hold only annotations or `if`/`then`/`else` onto the parent, so they do\n * not become `unknown`. The parent's own values win, and the conditional keywords are not enforced.\n */\nfunction mergeAnnotations(schema: SchemaObject): SchemaObject {\n const members = schema.allOf as Array<SchemaObject | ReferenceObject>\n const isAnnotation = (member: SchemaObject | ReferenceObject) => !isReference(member) && Object.keys(member).every((key) => annotationKeys.has(key))\n const annotations = members.filter(isAnnotation)\n const rest = members.filter((member) => !isAnnotation(member))\n\n return annotations.length && rest.length ? { ...Object.assign({}, ...annotations), ...schema, allOf: rest } : schema\n}\n\n/**\n * Converts an `allOf` schema into a flattened node or an `IntersectionSchemaNode`.\n */\nexport function convertAllOf({ schema: original, name, nullable, defaultValue, parse, refs }: ConvertContext): ast.SchemaNode {\n const schema = mergeAnnotations(original)\n\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 })\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: removeInheritedDiscriminator({ members: schema.allOf as Array<SchemaObject | ReferenceObject>, refs }),\n name,\n refs,\n })\n const siblingProperties = collectSiblingProperties(schema.allOf as Array<SchemaObject | ReferenceObject>, refs, schema.properties)\n const resolvedAllOf = discriminatedAllOf.map((s) => (isReference(s) ? s : resolveUnionSchema(s as SchemaObject, siblingProperties)))\n const allOfMembers: Array<ast.SchemaNode> = resolvedAllOf.map((s) => parse({ schema: s as SchemaObject, name }))\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 }))\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 }))\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: ast.schemaTypes.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(context: ConvertContext): ast.SchemaNode {\n const annotatedEnum = convertAnnotatedEnum(context)\n if (annotatedEnum) return annotatedEnum\n const { schema, name, nullable, defaultValue, parse, refs } = context\n const ctx = { schema, name, nullable, defaultValue }\n const unionMembers = resolveUnionMembers([...(schema.oneOf ?? []), ...(schema.anyOf ?? [])], schema.properties ?? {})\n const strategy: 'one' | 'any' = schema.oneOf ? 'one' : 'any'\n const explicitDiscriminatorPropertyName = isDiscriminator(schema) ? schema.discriminator.propertyName : undefined\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 }) : undefined\n const missingRequired = (Array.isArray(schema.required) ? schema.required : []).filter((key) => !Object.hasOwn(schema.properties ?? {}, key))\n\n if (sharedPropertiesNode || discriminator || missingRequired.length) {\n const members = narrowUnionMembers({\n unionMembers,\n discriminator,\n sharedPropertiesNode,\n parentType: discriminator && propertyTypeOf({ schema, propertyName: discriminator.propertyName, refs }),\n parse,\n name,\n refs,\n })\n const unionNode = createNode(ctx, {\n type: ast.schemaTypes.union,\n strategy,\n members,\n discriminatorPropertyName: explicitDiscriminatorPropertyName ?? ast.inferDiscriminatorPropertyName(members),\n })\n\n const requiredProperties = missingRequired.map((name) =>\n ast.factory.createProperty({ name, required: true, schema: ast.factory.createSchema({ type: ast.schemaTypes.unknown }) }),\n )\n const siblings = sharedPropertiesNode ? [sharedPropertiesNode] : []\n if (requiredProperties.length) {\n siblings.push(ast.factory.createSchema({ type: ast.schemaTypes.object, properties: requiredProperties }))\n }\n\n if (!siblings.length) {\n return unionNode\n }\n\n return createNode(ctx, { type: ast.schemaTypes.intersection, members: [unionNode, ...siblings] })\n }\n\n const members = unionMembers.map((s) => parse({ schema: s as SchemaObject, name }))\n const unionNode = createNode(ctx, {\n type: ast.schemaTypes.union,\n strategy,\n members,\n discriminatorPropertyName: explicitDiscriminatorPropertyName ?? ast.inferDiscriminatorPropertyName(members),\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, 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: ast.schemaTypes.union,\n members: nonNullTypes.map((t) => {\n const raw = { ...schema, type: t }\n const memberSchema = raw as SchemaObject\n return parse({ schema: memberSchema, name })\n }),\n },\n )\n}\n","import { ast } from '@kubb/kit'\nimport { enumDescriptionKeys, enumExtensionKeys, formatMap, numericFormats } from '../../constants.ts'\nimport type { SchemaObject } from '../../types.ts'\nimport { createNode } from '../createNode.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\nimport { resolveDateTypeValue } 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\nfunction 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/** Shared by number, integer and bigint nodes; the exclusive bounds keep only the OAS 3.1 numeric form. */\nfunction getNumericConstraints(schema: SchemaObject): Pick<ast.NumberSchemaNode, 'min' | 'max' | 'exclusiveMinimum' | 'exclusiveMaximum' | 'multipleOf'> {\n return {\n min: schema.minimum,\n max: schema.maximum,\n exclusiveMinimum: typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined,\n exclusiveMaximum: typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : undefined,\n multipleOf: schema.multipleOf,\n }\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(context: ConvertContext): ast.SchemaNode {\n const { schema, name } = context\n const constValue = schema.const\n\n if (constValue === null) {\n return createNullNode(schema, name)\n }\n\n return createNode(context, {\n type: 'enum',\n primitive: getPrimitiveType(typeof constValue),\n enumValues: [constValue as string | number | boolean],\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, options, type } = context\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(context, {\n type: options.integerType === 'bigint' ? 'bigint' : 'integer',\n primitive: 'integer',\n ...getNumericConstraints(schema),\n })\n }\n\n if (schema.format === 'date-time' || schema.format === 'date' || schema.format === 'time') {\n const value = resolveDateTypeValue(options.dateType, schema.format)\n\n if (schema.format === 'date-time' && value !== 'date') {\n return createNode(context, { primitive: 'string', type: 'datetime', offset: value === 'stringOffset', local: value === 'stringLocal' })\n }\n return createNode(context, {\n primitive: 'string',\n type: schema.format === 'date-time' ? 'date' : schema.format,\n representation: value === 'date' ? 'date' : 'string',\n })\n }\n\n const specialType = formatMap[schema.format as keyof typeof formatMap]\n if (specialType === 'string') {\n // A numeric schema keeps its type, such as `type: integer, format: duration` in seconds.\n if (type === 'integer' || type === 'number') return convertNumeric(context, type)\n // Keeps `format` on the node, plus `minLength`, `maxLength` and `pattern`.\n return convertString(context)\n }\n\n const isNumeric = specialType === 'number' || specialType === 'integer'\n const specialPrimitive: ast.PrimitiveSchemaType = isNumeric ? specialType : 'string'\n const hasLength = specialType === 'url' || specialType === 'uuid' || specialType === 'email'\n\n return createNode(context, {\n primitive: specialPrimitive,\n type: specialType as ast.ScalarSchemaType,\n ...(hasLength ? { min: schema.minLength, max: schema.maxLength } : {}),\n ...(isNumeric ? getNumericConstraints(schema) : {}),\n })\n}\n\n/**\n * Converts an `enum` schema into an `EnumSchemaNode`.\n */\nexport function convertEnum({ schema, name, nullable, type, parse }: ConvertContext): ast.SchemaNode {\n if (type === 'array') {\n return parse({ schema: normalizeArrayEnum(schema), name })\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 primitive: 'number' | 'boolean' | 'string' = type === 'boolean' ? 'boolean' : type === 'number' || type === 'integer' ? 'number' : 'string'\n const uniqueValues = [...new Set(filteredValues)]\n\n const ctx = { schema, name, nullable: enumNullable as true | undefined, defaultValue: enumDefault }\n\n const extensionKey = enumExtensionKeys.find((key) => key in schema)\n const descriptionKey = enumDescriptionKeys.find((key) => key in schema)\n if (!extensionKey && !descriptionKey && primitive === 'string') {\n return createNode(ctx, { type: 'enum', primitive, enumValues: uniqueValues })\n }\n\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 seenNames = new Set<string>()\n\n return createNode(ctx, {\n type: 'enum',\n primitive,\n namedEnumValues: uniqueValues\n .map((value, index) => ({\n name: String(rawEnumNames?.[index] ?? value),\n value,\n primitive,\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/**\n * Converts a `type: 'string'` schema into a `StringSchemaNode`.\n */\nexport function convertString(context: ConvertContext): ast.SchemaNode {\n const { schema } = context\n\n return createNode(context, {\n type: 'string',\n primitive: 'string',\n min: schema.minLength,\n max: schema.maxLength,\n pattern: schema.pattern,\n })\n}\n\n/**\n * Converts a `type: 'number'` or `type: 'integer'` schema.\n */\nexport function convertNumeric(context: ConvertContext, type: 'number' | 'integer'): ast.SchemaNode {\n return createNode(context, {\n type,\n primitive: type,\n ...getNumericConstraints(context.schema),\n })\n}\n","import { ast, childName, enumPropName, macroDiscriminatorEnum, macroEnumName } from '@kubb/kit'\nimport { isDiscriminator, isNullable } from '../../oas.ts'\nimport { getMappingKeys, propertyTypeOf, typedKeys } from '../discriminator/preserve.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(mapSchema: unknown, { options, parse }: Pick<ConvertContext, 'options' | 'parse'>): ast.SchemaNode {\n if (mapSchema === false) return ast.factory.createSchema({ type: 'never' })\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 })\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, options, parse, refs }: ConvertContext): ast.SchemaNode {\n const requiredNames = Array.isArray(schema.required) ? new Set(schema.required) : undefined\n const properties: Array<ast.PropertyNode> = schema.properties\n ? Object.entries(schema.properties).map(([propName, propSchema]) => {\n const required = requiredNames ? requiredNames.has(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 })\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 || schemaNode.nullable || undefined,\n },\n required,\n })\n })\n : []\n\n const additionalProperties = schema.additionalProperties\n const additionalPropertiesNode = (() => {\n if (additionalProperties === true) return true\n if (additionalProperties) return resolveMapSchema(additionalProperties, { options, parse })\n return additionalProperties\n })()\n\n const rawPatternProperties = 'patternProperties' in schema ? schema.patternProperties : undefined\n\n const patternProperties = rawPatternProperties\n ? Object.fromEntries(Object.entries(rawPatternProperties).map(([pattern, patternSchema]) => [pattern, resolveMapSchema(patternSchema, { options, parse })]))\n : undefined\n const propertyNames = 'propertyNames' in schema && schema.propertyNames !== undefined ? resolveMapSchema(schema.propertyNames, { options, parse }) : 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 propertyNames,\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 = typedKeys({\n keys: getMappingKeys({ discriminator: schema.discriminator, refs }),\n propertyType: propertyTypeOf({ schema, propertyName: discPropName, refs }),\n })\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, options, parse }: ConvertContext): ast.SchemaNode {\n const tupleItems = (schema.prefixItems ?? []).map((item) => parse({ schema: item as SchemaObject }))\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 })\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, 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 })] : []\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/kit'\nimport { isBinary, isReference } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport type { Document, SchemaObject } from '../types.ts'\nimport { convertAllOf, convertMultiType, convertNot, convertRef, convertUnion } from './converters/composition.ts'\nimport { convertConst, convertEnum, convertFormat, convertNumeric, convertString, createNullNode } from './converters/scalar.ts'\nimport { convertArray, convertObject, convertTuple } from './converters/structural.ts'\nimport { createNode } from './createNode.ts'\nimport { isHandledFormat, resolveDateTypeValue } from './schemaShape.ts'\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 }) => ast.SchemaNode\n\n/**\n * Everything a converter receives: the per-schema derivations plus the parser instance's\n * recursion seam, document, `$ref` service and collision renames.\n */\nexport type ConvertContext = {\n schema: SchemaObject\n name: string | null | undefined\n nullable: true | undefined\n defaultValue: unknown\n /** First non-`null` entry of an OAS 3.1 multi-type array, or the plain `type`. */\n type: string | undefined\n options: ast.ParserOptions\n parse: ParseFn\n document: Document\n refs: Refs\n renames?: ReadonlyMap<string, string>\n}\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 */\ntype 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 (`not`, `$ref`, `allOf`,\n * `oneOf`/`anyOf`) take precedence over `const` (except a `$ref` with a sibling `const`, where the\n * `const` wins), which takes precedence over a genuine OAS 3.1 multi-type array (more than one\n * 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 }) => typeof schema.not === 'object' && schema.not !== null, convert: convertNot },\n { match: ({ schema }) => isReference(schema) && !('const' in schema && schema.const !== undefined), 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: (ctx) => createNode(ctx, { type: 'blob', primitive: 'string' }) },\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 }) =>\n type === 'object' || !!schema.properties || !!schema.additionalProperties || 'patternProperties' in schema || 'propertyNames' 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: (ctx) => createNode(ctx, { type: 'boolean', primitive: 'boolean' }) },\n { match: ({ type }) => type === 'null', convert: ({ schema, name, nullable }) => createNullNode(schema, name, nullable) },\n]\n","import type { ast } from '@kubb/kit'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { createNode } from './emit/createNode.ts'\nimport { type ConvertContext, schemaRules } from './emit/parseSchema.ts'\nimport { flattenSchema } from './emit/schemaShape.ts'\nimport { isNullable } from './oas.ts'\nimport type { Refs } from './refs.ts'\nimport type { Document, SchemaObject } from './types.ts'\n\n/**\n * Parser context holding the raw OpenAPI document and its `$ref` service.\n */\nexport type OasParserContext = {\n document: Document\n refs: Refs\n /**\n * Renames from `getSchemas`, keyed by the collision-renamed component or nested `$defs` pointer.\n * `convertRef` stamps `targetName` from it at ref creation, so refs to renamed schemas resolve\n * to the emitted name without a post-parse pass.\n */\n renames?: ReadonlyMap<string, string>\n options?: Partial<ast.ParserOptions>\n}\n\n/**\n * Creates the schema converter bound to one OpenAPI document: `parseSchema` dispatches each\n * schema through the ordered `schemaRules` table, with the parser options merged once.\n *\n * @internal\n */\nexport function createSchemaParser(ctx: OasParserContext) {\n const { document, refs, renames } = ctx\n const options: ast.ParserOptions = { ...DEFAULT_PARSER_OPTIONS, ...ctx.options }\n\n function parseSchema({ schema, name }: { schema: SchemaObject; name?: string | null }): ast.SchemaNode {\n const flattenedSchema = flattenSchema(schema)\n if (flattenedSchema !== schema) {\n return parseSchema({ schema: flattenedSchema, name })\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 options,\n parse: parseSchema,\n document,\n refs,\n renames,\n }\n\n for (const rule of schemaRules) {\n if (rule.match(context)) return rule.convert(context)\n }\n\n return createNode(context, { type: options.emptySchemaType as ast.ScalarSchemaType })\n }\n\n return parseSchema\n}\n","import { ast } from '@kubb/kit'\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 === ast.nodeKinds.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 { escapePointerToken } from '@internals/utils'\nimport type { Adapter } from '@kubb/core'\nimport * as yaml from 'yaml'\n\ntype Range = ReturnType<NonNullable<Adapter['locate']>>\n\n// Diagnostics of one run share a source, so its parsed document, or its JSON index, is kept for the next call.\nlet cached: { source: string; document: yaml.Document } | { source: string; json: ReturnType<typeof indexJson> } | undefined\n\nconst toRange = ([start, end]: yaml.Range): Range => ({ start, end })\n\nconst unescapeToken = (token: string) => token.replaceAll('~1', '/').replaceAll('~0', '~')\n\n/** Walks a JSON pointer through maps and sequences; the range is the last key or item it reached. */\nfunction findPointer(document: yaml.Document, pointer: string): Range {\n const tokens = pointer.replace(/^#/, '').split('/').slice(1).map(unescapeToken)\n return tokens.reduce<{ node: unknown; range: Range } | undefined>(\n (at, token) => {\n if (yaml.isMap(at?.node)) {\n const pair = at.node.items.find((item) => yaml.isScalar(item.key) && String(item.key.value) === token)\n return pair && yaml.isScalar(pair.key) && pair.key.range ? { node: pair.value, range: toRange(pair.key.range) } : undefined\n }\n if (yaml.isSeq(at?.node)) {\n const item = at.node.items[Number(token)]\n return yaml.isNode(item) && item.range ? { node: item, range: toRange(item.range) } : undefined\n }\n return undefined\n },\n { node: document.contents, range: undefined },\n )?.range\n}\n\n/** The first `$ref` whose value is `ref`. */\nfunction findRefUsage(document: yaml.Document, ref: string): Range {\n const found: Array<Range> = []\n yaml.visit(document, {\n Pair(_, { key, value }) {\n if (!yaml.isScalar(key) || key.value !== '$ref' || !yaml.isScalar(value) || value.value !== ref || !value.range) return\n found.push(toRange(value.range))\n return yaml.visit.BREAK\n },\n })\n return found[0]\n}\n\n/**\n * One pass over JSON text, so a located diagnostic in a large JSON spec skips `yaml.parseDocument`.\n * Holds the range of every key and array item by pointer, and the first usage of every `$ref`, as\n * `findPointer` and `findRefUsage` return them. Throws where the text breaks JSON syntax, such as a\n * comment, an unquoted key, or an unquoted `$ref` value. Other bare values, such as `object`, pass.\n */\nfunction indexJson(source: string) {\n const pointers = new Map<string, NonNullable<Range>>()\n const refs = new Map<string, NonNullable<Range>>()\n let at = source.indexOf('{')\n\n const fail = (): never => {\n throw new SyntaxError(`Unexpected character at ${at}`)\n }\n const skipSpace = () => {\n for (let code = source.charCodeAt(at); code === 32 || code === 9 || code === 10 || code === 13; code = source.charCodeAt(++at));\n }\n const readString = () => {\n if (source[at] !== '\"') fail()\n const start = at\n for (at++; source.charCodeAt(at) !== 34; at++) {\n if (at >= source.length) fail()\n if (source.charCodeAt(at) === 92) at++\n }\n const raw = source.slice(start + 1, at++)\n return { text: raw.includes('\\\\') ? (JSON.parse(source.slice(start, at)) as string) : raw, start, end: at }\n }\n const expect = (char: string) => {\n skipSpace()\n if (source[at++] !== char) fail()\n skipSpace()\n }\n // Walks the value at `at`; `pointer` is where it sits.\n const walk = (pointer: string): void => {\n const open = source[at]\n if (open === '\"') {\n readString()\n return\n }\n if (open !== '{' && open !== '[') {\n const start = at\n while (at < source.length && !/[\\s,\\]}]/.test(source[at]!)) at++\n if (at === start) fail()\n return\n }\n const close = open === '{' ? '}' : ']'\n at++\n for (let index = 0; ; index++) {\n skipSpace()\n if (source[at] === close) break\n if (index > 0) expect(',')\n if (open === '[') {\n const start = at\n const next = `${pointer}/${index}`\n walk(next)\n if (!pointers.has(next)) pointers.set(next, { start, end: at })\n continue\n }\n const key = readString()\n const next = `${pointer}/${escapePointerToken(key.text)}`\n // A duplicate key keeps its first range, like `findPointer`.\n if (!pointers.has(next)) pointers.set(next, { start: key.start, end: key.end })\n expect(':')\n if (key.text !== '$ref' || source[at] === '{' || source[at] === '[') {\n walk(next)\n continue\n }\n // YAML reads an unquoted `$ref` value as a string, so only the YAML parser finds that usage.\n const value = readString()\n if (!refs.has(value.text)) refs.set(value.text, { start: value.start, end: value.end })\n }\n at++\n }\n walk('#')\n return { pointers, refs }\n}\n\n/** Indexes plain JSON text; anything else goes to the YAML parser. */\nfunction parse(source: string): NonNullable<typeof cached> {\n if (/^[ \\t\\n\\r]*\\{/.test(source)) {\n try {\n return { source, json: indexJson(source) }\n } catch {\n // Not plain JSON, such as YAML flow style with comments.\n }\n }\n return { source, document: yaml.parseDocument(source) }\n}\n\n/**\n * Maps OpenAPI JSON pointers and unresolved references to ranges in YAML or JSON source.\n */\nexport const locate: NonNullable<Adapter['locate']> = (source, location) => {\n if (!('pointer' in location)) return undefined\n // An equal but distinct string costs a full comparison on every check. Keeping the caller's\n // string turns the next checks into identity hits.\n cached = cached?.source === source ? { ...cached, source } : parse(source)\n const ref = 'ref' in location ? location.ref : undefined\n if ('json' in cached) {\n const { pointers, refs } = cached.json\n return pointers.get(location.pointer) ?? (ref ? refs.get(ref) : undefined)\n }\n const { document } = cached\n return findPointer(document, location.pointer) ?? (ref ? findRefUsage(document, ref) : undefined)\n}\n","import { defineExtension } from '@kubb/core'\nimport { ast, Diagnostics } from '@kubb/kit'\nimport type { AdapterSource } from '@kubb/kit'\nimport { compatibility } from '../kubb-extension.json'\nimport { version } from '../package.json'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { buildDiscriminatorChildMap, patchDiscriminatorNode } from './emit/discriminator/propagate.ts'\nimport type { DiscriminatorTarget } from './emit/discriminator/propagate.ts'\nimport { assertDocument, parseFromConfig, validateDocument, validateDocumentInWorker } from './load/normalize.ts'\nimport { getSchemas } from './model/components.ts'\nimport { resolveBaseUrl, resolveServerUrl } from './model/server.ts'\nimport { pickExtensions } from './oas.ts'\nimport { getOperations, parseOperation } 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 { locate } from './sourceLocator.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 = defineExtension<AdapterOas>({\n kind: 'adapter',\n meta: { name: adapterOasName, version, compatibility, issues: 'https://github.com/kubb-labs/kubb/issues' },\n setup: ({\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 }) => ({ validate, contentType, server, discriminator, enums, dateType, integerType, unknownType, emptySchemaType, enumSuffix }),\n build({ validate, contentType, server, discriminator, enums, ...parserOptions }) {\n let parsedDocument: Document | null = null\n let sources: Array<string> = []\n const pendingValidations: Array<Promise<void>> = []\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: Promise<ast.InputNode>; sources: Array<string> }>()\n\n /**\n * Parses every schema and operation once, resolving ref aliases and discriminator children from that same pass.\n */\n function parseInput({\n document,\n refs,\n schemas,\n pointers,\n parseSchema,\n }: {\n document: Document\n refs: ReturnType<typeof createRefs>\n schemas: Record<string, SchemaObject>\n pointers: Map<string, string>\n parseSchema: ReturnType<typeof createSchemaParser>\n }): ast.InputNode {\n const parsedByName = new Map<string, ast.SchemaNode>()\n const refAliasMap = new Map<string, ast.RefSchemaNode>()\n const enumNames = new Set<string>()\n const discriminatorParentNodes: Array<ast.SchemaNode> = []\n\n for (const [name, schema] of Object.entries(schemas)) {\n const node = { ...parseSchema({ schema, name }), pointer: pointers.get(name) }\n parsedByName.set(name, node)\n scanSchema(node)\n if (node.type === 'ref' && node.name) {\n refAliasMap.set(name, node)\n }\n if (ast.narrowSchema(node, 'enum') && node.name) {\n enumNames.add(node.name)\n }\n if (discriminator === 'propagate' && (schema.oneOf ?? schema.anyOf) && schema.discriminator?.propertyName) {\n discriminatorParentNodes.push(node)\n }\n }\n\n const circularNames = ast.findCircularSchemas([...parsedByName.values()])\n const discriminatorChildMap: Map<string, DiscriminatorTarget> | null =\n discriminatorParentNodes.length > 0 ? buildDiscriminatorChildMap(discriminatorParentNodes) : null\n\n const operationNodes = getOperations(document, refs).map((operation) =>\n parseOperation({ operation, refs, contentType, options: parserOptions, parseSchema }),\n )\n\n const promotedEnums = enums === 'root' ? collectInlineEnums([...parsedByName.values(), ...operationNodes], new Set(Object.keys(schemas))) : null\n if (promotedEnums) {\n for (const name of promotedEnums.keys()) enumNames.add(name)\n }\n\n // A collapsed single-member `allOf` is named after the wrapper, so the target comes from `ref`.\n const aliasTargetOf = (name: string) => {\n const node = refAliasMap.get(name)\n return node?.ref ? ast.refName(node.ref) : node?.name\n }\n\n // A chain of pure aliases that leads back to `name` has no target to print, so it becomes `unknown`.\n function isAliasCycle(name: string): boolean {\n const seen = new Set([name])\n for (let next = aliasTargetOf(name); next; next = aliasTargetOf(next)) {\n if (next === name) return true\n if (seen.has(next)) return false\n seen.add(next)\n }\n return false\n }\n\n function createCycleNode(name: string, pointer: string | undefined): ast.SchemaNode {\n Diagnostics.report({\n code: Diagnostics.code.aliasCycle,\n severity: 'warning',\n message: `${name} only refers to other schemas that lead back to it, so it is resolved to unknown.`,\n help: 'Give one of the schemas in the loop a real definition, or remove the `$ref` that closes it.',\n location: { kind: 'schema', pointer: pointer ?? `#/components/schemas/${name}` },\n })\n\n return ast.factory.createSchema({ type: 'unknown', name, pointer })\n }\n\n const schemaNodes: Array<ast.SchemaNode> = promotedEnums ? [...promotedEnums.values()] : []\n for (const name of Object.keys(schemas)) {\n const aliasTarget = refAliasMap.get(name)?.name\n const aliased = aliasTarget ? parsedByName.get(aliasTarget) : undefined\n const parsed = parsedByName.get(name)!\n const child = discriminatorChildMap?.get(name)\n const base = child ? patchDiscriminatorNode(parsed, child) : parsed\n const resolved = aliased ? { ...aliased, name, pointer: parsed.pointer } : base\n const node = isAliasCycle(name) ? createCycleNode(name, parsed.pointer) : resolved\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 servers: (document.servers ?? [])\n .filter((entry) => entry.url)\n .map(({ url, description, variables }) => {\n const declared = variables && Object.keys(variables).length > 0 ? { variables } : {}\n try {\n return { url: resolveServerUrl({ url, variables }), description, ...declared }\n } catch {\n return { url, description, ...declared }\n }\n }),\n securitySchemes: Object.entries(document.components?.securitySchemes ?? {}).flatMap(([name, value]) => {\n const scheme = refs.deref<Record<string, string>>(value)\n return scheme?.type\n ? [\n {\n name,\n type: scheme.type,\n description: scheme.description,\n scheme: scheme.scheme,\n bearerFormat: scheme.bearerFormat,\n in: scheme.in,\n parameterName: scheme.name,\n },\n ]\n : []\n }),\n circularNames,\n enumNames,\n extensions: pickExtensions(document),\n },\n })\n }\n\n return {\n get document() {\n return parsedDocument\n },\n get sources() {\n return sources\n },\n locate,\n async validate(input, options) {\n const document = await parseFromConfig({ type: 'path', path: input })\n assertDocument(document)\n await validateDocument(document, options)\n },\n async settle() {\n await Promise.all(pendingValidations.splice(0))\n },\n async parse(source, { signal } = {}) {\n signal?.throwIfAborted()\n const cached = inputCache.get(source)\n if (cached) {\n sources = cached.sources\n return cached.promise\n }\n\n const read: Array<string> = []\n sources = read\n const promise = (async () => {\n const document = await parseFromConfig(source, read)\n signal?.throwIfAborted()\n assertDocument(document)\n if (validate) pendingValidations.push(validateDocumentInWorker(document))\n parsedDocument = document\n\n const refs = createRefs(document)\n const { schemas, renames, pointers } = getSchemas(document, { contentType }, refs)\n const parseSchema = createSchemaParser({ document, refs, renames, options: parserOptions })\n\n return parseInput({ document, refs, schemas, pointers, parseSchema })\n })()\n inputCache.set(source, { promise, sources: read })\n return promise.catch((error: unknown) => {\n // A canceled parse must not poison the cache: the next call with the same source needs a fresh attempt.\n if (signal?.aborted) inputCache.delete(source)\n throw error\n })\n },\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AEKA,MAAa,yBAAyB;CACpC,UAAU;CACV,aAAa;CACb,aAAa;CACb,iBAAiB;CACjB,YAAY;AACd;;;;;;;;;;;AAYA,MAAa,oBAAoB;;;;;;AAOjC,MAAa,oCAAyC,IAAI,IAAI;CAAC;CAAO;CAAO;CAAQ;CAAU;CAAW;CAAQ;CAAS;CAAS;AAAO,CAAC;;;;;;;AAQ5I,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;;;;;;;;;;;;;AAc1G,MAAa,YAAY;CACvB,MAAM;CACN,OAAO;CACP,aAAa;CACb,KAAK;CACL,iBAAiB;CACjB,KAAK;CACL,iBAAiB;CACjB,KAAK;CACL,MAAM;CACN,MAAM;CACN,UAAU;CACV,gBAAgB;CAChB,QAAQ;CACR,MAAM;CACN,WAAW;CACX,KAAK;CACL,MAAM;CACN,MAAM;CACN,UAAU;CAGV,OAAO;CACP,OAAO;CACP,QAAQ;AACV;;;;AAKA,MAAa,oBAAoB,CAAC,eAAe,iBAAiB;;;;AAKlE,MAAa,sBAAsB,CAAC,sBAAsB,qBAAqB;;;;;;;;;AC1F/E,SAAgB,2BAA2B,SAAkE;CAC3G,MAAM,2BAAW,IAAI,IA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