@kubb/adapter-oas 5.29.4 → 5.29.5

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","load","CORE_SCHEMA","EVENT_ID","SCALAR_STYLE","COLLECTION_STYLE","parseEvents","Diagnostics","parseEvents","constructFromEvents","CORE_SCHEMA","fileURLToPath","resolve","dirname","normalize","Diagnostics","bundle","join","upgrade","pascalCase","Diagnostics","ast","ast","enumPrimitive","macroDiscriminatorEnum","ast","mergeAdjacentObjectsLazy","macroDedupeUnion","Diagnostics","ast","ast","ast","macroEnumName","pascalCase","pascalCase","Diagnostics","ast","Url","ast","ast","macroEnumName","childName","enumPropName","macroDiscriminatorEnum","ast","ast","ast","Diagnostics","defineExtension"],"sources":["../kubb-extension.json","../package.json","../src/constants.ts","../src/emit/discriminator/propagate.ts","../../../internals/utils/src/promise.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/schemaIds.ts","../src/sourceLocator.ts","../src/load/source.ts","../src/load/normalize.ts","../src/model/components.ts","../src/model/security.ts","../src/model/server.ts","../src/model/tag.ts","../src/emit/schemaShape.ts","../src/emit/createNode.ts","../src/emit/discriminator/preserve.ts","../src/emit/converters/annotatedEnum.ts","../src/emit/converters/composition.ts","../src/schemaDiagnostics.ts","../src/model/mediaType.ts","../src/model/content.ts","../src/model/parameters.ts","../src/operation.ts","../src/emit/converters/scalar.ts","../src/emit/converters/structural.ts","../src/emit/parseSchema.ts","../src/schemaParser.ts","../src/promoteEnums.ts","../src/adapter.ts"],"sourcesContent":["","","import type { ast } from '@kubb/kit'\nimport type { ParserOptions } from './parserOptions.ts'\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 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 * Keys whose value maps names the user chose to entries: `properties`-like schema maps, schema definitions,\n * and the OpenAPI component and path-level maps. An entry name here is never a keyword, so `x-rate-limit`\n * under `headers` is a real header, not a vendor extension, and a property named `default` holds a schema.\n */\nexport const namedEntryKeys: ReadonlySet<string> = new Set([\n 'properties',\n 'patternProperties',\n 'dependentSchemas',\n '$defs',\n 'definitions',\n 'schemas',\n 'headers',\n 'responses',\n 'parameters',\n 'requestBodies',\n 'examples',\n 'links',\n 'callbacks',\n 'securitySchemes',\n 'securityDefinitions',\n 'pathItems',\n])\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: 'string',\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 * The `formatMap` entry for `format`. Reads own keys only, so `constructor` or `toString` never match.\n */\nexport function getFormatType(format: string): (typeof formatMap)[keyof typeof formatMap] | undefined {\n const formats: Record<string, (typeof formatMap)[keyof typeof formatMap]> = formatMap\n return Object.hasOwn(formats, format) ? formats[format] : undefined\n}\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\ntype ChildDiscriminant = { name: string; enumValues: DiscriminatorTarget['enumValues'] }\n\n// A union, or an intersection that wraps one, as for a union with shared properties.\nfunction findUnion(schema: ast.SchemaNode): ast.SchemaNodeByType['union'] | null | undefined {\n return (\n ast.schema.narrow(schema, 'union') ??\n ast.schema\n .narrow(schema, 'intersection')\n ?.members?.map((member) => ast.schema.narrow(member, 'union'))\n .find((union) => union)\n )\n}\n\nfunction pinnedValues({ objNode, propertyName }: { objNode: ast.SchemaNodeByType['object']; propertyName: string }): DiscriminatorTarget['enumValues'] {\n const prop = objNode.properties.find((p) => p.name === propertyName)\n const enumNode = prop ? ast.schema.narrow(prop.schema, 'enum') : null\n return enumNode?.enumValues?.filter((v): v is string | number | boolean => v !== null) ?? []\n}\n\nfunction memberDiscriminant({ member, propertyName }: { member: ast.SchemaNode; propertyName: string }): ChildDiscriminant | null {\n const members = ast.schema.narrow(member, 'intersection')?.members ?? []\n const refNode = members.map((m) => ast.schema.narrow(m, 'ref')).find(Boolean)\n const objNode = members.map((m) => ast.schema.narrow(m, 'object')).find(Boolean)\n if (!refNode?.name || !objNode) return null\n\n const enumValues = pinnedValues({ objNode, propertyName })\n // A child renamed by a name collision is emitted, and looked up, under its unique name.\n return enumValues.length ? { name: refNode.targetName ?? refNode.name, enumValues } : null\n}\n\n/**\n * Maps each child schema's emitted 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 const unionNode = findUnion(schema)\n if (!unionNode?.discriminatorPropertyName || !unionNode.members) continue\n const propertyName = unionNode.discriminatorPropertyName\n\n for (const member of unionNode.members) {\n const child = memberDiscriminant({ member, propertyName })\n if (!child) continue\n const existing = childMap.get(child.name)\n const enumValues = [...new Set([...(existing?.enumValues ?? []), ...child.enumValues])]\n childMap.set(child.name, { propertyName: existing?.propertyName ?? propertyName, 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.schema.narrow(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.schema.narrow(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.schema.narrow(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","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\nexport type Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Returns the value cached under `key` in `store`, computing and storing it on the first call.\n * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive\n * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.\n *\n * @example\n * `const refs = memo(refCache, node, () => collectRefs(node))`\n */\nexport function memo<TKey, TValue>(store: Store<TKey, TValue>, key: TKey, compute: () => TValue): TValue {\n const cached = store.get(key)\n if (cached !== undefined || store.has(key)) return cached as TValue\n const value = compute()\n store.set(key, value)\n return value\n}\n\nclass BoundedStore<TKey, TValue> implements Store<TKey, TValue> {\n readonly #entry = new Map<TKey, TValue>()\n readonly #max: number\n\n constructor(max: number) {\n this.#max = max\n }\n\n has(key: TKey): boolean {\n return this.#entry.has(key)\n }\n\n get(key: TKey): TValue | undefined {\n return this.#entry.get(key)\n }\n\n set(key: TKey, value: TValue): void {\n if (this.#entry.size >= this.#max) this.#entry.clear()\n this.#entry.set(key, value)\n }\n}\n\nclass LastEntryStore<TKey, TValue> extends BoundedStore<TKey, TValue> {\n constructor() {\n super(1)\n }\n\n // A key equal to the stored one but a different object, such as a copy of a string, replaces the\n // stored key, so the next lookup is an identity hit instead of a full comparison.\n #touch(key: TKey): boolean {\n if (!super.has(key)) return false\n this.set(key, super.get(key) as TValue)\n return true\n }\n\n override has(key: TKey): boolean {\n return this.#touch(key)\n }\n\n override get(key: TKey): TValue | undefined {\n return this.#touch(key) ? super.get(key) : undefined\n }\n}\n\n/**\n * Creates a store for `memo`. With no options it is a `Map`. Each option changes one thing:\n *\n * - `weak` holds the keys weakly, in a `WeakMap`, so an entry goes away with its key.\n * - `max` bounds the store: it empties itself before the entry that would pass `max`, which keeps a\n * cache in a long-running process from growing without end. `max: 1` keeps only the last entry.\n *\n * @example\n * `const patterns = memo.create<string, RegExp>()`\n *\n * @example Freed with its key\n * `const refs = memo.create<SchemaNode, Array<string>>({ weak: true })`\n *\n * @example Bounded\n * `const names = memo.create<string, string>({ max: 100_000 })`\n *\n * @example Many values per key\n * ```ts\n * const filesByPlugin = memo.create<string, Array<string>>()\n * memo(filesByPlugin, 'plugin-ts', () => []).push('models.ts')\n * ```\n */\nfunction createStore<TKey, TValue>(options?: { weak?: false; max?: undefined }): Map<TKey, TValue>\nfunction createStore<TKey extends WeakKey, TValue>(options: { weak: true; max?: undefined }): WeakMap<TKey, TValue>\nfunction createStore<TKey, TValue>(options: { max: number; weak?: false }): Store<TKey, TValue>\nfunction createStore<TKey, TValue>({ weak, max }: { weak?: boolean; max?: number } = {}): Store<TKey, TValue> {\n if (weak) return new WeakMap<WeakKey, TValue>() as Store<TKey, TValue>\n if (max === undefined) return new Map<TKey, TValue>()\n if (max !== 1) return new BoundedStore<TKey, TValue>(max)\n return new LastEntryStore<TKey, TValue>()\n}\n\nmemo.create = createStore\n\nexport type InParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain. The first\n * rejection rejects the call, and the other workers start no new item after it.\n *\n * @throws {RangeError} When `limit` is not a positive whole number, which would run no item at all.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: InParallelOptions<TItem>): Promise<void> {\n if (!Number.isInteger(limit) || limit < 1) throw new RangeError(`inParallel needs a limit of 1 or more, got ${limit}`)\n const queue = items.entries()\n let failed = false\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) {\n if (failed) return\n await run(item, index).catch((error: unknown) => {\n failed = true\n throw error\n })\n }\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\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/**\n * Builds an error that `Diagnostics.isError` from `@kubb/core` reads as a `Diagnostics.Error` with\n * `code`, without importing `@kubb/core` at run time. Use it in packages that only take core as a\n * type or peer dependency, so reporters show the code and `help` instead of `KUBB_UNKNOWN`.\n *\n * @example\n * ```ts\n * throw createDiagnosticError({ code: 'KUBB_MODULE_NOT_FOUND', message: 'Install typescript', cause })\n * ```\n */\nexport function createDiagnosticError({ code, message, help, cause }: { code: `KUBB_${string}`; message: string; help?: string; cause?: Error }): Error {\n const error = new Error(message, { cause })\n error.name = 'DiagnosticError'\n return Object.assign(error, { diagnostic: { code, severity: 'error' as const, message, ...(help ? { help } : {}), ...(cause ? { cause } : {}) } })\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\n/**\n * Unescapes one JSON pointer token per RFC 6901 (`~1` → `/`, then `~0` → `~`).\n */\nexport function unescapePointerToken(token: string): string {\n return token.replaceAll('~1', '/').replaceAll('~0', '~')\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 { existsSync, readFile, readFileSync, writeFile } from 'node:fs'\nimport { access, glob as globNode, lstat, mkdir, realpath } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } 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 // The callback API skips the `FileHandle` every `fs/promises` call opens.\n return new Promise((resolvePromise, reject) => readFile(path, { encoding: 'utf8' }, (error, data) => (error ? reject(error) : resolvePromise(data))))\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string, or `null` when it does not exist or cannot be read.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFileSync` otherwise.\n *\n * @example\n * ```ts\n * const stored = await readIfExists('./src/gen/Pet.ts') // null on a first run\n * ```\n */\nexport async function readIfExists(path: string): Promise<string | null> {\n if (runtime.isBun) {\n return Bun.file(path)\n .text()\n .catch(() => null)\n }\n // A small read is faster on the main thread than a thread-pool round trip, and `existsSync`\n // answers a missing file without building an error.\n if (!existsSync(path)) return null\n try {\n return readFileSync(path, 'utf8')\n } catch (_error) {\n return null\n }\n}\n\nexport type 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 const stored = options.stored === undefined ? await readIfExists(resolved) : options.stored\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 new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\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 * 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 * It ignores symlinks, so check a path a caller supplied with {@link isRealPathInside}.\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 // A child named `..cache` stays inside; only a `..` segment leaves.\n return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)\n}\n\n// A missing path resolves through its nearest existing parent. `undefined` for a dangling symlink or another error.\nasync function realPath(target: string): Promise<string | undefined> {\n const missing: Array<string> = []\n for (let current = resolve(target); ; current = dirname(current)) {\n try {\n return join(await realpath(current), ...missing)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return undefined\n // `realpath` also reports ENOENT for a symlink whose target is gone, and that link could later point anywhere.\n const isDanglingLink = await lstat(current).then(\n (stats) => stats.isSymbolicLink(),\n () => false,\n )\n if (isDanglingLink) return undefined\n if (dirname(current) === current) return undefined\n missing.unshift(basename(current))\n }\n }\n}\n\n/**\n * Like {@link isPathInside}, after resolving symlinks. Fails closed when a path cannot be resolved.\n */\nexport async function isRealPathInside({ target, base }: { target: string; base: string }): Promise<boolean> {\n const [real, realBase] = await Promise.all([realPath(target), realPath(base)])\n return real !== undefined && realBase !== undefined && isPathInside(real, realBase)\n}\n\n/**\n * Whether `storage` writes to disk, which Kubb knows only for a storage named `'fs'`.\n */\nexport function writesToDisk(storage: { name: string }): boolean {\n return storage.name === 'fs'\n}\n","import type { ast } from '@kubb/kit'\nimport type { DiscriminatorObject, Document, ReferenceObject, SchemaObject } from './types.ts'\n\nconst legacyDocuments = new WeakSet<Document>()\n\n/**\n * Marks a document upgraded from Swagger 2.0 or OpenAPI 3.0, so its enums keep the loose `nullable` reading.\n */\nexport function markLegacyDocument(document: Document): void {\n legacyDocuments.add(document)\n}\n\n/**\n * Returns `true` for a document upgraded from Swagger 2.0 or OpenAPI 3.0.\n */\nexport function isLegacyDocument(document: Document | undefined): boolean {\n return !!document && legacyDocuments.has(document)\n}\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 * A sibling `enum` without `null` makes the schema non-nullable, except in documents upgraded from 3.0.\n */\nexport function isNullable(schema?: SchemaObject & { 'x-nullable'?: boolean }, document?: Document): boolean {\n const explicitNullable = schema?.nullable ?? schema?.['x-nullable']\n if (explicitNullable === true) return true\n\n const schemaType = schema?.type\n const typeAllowsNull = schemaType === 'null' || (Array.isArray(schemaType) && schemaType.includes('null'))\n if (typeAllowsNull && Array.isArray(schema?.enum) && !schema.enum.includes(null)) return isLegacyDocument(document)\n\n return typeAllowsNull\n}\n\n/**\n * Returns `true` for an OpenAPI 3.2 or later document. Swagger 2.0 and OpenAPI 3.0 documents are\n * upgraded to 3.1 before parsing, so `openapi` is always set here.\n */\nexport function isOpenApi32(document: Document): boolean {\n const [major = 0, minor = 0] = String(document.openapi).split('.').map(Number)\n return major > 3 || (major === 3 && minor >= 2)\n}\n\nexport function pickStrings<TKey extends string>(source: unknown, keys: ReadonlyArray<TKey>): Partial<Record<TKey, string>> | undefined {\n if (!source || typeof source !== 'object') return undefined\n const entries = keys.flatMap((key) => {\n const value = (source as Record<string, unknown>)[key]\n return typeof value === 'string' ? [[key, value] as const] : []\n })\n return entries.length ? (Object.fromEntries(entries) as Partial<Record<TKey, string>>) : undefined\n}\n\nexport function getExternalDocs(source: unknown): ast.ExternalDocs | undefined {\n const docs = pickStrings(source, ['url', 'description'])\n return docs?.url ? { url: docs.url, ...(docs.description !== undefined && { description: docs.description }) } : undefined\n}\n\n/**\n * Returns the `x-*` keys of `source` as-is, or `undefined` when there are none.\n */\nexport function pickExtensions(source: object | null | undefined): Record<string, unknown> | undefined {\n if (!source) return 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 that names a\n * `propertyName`, excluding the Swagger 2 string form and a 3.2 discriminator that only sets `defaultMapping`.\n */\nexport function isDiscriminator(obj?: unknown): obj is SchemaObject & { discriminator: DiscriminatorObject } {\n const discriminator = (obj as Record<string, unknown> | undefined)?.['discriminator']\n return !!discriminator && typeof discriminator === 'object' && typeof (discriminator as DiscriminatorObject).propertyName === '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 * Keywords that only annotate a schema. A schema with nothing else does not constrain the value.\n */\nconst annotationKeywords = new Set(['title', 'description', 'default', 'example', 'examples', 'deprecated', 'readOnly', 'writeOnly', 'externalDocs'])\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. Annotations such as `description` survive the upgrade and are kept.\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).some((key) => !annotationKeywords.has(key) && !key.startsWith('x-'))) return undefined\n\n return { ...(schema as SchemaObject | undefined), 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 const lower = mimeType.toLowerCase()\n return jsonMimeFragments.some((fragment) => lower.includes(fragment))\n}\n","import { memo, unescapePointerToken } from '@internals/utils'\nimport { 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 *\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 class Refs {\n readonly #document: Document\n readonly #pointerCache = new Map<string, unknown>()\n readonly #resolvedNodeCache = memo.create<string, ast.SchemaNode | null>()\n readonly #resolvingRefs = new Set<string>()\n\n constructor(document: Document) {\n this.#document = document\n }\n\n // `found` is true for a falsy target too, such as a boolean `false` schema.\n #walkPointer<T>($ref: string): { applicable: boolean; found: boolean; value: T | null } {\n const trimmed = $ref.trim()\n if (trimmed === '' || !trimmed.startsWith('#')) {\n return { applicable: false, found: false, value: null }\n }\n const pointer = trimmed.substring(1)\n\n if (this.#pointerCache.has(pointer)) {\n return { applicable: true, found: true, value: this.#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 let current: unknown\n try {\n current = pointer\n .split('/')\n .filter(Boolean)\n .map((token) => unescapePointerToken(globalThis.decodeURIComponent(token)))\n .reduce(\n (obj: unknown, key: string) => (obj != null && Object.hasOwn(obj, key) ? (obj as Record<string, unknown>)[key] : undefined),\n this.#document as unknown,\n )\n } catch {\n // A malformed `%` escape cannot name a node, so it reports as an unresolved ref.\n current = undefined\n }\n\n if (current === undefined) {\n return { applicable: true, found: false, value: null }\n }\n this.#pointerCache.set(pointer, current)\n\n return { applicable: true, found: true, value: current as T }\n }\n\n /**\n * Resolves a local `#/...` JSON pointer. Returns `null` for an empty, non-local or missing ref.\n * A target that exists is returned as is, even when it is falsy, such as a boolean `false` schema.\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 resolve<T = unknown>(refPath: string, options?: { report?: boolean }): T | null {\n const { applicable, found, value } = this.#walkPointer<T>(refPath)\n if (!applicable || found || 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). An error from `parse` is thrown, so a bug\n * in a converter is not mistaken for a missing ref.\n */\n resolveNode(refPath: string, parse: ParseFn): ast.SchemaNode | null {\n if (this.#resolvingRefs.has(refPath)) return null\n\n return memo(this.#resolvedNodeCache, refPath, () => {\n let referenced: SchemaObject | null\n try {\n referenced = this.resolve<SchemaObject>(refPath)\n } catch (error) {\n // A missing ref outside a build is `null`; any other error is a real failure.\n if (Diagnostics.isError(error) && error.diagnostic.code === Diagnostics.code.refNotFound) return null\n throw error\n }\n if (referenced === null) return null\n this.#resolvingRefs.add(refPath)\n try {\n return parse({ schema: referenced })\n } finally {\n this.#resolvingRefs.delete(refPath)\n }\n })\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 deref<T = unknown>(value: unknown): T | null {\n if (!isReference(value)) {\n return value ? (value as T) : null\n }\n\n const resolved = this.resolve<T>(value.$ref)\n return resolved && !isReference(resolved) ? resolved : null\n }\n\n /**\n * Resolves a `$ref` object but keeps the `$ref` field on the result; other values pass through.\n */\n derefKeepingRef<T = unknown>(value?: T): T {\n if (isReference(value)) {\n return { ...value, ...this.resolve(value.$ref), $ref: value.$ref }\n }\n\n return value as T\n }\n}\n\n/**\n * Creates the `$ref` resolution service for one document. One pointer walk backs every method.\n */\nexport function createRefs(document: Document): Refs {\n return new Refs(document)\n}\n","import { escapePointerToken, memo } from '@internals/utils'\nimport { namedEntryKeys } from '../constants.ts'\n\nconst DATA_KEYS = new Set(['example', 'examples', 'const', 'enum', 'default'])\nconst TARGET_KEYS = ['$id', '$anchor', '$dynamicAnchor'] as const\n\n// A named map's keys are entry names, so an `x-` or `default` key there is a real entry.\nfunction isNamedMap({ node, keyword }: { node: object; keyword: string | undefined }): boolean {\n return keyword !== undefined && !Array.isArray(node) && namedEntryKeys.has(keyword)\n}\n\nfunction childKeyword({ node, key, named }: { node: object; key: string; named: boolean }): string | undefined {\n return named || Array.isArray(node) ? undefined : key\n}\n\nfunction walk(node: unknown, pointer: string, visit: (node: Record<string, unknown>, pointer: string) => void, keyword?: string): void {\n if (!node || typeof node !== 'object') return\n if (!Array.isArray(node)) visit(node as Record<string, unknown>, pointer)\n const named = isNamedMap({ node, keyword })\n for (const [key, value] of Object.entries(node)) {\n if (!named && isDataOrExtension(key)) continue\n walk(value, `${pointer}/${escapePointerToken(key)}`, visit, childKeyword({ node, key, named }))\n }\n}\n\nexport type DocumentScan = {\n /** A `$ref` points outside the document. */\n externalRef: boolean\n /** An `$id`, `$anchor` or `$dynamicAnchor` sits where {@link resolveSchemaIds} reads it. */\n schemaIds: boolean\n /** A `$ref` points into `#/paths/`. */\n pathRefs: boolean\n}\n\nfunction isDataOrExtension(key: string): boolean {\n return DATA_KEYS.has(key) || key.startsWith('x-')\n}\n\nfunction scanNode({ scan, node, readsIds }: { scan: DocumentScan; node: object; readsIds: boolean }): void {\n const record = node as Record<string, unknown>\n const ref = record['$ref']\n if (typeof ref === 'string' && !ref.startsWith('#')) scan.externalRef = true\n if (typeof ref === 'string' && ref.startsWith('#/paths/')) scan.pathRefs = true\n if (readsIds && !Array.isArray(node) && TARGET_KEYS.some((key) => typeof record[key] === 'string')) scan.schemaIds = true\n}\n\n/** Answers, in one walk and without building JSON pointers, what the loading steps after it need to know. */\nexport function scanDocument(document: unknown): DocumentScan {\n const scan: DocumentScan = { externalRef: false, schemaIds: false, pathRefs: false }\n const visit = ({ node, readsIds, keyword }: { node: unknown; readsIds: boolean; keyword?: string }): void => {\n if (!node || typeof node !== 'object') return\n scanNode({ scan, node, readsIds })\n const named = isNamedMap({ node, keyword })\n const record = node as Record<string, unknown>\n for (const key in record) {\n visit({ node: record[key], readsIds: readsIds && (named || !isDataOrExtension(key)), keyword: childKeyword({ node, key, named }) })\n }\n }\n visit({ node: document, readsIds: true })\n return scan\n}\n\n/**\n * The declaration in the nearest enclosing schema, else the only one, else `undefined`.\n */\nfunction pick(declarations: Array<string> | undefined, pointer: string): string | undefined {\n if (!declarations) return undefined\n const enclosing = declarations.filter((target) => pointer === target || pointer.startsWith(`${target}/`))\n if (enclosing.length) return enclosing.reduce((a, b) => (b.length > a.length ? b : a))\n return declarations.length === 1 ? declarations[0] : undefined\n}\n\n/**\n * Rewrites, in place, each `$ref` to an `$id`, `$anchor` or `$dynamicAnchor`, and each `$dynamicRef`, into a\n * `#/...` pointer, so it is not fetched. Instance data and `x-` extensions are left as written.\n *\n * shortcut: `$id` matches the `$ref` string exactly and `$dynamicRef` resolves statically to the nearest\n * enclosing anchor, so a relative `$id` base or a recursively extended schema is not followed, upgrade when a spec needs that.\n */\nexport function resolveSchemaIds(document: unknown): void {\n const targets = memo.create<string, Array<string>>()\n const declare = (key: string, pointer: string) => memo(targets, key, () => []).push(pointer)\n walk(document, '#', (node, pointer) => {\n if (typeof node['$id'] === 'string') declare(node['$id'], pointer)\n for (const key of ['$anchor', '$dynamicAnchor']) {\n if (typeof node[key] === 'string') declare(`#${node[key]}`, pointer)\n }\n })\n if (!targets.size) return\n\n walk(document, '#', (node, pointer) => {\n const ref = typeof node['$ref'] === 'string' ? pick(targets.get(node['$ref']), pointer) : undefined\n if (ref) node['$ref'] = ref\n const dynamicRef = typeof node['$dynamicRef'] === 'string' ? pick(targets.get(node['$dynamicRef']), pointer) : undefined\n if (dynamicRef && node['$ref'] === undefined) {\n node['$ref'] = dynamicRef\n delete node['$dynamicRef']\n }\n })\n}\n","import { memo, unescapePointerToken } from '@internals/utils'\nimport type { Adapter, SourceRange } from '@kubb/core'\nimport { COLLECTION_STYLE, CORE_SCHEMA, EVENT_ID, load, parseEvents, SCALAR_STYLE } from 'js-yaml'\nimport type { Event } from 'js-yaml'\n\ntype Child = { index: number; range: SourceRange }\n\n// One entry per event in typed arrays: an event object per value takes ten times the memory.\ntype EventIndex = {\n types: Uint8Array\n styles: Uint8Array\n starts: Int32Array\n ends: Int32Array\n collections: Map<number, { keys: Map<string, Child>; items: Array<Child> }>\n refs?: Map<string, SourceRange>\n}\n\nconst flowGap = /(?:[\\s,]|#[^\\n]*)*/y\n\n/**\n * How long the indexes of the last sources stay in memory after their last use, in milliseconds.\n */\nexport const INDEX_IDLE_MS = 60_000\n\n// Shared schema detection parses every spec before the builds report, so the last few indexes are kept. They are\n// dropped after `INDEX_IDLE_MS` unused, so a long-lived host does not hold a large spec.\nclass IndexCache {\n #indexes = IndexCache.#createStore()\n #lastUsed = 0\n #timer: ReturnType<typeof setTimeout> | undefined\n\n static #createStore() {\n return memo.create<string, EventIndex | undefined>({ max: 8 })\n }\n\n get({ source, compute }: { source: string; compute: () => EventIndex | undefined }): EventIndex | undefined {\n const index = memo(this.#indexes, source, compute)\n this.#keep()\n return index\n }\n\n set({ source, index }: { source: string; index: EventIndex }): void {\n this.#indexes.set(source, index)\n this.#keep()\n }\n\n // Cheap on every call: one timer runs, and it schedules itself again for the time that is left.\n #keep(): void {\n this.#lastUsed = Date.now()\n if (!this.#timer) this.#schedule(INDEX_IDLE_MS)\n }\n\n #schedule(ms: number): void {\n this.#timer = setTimeout(this.#dropWhenIdle, ms)\n // The timer must not keep a finished CLI run alive.\n this.#timer.unref?.()\n }\n\n readonly #dropWhenIdle = (): void => {\n const remaining = this.#lastUsed + INDEX_IDLE_MS - Date.now()\n if (remaining > 0) return this.#schedule(remaining)\n this.#indexes = IndexCache.#createStore()\n this.#timer = undefined\n }\n}\n\nfunction createIndexCache(): IndexCache {\n return new IndexCache()\n}\n\nconst indexes = createIndexCache()\n\n// A plain `1.50` or `~` is a number or null to `js-yaml`, so the document, and the pointer, spell it `1.5` or `null`.\nfunction toKeyText(text: string): string {\n if (!/^[-+.~\\d]|^(?:null|true|false)$/i.test(text)) return text\n try {\n const value = load(text, { schema: CORE_SCHEMA })\n return value === null || typeof value === 'number' || typeof value === 'boolean' ? String(value) : text\n } catch {\n return text\n }\n}\n\nfunction indexEvents(events: ReadonlyArray<Event>): EventIndex {\n const types = new Uint8Array(events.length)\n const styles = new Uint8Array(events.length)\n const starts = new Int32Array(events.length)\n const ends = new Int32Array(events.length)\n\n for (let at = 0, last = 0; at < events.length; last = Math.max(last, starts[at]!, ends[at]!), at++) {\n const event = events[at]!\n types[at] = event.type\n if (event.type === EVENT_ID.SCALAR) {\n // Quotes sit outside the offsets of a scalar's value. An empty value has none, so it sits where the node before it ended.\n const quote = event.style === SCALAR_STYLE.SINGLE_QUOTED || event.style === SCALAR_STYLE.DOUBLE_QUOTED ? 1 : 0\n const empty = event.valueStart < 0\n styles[at] = event.style\n starts[at] = empty ? last : event.valueStart - quote\n ends[at] = empty ? last : event.valueEnd + quote\n }\n if (event.type === EVENT_ID.ALIAS) {\n starts[at] = event.anchorStart - 1\n ends[at] = event.anchorEnd\n }\n if (event.type === EVENT_ID.MAPPING || event.type === EVENT_ID.SEQUENCE) {\n styles[at] = event.style\n starts[at] = event.start\n }\n }\n return { types, styles, starts, ends, collections: new Map() }\n}\n\ntype SourceLocatorOptions = { index: EventIndex; source: string }\n\nclass SourceLocator {\n readonly #index: EventIndex\n readonly #source: string\n readonly #types: Uint8Array\n readonly #styles: Uint8Array\n readonly #starts: Int32Array\n readonly #ends: Int32Array\n\n constructor({ index, source }: SourceLocatorOptions) {\n this.#index = index\n this.#source = source\n this.#types = index.types\n this.#styles = index.styles\n this.#starts = index.starts\n this.#ends = index.ends\n }\n\n find(pointer: string): SourceRange | undefined {\n // The first event opens the document, the second is its root.\n return this.#walk({ at: 1, tokens: pointer.replace(/^#/, '').split('/').slice(1).map(unescapePointerToken), range: undefined })\n }\n\n findRef(ref: string): SourceRange | undefined {\n this.#index.refs ??= this.#indexRefs()\n return this.#index.refs.get(ref)\n }\n\n // Every `$ref` value in the document, mapped to the range of its first occurrence.\n #indexRefs(): Map<string, SourceRange> {\n const types = this.#types\n const refs = new Map<string, SourceRange>()\n // -1 in a sequence. In a mapping, 0 before a key and 1 before its value.\n const frames: Array<number> = []\n for (let at = 1; at + 1 < types.length; at++) {\n if (!this.#stepFrames({ frames, at }) || !this.#isRefKey(at)) continue\n const text = this.#readText(at + 1)\n if (!refs.has(text)) refs.set(text, { start: this.#starts[at + 1]!, end: this.#ends[at + 1]! })\n }\n return refs\n }\n\n // Moves `frames` past the event at `at`, and tells whether that event is a mapping key.\n #stepFrames({ frames, at }: { frames: Array<number>; at: number }): boolean {\n if (this.#types[at] === EVENT_ID.POP) {\n frames.pop()\n return false\n }\n const top = frames.length - 1\n const isKey = frames[top] === 0\n if (frames[top]! >= 0) frames[top] = 1 - frames[top]!\n if (this.#isCollection(at)) frames.push(this.#types[at] === EVENT_ID.MAPPING ? 0 : -1)\n return isKey\n }\n\n // A `$ref` key followed by its scalar value.\n #isRefKey(at: number): boolean {\n return this.#types[at] === EVENT_ID.SCALAR && this.#types[at + 1] === EVENT_ID.SCALAR && this.#readText(at) === '$ref'\n }\n\n #isCollection(at: number): boolean {\n return this.#types[at] === EVENT_ID.MAPPING || this.#types[at] === EVENT_ID.SEQUENCE\n }\n\n #readText(at: number): string {\n const styles = this.#styles\n const text = this.#source.slice(this.#starts[at], this.#ends[at])\n if (styles[at] === SCALAR_STYLE.SINGLE_QUOTED) return text.slice(1, -1).replaceAll(\"''\", \"'\")\n if (styles[at] !== SCALAR_STYLE.DOUBLE_QUOTED) return text\n try {\n return JSON.parse(text) as string\n } catch {\n return String(load(text, { schema: CORE_SCHEMA }))\n }\n }\n\n #readNode(at: number): SourceRange & { next: number } {\n const starts = this.#starts\n if (!this.#isCollection(at)) return { start: starts[at]!, end: this.#ends[at]!, next: at + 1 }\n let next = at + 1\n let end = starts[at]!\n while (this.#types[next] !== EVENT_ID.POP) ({ end, next } = this.#readNode(next))\n // A flow collection ends at its closing bracket, which no event marks, after any commas and comments.\n if (this.#styles[at] === COLLECTION_STYLE.FLOW) {\n flowGap.lastIndex = end\n flowGap.exec(this.#source)\n end = flowGap.lastIndex + 1\n }\n return { start: starts[at]!, end, next: next + 1 }\n }\n\n #readChildren(collection: number): { keys: Map<string, Child>; items: Array<Child> } {\n const types = this.#types\n const keys = new Map<string, Child>()\n const items: Array<Child> = []\n const isMapping = types[collection] === EVENT_ID.MAPPING\n for (let at = collection + 1; types[at] !== EVENT_ID.POP;) {\n const key = isMapping ? at : undefined\n if (key !== undefined) at = this.#readNode(at).next\n const { start, end, next } = this.#readNode(at)\n if (key === undefined) items.push({ index: at, range: { start, end } })\n const text = key !== undefined ? this.#readKey(key) : undefined\n if (text !== undefined && !keys.has(text)) keys.set(text, { index: at, range: { start: this.#starts[key!]!, end: this.#ends[key!]! } })\n at = next\n }\n return { keys, items }\n }\n\n #readKey(key: number): string | undefined {\n if (this.#types[key] !== EVENT_ID.SCALAR) return undefined\n const raw = this.#readText(key)\n return this.#styles[key] === SCALAR_STYLE.PLAIN ? toKeyText(raw) : raw\n }\n\n // Follows `tokens` from the collection at `at`. The range is the last key or item it reached.\n #walk({ at, tokens: [token, ...rest], range }: { at: number; tokens: Array<string>; range: SourceRange | undefined }): SourceRange | undefined {\n if (token === undefined) return range\n if (!this.#isCollection(at)) return undefined\n const { keys, items } = memo(this.#index.collections, at, () => this.#readChildren(at))\n const child = keys.get(token) ?? items[Number(token)]\n return child ? this.#walk({ at: child.index, tokens: rest, range: child.range }) : undefined\n }\n}\n\nfunction createSourceLocator(options: SourceLocatorOptions): SourceLocator {\n return new SourceLocator(options)\n}\n\nfunction parse(source: string): EventIndex | undefined {\n try {\n return indexEvents(parseEvents(source, { maxDepth: Number.POSITIVE_INFINITY }))\n } catch {\n // Text that is not YAML has no locations.\n return undefined\n }\n}\n\n/**\n * Keeps the event index of a source the adapter already parsed, so `locate` does not parse it again.\n */\nexport function rememberEvents({ source, events }: { source: string; events: ReadonlyArray<Event> }): void {\n indexes.set({ source, index: indexEvents(events) })\n}\n\n// The adapter merges `oneOf` or `anyOf` next to `properties` into an `allOf` the spec does not have, so its\n// pointers can step through `/allOf/<n>`. Without those steps the pointer names the key the user wrote.\nconst withoutAllOf = (pointer: string) => pointer.replace(/\\/allOf\\/\\d+(?=\\/|$)/g, '')\n\n/**\n * Maps OpenAPI JSON pointers and unresolved references to ranges in YAML or JSON source. A pointer through an `allOf`\n * the spec does not have falls back to the same pointer without its `allOf` steps. The indexes of the last few\n * sources are reused until they go unused for `INDEX_IDLE_MS`.\n */\nexport const locate: NonNullable<Adapter['locate']> = (source, location) => {\n if (!('pointer' in location)) return undefined\n const index = indexes.get({ source, compute: () => parse(source) })\n if (!index) return undefined\n\n const locator = createSourceLocator({ index, source })\n const ref = 'ref' in location ? location.ref : undefined\n const flattened = withoutAllOf(location.pointer)\n return locator.find(location.pointer) ?? (flattened === location.pointer ? undefined : locator.find(flattened)) ?? (ref ? locator.findRef(ref) : undefined)\n}\n","import { exists, getErrorMessage, read, toError } from '@internals/utils'\nimport { Diagnostics } from '@kubb/kit'\nimport { CORE_SCHEMA, constructFromEvents, parseEvents } from 'js-yaml'\nimport { rememberEvents } from '../sourceLocator.ts'\n\nexport const urlRegExp = /^https?:\\/+/i\n\n/** How long one request for a document or a `$ref` may take before Kubb gives up on it. */\nconst FETCH_TIMEOUT_MS = 30_000\n\n/**\n * Options for reading a source. `signal` cancels the request. `fetch` makes the request, the global\n * `fetch` when unset, and `read` reads a local file, from disk when unset.\n */\nexport type ReadSourceOptions = {\n signal?: AbortSignal\n fetch?: (url: URL, init: { signal: AbortSignal }) => Promise<Response>\n read?: (path: string) => Promise<string>\n}\n\n/**\n * Whether `error` is a harness refusal. It checks the code, since a host may load another copy of `@kubb/core`.\n */\nexport function isAccessRefused(error: unknown): error is InstanceType<typeof Diagnostics.Error> {\n return (error as { diagnostic?: { code?: unknown } } | null)?.diagnostic?.code === Diagnostics.code.accessRefused\n}\n\nfunction withTimeout(signal: AbortSignal | undefined): AbortSignal {\n const timeout = AbortSignal.timeout(FETCH_TIMEOUT_MS)\n return signal ? AbortSignal.any([signal, timeout]) : timeout\n}\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, { signal, fetch = globalThis.fetch }: ReadSourceOptions): Promise<{ response: Response; body: string }> {\n const deadline = withTimeout(signal)\n try {\n const response = await fetch(url, { signal: deadline })\n // The body is read here too, so a server that stalls after its headers also hits the timeout.\n return { response, body: response.ok ? await response.text() : '' }\n } catch (error) {\n // A canceled build stops here; only a timeout or a network failure is the server's problem.\n if (signal?.aborted) throw signal.reason\n if (isAccessRefused(error)) throw error\n const reason = deadline.aborted ? `no answer within ${FETCH_TIMEOUT_MS / 1000} seconds` : describeFetchFailure(error)\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputUnreachable,\n severity: 'error',\n message: `Cannot reach ${url.href}: ${reason}`,\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, options: ReadSourceOptions): 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, body } = await fetchSource(url, options)\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 body\n }\n\n return (options.read ?? 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, { remember, ...options }: { remember?: boolean } & ReadSourceOptions = {}): Promise<object | string> {\n const data = await readSource(sourcePath, options)\n\n if (sourcePath.toLowerCase().endsWith('.md')) {\n return data\n }\n\n // A URL's query string or fragment must not hide the extension.\n const pathname = urlRegExp.test(sourcePath) ? new URL(sourcePath).pathname : sourcePath\n\n return parseYaml(data, {\n origin: sourcePath,\n json: !/\\.ya?ml$/i.test(pathname),\n help: 'Fix the syntax at the reported line, or check that `input` points at the spec and not an HTML page.',\n remember,\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 * With `json` (the default), a document that starts with `{` or `[` goes through `JSON.parse`\n * first, about ten times faster than `js-yaml` on a JSON spec. A duplicate key then keeps the last\n * value, as every JSON parser does. YAML flow syntax also starts with `{`, so a parse failure falls\n * through to YAML. Pass `json: false` for a source known to be YAML.\n *\n * `js-yaml` rejects duplicate keys instead of keeping the last one. Its core schema keeps\n * timestamps as strings and `<<` as a plain key, as YAML 1.2 does.\n */\nexport function parseYaml(\n data: string,\n { origin, help, json = true, remember = false }: { origin: string; help: string; json?: boolean; remember?: boolean },\n): object {\n if (json && /^\\s*[[{]/.test(data)) {\n try {\n return JSON.parse(data) as object\n } catch {\n // Not JSON, so YAML parses it below.\n }\n }\n try {\n const events = parseEvents(data, {})\n const documents = constructFromEvents(events, { source: data, schema: CORE_SCHEMA })\n if (remember && documents.length === 1) rememberEvents({ source: data, events })\n return documents[0] 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 { dirname, join, normalize, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { escapePointerToken, getErrorMessage, memo, toError } from '@internals/utils'\nimport { Diagnostics } from '@kubb/kit'\nimport type { AdapterSource, Diagnostic, Harness } from '@kubb/kit'\nimport { upgrade } from '@scalar/openapi-upgrader'\nimport { bundle } from 'api-ref-bundler'\nimport { namedEntryKeys } from '../constants.ts'\nimport { markLegacyDocument } from '../oas.ts'\nimport { createRefs } from '../refs.ts'\nimport type { Document } from '../types.ts'\nimport type { ValidationErrors, WorkerResult } from './validateSpec.ts'\nimport { type DocumentScan, resolveSchemaIds, scanDocument } from './schemaIds.ts'\nimport { assertInputExists, isAccessRefused, parseYaml, resolveSource, urlRegExp } from './source.ts'\n\ntype RefusalDiagnostic = InstanceType<typeof Diagnostics.Error>['diagnostic']\n\n// The scan of each document returned unbundled, so a later step can skip a walk it answers.\nconst scans = new WeakMap<object, DocumentScan>()\n\n/**\n * Rewrites `$id` and `$anchor` refs in place, then returns the scan of the result.\n */\nfunction resolveTargets(document: unknown): DocumentScan {\n const scan = scanDocument(document)\n if (!scan.schemaIds) return scan\n resolveSchemaIds(document)\n return scanDocument(document)\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/**\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 // An entry name in a named map is never a keyword itself, so a property named `dependentSchemas` holds keywords again.\n let inNamedMap = false\n for (const token of path) {\n const key = String(token)\n if (key.startsWith('x-') && !inNamedMap) return true\n inNamedMap = !inNamedMap && namedEntryKeys.has(key)\n }\n return false\n}\n\n/**\n * True when `node` is the value at `path` in `document`. api-ref-bundler reports the output path of a\n * failed `$ref`, so this tells a `$ref` in the input itself from one in a file it pulled in.\n */\nfunction isNodeAt(document: unknown, path: ReadonlyArray<string | number>, node: unknown): boolean {\n let current = document\n for (const token of path) {\n if (!current || typeof current !== 'object' || !Object.hasOwn(current, token)) return false\n current = (current as Record<string | number, unknown>)[token]\n }\n return current === node\n}\n\n/**\n * Returns the base for relative `$ref`s: the 3.2 `$self` resolved against `pathOrUrl`, else `pathOrUrl`.\n */\nexport function getBaseUri(pathOrUrl: string, root: unknown): string {\n const self = root && typeof root === 'object' ? (root as { $self?: unknown }).$self : undefined\n if (typeof self !== 'string' || !self) return pathOrUrl\n try {\n if (urlRegExp.test(self)) return new URL(self).href\n if (/^file:/i.test(self)) return fileURLToPath(self)\n if (/^[a-z][a-z\\d+.-]*:/i.test(self)) return pathOrUrl\n return urlRegExp.test(pathOrUrl) ? new URL(self, pathOrUrl).href : resolve(dirname(pathOrUrl), self)\n } catch {\n return pathOrUrl\n }\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. Relative `$ref`s resolve\n * against the OpenAPI 3.2 `$self` when the document sets one. Every other file or URL read,\n * 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 * So does any local file from a URL input. With `harness`, every `$ref` file and every URL is read\n * through it, and a target its rules refuse reports `KUBB_ACCESS_REFUSED`. Without one, a `$ref` reads\n * any file and host. `signal` cancels every request.\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(\n pathOrUrl: string,\n {\n document,\n sources = [],\n harness,\n signal,\n }: {\n document?: Document\n sources?: Array<string>\n harness?: Harness\n signal?: AbortSignal\n } = {},\n): Promise<Document> {\n const cache = memo.create<string, Promise<object | string>>()\n // api-ref-bundler refers to the same URL as both `https://` and the posix-normalized\n // `https:/`, and to `./openapi.yaml` as `openapi.yaml`, so key on the canonical href or the\n // normalized path to fetch each source once and to match the input.\n const toKey = (sourcePath: string) => (urlRegExp.test(sourcePath) ? new URL(sourcePath).href : normalize(sourcePath))\n const refused = new Set<string>()\n // What the harness refused, by the key of the file or URL it refused.\n const harnessRefusals = new Map<string, RefusalDiagnostic>()\n const read = ({ sourcePath, isRef }: { sourcePath: string; isRef: boolean }) => {\n if (!harness) return resolveSource(sourcePath, { remember: !isRef, signal })\n return resolveSource(sourcePath, {\n remember: !isRef,\n signal,\n fetch: (url, init) => harness.fetch(url, init),\n // The input itself is the file the host named, so only what it refers to goes through the rules.\n read: isRef ? (file) => harness.read(file) : undefined,\n }).catch((error: unknown) => {\n if (isRef && isAccessRefused(error)) harnessRefusals.set(toKey(sourcePath), error.diagnostic)\n throw error\n })\n }\n const refDiagnostic = ({ message, target }: { message: string; target: string | undefined }): RefusalDiagnostic => {\n const harnessRefusal = target === undefined ? undefined : harnessRefusals.get(target)\n if (harnessRefusal) return harnessRefusal\n if (target === undefined || !refused.has(target)) {\n return {\n code: Diagnostics.code.refNotFound,\n severity: '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 }\n }\n return {\n code: Diagnostics.code.accessRefused,\n severity: 'error',\n message: `Refused an external \\`$ref\\` to the local file ${target}.`,\n help: 'This input reads no local file. Inline the schema, or serve the file from a URL.',\n }\n }\n\n let entry = pathOrUrl\n let entryDocument: object | string | undefined = document\n const resolver = async (sourcePath: string) => {\n if (entryDocument !== undefined && toKey(sourcePath) === toKey(entry)) {\n return entryDocument\n }\n const key = toKey(sourcePath)\n const isRef = key !== toKey(pathOrUrl)\n // A URL input has no folder of its own, so it reads no local file.\n if (isRef && !urlRegExp.test(sourcePath) && urlRegExp.test(pathOrUrl)) {\n refused.add(key)\n throw new Error(`Refused ${sourcePath}`)\n }\n return memo(cache, key, () => {\n sources.push(key)\n return read({ sourcePath, isRef })\n })\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 // Before bundling, so a `$ref` to a schema's `$id` URL is not fetched.\n const scan = resolveTargets(root)\n\n if (typeof root === 'object' && root !== null && !scan.externalRef) {\n scans.set(root, scan)\n return root as Document\n }\n entry = getBaseUri(pathOrUrl, root)\n entryDocument = root\n\n return (await bundle(entry, resolver, {\n hooks: {\n onError: (message, { path, value }, detail) => {\n // api-ref-bundler also swallows a canceled request, so stop here instead of reporting it as a missing ref.\n signal?.throwIfAborted()\n // Only a `$ref` in the input itself has a key in the document to point at.\n const pointer = isNodeAt(root, path, value) ? `#/${path.map((token) => escapePointerToken(String(token))).join('/')}` : undefined\n const diagnostic: Diagnostic = {\n // api-ref-bundler drops the rejection's message, so a failed `$ref` is matched by the key of its target.\n ...refDiagnostic({ message, target: detail && toKey(detail.document) }),\n severity: isExtensionPath(path) ? 'warning' : 'error',\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\nfunction readInlineData(data: unknown): Document {\n if (typeof data !== 'string') return structuredClone(data as Document)\n return parseYaml(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}\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(\n source: AdapterSource,\n sources: Array<string> = [],\n { harness, signal }: { harness?: Harness; signal?: AbortSignal } = {},\n): Promise<Document> {\n const raw = await (async (): Promise<Document> => {\n // YAML parsing also handles JSON.\n if (source.type === 'data') {\n const data = readInlineData(source.data)\n const isObject = Boolean(data) && typeof data === 'object'\n // `bundleDocument` returns the document as is when it has no external ref.\n if (source.root && isObject) return bundleDocument(join(source.root, inlineInputName), { document: data, sources, harness, signal })\n const scan = resolveTargets(data)\n if (isObject) scans.set(data, scan)\n return data\n }\n await assertInputExists(source.path)\n return bundleDocument(source.path, { sources, harness, signal })\n })()\n\n return upgradeDocument(raw, { pathRefs: scans.get(raw)?.pathRefs ?? true })\n}\n\n/** Upgrades Swagger 2.0 or OpenAPI 3.0 to 3.1. `pathRefs: false` skips the `#/paths/` ref walk. */\nfunction upgradeDocument(raw: Document, { pathRefs = true }: { pathRefs?: boolean } = {}): Document {\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 && pathRefs) {\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 const declared = raw && typeof raw === 'object' ? ((raw as { openapi?: unknown }).openapi ?? (raw as { swagger?: unknown }).swagger) : undefined\n const legacy = declared !== undefined && /^(2|3\\.0)(\\.|$)/.test(String(declared))\n try {\n const document = upgrade(raw, '3.1') as Document\n if (legacy) markLegacyDocument(document)\n return document\n } catch (error) {\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 { validateSpec } = await import('./validateSpec.ts')\n // `validateSpec` dereferences its input in place, so clone to keep the cached document intact.\n const result = await validateSpec(structuredClone(document))\n if (throwOnError) return throwResult(result)\n reportResult(result)\n}\n\nfunction throwResult(result: WorkerResult): void {\n if ('valid' in result && result.valid) return\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidSpec,\n severity: 'error',\n // The code frames number a JSON copy of the spec, not the user's file, but they still show which key fails.\n message: 'thrown' in result ? result.thrown : result.message,\n help: 'Fix each problem listed in the spec, then validate again.',\n })\n}\n\nfunction reportResult(result: WorkerResult): void {\n if ('thrown' in result) return reportInvalidSpec(result.thrown)\n if (!result.valid) 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// A worker gets its own heap, whose young generation V8 lets grow to tens of megabytes before it\n// collects. Validation makes mostly short-lived objects, so a small one frees them sooner at no cost in time.\nconst VALIDATION_WORKER_LIMITS = { maxYoungGenerationSizeMb: 4 }\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, resourceLimits: VALIDATION_WORKER_LIMITS })\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 reportResult(message)\n}\n","import { escapePointerToken, memo } from '@internals/utils'\nimport { pascalCase } from '@kubb/core'\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\nexport type 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\n// Names are compared in PascalCase, the form the generated identifiers use.\nclass SchemaNames {\n readonly #taken: Set<string>\n\n constructor(reserved: Iterable<string>) {\n this.#taken = new Set(reserved)\n }\n\n // The first free name of `base`, `base2`, `base3`, … A `from` number skips the plain `base`.\n claim({ base, from }: { base: string; from?: number }): string {\n let n = from ?? 1\n let name = from ? `${base}${n}` : base\n while (this.#taken.has(pascalCase(name))) {\n n = Math.max(n + 1, 2)\n name = `${base}${n}`\n }\n this.#taken.add(pascalCase(name))\n return name\n }\n}\n\nfunction createSchemaNames(reserved: Iterable<string>): SchemaNames {\n return new SchemaNames(reserved)\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 /**\n * Follows a `$ref` to the schema it ends at. Keywords next to a `$ref` apply together with its target,\n * so they stay on a one-member `allOf` around it.\n */\n function inlineRef(schema: SchemaObject, seen = new Set<string>()): SchemaObject {\n if (!isReference(schema) || seen.has(schema.$ref)) return schema\n const { $ref, ...siblings } = schema\n const resolved = refs.resolve<SchemaObject>($ref)\n if (!resolved) return schema\n const target = inlineRef(resolved, seen.add($ref))\n if (!Object.keys(siblings).length) return target\n const own = 'allOf' in siblings && Array.isArray(siblings.allOf) ? siblings.allOf : []\n const wrapped = { ...siblings, allOf: [...own, target] }\n\n return wrapped as SchemaObject\n }\n\n /**\n * Replaces a `$ref` schema with its target. A plain `$ref` to another `$ref` stays as it is, so the parser reads it as an alias.\n */\n function resolveSchemaRef(schema: SchemaObject): SchemaObject {\n if (!isReference(schema)) return schema\n if (Object.keys(schema).length > 1) return inlineRef(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 = memo.create<string, Array<SchemaWithMetadata>>()\n for (const item of candidates) {\n const key = pascalCase(item.originalName)\n memo(normalizedNames, key, () => []).push(item)\n }\n\n const schemas: Record<string, SchemaObject> = {}\n const renames = new Map<string, string>()\n const pointers = new Map<string, string>()\n // Every original name is reserved up front, so a suffixed name never takes one that a later group keeps.\n const names = createSchemaNames(normalizedNames.keys())\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 // A collision across sources gets a semantic suffix, within one source a numeric one, counting up while taken.\n const uniqueName = (() => {\n if (isSingle || (!hasMultipleSources && !index)) return item.originalName\n return hasMultipleSources\n ? names.claim({ base: item.originalName + semanticSuffixes[item.source] })\n : names.claim({ base: item.originalName, from: index + 1 })\n })()\n schemas[uniqueName] = item.schema\n pointers.set(uniqueName, item.pointer ?? item.ref)\n if (uniqueName !== item.originalName || item.nested) renames.set(item.ref, uniqueName)\n })\n }\n\n return { schemas: sortSchemas(schemas, renames), renames, pointers }\n}\n","import { unescapePointerToken } from '@internals/utils'\nimport type { ast } from '@kubb/kit'\nimport { pickStrings } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport type { Document, SecuritySchemeObject } from '../types.ts'\n\nconst SCHEME_POINTER = '#/components/securitySchemes/'\nconst API_KEY_LOCATIONS = new Set(['header', 'query', 'cookie'])\n\nfunction getCredential(scheme: SecuritySchemeObject): ast.AuthCredential | undefined {\n if (scheme.type === 'apiKey') {\n return scheme.name && scheme.in && API_KEY_LOCATIONS.has(scheme.in)\n ? { type: 'apiKey', in: scheme.in as 'header' | 'query' | 'cookie', name: scheme.name }\n : undefined\n }\n if (scheme.type === 'http') {\n return scheme.scheme ? { type: 'http', scheme: scheme.scheme.toLowerCase(), ...(scheme.bearerFormat && { bearerFormat: scheme.bearerFormat }) } : undefined\n }\n if (scheme.type === 'openIdConnect') return { type: 'openIdConnect', ...(scheme.openIdConnectUrl && { url: scheme.openIdConnectUrl }) }\n if (scheme.type === 'oauth2') {\n const flows = Object.entries(scheme.flows ?? {}).map(([name, flow]) => {\n const scopes = flow && typeof flow === 'object' && flow.scopes && typeof flow.scopes === 'object' ? { scopes: flow.scopes as Record<string, string> } : {}\n return [name, { ...pickStrings(flow, ['authorizationUrl', 'deviceAuthorizationUrl', 'tokenUrl', 'refreshUrl']), ...scopes }] as const\n })\n return { type: 'oauth2', flows: Object.fromEntries(flows), ...(scheme.oauth2MetadataUrl && { metadataUrl: scheme.oauth2MetadataUrl }) }\n }\n return scheme.type === 'mutualTLS' ? { type: 'mutualTLS' } : undefined\n}\n\n/**\n * Maps `components.securitySchemes` to `AuthScheme` entries, leaving out a scheme a client cannot place.\n */\nexport function toAuthSchemes(schemes: Record<string, unknown> | undefined, refs: Refs): Array<ast.AuthScheme> {\n return Object.entries(schemes ?? {}).flatMap(([name, value]) => {\n const scheme = refs.deref<SecuritySchemeObject>(value)\n const credential = scheme && getCredential(scheme)\n if (!scheme || !credential) return []\n return [\n {\n name,\n ...(scheme.description && { description: scheme.description }),\n ...(scheme.deprecated && { deprecated: true }),\n credential,\n },\n ]\n })\n}\n\n/**\n * Maps security requirements to `AuthRequirement` entries. A 3.2 URI key becomes the scheme name.\n */\nexport function toAuthRequirements(requirements: unknown, document: Document): Array<ast.AuthRequirement> | undefined {\n if (!Array.isArray(requirements)) return undefined\n const schemes = document.components?.securitySchemes ?? {}\n const toName = (key: string) => {\n const index = key.indexOf(SCHEME_POINTER)\n return Object.hasOwn(schemes, key) || index === -1 ? key : unescapePointerToken(key.slice(index + SCHEME_POINTER.length))\n }\n\n return requirements\n .filter((requirement): requirement is Record<string, unknown> => !!requirement && typeof requirement === 'object')\n .map((requirement) =>\n Object.entries(requirement).map(([key, scopes]) => ({\n scheme: toName(key),\n ...(Array.isArray(scopes) && scopes.length && { scopes: scopes.map(String) }),\n })),\n )\n}\n","import { type ast, 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\n/**\n * Maps OpenAPI servers to `InputServer` entries: drops entries without a `url` and fills `{variable}` defaults.\n */\nexport function toInputServers(servers: Array<ServerObject>): Array<ast.InputServer> {\n return servers\n .filter((entry) => entry.url)\n .map(({ url, name, description, variables }) => {\n const declared = { ...(name !== undefined && { name }), ...(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}\n","import type { ast } from '@kubb/kit'\nimport { getExternalDocs } from '../oas.ts'\nimport type { TagObject } from '../types.ts'\n\nexport function toInputTags(tags: Array<TagObject>): Array<ast.InputTag> {\n return tags\n .filter((tag) => typeof tag.name === 'string')\n .map(({ name, summary, description, parent, kind, externalDocs }) => {\n const docs = getExternalDocs(externalDocs)\n return {\n name,\n ...(typeof summary === 'string' && { summary }),\n ...(typeof description === 'string' && { description }),\n ...(typeof parent === 'string' && { parent }),\n ...(typeof kind === 'string' && { kind }),\n ...(docs && { externalDocs: docs }),\n }\n })\n}\n","import { getFormatType, specialCasedFormats, structuralKeys } from '../constants.ts'\nimport { isReference } from '../oas.ts'\nimport type { ReferenceObject, SchemaObject } from '../types.ts'\nimport type { DateOnlyTypeValue, DateTimeTypeValue, ParserOptions } from '../parserOptions.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 getFormatType(format) !== 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(dateType: ParserOptions['dateType'], format: 'date-time' | 'date' | 'time'): DateTimeTypeValue | 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\n/**\n * Whether the schema and its inline `allOf` members hold more than one distinct `pattern`. A value must match every one.\n */\nexport function hasSeveralPatterns(schema: SchemaObject): boolean {\n const members = (schema.allOf ?? []) as Array<SchemaObject | ReferenceObject>\n const patterns = [schema, ...members].map((item) => (isReference(item) ? undefined : item.pattern)).filter((pattern) => pattern !== undefined)\n\n return new Set(patterns).size > 1\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 // A node holds only one `pattern`, so several patterns stay an intersection.\n if (hasSeveralPatterns(schema)) return schema\n\n // Destructure `allOf` out instead of `delete merged.allOf`: a `delete` transitions the freshly\n // spread object into V8 dictionary (slow) mode, and this runs per `allOf` schema during parsing.\n const { allOf: _allOf, ...rest } = schema\n const merged = rest as SchemaObject\n\n for (const fragment of allOfFragments) {\n for (const [key, value] of Object.entries(fragment)) {\n merged[key as keyof SchemaObject] ??= value as SchemaObject[keyof SchemaObject]\n }\n }\n\n return merged\n}\n","import { ast } from '@kubb/kit'\nimport { getExternalDocs, pickExtensions } from '../oas.ts'\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 */\nexport type NodeBaseContext = Pick<ConvertContext, 'schema' | 'name' | 'nullable' | 'defaultValue'>\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: ast.CreateSchemaInput): 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 externalDocs: getExternalDocs(schema.externalDocs),\n extensions: pickExtensions(schema),\n ...extras,\n })\n}\n","import { ast, enumPrimitive, 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\nexport type 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// OpenAPI allows a bare schema name, such as `Dog`, as a mapping value.\nfunction toMappingRef(value: string): string {\n return value.includes('/') ? value : `${SCHEMA_REF_PREFIX}${value}`\n}\n\n/**\n * Returns the `$ref` of an OpenAPI 3.2 `defaultMapping`, written as a schema name or a `$ref`; `undefined` when none.\n */\nexport function getDefaultMappingRef(discriminator: DiscriminatorObject | undefined): string | undefined {\n const value = discriminator?.defaultMapping\n if (!value) return undefined\n\n return toMappingRef(value)\n}\n\n/**\n * Returns every discriminator key whose mapping value matches `ref`, in mapping order.\n * A bare schema name in the mapping matches its `#/components/schemas/<name>` ref.\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]) => toMappingRef(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, value]) => {\n const target = toMappingRef(value)\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 * Whether a member can carry the discriminator property. A discriminator is only a hint, so an array\n * or primitive member keeps its own type instead of an intersection no value can satisfy.\n */\nfunction isObjectLike(member: unknown, refs: Refs): boolean {\n const schema = isReference(member) ? refs.resolve<SchemaObject>(member.$ref, { report: false }) : (member as SchemaObject | undefined)\n const type = schema?.type\n if (type === undefined) return true\n\n return Array.isArray(type) ? type.includes('object') : type === 'object'\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.schema.narrow(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 = ast.ref.getName(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 /** Whether the variant, or a schema it composes, pins the discriminator property to literal values. */\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 const pins = (candidate: SchemaObject) => Array.isArray(candidate.enum) || candidate.const !== undefined\n // The OpenAPI 3.1 nullable form `anyOf: [{ enum }, { type: 'null' }]` pins the value, a plain `string` member does not.\n const members = ((resolved?.anyOf ?? resolved?.oneOf ?? []) as Array<SchemaObject>).filter((member) => member.type !== 'null')\n if (resolved && (pins(resolved) || (members.length > 0 && members.every(pins)))) 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 const defaultRef = getDefaultMappingRef(discriminator)\n\n return unionMembers.map((s) => {\n const ref = isReference(s) ? s.$ref : undefined\n // The default member accepts every value outside `mapping`, so it is never narrowed.\n const isDefault = ref !== undefined && ref === defaultRef\n const mappedValues = isDefault ? [] : findDiscriminators({ mapping: discriminator?.mapping, ref })\n const implicitValue = mappedValues.length || isDefault ? 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 || !isObjectLike(s, refs)) {\n return memberNode\n }\n\n const narrowedDiscriminatorNode = sharedPropertiesNode\n ? pickDiscriminatorPropertyNode(\n ast.macro.apply(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 // The default child accepts every value outside `mapping`, so it drops the parent like a mapped child but gets no discriminant.\n const isDefault = childRef === getDefaultMappingRef(discriminator)\n const values = isDefault ? [] : 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 && (isDefault || 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, macroDedupeUnion, mergeAdjacentObjectsLazy } from '@kubb/kit'\nimport { SCHEMA_REF_PREFIX } from '../../constants.ts'\nimport { getExternalDocs, isDiscriminator, isLegacyDocument, isNullable, isReference, pickExtensions } 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 getDefaultMappingRef,\n removeInheritedDiscriminator,\n extractDiscriminatedAllOfMembers,\n narrowUnionMembers,\n propertyTypeOf,\n} from '../discriminator/preserve.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\nimport { extractExamples, hasSeveralPatterns } 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 */\nexport function collectSiblingProperties(\n allOfMembers: Array<SchemaObject | ReferenceObject>,\n refs: Refs,\n outerProperties?: Record<string, unknown>,\n): Record<string, unknown> {\n // No prototype, so an own `__proto__` property is copied as a key, not as the prototype.\n const properties: Record<string, unknown> = Object.assign(Object.create(null), outerProperties)\n const visited = new Set<string>()\n\n /** Adds the properties of one member, following its `$ref` and its own `allOf`. */\n function collectFrom(item: SchemaObject | ReferenceObject | undefined): void {\n if (!item) return\n\n if (isReference(item)) {\n const { $ref, ...siblings } = item\n // The target can be another `$ref`, an alias, which `visited` keeps from looping.\n if (!visited.has($ref)) {\n visited.add($ref)\n collectFrom(refs.resolve<SchemaObject>($ref, { report: false }) ?? undefined)\n }\n // Keywords next to a `$ref` apply too, and win over the target's.\n collectFrom(siblings as SchemaObject)\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 `ast.ref.mergeSchema(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 }) === null) {\n return createNode(ctx, { type: ast.schema.types.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 extensions: pickExtensions({ ...resolvedSchema.extensions, ...schema }),\n })\n }\n\n const targetName = renames?.get(schema.$ref!)\n\n return createNode(ctx, {\n type: ast.schema.types.ref,\n name: ast.ref.getName(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.schema.types.not, members: [parse({ schema: subschema })] })\n\n return createNode({ schema, name, nullable, defaultValue }, { type: ast.schema.types.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. The parser reads their `if`/`then`/`else` into `conditionals`.\n */\nexport function isAnnotationMember(member: unknown): boolean {\n return !!member && typeof member === 'object' && !isReference(member) && Object.keys(member).every((key) => annotationKeys.has(key))\n}\n\nfunction mergeAnnotations(schema: SchemaObject): SchemaObject {\n const members = schema.allOf as Array<SchemaObject | ReferenceObject>\n const annotations = members.filter(isAnnotationMember)\n const rest = members.filter((member) => !isAnnotationMember(member))\n\n return annotations.length && rest.length ? { ...Object.assign({}, ...annotations), ...schema, allOf: rest } : schema\n}\n\n/**\n * Whether the parent's own keywords become an intersection member: always beside `properties`, and\n * beside several patterns when the parent holds more than its type and annotations, such as `minLength`.\n */\nfunction keepsOwnKeywords(schema: SchemaObject): boolean {\n if (schema.properties) return true\n if (!hasSeveralPatterns(schema)) return false\n\n return Object.keys(schema).some((key) => key !== 'allOf' && key !== 'type' && key !== 'nullable' && !annotationKeys.has(key))\n}\n\n/**\n * Whether a one-member `allOf` adds nothing but annotations, so it parses as that member.\n */\nfunction isSingleMemberAllOf(schema: SchemaObject): boolean {\n return (\n schema.allOf!.length === 1 &&\n !schema.properties &&\n !(Array.isArray(schema.required) && schema.required.length) &&\n schema.additionalProperties === undefined &&\n !hasSeveralPatterns(schema)\n )\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 (isSingleMemberAllOf(schema)) {\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 extensions: pickExtensions({ ...memberNode.extensions, ...schema }),\n externalDocs: getExternalDocs(schema.externalDocs) ?? memberNode.externalDocs,\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 // An alias, a schema that is only a `$ref`, is followed to its target.\n const seen = new Set<string>()\n let deref: SchemaObject | ReferenceObject | null | undefined = item\n while (deref && isReference(deref) && !seen.has(deref.$ref)) {\n seen.add(deref.$ref)\n deref = refs.resolve<SchemaObject>(deref.$ref)\n }\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 (keepsOwnKeywords(schema)) {\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.schema.types.intersection,\n members: [...mergeAdjacentObjectsLazy(allOfMembers.slice(0, syntheticStart)), ...mergeAdjacentObjectsLazy(allOfMembers.slice(syntheticStart))],\n },\n )\n}\n\nconst scalarTypes = new Set(['string', 'number', 'integer', 'boolean'])\n\n/**\n * Copies a scalar parent `type` and `format` onto inline members without a `type`. JSON Schema applies\n * sibling keywords to every member, so `type: 'integer', anyOf: [{ minimum: 10 }]` keeps each member an integer.\n */\nfunction inheritScalarType(members: Array<unknown>, { schema, type }: Pick<ConvertContext, 'schema' | 'type'>): Array<unknown> {\n if (!type || !scalarTypes.has(type)) return members\n // `type` holds only the first entry of a multi-type array, so it does not apply to every member.\n if (Array.isArray(schema.type) && schema.type.filter((t) => t !== 'null').length > 1) return members\n\n return members.map((member) => {\n if (!member || typeof member !== 'object' || isReference(member) || (member as SchemaObject).type !== undefined) return member\n const obj = member as SchemaObject\n\n return { type, ...(schema.format !== undefined && obj.format === undefined && { format: schema.format }), ...obj }\n })\n}\n\n/**\n * Converts a `oneOf` / `anyOf` schema into a `UnionSchemaNode`.\n */\nexport function convertUnion(context: ConvertContext): ast.SchemaNode {\n if (context.schema.enum?.length) {\n const { enum: values, ...union } = context.schema\n // A sibling `enum` restricts the union too. A 3.0 `nullable: true`, which the upgrade turns into a `null` member, keeps `null` allowed.\n const nullable =\n context.nullable ||\n [...(union.oneOf ?? []), ...(union.anyOf ?? [])].some((member) => {\n const resolved = isReference(member) ? context.refs.resolve<SchemaObject>(member.$ref, { report: false }) : (member as SchemaObject)\n return !!resolved && !isReference(resolved) && isNullable(resolved, context.document)\n })\n const enumSchema: SchemaObject = { type: union.type, enum: nullable && isLegacyDocument(context.document) ? [...values, null] : values }\n const members = [convertUnion({ ...context, schema: union }), context.parse({ schema: enumSchema })]\n return createNode(context, { type: ast.schema.types.intersection, members })\n }\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 discriminator = isDiscriminator(schema) ? schema.discriminator : undefined\n const declaredMembers = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]\n // From 3.2 `propertyName` is optional, and a discriminator with only `defaultMapping` still adds that member.\n const defaultRef = getDefaultMappingRef(typeof schema.discriminator === 'object' ? schema.discriminator : undefined)\n const allMembers =\n defaultRef && !declaredMembers.some((member) => isReference(member) && member.$ref === defaultRef)\n ? [...declaredMembers, { $ref: defaultRef }]\n : declaredMembers\n const unionMembers = resolveUnionMembers(inheritScalarType(allMembers, context), schema.properties ?? {})\n const strategy: 'one' | 'any' = schema.oneOf ? 'one' : 'any'\n const explicitDiscriminatorPropertyName = discriminator?.propertyName\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.schema.types.union,\n strategy,\n members,\n discriminatorPropertyName: explicitDiscriminatorPropertyName ?? ast.schema.inferDiscriminator(members),\n })\n\n const requiredProperties = missingRequired.map((name) =>\n ast.factory.createProperty({ name, required: true, schema: ast.factory.createSchema({ type: ast.schema.types.unknown }) }),\n )\n const siblings = sharedPropertiesNode ? [sharedPropertiesNode] : []\n if (requiredProperties.length) {\n siblings.push(ast.factory.createSchema({ type: ast.schema.types.object, properties: requiredProperties }))\n }\n\n if (!siblings.length) {\n return unionNode\n }\n\n return createNode(ctx, { type: ast.schema.types.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.schema.types.union,\n strategy,\n members,\n discriminatorPropertyName: explicitDiscriminatorPropertyName ?? ast.schema.inferDiscriminator(members),\n })\n\n return ast.macro.apply(unionNode, [macroDedupeUnion], { 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 return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: ast.schema.types.union,\n members: nonNullTypes.map((t) => {\n // The union node keeps the `x-*` keys, so members do not repeat them.\n const raw = { ...Object.fromEntries(Object.entries(schema).filter(([key]) => !key.startsWith('x-'))), type: t }\n const memberSchema = raw as SchemaObject\n return parse({ schema: memberSchema, name })\n }),\n },\n )\n}\n","import { escapePointerToken, memo } from '@internals/utils'\nimport { ast, 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`, `KUBB_DUPLICATE_DISCRIMINATOR`) 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\nclass FormatTally {\n // Pointers per unsupported format, collected while `groupUnsupportedFormats` runs.\n #pointers: Map<string, Set<string>> | undefined\n\n group<T>(fn: () => T): T {\n this.#pointers = memo.create()\n try {\n return fn()\n } finally {\n const tally = this.#pointers\n this.#pointers = undefined\n for (const [format, pointers] of tally) reportUnsupportedFormat(format, [...pointers])\n }\n }\n\n add(format: string, pointer: string): void {\n if (!this.#pointers) return reportUnsupportedFormat(format, [pointer])\n memo(this.#pointers, format, () => new Set()).add(pointer)\n }\n}\n\nconst formatTally = new FormatTally()\n\n/**\n * Runs `fn` and reports `KUBB_UNSUPPORTED_FORMAT` once per format with the number of schemas that use it,\n * instead of once per schema. `format` is an open value in OpenAPI, so a large spec would otherwise print\n * thousands of warnings that say the same thing. `fn` must be synchronous.\n */\nexport function groupUnsupportedFormats<T>(fn: () => T): T {\n return formatTally.group(fn)\n}\n\nfunction reportUnsupportedFormat(format: string, pointers: Array<string>): void {\n const count = pointers.length\n Diagnostics.report({\n code: Diagnostics.code.unsupportedFormat,\n severity: 'warning',\n message:\n count === 1\n ? `Kubb does not map the format \"${format}\" to a specific type, so it falls back to the base type.`\n : `Kubb does not map the format \"${format}\" to a specific type, so ${count} schemas fall back to the base type.`,\n help: `Use a format Kubb supports, or handle \"${format}\" with a custom parser or plugin.`,\n location: { kind: 'schema', pointer: pointers[0]! },\n })\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 formatTally.add(node.format, pointer)\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.discriminatorPropertyName) reportDuplicateDiscriminators(node, node.discriminatorPropertyName, pointer)\n\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\n/**\n * Reports a declared discriminator whose value pins more than one member. The spec cannot tell\n * those members apart, and Zod's `z.discriminatedUnion` throws on the first parse.\n * One diagnostic per union, since the build dedupes by code and pointer.\n */\nfunction reportDuplicateDiscriminators(node: ast.UnionSchemaNode, propertyName: string, pointer: string): void {\n const keyword = node.strategy === 'any' ? 'anyOf' : 'oneOf'\n const membersByValue = memo.create<Literal, Array<string>>()\n\n for (const [index, member] of (node.members ?? []).entries()) {\n const label = memberName(member) ?? `${keyword}/${index}`\n for (const value of memberValues(member, propertyName)) memo(membersByValue, value, () => []).push(label)\n }\n\n const duplicates = [...membersByValue].filter(([, members]) => members.length > 1)\n if (!duplicates.length) return\n\n Diagnostics.report({\n code: Diagnostics.code.duplicateDiscriminator,\n severity: 'warning',\n message: duplicates\n .map(([value, members]) => `Discriminator \"${propertyName}\" value ${JSON.stringify(value)} matches more than one member (${members.join(', ')}).`)\n .join(' '),\n help: `Give each member its own \"${propertyName}\" value, or drop the discriminator. Zod's z.discriminatedUnion throws on the first parse of this union.`,\n location: { kind: 'schema', pointer },\n })\n}\n\ntype Literal = string | number | boolean | null\n\n// Values a member allows for the discriminator. A nested `oneOf`/`anyOf` allows any of its alternatives' values.\nfunction memberValues(node: ast.SchemaNode, propertyName: string, seen = new Set<ast.SchemaNode>()): Array<Literal> {\n if (seen.has(node)) return []\n seen.add(node)\n const target = node.type === 'ref' && node.schema ? node.schema : node\n if (target.type === 'union') return [...new Set(target.members?.flatMap((member) => memberValues(member, propertyName, seen)))]\n\n return intersect(ast.schema.findProperties({ node, propertyName }).map((property) => [...ast.schema.getLiterals(property.schema)]))\n}\n\n// Every slice that pins values narrows the set, so only values they all allow count. Unpinned slices are ignored.\nfunction intersect(slices: Array<Array<Literal>>): Array<Literal> {\n const pinned = slices.filter((values) => values.length > 0)\n return pinned.reduce((acc, values) => acc.filter((value) => values.includes(value)), pinned[0] ?? [])\n}\n\n// A member is a `$ref`, or an intersection of the `$ref` and its narrowed discriminant.\nfunction memberName(member: ast.SchemaNode): string | undefined {\n if (member.type === 'ref') return member.name ?? undefined\n if (member.type === 'intersection') return member.members?.map(memberName).find(Boolean)\n return undefined\n}\n","import { ast } from '@kubb/kit'\nimport { isJsonMimeType, isOpenApi32, isReference } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport type { Document, MediaTypeObject, ReferenceObject, SchemaObject } from '../types.ts'\n\nconst streamMediaTypes = new Set(['application/jsonl', 'application/x-ndjson', 'application/json-seq', 'text/event-stream'])\n\n/**\n * Returns `true` for a media type read as a stream of items: SSE, JSON Lines, a `+json-seq` sequence, or any media type that declares `itemSchema`.\n */\nexport function isStream(contentType: string, mediaType: MediaTypeObject | null): boolean {\n const baseType = ast.mediaType.getBase(contentType)\n const streamed = streamMediaTypes.has(baseType) || (baseType.startsWith('application/') && baseType.endsWith('+json-seq'))\n return streamed || mediaType?.itemSchema !== undefined\n}\n\n/**\n * Whether the media type is `text/event-stream`, with or without parameters.\n */\nexport function isEventStream(contentType: string): boolean {\n return ast.mediaType.getBase(contentType) === 'text/event-stream'\n}\n\n/**\n * Replaces a `data` string that holds JSON with its `contentSchema`, so the event reads as parsed.\n */\nfunction withParsedData(schema: SchemaObject, refs: Refs): SchemaObject {\n const data = schema.properties?.data as SchemaObject | ReferenceObject | undefined\n const resolved = data && isReference(data) ? refs.resolve<SchemaObject>(data.$ref, { report: false }) : data\n if (!resolved?.contentSchema || !resolved.contentMediaType || !isJsonMimeType(resolved.contentMediaType)) return schema\n\n const parsed = { ...schema, properties: { ...schema.properties, data: resolved.contentSchema } }\n return parsed as SchemaObject\n}\n\n/**\n * Inlines a `$ref` event whose JSON `data` string needs its `contentSchema`, so the shared component keeps `data` as a string elsewhere.\n */\nfunction withParsedRef(schema: ReferenceObject, refs: Refs): SchemaObject | ReferenceObject {\n const resolved = refs.resolve<SchemaObject | ReferenceObject>(schema.$ref, { report: false })\n if (!resolved || isReference(resolved)) return schema\n const parsed = withParsedData(resolved, refs)\n return parsed === resolved ? schema : parsed\n}\n\n/**\n * Keywords next to `$ref` that only annotate it, so a reference that carries nothing else stays a reference.\n */\nconst REF_ANNOTATIONS = new Set(['$ref', 'summary', 'description', '$comment'])\n\n/**\n * Applies `extra` on top of `base` the way JSON Schema does: `properties` and `required` add up, other keywords of `extra` win.\n */\nfunction mergeSchemas(base: Pick<SchemaObject, 'properties' | 'required'>, extra: SchemaObject): SchemaObject {\n const required = [...new Set([...(Array.isArray(base.required) ? base.required : []), ...(Array.isArray(extra.required) ? extra.required : [])])]\n const merged = { type: 'object', ...base, ...extra, properties: { ...base.properties, ...extra.properties }, ...(required.length ? { required } : {}) }\n return merged as SchemaObject\n}\n\n/**\n * Normalizes the OpenAPI 3.2 `text/event-stream` item schema into one schema per event.\n * - Keywords next to a `$ref` apply to the referenced schema.\n * - Shared `properties` merge into each inline `oneOf`/`anyOf` member.\n * - A JSON `data` string becomes its `contentSchema`.\n */\nfunction toEventSchema(schema: SchemaObject | ReferenceObject, refs: Refs): SchemaObject | ReferenceObject {\n if (isReference(schema)) {\n const siblings = Object.fromEntries(Object.entries(schema).filter(([key]) => !REF_ANNOTATIONS.has(key)))\n const resolved = Object.keys(siblings).length ? refs.resolve<SchemaObject>(schema.$ref, { report: false }) : null\n return resolved ? toEventSchema(mergeSchemas(resolved, siblings as SchemaObject), refs) : withParsedRef(schema, refs)\n }\n const key = schema.oneOf?.length ? 'oneOf' : schema.anyOf?.length ? 'anyOf' : undefined\n if (!key) return withParsedData(schema, refs)\n\n const members = schema[key] as Array<SchemaObject | ReferenceObject>\n const { properties, required, ...rest } = schema\n // Shared properties cannot move into a `$ref` member, so they only merge when every member is inline.\n const merge = !!properties && !members.some(isReference)\n const shared = { properties, required }\n const event = {\n ...(merge ? rest : schema),\n [key]: members.map((member) => (isReference(member) ? withParsedRef(member, refs) : withParsedData(merge ? mergeSchemas(shared, member) : member, refs))),\n }\n return event as SchemaObject\n}\n\nconst SSE_FIELDS: ReadonlySet<string> = new Set(['event', 'id', 'retry', 'data'])\n\n/**\n * Property names of the schema and its `allOf` members, following `$ref`s, as one combined object declares them.\n */\nfunction collectFields(schema: SchemaObject | ReferenceObject, refs: Refs, seen: Set<string>): Array<string> {\n if (isReference(schema)) {\n if (seen.has(schema.$ref)) return []\n seen.add(schema.$ref)\n const resolved = refs.resolve<SchemaObject | ReferenceObject>(schema.$ref, { report: false })\n return resolved ? collectFields(resolved, refs, seen) : []\n }\n const members = (schema.allOf ?? []) as Array<SchemaObject | ReferenceObject>\n return [...Object.keys(schema.properties ?? {}), ...members.flatMap((member) => collectFields(member, refs, seen))]\n}\n\n/**\n * Whether the schema, following `$ref`s, or a `oneOf`/`anyOf` member of it is a whole Server-Sent Event: its combined\n * `allOf` fields declare `data`, or `event` with no field an event cannot carry. An `event` next to fields such as\n * `planet` is the payload's own property, sent as JSON in the `data:` line.\n */\nfunction declaresEventFields(schema: SchemaObject | ReferenceObject, refs: Refs, seen: Set<string>): boolean {\n if (isReference(schema)) {\n if (seen.has(schema.$ref)) return false\n seen.add(schema.$ref)\n const resolved = refs.resolve<SchemaObject | ReferenceObject>(schema.$ref, { report: false })\n return !!resolved && declaresEventFields(resolved, refs, seen)\n }\n const fields = collectFields(schema, refs, new Set(seen))\n if (fields.includes('data')) return true\n if (fields.includes('event')) return fields.every((field) => SSE_FIELDS.has(field))\n\n const members = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])] as Array<SchemaObject | ReferenceObject>\n return members.some((member) => declaresEventFields(member, refs, seen))\n}\n\n/**\n * Returns `'event'` when the item is a whole event, directly or in a composition member (see `declaresEventFields`), else `'data'`.\n */\nexport function getItemShape(schema: SchemaObject | ReferenceObject, refs: Refs): 'event' | 'data' {\n return declaresEventFields(schema, refs, new Set()) ? 'event' : 'data'\n}\n\n/**\n * Returns the raw item schema: `itemSchema`, or `schema` on `text/event-stream` as 3.0 and 3.1 documents write one event.\n */\nexport function getItemSchema({\n contentType,\n mediaType,\n refs,\n document,\n}: {\n contentType: string\n mediaType: MediaTypeObject | null\n refs: Refs\n document: Document\n}): SchemaObject | ReferenceObject | null {\n if (!mediaType || !isStream(contentType, mediaType)) return null\n // Below 3.2 there is no `itemSchema`, so `schema` on an event stream is the event by convention; from 3.2 it is the whole stream.\n const raw = mediaType.itemSchema ?? (isEventStream(contentType) && !isOpenApi32(document) ? mediaType.schema : undefined)\n if (!raw) return null\n\n return isEventStream(contentType) ? toEventSchema(raw, refs) : raw\n}\n","import { escapePointerToken } from '@internals/utils'\nimport type { ast } from '@kubb/kit'\nimport { collectSiblingProperties } from '../emit/converters/composition.ts'\nimport { getBinaryFallbackSchema, isReference, pickExtensions } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport { scanSchema } from '../schemaDiagnostics.ts'\nimport type { Document, EncodingObject, ExampleObject, MediaTypeObject, ReferenceObject, SchemaObject } from '../types.ts'\nimport { getItemSchema, getItemShape, isEventStream, isStream } from './mediaType.ts'\n\nconst PARAMETER_STYLES = new Set(['matrix', 'label', 'form', 'simple', 'spaceDelimited', 'pipeDelimited', 'deepObject', 'cookie'])\n\nexport function pickStyleFields({ style, explode, allowReserved }: { style?: string; explode?: boolean; allowReserved?: boolean }): {\n style?: ast.ParameterStyle\n explode?: boolean\n allowReserved?: boolean\n} {\n return {\n ...(style !== undefined && PARAMETER_STYLES.has(style) ? { style: style as ast.ParameterStyle } : {}),\n ...(explode !== undefined ? { explode } : {}),\n ...(allowReserved !== undefined ? { allowReserved } : {}),\n }\n}\n\nexport function getEncodingFields({\n encoding,\n prefixEncoding,\n itemEncoding,\n}: Pick<EncodingObject, 'encoding' | 'prefixEncoding' | 'itemEncoding'>): Pick<ast.EncodingNode, 'encoding' | 'prefixEncoding' | 'itemEncoding'> {\n const entries = Object.entries(encoding ?? {}).flatMap(([property, entry]) => {\n const node = toEncodingNode(entry)\n return Object.keys(node).length ? [[property, node] as const] : []\n })\n const item = itemEncoding && toEncodingNode(itemEncoding)\n\n return {\n ...(entries.length && { encoding: Object.fromEntries(entries) }),\n // Entries keep their position, so an empty one still stands for its part.\n ...(prefixEncoding?.length && { prefixEncoding: prefixEncoding.map(toEncodingNode) }),\n ...(item && Object.keys(item).length && { itemEncoding: item }),\n }\n}\n\nfunction toEncodingNode({ contentType, encoding, prefixEncoding, itemEncoding, ...rest }: EncodingObject): ast.EncodingNode {\n return {\n ...(contentType !== undefined && { contentType }),\n ...pickStyleFields(rest),\n ...getEncodingFields({ encoding, prefixEncoding, itemEncoding }),\n }\n}\n\n/**\n * The examples of a media type or a parameter. Named `examples` win over a single `example`.\n */\nexport function getExamples({ example, examples }: { example?: unknown; examples?: Record<string, unknown> }, refs: Refs): Pick<ast.ContentNode, 'examples'> {\n const named = Object.entries(examples ?? {}).flatMap(([name, entry]) => {\n const resolved = refs.deref<ExampleObject>(entry)\n if (!resolved) return []\n const { summary, description, dataValue, value, serializedValue } = resolved\n const data = dataValue !== undefined ? dataValue : value\n return [\n {\n name,\n ...(typeof summary === 'string' && { summary }),\n ...(typeof description === 'string' && { description }),\n ...(data !== undefined && { value: data }),\n ...(typeof serializedValue === 'string' && { serializedValue }),\n },\n ]\n })\n if (named.length) return { examples: named }\n\n return example !== undefined ? { examples: [{ value: example }] } : {}\n}\n\nexport type ContentMap = Record<string, MediaTypeObject | ReferenceObject> | undefined\n\n/**\n * Returns the media type entry for `contentType`, resolving a `$ref` into `components.mediaTypes`. `null` when absent.\n */\nexport function getMediaType({ content, contentType, refs }: { content: ContentMap; contentType: string | undefined; refs: Refs }): MediaTypeObject | null {\n return contentType ? refs.deref<MediaTypeObject>(content?.[contentType]) : null\n}\n\ntype BodySchemaContext = {\n content: ContentMap\n contentType: string | undefined\n refs: Refs\n document: Document\n}\n\n/**\n * Returns the schema for one media type of a `content` map, before its `$ref` is resolved, with the binary fallback\n * for an emptied non-JSON entry. For a stream this is the item schema, so `schema: string` next to `itemSchema` types one item.\n */\nfunction getDeclaredBodySchema({ content, contentType, refs, document }: BodySchemaContext): SchemaObject | null {\n const entry = getMediaType({ content, contentType, refs })\n if (!contentType || !entry) return null\n\n const schema = getItemSchema({ contentType, mediaType: entry, refs, document }) ?? entry.schema\n // A declared `itemSchema`, even an empty one, is a schema of its own and not an emptied binary entry.\n const binary = entry.itemSchema ? undefined : getBinaryFallbackSchema(contentType, schema)\n return binary ?? (schema as SchemaObject | undefined) ?? null\n}\n\nfunction getStreamField({\n contentType,\n mediaType,\n refs,\n document,\n node,\n}: {\n contentType: string\n mediaType: MediaTypeObject | null\n refs: Refs\n document: Document\n node: ast.SchemaNode\n}): Pick<ast.ContentNode, 'stream'> {\n if (!isStream(contentType, mediaType)) return {}\n const raw = getItemSchema({ contentType, mediaType, refs, document })\n\n return {\n stream: {\n ...(raw ? { schema: node } : {}),\n ...(raw && isEventStream(contentType) ? { shape: getItemShape(raw, refs) } : {}),\n },\n }\n}\n\nfunction schemaKeyword(mediaType: MediaTypeObject | null): 'itemSchema' | 'schema' {\n return mediaType?.itemSchema ? 'itemSchema' : 'schema'\n}\n\n// Follows a `$ref` into `components.mediaTypes`, so a diagnostic lands on the source.\nfunction mediaTypePointer(content: ContentMap, contentType: string, fallback: string): string {\n const entry = content?.[contentType]\n return isReference(entry) ? entry.$ref : fallback\n}\n\nexport type ReadWriteFlag = 'readOnly' | 'writeOnly'\n\n// Reads the properties of the schema, its `$ref` target and its `allOf` members.\nfunction collectPropertyKeysByFlag({ schema, flag, refs }: { schema: SchemaObject | null; flag: ReadWriteFlag; refs: Refs }): Array<string> | null {\n if (!schema) return null\n\n const keys = Object.entries(collectSiblingProperties([schema], refs)).flatMap(([key, prop]) => (hasFlag({ prop, flag, refs }) ? [key] : []))\n return keys.length ? keys : null\n}\n\n// The flag counts next to a property `$ref` and on its target.\nfunction hasFlag({ prop, flag, refs }: { prop: unknown; flag: ReadWriteFlag; refs: Refs }): boolean {\n if (!prop || typeof prop !== 'object') return false\n if ((prop as Record<string, unknown>)[flag]) return true\n const target = isReference(prop) ? refs.resolve<SchemaObject>(prop.$ref, { report: false }) : null\n return !!target?.[flag]\n}\n\nexport type ContentEntryOptions = {\n content: ContentMap\n contentType: string | undefined\n /**\n * Pointer of the `content` map, used when the media type entry is not a `$ref`.\n */\n contentPointer: string\n /**\n * Properties a request (`readOnly`) or a response (`writeOnly`) leaves out.\n */\n omit: ReadWriteFlag\n refs: Refs\n document: Document\n}\n\nexport type ContentEntry = Omit<ast.ContentNode, 'kind' | 'contentType'>\n\n/**\n * Builds the fields of a request or response content node for one media type of a `content` map.\n * `parse` turns the body schema into a node, and returning `null` drops the entry.\n */\nexport function parseContentEntry(options: ContentEntryOptions & { parse: (schema: SchemaObject | null) => ast.SchemaNode }): ContentEntry\nexport function parseContentEntry(options: ContentEntryOptions & { parse: (schema: SchemaObject | null) => ast.SchemaNode | null }): ContentEntry | null\nexport function parseContentEntry({\n content,\n contentType,\n contentPointer,\n omit,\n refs,\n document,\n parse,\n}: ContentEntryOptions & { parse: (schema: SchemaObject | null) => ast.SchemaNode | null }): ContentEntry | null {\n const declared = getDeclaredBodySchema({ content, contentType, refs, document })\n const schema = declared ? refs.derefKeepingRef(declared) : null\n const node = parse(schema)\n if (!node) return null\n const mediaType = getMediaType({ content, contentType, refs })\n if (schema && contentType) {\n scanSchema(node, `${mediaTypePointer(content, contentType, `${contentPointer}/${escapePointerToken(contentType)}`)}/${schemaKeyword(mediaType)}`)\n }\n\n return {\n schema: node,\n keysToOmit: collectPropertyKeysByFlag({ schema: declared, flag: omit, refs }),\n ...(mediaType && getEncodingFields(mediaType)),\n ...(mediaType && getExamples(mediaType, refs)),\n ...(contentType ? getStreamField({ contentType, mediaType, refs, document, node }) : {}),\n extensions: pickExtensions(mediaType),\n }\n}\n","import { escapePointerToken } from '@internals/utils'\nimport { pascalCase } from '@kubb/core'\nimport { ast, macroEnumName } from '@kubb/kit'\nimport { pickExtensions } from '../oas.ts'\nimport type { OperationParseContext } from '../operation.ts'\nimport { scanSchema } from '../schemaDiagnostics.ts'\nimport type { MediaTypeObject, ParameterObject, SchemaObject } from '../types.ts'\nimport { getEncodingFields, getExamples, getMediaType, pickStyleFields } from './content.ts'\n\nexport type ParameterContext = Pick<OperationParseContext, 'options' | 'parseSchema' | 'refs'> & {\n param: ParameterObject\n pointer: string\n parentName?: string\n}\ntype ResolvedMedia = { contentType?: string; mediaType: MediaTypeObject | null }\n\n// An inline enum gets `enumSuffix`, the same as an inline enum on an object property.\nfunction withEnumName({\n schema,\n param,\n parentName,\n options,\n}: Pick<ParameterContext, 'param' | 'parentName' | 'options'> & { schema: ast.SchemaNode }): ast.SchemaNode {\n if (!parentName || !param.name) return schema\n return ast.macro.apply(schema, [macroEnumName({ parentName, propName: param.name, enumSuffix: options.enumSuffix })], { depth: 'shallow' })\n}\n\nfunction parseParameterSchema(ctx: ParameterContext & ResolvedMedia): ast.SchemaNode {\n const { param, pointer, parentName, options, parseSchema, contentType, mediaType } = ctx\n const rawSchema = param.schema ?? mediaType?.schema\n const schemaName = parentName && param.name ? pascalCase(`${parentName} ${param.name}`) : undefined\n const parsed = rawSchema ? parseSchema({ schema: rawSchema as SchemaObject, name: schemaName }) : ast.factory.createSchema({ type: options.unknownType })\n const schema = withEnumName({ schema: parsed, param, parentName, options })\n if (rawSchema) scanSchema(schema, contentType ? `${pointer}/content/${escapePointerToken(contentType)}/schema` : `${pointer}/schema`)\n return schema\n}\n\n/**\n * Converts one parameter into a `ParameterNode`, naming an inline schema after the operation and the parameter.\n */\nexport function parseParameter(ctx: ParameterContext): ast.ParameterNode {\n const { param, pointer, refs } = ctx\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 mediaType = getMediaType({ content: param.content, contentType, refs })\n const schema = parseParameterSchema({ ...ctx, contentType, mediaType })\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 ...pickStyleFields(param),\n ...(contentType !== undefined ? { contentType } : {}),\n ...(mediaType?.encoding && { encoding: getEncodingFields({ encoding: mediaType.encoding }).encoding }),\n ...getExamples(mediaType ?? param, refs),\n ...(param.deprecated && { deprecated: true }),\n ...(param.allowEmptyValue && { allowEmptyValue: true }),\n extensions: pickExtensions(param),\n })\n}\n\n/**\n * Spreads a form-encoded OpenAPI 3.2 `querystring` object into one query parameter per property. Another content type stays whole.\n */\nexport function spreadQuerystring(param: ast.ParameterNode): Array<ast.ParameterNode> {\n if (param.in !== 'querystring') return [param]\n const schema = ast.ref.getSchema(param.schema)\n const formEncoded = !param.contentType || ast.mediaType.getBase(param.contentType) === 'application/x-www-form-urlencoded'\n if (schema.type !== 'object' || !formEncoded) return [param]\n return schema.properties.map((property) => {\n const { style, explode, allowReserved } = param.encoding?.[property.name] ?? {}\n return ast.factory.createParameter({\n ...(param.pointer ? { pointer: param.pointer } : {}),\n name: property.name,\n in: 'query',\n schema: property.schema,\n required: param.required && property.required,\n ...(style !== undefined && { style }),\n ...(explode !== undefined && { explode }),\n ...(allowReserved !== undefined && { allowReserved }),\n ...(param.extensions && { extensions: param.extensions }),\n })\n })\n}\n","import { escapePointerToken } from '@internals/utils'\nimport type { OpenAPIV3_1 } from 'openapi-types'\nimport { pascalCase } from '@kubb/core'\nimport { ast, Diagnostics, Url } from '@kubb/kit'\nimport { SUPPORTED_METHODS } from './constants.ts'\nimport type { ParseFn } from './emit/parseSchema.ts'\nimport { parseContentEntry } from './model/content.ts'\nimport { parseParameter, spreadQuerystring } from './model/parameters.ts'\nimport { toAuthRequirements } from './model/security.ts'\nimport { toInputServers } from './model/server.ts'\nimport { getExternalDocs, isReference, pickExtensions, pickStrings } from './oas.ts'\nimport type { Refs } from './refs.ts'\nimport type { ContentType, Document, OperationObject, ParameterObject, PathItemObject, ReferenceObject, ResponseObject } from './types.ts'\nimport type { ParserOptions } from './parserOptions.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\nexport type OperationContext = {\n operation: Operation\n refs: Refs\n}\n\n/** What `parseOperation` needs beyond the operation. */\nexport type OperationParseContext = {\n document: Document\n refs: Refs\n contentType?: ContentType\n options: 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 JSON pointer, under `additionalOperations` for an OpenAPI 3.2 method outside the fixed fields.\n */\nfunction getOperationPointer({ path, method }: Pick<Operation, 'path' | 'method'>): string {\n const pathPointer = `#/paths/${escapePointerToken(path)}`\n\n return SUPPORTED_METHODS.has(method.toLowerCase())\n ? `${pathPointer}/${method.toLowerCase()}`\n : `${pathPointer}/additionalOperations/${escapePointerToken(method)}`\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 */\nfunction 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 */\nfunction 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 */\nfunction getRequestBody({ operation, refs }: OperationContext): OpenAPIV3_1.RequestBodyObject | null {\n return refs.deref<OpenAPIV3_1.RequestBodyObject>(operation.schema.requestBody)\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 || [], getOperationPointer(operation))\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\nfunction getLinks(links: unknown, refs: Refs): Record<string, ast.ResponseLink> | undefined {\n const entries = Object.entries(links ?? {}).flatMap(([name, value]) => {\n const link = refs.deref<OpenAPIV3_1.LinkObject>(value)\n if (!link) return []\n const server = link.server ? toInputServers([link.server])[0] : undefined\n const node: ast.ResponseLink = {\n ...pickStrings(link, ['operationId', 'operationRef', 'description']),\n ...(link.parameters && { parameters: link.parameters }),\n ...('requestBody' in link && { requestBody: link.requestBody }),\n ...(server && { server }),\n }\n return [[name, node] as const]\n })\n return entries.length ? Object.fromEntries(entries) : undefined\n}\n\n/**\n * Builds an `Operation` for every supported HTTP method and every OpenAPI 3.2 `additionalOperations` entry on\n * every path, in document order. `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 for (const [method, schema] of Object.entries(pathItem.additionalOperations ?? {})) {\n // The spec forbids a fixed method here; such an entry would also take the fixed operation's pointer.\n if (schema && typeof schema === 'object' && !SUPPORTED_METHODS.has(method.toLowerCase())) {\n operations.push({ path, method, schema, pathItem })\n }\n }\n }\n\n return withUniqueOperationIds(operations)\n}\n\n// Names come from `pascalCase(operationId)`, so `getPets_2` and `getPets2` would clash too.\nfunction suffixed(id: string, taken: Set<string>, counts: Map<string, number>): string {\n const count = (counts.get(id) ?? 1) + 1\n counts.set(id, count)\n const candidate = `${id}_${count}`\n return taken.has(pascalCase(candidate)) ? suffixed(id, taken, counts) : candidate\n}\n\n// Two operations with one id would share every generated name and file.\nfunction withUniqueOperationIds(operations: Array<Operation>): Array<Operation> {\n // Declared ids are reserved first, so a suffix never takes an id a later operation declares.\n const taken = new Set(\n operations.flatMap(({ schema }) => (typeof schema.operationId === 'string' && schema.operationId ? [pascalCase(schema.operationId)] : [])),\n )\n const claimed = new Set<string>()\n const counts = new Map<string, number>()\n\n return operations.map((operation) => {\n const operationId = getOperationId(operation)\n const name = pascalCase(operationId)\n if (!claimed.has(name)) {\n claimed.add(name)\n taken.add(name)\n return operation\n }\n\n const unique = suffixed(operationId, taken, counts)\n taken.add(pascalCase(unique))\n claimed.add(pascalCase(unique))\n Diagnostics.report({\n code: Diagnostics.code.duplicateOperationId,\n severity: 'warning',\n message: `operationId \"${operationId}\" of ${operation.method.toUpperCase()} ${operation.path} is already used, so it is renamed to \"${unique}\".`,\n help: 'Give each operation its own `operationId`.',\n location: { kind: 'operation', pointer: getOperationPointer(operation) },\n })\n\n return { ...operation, schema: { ...operation.schema, operationId: unique } }\n })\n}\n\ntype RequestBodyContext = { operation: Operation; operationName: string | undefined; pointer: string; ctx: OperationParseContext }\ntype ResponseContext = RequestBodyContext & { key: string }\n\nfunction parseRequestBody({ operation, operationName, pointer, ctx }: RequestBodyContext): Omit<ast.RequestBodyNode, 'kind'> | undefined {\n const { document, refs, contentType, parseSchema } = ctx\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 if (!body) return undefined\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 entry = parseContentEntry({\n content: body.content,\n contentType: ct,\n contentPointer: `${pointer}/requestBody/content`,\n omit: 'readOnly',\n refs,\n document,\n parse: (schema) => (schema ? ast.schema.applyOptionality(parseSchema({ schema, name: requestBodyName }), bodyRequired) : null),\n })\n return entry ? [ast.factory.createContent({ contentType: ct, ...entry })] : []\n })\n if (content.length === 0 && !body.description) return undefined\n\n return {\n pointer: `${pointer}/requestBody`,\n description: body.description,\n required: bodyRequired || undefined,\n content: content.length > 0 ? content : undefined,\n extensions: pickExtensions(body),\n }\n}\n\nfunction pickDoc({ operation, key }: { operation: Operation; 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// The spec ignores a `Content-Type` header, since `content` already names the media type.\nfunction parseResponseHeaders({\n response,\n responsePointer,\n responseName,\n ctx: { options, parseSchema, refs },\n}: Pick<ResponseContext, 'ctx'> & { response: ResponseObject | null; responsePointer: string; responseName: string | undefined }): Array<ast.ParameterNode> {\n return Object.entries(response?.headers ?? {}).flatMap(([name, value]) => {\n const header = name.toLowerCase() === 'content-type' ? null : refs.deref<OpenAPIV3_1.HeaderObject>(value)\n if (!header) return []\n const param: ParameterObject = { ...header, name, in: 'header' }\n return [parseParameter({ param, pointer: `${responsePointer}/headers/${escapePointerToken(name)}`, parentName: responseName, options, parseSchema, refs })]\n })\n}\n\nfunction parseResponse({ operation, key, operationName, pointer, ctx }: ResponseContext): ast.ResponseNode {\n const { document, refs, contentType, options, parseSchema } = ctx\n const response = getResponseByStatusCode({ operation, refs, statusCode: key })\n const { content, summary, description, links: rawLinks }: Partial<ResponseObject> = response ?? {}\n // A range such as `2XX` is written `2xx`. Pointers keep the key as the document spells it.\n const statusCode = key.toLowerCase() as ast.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 const responsePointer = `${pointer}/responses/${key}`\n\n const parseEntrySchema = (ct?: string) =>\n parseContentEntry({\n content,\n contentType: ct,\n contentPointer: `${responsePointer}/content`,\n omit: 'writeOnly',\n refs,\n document,\n parse: (schema) =>\n schema && Object.keys(schema).length > 0 ? parseSchema({ schema, name: responseName }) : ast.factory.createSchema({ type: options.emptySchemaType }),\n })\n\n const declaredContentTypes = Object.keys(content ?? {})\n // The adapter `contentType` only narrows a response that has a body.\n const responseContentTypes = contentType && declaredContentTypes.length ? [contentType] : declaredContentTypes\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 // Its empty `contentType` says there is no body, so plugins do not read a `text/*` request type as a `string` response.\n if (responseContent.length === 0) {\n responseContent.push(ast.factory.createContent({ contentType: '', ...parseEntrySchema(contentType) }))\n }\n\n const headers = parseResponseHeaders({ response, responsePointer, responseName, ctx })\n const links = getLinks(rawLinks, refs)\n\n return ast.factory.createResponse({\n pointer: responsePointer,\n statusCode,\n summary,\n description,\n content: responseContent,\n ...(headers.length && { headers }),\n ...(links && { links }),\n extensions: pickExtensions(response),\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 { document, refs, options, parseSchema } = ctx\n const operationId = getOperationId(operation)\n const operationName = operationId ? pascalCase(operationId) : undefined\n const pointer = getOperationPointer(operation)\n const parameters = getParameters({ operation, refs })\n .map((entry) => parseParameter({ options, parseSchema, refs, ...entry, parentName: operationName }))\n .flatMap(spreadQuerystring)\n\n const requestBody = parseRequestBody({ operation, operationName, pointer, ctx })\n const responses = getResponseStatusCodes(operation).map((key) => parseResponse({ operation, key, operationName, pointer, ctx }))\n\n // An empty operation `servers` list overrides nothing, so the path item's servers still apply.\n const servers = operation.schema.servers?.length ? operation.schema.servers : operation.pathItem.servers\n const auth = toAuthRequirements(operation.schema.security ?? document.security, document)\n\n return ast.factory.createOperation({\n pointer,\n operationId,\n protocol: 'http',\n // An `additionalOperations` key is sent with its own capitalization, so only the fixed lowercase fields are uppercased.\n method: (SUPPORTED_METHODS.has(operation.method) ? operation.method.toUpperCase() : operation.method) as ast.HttpMethod,\n path: operation.path,\n tags: Array.isArray(operation.schema.tags) ? operation.schema.tags.map(String) : [],\n summary: pickDoc({ operation, key: 'summary' }) || undefined,\n description: pickDoc({ operation, key: 'description' }) || undefined,\n deprecated: operation.schema.deprecated || undefined,\n externalDocs: getExternalDocs(operation.schema.externalDocs),\n parameters,\n requestBody,\n responses,\n extensions: pickExtensions(operation.schema),\n ...(servers && { servers: toInputServers(servers) }),\n ...(auth && { auth }),\n })\n}\n\n/** Renames path parameters and their `{placeholder}` to the camelCase names from {@link Url.toParamNames}. */\nexport function camelCasePathParams(node: ast.OperationNode): ast.OperationNode {\n // A `matrix` value is sent as `;name=value`, so renaming would change the request.\n if (!node.path || node.parameters.some((param) => param.in === 'path' && param.style === 'matrix')) return node\n const names = Url.toParamNames(node.path)\n\n return {\n ...node,\n path: node.path.replace(/\\{([^}]+)\\}/g, (_match, name: string) => `{${names.get(name) ?? name}}`),\n parameters: node.parameters.map((param) => (param.in === 'path' && names.has(param.name) ? { ...param, name: names.get(param.name)! } : param)),\n }\n}\n","import { ast } from '@kubb/kit'\nimport { enumDescriptionKeys, enumExtensionKeys, getFormatType, numericFormats } from '../../constants.ts'\nimport { pickExtensions } from '../../oas.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(\n schema: SchemaObject,\n): Pick<ast.NumberSchemaNode, 'min' | 'max' | 'exclusive' | 'exclusiveMinimum' | 'exclusiveMaximum' | 'multipleOf'> {\n const exclusiveMinimum = typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined\n const exclusiveMaximum = typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : undefined\n const hasExclusive = exclusiveMinimum !== undefined || exclusiveMaximum !== undefined\n return {\n min: schema.minimum,\n max: schema.maximum,\n ...(hasExclusive && {\n exclusive: { ...(exclusiveMinimum !== undefined && { min: exclusiveMinimum }), ...(exclusiveMaximum !== undefined && { max: exclusiveMaximum }) },\n }),\n // shortcut: the pre-`exclusive` names, kept so plugins that read them keep working, remove them in Kubb v6.\n exclusiveMinimum,\n exclusiveMaximum,\n multipleOf: schema.multipleOf,\n }\n}\n\n/**\n * Whether an enum value fits the schema's numeric bounds.\n */\nfunction isWithinBounds({ value, schema }: { value: unknown; schema: SchemaObject }): boolean {\n if (typeof value !== 'number') return true\n const { min, max, exclusive, multipleOf } = getNumericConstraints(schema)\n if (min !== undefined && value < min) return false\n if (max !== undefined && value > max) return false\n if (exclusive?.min !== undefined && value <= exclusive.min) return false\n if (exclusive?.max !== undefined && value >= exclusive.max) return false\n // The tolerance keeps float quotients such as `0.3 / 0.1` from failing.\n if (multipleOf !== undefined && Math.abs(value / multipleOf - Math.round(value / multipleOf)) > 1e-9) return false\n return true\n}\n\n/**\n * Builds the test for which `enum` entries stay: not `null`, and within the numeric bounds. `enum` and the bounds\n * apply together, so a value outside them is never valid. Bounds that exclude every value are a spec error, so\n * they are ignored rather than leaving an empty enum.\n */\nfunction createEnumMemberFilter(schema: SchemaObject): (value: unknown) => boolean {\n const boundsApply = schema.enum!.some((value) => value !== null && isWithinBounds({ value, schema }))\n return (value) => value !== null && (!boundsApply || isWithinBounds({ value, schema }))\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 extensions: pickExtensions(schema),\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 = getFormatType(schema.format!)\n if (specialType === 'blob') return convertBlob(context)\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 Exclude<ast.ScalarSchemaType, 'blob'>,\n ...(hasLength ? { min: schema.minLength, max: schema.maxLength } : {}),\n ...(isNumeric ? getNumericConstraints(schema) : {}),\n })\n}\n\n/**\n * Primitive of an enum's members. Without a `type`, the values decide: `{ enum: [0, 1] }` is a number enum.\n */\nfunction getEnumPrimitive(type: string | undefined, values: Array<string | number | boolean>): 'number' | 'boolean' | 'string' {\n if (type === 'boolean') return 'boolean'\n if (type === 'number' || type === 'integer') return 'number'\n if (type !== undefined || values.length === 0) return 'string'\n if (values.every((value) => typeof value === 'boolean')) return 'boolean'\n if (values.every((value) => typeof value === 'number')) return 'number'\n\n return 'string'\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 isMember = createEnumMemberFilter(schema)\n const filteredValues = schema.enum!.filter(isMember) 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 uniqueValues = [...new Set(filteredValues)]\n const primitive = getEnumPrimitive(type, uniqueValues)\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 // Names and descriptions run parallel to `enum`, so drop the slots of the removed values to keep each name with its value.\n const memberSlots = (list: unknown) => (Array.isArray(list) ? list.filter((_, index) => isMember(schema.enum![index])) : undefined)\n const rawEnumNames = extensionKey ? (memberSlots((schema as Record<string, unknown>)[extensionKey]) as Array<string | number> | undefined) : undefined\n const rawEnumDescriptions = descriptionKey ? (memberSlots((schema as Record<string, unknown>)[descriptionKey]) as Array<string> | undefined) : undefined\n const seenNames = new Set<string>()\n const seenValues = new Set<string | number | boolean>()\n\n return createNode(ctx, {\n type: 'enum',\n primitive,\n // Pair each value with its name before duplicates go, so a later value keeps its own name.\n namedEnumValues: filteredValues\n .map((value, index) => ({\n name: String(rawEnumNames?.[index] ?? value),\n value,\n primitive,\n description: rawEnumDescriptions?.[index],\n }))\n .filter((entry) => {\n if (seenValues.has(entry.value) || seenNames.has(entry.name)) return false\n seenValues.add(entry.value)\n seenNames.add(entry.name)\n return true\n }),\n })\n}\n\n/**\n * Converts an `enum` with a handled `format` into a union of its literal values. A named enum node would rename\n * the exported type (`Status` becomes `StatusKey`), so the union keeps the name the format type had.\n */\nexport function convertFormattedEnum(context: ConvertContext): ast.SchemaNode {\n const { schema, nullable } = context\n const values = [...new Set(schema.enum!.filter(createEnumMemberFilter(schema)))] as Array<string | number | boolean>\n\n return createNode(\n { ...context, nullable: nullable || schema.enum!.includes(null) || undefined },\n {\n type: 'union',\n members: values.map((value) => ast.factory.createSchema({ type: 'enum', primitive: getPrimitiveType(typeof value), enumValues: [value] })),\n },\n )\n}\n\nfunction getStringContent({ schema, parse }: ConvertContext): Pick<ast.StringSchemaNode, 'content'> {\n const { contentMediaType: mediaType, contentEncoding: encoding, contentSchema } = schema\n if (mediaType === undefined && encoding === undefined && !contentSchema) return {}\n return {\n content: {\n ...(mediaType !== undefined && { mediaType }),\n ...(encoding !== undefined && { encoding }),\n ...(contentSchema && { schema: parse({ schema: contentSchema as SchemaObject }) }),\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 ...getStringContent(context),\n })\n}\n\n/** Converts a binary schema into a `BlobSchemaNode`, keeping `contentMediaType` and `contentEncoding`. */\nexport function convertBlob(context: ConvertContext): ast.SchemaNode {\n return createNode(context, { type: 'blob', primitive: 'string', ...getStringContent(context) })\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\nfunction getContains(schema: SchemaObject, parse: ConvertContext['parse']): Pick<ast.ArraySchemaNode, 'contains'> {\n const { contains, minContains, maxContains } = schema\n if (!contains || typeof contains !== 'object') return {}\n return {\n contains: {\n schema: parse({ schema: contains as SchemaObject }),\n ...(typeof minContains === 'number' && { min: minContains }),\n ...(typeof maxContains === 'number' && { max: maxContains }),\n },\n }\n}\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.macro.apply(node, [macro], { depth: 'shallow' })\n const tupleNode = ast.schema.narrow(named, 'tuple')\n if (tupleNode?.items) {\n const namedItems = tupleNode.items.map((item) => ast.macro.apply(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, document }: 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, document)\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 ?? schema.unevaluatedProperties\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 min: schema.minProperties,\n max: schema.maxProperties,\n // shortcut: the pre-`min`/`max` names, kept so plugins that read them keep working, remove them in Kubb v6.\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.macro.apply(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 prefixItems = schema.prefixItems ?? []\n // A `maxItems` no larger than the `prefixItems` count closes the tuple, like `items: false`.\n const isClosed = schema.maxItems !== undefined && schema.maxItems <= prefixItems.length\n const tupleItems = (isClosed ? prefixItems.slice(0, schema.maxItems) : prefixItems).map((item) => parse({ schema: item as SchemaObject }))\n const tail = isClosed ? false : (schema.items ?? schema.unevaluatedItems)\n // items: false closes the tuple; absent/true widens the tail to unknownType.\n const rest =\n tail === false ? undefined : !tail || tail === true ? ast.factory.createSchema({ type: options.unknownType }) : parse({ schema: tail 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 ...getContains(schema, parse),\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 ...getContains(schema, parse),\n },\n )\n}\n","import type { ast } from '@kubb/kit'\nimport { enumExtensionKeys, getFormatType } from '../constants.ts'\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 {\n convertBlob,\n convertConst,\n convertEnum,\n convertFormat,\n convertFormattedEnum,\n convertNumeric,\n convertString,\n createNullNode,\n} from './converters/scalar.ts'\nimport { convertArray, convertObject, convertTuple } from './converters/structural.ts'\nimport { createNode } from './createNode.ts'\nimport { isHandledFormat, resolveDateTypeValue } from './schemaShape.ts'\nimport type { ParserOptions } from '../parserOptions.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: 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 */\nexport type SchemaRule = {\n /**\n * Returns `true` when this rule is responsible for the given context.\n */\n match: (context: ConvertContext) => boolean\n /**\n * Produces a node for the context.\n */\n convert: (context: ConvertContext) => ast.SchemaNode\n}\n\n/**\n * Whether the `format` rule owns the schema: a handled format, and for a date format a `dateType` that is not `false`.\n */\nfunction matchesFormat({ schema, options }: ConvertContext): boolean {\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\n/**\n * Whether the format prints as a plain `string` or `number`, so narrowing it to literal values cannot break callers.\n * `Date`, `bigint` and `Blob` outputs keep the format.\n */\nfunction formatPrintsPlainType({ schema, options, type }: ConvertContext): boolean {\n const format = schema.format!\n if (format === 'date-time' || format === 'date' || format === 'time') return resolveDateTypeValue(options.dateType, format) !== 'date'\n if ((format === 'int64' || format === 'uint64') && type !== 'string') return options.integerType !== 'bigint'\n return getFormatType(format) !== 'blob'\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 // A formatted enum keeps its values as a union of literals, so its type keeps its name. With `x-enumNames`\n // or `x-enum-varnames` it becomes a named enum, the same as an enum without a `format`.\n match: (ctx) => ctx.type !== 'array' && !!ctx.schema.enum?.some((value) => value !== null) && matchesFormat(ctx) && formatPrintsPlainType(ctx),\n convert: (ctx) => (enumExtensionKeys.some((key) => key in ctx.schema) ? convertEnum(ctx) : convertFormattedEnum(ctx)),\n },\n { match: matchesFormat, convert: convertFormat },\n { match: ({ schema }) => isBinary(schema), convert: convertBlob },\n {\n match: ({ schema, type }) => !type && !schema.enum?.length && (schema.contentMediaType !== undefined || schema.contentSchema !== undefined),\n convert: convertString,\n },\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 { ast } from '@kubb/kit'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { isAnnotationMember } from './emit/converters/composition.ts'\nimport { createNode } from './emit/createNode.ts'\nimport { type ConvertContext, type ParseFn, 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'\nimport type { ParserOptions } from './parserOptions.ts'\n\n/**\n * Parser context holding the raw OpenAPI document and its `$ref` service.\n */\nexport type SchemaParserOptions = {\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<ParserOptions>\n}\n\n/**\n * `unevaluated*` also sees what composition siblings evaluate, so with such a sibling it is dropped to keep the schema open.\n */\nfunction hasUnevaluatedSiblings(schema: SchemaObject): boolean {\n if (schema.unevaluatedProperties === undefined && schema.unevaluatedItems === undefined) return false\n return [schema.allOf, schema.anyOf, schema.oneOf, schema.if, schema.dependentSchemas, schema.$ref].some((value) => value !== undefined)\n}\n\nfunction isKeyList(value: unknown): value is Array<string> {\n return Array.isArray(value) && value.length > 0 && value.every((name) => typeof name === 'string')\n}\n\n/**\n * The schema converter bound to one OpenAPI document: `parse` dispatches each schema through the\n * ordered `schemaRules` table, with the parser options merged once.\n *\n * @internal\n */\nexport class SchemaParser {\n readonly #document: Document\n readonly #refs: Refs\n readonly #renames: ReadonlyMap<string, string> | undefined\n readonly #options: ParserOptions\n // The key lists of the presence checks `#requireKeys` builds, so two entries that check the same keys compare equal.\n readonly #presenceKeys = new WeakMap<ast.SchemaNode, string>()\n\n constructor(ctx: SchemaParserOptions) {\n this.#document = ctx.document\n this.#refs = ctx.refs\n this.#renames = ctx.renames\n this.#options = { ...DEFAULT_PARSER_OPTIONS, ...ctx.options }\n }\n\n /**\n * Converts one OpenAPI schema into a `SchemaNode`, through the first matching rule of `schemaRules`.\n */\n parse: ParseFn = ({ schema, name }) => {\n const options = this.#options\n // A JSON Schema boolean: `true` accepts any value and `false` accepts none.\n if (typeof schema === 'boolean') {\n return ast.factory.createSchema({ type: schema ? (options.emptySchemaType as ast.ScalarSchemaType) : 'never', name: name ?? undefined })\n }\n\n const flattenedSchema = flattenSchema(schema)\n if (flattenedSchema !== schema) {\n // `flattenSchema` keeps the first value of each keyword, so the conditionals of the schema and of every member are read on their own.\n const { if: _if, then: _then, else: _else, dependentRequired: _required, dependentSchemas: _schemas, ...shape } = flattenedSchema\n return this.#withConditionals(this.parse({ schema: shape, name }), [schema, ...(schema.allOf as Array<SchemaObject>)])\n }\n if (hasUnevaluatedSiblings(schema)) {\n const { unevaluatedProperties: _properties, unevaluatedItems: _items, ...open } = schema\n return this.parse({ schema: open, name })\n }\n\n return this.#convert({ schema, name })\n }\n\n #convert({ schema, name }: { schema: SchemaObject; name?: string | null }): ast.SchemaNode {\n const options = this.#options\n const nullable = isNullable(schema, this.#document) || 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: this.parse,\n document: this.#document,\n refs: this.#refs,\n renames: this.#renames,\n }\n\n const rule = schemaRules.find((entry) => entry.match(context))\n const node = rule ? rule.convert(context) : createNode(context, { type: options.emptySchemaType as ast.ScalarSchemaType })\n\n // `allOf` members that hold only annotations and `if`/`then`/`else` are not parsed as members, so read their conditionals here.\n const annotationMembers = Array.isArray(schema.allOf) ? (schema.allOf as Array<SchemaObject>).filter(isAnnotationMember) : []\n return this.#withConditionals(node, [schema, ...annotationMembers])\n }\n\n #requireKeys(keys: Array<string>): ast.SchemaNode {\n const unknown = ast.factory.createSchema({ type: ast.schema.types.unknown })\n const node = ast.factory.createSchema({\n type: ast.schema.types.object,\n primitive: 'object',\n properties: keys.map((name) => ast.factory.createProperty({ name, required: true, schema: unknown })),\n })\n this.#presenceKeys.set(node, keys.join('\\0'))\n return node\n }\n\n #withConditionals(node: ast.SchemaNode, sources: Array<SchemaObject>): ast.SchemaNode {\n const conditionals = sources.flatMap((source) => this.#toConditionals(source))\n // A collapsed one-member `allOf` already carries the conditionals of its member, so a repeated entry is skipped.\n const existing = new Set((node.conditionals ?? []).map((entry) => this.#presenceKey(entry)))\n const added = conditionals.filter((entry) => {\n const key = this.#presenceKey(entry)\n return key === undefined || !existing.has(key)\n })\n return added.length ? { ...node, conditionals: [...(node.conditionals ?? []), ...added] } : node\n }\n\n // The keys an entry checks for presence, or `undefined` when a branch checks more than presence and the entry is always kept.\n #presenceKey({ if: condition, then: thenNode, else: elseNode }: NonNullable<ast.SchemaNode['conditionals']>[number]): string | undefined {\n const keys = [condition, thenNode, elseNode].map((branch) => (branch ? this.#presenceKeys.get(branch) : ''))\n return keys.includes(undefined) ? undefined : keys.join('\\n')\n }\n\n #toBranch(value: unknown): ast.SchemaNode | undefined {\n if (!value || typeof value !== 'object') return undefined\n const { required, type, ...rest } = value as SchemaObject\n // A subschema with only `required`, such as `{ required: ['postalCode'] }`, would otherwise parse as `unknown`.\n if (Array.isArray(required) && required.length && (type === undefined || type === 'object') && !Object.keys(rest).length) return this.#requireKeys(required)\n return this.parse({ schema: value as SchemaObject })\n }\n\n #toConditionals(schema: SchemaObject): NonNullable<ast.SchemaNode['conditionals']> {\n const entries = (value: unknown) => (value && typeof value === 'object' ? Object.entries(value) : [])\n const conditionals: NonNullable<ast.SchemaNode['conditionals']> = []\n\n const condition = this.#toBranch(schema.if)\n if (condition) {\n const thenNode = this.#toBranch(schema.then)\n const elseNode = this.#toBranch(schema.else)\n conditionals.push({ if: condition, ...(thenNode && { then: thenNode }), ...(elseNode && { else: elseNode }) })\n }\n for (const [key, required] of entries(schema.dependentRequired)) {\n if (isKeyList(required)) conditionals.push({ if: this.#requireKeys([key]), then: this.#requireKeys(required) })\n }\n for (const [key, dependent] of entries(schema.dependentSchemas)) {\n const thenNode = this.#toBranch(dependent)\n if (thenNode) conditionals.push({ if: this.#requireKeys([key]), then: thenNode })\n }\n\n return conditionals\n }\n}\n\n/**\n * Creates the schema converter bound to one OpenAPI document.\n *\n * @internal\n */\nexport function createSchemaParser(ctx: SchemaParserOptions): SchemaParser {\n return new SchemaParser(ctx)\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.node.kinds.schema\n for (const node of ast.node.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.node.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 { defineExtension } from '@kubb/core'\nimport type { AdapterParseOptions, AdapterParseResult, AdapterValidateOptions } from '@kubb/core'\nimport { ast, Diagnostics } from '@kubb/kit'\nimport type { AdapterSource, Harness } 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 { toAuthSchemes } from './model/security.ts'\nimport { resolveBaseUrl, toInputServers } from './model/server.ts'\nimport { toInputTags } from './model/tag.ts'\nimport { getExternalDocs, pickExtensions, pickStrings } from './oas.ts'\nimport { camelCasePathParams, getOperations, parseOperation } from './operation.ts'\nimport type { ParseFn } from './emit/parseSchema.ts'\nimport { createSchemaParser } from './schemaParser.ts'\nimport { collectInlineEnums, refPromotedEnums } from './promoteEnums.ts'\nimport { createRefs, type Refs } from './refs.ts'\nimport { groupUnsupportedFormats, scanSchema } from './schemaDiagnostics.ts'\nimport { locate } from './sourceLocator.ts'\nimport type { AdapterOas, AdapterOasResolvedOptions, 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\ntype InputCacheEntry = {\n promise: Promise<ast.InputNode>\n sources: Array<string>\n document: Document | null\n harness?: Harness\n}\n\ntype AdapterSettings = Pick<AdapterOasResolvedOptions, 'validate' | 'contentType' | 'server' | 'discriminator' | 'enums' | 'pathParamsCasing'>\n\ntype ParserOptions = Omit<AdapterOasResolvedOptions, keyof AdapterSettings>\n\ntype ParseInputContext = {\n document: Document\n refs: Refs\n schemas: Record<string, SchemaObject>\n pointers: Map<string, string>\n parseSchema: ParseFn\n}\n\ntype ParsedSchemas = {\n parsedByName: Map<string, ast.SchemaNode>\n refAliasMap: Map<string, ast.RefSchemaNode>\n discriminatorChildMap: Map<string, DiscriminatorTarget> | null\n}\n\nclass Adapter {\n readonly locate = locate\n readonly #settings: AdapterSettings\n readonly #parserOptions: ParserOptions\n #document: Document | null = null\n #sources: Array<string> = []\n readonly #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 readonly #inputCache = new WeakMap<AdapterSource, InputCacheEntry>()\n\n constructor({ validate, contentType, server, discriminator, enums, pathParamsCasing, ...parserOptions }: AdapterOasResolvedOptions) {\n this.#settings = { validate, contentType, server, discriminator, enums, pathParamsCasing }\n this.#parserOptions = parserOptions\n }\n\n /**\n * @deprecated Read `document` from the result of `parse`. It follows the last parse. Removed in Kubb v6.\n */\n get document(): Document | null {\n return this.#document\n }\n\n /**\n * @deprecated Read `sources` from the result of `parse`. It follows the last parse. Removed in Kubb v6.\n */\n get sources(): Array<string> {\n return this.#sources\n }\n\n // Arrow properties, so an adapter that a user spreads or destructures keeps its methods.\n validate = async (input: string, options?: AdapterValidateOptions): Promise<void> => {\n const document = await parseFromConfig({ type: 'path', path: input }, [], { harness: options?.harness })\n assertDocument(document)\n await validateDocument(document, options)\n }\n\n settle = async (): Promise<void> => {\n await Promise.all(this.#pendingValidations.splice(0))\n }\n\n /**\n * Returns the AST with the document and the files this call read, so two overlapping parses on one instance each\n * get their own.\n */\n parse = async (source: AdapterSource, options?: AdapterParseOptions): Promise<AdapterParseResult<Document>> => {\n const entry = this.#start(source, options)\n const node = await entry.promise\n return { node, document: entry.document, sources: entry.sources }\n }\n\n // Starts a parse, or returns the cached one for `source`. The deprecated `document` and `sources` getters follow the last call.\n #start(source: AdapterSource, { signal, harness }: AdapterParseOptions = {}): InputCacheEntry {\n signal?.throwIfAborted()\n const cached = this.#cached({ source, harness })\n if (cached) {\n this.#sources = cached.sources\n this.#document = cached.document\n return cached\n }\n\n const read: Array<string> = []\n this.#sources = read\n const entry = { sources: read, document: null as Document | null, harness }\n const promise = (async () => {\n const document = await parseFromConfig(source, read, { harness, signal })\n signal?.throwIfAborted()\n assertDocument(document)\n if (this.#settings.validate) this.#pendingValidations.push(validateDocumentInWorker(document))\n entry.document = document\n this.#document = document\n\n const refs = createRefs(document)\n const { schemas, renames, pointers } = getSchemas(document, { contentType: this.#settings.contentType }, refs)\n const parseSchema = createSchemaParser({ document, refs, renames, options: this.#parserOptions }).parse\n\n return groupUnsupportedFormats(() => this.#parseInput({ document, refs, schemas, pointers, parseSchema }))\n })().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) this.#inputCache.delete(source)\n throw error\n })\n const started = Object.assign(entry, { promise })\n this.#inputCache.set(source, started)\n return started\n }\n\n // A parse with another `harness` may read different sources, so it does not reuse the cached one.\n #cached({ source, harness }: { source: AdapterSource } & Pick<AdapterParseOptions, 'harness'>): InputCacheEntry | undefined {\n const cached = this.#inputCache.get(source)\n return cached?.harness === harness ? cached : undefined\n }\n\n /**\n * Parses every schema and operation once, resolving ref aliases and discriminator children from that same pass.\n */\n #parseInput({ document, refs, schemas, pointers, parseSchema }: ParseInputContext): ast.InputNode {\n const { contentType, server, enums, pathParamsCasing } = this.#settings\n const parserOptions = this.#parserOptions\n const parsed = this.#parseSchemas({ schemas, pointers, parseSchema })\n\n const operationNodes = getOperations(document, refs).map((operation) => {\n const node = parseOperation({ operation, document, refs, contentType, options: parserOptions, parseSchema })\n return pathParamsCasing === 'camelcase' ? camelCasePathParams(node) : node\n })\n\n const promotedEnums = enums === 'root' ? collectInlineEnums([...parsed.parsedByName.values(), ...operationNodes], new Set(Object.keys(schemas))) : null\n\n const schemaNodes = resolveSchemaNodes({ names: Object.keys(schemas), parsed, promotedEnums })\n\n const operations = promotedEnums ? operationNodes.map((node) => refPromotedEnums(node, promotedEnums!)) : operationNodes\n\n const authSchemes = toAuthSchemes(document.components?.securitySchemes, refs)\n\n return ast.factory.createInput({\n schemas: schemaNodes,\n operations,\n meta: toInputMeta({ document, server, authSchemes }),\n })\n }\n\n #parseSchemas({ schemas, pointers, parseSchema }: Omit<ParseInputContext, 'document' | 'refs'>): ParsedSchemas {\n const { discriminator } = this.#settings\n const parsedByName = new Map<string, ast.SchemaNode>()\n const refAliasMap = new Map<string, ast.RefSchemaNode>()\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 (discriminator === 'propagate' && isDiscriminatorParent(schema)) {\n discriminatorParentNodes.push(node)\n }\n }\n\n const discriminatorChildMap: Map<string, DiscriminatorTarget> | null =\n discriminatorParentNodes.length > 0 ? buildDiscriminatorChildMap(discriminatorParentNodes) : null\n\n return { parsedByName, refAliasMap, discriminatorChildMap }\n }\n}\n\nfunction isDiscriminatorParent(schema: SchemaObject): boolean {\n return Boolean((schema.oneOf ?? schema.anyOf) && schema.discriminator?.propertyName)\n}\n\nfunction resolveSchemaNodes({\n names,\n parsed: { parsedByName, refAliasMap, discriminatorChildMap },\n promotedEnums,\n}: {\n names: Array<string>\n parsed: ParsedSchemas\n promotedEnums: Map<string, ast.SchemaNode> | null\n}): Array<ast.SchemaNode> {\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.ref.getName(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 const schemaNodes: Array<ast.SchemaNode> = promotedEnums ? [...promotedEnums.values()] : []\n for (const name of names) {\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 return schemaNodes\n}\n\nfunction 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\nfunction toInfoMeta(info: Document['info']) {\n return {\n title: info?.title,\n description: info?.description,\n version: info?.version,\n summary: info?.summary,\n termsOfService: info?.termsOfService,\n contact: pickStrings(info?.contact, ['name', 'url', 'email']),\n license: typeof info?.license?.name === 'string' ? { ...pickStrings(info.license, ['identifier', 'url']), name: info.license.name } : undefined,\n }\n}\n\nfunction toInputMeta({ document, server, authSchemes }: { document: Document; server: AdapterSettings['server']; authSchemes: Array<ast.AuthScheme> }) {\n return {\n ...toInfoMeta(document.info),\n externalDocs: getExternalDocs(document.externalDocs),\n baseURL: resolveBaseUrl({ document, server }),\n ...(server?.index !== undefined && { serverIndex: server.index }),\n servers: toInputServers(document.servers ?? []),\n ...(document.tags?.length && { tags: toInputTags(document.tags) }),\n ...(authSchemes.length && { auth: authSchemes }),\n extensions: pickExtensions(document),\n }\n}\n\n/**\n * Default Kubb adapter for OpenAPI 2.0, 3.0, 3.1, and 3.2 specifications. Reads the\n * spec from `input` (a file path, URL, inline content, or parsed object), resolves\n * the base URL, and converts every schema and operation into the universal AST that\n * every downstream plugin consumes. Set `validate: true` to also check the spec.\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 = false,\n contentType,\n server,\n discriminator = 'preserve',\n enums = 'inline',\n pathParamsCasing,\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, pathParamsCasing, dateType, integerType, unknownType, emptySchemaType, enumSuffix }),\n build: (options) => new Adapter(options),\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AEMA,MAAa,yBAAyB;CACpC,UAAU;CACV,aAAa;CACb,aAAa;CACb,iBAAiB;CACjB,YAAY;AACd;;;;;;;;;;;AAYA,MAAa,oBAAoB;;;;;;AAOjC,MAAa,iCAAsC,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,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,SAAgB,cAAc,QAAwE;CACpG,MAAM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,YAAY,EAAE,UAAU,QAAQ,eAA8G;CACrJ,OAAO;EACL,GAAG,WAAW,SAAS,IAAI;EAC3B,cAAc,gBAAgB,SAAS,YAAY;EACnD,SAAS,eAAe;GAAE;GAAU;EAAO,CAAC;EAC5C,GAAI,QAAQ,UAAU,KAAA,KAAa,EAAE,aAAa,OAAO,MAAM;EAC/D,SAAS,eAAe,SAAS,WAAW,CAAC,CAAC;EAC9C,GAAI,SAAS,MAAM,UAAU,EAAE,MAAM,YAAY,SAAS,IAAI,EAAE;EAChE,GAAI,YAAY,UAAU,EAAE,MAAM,YAAY;EAC9C,YAAY,eAAe,QAAQ;CACrC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,cAAA,GAAaE,WAAAA,gBAAAA,CAA4B;CACpD,MAAM;CACN,MAAM;EAAE,MAAA;EAAsB;EAAS;EAAe,QAAQ;CAA2C;CACzG,QAAQ,EACN,WAAW,OACX,aACA,QACA,gBAAgB,YAChB,QAAQ,UACR,kBACA,WAAW,uBAAuB,UAClC,cAAc,uBAAuB,aACrC,cAAc,uBAAuB,aACrC,aAAa,uBAAuB,YACpC,kBAAkB,eAAe,uBAAuB,uBACnD;EAAE;EAAU;EAAa;EAAQ;EAAe;EAAO;EAAkB;EAAU;EAAa;EAAa;EAAiB;CAAW;CAChJ,QAAQ,YAAY,IAAI,QAAQ,OAAO;AACzC,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["ast","access","readFile","Diagnostics","load","CORE_SCHEMA","EVENT_ID","SCALAR_STYLE","COLLECTION_STYLE","parseEvents","Diagnostics","parseEvents","constructFromEvents","CORE_SCHEMA","fileURLToPath","resolve","dirname","normalize","Diagnostics","bundle","join","upgrade","pascalCase","Diagnostics","ast","ast","enumPrimitive","macroDiscriminatorEnum","ast","mergeAdjacentObjectsLazy","macroDedupeUnion","Diagnostics","ast","ast","ast","macroEnumName","pascalCase","pascalCase","Diagnostics","ast","Url","ast","ast","macroEnumName","childName","enumPropName","macroDiscriminatorEnum","ast","ast","ast","Diagnostics","defineExtension"],"sources":["../kubb-extension.json","../package.json","../src/constants.ts","../src/emit/discriminator/propagate.ts","../../../internals/utils/src/promise.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/schemaIds.ts","../src/sourceLocator.ts","../src/load/source.ts","../src/load/normalize.ts","../src/model/components.ts","../src/model/security.ts","../src/model/server.ts","../src/model/tag.ts","../src/emit/schemaShape.ts","../src/emit/createNode.ts","../src/emit/discriminator/preserve.ts","../src/emit/converters/annotatedEnum.ts","../src/emit/converters/composition.ts","../src/schemaDiagnostics.ts","../src/model/mediaType.ts","../src/model/content.ts","../src/model/parameters.ts","../src/operation.ts","../src/emit/converters/scalar.ts","../src/emit/converters/structural.ts","../src/emit/parseSchema.ts","../src/schemaParser.ts","../src/promoteEnums.ts","../src/adapter.ts"],"sourcesContent":["","","import type { ast } from '@kubb/kit'\nimport type { ParserOptions } from './parserOptions.ts'\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 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 * Keys whose value maps names the user chose to entries: `properties`-like schema maps, schema definitions,\n * and the OpenAPI component and path-level maps. An entry name here is never a keyword, so `x-rate-limit`\n * under `headers` is a real header, not a vendor extension, and a property named `default` holds a schema.\n */\nexport const namedEntryKeys: ReadonlySet<string> = new Set([\n 'properties',\n 'patternProperties',\n 'dependentSchemas',\n '$defs',\n 'definitions',\n 'schemas',\n 'headers',\n 'responses',\n 'parameters',\n 'requestBodies',\n 'examples',\n 'links',\n 'callbacks',\n 'securitySchemes',\n 'securityDefinitions',\n 'pathItems',\n])\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: 'string',\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 * The `formatMap` entry for `format`. Reads own keys only, so `constructor` or `toString` never match.\n */\nexport function getFormatType(format: string): (typeof formatMap)[keyof typeof formatMap] | undefined {\n const formats: Record<string, (typeof formatMap)[keyof typeof formatMap]> = formatMap\n return Object.hasOwn(formats, format) ? formats[format] : undefined\n}\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\ntype ChildDiscriminant = { name: string; enumValues: DiscriminatorTarget['enumValues'] }\n\nfunction pinnedValues({ objNode, propertyName }: { objNode: ast.SchemaNodeByType['object']; propertyName: string }): DiscriminatorTarget['enumValues'] {\n const prop = objNode.properties.find((p) => p.name === propertyName)\n const enumNode = prop ? ast.schema.narrow(prop.schema, 'enum') : null\n return enumNode?.enumValues?.filter((v): v is string | number | boolean => v !== null) ?? []\n}\n\nfunction memberDiscriminant({ member, propertyName }: { member: ast.SchemaNode; propertyName: string }): ChildDiscriminant | null {\n const members = ast.schema.narrow(member, 'intersection')?.members ?? []\n const refNode = members.map((m) => ast.schema.narrow(m, 'ref')).find(Boolean)\n const objNode = members.map((m) => ast.schema.narrow(m, 'object')).find(Boolean)\n if (!refNode?.name || !objNode) return null\n\n const enumValues = pinnedValues({ objNode, propertyName })\n // A child renamed by a name collision is emitted, and looked up, under its unique name.\n return enumValues.length ? { name: refNode.targetName ?? refNode.name, enumValues } : null\n}\n\n/**\n * Maps each child schema's emitted name to its discriminator patch data, one entry per discriminator property, by scanning the given\n * AST schema nodes, and the schemas nested in them, for union schemas that carry a `discriminatorPropertyName`.\n * A union can sit at the root, inside an intersection (a union with shared properties), on a property, or on array `items`.\n * Ref targets are not followed.\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, Array<DiscriminatorTarget>> {\n const childMap = new Map<string, Array<DiscriminatorTarget>>()\n const unions = schemas.flatMap((schema) => ast.node.collect<ast.SchemaNodeByType['union']>(schema, { schema: (node) => ast.schema.narrow(node, 'union') }))\n\n for (const unionNode of unions) {\n if (!unionNode.discriminatorPropertyName || !unionNode.members) continue\n const propertyName = unionNode.discriminatorPropertyName\n\n for (const member of unionNode.members) {\n const child = memberDiscriminant({ member, propertyName })\n if (!child) continue\n // Values merge per property name, so a child of unions on different properties gets one discriminant for each.\n const targets = childMap.get(child.name) ?? []\n const existing = targets.find((target) => target.propertyName === propertyName)\n if (existing) existing.enumValues = [...new Set([...existing.enumValues, ...child.enumValues])]\n else targets.push({ propertyName, enumValues: child.enumValues })\n childMap.set(child.name, targets)\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.schema.narrow(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.schema.narrow(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.schema.narrow(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","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\nexport type Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Returns the value cached under `key` in `store`, computing and storing it on the first call.\n * Pass a `WeakMap` for object keys, so an entry goes away with its key, or a `Map` for primitive\n * keys. A cached `null` or `undefined` counts as a hit, so `compute` runs once per key.\n *\n * @example\n * `const refs = memo(refCache, node, () => collectRefs(node))`\n */\nexport function memo<TKey, TValue>(store: Store<TKey, TValue>, key: TKey, compute: () => TValue): TValue {\n const cached = store.get(key)\n if (cached !== undefined || store.has(key)) return cached as TValue\n const value = compute()\n store.set(key, value)\n return value\n}\n\nclass BoundedStore<TKey, TValue> implements Store<TKey, TValue> {\n readonly #entry = new Map<TKey, TValue>()\n readonly #max: number\n\n constructor(max: number) {\n this.#max = max\n }\n\n has(key: TKey): boolean {\n return this.#entry.has(key)\n }\n\n get(key: TKey): TValue | undefined {\n return this.#entry.get(key)\n }\n\n set(key: TKey, value: TValue): void {\n if (this.#entry.size >= this.#max) this.#entry.clear()\n this.#entry.set(key, value)\n }\n}\n\nclass LastEntryStore<TKey, TValue> extends BoundedStore<TKey, TValue> {\n constructor() {\n super(1)\n }\n\n // A key equal to the stored one but a different object, such as a copy of a string, replaces the\n // stored key, so the next lookup is an identity hit instead of a full comparison.\n #touch(key: TKey): boolean {\n if (!super.has(key)) return false\n this.set(key, super.get(key) as TValue)\n return true\n }\n\n override has(key: TKey): boolean {\n return this.#touch(key)\n }\n\n override get(key: TKey): TValue | undefined {\n return this.#touch(key) ? super.get(key) : undefined\n }\n}\n\n/**\n * Creates a store for `memo`. With no options it is a `Map`. Each option changes one thing:\n *\n * - `weak` holds the keys weakly, in a `WeakMap`, so an entry goes away with its key.\n * - `max` bounds the store: it empties itself before the entry that would pass `max`, which keeps a\n * cache in a long-running process from growing without end. `max: 1` keeps only the last entry.\n *\n * @example\n * `const patterns = memo.create<string, RegExp>()`\n *\n * @example Freed with its key\n * `const refs = memo.create<SchemaNode, Array<string>>({ weak: true })`\n *\n * @example Bounded\n * `const names = memo.create<string, string>({ max: 100_000 })`\n *\n * @example Many values per key\n * ```ts\n * const filesByPlugin = memo.create<string, Array<string>>()\n * memo(filesByPlugin, 'plugin-ts', () => []).push('models.ts')\n * ```\n */\nfunction createStore<TKey, TValue>(options?: { weak?: false; max?: undefined }): Map<TKey, TValue>\nfunction createStore<TKey extends WeakKey, TValue>(options: { weak: true; max?: undefined }): WeakMap<TKey, TValue>\nfunction createStore<TKey, TValue>(options: { max: number; weak?: false }): Store<TKey, TValue>\nfunction createStore<TKey, TValue>({ weak, max }: { weak?: boolean; max?: number } = {}): Store<TKey, TValue> {\n if (weak) return new WeakMap<WeakKey, TValue>() as Store<TKey, TValue>\n if (max === undefined) return new Map<TKey, TValue>()\n if (max !== 1) return new BoundedStore<TKey, TValue>(max)\n return new LastEntryStore<TKey, TValue>()\n}\n\nmemo.create = createStore\n\nexport type InParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain. The first\n * rejection rejects the call, and the other workers start no new item after it.\n *\n * @throws {RangeError} When `limit` is not a positive whole number, which would run no item at all.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: InParallelOptions<TItem>): Promise<void> {\n if (!Number.isInteger(limit) || limit < 1) throw new RangeError(`inParallel needs a limit of 1 or more, got ${limit}`)\n const queue = items.entries()\n let failed = false\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) {\n if (failed) return\n await run(item, index).catch((error: unknown) => {\n failed = true\n throw error\n })\n }\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\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/**\n * Builds an error that `Diagnostics.isError` from `@kubb/core` reads as a `Diagnostics.Error` with\n * `code`, without importing `@kubb/core` at run time. Use it in packages that only take core as a\n * type or peer dependency, so reporters show the code and `help` instead of `KUBB_UNKNOWN`.\n *\n * @example\n * ```ts\n * throw createDiagnosticError({ code: 'KUBB_MODULE_NOT_FOUND', message: 'Install typescript', cause })\n * ```\n */\nexport function createDiagnosticError({ code, message, help, cause }: { code: `KUBB_${string}`; message: string; help?: string; cause?: Error }): Error {\n const error = new Error(message, { cause })\n error.name = 'DiagnosticError'\n return Object.assign(error, { diagnostic: { code, severity: 'error' as const, message, ...(help ? { help } : {}), ...(cause ? { cause } : {}) } })\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\n/**\n * Unescapes one JSON pointer token per RFC 6901 (`~1` → `/`, then `~0` → `~`).\n */\nexport function unescapePointerToken(token: string): string {\n return token.replaceAll('~1', '/').replaceAll('~0', '~')\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 { existsSync, readFile, readFileSync, writeFile } from 'node:fs'\nimport { access, glob as globNode, lstat, mkdir, realpath } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } 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 // The callback API skips the `FileHandle` every `fs/promises` call opens.\n return new Promise((resolvePromise, reject) => readFile(path, { encoding: 'utf8' }, (error, data) => (error ? reject(error) : resolvePromise(data))))\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string, or `null` when it does not exist or cannot be read.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFileSync` otherwise.\n *\n * @example\n * ```ts\n * const stored = await readIfExists('./src/gen/Pet.ts') // null on a first run\n * ```\n */\nexport async function readIfExists(path: string): Promise<string | null> {\n if (runtime.isBun) {\n return Bun.file(path)\n .text()\n .catch(() => null)\n }\n // A small read is faster on the main thread than a thread-pool round trip, and `existsSync`\n // answers a missing file without building an error.\n if (!existsSync(path)) return null\n try {\n return readFileSync(path, 'utf8')\n } catch (_error) {\n return null\n }\n}\n\nexport type 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 const stored = options.stored === undefined ? await readIfExists(resolved) : options.stored\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 new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n await mkdir(dirname(resolved), { recursive: true })\n await new Promise<void>((resolvePromise, reject) =>\n writeFile(resolved, content, { encoding: 'utf-8' }, (error) => (error ? reject(error) : resolvePromise())),\n )\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 * 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 * It ignores symlinks, so check a path a caller supplied with {@link isRealPathInside}.\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 // A child named `..cache` stays inside; only a `..` segment leaves.\n return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)\n}\n\n// A missing path resolves through its nearest existing parent. `undefined` for a dangling symlink or another error.\nasync function realPath(target: string): Promise<string | undefined> {\n const missing: Array<string> = []\n for (let current = resolve(target); ; current = dirname(current)) {\n try {\n return join(await realpath(current), ...missing)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') return undefined\n // `realpath` also reports ENOENT for a symlink whose target is gone, and that link could later point anywhere.\n const isDanglingLink = await lstat(current).then(\n (stats) => stats.isSymbolicLink(),\n () => false,\n )\n if (isDanglingLink) return undefined\n if (dirname(current) === current) return undefined\n missing.unshift(basename(current))\n }\n }\n}\n\n/**\n * Like {@link isPathInside}, after resolving symlinks. Fails closed when a path cannot be resolved.\n */\nexport async function isRealPathInside({ target, base }: { target: string; base: string }): Promise<boolean> {\n const [real, realBase] = await Promise.all([realPath(target), realPath(base)])\n return real !== undefined && realBase !== undefined && isPathInside(real, realBase)\n}\n\n/**\n * Whether `storage` writes to disk, which Kubb knows only for a storage named `'fs'`.\n */\nexport function writesToDisk(storage: { name: string }): boolean {\n return storage.name === 'fs'\n}\n","import type { ast } from '@kubb/kit'\nimport type { DiscriminatorObject, Document, ReferenceObject, SchemaObject } from './types.ts'\n\nconst legacyDocuments = new WeakSet<Document>()\n\n/**\n * Marks a document upgraded from Swagger 2.0 or OpenAPI 3.0, so its enums keep the loose `nullable` reading.\n */\nexport function markLegacyDocument(document: Document): void {\n legacyDocuments.add(document)\n}\n\n/**\n * Returns `true` for a document upgraded from Swagger 2.0 or OpenAPI 3.0.\n */\nexport function isLegacyDocument(document: Document | undefined): boolean {\n return !!document && legacyDocuments.has(document)\n}\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 * A sibling `enum` without `null` makes the schema non-nullable, except in documents upgraded from 3.0.\n */\nexport function isNullable(schema?: SchemaObject & { 'x-nullable'?: boolean }, document?: Document): boolean {\n const explicitNullable = schema?.nullable ?? schema?.['x-nullable']\n if (explicitNullable === true) return true\n\n const schemaType = schema?.type\n const typeAllowsNull = schemaType === 'null' || (Array.isArray(schemaType) && schemaType.includes('null'))\n if (typeAllowsNull && Array.isArray(schema?.enum) && !schema.enum.includes(null)) return isLegacyDocument(document)\n\n return typeAllowsNull\n}\n\n/**\n * Returns `true` for an OpenAPI 3.2 or later document. Swagger 2.0 and OpenAPI 3.0 documents are\n * upgraded to 3.1 before parsing, so `openapi` is always set here.\n */\nexport function isOpenApi32(document: Document): boolean {\n const [major = 0, minor = 0] = String(document.openapi).split('.').map(Number)\n return major > 3 || (major === 3 && minor >= 2)\n}\n\nexport function pickStrings<TKey extends string>(source: unknown, keys: ReadonlyArray<TKey>): Partial<Record<TKey, string>> | undefined {\n if (!source || typeof source !== 'object') return undefined\n const entries = keys.flatMap((key) => {\n const value = (source as Record<string, unknown>)[key]\n return typeof value === 'string' ? [[key, value] as const] : []\n })\n return entries.length ? (Object.fromEntries(entries) as Partial<Record<TKey, string>>) : undefined\n}\n\nexport function getExternalDocs(source: unknown): ast.ExternalDocs | undefined {\n const docs = pickStrings(source, ['url', 'description'])\n return docs?.url ? { url: docs.url, ...(docs.description !== undefined && { description: docs.description }) } : undefined\n}\n\n/**\n * Returns the `x-*` keys of `source` as-is, or `undefined` when there are none.\n */\nexport function pickExtensions(source: object | null | undefined): Record<string, unknown> | undefined {\n if (!source) return 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 that names a\n * `propertyName`, excluding the Swagger 2 string form and a 3.2 discriminator that only sets `defaultMapping`.\n */\nexport function isDiscriminator(obj?: unknown): obj is SchemaObject & { discriminator: DiscriminatorObject } {\n const discriminator = (obj as Record<string, unknown> | undefined)?.['discriminator']\n return !!discriminator && typeof discriminator === 'object' && typeof (discriminator as DiscriminatorObject).propertyName === '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 * Keywords that only annotate a schema. A schema with nothing else does not constrain the value.\n */\nconst annotationKeywords = new Set(['title', 'description', 'default', 'example', 'examples', 'deprecated', 'readOnly', 'writeOnly', 'externalDocs'])\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. Annotations such as `description` survive the upgrade and are kept.\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).some((key) => !annotationKeywords.has(key) && !key.startsWith('x-'))) return undefined\n\n return { ...(schema as SchemaObject | undefined), 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 const lower = mimeType.toLowerCase()\n return jsonMimeFragments.some((fragment) => lower.includes(fragment))\n}\n","import { memo, unescapePointerToken } from '@internals/utils'\nimport { 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 *\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 class Refs {\n readonly #document: Document\n readonly #pointerCache = new Map<string, unknown>()\n readonly #resolvedNodeCache = memo.create<string, ast.SchemaNode | null>()\n readonly #resolvingRefs = new Set<string>()\n\n constructor(document: Document) {\n this.#document = document\n }\n\n // `found` is true for a falsy target too, such as a boolean `false` schema.\n #walkPointer<T>($ref: string): { applicable: boolean; found: boolean; value: T | null } {\n const trimmed = $ref.trim()\n if (trimmed === '' || !trimmed.startsWith('#')) {\n return { applicable: false, found: false, value: null }\n }\n const pointer = trimmed.substring(1)\n\n if (this.#pointerCache.has(pointer)) {\n return { applicable: true, found: true, value: this.#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 let current: unknown\n try {\n current = pointer\n .split('/')\n .filter(Boolean)\n .map((token) => unescapePointerToken(globalThis.decodeURIComponent(token)))\n .reduce(\n (obj: unknown, key: string) => (obj != null && Object.hasOwn(obj, key) ? (obj as Record<string, unknown>)[key] : undefined),\n this.#document as unknown,\n )\n } catch {\n // A malformed `%` escape cannot name a node, so it reports as an unresolved ref.\n current = undefined\n }\n\n if (current === undefined) {\n return { applicable: true, found: false, value: null }\n }\n this.#pointerCache.set(pointer, current)\n\n return { applicable: true, found: true, value: current as T }\n }\n\n /**\n * Resolves a local `#/...` JSON pointer. Returns `null` for an empty, non-local or missing ref.\n * A target that exists is returned as is, even when it is falsy, such as a boolean `false` schema.\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 resolve<T = unknown>(refPath: string, options?: { report?: boolean }): T | null {\n const { applicable, found, value } = this.#walkPointer<T>(refPath)\n if (!applicable || found || 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). An error from `parse` is thrown, so a bug\n * in a converter is not mistaken for a missing ref.\n */\n resolveNode(refPath: string, parse: ParseFn): ast.SchemaNode | null {\n if (this.#resolvingRefs.has(refPath)) return null\n\n return memo(this.#resolvedNodeCache, refPath, () => {\n let referenced: SchemaObject | null\n try {\n referenced = this.resolve<SchemaObject>(refPath)\n } catch (error) {\n // A missing ref outside a build is `null`; any other error is a real failure.\n if (Diagnostics.isError(error) && error.diagnostic.code === Diagnostics.code.refNotFound) return null\n throw error\n }\n if (referenced === null) return null\n this.#resolvingRefs.add(refPath)\n try {\n return parse({ schema: referenced })\n } finally {\n this.#resolvingRefs.delete(refPath)\n }\n })\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 deref<T = unknown>(value: unknown): T | null {\n if (!isReference(value)) {\n return value ? (value as T) : null\n }\n\n const resolved = this.resolve<T>(value.$ref)\n return resolved && !isReference(resolved) ? resolved : null\n }\n\n /**\n * Resolves a `$ref` object but keeps the `$ref` field on the result; other values pass through.\n */\n derefKeepingRef<T = unknown>(value?: T): T {\n if (isReference(value)) {\n return { ...value, ...this.resolve(value.$ref), $ref: value.$ref }\n }\n\n return value as T\n }\n}\n\n/**\n * Creates the `$ref` resolution service for one document. One pointer walk backs every method.\n */\nexport function createRefs(document: Document): Refs {\n return new Refs(document)\n}\n","import { escapePointerToken, memo } from '@internals/utils'\nimport { namedEntryKeys } from '../constants.ts'\n\nconst DATA_KEYS = new Set(['example', 'examples', 'const', 'enum', 'default'])\nconst TARGET_KEYS = ['$id', '$anchor', '$dynamicAnchor'] as const\n\n// A named map's keys are entry names, so an `x-` or `default` key there is a real entry.\nfunction isNamedMap({ node, keyword }: { node: object; keyword: string | undefined }): boolean {\n return keyword !== undefined && !Array.isArray(node) && namedEntryKeys.has(keyword)\n}\n\nfunction childKeyword({ node, key, named }: { node: object; key: string; named: boolean }): string | undefined {\n return named || Array.isArray(node) ? undefined : key\n}\n\nfunction walk(node: unknown, pointer: string, visit: (node: Record<string, unknown>, pointer: string) => void, keyword?: string): void {\n if (!node || typeof node !== 'object') return\n if (!Array.isArray(node)) visit(node as Record<string, unknown>, pointer)\n const named = isNamedMap({ node, keyword })\n for (const [key, value] of Object.entries(node)) {\n if (!named && isDataOrExtension(key)) continue\n walk(value, `${pointer}/${escapePointerToken(key)}`, visit, childKeyword({ node, key, named }))\n }\n}\n\nexport type DocumentScan = {\n /** A `$ref` points outside the document. */\n externalRef: boolean\n /** An `$id`, `$anchor` or `$dynamicAnchor` sits where {@link resolveSchemaIds} reads it. */\n schemaIds: boolean\n /** A `$ref` points into `#/paths/`. */\n pathRefs: boolean\n}\n\nfunction isDataOrExtension(key: string): boolean {\n return DATA_KEYS.has(key) || key.startsWith('x-')\n}\n\nfunction scanNode({ scan, node, readsIds }: { scan: DocumentScan; node: object; readsIds: boolean }): void {\n const record = node as Record<string, unknown>\n const ref = record['$ref']\n if (typeof ref === 'string' && !ref.startsWith('#')) scan.externalRef = true\n if (typeof ref === 'string' && ref.startsWith('#/paths/')) scan.pathRefs = true\n if (readsIds && !Array.isArray(node) && TARGET_KEYS.some((key) => typeof record[key] === 'string')) scan.schemaIds = true\n}\n\n/** Answers, in one walk and without building JSON pointers, what the loading steps after it need to know. */\nexport function scanDocument(document: unknown): DocumentScan {\n const scan: DocumentScan = { externalRef: false, schemaIds: false, pathRefs: false }\n const visit = ({ node, readsIds, keyword }: { node: unknown; readsIds: boolean; keyword?: string }): void => {\n if (!node || typeof node !== 'object') return\n scanNode({ scan, node, readsIds })\n const named = isNamedMap({ node, keyword })\n const record = node as Record<string, unknown>\n for (const key in record) {\n visit({ node: record[key], readsIds: readsIds && (named || !isDataOrExtension(key)), keyword: childKeyword({ node, key, named }) })\n }\n }\n visit({ node: document, readsIds: true })\n return scan\n}\n\n/**\n * The declaration in the nearest enclosing schema, else the only one, else `undefined`.\n */\nfunction pick(declarations: Array<string> | undefined, pointer: string): string | undefined {\n if (!declarations) return undefined\n const enclosing = declarations.filter((target) => pointer === target || pointer.startsWith(`${target}/`))\n if (enclosing.length) return enclosing.reduce((a, b) => (b.length > a.length ? b : a))\n return declarations.length === 1 ? declarations[0] : undefined\n}\n\n/**\n * Rewrites, in place, each `$ref` to an `$id`, `$anchor` or `$dynamicAnchor`, and each `$dynamicRef`, into a\n * `#/...` pointer, so it is not fetched. Instance data and `x-` extensions are left as written.\n *\n * shortcut: `$id` matches the `$ref` string exactly and `$dynamicRef` resolves statically to the nearest\n * enclosing anchor, so a relative `$id` base or a recursively extended schema is not followed, upgrade when a spec needs that.\n */\nexport function resolveSchemaIds(document: unknown): void {\n const targets = memo.create<string, Array<string>>()\n const declare = (key: string, pointer: string) => memo(targets, key, () => []).push(pointer)\n walk(document, '#', (node, pointer) => {\n if (typeof node['$id'] === 'string') declare(node['$id'], pointer)\n for (const key of ['$anchor', '$dynamicAnchor']) {\n if (typeof node[key] === 'string') declare(`#${node[key]}`, pointer)\n }\n })\n if (!targets.size) return\n\n walk(document, '#', (node, pointer) => {\n const ref = typeof node['$ref'] === 'string' ? pick(targets.get(node['$ref']), pointer) : undefined\n if (ref) node['$ref'] = ref\n const dynamicRef = typeof node['$dynamicRef'] === 'string' ? pick(targets.get(node['$dynamicRef']), pointer) : undefined\n if (dynamicRef && node['$ref'] === undefined) {\n node['$ref'] = dynamicRef\n delete node['$dynamicRef']\n }\n })\n}\n","import { memo, unescapePointerToken } from '@internals/utils'\nimport type { Adapter, SourceRange } from '@kubb/core'\nimport { COLLECTION_STYLE, CORE_SCHEMA, EVENT_ID, load, parseEvents, SCALAR_STYLE } from 'js-yaml'\nimport type { Event } from 'js-yaml'\n\ntype Child = { index: number; range: SourceRange }\n\n// One entry per event in typed arrays: an event object per value takes ten times the memory.\ntype EventIndex = {\n types: Uint8Array\n styles: Uint8Array\n starts: Int32Array\n ends: Int32Array\n collections: Map<number, { keys: Map<string, Child>; items: Array<Child> }>\n refs?: Map<string, SourceRange>\n}\n\nconst flowGap = /(?:[\\s,]|#[^\\n]*)*/y\n\n/**\n * How long the indexes of the last sources stay in memory after their last use, in milliseconds.\n */\nexport const INDEX_IDLE_MS = 60_000\n\n// Shared schema detection parses every spec before the builds report, so the last few indexes are kept. They are\n// dropped after `INDEX_IDLE_MS` unused, so a long-lived host does not hold a large spec.\nclass IndexCache {\n #indexes = IndexCache.#createStore()\n #lastUsed = 0\n #timer: ReturnType<typeof setTimeout> | undefined\n\n static #createStore() {\n return memo.create<string, EventIndex | undefined>({ max: 8 })\n }\n\n get({ source, compute }: { source: string; compute: () => EventIndex | undefined }): EventIndex | undefined {\n const index = memo(this.#indexes, source, compute)\n this.#keep()\n return index\n }\n\n set({ source, index }: { source: string; index: EventIndex }): void {\n this.#indexes.set(source, index)\n this.#keep()\n }\n\n // Cheap on every call: one timer runs, and it schedules itself again for the time that is left.\n #keep(): void {\n this.#lastUsed = Date.now()\n if (!this.#timer) this.#schedule(INDEX_IDLE_MS)\n }\n\n #schedule(ms: number): void {\n this.#timer = setTimeout(this.#dropWhenIdle, ms)\n // The timer must not keep a finished CLI run alive.\n this.#timer.unref?.()\n }\n\n readonly #dropWhenIdle = (): void => {\n const remaining = this.#lastUsed + INDEX_IDLE_MS - Date.now()\n if (remaining > 0) return this.#schedule(remaining)\n this.#indexes = IndexCache.#createStore()\n this.#timer = undefined\n }\n}\n\nfunction createIndexCache(): IndexCache {\n return new IndexCache()\n}\n\nconst indexes = createIndexCache()\n\n// A plain `1.50` or `~` is a number or null to `js-yaml`, so the document, and the pointer, spell it `1.5` or `null`.\nfunction toKeyText(text: string): string {\n if (!/^[-+.~\\d]|^(?:null|true|false)$/i.test(text)) return text\n try {\n const value = load(text, { schema: CORE_SCHEMA })\n return value === null || typeof value === 'number' || typeof value === 'boolean' ? String(value) : text\n } catch {\n return text\n }\n}\n\nfunction indexEvents(events: ReadonlyArray<Event>): EventIndex {\n const types = new Uint8Array(events.length)\n const styles = new Uint8Array(events.length)\n const starts = new Int32Array(events.length)\n const ends = new Int32Array(events.length)\n\n for (let at = 0, last = 0; at < events.length; last = Math.max(last, starts[at]!, ends[at]!), at++) {\n const event = events[at]!\n types[at] = event.type\n if (event.type === EVENT_ID.SCALAR) {\n // Quotes sit outside the offsets of a scalar's value. An empty value has none, so it sits where the node before it ended.\n const quote = event.style === SCALAR_STYLE.SINGLE_QUOTED || event.style === SCALAR_STYLE.DOUBLE_QUOTED ? 1 : 0\n const empty = event.valueStart < 0\n styles[at] = event.style\n starts[at] = empty ? last : event.valueStart - quote\n ends[at] = empty ? last : event.valueEnd + quote\n }\n if (event.type === EVENT_ID.ALIAS) {\n starts[at] = event.anchorStart - 1\n ends[at] = event.anchorEnd\n }\n if (event.type === EVENT_ID.MAPPING || event.type === EVENT_ID.SEQUENCE) {\n styles[at] = event.style\n starts[at] = event.start\n }\n }\n return { types, styles, starts, ends, collections: new Map() }\n}\n\ntype SourceLocatorOptions = { index: EventIndex; source: string }\n\nclass SourceLocator {\n readonly #index: EventIndex\n readonly #source: string\n readonly #types: Uint8Array\n readonly #styles: Uint8Array\n readonly #starts: Int32Array\n readonly #ends: Int32Array\n\n constructor({ index, source }: SourceLocatorOptions) {\n this.#index = index\n this.#source = source\n this.#types = index.types\n this.#styles = index.styles\n this.#starts = index.starts\n this.#ends = index.ends\n }\n\n find(pointer: string): SourceRange | undefined {\n // The first event opens the document, the second is its root.\n return this.#walk({ at: 1, tokens: pointer.replace(/^#/, '').split('/').slice(1).map(unescapePointerToken), range: undefined })\n }\n\n findRef(ref: string): SourceRange | undefined {\n this.#index.refs ??= this.#indexRefs()\n return this.#index.refs.get(ref)\n }\n\n // Every `$ref` value in the document, mapped to the range of its first occurrence.\n #indexRefs(): Map<string, SourceRange> {\n const types = this.#types\n const refs = new Map<string, SourceRange>()\n // -1 in a sequence. In a mapping, 0 before a key and 1 before its value.\n const frames: Array<number> = []\n for (let at = 1; at + 1 < types.length; at++) {\n if (!this.#stepFrames({ frames, at }) || !this.#isRefKey(at)) continue\n const text = this.#readText(at + 1)\n if (!refs.has(text)) refs.set(text, { start: this.#starts[at + 1]!, end: this.#ends[at + 1]! })\n }\n return refs\n }\n\n // Moves `frames` past the event at `at`, and tells whether that event is a mapping key.\n #stepFrames({ frames, at }: { frames: Array<number>; at: number }): boolean {\n if (this.#types[at] === EVENT_ID.POP) {\n frames.pop()\n return false\n }\n const top = frames.length - 1\n const isKey = frames[top] === 0\n if (frames[top]! >= 0) frames[top] = 1 - frames[top]!\n if (this.#isCollection(at)) frames.push(this.#types[at] === EVENT_ID.MAPPING ? 0 : -1)\n return isKey\n }\n\n // A `$ref` key followed by its scalar value.\n #isRefKey(at: number): boolean {\n return this.#types[at] === EVENT_ID.SCALAR && this.#types[at + 1] === EVENT_ID.SCALAR && this.#readText(at) === '$ref'\n }\n\n #isCollection(at: number): boolean {\n return this.#types[at] === EVENT_ID.MAPPING || this.#types[at] === EVENT_ID.SEQUENCE\n }\n\n #readText(at: number): string {\n const styles = this.#styles\n const text = this.#source.slice(this.#starts[at], this.#ends[at])\n if (styles[at] === SCALAR_STYLE.SINGLE_QUOTED) return text.slice(1, -1).replaceAll(\"''\", \"'\")\n if (styles[at] !== SCALAR_STYLE.DOUBLE_QUOTED) return text\n try {\n return JSON.parse(text) as string\n } catch {\n return String(load(text, { schema: CORE_SCHEMA }))\n }\n }\n\n #readNode(at: number): SourceRange & { next: number } {\n const starts = this.#starts\n if (!this.#isCollection(at)) return { start: starts[at]!, end: this.#ends[at]!, next: at + 1 }\n let next = at + 1\n let end = starts[at]!\n while (this.#types[next] !== EVENT_ID.POP) ({ end, next } = this.#readNode(next))\n // A flow collection ends at its closing bracket, which no event marks, after any commas and comments.\n if (this.#styles[at] === COLLECTION_STYLE.FLOW) {\n flowGap.lastIndex = end\n flowGap.exec(this.#source)\n end = flowGap.lastIndex + 1\n }\n return { start: starts[at]!, end, next: next + 1 }\n }\n\n #readChildren(collection: number): { keys: Map<string, Child>; items: Array<Child> } {\n const types = this.#types\n const keys = new Map<string, Child>()\n const items: Array<Child> = []\n const isMapping = types[collection] === EVENT_ID.MAPPING\n for (let at = collection + 1; types[at] !== EVENT_ID.POP;) {\n const key = isMapping ? at : undefined\n if (key !== undefined) at = this.#readNode(at).next\n const { start, end, next } = this.#readNode(at)\n if (key === undefined) items.push({ index: at, range: { start, end } })\n const text = key !== undefined ? this.#readKey(key) : undefined\n if (text !== undefined && !keys.has(text)) keys.set(text, { index: at, range: { start: this.#starts[key!]!, end: this.#ends[key!]! } })\n at = next\n }\n return { keys, items }\n }\n\n #readKey(key: number): string | undefined {\n if (this.#types[key] !== EVENT_ID.SCALAR) return undefined\n const raw = this.#readText(key)\n return this.#styles[key] === SCALAR_STYLE.PLAIN ? toKeyText(raw) : raw\n }\n\n // Follows `tokens` from the collection at `at`. The range is the last key or item it reached.\n #walk({ at, tokens: [token, ...rest], range }: { at: number; tokens: Array<string>; range: SourceRange | undefined }): SourceRange | undefined {\n if (token === undefined) return range\n if (!this.#isCollection(at)) return undefined\n const { keys, items } = memo(this.#index.collections, at, () => this.#readChildren(at))\n const child = keys.get(token) ?? items[Number(token)]\n return child ? this.#walk({ at: child.index, tokens: rest, range: child.range }) : undefined\n }\n}\n\nfunction createSourceLocator(options: SourceLocatorOptions): SourceLocator {\n return new SourceLocator(options)\n}\n\nfunction parse(source: string): EventIndex | undefined {\n try {\n return indexEvents(parseEvents(source, { maxDepth: Number.POSITIVE_INFINITY }))\n } catch {\n // Text that is not YAML has no locations.\n return undefined\n }\n}\n\n/**\n * Keeps the event index of a source the adapter already parsed, so `locate` does not parse it again.\n */\nexport function rememberEvents({ source, events }: { source: string; events: ReadonlyArray<Event> }): void {\n indexes.set({ source, index: indexEvents(events) })\n}\n\n// The adapter merges `oneOf` or `anyOf` next to `properties` into an `allOf` the spec does not have, so its\n// pointers can step through `/allOf/<n>`. Without those steps the pointer names the key the user wrote.\nconst withoutAllOf = (pointer: string) => pointer.replace(/\\/allOf\\/\\d+(?=\\/|$)/g, '')\n\n/**\n * Maps OpenAPI JSON pointers and unresolved references to ranges in YAML or JSON source. A pointer through an `allOf`\n * the spec does not have falls back to the same pointer without its `allOf` steps. The indexes of the last few\n * sources are reused until they go unused for `INDEX_IDLE_MS`.\n */\nexport const locate: NonNullable<Adapter['locate']> = (source, location) => {\n if (!('pointer' in location)) return undefined\n const index = indexes.get({ source, compute: () => parse(source) })\n if (!index) return undefined\n\n const locator = createSourceLocator({ index, source })\n const ref = 'ref' in location ? location.ref : undefined\n const flattened = withoutAllOf(location.pointer)\n return locator.find(location.pointer) ?? (flattened === location.pointer ? undefined : locator.find(flattened)) ?? (ref ? locator.findRef(ref) : undefined)\n}\n","import { exists, getErrorMessage, read, toError } from '@internals/utils'\nimport { Diagnostics } from '@kubb/kit'\nimport { CORE_SCHEMA, constructFromEvents, parseEvents } from 'js-yaml'\nimport { rememberEvents } from '../sourceLocator.ts'\n\nexport const urlRegExp = /^https?:\\/+/i\n\n/** How long one request for a document or a `$ref` may take before Kubb gives up on it. */\nconst FETCH_TIMEOUT_MS = 30_000\n\n/**\n * Options for reading a source. `signal` cancels the request. `fetch` makes the request, the global\n * `fetch` when unset, and `read` reads a local file, from disk when unset.\n */\nexport type ReadSourceOptions = {\n signal?: AbortSignal\n fetch?: (url: URL, init: { signal: AbortSignal }) => Promise<Response>\n read?: (path: string) => Promise<string>\n}\n\n/**\n * Whether `error` is a harness refusal. It checks the code, since a host may load another copy of `@kubb/core`.\n */\nexport function isAccessRefused(error: unknown): error is InstanceType<typeof Diagnostics.Error> {\n return (error as { diagnostic?: { code?: unknown } } | null)?.diagnostic?.code === Diagnostics.code.accessRefused\n}\n\nfunction withTimeout(signal: AbortSignal | undefined): AbortSignal {\n const timeout = AbortSignal.timeout(FETCH_TIMEOUT_MS)\n return signal ? AbortSignal.any([signal, timeout]) : timeout\n}\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, { signal, fetch = globalThis.fetch }: ReadSourceOptions): Promise<{ response: Response; body: string }> {\n const deadline = withTimeout(signal)\n try {\n const response = await fetch(url, { signal: deadline })\n // The body is read here too, so a server that stalls after its headers also hits the timeout.\n return { response, body: response.ok ? await response.text() : '' }\n } catch (error) {\n // A canceled build stops here; only a timeout or a network failure is the server's problem.\n if (signal?.aborted) throw signal.reason\n if (isAccessRefused(error)) throw error\n const reason = deadline.aborted ? `no answer within ${FETCH_TIMEOUT_MS / 1000} seconds` : describeFetchFailure(error)\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputUnreachable,\n severity: 'error',\n message: `Cannot reach ${url.href}: ${reason}`,\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, options: ReadSourceOptions): 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, body } = await fetchSource(url, options)\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 body\n }\n\n return (options.read ?? 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, { remember, ...options }: { remember?: boolean } & ReadSourceOptions = {}): Promise<object | string> {\n const data = await readSource(sourcePath, options)\n\n if (sourcePath.toLowerCase().endsWith('.md')) {\n return data\n }\n\n // A URL's query string or fragment must not hide the extension.\n const pathname = urlRegExp.test(sourcePath) ? new URL(sourcePath).pathname : sourcePath\n\n return parseYaml(data, {\n origin: sourcePath,\n json: !/\\.ya?ml$/i.test(pathname),\n help: 'Fix the syntax at the reported line, or check that `input` points at the spec and not an HTML page.',\n remember,\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 * With `json` (the default), a document that starts with `{` or `[` goes through `JSON.parse`\n * first, about ten times faster than `js-yaml` on a JSON spec. A duplicate key then keeps the last\n * value, as every JSON parser does. YAML flow syntax also starts with `{`, so a parse failure falls\n * through to YAML. Pass `json: false` for a source known to be YAML.\n *\n * `js-yaml` rejects duplicate keys instead of keeping the last one. Its core schema keeps\n * timestamps as strings and `<<` as a plain key, as YAML 1.2 does.\n */\nexport function parseYaml(\n data: string,\n { origin, help, json = true, remember = false }: { origin: string; help: string; json?: boolean; remember?: boolean },\n): object {\n if (json && /^\\s*[[{]/.test(data)) {\n try {\n return JSON.parse(data) as object\n } catch {\n // Not JSON, so YAML parses it below.\n }\n }\n try {\n const events = parseEvents(data, {})\n const documents = constructFromEvents(events, { source: data, schema: CORE_SCHEMA })\n if (remember && documents.length === 1) rememberEvents({ source: data, events })\n return documents[0] 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 { dirname, join, normalize, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { escapePointerToken, getErrorMessage, memo, toError } from '@internals/utils'\nimport { Diagnostics } from '@kubb/kit'\nimport type { AdapterSource, Diagnostic, Harness } from '@kubb/kit'\nimport { upgrade } from '@scalar/openapi-upgrader'\nimport { bundle } from 'api-ref-bundler'\nimport { namedEntryKeys } from '../constants.ts'\nimport { markLegacyDocument } from '../oas.ts'\nimport { createRefs } from '../refs.ts'\nimport type { Document } from '../types.ts'\nimport type { ValidationErrors, WorkerResult } from './validateSpec.ts'\nimport { type DocumentScan, resolveSchemaIds, scanDocument } from './schemaIds.ts'\nimport { assertInputExists, isAccessRefused, parseYaml, resolveSource, urlRegExp } from './source.ts'\n\ntype RefusalDiagnostic = InstanceType<typeof Diagnostics.Error>['diagnostic']\n\n// The scan of each document returned unbundled, so a later step can skip a walk it answers.\nconst scans = new WeakMap<object, DocumentScan>()\n\n/**\n * Rewrites `$id` and `$anchor` refs in place, then returns the scan of the result.\n */\nfunction resolveTargets(document: unknown): DocumentScan {\n const scan = scanDocument(document)\n if (!scan.schemaIds) return scan\n resolveSchemaIds(document)\n return scanDocument(document)\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/**\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 // An entry name in a named map is never a keyword itself, so a property named `dependentSchemas` holds keywords again.\n let inNamedMap = false\n for (const token of path) {\n const key = String(token)\n if (key.startsWith('x-') && !inNamedMap) return true\n inNamedMap = !inNamedMap && namedEntryKeys.has(key)\n }\n return false\n}\n\n/**\n * True when `node` is the value at `path` in `document`. api-ref-bundler reports the output path of a\n * failed `$ref`, so this tells a `$ref` in the input itself from one in a file it pulled in.\n */\nfunction isNodeAt(document: unknown, path: ReadonlyArray<string | number>, node: unknown): boolean {\n let current = document\n for (const token of path) {\n if (!current || typeof current !== 'object' || !Object.hasOwn(current, token)) return false\n current = (current as Record<string | number, unknown>)[token]\n }\n return current === node\n}\n\n/**\n * Returns the base for relative `$ref`s: the 3.2 `$self` resolved against `pathOrUrl`, else `pathOrUrl`.\n */\nexport function getBaseUri(pathOrUrl: string, root: unknown): string {\n const self = root && typeof root === 'object' ? (root as { $self?: unknown }).$self : undefined\n if (typeof self !== 'string' || !self) return pathOrUrl\n try {\n if (urlRegExp.test(self)) return new URL(self).href\n if (/^file:/i.test(self)) return fileURLToPath(self)\n if (/^[a-z][a-z\\d+.-]*:/i.test(self)) return pathOrUrl\n return urlRegExp.test(pathOrUrl) ? new URL(self, pathOrUrl).href : resolve(dirname(pathOrUrl), self)\n } catch {\n return pathOrUrl\n }\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. Relative `$ref`s resolve\n * against the OpenAPI 3.2 `$self` when the document sets one. Every other file or URL read,\n * 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 * So does any local file from a URL input. With `harness`, every `$ref` file and every URL is read\n * through it, and a target its rules refuse reports `KUBB_ACCESS_REFUSED`. Without one, a `$ref` reads\n * any file and host. `signal` cancels every request.\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(\n pathOrUrl: string,\n {\n document,\n sources = [],\n harness,\n signal,\n }: {\n document?: Document\n sources?: Array<string>\n harness?: Harness\n signal?: AbortSignal\n } = {},\n): Promise<Document> {\n const cache = memo.create<string, Promise<object | string>>()\n // api-ref-bundler refers to the same URL as both `https://` and the posix-normalized\n // `https:/`, and to `./openapi.yaml` as `openapi.yaml`, so key on the canonical href or the\n // normalized path to fetch each source once and to match the input.\n const toKey = (sourcePath: string) => (urlRegExp.test(sourcePath) ? new URL(sourcePath).href : normalize(sourcePath))\n const refused = new Set<string>()\n // What the harness refused, by the key of the file or URL it refused.\n const harnessRefusals = new Map<string, RefusalDiagnostic>()\n const read = ({ sourcePath, isRef }: { sourcePath: string; isRef: boolean }) => {\n if (!harness) return resolveSource(sourcePath, { remember: !isRef, signal })\n return resolveSource(sourcePath, {\n remember: !isRef,\n signal,\n fetch: (url, init) => harness.fetch(url, init),\n // The input itself is the file the host named, so only what it refers to goes through the rules.\n read: isRef ? (file) => harness.read(file) : undefined,\n }).catch((error: unknown) => {\n if (isRef && isAccessRefused(error)) harnessRefusals.set(toKey(sourcePath), error.diagnostic)\n throw error\n })\n }\n const refDiagnostic = ({ message, target }: { message: string; target: string | undefined }): RefusalDiagnostic => {\n const harnessRefusal = target === undefined ? undefined : harnessRefusals.get(target)\n if (harnessRefusal) return harnessRefusal\n if (target === undefined || !refused.has(target)) {\n return {\n code: Diagnostics.code.refNotFound,\n severity: '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 }\n }\n return {\n code: Diagnostics.code.accessRefused,\n severity: 'error',\n message: `Refused an external \\`$ref\\` to the local file ${target}.`,\n help: 'This input reads no local file. Inline the schema, or serve the file from a URL.',\n }\n }\n\n let entry = pathOrUrl\n let entryDocument: object | string | undefined = document\n const resolver = async (sourcePath: string) => {\n if (entryDocument !== undefined && toKey(sourcePath) === toKey(entry)) {\n return entryDocument\n }\n const key = toKey(sourcePath)\n const isRef = key !== toKey(pathOrUrl)\n // A URL input has no folder of its own, so it reads no local file.\n if (isRef && !urlRegExp.test(sourcePath) && urlRegExp.test(pathOrUrl)) {\n refused.add(key)\n throw new Error(`Refused ${sourcePath}`)\n }\n return memo(cache, key, () => {\n sources.push(key)\n return read({ sourcePath, isRef })\n })\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 // Before bundling, so a `$ref` to a schema's `$id` URL is not fetched.\n const scan = resolveTargets(root)\n\n if (typeof root === 'object' && root !== null && !scan.externalRef) {\n scans.set(root, scan)\n return root as Document\n }\n entry = getBaseUri(pathOrUrl, root)\n entryDocument = root\n\n return (await bundle(entry, resolver, {\n hooks: {\n onError: (message, { path, value }, detail) => {\n // api-ref-bundler also swallows a canceled request, so stop here instead of reporting it as a missing ref.\n signal?.throwIfAborted()\n // Only a `$ref` in the input itself has a key in the document to point at.\n const pointer = isNodeAt(root, path, value) ? `#/${path.map((token) => escapePointerToken(String(token))).join('/')}` : undefined\n const diagnostic: Diagnostic = {\n // api-ref-bundler drops the rejection's message, so a failed `$ref` is matched by the key of its target.\n ...refDiagnostic({ message, target: detail && toKey(detail.document) }),\n severity: isExtensionPath(path) ? 'warning' : 'error',\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\nfunction readInlineData(data: unknown): Document {\n if (typeof data !== 'string') return structuredClone(data as Document)\n return parseYaml(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}\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(\n source: AdapterSource,\n sources: Array<string> = [],\n { harness, signal }: { harness?: Harness; signal?: AbortSignal } = {},\n): Promise<Document> {\n const raw = await (async (): Promise<Document> => {\n // YAML parsing also handles JSON.\n if (source.type === 'data') {\n const data = readInlineData(source.data)\n const isObject = Boolean(data) && typeof data === 'object'\n // `bundleDocument` returns the document as is when it has no external ref.\n if (source.root && isObject) return bundleDocument(join(source.root, inlineInputName), { document: data, sources, harness, signal })\n const scan = resolveTargets(data)\n if (isObject) scans.set(data, scan)\n return data\n }\n await assertInputExists(source.path)\n return bundleDocument(source.path, { sources, harness, signal })\n })()\n\n return upgradeDocument(raw, { pathRefs: scans.get(raw)?.pathRefs ?? true })\n}\n\n/** Upgrades Swagger 2.0 or OpenAPI 3.0 to 3.1. `pathRefs: false` skips the `#/paths/` ref walk. */\nfunction upgradeDocument(raw: Document, { pathRefs = true }: { pathRefs?: boolean } = {}): Document {\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 && pathRefs) {\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 const declared = raw && typeof raw === 'object' ? ((raw as { openapi?: unknown }).openapi ?? (raw as { swagger?: unknown }).swagger) : undefined\n const legacy = declared !== undefined && /^(2|3\\.0)(\\.|$)/.test(String(declared))\n try {\n const document = upgrade(raw, '3.1') as Document\n if (legacy) markLegacyDocument(document)\n return document\n } catch (error) {\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 { validateSpec } = await import('./validateSpec.ts')\n // `validateSpec` dereferences its input in place, so clone to keep the cached document intact.\n const result = await validateSpec(structuredClone(document))\n if (throwOnError) return throwResult(result)\n reportResult(result)\n}\n\nfunction throwResult(result: WorkerResult): void {\n if ('valid' in result && result.valid) return\n throw new Diagnostics.Error({\n code: Diagnostics.code.invalidSpec,\n severity: 'error',\n // The code frames number a JSON copy of the spec, not the user's file, but they still show which key fails.\n message: 'thrown' in result ? result.thrown : result.message,\n help: 'Fix each problem listed in the spec, then validate again.',\n })\n}\n\nfunction reportResult(result: WorkerResult): void {\n if ('thrown' in result) return reportInvalidSpec(result.thrown)\n if (!result.valid) 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// A worker gets its own heap, whose young generation V8 lets grow to tens of megabytes before it\n// collects. Validation makes mostly short-lived objects, so a small one frees them sooner at no cost in time.\nconst VALIDATION_WORKER_LIMITS = { maxYoungGenerationSizeMb: 4 }\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, resourceLimits: VALIDATION_WORKER_LIMITS })\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 reportResult(message)\n}\n","import { escapePointerToken, memo } from '@internals/utils'\nimport { pascalCase } from '@kubb/core'\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\nexport type 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\n// Names are compared in PascalCase, the form the generated identifiers use.\nclass SchemaNames {\n readonly #taken: Set<string>\n\n constructor(reserved: Iterable<string>) {\n this.#taken = new Set(reserved)\n }\n\n // The first free name of `base`, `base2`, `base3`, … A `from` number skips the plain `base`.\n claim({ base, from }: { base: string; from?: number }): string {\n let n = from ?? 1\n let name = from ? `${base}${n}` : base\n while (this.#taken.has(pascalCase(name))) {\n n = Math.max(n + 1, 2)\n name = `${base}${n}`\n }\n this.#taken.add(pascalCase(name))\n return name\n }\n}\n\nfunction createSchemaNames(reserved: Iterable<string>): SchemaNames {\n return new SchemaNames(reserved)\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 /**\n * Follows a `$ref` to the schema it ends at. Keywords next to a `$ref` apply together with its target,\n * so they stay on a one-member `allOf` around it.\n */\n function inlineRef(schema: SchemaObject, seen = new Set<string>()): SchemaObject {\n if (!isReference(schema) || seen.has(schema.$ref)) return schema\n const { $ref, ...siblings } = schema\n const resolved = refs.resolve<SchemaObject>($ref)\n if (!resolved) return schema\n const target = inlineRef(resolved, seen.add($ref))\n if (!Object.keys(siblings).length) return target\n const own = 'allOf' in siblings && Array.isArray(siblings.allOf) ? siblings.allOf : []\n const wrapped = { ...siblings, allOf: [...own, target] }\n\n return wrapped as SchemaObject\n }\n\n /**\n * Replaces a `$ref` schema with its target. A plain `$ref` to another `$ref` stays as it is, so the parser reads it as an alias.\n */\n function resolveSchemaRef(schema: SchemaObject): SchemaObject {\n if (!isReference(schema)) return schema\n if (Object.keys(schema).length > 1) return inlineRef(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 = memo.create<string, Array<SchemaWithMetadata>>()\n for (const item of candidates) {\n const key = pascalCase(item.originalName)\n memo(normalizedNames, key, () => []).push(item)\n }\n\n const schemas: Record<string, SchemaObject> = {}\n const renames = new Map<string, string>()\n const pointers = new Map<string, string>()\n // Every original name is reserved up front, so a suffixed name never takes one that a later group keeps.\n const names = createSchemaNames(normalizedNames.keys())\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 // A collision across sources gets a semantic suffix, within one source a numeric one, counting up while taken.\n const uniqueName = (() => {\n if (isSingle || (!hasMultipleSources && !index)) return item.originalName\n return hasMultipleSources\n ? names.claim({ base: item.originalName + semanticSuffixes[item.source] })\n : names.claim({ base: item.originalName, from: index + 1 })\n })()\n schemas[uniqueName] = item.schema\n pointers.set(uniqueName, item.pointer ?? item.ref)\n if (uniqueName !== item.originalName || item.nested) renames.set(item.ref, uniqueName)\n })\n }\n\n return { schemas: sortSchemas(schemas, renames), renames, pointers }\n}\n","import { unescapePointerToken } from '@internals/utils'\nimport type { ast } from '@kubb/kit'\nimport { pickStrings } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport type { Document, SecuritySchemeObject } from '../types.ts'\n\nconst SCHEME_POINTER = '#/components/securitySchemes/'\nconst API_KEY_LOCATIONS = new Set(['header', 'query', 'cookie'])\n\nfunction getCredential(scheme: SecuritySchemeObject): ast.AuthCredential | undefined {\n if (scheme.type === 'apiKey') {\n return scheme.name && scheme.in && API_KEY_LOCATIONS.has(scheme.in)\n ? { type: 'apiKey', in: scheme.in as 'header' | 'query' | 'cookie', name: scheme.name }\n : undefined\n }\n if (scheme.type === 'http') {\n return scheme.scheme ? { type: 'http', scheme: scheme.scheme.toLowerCase(), ...(scheme.bearerFormat && { bearerFormat: scheme.bearerFormat }) } : undefined\n }\n if (scheme.type === 'openIdConnect') return { type: 'openIdConnect', ...(scheme.openIdConnectUrl && { url: scheme.openIdConnectUrl }) }\n if (scheme.type === 'oauth2') {\n const flows = Object.entries(scheme.flows ?? {}).map(([name, flow]) => {\n const scopes = flow && typeof flow === 'object' && flow.scopes && typeof flow.scopes === 'object' ? { scopes: flow.scopes as Record<string, string> } : {}\n return [name, { ...pickStrings(flow, ['authorizationUrl', 'deviceAuthorizationUrl', 'tokenUrl', 'refreshUrl']), ...scopes }] as const\n })\n return { type: 'oauth2', flows: Object.fromEntries(flows), ...(scheme.oauth2MetadataUrl && { metadataUrl: scheme.oauth2MetadataUrl }) }\n }\n return scheme.type === 'mutualTLS' ? { type: 'mutualTLS' } : undefined\n}\n\n/**\n * Maps `components.securitySchemes` to `AuthScheme` entries, leaving out a scheme a client cannot place.\n */\nexport function toAuthSchemes(schemes: Record<string, unknown> | undefined, refs: Refs): Array<ast.AuthScheme> {\n return Object.entries(schemes ?? {}).flatMap(([name, value]) => {\n const scheme = refs.deref<SecuritySchemeObject>(value)\n const credential = scheme && getCredential(scheme)\n if (!scheme || !credential) return []\n return [\n {\n name,\n ...(scheme.description && { description: scheme.description }),\n ...(scheme.deprecated && { deprecated: true }),\n credential,\n },\n ]\n })\n}\n\n/**\n * Maps security requirements to `AuthRequirement` entries. A 3.2 URI key becomes the scheme name.\n */\nexport function toAuthRequirements(requirements: unknown, document: Document): Array<ast.AuthRequirement> | undefined {\n if (!Array.isArray(requirements)) return undefined\n const schemes = document.components?.securitySchemes ?? {}\n const toName = (key: string) => {\n const index = key.indexOf(SCHEME_POINTER)\n return Object.hasOwn(schemes, key) || index === -1 ? key : unescapePointerToken(key.slice(index + SCHEME_POINTER.length))\n }\n\n return requirements\n .filter((requirement): requirement is Record<string, unknown> => !!requirement && typeof requirement === 'object')\n .map((requirement) =>\n Object.entries(requirement).map(([key, scopes]) => ({\n scheme: toName(key),\n ...(Array.isArray(scopes) && scopes.length && { scopes: scopes.map(String) }),\n })),\n )\n}\n","import { type ast, 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\n/**\n * Maps OpenAPI servers to `InputServer` entries: drops entries without a `url` and fills `{variable}` defaults.\n */\nexport function toInputServers(servers: Array<ServerObject>): Array<ast.InputServer> {\n return servers\n .filter((entry) => entry.url)\n .map(({ url, name, description, variables }) => {\n const declared = { ...(name !== undefined && { name }), ...(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}\n","import type { ast } from '@kubb/kit'\nimport { getExternalDocs } from '../oas.ts'\nimport type { TagObject } from '../types.ts'\n\nexport function toInputTags(tags: Array<TagObject>): Array<ast.InputTag> {\n return tags\n .filter((tag) => typeof tag.name === 'string')\n .map(({ name, summary, description, parent, kind, externalDocs }) => {\n const docs = getExternalDocs(externalDocs)\n return {\n name,\n ...(typeof summary === 'string' && { summary }),\n ...(typeof description === 'string' && { description }),\n ...(typeof parent === 'string' && { parent }),\n ...(typeof kind === 'string' && { kind }),\n ...(docs && { externalDocs: docs }),\n }\n })\n}\n","import { getFormatType, specialCasedFormats, structuralKeys } from '../constants.ts'\nimport { isReference } from '../oas.ts'\nimport type { ReferenceObject, SchemaObject } from '../types.ts'\nimport type { DateOnlyTypeValue, DateTimeTypeValue, ParserOptions } from '../parserOptions.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 getFormatType(format) !== 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(dateType: ParserOptions['dateType'], format: 'date-time' | 'date' | 'time'): DateTimeTypeValue | 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\n/**\n * Whether the schema and its inline `allOf` members hold more than one distinct `pattern`. A value must match every one.\n */\nexport function hasSeveralPatterns(schema: SchemaObject): boolean {\n const members = (schema.allOf ?? []) as Array<SchemaObject | ReferenceObject>\n const patterns = [schema, ...members].map((item) => (isReference(item) ? undefined : item.pattern)).filter((pattern) => pattern !== undefined)\n\n return new Set(patterns).size > 1\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 // A node holds only one `pattern`, so several patterns stay an intersection.\n if (hasSeveralPatterns(schema)) return schema\n\n // Destructure `allOf` out instead of `delete merged.allOf`: a `delete` transitions the freshly\n // spread object into V8 dictionary (slow) mode, and this runs per `allOf` schema during parsing.\n const { allOf: _allOf, ...rest } = schema\n const merged = rest as SchemaObject\n\n for (const fragment of allOfFragments) {\n for (const [key, value] of Object.entries(fragment)) {\n merged[key as keyof SchemaObject] ??= value as SchemaObject[keyof SchemaObject]\n }\n }\n\n return merged\n}\n","import { ast } from '@kubb/kit'\nimport { getExternalDocs, pickExtensions } from '../oas.ts'\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 */\nexport type NodeBaseContext = Pick<ConvertContext, 'schema' | 'name' | 'nullable' | 'defaultValue'>\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: ast.CreateSchemaInput): 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 externalDocs: getExternalDocs(schema.externalDocs),\n extensions: pickExtensions(schema),\n ...extras,\n })\n}\n","import { ast, enumPrimitive, 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\nexport type 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// OpenAPI allows a bare schema name, such as `Dog`, as a mapping value.\nfunction toMappingRef(value: string): string {\n return value.includes('/') ? value : `${SCHEMA_REF_PREFIX}${value}`\n}\n\n/**\n * Returns the `$ref` of an OpenAPI 3.2 `defaultMapping`, written as a schema name or a `$ref`; `undefined` when none.\n */\nexport function getDefaultMappingRef(discriminator: DiscriminatorObject | undefined): string | undefined {\n const value = discriminator?.defaultMapping\n if (!value) return undefined\n\n return toMappingRef(value)\n}\n\n/**\n * Returns every discriminator key whose mapping value matches `ref`, in mapping order.\n * A bare schema name in the mapping matches its `#/components/schemas/<name>` ref.\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]) => toMappingRef(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, value]) => {\n const target = toMappingRef(value)\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 * Whether a member can carry the discriminator property. A discriminator is only a hint, so an array\n * or primitive member keeps its own type instead of an intersection no value can satisfy.\n */\nfunction isObjectLike(member: unknown, refs: Refs): boolean {\n const schema = isReference(member) ? refs.resolve<SchemaObject>(member.$ref, { report: false }) : (member as SchemaObject | undefined)\n const type = schema?.type\n if (type === undefined) return true\n\n return Array.isArray(type) ? type.includes('object') : type === 'object'\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.schema.narrow(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 = ast.ref.getName(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 /** Whether the variant, or a schema it composes, pins the discriminator property to literal values. */\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 const pins = (candidate: SchemaObject) => Array.isArray(candidate.enum) || candidate.const !== undefined\n // The OpenAPI 3.1 nullable form `anyOf: [{ enum }, { type: 'null' }]` pins the value, a plain `string` member does not.\n const members = ((resolved?.anyOf ?? resolved?.oneOf ?? []) as Array<SchemaObject>).filter((member) => member.type !== 'null')\n if (resolved && (pins(resolved) || (members.length > 0 && members.every(pins)))) 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 const defaultRef = getDefaultMappingRef(discriminator)\n\n return unionMembers.map((s) => {\n const ref = isReference(s) ? s.$ref : undefined\n // The default member accepts every value outside `mapping`, so it is never narrowed.\n const isDefault = ref !== undefined && ref === defaultRef\n const mappedValues = isDefault ? [] : findDiscriminators({ mapping: discriminator?.mapping, ref })\n const implicitValue = mappedValues.length || isDefault ? 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 || !isObjectLike(s, refs)) {\n return memberNode\n }\n\n const narrowedDiscriminatorNode = sharedPropertiesNode\n ? pickDiscriminatorPropertyNode(\n ast.macro.apply(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 // The default child accepts every value outside `mapping`, so it drops the parent like a mapped child but gets no discriminant.\n const isDefault = childRef === getDefaultMappingRef(discriminator)\n const values = isDefault ? [] : 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 && (isDefault || 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, macroDedupeUnion, mergeAdjacentObjectsLazy } from '@kubb/kit'\nimport { SCHEMA_REF_PREFIX } from '../../constants.ts'\nimport { getExternalDocs, isDiscriminator, isLegacyDocument, isNullable, isReference, pickExtensions } 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 getDefaultMappingRef,\n removeInheritedDiscriminator,\n extractDiscriminatedAllOfMembers,\n narrowUnionMembers,\n propertyTypeOf,\n} from '../discriminator/preserve.ts'\nimport type { ConvertContext } from '../parseSchema.ts'\nimport { extractExamples, hasSeveralPatterns } 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 */\nexport function collectSiblingProperties(\n allOfMembers: Array<SchemaObject | ReferenceObject>,\n refs: Refs,\n outerProperties?: Record<string, unknown>,\n): Record<string, unknown> {\n // No prototype, so an own `__proto__` property is copied as a key, not as the prototype.\n const properties: Record<string, unknown> = Object.assign(Object.create(null), outerProperties)\n const visited = new Set<string>()\n\n /** Adds the properties of one member, following its `$ref` and its own `allOf`. */\n function collectFrom(item: SchemaObject | ReferenceObject | undefined): void {\n if (!item) return\n\n if (isReference(item)) {\n const { $ref, ...siblings } = item\n // The target can be another `$ref`, an alias, which `visited` keeps from looping.\n if (!visited.has($ref)) {\n visited.add($ref)\n collectFrom(refs.resolve<SchemaObject>($ref, { report: false }) ?? undefined)\n }\n // Keywords next to a `$ref` apply too, and win over the target's.\n collectFrom(siblings as SchemaObject)\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 `ast.ref.mergeSchema(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 }) === null) {\n return createNode(ctx, { type: ast.schema.types.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 extensions: pickExtensions({ ...resolvedSchema.extensions, ...schema }),\n })\n }\n\n const targetName = renames?.get(schema.$ref!)\n\n return createNode(ctx, {\n type: ast.schema.types.ref,\n name: ast.ref.getName(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.schema.types.not, members: [parse({ schema: subschema })] })\n\n return createNode({ schema, name, nullable, defaultValue }, { type: ast.schema.types.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. The parser reads their `if`/`then`/`else` into `conditionals`.\n */\nexport function isAnnotationMember(member: unknown): boolean {\n return !!member && typeof member === 'object' && !isReference(member) && Object.keys(member).every((key) => annotationKeys.has(key))\n}\n\nfunction mergeAnnotations(schema: SchemaObject): SchemaObject {\n const members = schema.allOf as Array<SchemaObject | ReferenceObject>\n const annotations = members.filter(isAnnotationMember)\n const rest = members.filter((member) => !isAnnotationMember(member))\n\n return annotations.length && rest.length ? { ...Object.assign({}, ...annotations), ...schema, allOf: rest } : schema\n}\n\n/**\n * Whether the parent's own keywords become an intersection member: always beside `properties`, and\n * beside several patterns when the parent holds more than its type and annotations, such as `minLength`.\n */\nfunction keepsOwnKeywords(schema: SchemaObject): boolean {\n if (schema.properties) return true\n if (!hasSeveralPatterns(schema)) return false\n\n return Object.keys(schema).some((key) => key !== 'allOf' && key !== 'type' && key !== 'nullable' && !annotationKeys.has(key))\n}\n\n/**\n * Whether a one-member `allOf` adds nothing but annotations, so it parses as that member.\n */\nfunction isSingleMemberAllOf(schema: SchemaObject): boolean {\n return (\n schema.allOf!.length === 1 &&\n !schema.properties &&\n !(Array.isArray(schema.required) && schema.required.length) &&\n schema.additionalProperties === undefined &&\n !hasSeveralPatterns(schema)\n )\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 (isSingleMemberAllOf(schema)) {\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 extensions: pickExtensions({ ...memberNode.extensions, ...schema }),\n externalDocs: getExternalDocs(schema.externalDocs) ?? memberNode.externalDocs,\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 // An alias, a schema that is only a `$ref`, is followed to its target.\n const seen = new Set<string>()\n let deref: SchemaObject | ReferenceObject | null | undefined = item\n while (deref && isReference(deref) && !seen.has(deref.$ref)) {\n seen.add(deref.$ref)\n deref = refs.resolve<SchemaObject>(deref.$ref)\n }\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 (keepsOwnKeywords(schema)) {\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.schema.types.intersection,\n members: [...mergeAdjacentObjectsLazy(allOfMembers.slice(0, syntheticStart)), ...mergeAdjacentObjectsLazy(allOfMembers.slice(syntheticStart))],\n },\n )\n}\n\nconst scalarTypes = new Set(['string', 'number', 'integer', 'boolean'])\n\n/**\n * Copies a scalar parent `type` and `format` onto inline members without a `type`. JSON Schema applies\n * sibling keywords to every member, so `type: 'integer', anyOf: [{ minimum: 10 }]` keeps each member an integer.\n */\nfunction inheritScalarType(members: Array<unknown>, { schema, type }: Pick<ConvertContext, 'schema' | 'type'>): Array<unknown> {\n if (!type || !scalarTypes.has(type)) return members\n // `type` holds only the first entry of a multi-type array, so it does not apply to every member.\n if (Array.isArray(schema.type) && schema.type.filter((t) => t !== 'null').length > 1) return members\n\n return members.map((member) => {\n if (!member || typeof member !== 'object' || isReference(member) || (member as SchemaObject).type !== undefined) return member\n const obj = member as SchemaObject\n\n return { type, ...(schema.format !== undefined && obj.format === undefined && { format: schema.format }), ...obj }\n })\n}\n\n/**\n * Converts a `oneOf` / `anyOf` schema into a `UnionSchemaNode`.\n */\nexport function convertUnion(context: ConvertContext): ast.SchemaNode {\n if (context.schema.enum?.length) {\n const { enum: values, ...union } = context.schema\n // A sibling `enum` restricts the union too. A 3.0 `nullable: true`, which the upgrade turns into a `null` member, keeps `null` allowed.\n const nullable =\n context.nullable ||\n [...(union.oneOf ?? []), ...(union.anyOf ?? [])].some((member) => {\n const resolved = isReference(member) ? context.refs.resolve<SchemaObject>(member.$ref, { report: false }) : (member as SchemaObject)\n return !!resolved && !isReference(resolved) && isNullable(resolved, context.document)\n })\n const enumSchema: SchemaObject = { type: union.type, enum: nullable && isLegacyDocument(context.document) ? [...values, null] : values }\n const members = [convertUnion({ ...context, schema: union }), context.parse({ schema: enumSchema })]\n return createNode(context, { type: ast.schema.types.intersection, members })\n }\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 discriminator = isDiscriminator(schema) ? schema.discriminator : undefined\n const declaredMembers = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])]\n // From 3.2 `propertyName` is optional, and a discriminator with only `defaultMapping` still adds that member.\n const defaultRef = getDefaultMappingRef(typeof schema.discriminator === 'object' ? schema.discriminator : undefined)\n const allMembers =\n defaultRef && !declaredMembers.some((member) => isReference(member) && member.$ref === defaultRef)\n ? [...declaredMembers, { $ref: defaultRef }]\n : declaredMembers\n const unionMembers = resolveUnionMembers(inheritScalarType(allMembers, context), schema.properties ?? {})\n const strategy: 'one' | 'any' = schema.oneOf ? 'one' : 'any'\n const explicitDiscriminatorPropertyName = discriminator?.propertyName\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.schema.types.union,\n strategy,\n members,\n discriminatorPropertyName: explicitDiscriminatorPropertyName ?? ast.schema.inferDiscriminator(members),\n })\n\n const requiredProperties = missingRequired.map((name) =>\n ast.factory.createProperty({ name, required: true, schema: ast.factory.createSchema({ type: ast.schema.types.unknown }) }),\n )\n const siblings = sharedPropertiesNode ? [sharedPropertiesNode] : []\n if (requiredProperties.length) {\n siblings.push(ast.factory.createSchema({ type: ast.schema.types.object, properties: requiredProperties }))\n }\n\n if (!siblings.length) {\n return unionNode\n }\n\n return createNode(ctx, { type: ast.schema.types.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.schema.types.union,\n strategy,\n members,\n discriminatorPropertyName: explicitDiscriminatorPropertyName ?? ast.schema.inferDiscriminator(members),\n })\n\n return ast.macro.apply(unionNode, [macroDedupeUnion], { 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 return createNode(\n { schema, name, nullable, defaultValue },\n {\n type: ast.schema.types.union,\n members: nonNullTypes.map((t) => {\n // The union node keeps the `x-*` keys, so members do not repeat them.\n const raw = { ...Object.fromEntries(Object.entries(schema).filter(([key]) => !key.startsWith('x-'))), type: t }\n const memberSchema = raw as SchemaObject\n return parse({ schema: memberSchema, name })\n }),\n },\n )\n}\n","import { escapePointerToken, memo } from '@internals/utils'\nimport { ast, 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`, `KUBB_DUPLICATE_DISCRIMINATOR`) 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\nclass FormatTally {\n // Pointers per unsupported format, collected while `groupUnsupportedFormats` runs.\n #pointers: Map<string, Set<string>> | undefined\n\n group<T>(fn: () => T): T {\n this.#pointers = memo.create()\n try {\n return fn()\n } finally {\n const tally = this.#pointers\n this.#pointers = undefined\n for (const [format, pointers] of tally) reportUnsupportedFormat(format, [...pointers])\n }\n }\n\n add(format: string, pointer: string): void {\n if (!this.#pointers) return reportUnsupportedFormat(format, [pointer])\n memo(this.#pointers, format, () => new Set()).add(pointer)\n }\n}\n\nconst formatTally = new FormatTally()\n\n/**\n * Runs `fn` and reports `KUBB_UNSUPPORTED_FORMAT` once per format with the number of schemas that use it,\n * instead of once per schema. `format` is an open value in OpenAPI, so a large spec would otherwise print\n * thousands of warnings that say the same thing. `fn` must be synchronous.\n */\nexport function groupUnsupportedFormats<T>(fn: () => T): T {\n return formatTally.group(fn)\n}\n\nfunction reportUnsupportedFormat(format: string, pointers: Array<string>): void {\n const count = pointers.length\n Diagnostics.report({\n code: Diagnostics.code.unsupportedFormat,\n severity: 'warning',\n message:\n count === 1\n ? `Kubb does not map the format \"${format}\" to a specific type, so it falls back to the base type.`\n : `Kubb does not map the format \"${format}\" to a specific type, so ${count} schemas fall back to the base type.`,\n help: `Use a format Kubb supports, or handle \"${format}\" with a custom parser or plugin.`,\n location: { kind: 'schema', pointer: pointers[0]! },\n })\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 formatTally.add(node.format, pointer)\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.discriminatorPropertyName) reportDuplicateDiscriminators(node, node.discriminatorPropertyName, pointer)\n\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\n/**\n * Reports a declared discriminator whose value pins more than one member. The spec cannot tell\n * those members apart, and Zod's `z.discriminatedUnion` throws on the first parse.\n * One diagnostic per union, since the build dedupes by code and pointer.\n */\nfunction reportDuplicateDiscriminators(node: ast.UnionSchemaNode, propertyName: string, pointer: string): void {\n const keyword = node.strategy === 'any' ? 'anyOf' : 'oneOf'\n const membersByValue = memo.create<Literal, Array<string>>()\n\n for (const [index, member] of (node.members ?? []).entries()) {\n const label = memberName(member) ?? `${keyword}/${index}`\n for (const value of memberValues(member, propertyName)) memo(membersByValue, value, () => []).push(label)\n }\n\n const duplicates = [...membersByValue].filter(([, members]) => members.length > 1)\n if (!duplicates.length) return\n\n Diagnostics.report({\n code: Diagnostics.code.duplicateDiscriminator,\n severity: 'warning',\n message: duplicates\n .map(([value, members]) => `Discriminator \"${propertyName}\" value ${JSON.stringify(value)} matches more than one member (${members.join(', ')}).`)\n .join(' '),\n help: `Give each member its own \"${propertyName}\" value, or drop the discriminator. Zod's z.discriminatedUnion throws on the first parse of this union.`,\n location: { kind: 'schema', pointer },\n })\n}\n\ntype Literal = string | number | boolean | null\n\n// Values a member allows for the discriminator. A nested `oneOf`/`anyOf` allows any of its alternatives' values.\nfunction memberValues(node: ast.SchemaNode, propertyName: string, seen = new Set<ast.SchemaNode>()): Array<Literal> {\n if (seen.has(node)) return []\n seen.add(node)\n const target = node.type === 'ref' && node.schema ? node.schema : node\n if (target.type === 'union') return [...new Set(target.members?.flatMap((member) => memberValues(member, propertyName, seen)))]\n\n return intersect(ast.schema.findProperties({ node, propertyName }).map((property) => [...ast.schema.getLiterals(property.schema)]))\n}\n\n// Every slice that pins values narrows the set, so only values they all allow count. Unpinned slices are ignored.\nfunction intersect(slices: Array<Array<Literal>>): Array<Literal> {\n const pinned = slices.filter((values) => values.length > 0)\n return pinned.reduce((acc, values) => acc.filter((value) => values.includes(value)), pinned[0] ?? [])\n}\n\n// A member is a `$ref`, or an intersection of the `$ref` and its narrowed discriminant.\nfunction memberName(member: ast.SchemaNode): string | undefined {\n if (member.type === 'ref') return member.name ?? undefined\n if (member.type === 'intersection') return member.members?.map(memberName).find(Boolean)\n return undefined\n}\n","import { ast } from '@kubb/kit'\nimport { isJsonMimeType, isOpenApi32, isReference } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport type { Document, MediaTypeObject, ReferenceObject, SchemaObject } from '../types.ts'\n\nconst streamMediaTypes = new Set(['application/jsonl', 'application/x-ndjson', 'application/json-seq', 'text/event-stream'])\n\n/**\n * Returns `true` for a media type read as a stream of items: SSE, JSON Lines, a `+json-seq` sequence, or any media type that declares `itemSchema`.\n */\nexport function isStream(contentType: string, mediaType: MediaTypeObject | null): boolean {\n const baseType = ast.mediaType.getBase(contentType)\n const streamed = streamMediaTypes.has(baseType) || (baseType.startsWith('application/') && baseType.endsWith('+json-seq'))\n return streamed || mediaType?.itemSchema !== undefined\n}\n\n/**\n * Whether the media type is `text/event-stream`, with or without parameters.\n */\nexport function isEventStream(contentType: string): boolean {\n return ast.mediaType.getBase(contentType) === 'text/event-stream'\n}\n\n/**\n * Replaces a `data` string that holds JSON with its `contentSchema`, so the event reads as parsed.\n */\nfunction withParsedData(schema: SchemaObject, refs: Refs): SchemaObject {\n const data = schema.properties?.data as SchemaObject | ReferenceObject | undefined\n const resolved = data && isReference(data) ? refs.resolve<SchemaObject>(data.$ref, { report: false }) : data\n if (!resolved?.contentSchema || !resolved.contentMediaType || !isJsonMimeType(resolved.contentMediaType)) return schema\n\n const parsed = { ...schema, properties: { ...schema.properties, data: resolved.contentSchema } }\n return parsed as SchemaObject\n}\n\n/**\n * Inlines a `$ref` event whose JSON `data` string needs its `contentSchema`, so the shared component keeps `data` as a string elsewhere.\n */\nfunction withParsedRef(schema: ReferenceObject, refs: Refs): SchemaObject | ReferenceObject {\n const resolved = refs.resolve<SchemaObject | ReferenceObject>(schema.$ref, { report: false })\n if (!resolved || isReference(resolved)) return schema\n const parsed = withParsedData(resolved, refs)\n return parsed === resolved ? schema : parsed\n}\n\n/**\n * Keywords next to `$ref` that only annotate it, so a reference that carries nothing else stays a reference.\n */\nconst REF_ANNOTATIONS = new Set(['$ref', 'summary', 'description', '$comment'])\n\n/**\n * Applies `extra` on top of `base` the way JSON Schema does: `properties` and `required` add up, other keywords of `extra` win.\n */\nfunction mergeSchemas(base: Pick<SchemaObject, 'properties' | 'required'>, extra: SchemaObject): SchemaObject {\n const required = [...new Set([...(Array.isArray(base.required) ? base.required : []), ...(Array.isArray(extra.required) ? extra.required : [])])]\n const merged = { type: 'object', ...base, ...extra, properties: { ...base.properties, ...extra.properties }, ...(required.length ? { required } : {}) }\n return merged as SchemaObject\n}\n\n/**\n * Normalizes the OpenAPI 3.2 `text/event-stream` item schema into one schema per event.\n * - Keywords next to a `$ref` apply to the referenced schema.\n * - Shared `properties` merge into each inline `oneOf`/`anyOf` member.\n * - A JSON `data` string becomes its `contentSchema`.\n */\nfunction toEventSchema(schema: SchemaObject | ReferenceObject, refs: Refs): SchemaObject | ReferenceObject {\n if (isReference(schema)) {\n const siblings = Object.fromEntries(Object.entries(schema).filter(([key]) => !REF_ANNOTATIONS.has(key)))\n const resolved = Object.keys(siblings).length ? refs.resolve<SchemaObject>(schema.$ref, { report: false }) : null\n return resolved ? toEventSchema(mergeSchemas(resolved, siblings as SchemaObject), refs) : withParsedRef(schema, refs)\n }\n const key = schema.oneOf?.length ? 'oneOf' : schema.anyOf?.length ? 'anyOf' : undefined\n if (!key) return withParsedData(schema, refs)\n\n const members = schema[key] as Array<SchemaObject | ReferenceObject>\n const { properties, required, ...rest } = schema\n // Shared properties cannot move into a `$ref` member, so they only merge when every member is inline.\n const merge = !!properties && !members.some(isReference)\n const shared = { properties, required }\n const event = {\n ...(merge ? rest : schema),\n [key]: members.map((member) => (isReference(member) ? withParsedRef(member, refs) : withParsedData(merge ? mergeSchemas(shared, member) : member, refs))),\n }\n return event as SchemaObject\n}\n\nconst SSE_FIELDS: ReadonlySet<string> = new Set(['event', 'id', 'retry', 'data'])\n\n/**\n * Property names of the schema and its `allOf` members, following `$ref`s, as one combined object declares them.\n */\nfunction collectFields(schema: SchemaObject | ReferenceObject, refs: Refs, seen: Set<string>): Array<string> {\n if (isReference(schema)) {\n if (seen.has(schema.$ref)) return []\n seen.add(schema.$ref)\n const resolved = refs.resolve<SchemaObject | ReferenceObject>(schema.$ref, { report: false })\n return resolved ? collectFields(resolved, refs, seen) : []\n }\n const members = (schema.allOf ?? []) as Array<SchemaObject | ReferenceObject>\n return [...Object.keys(schema.properties ?? {}), ...members.flatMap((member) => collectFields(member, refs, seen))]\n}\n\n/**\n * Whether the schema, following `$ref`s, or a `oneOf`/`anyOf` member of it is a whole Server-Sent Event: its combined\n * `allOf` fields declare `data`, or `event` with no field an event cannot carry. An `event` next to fields such as\n * `planet` is the payload's own property, sent as JSON in the `data:` line.\n */\nfunction declaresEventFields(schema: SchemaObject | ReferenceObject, refs: Refs, seen: Set<string>): boolean {\n if (isReference(schema)) {\n if (seen.has(schema.$ref)) return false\n seen.add(schema.$ref)\n const resolved = refs.resolve<SchemaObject | ReferenceObject>(schema.$ref, { report: false })\n return !!resolved && declaresEventFields(resolved, refs, seen)\n }\n const fields = collectFields(schema, refs, new Set(seen))\n if (fields.includes('data')) return true\n if (fields.includes('event')) return fields.every((field) => SSE_FIELDS.has(field))\n\n const members = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])] as Array<SchemaObject | ReferenceObject>\n return members.some((member) => declaresEventFields(member, refs, seen))\n}\n\n/**\n * Returns `'event'` when the item is a whole event, directly or in a composition member (see `declaresEventFields`), else `'data'`.\n */\nexport function getItemShape(schema: SchemaObject | ReferenceObject, refs: Refs): 'event' | 'data' {\n return declaresEventFields(schema, refs, new Set()) ? 'event' : 'data'\n}\n\n/**\n * Returns the raw item schema: `itemSchema`, or `schema` on `text/event-stream` as 3.0 and 3.1 documents write one event.\n */\nexport function getItemSchema({\n contentType,\n mediaType,\n refs,\n document,\n}: {\n contentType: string\n mediaType: MediaTypeObject | null\n refs: Refs\n document: Document\n}): SchemaObject | ReferenceObject | null {\n if (!mediaType || !isStream(contentType, mediaType)) return null\n // Below 3.2 there is no `itemSchema`, so `schema` on an event stream is the event by convention; from 3.2 it is the whole stream.\n const raw = mediaType.itemSchema ?? (isEventStream(contentType) && !isOpenApi32(document) ? mediaType.schema : undefined)\n if (!raw) return null\n\n return isEventStream(contentType) ? toEventSchema(raw, refs) : raw\n}\n","import { escapePointerToken } from '@internals/utils'\nimport type { ast } from '@kubb/kit'\nimport { collectSiblingProperties } from '../emit/converters/composition.ts'\nimport { getBinaryFallbackSchema, isReference, pickExtensions } from '../oas.ts'\nimport type { Refs } from '../refs.ts'\nimport { scanSchema } from '../schemaDiagnostics.ts'\nimport type { Document, EncodingObject, ExampleObject, MediaTypeObject, ReferenceObject, SchemaObject } from '../types.ts'\nimport { getItemSchema, getItemShape, isEventStream, isStream } from './mediaType.ts'\n\nconst PARAMETER_STYLES = new Set(['matrix', 'label', 'form', 'simple', 'spaceDelimited', 'pipeDelimited', 'deepObject', 'cookie'])\n\nexport function pickStyleFields({ style, explode, allowReserved }: { style?: string; explode?: boolean; allowReserved?: boolean }): {\n style?: ast.ParameterStyle\n explode?: boolean\n allowReserved?: boolean\n} {\n return {\n ...(style !== undefined && PARAMETER_STYLES.has(style) ? { style: style as ast.ParameterStyle } : {}),\n ...(explode !== undefined ? { explode } : {}),\n ...(allowReserved !== undefined ? { allowReserved } : {}),\n }\n}\n\nexport function getEncodingFields({\n encoding,\n prefixEncoding,\n itemEncoding,\n}: Pick<EncodingObject, 'encoding' | 'prefixEncoding' | 'itemEncoding'>): Pick<ast.EncodingNode, 'encoding' | 'prefixEncoding' | 'itemEncoding'> {\n const entries = Object.entries(encoding ?? {}).flatMap(([property, entry]) => {\n const node = toEncodingNode(entry)\n return Object.keys(node).length ? [[property, node] as const] : []\n })\n const item = itemEncoding && toEncodingNode(itemEncoding)\n\n return {\n ...(entries.length && { encoding: Object.fromEntries(entries) }),\n // Entries keep their position, so an empty one still stands for its part.\n ...(prefixEncoding?.length && { prefixEncoding: prefixEncoding.map(toEncodingNode) }),\n ...(item && Object.keys(item).length && { itemEncoding: item }),\n }\n}\n\nfunction toEncodingNode({ contentType, encoding, prefixEncoding, itemEncoding, ...rest }: EncodingObject): ast.EncodingNode {\n return {\n ...(contentType !== undefined && { contentType }),\n ...pickStyleFields(rest),\n ...getEncodingFields({ encoding, prefixEncoding, itemEncoding }),\n }\n}\n\n/**\n * The examples of a media type or a parameter. Named `examples` win over a single `example`.\n */\nexport function getExamples({ example, examples }: { example?: unknown; examples?: Record<string, unknown> }, refs: Refs): Pick<ast.ContentNode, 'examples'> {\n const named = Object.entries(examples ?? {}).flatMap(([name, entry]) => {\n const resolved = refs.deref<ExampleObject>(entry)\n if (!resolved) return []\n const { summary, description, dataValue, value, serializedValue } = resolved\n const data = dataValue !== undefined ? dataValue : value\n return [\n {\n name,\n ...(typeof summary === 'string' && { summary }),\n ...(typeof description === 'string' && { description }),\n ...(data !== undefined && { value: data }),\n ...(typeof serializedValue === 'string' && { serializedValue }),\n },\n ]\n })\n if (named.length) return { examples: named }\n\n return example !== undefined ? { examples: [{ value: example }] } : {}\n}\n\nexport type ContentMap = Record<string, MediaTypeObject | ReferenceObject> | undefined\n\n/**\n * Returns the media type entry for `contentType`, resolving a `$ref` into `components.mediaTypes`. `null` when absent.\n */\nexport function getMediaType({ content, contentType, refs }: { content: ContentMap; contentType: string | undefined; refs: Refs }): MediaTypeObject | null {\n return contentType ? refs.deref<MediaTypeObject>(content?.[contentType]) : null\n}\n\ntype BodySchemaContext = {\n content: ContentMap\n contentType: string | undefined\n refs: Refs\n document: Document\n}\n\n/**\n * Returns the schema for one media type of a `content` map, before its `$ref` is resolved, with the binary fallback\n * for an emptied non-JSON entry. For a stream this is the item schema, so `schema: string` next to `itemSchema` types one item.\n */\nfunction getDeclaredBodySchema({ content, contentType, refs, document }: BodySchemaContext): SchemaObject | null {\n const entry = getMediaType({ content, contentType, refs })\n if (!contentType || !entry) return null\n\n const schema = getItemSchema({ contentType, mediaType: entry, refs, document }) ?? entry.schema\n // A declared `itemSchema`, even an empty one, is a schema of its own and not an emptied binary entry.\n const binary = entry.itemSchema ? undefined : getBinaryFallbackSchema(contentType, schema)\n return binary ?? (schema as SchemaObject | undefined) ?? null\n}\n\nfunction getStreamField({\n contentType,\n mediaType,\n refs,\n document,\n node,\n}: {\n contentType: string\n mediaType: MediaTypeObject | null\n refs: Refs\n document: Document\n node: ast.SchemaNode\n}): Pick<ast.ContentNode, 'stream'> {\n if (!isStream(contentType, mediaType)) return {}\n const raw = getItemSchema({ contentType, mediaType, refs, document })\n\n return {\n stream: {\n ...(raw ? { schema: node } : {}),\n ...(raw && isEventStream(contentType) ? { shape: getItemShape(raw, refs) } : {}),\n },\n }\n}\n\nfunction schemaKeyword(mediaType: MediaTypeObject | null): 'itemSchema' | 'schema' {\n return mediaType?.itemSchema ? 'itemSchema' : 'schema'\n}\n\n// Follows a `$ref` into `components.mediaTypes`, so a diagnostic lands on the source.\nfunction mediaTypePointer(content: ContentMap, contentType: string, fallback: string): string {\n const entry = content?.[contentType]\n return isReference(entry) ? entry.$ref : fallback\n}\n\nexport type ReadWriteFlag = 'readOnly' | 'writeOnly'\n\n// Reads the properties of the schema, its `$ref` target and its `allOf` members.\nfunction collectPropertyKeysByFlag({ schema, flag, refs }: { schema: SchemaObject | null; flag: ReadWriteFlag; refs: Refs }): Array<string> | null {\n if (!schema) return null\n\n const keys = Object.entries(collectSiblingProperties([schema], refs)).flatMap(([key, prop]) => (hasFlag({ prop, flag, refs }) ? [key] : []))\n return keys.length ? keys : null\n}\n\n// The flag counts next to a property `$ref` and on its target.\nfunction hasFlag({ prop, flag, refs }: { prop: unknown; flag: ReadWriteFlag; refs: Refs }): boolean {\n if (!prop || typeof prop !== 'object') return false\n if ((prop as Record<string, unknown>)[flag]) return true\n const target = isReference(prop) ? refs.resolve<SchemaObject>(prop.$ref, { report: false }) : null\n return !!target?.[flag]\n}\n\nexport type ContentEntryOptions = {\n content: ContentMap\n contentType: string | undefined\n /**\n * Pointer of the `content` map, used when the media type entry is not a `$ref`.\n */\n contentPointer: string\n /**\n * Properties a request (`readOnly`) or a response (`writeOnly`) leaves out.\n */\n omit: ReadWriteFlag\n refs: Refs\n document: Document\n}\n\nexport type ContentEntry = Omit<ast.ContentNode, 'kind' | 'contentType'>\n\n/**\n * Builds the fields of a request or response content node for one media type of a `content` map.\n * `parse` turns the body schema into a node, and returning `null` drops the entry.\n */\nexport function parseContentEntry(options: ContentEntryOptions & { parse: (schema: SchemaObject | null) => ast.SchemaNode }): ContentEntry\nexport function parseContentEntry(options: ContentEntryOptions & { parse: (schema: SchemaObject | null) => ast.SchemaNode | null }): ContentEntry | null\nexport function parseContentEntry({\n content,\n contentType,\n contentPointer,\n omit,\n refs,\n document,\n parse,\n}: ContentEntryOptions & { parse: (schema: SchemaObject | null) => ast.SchemaNode | null }): ContentEntry | null {\n const declared = getDeclaredBodySchema({ content, contentType, refs, document })\n const schema = declared ? refs.derefKeepingRef(declared) : null\n const node = parse(schema)\n if (!node) return null\n const mediaType = getMediaType({ content, contentType, refs })\n if (schema && contentType) {\n scanSchema(node, `${mediaTypePointer(content, contentType, `${contentPointer}/${escapePointerToken(contentType)}`)}/${schemaKeyword(mediaType)}`)\n }\n\n return {\n schema: node,\n keysToOmit: collectPropertyKeysByFlag({ schema: declared, flag: omit, refs }),\n ...(mediaType && getEncodingFields(mediaType)),\n ...(mediaType && getExamples(mediaType, refs)),\n ...(contentType ? getStreamField({ contentType, mediaType, refs, document, node }) : {}),\n extensions: pickExtensions(mediaType),\n }\n}\n","import { escapePointerToken } from '@internals/utils'\nimport { pascalCase } from '@kubb/core'\nimport { ast, macroEnumName } from '@kubb/kit'\nimport { pickExtensions } from '../oas.ts'\nimport type { OperationParseContext } from '../operation.ts'\nimport { scanSchema } from '../schemaDiagnostics.ts'\nimport type { MediaTypeObject, ParameterObject, SchemaObject } from '../types.ts'\nimport { getEncodingFields, getExamples, getMediaType, pickStyleFields } from './content.ts'\n\nexport type ParameterContext = Pick<OperationParseContext, 'options' | 'parseSchema' | 'refs'> & {\n param: ParameterObject\n pointer: string\n parentName?: string\n}\ntype ResolvedMedia = { contentType?: string; mediaType: MediaTypeObject | null }\n\n// An inline enum gets `enumSuffix`, the same as an inline enum on an object property.\nfunction withEnumName({\n schema,\n param,\n parentName,\n options,\n}: Pick<ParameterContext, 'param' | 'parentName' | 'options'> & { schema: ast.SchemaNode }): ast.SchemaNode {\n if (!parentName || !param.name) return schema\n return ast.macro.apply(schema, [macroEnumName({ parentName, propName: param.name, enumSuffix: options.enumSuffix })], { depth: 'shallow' })\n}\n\nfunction parseParameterSchema(ctx: ParameterContext & ResolvedMedia): ast.SchemaNode {\n const { param, pointer, parentName, options, parseSchema, contentType, mediaType } = ctx\n const rawSchema = param.schema ?? mediaType?.schema\n const schemaName = parentName && param.name ? pascalCase(`${parentName} ${param.name}`) : undefined\n const parsed = rawSchema ? parseSchema({ schema: rawSchema as SchemaObject, name: schemaName }) : ast.factory.createSchema({ type: options.unknownType })\n const schema = withEnumName({ schema: parsed, param, parentName, options })\n if (rawSchema) scanSchema(schema, contentType ? `${pointer}/content/${escapePointerToken(contentType)}/schema` : `${pointer}/schema`)\n return schema\n}\n\n/**\n * Converts one parameter into a `ParameterNode`, naming an inline schema after the operation and the parameter.\n */\nexport function parseParameter(ctx: ParameterContext): ast.ParameterNode {\n const { param, pointer, refs } = ctx\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 mediaType = getMediaType({ content: param.content, contentType, refs })\n const schema = parseParameterSchema({ ...ctx, contentType, mediaType })\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 ...pickStyleFields(param),\n ...(contentType !== undefined ? { contentType } : {}),\n ...(mediaType?.encoding && { encoding: getEncodingFields({ encoding: mediaType.encoding }).encoding }),\n ...getExamples(mediaType ?? param, refs),\n ...(param.deprecated && { deprecated: true }),\n ...(param.allowEmptyValue && { allowEmptyValue: true }),\n extensions: pickExtensions(param),\n })\n}\n\n/**\n * Spreads a form-encoded OpenAPI 3.2 `querystring` object into one query parameter per property. Another content type stays whole.\n */\nexport function spreadQuerystring(param: ast.ParameterNode): Array<ast.ParameterNode> {\n if (param.in !== 'querystring') return [param]\n const schema = ast.ref.getSchema(param.schema)\n const formEncoded = !param.contentType || ast.mediaType.getBase(param.contentType) === 'application/x-www-form-urlencoded'\n if (schema.type !== 'object' || !formEncoded) return [param]\n return schema.properties.map((property) => {\n const { style, explode, allowReserved } = param.encoding?.[property.name] ?? {}\n return ast.factory.createParameter({\n ...(param.pointer ? { pointer: param.pointer } : {}),\n name: property.name,\n in: 'query',\n schema: property.schema,\n required: param.required && property.required,\n ...(style !== undefined && { style }),\n ...(explode !== undefined && { explode }),\n ...(allowReserved !== undefined && { allowReserved }),\n ...(param.extensions && { extensions: param.extensions }),\n })\n })\n}\n","import { escapePointerToken } from '@internals/utils'\nimport type { OpenAPIV3_1 } from 'openapi-types'\nimport { pascalCase } from '@kubb/core'\nimport { ast, Diagnostics, Url } from '@kubb/kit'\nimport { SUPPORTED_METHODS } from './constants.ts'\nimport type { ParseFn } from './emit/parseSchema.ts'\nimport { parseContentEntry } from './model/content.ts'\nimport { parseParameter, spreadQuerystring } from './model/parameters.ts'\nimport { toAuthRequirements } from './model/security.ts'\nimport { toInputServers } from './model/server.ts'\nimport { getExternalDocs, isReference, pickExtensions, pickStrings } from './oas.ts'\nimport type { Refs } from './refs.ts'\nimport type { ContentType, Document, OperationObject, ParameterObject, PathItemObject, ReferenceObject, ResponseObject } from './types.ts'\nimport type { ParserOptions } from './parserOptions.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\nexport type OperationContext = {\n operation: Operation\n refs: Refs\n}\n\n/** What `parseOperation` needs beyond the operation. */\nexport type OperationParseContext = {\n document: Document\n refs: Refs\n contentType?: ContentType\n options: 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 JSON pointer, under `additionalOperations` for an OpenAPI 3.2 method outside the fixed fields.\n */\nfunction getOperationPointer({ path, method }: Pick<Operation, 'path' | 'method'>): string {\n const pathPointer = `#/paths/${escapePointerToken(path)}`\n\n return SUPPORTED_METHODS.has(method.toLowerCase())\n ? `${pathPointer}/${method.toLowerCase()}`\n : `${pathPointer}/additionalOperations/${escapePointerToken(method)}`\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 */\nfunction 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 */\nfunction 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 */\nfunction getRequestBody({ operation, refs }: OperationContext): OpenAPIV3_1.RequestBodyObject | null {\n return refs.deref<OpenAPIV3_1.RequestBodyObject>(operation.schema.requestBody)\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 || [], getOperationPointer(operation))\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\nfunction getLinks(links: unknown, refs: Refs): Record<string, ast.ResponseLink> | undefined {\n const entries = Object.entries(links ?? {}).flatMap(([name, value]) => {\n const link = refs.deref<OpenAPIV3_1.LinkObject>(value)\n if (!link) return []\n const server = link.server ? toInputServers([link.server])[0] : undefined\n const node: ast.ResponseLink = {\n ...pickStrings(link, ['operationId', 'operationRef', 'description']),\n ...(link.parameters && { parameters: link.parameters }),\n ...('requestBody' in link && { requestBody: link.requestBody }),\n ...(server && { server }),\n }\n return [[name, node] as const]\n })\n return entries.length ? Object.fromEntries(entries) : undefined\n}\n\n/**\n * Builds an `Operation` for every supported HTTP method and every OpenAPI 3.2 `additionalOperations` entry on\n * every path, in document order. `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 for (const [method, schema] of Object.entries(pathItem.additionalOperations ?? {})) {\n // The spec forbids a fixed method here; such an entry would also take the fixed operation's pointer.\n if (schema && typeof schema === 'object' && !SUPPORTED_METHODS.has(method.toLowerCase())) {\n operations.push({ path, method, schema, pathItem })\n }\n }\n }\n\n return withUniqueOperationIds(operations)\n}\n\n// Names come from `pascalCase(operationId)`, so `getPets_2` and `getPets2` would clash too.\nfunction suffixed(id: string, taken: Set<string>, counts: Map<string, number>): string {\n const count = (counts.get(id) ?? 1) + 1\n counts.set(id, count)\n const candidate = `${id}_${count}`\n return taken.has(pascalCase(candidate)) ? suffixed(id, taken, counts) : candidate\n}\n\n// Two operations with one id would share every generated name and file.\nfunction withUniqueOperationIds(operations: Array<Operation>): Array<Operation> {\n // Declared ids are reserved first, so a suffix never takes an id a later operation declares.\n const taken = new Set(\n operations.flatMap(({ schema }) => (typeof schema.operationId === 'string' && schema.operationId ? [pascalCase(schema.operationId)] : [])),\n )\n const claimed = new Set<string>()\n const counts = new Map<string, number>()\n\n return operations.map((operation) => {\n const operationId = getOperationId(operation)\n const name = pascalCase(operationId)\n if (!claimed.has(name)) {\n claimed.add(name)\n taken.add(name)\n return operation\n }\n\n const unique = suffixed(operationId, taken, counts)\n taken.add(pascalCase(unique))\n claimed.add(pascalCase(unique))\n Diagnostics.report({\n code: Diagnostics.code.duplicateOperationId,\n severity: 'warning',\n message: `operationId \"${operationId}\" of ${operation.method.toUpperCase()} ${operation.path} is already used, so it is renamed to \"${unique}\".`,\n help: 'Give each operation its own `operationId`.',\n location: { kind: 'operation', pointer: getOperationPointer(operation) },\n })\n\n return { ...operation, schema: { ...operation.schema, operationId: unique } }\n })\n}\n\ntype RequestBodyContext = { operation: Operation; operationName: string | undefined; pointer: string; ctx: OperationParseContext }\ntype ResponseContext = RequestBodyContext & { key: string }\n\nfunction parseRequestBody({ operation, operationName, pointer, ctx }: RequestBodyContext): Omit<ast.RequestBodyNode, 'kind'> | undefined {\n const { document, refs, contentType, parseSchema } = ctx\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 if (!body) return undefined\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 entry = parseContentEntry({\n content: body.content,\n contentType: ct,\n contentPointer: `${pointer}/requestBody/content`,\n omit: 'readOnly',\n refs,\n document,\n parse: (schema) => (schema ? ast.schema.applyOptionality(parseSchema({ schema, name: requestBodyName }), bodyRequired) : null),\n })\n return entry ? [ast.factory.createContent({ contentType: ct, ...entry })] : []\n })\n if (content.length === 0 && !body.description) return undefined\n\n return {\n pointer: `${pointer}/requestBody`,\n description: body.description,\n required: bodyRequired || undefined,\n content: content.length > 0 ? content : undefined,\n extensions: pickExtensions(body),\n }\n}\n\nfunction pickDoc({ operation, key }: { operation: Operation; 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// The spec ignores a `Content-Type` header, since `content` already names the media type.\nfunction parseResponseHeaders({\n response,\n responsePointer,\n responseName,\n ctx: { options, parseSchema, refs },\n}: Pick<ResponseContext, 'ctx'> & { response: ResponseObject | null; responsePointer: string; responseName: string | undefined }): Array<ast.ParameterNode> {\n return Object.entries(response?.headers ?? {}).flatMap(([name, value]) => {\n const header = name.toLowerCase() === 'content-type' ? null : refs.deref<OpenAPIV3_1.HeaderObject>(value)\n if (!header) return []\n const param: ParameterObject = { ...header, name, in: 'header' }\n return [parseParameter({ param, pointer: `${responsePointer}/headers/${escapePointerToken(name)}`, parentName: responseName, options, parseSchema, refs })]\n })\n}\n\nfunction parseResponse({ operation, key, operationName, pointer, ctx }: ResponseContext): ast.ResponseNode {\n const { document, refs, contentType, options, parseSchema } = ctx\n const response = getResponseByStatusCode({ operation, refs, statusCode: key })\n const { content, summary, description, links: rawLinks }: Partial<ResponseObject> = response ?? {}\n // A range such as `2XX` is written `2xx`. Pointers keep the key as the document spells it.\n const statusCode = key.toLowerCase() as ast.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 const responsePointer = `${pointer}/responses/${key}`\n\n const parseEntrySchema = (ct?: string) =>\n parseContentEntry({\n content,\n contentType: ct,\n contentPointer: `${responsePointer}/content`,\n omit: 'writeOnly',\n refs,\n document,\n parse: (schema) =>\n schema && Object.keys(schema).length > 0 ? parseSchema({ schema, name: responseName }) : ast.factory.createSchema({ type: options.emptySchemaType }),\n })\n\n const declaredContentTypes = Object.keys(content ?? {})\n // The adapter `contentType` only narrows a response that has a body.\n const responseContentTypes = contentType && declaredContentTypes.length ? [contentType] : declaredContentTypes\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 // Its empty `contentType` says there is no body, so plugins do not read a `text/*` request type as a `string` response.\n if (responseContent.length === 0) {\n responseContent.push(ast.factory.createContent({ contentType: '', ...parseEntrySchema(contentType) }))\n }\n\n const headers = parseResponseHeaders({ response, responsePointer, responseName, ctx })\n const links = getLinks(rawLinks, refs)\n\n return ast.factory.createResponse({\n pointer: responsePointer,\n statusCode,\n summary,\n description,\n content: responseContent,\n ...(headers.length && { headers }),\n ...(links && { links }),\n extensions: pickExtensions(response),\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 { document, refs, options, parseSchema } = ctx\n const operationId = getOperationId(operation)\n const operationName = operationId ? pascalCase(operationId) : undefined\n const pointer = getOperationPointer(operation)\n const parameters = getParameters({ operation, refs })\n .map((entry) => parseParameter({ options, parseSchema, refs, ...entry, parentName: operationName }))\n .flatMap(spreadQuerystring)\n\n const requestBody = parseRequestBody({ operation, operationName, pointer, ctx })\n const responses = getResponseStatusCodes(operation).map((key) => parseResponse({ operation, key, operationName, pointer, ctx }))\n\n // An empty operation `servers` list overrides nothing, so the path item's servers still apply.\n const servers = operation.schema.servers?.length ? operation.schema.servers : operation.pathItem.servers\n const auth = toAuthRequirements(operation.schema.security ?? document.security, document)\n\n return ast.factory.createOperation({\n pointer,\n operationId,\n protocol: 'http',\n // An `additionalOperations` key is sent with its own capitalization, so only the fixed lowercase fields are uppercased.\n method: (SUPPORTED_METHODS.has(operation.method) ? operation.method.toUpperCase() : operation.method) as ast.HttpMethod,\n path: operation.path,\n tags: Array.isArray(operation.schema.tags) ? operation.schema.tags.map(String) : [],\n summary: pickDoc({ operation, key: 'summary' }) || undefined,\n description: pickDoc({ operation, key: 'description' }) || undefined,\n deprecated: operation.schema.deprecated || undefined,\n externalDocs: getExternalDocs(operation.schema.externalDocs),\n parameters,\n requestBody,\n responses,\n extensions: pickExtensions(operation.schema),\n ...(servers && { servers: toInputServers(servers) }),\n ...(auth && { auth }),\n })\n}\n\n/** Renames path parameters and their `{placeholder}` to the camelCase names from {@link Url.toParamNames}. */\nexport function camelCasePathParams(node: ast.OperationNode): ast.OperationNode {\n // A `matrix` value is sent as `;name=value`, so renaming would change the request.\n if (!node.path || node.parameters.some((param) => param.in === 'path' && param.style === 'matrix')) return node\n const names = Url.toParamNames(node.path)\n\n return {\n ...node,\n path: node.path.replace(/\\{([^}]+)\\}/g, (_match, name: string) => `{${names.get(name) ?? name}}`),\n parameters: node.parameters.map((param) => (param.in === 'path' && names.has(param.name) ? { ...param, name: names.get(param.name)! } : param)),\n }\n}\n","import { ast } from '@kubb/kit'\nimport { enumDescriptionKeys, enumExtensionKeys, getFormatType, numericFormats } from '../../constants.ts'\nimport { pickExtensions } from '../../oas.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(\n schema: SchemaObject,\n): Pick<ast.NumberSchemaNode, 'min' | 'max' | 'exclusive' | 'exclusiveMinimum' | 'exclusiveMaximum' | 'multipleOf'> {\n const exclusiveMinimum = typeof schema.exclusiveMinimum === 'number' ? schema.exclusiveMinimum : undefined\n const exclusiveMaximum = typeof schema.exclusiveMaximum === 'number' ? schema.exclusiveMaximum : undefined\n const hasExclusive = exclusiveMinimum !== undefined || exclusiveMaximum !== undefined\n return {\n min: schema.minimum,\n max: schema.maximum,\n ...(hasExclusive && {\n exclusive: { ...(exclusiveMinimum !== undefined && { min: exclusiveMinimum }), ...(exclusiveMaximum !== undefined && { max: exclusiveMaximum }) },\n }),\n // shortcut: the pre-`exclusive` names, kept so plugins that read them keep working, remove them in Kubb v6.\n exclusiveMinimum,\n exclusiveMaximum,\n multipleOf: schema.multipleOf,\n }\n}\n\n/**\n * Whether an enum value fits the schema's numeric bounds.\n */\nfunction isWithinBounds({ value, schema }: { value: unknown; schema: SchemaObject }): boolean {\n if (typeof value !== 'number') return true\n const { min, max, exclusive, multipleOf } = getNumericConstraints(schema)\n if (min !== undefined && value < min) return false\n if (max !== undefined && value > max) return false\n if (exclusive?.min !== undefined && value <= exclusive.min) return false\n if (exclusive?.max !== undefined && value >= exclusive.max) return false\n // The tolerance keeps float quotients such as `0.3 / 0.1` from failing.\n if (multipleOf !== undefined && Math.abs(value / multipleOf - Math.round(value / multipleOf)) > 1e-9) return false\n return true\n}\n\n/**\n * Builds the test for which `enum` entries stay: not `null`, and within the numeric bounds. `enum` and the bounds\n * apply together, so a value outside them is never valid. Bounds that exclude every value are a spec error, so\n * they are ignored rather than leaving an empty enum.\n */\nfunction createEnumMemberFilter(schema: SchemaObject): (value: unknown) => boolean {\n const boundsApply = schema.enum!.some((value) => value !== null && isWithinBounds({ value, schema }))\n return (value) => value !== null && (!boundsApply || isWithinBounds({ value, schema }))\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 extensions: pickExtensions(schema),\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 = getFormatType(schema.format!)\n if (specialType === 'blob') return convertBlob(context)\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 Exclude<ast.ScalarSchemaType, 'blob'>,\n ...(hasLength ? { min: schema.minLength, max: schema.maxLength } : {}),\n ...(isNumeric ? getNumericConstraints(schema) : {}),\n })\n}\n\n/**\n * Primitive of an enum's members. Without a `type`, the values decide: `{ enum: [0, 1] }` is a number enum.\n */\nfunction getEnumPrimitive(type: string | undefined, values: Array<string | number | boolean>): 'number' | 'boolean' | 'string' {\n if (type === 'boolean') return 'boolean'\n if (type === 'number' || type === 'integer') return 'number'\n if (type !== undefined || values.length === 0) return 'string'\n if (values.every((value) => typeof value === 'boolean')) return 'boolean'\n if (values.every((value) => typeof value === 'number')) return 'number'\n\n return 'string'\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 isMember = createEnumMemberFilter(schema)\n const filteredValues = schema.enum!.filter(isMember) 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 uniqueValues = [...new Set(filteredValues)]\n const primitive = getEnumPrimitive(type, uniqueValues)\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 // Names and descriptions run parallel to `enum`, so drop the slots of the removed values to keep each name with its value.\n const memberSlots = (list: unknown) => (Array.isArray(list) ? list.filter((_, index) => isMember(schema.enum![index])) : undefined)\n const rawEnumNames = extensionKey ? (memberSlots((schema as Record<string, unknown>)[extensionKey]) as Array<string | number> | undefined) : undefined\n const rawEnumDescriptions = descriptionKey ? (memberSlots((schema as Record<string, unknown>)[descriptionKey]) as Array<string> | undefined) : undefined\n const seenNames = new Set<string>()\n const seenValues = new Set<string | number | boolean>()\n\n return createNode(ctx, {\n type: 'enum',\n primitive,\n // Pair each value with its name before duplicates go, so a later value keeps its own name.\n namedEnumValues: filteredValues\n .map((value, index) => ({\n name: String(rawEnumNames?.[index] ?? value),\n value,\n primitive,\n description: rawEnumDescriptions?.[index],\n }))\n .filter((entry) => {\n if (seenValues.has(entry.value) || seenNames.has(entry.name)) return false\n seenValues.add(entry.value)\n seenNames.add(entry.name)\n return true\n }),\n })\n}\n\n/**\n * Converts an `enum` with a handled `format` into a union of its literal values. A named enum node would rename\n * the exported type (`Status` becomes `StatusKey`), so the union keeps the name the format type had.\n */\nexport function convertFormattedEnum(context: ConvertContext): ast.SchemaNode {\n const { schema, nullable } = context\n const values = [...new Set(schema.enum!.filter(createEnumMemberFilter(schema)))] as Array<string | number | boolean>\n\n return createNode(\n { ...context, nullable: nullable || schema.enum!.includes(null) || undefined },\n {\n type: 'union',\n members: values.map((value) => ast.factory.createSchema({ type: 'enum', primitive: getPrimitiveType(typeof value), enumValues: [value] })),\n },\n )\n}\n\nfunction getStringContent({ schema, parse }: ConvertContext): Pick<ast.StringSchemaNode, 'content'> {\n const { contentMediaType: mediaType, contentEncoding: encoding, contentSchema } = schema\n if (mediaType === undefined && encoding === undefined && !contentSchema) return {}\n return {\n content: {\n ...(mediaType !== undefined && { mediaType }),\n ...(encoding !== undefined && { encoding }),\n ...(contentSchema && { schema: parse({ schema: contentSchema as SchemaObject }) }),\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 ...getStringContent(context),\n })\n}\n\n/** Converts a binary schema into a `BlobSchemaNode`, keeping `contentMediaType` and `contentEncoding`. */\nexport function convertBlob(context: ConvertContext): ast.SchemaNode {\n return createNode(context, { type: 'blob', primitive: 'string', ...getStringContent(context) })\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\nfunction getContains(schema: SchemaObject, parse: ConvertContext['parse']): Pick<ast.ArraySchemaNode, 'contains'> {\n const { contains, minContains, maxContains } = schema\n if (!contains || typeof contains !== 'object') return {}\n return {\n contains: {\n schema: parse({ schema: contains as SchemaObject }),\n ...(typeof minContains === 'number' && { min: minContains }),\n ...(typeof maxContains === 'number' && { max: maxContains }),\n },\n }\n}\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.macro.apply(node, [macro], { depth: 'shallow' })\n const tupleNode = ast.schema.narrow(named, 'tuple')\n if (tupleNode?.items) {\n const namedItems = tupleNode.items.map((item) => ast.macro.apply(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, document }: 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, document)\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 ?? schema.unevaluatedProperties\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 min: schema.minProperties,\n max: schema.maxProperties,\n // shortcut: the pre-`min`/`max` names, kept so plugins that read them keep working, remove them in Kubb v6.\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.macro.apply(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 prefixItems = schema.prefixItems ?? []\n // A `maxItems` no larger than the `prefixItems` count closes the tuple, like `items: false`.\n const isClosed = schema.maxItems !== undefined && schema.maxItems <= prefixItems.length\n const tupleItems = (isClosed ? prefixItems.slice(0, schema.maxItems) : prefixItems).map((item) => parse({ schema: item as SchemaObject }))\n const tail = isClosed ? false : (schema.items ?? schema.unevaluatedItems)\n // items: false closes the tuple; absent/true widens the tail to unknownType.\n const rest =\n tail === false ? undefined : !tail || tail === true ? ast.factory.createSchema({ type: options.unknownType }) : parse({ schema: tail 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 ...getContains(schema, parse),\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 ...getContains(schema, parse),\n },\n )\n}\n","import type { ast } from '@kubb/kit'\nimport { enumExtensionKeys, getFormatType } from '../constants.ts'\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 {\n convertBlob,\n convertConst,\n convertEnum,\n convertFormat,\n convertFormattedEnum,\n convertNumeric,\n convertString,\n createNullNode,\n} from './converters/scalar.ts'\nimport { convertArray, convertObject, convertTuple } from './converters/structural.ts'\nimport { createNode } from './createNode.ts'\nimport { isHandledFormat, resolveDateTypeValue } from './schemaShape.ts'\nimport type { ParserOptions } from '../parserOptions.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: 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 */\nexport type SchemaRule = {\n /**\n * Returns `true` when this rule is responsible for the given context.\n */\n match: (context: ConvertContext) => boolean\n /**\n * Produces a node for the context.\n */\n convert: (context: ConvertContext) => ast.SchemaNode\n}\n\n/**\n * Whether the `format` rule owns the schema: a handled format, and for a date format a `dateType` that is not `false`.\n */\nfunction matchesFormat({ schema, options }: ConvertContext): boolean {\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\n/**\n * Whether the format prints as a plain `string` or `number`, so narrowing it to literal values cannot break callers.\n * `Date`, `bigint` and `Blob` outputs keep the format.\n */\nfunction formatPrintsPlainType({ schema, options, type }: ConvertContext): boolean {\n const format = schema.format!\n if (format === 'date-time' || format === 'date' || format === 'time') return resolveDateTypeValue(options.dateType, format) !== 'date'\n if ((format === 'int64' || format === 'uint64') && type !== 'string') return options.integerType !== 'bigint'\n return getFormatType(format) !== 'blob'\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 // A formatted enum keeps its values as a union of literals, so its type keeps its name. With `x-enumNames`\n // or `x-enum-varnames` it becomes a named enum, the same as an enum without a `format`.\n match: (ctx) => ctx.type !== 'array' && !!ctx.schema.enum?.some((value) => value !== null) && matchesFormat(ctx) && formatPrintsPlainType(ctx),\n convert: (ctx) => (enumExtensionKeys.some((key) => key in ctx.schema) ? convertEnum(ctx) : convertFormattedEnum(ctx)),\n },\n { match: matchesFormat, convert: convertFormat },\n { match: ({ schema }) => isBinary(schema), convert: convertBlob },\n {\n match: ({ schema, type }) => !type && !schema.enum?.length && (schema.contentMediaType !== undefined || schema.contentSchema !== undefined),\n convert: convertString,\n },\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 { ast } from '@kubb/kit'\nimport { DEFAULT_PARSER_OPTIONS } from './constants.ts'\nimport { isAnnotationMember } from './emit/converters/composition.ts'\nimport { createNode } from './emit/createNode.ts'\nimport { type ConvertContext, type ParseFn, 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'\nimport type { ParserOptions } from './parserOptions.ts'\n\n/**\n * Parser context holding the raw OpenAPI document and its `$ref` service.\n */\nexport type SchemaParserOptions = {\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<ParserOptions>\n}\n\n/**\n * `unevaluated*` also sees what composition siblings evaluate, so with such a sibling it is dropped to keep the schema open.\n */\nfunction hasUnevaluatedSiblings(schema: SchemaObject): boolean {\n if (schema.unevaluatedProperties === undefined && schema.unevaluatedItems === undefined) return false\n return [schema.allOf, schema.anyOf, schema.oneOf, schema.if, schema.dependentSchemas, schema.$ref].some((value) => value !== undefined)\n}\n\nfunction isKeyList(value: unknown): value is Array<string> {\n return Array.isArray(value) && value.length > 0 && value.every((name) => typeof name === 'string')\n}\n\n/**\n * The schema converter bound to one OpenAPI document: `parse` dispatches each schema through the\n * ordered `schemaRules` table, with the parser options merged once.\n *\n * @internal\n */\nexport class SchemaParser {\n readonly #document: Document\n readonly #refs: Refs\n readonly #renames: ReadonlyMap<string, string> | undefined\n readonly #options: ParserOptions\n // The key lists of the presence checks `#requireKeys` builds, so two entries that check the same keys compare equal.\n readonly #presenceKeys = new WeakMap<ast.SchemaNode, string>()\n\n constructor(ctx: SchemaParserOptions) {\n this.#document = ctx.document\n this.#refs = ctx.refs\n this.#renames = ctx.renames\n this.#options = { ...DEFAULT_PARSER_OPTIONS, ...ctx.options }\n }\n\n /**\n * Converts one OpenAPI schema into a `SchemaNode`, through the first matching rule of `schemaRules`.\n */\n parse: ParseFn = ({ schema, name }) => {\n const options = this.#options\n // A JSON Schema boolean: `true` accepts any value and `false` accepts none.\n if (typeof schema === 'boolean') {\n return ast.factory.createSchema({ type: schema ? (options.emptySchemaType as ast.ScalarSchemaType) : 'never', name: name ?? undefined })\n }\n\n const flattenedSchema = flattenSchema(schema)\n if (flattenedSchema !== schema) {\n // `flattenSchema` keeps the first value of each keyword, so the conditionals of the schema and of every member are read on their own.\n const { if: _if, then: _then, else: _else, dependentRequired: _required, dependentSchemas: _schemas, ...shape } = flattenedSchema\n return this.#withConditionals(this.parse({ schema: shape, name }), [schema, ...(schema.allOf as Array<SchemaObject>)])\n }\n if (hasUnevaluatedSiblings(schema)) {\n const { unevaluatedProperties: _properties, unevaluatedItems: _items, ...open } = schema\n return this.parse({ schema: open, name })\n }\n\n return this.#convert({ schema, name })\n }\n\n #convert({ schema, name }: { schema: SchemaObject; name?: string | null }): ast.SchemaNode {\n const options = this.#options\n const nullable = isNullable(schema, this.#document) || 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: this.parse,\n document: this.#document,\n refs: this.#refs,\n renames: this.#renames,\n }\n\n const rule = schemaRules.find((entry) => entry.match(context))\n const node = rule ? rule.convert(context) : createNode(context, { type: options.emptySchemaType as ast.ScalarSchemaType })\n\n // `allOf` members that hold only annotations and `if`/`then`/`else` are not parsed as members, so read their conditionals here.\n const annotationMembers = Array.isArray(schema.allOf) ? (schema.allOf as Array<SchemaObject>).filter(isAnnotationMember) : []\n return this.#withConditionals(node, [schema, ...annotationMembers])\n }\n\n #requireKeys(keys: Array<string>): ast.SchemaNode {\n const unknown = ast.factory.createSchema({ type: ast.schema.types.unknown })\n const node = ast.factory.createSchema({\n type: ast.schema.types.object,\n primitive: 'object',\n properties: keys.map((name) => ast.factory.createProperty({ name, required: true, schema: unknown })),\n })\n this.#presenceKeys.set(node, keys.join('\\0'))\n return node\n }\n\n #withConditionals(node: ast.SchemaNode, sources: Array<SchemaObject>): ast.SchemaNode {\n const conditionals = sources.flatMap((source) => this.#toConditionals(source))\n // A collapsed one-member `allOf` already carries the conditionals of its member, so a repeated entry is skipped.\n const existing = new Set((node.conditionals ?? []).map((entry) => this.#presenceKey(entry)))\n const added = conditionals.filter((entry) => {\n const key = this.#presenceKey(entry)\n return key === undefined || !existing.has(key)\n })\n return added.length ? { ...node, conditionals: [...(node.conditionals ?? []), ...added] } : node\n }\n\n // The keys an entry checks for presence, or `undefined` when a branch checks more than presence and the entry is always kept.\n #presenceKey({ if: condition, then: thenNode, else: elseNode }: NonNullable<ast.SchemaNode['conditionals']>[number]): string | undefined {\n const keys = [condition, thenNode, elseNode].map((branch) => (branch ? this.#presenceKeys.get(branch) : ''))\n return keys.includes(undefined) ? undefined : keys.join('\\n')\n }\n\n #toBranch(value: unknown): ast.SchemaNode | undefined {\n if (!value || typeof value !== 'object') return undefined\n const { required, type, ...rest } = value as SchemaObject\n // A subschema with only `required`, such as `{ required: ['postalCode'] }`, would otherwise parse as `unknown`.\n if (Array.isArray(required) && required.length && (type === undefined || type === 'object') && !Object.keys(rest).length) return this.#requireKeys(required)\n return this.parse({ schema: value as SchemaObject })\n }\n\n #toConditionals(schema: SchemaObject): NonNullable<ast.SchemaNode['conditionals']> {\n const entries = (value: unknown) => (value && typeof value === 'object' ? Object.entries(value) : [])\n const conditionals: NonNullable<ast.SchemaNode['conditionals']> = []\n\n const condition = this.#toBranch(schema.if)\n if (condition) {\n const thenNode = this.#toBranch(schema.then)\n const elseNode = this.#toBranch(schema.else)\n conditionals.push({ if: condition, ...(thenNode && { then: thenNode }), ...(elseNode && { else: elseNode }) })\n }\n for (const [key, required] of entries(schema.dependentRequired)) {\n if (isKeyList(required)) conditionals.push({ if: this.#requireKeys([key]), then: this.#requireKeys(required) })\n }\n for (const [key, dependent] of entries(schema.dependentSchemas)) {\n const thenNode = this.#toBranch(dependent)\n if (thenNode) conditionals.push({ if: this.#requireKeys([key]), then: thenNode })\n }\n\n return conditionals\n }\n}\n\n/**\n * Creates the schema converter bound to one OpenAPI document.\n *\n * @internal\n */\nexport function createSchemaParser(ctx: SchemaParserOptions): SchemaParser {\n return new SchemaParser(ctx)\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.node.kinds.schema\n for (const node of ast.node.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.node.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 { defineExtension } from '@kubb/core'\nimport type { AdapterParseOptions, AdapterParseResult, AdapterValidateOptions } from '@kubb/core'\nimport { ast, Diagnostics } from '@kubb/kit'\nimport type { AdapterSource, Harness } 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 { toAuthSchemes } from './model/security.ts'\nimport { resolveBaseUrl, toInputServers } from './model/server.ts'\nimport { toInputTags } from './model/tag.ts'\nimport { getExternalDocs, pickExtensions, pickStrings } from './oas.ts'\nimport { camelCasePathParams, getOperations, parseOperation } from './operation.ts'\nimport type { ParseFn } from './emit/parseSchema.ts'\nimport { createSchemaParser } from './schemaParser.ts'\nimport { collectInlineEnums, refPromotedEnums } from './promoteEnums.ts'\nimport { createRefs, type Refs } from './refs.ts'\nimport { groupUnsupportedFormats, scanSchema } from './schemaDiagnostics.ts'\nimport { locate } from './sourceLocator.ts'\nimport type { AdapterOas, AdapterOasResolvedOptions, 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\ntype InputCacheEntry = {\n promise: Promise<ast.InputNode>\n sources: Array<string>\n document: Document | null\n harness?: Harness\n}\n\ntype AdapterSettings = Pick<AdapterOasResolvedOptions, 'validate' | 'contentType' | 'server' | 'discriminator' | 'enums' | 'pathParamsCasing'>\n\ntype ParserOptions = Omit<AdapterOasResolvedOptions, keyof AdapterSettings>\n\ntype ParseInputContext = {\n document: Document\n refs: Refs\n schemas: Record<string, SchemaObject>\n pointers: Map<string, string>\n parseSchema: ParseFn\n}\n\ntype ParsedSchemas = {\n parsedByName: Map<string, ast.SchemaNode>\n refAliasMap: Map<string, ast.RefSchemaNode>\n discriminatorChildMap: Map<string, Array<DiscriminatorTarget>> | null\n}\n\nclass Adapter {\n readonly locate = locate\n readonly #settings: AdapterSettings\n readonly #parserOptions: ParserOptions\n #document: Document | null = null\n #sources: Array<string> = []\n readonly #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 readonly #inputCache = new WeakMap<AdapterSource, InputCacheEntry>()\n\n constructor({ validate, contentType, server, discriminator, enums, pathParamsCasing, ...parserOptions }: AdapterOasResolvedOptions) {\n this.#settings = { validate, contentType, server, discriminator, enums, pathParamsCasing }\n this.#parserOptions = parserOptions\n }\n\n /**\n * @deprecated Read `document` from the result of `parse`. It follows the last parse. Removed in Kubb v6.\n */\n get document(): Document | null {\n return this.#document\n }\n\n /**\n * @deprecated Read `sources` from the result of `parse`. It follows the last parse. Removed in Kubb v6.\n */\n get sources(): Array<string> {\n return this.#sources\n }\n\n // Arrow properties, so an adapter that a user spreads or destructures keeps its methods.\n validate = async (input: string, options?: AdapterValidateOptions): Promise<void> => {\n const document = await parseFromConfig({ type: 'path', path: input }, [], { harness: options?.harness })\n assertDocument(document)\n await validateDocument(document, options)\n }\n\n settle = async (): Promise<void> => {\n await Promise.all(this.#pendingValidations.splice(0))\n }\n\n /**\n * Returns the AST with the document and the files this call read, so two overlapping parses on one instance each\n * get their own.\n */\n parse = async (source: AdapterSource, options?: AdapterParseOptions): Promise<AdapterParseResult<Document>> => {\n const entry = this.#start(source, options)\n const node = await entry.promise\n return { node, document: entry.document, sources: entry.sources }\n }\n\n // Starts a parse, or returns the cached one for `source`. The deprecated `document` and `sources` getters follow the last call.\n #start(source: AdapterSource, { signal, harness }: AdapterParseOptions = {}): InputCacheEntry {\n signal?.throwIfAborted()\n const cached = this.#cached({ source, harness })\n if (cached) {\n this.#sources = cached.sources\n this.#document = cached.document\n return cached\n }\n\n const read: Array<string> = []\n this.#sources = read\n const entry = { sources: read, document: null as Document | null, harness }\n const promise = (async () => {\n const document = await parseFromConfig(source, read, { harness, signal })\n signal?.throwIfAborted()\n assertDocument(document)\n if (this.#settings.validate) this.#pendingValidations.push(validateDocumentInWorker(document))\n entry.document = document\n this.#document = document\n\n const refs = createRefs(document)\n const { schemas, renames, pointers } = getSchemas(document, { contentType: this.#settings.contentType }, refs)\n const parseSchema = createSchemaParser({ document, refs, renames, options: this.#parserOptions }).parse\n\n return groupUnsupportedFormats(() => this.#parseInput({ document, refs, schemas, pointers, parseSchema }))\n })().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) this.#inputCache.delete(source)\n throw error\n })\n const started = Object.assign(entry, { promise })\n this.#inputCache.set(source, started)\n return started\n }\n\n // A parse with another `harness` may read different sources, so it does not reuse the cached one.\n #cached({ source, harness }: { source: AdapterSource } & Pick<AdapterParseOptions, 'harness'>): InputCacheEntry | undefined {\n const cached = this.#inputCache.get(source)\n return cached?.harness === harness ? cached : undefined\n }\n\n /**\n * Parses every schema and operation once, resolving ref aliases and discriminator children from that same pass.\n */\n #parseInput({ document, refs, schemas, pointers, parseSchema }: ParseInputContext): ast.InputNode {\n const { contentType, server, enums, pathParamsCasing } = this.#settings\n const parserOptions = this.#parserOptions\n const parsed = this.#parseSchemas({ schemas, pointers, parseSchema })\n\n const operationNodes = getOperations(document, refs).map((operation) => {\n const node = parseOperation({ operation, document, refs, contentType, options: parserOptions, parseSchema })\n return pathParamsCasing === 'camelcase' ? camelCasePathParams(node) : node\n })\n\n const promotedEnums = enums === 'root' ? collectInlineEnums([...parsed.parsedByName.values(), ...operationNodes], new Set(Object.keys(schemas))) : null\n\n const schemaNodes = resolveSchemaNodes({ names: Object.keys(schemas), parsed, promotedEnums })\n\n const operations = promotedEnums ? operationNodes.map((node) => refPromotedEnums(node, promotedEnums!)) : operationNodes\n\n const authSchemes = toAuthSchemes(document.components?.securitySchemes, refs)\n\n return ast.factory.createInput({\n schemas: schemaNodes,\n operations,\n meta: toInputMeta({ document, server, authSchemes }),\n })\n }\n\n #parseSchemas({ schemas, pointers, parseSchema }: Omit<ParseInputContext, 'document' | 'refs'>): ParsedSchemas {\n const { discriminator } = this.#settings\n const parsedByName = new Map<string, ast.SchemaNode>()\n const refAliasMap = new Map<string, ast.RefSchemaNode>()\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 (discriminator === 'propagate' && isDiscriminatorParent(schema)) {\n discriminatorParentNodes.push(node)\n }\n }\n\n const discriminatorChildMap: Map<string, Array<DiscriminatorTarget>> | null =\n discriminatorParentNodes.length > 0 ? buildDiscriminatorChildMap(discriminatorParentNodes) : null\n\n return { parsedByName, refAliasMap, discriminatorChildMap }\n }\n}\n\n/**\n * Returns `true` when the schema, or any schema nested in it, is a `oneOf`/`anyOf` with a discriminator,\n * such as a union declared on a property or on array `items`.\n */\nfunction isDiscriminatorParent(schema: unknown, seen = new WeakSet<object>()): boolean {\n if (!schema || typeof schema !== 'object' || seen.has(schema)) return false\n seen.add(schema)\n\n const { oneOf, anyOf, discriminator } = schema as SchemaObject\n if ((oneOf ?? anyOf) && discriminator?.propertyName) return true\n\n return Object.values(schema).some((value) => isDiscriminatorParent(value, seen))\n}\n\nfunction resolveSchemaNodes({\n names,\n parsed: { parsedByName, refAliasMap, discriminatorChildMap },\n promotedEnums,\n}: {\n names: Array<string>\n parsed: ParsedSchemas\n promotedEnums: Map<string, ast.SchemaNode> | null\n}): Array<ast.SchemaNode> {\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.ref.getName(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 const schemaNodes: Array<ast.SchemaNode> = promotedEnums ? [...promotedEnums.values()] : []\n for (const name of names) {\n const aliasTarget = refAliasMap.get(name)?.name\n const aliased = aliasTarget ? parsedByName.get(aliasTarget) : undefined\n const parsed = parsedByName.get(name)!\n const base = (discriminatorChildMap?.get(name) ?? []).reduce(patchDiscriminatorNode, 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 return schemaNodes\n}\n\nfunction 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\nfunction toInfoMeta(info: Document['info']) {\n return {\n title: info?.title,\n description: info?.description,\n version: info?.version,\n summary: info?.summary,\n termsOfService: info?.termsOfService,\n contact: pickStrings(info?.contact, ['name', 'url', 'email']),\n license: typeof info?.license?.name === 'string' ? { ...pickStrings(info.license, ['identifier', 'url']), name: info.license.name } : undefined,\n }\n}\n\nfunction toInputMeta({ document, server, authSchemes }: { document: Document; server: AdapterSettings['server']; authSchemes: Array<ast.AuthScheme> }) {\n return {\n ...toInfoMeta(document.info),\n externalDocs: getExternalDocs(document.externalDocs),\n baseURL: resolveBaseUrl({ document, server }),\n ...(server?.index !== undefined && { serverIndex: server.index }),\n servers: toInputServers(document.servers ?? []),\n ...(document.tags?.length && { tags: toInputTags(document.tags) }),\n ...(authSchemes.length && { auth: authSchemes }),\n extensions: pickExtensions(document),\n }\n}\n\n/**\n * Default Kubb adapter for OpenAPI 2.0, 3.0, 3.1, and 3.2 specifications. Reads the\n * spec from `input` (a file path, URL, inline content, or parsed object), resolves\n * the base URL, and converts every schema and operation into the universal AST that\n * every downstream plugin consumes. Set `validate: true` to also check the spec.\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 = false,\n contentType,\n server,\n discriminator = 'preserve',\n enums = 'inline',\n pathParamsCasing,\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, pathParamsCasing, dateType, integerType, unknownType, emptySchemaType, enumSuffix }),\n build: (options) => new Adapter(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