{"version":3,"file":"baseline.mjs","names":["SCHEMA_KEYWORDS","isRecord","isRecord","isRecord","sameNames","isRecord","isRecord","fingerprintType","admits","planOperations","modelShapeKey","isRecord","allOfReadAsMember","pinnedValues","isRecord"],"sources":["../../../src/ir/sdk-behavior.ts","../../../src/errors.ts","../../../src/parser/schema-refs.ts","../../../src/parser/refs.ts","../../../src/ir/types.ts","../../../src/utils/naming.ts","../../../src/parser/external-docs.ts","../../../src/parser/extensions.ts","../../../src/parser/enum-members.ts","../../../src/parser/union-shape.ts","../../../src/parser/path-item-refs.ts","../../../src/ir/operation-hints.ts","../../../src/ir/server-url.ts","../../../src/ir/parameter-key.ts","../../../src/utils/media-type.ts","../../../src/parser/body-media-types.ts","../../../src/parser/pagination.ts","../../../src/parser/materialize-inline.ts","../../../src/parser/responses.ts","../../../src/parser/reference-objects.ts","../../../src/parser/response-refs.ts","../../../src/parser/security.ts","../../../src/parser/servers.ts","../../../src/parser/envelope-companion-names.ts","../../../src/parser/operations.ts","../../../src/parser/inline-models.ts","../../../src/parser/schema-pointers.ts","../../../src/parser/schemas.ts","../../../src/parser/webhooks.ts","../../../src/parser/callbacks.ts","../../../src/parser/normalize-inline-models.ts","../../../src/parser/collect-inline-enums.ts","../../../src/parser/parameter-group-names.ts","../../../src/parser/normalize-model-refs.ts","../../../src/parser/settle-bases.ts","../../../src/parser/collapse-error-bodies.ts","../../../src/parser/parse.ts","../../../scripts/smoke/shared.ts","../../../scripts/smoke/baseline.ts"],"sourcesContent":["/**\n * SDK Behavior IR — language-agnostic runtime policies for generated SDKs.\n *\n * These types capture the \"what\" of SDK behavior (retry, telemetry, errors, etc.)\n * while emitters provide the \"how\" (language-specific mechanism).\n *\n * Emitters access these via `ctx.spec.sdk` — always populated, never undefined.\n */\n\n// ── Retry ──────────────────────────────────────────────────────────\n\n/** Retry policy — when and how to retry failed requests. */\nexport interface RetryPolicy {\n  /** HTTP status codes that trigger a retry. */\n  retryableStatusCodes: number[];\n  /** Maximum number of retry attempts (0 = no retries). */\n  maxRetries: number;\n  /** Whether to retry on connection errors (DNS failure, TCP reset). */\n  retryOnConnectionError: boolean;\n  /** Whether to retry on timeout errors. */\n  retryOnTimeout: boolean;\n  /** Backoff strategy between retries. */\n  backoff: BackoffStrategy;\n}\n\n/** Exponential backoff configuration.\n *\n * Formula: `delay = min(initialDelay * multiplier^attempt, maxDelay)`\n * With jitter: `delay += delay * jitterFactor * random(0, 1)`\n */\nexport interface BackoffStrategy {\n  /** Initial delay in seconds before the first retry. */\n  initialDelay: number;\n  /** Multiplier applied to the delay on each subsequent retry. */\n  multiplier: number;\n  /** Maximum delay in seconds (cap). */\n  maxDelay: number;\n  /** Jitter factor (0..1). 0.5 means up to 50% random jitter added. */\n  jitterFactor: number;\n}\n\n// ── Errors ─────────────────────────────────────────────────────────\n\n/** Error mapping — status codes to named exception kinds. */\nexport interface ErrorPolicy {\n  /** Map from HTTP status code to a logical error kind name (e.g. 400 → 'BadRequest').\n   *  Emitters append language-specific suffixes (e.g. 'BadRequestException'). */\n  statusCodeMap: Record<number, string>;\n  /** Catch-all error kind for 5xx status codes not in the map. */\n  serverErrorKind: string;\n  /** Catch-all error kind for unrecognized status codes. */\n  clientErrorKind: string;\n  /** URL template for error documentation. Use {code} as placeholder for the API error code. */\n  errorDocUrlTemplate?: string;\n}\n\n// ── Telemetry ──────────────────────────────────────────────────────\n\n/** Telemetry — what request metrics to track and send. */\nexport interface TelemetryPolicy {\n  /** Whether telemetry is enabled by default. Users can opt out via constructor param. */\n  enabledByDefault: boolean;\n  /** Header name for client telemetry data (previous request's ID + latency). */\n  headerName: string;\n  /** Response header name for the request ID. */\n  requestIdHeader: string;\n}\n\n// ── Pagination ─────────────────────────────────────────────────────\n\n/** Pagination behavior defaults. */\nexport interface PaginationPolicy {\n  /** Delay in milliseconds between pages during auto-pagination. 0 = no delay. */\n  autoPageDelayMs: number;\n}\n\n// ── Idempotency ────────────────────────────────────────────────────\n\n/** Idempotency auto-generation rules. */\nexport interface IdempotencyPolicy {\n  /** Header name for the idempotency key. */\n  headerName: string;\n  /** Whether to auto-generate a UUID v4 idempotency key for POST requests when retries > 0. */\n  autoGenerateForPost: boolean;\n}\n\n// ── Logging ────────────────────────────────────────────────────────\n\n/** Logging contract — what to log at which level. */\nexport interface LoggingPolicy {\n  /** Whether structured logging hooks are generated. */\n  enabled: boolean;\n  /** Log events that the generated client emits. */\n  events: LogEvent[];\n}\n\n/** A discrete loggable event in the request lifecycle. */\nexport type LogEvent =\n  | 'request.start'\n  | 'request.success'\n  | 'request.retry'\n  | 'request.rate_limited'\n  | 'request.error'\n  | 'request.connection_error';\n\n// ── User-Agent ─────────────────────────────────────────────────────\n\n/** User-Agent construction rules. */\nexport interface UserAgentPolicy {\n  /** Template for the SDK identifier string.\n   *  Placeholders: {name} = spec name, {lang} = emitter language, {version} = SDK version.\n   *  Each emitter interpolates with its own language string and casing conventions.\n   *  Example: '{name} {lang}/{version}' → 'Acme PHP/4.32.0' */\n  sdkIdentifierTemplate: string;\n  /** Whether to append the runtime/language version (e.g. PHP 8.2, Python 3.12). */\n  includeRuntimeVersion: boolean;\n  /** Whether to allow app info enrichment via setAppInfo(name, version, url). */\n  allowAppInfo: boolean;\n  /** AI agent environment variable detection entries. */\n  aiAgentEnvVars: AiAgentEnvVar[];\n}\n\n/** Maps an environment variable to an AI agent slug for User-Agent enrichment. */\nexport interface AiAgentEnvVar {\n  /** Environment variable to check (e.g. 'CLAUDE_CODE'). */\n  envVar: string;\n  /** Agent name to append to User-Agent (e.g. 'ClaudeCode'). */\n  agentName: string;\n}\n\n// ── Request Guards ─────────────────────────────────────────────────\n\n/** Guards that validate request params before sending. */\nexport interface RequestGuardPolicy {\n  /** Keys that should be in RequestOptions, not in params.\n   *  If detected in the body or query params, the SDK throws an error. */\n  optionKeys: string[];\n}\n\n// ── Timeouts ───────────────────────────────────────────────────────\n\n/** Timeout configuration. */\nexport interface TimeoutPolicy {\n  /** Default HTTP request timeout in seconds. */\n  defaultTimeoutSeconds: number;\n  /** Environment variable name to override the timeout (e.g. 'SDK_REQUEST_TIMEOUT'). */\n  timeoutEnvVar?: string;\n}\n\n// ── Root ───────────────────────────────────────────────────────────\n\n/** Language-agnostic runtime policies for generated SDKs.\n *  Attached to `ApiSpec.sdk` and consumed by emitters via `ctx.spec.sdk`. */\nexport interface SdkBehavior {\n  retry: RetryPolicy;\n  errors: ErrorPolicy;\n  telemetry: TelemetryPolicy;\n  pagination: PaginationPolicy;\n  idempotency: IdempotencyPolicy;\n  logging: LoggingPolicy;\n  userAgent: UserAgentPolicy;\n  requestGuard: RequestGuardPolicy;\n  timeout: TimeoutPolicy;\n}\n\n// ── Defaults ───────────────────────────────────────────────────────\n\n/**\n * Canonical SDK behavior defaults. Per-language or per-project overrides can\n * be applied via `mergeSdkBehavior()` in each SDK's `oagen.config.ts`.\n *\n * - Retry: exponential backoff with jitter, retries on 429/5xx\n * - Errors: standard HTTP status → exception kind mapping\n * - Telemetry: enabled by default, tracks request ID + latency\n * - Pagination: no inter-page delay (Node overrides to 350ms)\n * - Idempotency: auto-generate UUID v4 for retryable POSTs\n * - Logging: all lifecycle events enabled\n * - User-Agent: SDK identifier + runtime version + app info + AI agent detection\n * - Request guards: detect misplaced RequestOptions keys in params\n * - Timeout: 60s default (Python overrides to 30s)\n */\nexport function defaultSdkBehavior(): SdkBehavior {\n  return {\n    retry: {\n      retryableStatusCodes: [429, 500, 502, 503, 504],\n      maxRetries: 3,\n      retryOnConnectionError: true,\n      retryOnTimeout: true,\n      backoff: {\n        initialDelay: 1.0,\n        multiplier: 2.0,\n        maxDelay: 30.0,\n        jitterFactor: 0.5,\n      },\n    },\n    errors: {\n      statusCodeMap: {\n        400: 'BadRequest',\n        401: 'Authentication',\n        403: 'Authorization',\n        404: 'NotFound',\n        409: 'Conflict',\n        422: 'UnprocessableEntity',\n        429: 'RateLimitExceeded',\n      },\n      serverErrorKind: 'Server',\n      clientErrorKind: 'Api',\n    },\n    telemetry: {\n      enabledByDefault: true,\n      headerName: 'X-Client-Telemetry',\n      requestIdHeader: 'X-Request-ID',\n    },\n    pagination: {\n      autoPageDelayMs: 0,\n    },\n    idempotency: {\n      headerName: 'Idempotency-Key',\n      autoGenerateForPost: true,\n    },\n    logging: {\n      enabled: true,\n      events: [\n        'request.start',\n        'request.success',\n        'request.retry',\n        'request.rate_limited',\n        'request.error',\n        'request.connection_error',\n      ],\n    },\n    userAgent: {\n      sdkIdentifierTemplate: '{name} {lang}/{version}',\n      includeRuntimeVersion: true,\n      allowAppInfo: true,\n      aiAgentEnvVars: [\n        { envVar: 'CLAUDE_CODE', agentName: 'ClaudeCode' },\n        { envVar: 'CURSOR_AGENT', agentName: 'Cursor' },\n        { envVar: 'CLINE_ACTIVE', agentName: 'Cline' },\n        { envVar: 'WINDSURF_ACTIVE', agentName: 'Windsurf' },\n        { envVar: 'COPILOT_AGENT', agentName: 'Copilot' },\n      ],\n    },\n    requestGuard: {\n      optionKeys: [\n        'api_key',\n        'apiKey',\n        'idempotency_key',\n        'idempotencyKey',\n        'extra_headers',\n        'extraHeaders',\n        'max_retries',\n        'maxRetries',\n        'base_url',\n        'baseUrl',\n      ],\n    },\n    timeout: {\n      defaultTimeoutSeconds: 60,\n    },\n  };\n}\n\n// ── Merge ──────────────────────────────────────────────────────────\n\n/** Recursive partial type for deep overrides. */\nexport type DeepPartial<T> = {\n  [K in keyof T]?: T[K] extends (infer U)[]\n    ? U[] // Arrays replace entirely (don't concat)\n    : T[K] extends object\n      ? DeepPartial<T[K]>\n      : T[K];\n};\n\n/**\n * Deep-merge partial overrides into the canonical defaults.\n * Arrays replace entirely (so `retryableStatusCodes: [429]` replaces the full list,\n * rather than appending). Object properties are merged recursively.\n */\nexport function mergeSdkBehavior(overrides: DeepPartial<SdkBehavior>): SdkBehavior {\n  return deepMerge(\n    defaultSdkBehavior() as unknown as Record<string, unknown>,\n    overrides as unknown as Record<string, unknown>,\n  ) as unknown as SdkBehavior;\n}\n\n/**\n * Self-contained deep merge (no external imports — ir/ is layer 0).\n * Arrays and primitives from `source` replace those in `target`.\n * Objects are merged recursively.\n */\nfunction deepMerge(target: Record<string, unknown>, source: Record<string, unknown>): Record<string, unknown> {\n  const result: Record<string, unknown> = { ...target };\n  for (const key of Object.keys(source)) {\n    const sourceVal = source[key];\n    const targetVal = target[key];\n    if (sourceVal === undefined) continue;\n    if (\n      sourceVal !== null &&\n      typeof sourceVal === 'object' &&\n      !Array.isArray(sourceVal) &&\n      targetVal !== null &&\n      typeof targetVal === 'object' &&\n      !Array.isArray(targetVal)\n    ) {\n      result[key] = deepMerge(targetVal as Record<string, unknown>, sourceVal as Record<string, unknown>);\n    } else {\n      result[key] = sourceVal;\n    }\n  }\n  return result;\n}\n","/**\n * Structured error hierarchy for oagen.\n *\n * Every error carries a human-readable `hint` that suggests a recovery action.\n * The hint is appended to the `message` so it appears in stack traces and logs.\n */\n\n/** Base class for all oagen errors. */\nexport class OagenError extends Error {\n  readonly hint: string;\n\n  constructor(message: string, hint: string) {\n    const fullMessage = hint ? `${message}\\nHint: ${hint}` : message;\n    super(fullMessage);\n    this.name = 'OagenError';\n    this.hint = hint;\n  }\n}\n\n/** Thrown when a command should terminate with a specific exit code. */\nexport class CommandError extends OagenError {\n  readonly exitCode: number;\n\n  constructor(message: string, hint: string, exitCode: number) {\n    super(message, hint);\n    this.name = 'CommandError';\n    this.exitCode = exitCode;\n  }\n}\n\n/** Thrown when an OpenAPI spec cannot be parsed or has an unsupported version. */\nexport class SpecParseError extends OagenError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'SpecParseError';\n  }\n}\n\n/** Thrown when configuration files (manifests, API surfaces, overlays) are missing or malformed. */\nexport class ConfigError extends OagenError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'ConfigError';\n  }\n}\n\n/** Thrown when a config file exists but cannot be loaded or evaluated. */\nexport class ConfigLoadError extends ConfigError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'ConfigLoadError';\n  }\n}\n\n/** Thrown when a config targets a different IR version than the installed package. */\nexport class ConfigVersionMismatchError extends ConfigError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'ConfigVersionMismatchError';\n  }\n}\n\n/** Thrown when an API surface extractor encounters a problem. */\nexport class ExtractorError extends OagenError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'ExtractorError';\n  }\n}\n\n/** Thrown when a requested language or extractor is not found in a registry. */\nexport class RegistryError extends OagenError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'RegistryError';\n  }\n}\n\n/** Thrown for internal invariant violations that indicate a bug. */\nexport class InternalError extends OagenError {\n  constructor(message: string, hint: string) {\n    super(message, hint);\n    this.name = 'InternalError';\n  }\n}\n","/**\n * Reading a Schema Object's `$ref` (#539).\n *\n * The bundler never inlines internal refs (`dereference: false`), so every\n * schema `$ref` reaches the readers as written. A `$ref` is a JSON Pointer\n * (RFC 6901), and one into `components/schemas` names either a component —\n * `#/components/schemas/Pet`, exactly one token after the map — or a schema\n * deeper inside one: `#/components/schemas/Pet/properties/owner` is `Pet`'s\n * `owner` schema, `#/components/schemas/Pets/items` the array component's\n * items. Every reader that follows a schema `$ref` reads it through this one\n * module, so none takes a pointer's last token for a component's key (which\n * named a model `Owner` that nothing declared, or an unrelated component\n * `Owner`): `componentKeyOf` answers for the readers that ask which\n * component a `$ref` names, `schemaRefTarget` for the ones that follow it\n * to the schema it points at. A `$ref` into any other section of the\n * document — a Response, Parameter or Request Body Object is no Schema\n * Object, and a pointer under `paths` is not followed — names nothing here.\n *\n * Tokens are decoded as the bundler decodes them when it checks that the\n * `$ref` resolves (`unescapePointerFragment` from `@redocly/openapi-core`,\n * which `pathItemRefTarget` reads a Path Item `$ref` with too): per token,\n * the JSON Pointer escapes undone as RFC 6901 §4 says, `~1` to `/` before\n * `~0` to `~`, then the percent-escapes a `$ref` carries as a URI fragment\n * decoded (RFC 6901 §6). So `#/components/schemas/a~1b` names the key\n * `a/b`, `#/components/schemas/Pet/properties/x~1y` the property `x/y`,\n * `#/components/schemas/Pet%20Owner` the key `Pet Owner` and\n * `#/components/schemas/Note/properties/due%20date` the property `due\n * date`. The bundler keeps the `$ref` string as written, so the parser\n * decodes it itself, and in the bundler's order, so every `$ref` the\n * bundler resolved is followed to the same place here (a `%2F` decodes\n * inside its token and never splits one).\n */\nimport { unescapePointerFragment } from '@redocly/openapi-core';\nimport type { Constraints, ModelRef, TypeRef } from '../ir/types.js';\nimport type { SchemaObject } from './schemas.js';\n\nconst SCHEMA_REF_PREFIX = '#/components/schemas/';\n\n/**\n * The reference tokens of a schema `$ref` into `components/schemas`, each\n * decoded as the bundler decodes it (`unescapePointerFragment`: the JSON\n * Pointer escapes undone, `~1` first, so `~01` is `~1` and not `/`, then\n * the percent-escapes): `['Pet']` for `#/components/schemas/Pet`, `['Pet',\n * 'properties', 'owner']` for a pointer into it, `['Pet Owner']` for\n * `#/components/schemas/Pet%20Owner`. `undefined` for a `$ref` that is not\n * a string, that points anywhere else in the document, or that ends at the\n * map itself.\n */\nexport function schemaRefTokens(ref: unknown): string[] | undefined {\n  if (typeof ref !== 'string' || !ref.startsWith(SCHEMA_REF_PREFIX)) return undefined;\n  const rest = ref.slice(SCHEMA_REF_PREFIX.length);\n  return rest === '' ? undefined : rest.split('/').map(unescapePointerFragment);\n}\n\n/**\n * The `components/schemas` key a `$ref` names — the pointer is exactly\n * `#/components/schemas/<key>` — or `undefined` for a pointer deeper into a\n * component, which names a schema and no component, and for a `$ref` into\n * another section. The one test every reader that decides by key makes\n * (whether a `$ref` is to an array, primitive or enum component, the name a\n * variant or a mapping target takes), so a pointer into `Pet` is never\n * mistaken for a component named by its last token.\n */\nexport function componentKeyOf(ref: unknown): string | undefined {\n  const tokens = schemaRefTokens(ref);\n  return tokens?.length === 1 ? tokens[0] : undefined;\n}\n\n/**\n * The schema a `$ref` points at in `schemas`: the component it names by\n * key, or the schema a deeper pointer lands on inside one\n * (`schemaAtPointer`). `undefined` when the `$ref` points outside\n * `components/schemas`, at a key the map lacks, or at no schema. The one\n * walk every reader that follows a schema `$ref` makes — to merge an\n * `allOf` member's properties, read a variant's const, take a referenced\n * schema's `example` or `default` — so a pointer is followed to the schema\n * it names wherever a component ref is followed.\n */\nexport function schemaRefTarget(\n  ref: unknown,\n  schemas: Record<string, SchemaObject> | undefined,\n): SchemaObject | undefined {\n  const tokens = schemaRefTokens(ref);\n  if (!tokens || !schemas || !Object.hasOwn(schemas, tokens[0])) return undefined;\n  const component = schemas[tokens[0]];\n  return component === undefined ? undefined : schemaAtPointer(component, tokens.slice(1));\n}\n\n/**\n * Keywords under which a Schema Object holds other schemas, and how: one\n * schema (`items`), a list of them indexed by position (`allOf/0`), or a map\n * of them by name (`properties/owner`). A pointer steps from one schema to\n * the next through these alone; any other token (`type`, `enum/0`,\n * `properties` with no name after it, an `x-` key) leads to no schema.\n */\nconst SCHEMA_KEYWORDS: ReadonlyMap<string, 'one' | 'list' | 'map'> = new Map<string, 'one' | 'list' | 'map'>([\n  ['items', 'one'],\n  ['additionalProperties', 'one'],\n  ['unevaluatedProperties', 'one'],\n  ['unevaluatedItems', 'one'],\n  ['additionalItems', 'one'],\n  ['contains', 'one'],\n  ['propertyNames', 'one'],\n  ['not', 'one'],\n  ['if', 'one'],\n  ['then', 'one'],\n  ['else', 'one'],\n  ['allOf', 'list'],\n  ['oneOf', 'list'],\n  ['anyOf', 'list'],\n  ['prefixItems', 'list'],\n  ['properties', 'map'],\n  ['patternProperties', 'map'],\n  ['dependentSchemas', 'map'],\n  ['$defs', 'map'],\n  ['definitions', 'map'],\n]);\n\n/**\n * The schema the pointer `tokens` lead to from `root`, as RFC 6901 §4\n * evaluates them — each token a key of the object at hand, or the index of\n * a list element (digits with no leading zero; `-` names nothing) — read\n * through the keywords a schema holds schemas under (`SCHEMA_KEYWORDS`), so\n * the walk lands on a Schema Object or nothing: `[]` is `root` itself,\n * `['properties', 'owner']` its `owner` property, `['allOf', '1',\n * 'properties', 'id']` the `id` of its second `allOf` member. The walk is\n * structural and never follows a `$ref` on the way: a pointer through one\n * (`Pet/properties/owner/properties/name` where `owner` is itself a `$ref`)\n * leads nowhere, as it does for any JSON Pointer evaluator; a pointer that\n * lands on a `$ref` schema is that schema, which the reader resolves in\n * turn. `undefined` for a token that names nothing, a value that is no\n * object, and a `true`/`false` boolean schema.\n */\nexport function schemaAtPointer(root: SchemaObject, tokens: readonly string[]): SchemaObject | undefined {\n  let current: SchemaObject = root;\n  for (let index = 0; index < tokens.length; index++) {\n    const keyword = tokens[index];\n    const holds = SCHEMA_KEYWORDS.get(keyword);\n    const value: unknown = Object.hasOwn(current, keyword) ? current[keyword] : undefined;\n    let next: unknown;\n    if (holds === 'one') {\n      next = value;\n    } else if (holds === 'list' && Array.isArray(value)) {\n      const token = tokens[++index];\n      next =\n        token !== undefined && isArrayIndex(token) && Number(token) < value.length ? value[Number(token)] : undefined;\n    } else if (holds === 'map' && isRecord(value)) {\n      const token = tokens[++index];\n      next = token !== undefined && Object.hasOwn(value, token) ? value[token] : undefined;\n    }\n    if (!isRecord(next)) return undefined;\n    current = next as SchemaObject;\n  }\n  return current;\n}\n\n/** Whether `token` is an array index as RFC 6901 §4 spells one: `0`, or digits with no leading zero. */\nfunction isArrayIndex(token: string): boolean {\n  if (token === '0') return true;\n  if (token === '' || token[0] === '0') return false;\n  for (const char of token) if (char < '0' || char > '9') return false;\n  return true;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * The model references `schemaToTypeRef` builds for a `$ref` that names no\n * component — a pointer deeper into one, or a `$ref` into another section\n * — each named by the `$ref` as written, a name no model can have. What\n * such a site is typed as is the type the parser gives the schema where it\n * stands (`Pet.owner`'s field type for `Pet/properties/owner`), which no\n * reader knows until every model is built, so the reference is settled\n * once they are (`resolveSchemaPointers`), in place, and until then it is\n * marked here: a merge pass never repoints it (no model carries its name),\n * and a copy keeps the mark (`cloneTypeRef`).\n */\nconst pendingSchemaRefs = new WeakSet<ModelRef>();\n\n/** A reference to be settled by `resolveSchemaPointers`, named by the `$ref` it was built from. */\nexport function pendingSchemaRef(ref: string): ModelRef {\n  const pending: ModelRef = { kind: 'model', name: ref };\n  pendingSchemaRefs.add(pending);\n  return pending;\n}\n\n/** Whether `ref` is a reference `resolveSchemaPointers` has yet to settle. */\nexport function isPendingSchemaRef(ref: ModelRef): boolean {\n  return pendingSchemaRefs.has(ref);\n}\n\n/** Mark `ref` as pending: for a copy of a pending reference (`cloneTypeRef`), which a structural clone would leave unmarked. */\nexport function markPendingSchemaRef(ref: ModelRef): void {\n  pendingSchemaRefs.add(ref);\n}\n\n/** Forget the mark once `ref` is settled into the type the pointer names. */\nexport function settlePendingSchemaRef(ref: ModelRef): void {\n  pendingSchemaRefs.delete(ref);\n}\n\n/**\n * The limits of the site a pending reference was built at — what is\n * written beside the `$ref`, with the wrapper's or `allOf` members' around\n * it, read as `schemaConstraints` reads any site (#545) — kept until the\n * reference is settled, since no `ModelRef` carries limits: the settled\n * type then carries them conjoined with the pointed schema's own, as a\n * `$ref` to a primitive component carries the component's conjoined with\n * the site's, and the field or parameter reads the same\n * (`resolveSchemaPointers`; #545 review). A copy of a pending reference\n * keeps them (`cloneTypeRef`).\n */\nconst pendingSiteLimits = new WeakMap<ModelRef, Constraints>();\n\n/** Record `limits` as what the site of the pending `ref` writes around it, in place of any recorded before; a wrapper's reading is conjoined with its branch's by the caller (`withTypeConstraints`), since it leaves a `$ref` branch out. */\nexport function recordPendingSiteLimits(ref: ModelRef, limits: Constraints | undefined): void {\n  if (limits) pendingSiteLimits.set(ref, limits);\n  else pendingSiteLimits.delete(ref);\n}\n\n/** The limits recorded for the site of the pending `ref`, `undefined` when it writes none. */\nexport function pendingSiteLimitsOf(ref: ModelRef): Constraints | undefined {\n  return pendingSiteLimits.get(ref);\n}\n\n/**\n * The entries of a discriminator `mapping` whose target is a pointer\n * deeper into a component (`#/components/schemas/Zoo/properties/dog`;\n * #539 review, #619), each to be written as the model the schema it\n * points at is built as once every model is. Such a target names no\n * component — the bundler rewrites one to a component it hoists the schema\n * into, and that rewrite is undone before the parser reads the document\n * (`loadAndBundleSpec`), so the entry reaches the parser as written — and\n * the model it names is known only once the models are built: `ZooDog`\n * for the variant written as that pointer, and `ShelterDog`, the model\n * `Shelter.dog` is built as, for a target outside the variants\n * (`Shelter/properties/dog`). So a site that builds a discriminated union\n * — a named union, an inline one, an allOf+oneOf dispatcher — records each\n * such entry here (`deferMappingEntry`): against the variant's own\n * reference when the target's schema is a pointer variant's, matched by\n * identity (`deferPointerMappingEntries`), else against a pending\n * reference of the target's own (`pendingSchemaRef`). Once\n * `resolveSchemaPointers` has settled the variants, it settles each\n * target's own reference at the mapping site and writes every entry as the\n * model its reference names (`settleDeferredMappingEntries`). A copy of the\n * union carries its entries with its copied variants, and a copy of each\n * reference of a target's own (`carryDeferredMappingEntries`, from\n * `cloneTypeRef`). Keyed by the mapping object, so a mapping the IR no\n * longer holds is forgotten with it.\n */\ninterface DeferredMappingEntry {\n  /** The discriminator value whose entry is deferred. */\n  value: string;\n  /** The reference the entry follows: the pointer variant, or its nullable wrapper, as the union holds it — or, for a target outside the variants, a pending reference of the target's own. */\n  variant: TypeRef;\n}\n\nconst deferredMappingEntries = new WeakMap<Record<string, string>, DeferredMappingEntry[]>();\n\n/** Record that `mapping`'s entry for `value` follows `variant` — a pointer variant to be settled, or a pending reference of the target's own — and is to be written as the model it settles to. */\nexport function deferMappingEntry(mapping: Record<string, string>, value: string, variant: TypeRef): void {\n  const entries = deferredMappingEntries.get(mapping) ?? [];\n  entries.push({ value, variant });\n  deferredMappingEntries.set(mapping, entries);\n}\n\n/**\n * Carry the deferred entries of `from`'s mapping onto `to`'s, each against\n * the copy of its variant at the same position, or against a copy of its\n * own reference (`copy`) for a target outside the variants — for\n * `cloneTypeRef`, which copies a union's variants and mapping alike, so\n * the copy's entries settle with the copy's references and follow their\n * renames, never the original's.\n */\nexport function carryDeferredMappingEntries(\n  from: { variants: readonly TypeRef[]; mapping: Record<string, string> },\n  to: { variants: readonly TypeRef[]; mapping: Record<string, string> },\n  copy: (ref: TypeRef) => TypeRef,\n): void {\n  for (const { value, variant } of deferredMappingEntries.get(from.mapping) ?? []) {\n    const index = from.variants.indexOf(variant);\n    const carried = index >= 0 ? to.variants[index] : copy(variant);\n    if (carried !== undefined) deferMappingEntry(to.mapping, value, carried);\n  }\n}\n\n/**\n * Write every deferred entry of `mapping` whose reference has settled to a\n * model — directly or under its nullable wrapper — as that model's name,\n * and forget the entries. A variant's reference, and a redirected inline\n * variant's (`deferPointerMappingEntries`), is settled by the walk before\n * this runs; a reference of a target's own — one outside the variants —\n * is still pending, and is settled here through `settleTarget`, at the\n * mapping site. An entry whose reference settled to no model — a pointer\n * to a string, or one that led nowhere, which the warning said — is left\n * as written. Returns every entry's reference, as the type it settled\n * into, so the caller can hand the models among them over with the union\n * (`attachSharedRefs`) when the union does not hold them as variants: a\n * rename of such a model then reaches its entries as it reaches a\n * variant's. Run once the variants are settled (`resolveSchemaPointers`).\n */\nexport function settleDeferredMappingEntries(\n  mapping: Record<string, string> | undefined,\n  settleTarget: (target: ModelRef, value: string) => void,\n): TypeRef[] {\n  const references: TypeRef[] = [];\n  if (mapping === undefined) return references;\n  const entries = deferredMappingEntries.get(mapping);\n  if (entries === undefined) return references;\n  deferredMappingEntries.delete(mapping);\n  for (const { value, variant } of entries) {\n    if (variant.kind === 'model' && isPendingSchemaRef(variant)) settleTarget(variant, value);\n    references.push(variant);\n    const model = settledVariantModel(variant);\n    if (model !== undefined && Object.hasOwn(mapping, value)) mapping[value] = model.name;\n  }\n  return references;\n}\n\n/** The model `variant` names, directly or under its nullable wrapper, once settled; `undefined` while pending or for any other type. */\nfunction settledVariantModel(variant: TypeRef): ModelRef | undefined {\n  if (variant.kind === 'nullable') return settledVariantModel(variant.inner);\n  return variant.kind === 'model' && !isPendingSchemaRef(variant) ? variant : undefined;\n}\n\n/** Whether `variant`, directly or under its nullable wrapper, is a reference `resolveSchemaPointers` has yet to settle. */\nexport function isPendingVariant(variant: TypeRef): boolean {\n  if (variant.kind === 'nullable') return isPendingVariant(variant.inner);\n  return variant.kind === 'model' && isPendingSchemaRef(variant);\n}\n","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { makeDocumentFromString, bundleDocument, createConfig, BaseResolver, Oas3_1Types } from '@redocly/openapi-core';\nimport { SpecParseError } from '../errors.js';\nimport { schemaRefTokens } from './schema-refs.js';\n\nexport interface BundledSpec {\n  parsed: Record<string, unknown>;\n  specPath: string;\n}\n\nexport async function loadAndBundleSpec(specPath: string): Promise<BundledSpec> {\n  const absolutePath = resolve(specPath);\n  const content = await readFile(absolutePath, 'utf-8');\n  const document = makeDocumentFromString(content, pathToFileURL(absolutePath).href);\n  // The bundler rewrites the document in place, so what it rewrites is\n  // recorded first and written back once it is done (see `SchemaMappingTarget`).\n  const mappingTargets = recordSchemaMappingTargets(document.parsed);\n  const ownSchemaKeys = new Set(Object.keys(componentSchemasOf(document.parsed) ?? {}));\n\n  const config = await createConfig({});\n  const resolver = new BaseResolver();\n\n  const result = await bundleDocument({\n    document,\n    config,\n    types: Oas3_1Types,\n    externalRefResolver: resolver,\n    dereference: false,\n  });\n\n  if (result.problems.some((p) => p.severity === 'error')) {\n    const errors = result.problems\n      .filter((p) => p.severity === 'error')\n      .map((p) => p.message)\n      .join('\\n');\n    throw new SpecParseError(\n      `Failed to parse spec: ${errors}`,\n      `Check the OpenAPI spec at \"${absolutePath}\" for syntax errors. Run a linter such as \\`npx @redocly/cli lint ${specPath}\\` to identify issues.`,\n    );\n  }\n\n  const parsed = result.bundle.parsed as Record<string, unknown>;\n  restoreSchemaMappingTargets(parsed, mappingTargets, ownSchemaKeys);\n  return { parsed, specPath: absolutePath };\n}\n\n/**\n * A discriminator `mapping` entry whose target is a `$ref` into\n * `components/schemas`, as the document spells it (#539, #619). The bundler\n * follows every such target to the schema it stands for — through a\n * component that is an alias (`Hound: { $ref: '#/components/schemas/\n * Shelter/properties/dog' }`; #619 review) — and, when that schema is no\n * component of its own, hoists it into a component named by its pointer's\n * last token (`dog`: the very object `Shelter.dog` is, not a copy, stepped\n * to `dog-2` when a component `dog` of another shape exists) and rewrites\n * the entry to it (`DiscriminatorMapping.leave` in `@redocly/openapi-core`'s\n * bundle visitor): `dog: '#/components/schemas/Shelter/properties/dog'`\n * and `dog: '#/components/schemas/Hound'` alike become `#/components/\n * schemas/dog`, and an alias of a component the component it aliases,\n * while a variant written as the same pointer or alias is left as written.\n * Read so, the entry would name the model built for the component the\n * bundler added (`Dog`), which no variant, field or operation references,\n * instead of the model built for the schema it stands for (`ShelterDog`).\n * So every such entry is recorded before the bundle\n * (`recordSchemaMappingTargets`) and written back after it, the component\n * the bundler added for it dropped (`restoreSchemaMappingTargets`): the\n * parser reads the entry as the document wrote it — as it reads one\n * `transformSpec` writes — and settles it to the model the schema it\n * stands for is built as (`deferPointerMappingEntries`). A target that is\n * a pointer into another section of the document, or into another file,\n * is no schema `$ref` the parser follows, and is left to the bundler.\n */\ninterface SchemaMappingTarget {\n  /** The `mapping` object, which the bundler rewrites in place. */\n  mapping: Record<string, unknown>;\n  /** The discriminator value the entry is for. */\n  value: string;\n  /** The target as the document wrote it. */\n  target: string;\n}\n\n/** Every schema mapping target under `document` (see `SchemaMappingTarget`), before the bundler reads it. */\nfunction recordSchemaMappingTargets(document: unknown): SchemaMappingTarget[] {\n  const targets: SchemaMappingTarget[] = [];\n  walkObjects(document, (node) => {\n    const mapping = isRecord(node.discriminator) ? node.discriminator.mapping : undefined;\n    if (!isRecord(mapping)) return;\n    for (const [value, target] of Object.entries(mapping)) {\n      if (typeof target === 'string' && schemaRefTokens(target) !== undefined) targets.push({ mapping, value, target });\n    }\n  });\n  return targets;\n}\n\n/**\n * Write every recorded target the bundler rewrote back as written, and\n * drop each component the bundler added for one — a key `components/\n * schemas` lacked before the bundle (`ownSchemaKeys`) — once nothing in\n * the document names it any more: a `$ref` of the document's own could\n * name no component the document lacked, so only another rewrite the\n * bundler made (one left to it, see `SchemaMappingTarget`) can, and a\n * component so named is kept. A target rewritten to a component the\n * document declares itself — the component an alias stands for, or one\n * the bundler found equal to the schema pointed at — is written back too:\n * the entry names the schema it stands for, not a look-alike, and the\n * parser reads the alias itself.\n */\nfunction restoreSchemaMappingTargets(\n  document: Record<string, unknown>,\n  targets: readonly SchemaMappingTarget[],\n  ownSchemaKeys: ReadonlySet<string>,\n): void {\n  const added = new Set<string>();\n  for (const { mapping, value, target } of targets) {\n    const rewritten = mapping[value];\n    if (rewritten === target) continue;\n    const key = schemaRefTokens(rewritten)?.[0];\n    if (key !== undefined && !ownSchemaKeys.has(key)) added.add(key);\n    mapping[value] = target;\n  }\n  if (added.size === 0) return;\n  walkObjects(document, (node) => {\n    for (const value of Object.values(node)) {\n      const key = schemaRefTokens(value)?.[0];\n      if (key !== undefined) added.delete(key);\n    }\n  });\n  const schemas = componentSchemasOf(document);\n  if (schemas === undefined) return;\n  for (const key of added) delete schemas[key];\n}\n\n/** The document's `components.schemas` map, when it has one. */\nfunction componentSchemasOf(document: unknown): Record<string, unknown> | undefined {\n  if (!isRecord(document) || !isRecord(document.components)) return undefined;\n  return isRecord(document.components.schemas) ? document.components.schemas : undefined;\n}\n\n/** Call `visit` on every object under `node`, each once: the document is a tree, and a node two aliases share is visited once. */\nfunction walkObjects(\n  node: unknown,\n  visit: (object: Record<string, unknown>) => void,\n  seen: WeakSet<object> = new WeakSet(),\n): void {\n  if (typeof node !== 'object' || node === null || seen.has(node)) return;\n  seen.add(node);\n  if (Array.isArray(node)) {\n    for (const item of node) walkObjects(item, visit, seen);\n    return;\n  }\n  const object = node as Record<string, unknown>;\n  visit(object);\n  for (const value of Object.values(object)) walkObjects(value, visit, seen);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","import type { SdkBehavior } from './sdk-behavior.js';\n\n/**\n * Authentication scheme extracted from OpenAPI `components.securitySchemes`.\n *\n * `schemeName` is the key under `components.securitySchemes`, spelled exactly as\n * in the document. The requirements under `ApiSpec.security` and\n * `Operation.security` refer to the same key, so emitters join a requirement to\n * its scheme on that field. `description` is present only when the document\n * declares one.\n */\nexport type AuthScheme = { description?: string; schemeName: string } & (\n  | { kind: 'basic' }\n  | { kind: 'bearer' }\n  | { kind: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string }\n  | { kind: 'oauth2'; flows: Record<string, unknown> }\n);\n\n/**\n * A variable in a templated server URL (`https://{region}.api.example.com`),\n * from the server's `variables` map.\n */\nexport interface ServerVariable {\n  /** Substituted for the placeholder when the caller picks no value; OpenAPI requires one. */\n  default: string;\n  /** The values the variable may take. Present only when the document declares a non-empty list. */\n  enum?: string[];\n  description?: string;\n}\n\n/** A server entry from the OpenAPI servers array */\nexport interface ServerEntry {\n  /**\n   * As written in the document, placeholders included. `ApiSpec.baseUrl` is\n   * the first server's URL with its variables' defaults filled in; resolve any\n   * other entry the same way with `resolveServerUrl` from `ir/server-url.ts`.\n   */\n  url: string;\n  description?: string;\n  /** The template's variables, keyed by placeholder name. Present only when the document declares them. */\n  variables?: Record<string, ServerVariable>;\n}\n\n/**\n * A link to documentation outside the OpenAPI document (an External\n * Documentation Object). Present on a node only when the document declares\n * one with a non-blank `url`; an emitter can surface it in a doc comment (a\n * JSDoc `@see`, say). `url` is exactly as written — OpenAPI allows a value\n * relative to the document's own location, which the parser does not know, so\n * it neither resolves nor rewrites it. `description` is present only when it\n * has non-whitespace content.\n */\nexport interface ExternalDocs {\n  url: string;\n  description?: string;\n}\n\n/**\n * The specification extensions (`x-*` keys) an OpenAPI object declares,\n * each under the key as written with its value verbatim — a string, a\n * boolean, a number, `null`, an array or an object, nested values\n * included — in document order. Carried on `Operation`, `Model`, `Field`\n * and `Enum` as `extensions`, present only when the object declares at\n * least one key the parser does not already read into a typed field (an\n * Operation Object's `x-pagination`, `x-oagen-async`,\n * `x-mutually-exclusive-parameter-groups` and\n * `x-mutually-exclusive-body-groups`; a Schema Object's\n * `x-enum-descriptions` and `x-enumDescriptions`), so an emitter can read\n * the keys it knows (`x-idempotent`, `x-since`) without the parser knowing\n * each one. Not shape: two schemas that differ only in their extensions\n * are one model or one enum wherever the parser decides that, and the\n * differ reports a change to them as additive (`extensionsChanged`,\n * `field-extensions-changed`), never as a type change. Values come from\n * the document unvalidated, so an emitter that writes one into generated\n * source must escape it as it escapes a `description`.\n */\nexport type Extensions = Record<string, unknown>;\n\n/** Root IR node representing the full API surface */\nexport interface ApiSpec {\n  name: string;\n  version: string;\n  description?: string;\n  /** The document's top-level `externalDocs`, when it declares a usable one. */\n  externalDocs?: ExternalDocs;\n  baseUrl: string;\n  servers?: ServerEntry[];\n  services: Service[];\n  /**\n   * The requests the API sends to its users, from the document's top-level\n   * `webhooks` map (OpenAPI 3.1), in document order. Absent — not an empty\n   * list — when the document declares none, so the IR of a document without\n   * webhooks is unchanged. A webhook is not an SDK method: it belongs to no\n   * service, gets no resolved operation name, and is untouched by operation\n   * hints and mount rules. See `Webhook`.\n   */\n  webhooks?: Webhook[];\n  models: Model[];\n  enums: Enum[];\n  auth?: AuthScheme[];\n  /**\n   * Document-level security requirements: the default every operation uses\n   * unless it declares its own `Operation.security`. Same shape and semantics\n   * as that field. `undefined` when the document declares none.\n   */\n  security?: SecurityRequirementSet[];\n  /** Language-agnostic runtime policies (retry, errors, telemetry, etc.). */\n  sdk: SdkBehavior;\n}\n\n/**\n * A request the API sends to its users: one HTTP method of one entry in the\n * document's top-level `webhooks` map (OpenAPI 3.1). An entry whose path item\n * declares several methods yields one `Webhook` per method, so `name` alone\n * does not identify a webhook; `name` + `httpMethod` does.\n *\n * Everything here is read from the receiver's side of the wire: the request\n * body is the payload the receiver is handed, the parameters are the headers\n * (signatures, event types) and query values the request carries, and\n * `responses` are the status codes the sender expects back. An emitter uses\n * this to generate a payload type or a typed handler per event. A webhook is\n * never an SDK method: it has no path, belongs to no `Service`, and gets no\n * resolved operation name.\n *\n * An operation's `callbacks` (OpenAPI 3.x), whose path items have this\n * shape, are read the same way: each is a `Callback`, a `Webhook` tied to\n * the operation that registers it, carried on `Operation.callbacks` — and\n * on `callbacks` here, since a `webhooks` operation may declare its own\n * (#382).\n */\nexport interface Webhook {\n  /** The key under `webhooks`, verbatim (`petAdopted`, `user.created`). */\n  name: string;\n  /**\n   * The operation's `operationId`, verbatim, when the document declares one\n   * that names something: one with no ASCII letter or digit once its trailing\n   * overload markers are stripped (`' '`, `'-'`, `'[1]'`, `'[1][2]'`) is left\n   * out, as `''` is and as on an `Operation`, and the webhook's models are\n   * named from its key (#564). No `operationIdTransform` is applied to it.\n   */\n  operationId?: string;\n  httpMethod: HttpMethod;\n  /**\n   * The `summary` alone, read as `Operation.summary` is: the operation's own,\n   * else the path item's. Absent when neither has content.\n   */\n  summary?: string;\n  /**\n   * The `description` alone, read as `Operation.description` is: the\n   * operation's own, else the path item's, never built from the summary (a\n   * `description` identical to the `summary` is kept in both). Absent when\n   * neither has content.\n   */\n  description?: string;\n  /**\n   * The operation's own `externalDocs`, when it declares a usable one, as on\n   * `Operation.externalDocs`. A Path Item Object has no `externalDocs`, so\n   * there is nothing to fall back to.\n   */\n  externalDocs?: ExternalDocs;\n  /** Present, and `true`, only when the document marks the webhook deprecated. */\n  deprecated?: boolean;\n  /** The operation's `tags`, read exactly as `Operation.tags` is. */\n  tags?: string[];\n  /** Header parameters the request carries, typed like `Operation.headerParams`. */\n  headerParams: Parameter[];\n  /** Query parameters the request carries, typed like `Operation.queryParams`. */\n  queryParams: Parameter[];\n  /** Cookie parameters; present only when the document declares at least one. */\n  cookieParams?: Parameter[];\n  /**\n   * The payload the receiver is handed. An inline object schema is\n   * materialized as a model named `<Stem>Payload`, where the stem is the\n   * `operationId` when there is one and the webhook's name otherwise (see the\n   * parser's `resolveWebhookModelStems` for how the stem is kept unique).\n   * Read from the content entry the same pick as `Operation.requestBody`\n   * chooses, by media type essence. Absent when the operation declares no\n   * `requestBody`, or one none of whose media types is read — which the\n   * parser warns about.\n   */\n  requestBody?: TypeRef;\n  /** How the payload is encoded, read like `Operation.requestBodyEncoding`. */\n  requestBodyEncoding?: 'json' | 'form-data' | 'form-urlencoded' | 'binary' | 'text';\n  /**\n   * The media type the payload was read from, by essence, read like\n   * `Operation.requestBodyContentType` (`application/merge-patch+json`;\n   * `application/json` for `application/json; charset=utf-8`): what the\n   * sender labels the request with, so a handler can check it. Present\n   * exactly when `requestBody` is.\n   */\n  requestBodyContentType?: string;\n  /**\n   * Present, and `true`, only when the document marks the request body\n   * `required` and the body declares a media type (`requestBodyContentTypes`\n   * is set), the presence rule `Operation.requestBodyRequired` follows: a\n   * payload carried in `requestBodyContents` alone keeps it, and a body with\n   * no `content`, or an empty map, has no entry.\n   */\n  requestBodyRequired?: boolean;\n  /**\n   * Doc text for the payload, read as `Operation.requestBodyDescription`\n   * is: the Request Body Object's own `description`, else the `description`\n   * written on the schema of the content entry `requestBody` is read from (a\n   * `$ref` is not followed; a nullable `oneOf`/`anyOf` or a single-member\n   * `allOf`, `oneOf` or `anyOf` is read to its branch, its own text first,\n   * an `allOf` member that declares no type being part of the wrapper, #555; a\n   * `oneOf`/`anyOf` of consts read as an enum is read as itself, never to a\n   * variant, #535). Present only when one of the two has non-whitespace\n   * content, kept verbatim.\n   */\n  requestBodyDescription?: string;\n  /**\n   * Media types the payload declares under `content`, in document order and\n   * exactly as written, read as `Operation.requestBodyContentTypes` is.\n   * Present only when at least one is declared.\n   */\n  requestBodyContentTypes?: string[];\n  /**\n   * One entry per `requestBodyContentTypes` entry, in the same order, typed\n   * as `Operation.requestBodyContents` is: the entry for the media type\n   * `requestBody` was read from carries that same TypeRef; an inline object\n   * under another media type is materialized as `<Stem><MediaType>Payload`\n   * (`PetAdoptedTextCsvPayload`). Present only when `requestBodyContentTypes`\n   * is.\n   */\n  requestBodyContents?: RequestBodyContent[];\n  /**\n   * The responses the sender expects from the receiver, in document order:\n   * one entry per status code key (three digits, 100–599) the operation\n   * declares. `default`, range (`2XX`) and `x-` keys are not carried; a key\n   * that is none of those (`error`, `6XX`, `600`) is ignored with a warning.\n   * An entry at a status code that is not an object — `200: \"oops\"`,\n   * `null`, `7` — is no Response Object and no Reference Object: it is\n   * skipped with one warning naming the site (`200 response of\n   * webhooks.petAdopted.post is not a Response Object (\"oops\"); skipping\n   * it.`), as is a `$ref` whose chain ends on a `components/responses` entry\n   * that is not an object (`Gone: []`), the warning naming the component\n   * (`components/responses/Gone (the 200 response of\n   * webhooks.petAdopted.post) is not a Response Object ([]); skipping it.`),\n   * and a `responses` that is not an object at all is read as declaring\n   * none, with a warning (#617); a callback's are read the same way.\n   * Body schemas on these responses are not carried either: a webhook\n   * response is an acknowledgement, and typing it would mint models no\n   * handler needs.\n   */\n  responses: WebhookResponse[];\n  /**\n   * The security the request carries, mirroring the OpenAPI document exactly\n   * as `Operation.security` does: `undefined` inherits `ApiSpec.security`,\n   * `[]` means none, otherwise one alternative per requirement object.\n   */\n  security?: SecurityRequirementSet[];\n  /**\n   * The callbacks the webhook's operation declares, read exactly as\n   * `Operation.callbacks` is: present only when at least one is readable, in\n   * document order. A callback nests through this field in turn, since a\n   * `Callback` is a `Webhook`.\n   */\n  callbacks?: Callback[];\n}\n\n/** One status code a webhook's sender expects back, with the document's description of it. */\nexport interface WebhookResponse {\n  statusCode: number;\n  description?: string;\n}\n\n/**\n * A request the API sends to a URL the caller handed it: one HTTP method of\n * one path item under one runtime expression of one `callbacks` entry\n * (OpenAPI 3.x). Read from the receiver's side exactly as a `Webhook` is —\n * the payload, parameters, responses, docs, deprecation, tags and security\n * are the same fields, read by the same code — and tied to the operation\n * or webhook that registers it through `Operation.callbacks` /\n * `Webhook.callbacks` (#382). A callback has no fixed path: the path item\n * is keyed by a runtime expression the sender evaluates per request, kept\n * verbatim as `expression`. One `callbacks` key may map several expressions\n * to path items, each declaring several methods, so `name` + `expression`\n * + `httpMethod` identifies a callback, and that triple is what `oagen\n * diff` keys its `callback-added` / `callback-removed` / `callback-modified`\n * changes on. A callback is never an SDK method, as a webhook is not.\n *\n * Its payload is materialized as `<Stem>Payload` where the stem is the\n * callback operation's `operationId` when it declares one that names\n * something and no other callback operation declares the same, else the\n * owner's stem followed by the key PascalCased — `createPet`'s `petAdopted`\n * mints `CreatePetPetAdoptedPayload` (see the parser's `extractCallbacks`).\n */\nexport interface Callback extends Webhook {\n  /** The key under the operation's `callbacks` map, verbatim (`petAdopted`). */\n  name: string;\n  /** The runtime expression the path item is keyed by, verbatim (`{$request.body#/callbackUrl}`); a callback has no fixed path. */\n  expression: string;\n}\n\n/**\n * The site a callback is read and reported under, below its owner's\n * `context` — an operation's `operationId` (else `METHOD /path`) or\n * `<service>.<operation>`, a webhook's `webhooks.<key>.<method>`, a parent\n * callback's own: `<context>.callbacks.<name>.<expression>.<method>`\n * (`createPet.callbacks.petAdopted.{$request.body#/callbackUrl}.post`).\n * One format for the parser's warnings and for every walker's diagnostics\n * (#382).\n */\nexport function callbackContext(\n  context: string,\n  callback: Pick<Callback, 'name' | 'expression' | 'httpMethod'>,\n): string {\n  return `${context}.callbacks.${callback.name}.${callback.expression}.${callback.httpMethod}`;\n}\n\n/** A service groups related operations (maps to an SDK resource class) */\nexport interface Service {\n  name: string;\n  description?: string;\n  /**\n   * A document tag's `externalDocs`, resolved by the same rule as\n   * `description`: a service named after a declared tag takes that tag's; a\n   * split-off service inherits it from the first linked tag its operations\n   * carry, chosen independently of the tag its description comes from.\n   * Absent when no tag gives one.\n   */\n  externalDocs?: ExternalDocs;\n  operations: Operation[];\n}\n\n/** One scheme a request must satisfy, with the scopes it needs. */\nexport interface SecurityRequirement {\n  /** Key under `components.securitySchemes`; joins to `AuthScheme.schemeName`. */\n  schemeName: string;\n  scopes: string[];\n}\n\n/**\n * One alternative from an OpenAPI security requirement list: a request must\n * satisfy *every* scheme in the set together (\"all of\"). A list of sets is\n * satisfied by *any one* of them (\"either of\"). An empty set is an alternative\n * that needs no credentials at all, which is how a document makes\n * authentication optional (`security: [{ userToken: [] }, {}]`).\n */\nexport type SecurityRequirementSet = SecurityRequirement[];\n\n/** A single API operation (maps to an SDK method) */\nexport interface Operation {\n  name: string;\n  /**\n   * The operation's `operationId`, verbatim, when the document declares one\n   * that names something: one with no ASCII letter or digit once its trailing\n   * overload markers are stripped — every `[N]` at the end, so `' '`, `'-'`,\n   * `'[1]'` and `'[1][2]'` alike — is left out, as `''` is, and the operation\n   * is path-named. `name` is what the parser made of it\n   * (`operationIdTransform` applied, after the markers are stripped:\n   * `listPets[1][2]` is `listPets`); this says that `name` came from one at\n   * all, which is what `resolveOperations` reads to prefer it over the\n   * path-derived method name. Left out as well when the transform returns a\n   * name that names nothing by the same reading (`''`, `' '`, `'-'`, `'[1]'`),\n   * or no string at all: the operation is path-named, with one warning, as\n   * if the document had declared no `operationId` (#570).\n   */\n  operationId?: string;\n  /**\n   * The `summary` alone: the OpenAPI operation's own, or — when the operation\n   * declares none with non-whitespace content — the `summary` of the Path\n   * Item it sits on (the `paths` entry, or the Path Item a `$ref` entry\n   * leads to), which OpenAPI applies to every operation on that\n   * path. Present only when one of the two has content; a summary that is not\n   * a string, or is empty or whitespace-only, is treated as absent at either\n   * level. `description` below never includes it, so an emitter that\n   * shows the summary — as a one-line label, or above the description —\n   * reads it from here.\n   */\n  summary?: string;\n  /**\n   * The `description` alone, read as `summary` above is: the operation's own,\n   * else the Path Item's. It is never built from the summary, so an operation\n   * that declares only a `summary` has none; a `description` identical to the\n   * `summary` is kept in both, since each is the document's own text. A value\n   * that is not a string, or is\n   * empty or whitespace-only, is treated as absent, and text with content is\n   * kept verbatim.\n   */\n  description?: string;\n  /** The operation's own `externalDocs`, when it declares a usable one. */\n  externalDocs?: ExternalDocs;\n  httpMethod: HttpMethod;\n  path: string;\n  /**\n   * The servers this operation is served from, when they differ from the\n   * document's: the operation's own `servers`, else its Path Item's (OpenAPI\n   * precedence). Absent when the operation inherits `ApiSpec.servers` — it\n   * declares none at either level, or what it declares is the document's list\n   * again (same URLs, descriptions and variables, in the same order), or both\n   * it and the document mean OpenAPI's default server (no servers,\n   * `servers: []`, or nothing but `/`, whatever its description or\n   * variables — `/` references none; `isDefaultServerList` in\n   * `ir/server-url.ts`). Same\n   * shape as `ApiSpec.servers`, variables included, so `resolveServerUrl`\n   * from `ir/server-url.ts` fills a template's defaults the way `baseUrl` was\n   * produced. To find where a request goes, take `op.servers ?? spec.servers`.\n   */\n  servers?: ServerEntry[];\n  pathParams: Parameter[];\n  queryParams: Parameter[];\n  /**\n   * Query parameters the spec also declares as request-body properties on a\n   * body-carrying method (POST/PUT/PATCH). They travel in the body only, so\n   * they are excluded from `queryParams`; they are kept here so inline enums\n   * they declare stay reachable and the compat surface still sees them.\n   * Emitters never serialize these to the URL.\n   */\n  bodyOwnedQueryParams?: Parameter[];\n  headerParams: Parameter[];\n  cookieParams?: Parameter[];\n  /**\n   * The request body's type, read from one content entry of the Request Body\n   * Object (after a `components/requestBodies` `$ref` is resolved). Media\n   * types are matched by essence — parameters and case aside, so\n   * `application/json; charset=utf-8` and `APPLICATION/JSON` are\n   * `application/json` — and tried in a fixed order: `application/json`, then\n   * a `+json` media type (`application/vnd.api+json`; never a range such as\n   * `application/*+json`), then `multipart/form-data`, then\n   * `application/x-www-form-urlencoded`, each\n   * only when it declares a schema; then `application/octet-stream`, then\n   * `text/plain`, with or without one (a schema-less binary body is a binary\n   * string, a schema-less text body a string). An inline object body is\n   * materialized as `<Op>Request`; an inline enum body, or an array of one,\n   * is promoted to `spec.enums` under that name, numbered on a clash with an\n   * enum of other members. Absent when the operation declares no\n   * body, or one none of whose media types is read — which the parser warns\n   * about once, so a body is never dropped silently.\n   */\n  requestBody?: TypeRef;\n  /**\n   * The wire encoding of the media type `requestBody` was read from: `json`\n   * for `application/json` and any concrete `+json` media type, `form-data`\n   * for `multipart/form-data`, `form-urlencoded` for\n   * `application/x-www-form-urlencoded`, `binary` for\n   * `application/octet-stream`, `text` for `text/plain`. Set exactly when\n   * `requestBody` is.\n   */\n  requestBodyEncoding?: 'json' | 'form-data' | 'form-urlencoded' | 'binary' | 'text';\n  /**\n   * The media type `requestBody` was read from, by essence — `type/subtype`\n   * with parameters and case stripped: `application/merge-patch+json` for a\n   * body declared under that key, `application/json` for one under\n   * `application/json; charset=utf-8`, `multipart/form-data` for one under\n   * `multipart/form-data; boundary=x`. This is what an emitter sends as the\n   * request's `Content-Type`, so a server that requires its declared media\n   * type accepts the request; parameters such as a multipart boundary are\n   * the emitter's to produce. `requestBodyEncoding` says how to serialize\n   * the body, this says how to label it. The key as written is the\n   * `contentType` of the `requestBodyContents` entry that shares\n   * `requestBody`'s type. Set exactly when `requestBody` is.\n   */\n  requestBodyContentType?: string;\n  /**\n   * Whether a caller must send the request body: the Request Body Object's\n   * `required`, read after a `components/requestBodies` `$ref` is resolved.\n   * OpenAPI defaults the flag to `false`, so a body the document does not\n   * mark required comes through as `false`. Present exactly when\n   * `requestBodyContentTypes` is — whenever the body declares a media type,\n   * whether it is read as `requestBody` or carried in `requestBodyContents`\n   * alone — so it is set beside every `requestBody` but does not imply one;\n   * an operation without a body, or whose body declares no media type, has\n   * no entry.\n   */\n  requestBodyRequired?: boolean;\n  /**\n   * Doc text for the request body, e.g. \"The pet to add to the shelter.\" —\n   * what an emitter prints for the body argument, as `responseDescription`\n   * is what it prints for the return. The Request Body Object's own\n   * `description`, read after a `components/requestBodies` `$ref` is\n   * resolved; when that has no non-whitespace content, the `description`\n   * written on the schema of the content entry `requestBody` is read from,\n   * as it stands there: a `$ref` is not followed, so a component's text\n   * stays on its model, while a `description` written beside the `$ref` is\n   * read; a wrapper the parser collapses or sees through — a nullable\n   * `oneOf`/`anyOf`, a single-member `allOf`, `oneOf` or `anyOf` — is read\n   * to its branch, its own text first, an `allOf` member that declares no\n   * type being part of the wrapper (`allOf: [{ $ref: Pet }, { description }]`\n   * carries that text; #555), while a `oneOf`/`anyOf` of consts\n   * read as an enum, nullable or not, is the schema that declares the\n   * members and is read as itself, never to a variant (#535). When both\n   * have content the body's own wins. The schema's text is also the `description` of the model an\n   * inline object body is materialized as (`<Op>Request`), and the `description` of the `Enum`\n   * an inline enum body is lifted to (`<Op>Request` in `enums`); for a body\n   * no model or enum carries — an inline `oneOf`, an array, a primitive —\n   * this field is the only place that text reaches. Present only when one\n   * of the two has non-whitespace content, kept verbatim. The body's own text is\n   * carried whether or not a media type is read as `requestBody`; the\n   * schema's is read only from the entry that is.\n   */\n  requestBodyDescription?: string;\n  /**\n   * Media types the request body declares under `content`, in document\n   * order and exactly as written (`application/json; charset=utf-8`,\n   * `multipart/form-data; boundary=x`, `text/csv`), so an emitter can offer\n   * each verbatim as a `Content-Type`. Present only when the body declares at\n   * least one media type — whether or not one of them is read as\n   * `requestBody` — as `responseContentTypes` is on the response side.\n   */\n  requestBodyContentTypes?: string[];\n  /**\n   * One entry per `requestBodyContentTypes` entry, in the same order, with\n   * the type that media type resolves to. The entry for the media type\n   * `requestBody` was read from carries that very TypeRef, so the two never\n   * disagree. Every other entry is typed as it would be were it the only one\n   * declared: from its schema when it has one (an inline object materialized\n   * as `<Op><MediaType>Request`, `ReplaceWidgetTextCsvRequest`), else a\n   * binary string for `application/octet-stream`, a string for `text/plain`,\n   * and `unknown` for any other media type. Present only when\n   * `requestBodyContentTypes` is.\n   */\n  requestBodyContents?: RequestBodyContent[];\n  /**\n   * The primary success response's body type: the lowest declared status code\n   * from 200 to 399 whose type is not `unknown` — the lowest 2xx with a typed\n   * body, so a `200` left `unknown` by the media-type rules (a schema-less\n   * `text/csv`) yields to a `201` typed from a schema, and a 3xx entry (always\n   * `unknown`) never wins over a typed 2xx — falling back to the lowest\n   * declared code (an untyped 2xx, or a 3xx when no 2xx is declared).\n   * `responseHeaders` and `responseDescription` come from the same entry.\n   * Never promoted from a `2XX` range or the `default` response: an\n   * operation declaring no 2xx or 3xx response at all (only `default` or\n   * `2XX`, only a `404`, an empty `responses` map, or no `responses` key)\n   * has `{ kind: 'primitive', type: 'unknown' }` here — the type of a body\n   * the document does not describe — with no `responseHeaders` or\n   * `responseDescription`, and an emitter should take the success body\n   * from `rangeResponses` (`2XX`), then `defaultResponse` — the same order\n   * it resolves any status: the explicit entry, then the matching range,\n   * then the default. A body that is itself an inline enum is promoted to\n   * `spec.enums` as `<Op>Response`, and an array of one as `<Op>Item` (see\n   * `SuccessResponse.type` for one of several success bodies).\n   */\n  response: TypeRef;\n  /**\n   * The status code of the response `response` was read from — the primary\n   * success response chosen as described there: `200`; `201` when an untyped\n   * `200` yielded to a typed `201`; `302` for a lone redirect; a POST's lone\n   * `200`. Present exactly when the operation declares at least one 2xx or\n   * 3xx response, and absent when it declares none (only `default`, a range,\n   * 4xx/5xx codes, an empty `responses` map or no `responses` key) — the\n   * case where `response` is `unknown`. When `successResponses` is set, this\n   * equals the `statusCode` of the entry `response` was taken from. Read it\n   * to check or document the status an operation succeeds with instead of\n   * guessing one from the HTTP method. The differ pairs a lone 2xx/3xx with\n   * the other spec's entry of this code, so an entry added beside it is not\n   * mistaken for it, and reports it moving while both specs carry one as\n   * `responseStatusCodeChanged`, breaking unless the new spec still declares\n   * the old code among its 2xx/3xx (#407).\n   */\n  responseStatusCode?: number;\n  /**\n   * Headers the primary success response declares (the one `response` is the\n   * body of). Present only when the spec declares at least one. Each entry of\n   * `successResponses` carries its own `headers`, but that list is only set\n   * when an operation declares more than one 2xx or 3xx response (counted\n   * together), so the primary response's headers need a home of their own.\n   */\n  responseHeaders?: ResponseHeader[];\n  /**\n   * Media types the primary success response declares under `content`, in\n   * document order and exactly as written (`application/json; charset=utf-8`,\n   * `application/vnd.api+json`, a wildcard such as `application/*`). Present\n   * only when it declares at least one. Like `responseHeaders`, this lifts\n   * the primary entry's `contentTypes`, because `successResponses` only\n   * exists when an operation declares more than one 2xx or 3xx response.\n   */\n  responseContentTypes?: string[];\n  /**\n   * One entry per `responseContentTypes` entry, in the same order, with the\n   * type that media type's schema resolves to. The entry for the media type\n   * `response` was read from carries that same TypeRef. Present only when\n   * `responseContentTypes` is.\n   */\n  responseContents?: ResponseContent[];\n  /**\n   * The `description` of the primary success response (the one `response` is\n   * the body of), e.g. \"The pet, with its owner.\" — often the clearest\n   * statement of what an operation gives back, so an emitter can print it as\n   * a `@returns` tag. Present only when that response declares one with\n   * non-whitespace content; the text is kept verbatim. Each entry of\n   * `successResponses` carries its own `description`, but that list is only\n   * set when an operation declares more than one 2xx or 3xx response (counted\n   * together), so the primary response's description needs a home of its own.\n   */\n  responseDescription?: string;\n  /**\n   * Every declared 2xx and 3xx response, one `SuccessResponse` per status\n   * code, each with its own `type`, `headers` and `description`. A 2xx entry's\n   * `type` is its body, read by media type compared by essence, parameters\n   * and case aside (the JSON schema — `application/json`, else a `+json`\n   * media type; else binary string for `application/octet-stream` /\n   * `application/pdf`; else `string` for `text/plain`, `text/html`,\n   * `text/xml`, `application/xml`; else the schema of the first media type\n   * that declares one) and `unknown` when none applies, a schema-less\n   * `text/csv` included; a 3xx entry's `type` is always\n   * `unknown`, and the entry is kept so an emitter can\n   * recognize a redirect endpoint. Set only when more than one such response\n   * is declared, counting 2xx and 3xx together: `200` + `201`, `200` + `302`\n   * and `301` + `302` all set it, while a lone `200` (or a lone `302`) leaves\n   * it `undefined` and `response` / `responseHeaders` / `responseDescription`\n   * describe that single response alone. 4xx and 5xx responses go to\n   * `errors`; `default` and the ranges `1XX`–`5XX` to `defaultResponse` and\n   * `rangeResponses`; an explicit 1xx code is not carried. A key is a status\n   * code only when it is exactly three digits in 100–599: `6XX`, `4XXX`,\n   * `20X`, `600` and `200 ` are no status code and no range, so they are\n   * ignored with a warning, like `error`, never read from a numeric prefix.\n   * An entry that is not an object — `200: \"oops\"`, `null`, `7`, `true`,\n   * `[]` — under any key a reader reads (a status code, `default`, a range)\n   * is no Response Object and no Reference Object: it is skipped with one\n   * warning naming the site (`200 response of listPets is not a Response\n   * Object (\"oops\"); skipping it.`) and the operation is read from its other\n   * entries, so `listPets` with `200: \"oops\"` beside a `204` is read from\n   * the `204`, with no entry here, in `errors`, `defaultResponse` or\n   * `rangeResponses` for the skipped key; a `$ref` whose chain ends on a\n   * `components/responses` entry that is not an object (`Gone: []`) is\n   * skipped the same way, the warning naming the component\n   * (`components/responses/Gone (the 200 response of listPets) is not a\n   * Response Object ([]); skipping it.`), so the inline and `$ref`\n   * spellings give one IR; a `responses` that is not an object at all is\n   * read as absent, with a warning (#617).\n   */\n  successResponses?: SuccessResponse[];\n  errors: ErrorResponse[];\n  /**\n   * The document's `default` response: what the operation returns for every\n   * status it does not list explicitly or by range. Present only when the\n   * spec declares one. It is kept apart from `errors` because it carries no\n   * status code (`ErrorResponse.statusCode` is a number emitters compare and\n   * format as one) and is not always an error — a spec may use it for its\n   * success body too. An emitter should treat its `type` as the fallback for\n   * any status that neither `errors`/`successResponses` nor `rangeResponses`\n   * covers. `response` is never promoted from it: when the operation declares\n   * no explicit 2xx, the emitter takes the success body from the `2XX` entry\n   * of `rangeResponses`, then from here.\n   */\n  defaultResponse?: DefaultResponse;\n  /**\n   * The document's `1XX`–`5XX` range responses, in declaration order. Present\n   * only when the spec declares at least one. A range covers every status in\n   * its hundred that the operation does not list explicitly, so an emitter\n   * resolves a status in the order OpenAPI does: the explicit entry, then\n   * the range, then `defaultResponse`. Ranges never feed `response`,\n   * `successResponses` or `errors`, whose numeric `statusCode` could not say\n   * which codes an entry stands for.\n   */\n  rangeResponses?: RangeResponse[];\n  pagination?: PaginationMeta;\n  injectIdempotencyKey: boolean;\n  deprecated?: boolean;\n  async?: boolean;\n  /**\n   * The operation's `tags`, in document order, with every entry that is not\n   * a string with non-whitespace content dropped and a repeated entry folded\n   * onto its first occurrence. Present only when at least one remains. The\n   * parser names the service from the first entry that still has a name once\n   * PascalCased (`tags[0]`, unless it has no ASCII letter or digit, like\n   * `-`), or from the path when none has one, as for an untagged operation;\n   * the list is kept so an emitter can group or document the method by every\n   * tag.\n   */\n  tags?: string[];\n  /**\n   * Per-operation security requirements, mirroring the OpenAPI document:\n   * - `undefined` — the operation declares nothing and inherits\n   *   `ApiSpec.security` (which may itself be `undefined`).\n   * - `[]` — `security: []`: the operation needs no authentication.\n   * - otherwise one `SecurityRequirementSet` per requirement object; the\n   *   request must satisfy any one set, and every scheme within it.\n   */\n  security?: SecurityRequirementSet[];\n  /**\n   * Mutually-exclusive parameter groups parsed from `x-mutually-exclusive-parameter-groups`.\n   * Each group represents a logical choice the caller must (or may) make between\n   * several subsets of query/path/header parameters. The grouped parameters remain\n   * in their original arrays (queryParams, pathParams, etc.) for wire-format purposes;\n   * this field adds the grouping metadata so emitters can render sum types.\n   */\n  parameterGroups?: ParameterGroup[];\n  /**\n   * The Operation Object's own `x-*` keys (see `Extensions`), less the ones\n   * the parser reads into typed fields: `x-pagination` (`pagination`),\n   * `x-oagen-async` (`async`), `x-mutually-exclusive-parameter-groups` and\n   * `x-mutually-exclusive-body-groups` (`parameterGroups`). A Path Item\n   * Object's extensions are not read. Present only when at least one key\n   * remains.\n   */\n  extensions?: Extensions;\n  /**\n   * The requests the API sends back to URLs the caller supplied, from the\n   * Operation Object's `callbacks` map (OpenAPI 3.x), each read as a\n   * `Webhook` is (see `Callback`; #382). Present only when the operation\n   * declares at least one readable callback, in document order: `callbacks`\n   * key order, then expression order within each Callback Object, then the\n   * path item's method order. A callback is not an SDK method: it belongs\n   * to no service, gets no resolved operation name, and is untouched by\n   * operation hints and mount rules; an emitter types its payload, or a\n   * handler for it, beside the operation. Its models are named from this\n   * operation's stem (`CreatePetPetAdoptedPayload`) and assigned to this\n   * operation's service, as the operation's own are.\n   */\n  callbacks?: Callback[];\n}\n\n/**\n * A mutually-exclusive parameter group. The caller must supply exactly one\n * variant (when `optional` is false) or may omit the group entirely (when true).\n */\nexport interface ParameterGroup {\n  /** Group name from the extension (e.g. \"parent_resource\"). */\n  name: string;\n  /** True when the whole group may be omitted. */\n  optional: boolean;\n  /** Ordered variants (insertion order matches the spec). */\n  variants: ParameterGroupVariant[];\n  /**\n   * Base name emitters must use for this group's generated wrapper type, in\n   * place of `name`.\n   *\n   * Two operations commonly share one group name — create and update both\n   * declare `protocol_options` — and emitters name the wrapper from the group\n   * name alone, so both operations collapse onto one type. That is correct\n   * only while their members agree. When they disagree (create's\n   * `saml_options` is a `CreateConnectionSAMLOptions`, update's is a\n   * `PatchConnectionSAMLOptions`) one wrapper silently forces one operation to\n   * use the other operation's type.\n   *\n   * The parser therefore fingerprints each group's members across every\n   * operation declaring it and qualifies this with the operation name\n   * (`update_connection_protocol_options`) only where they genuinely diverge.\n   * Groups that agree — including ones differing only by nullability, or by\n   * duplicate inline enums carrying identical values — keep the bare group\n   * name, so already-published wrapper types are never renamed.\n   */\n  wrapperName?: string;\n}\n\n/**\n * One variant within a mutually-exclusive parameter group.\n */\nexport interface ParameterGroupVariant {\n  /** Variant name from the extension (e.g. \"by_id\", \"by_external_id\"). */\n  name: string;\n  /**\n   * References to the actual parameter IR nodes. These are the same\n   * objects that live in operation.queryParams / .pathParams / .headerParams --\n   * shared by identity, not duplicated.\n   */\n  parameters: Parameter[];\n  /**\n   * Names of parameters that may be omitted when this variant is used —\n   * optional modifiers of the variant's required fields, from the\n   * extension's `optionalFields`. Absent means every parameter in the\n   * variant is required with it.\n   */\n  optionalParameters?: string[];\n}\n\n/**\n * How an operation's list is paged — what an auto-paging iterator sends to\n * reach the next page:\n *\n * - `cursor` — `param` carries an opaque cursor taken from the previous\n *   response; iteration ends when the response yields no next cursor.\n * - `offset` — `param` is the number of items to skip; advance it by the\n *   number of items received, with `limitParam` as the page size.\n * - `page` — `param` is a page *number*; start at `pageStart` (the\n *   parameter's `default`, else its `minimum`, else 1) and advance it by\n *   exactly one per request, with `limitParam` as the page size.\n * - `link-header` — follow the RFC 5988 `Link: <…>; rel=\"next\"` response\n *   header instead of building the next request from `param`.\n *\n * Under every strategy an empty page ends the iteration; `endOfIteration`\n * names a response field that ends it earlier.\n */\nexport type PaginationStrategy = 'cursor' | 'offset' | 'page' | 'link-header';\n\n/**\n * The response field that tells an iterator the last page has been reached.\n * `path` is a dotted property path from the response root, in the convention\n * `dataPath` uses: `has_more` at the top level, `pagination.totalPages` one\n * level down inside the pagination companion.\n *\n * - `hasMore` — a boolean; stop when it is `false`.\n * - `totalPages` — an integer count of pages; stop once the pages fetched so\n *   far reach it. For the `page` strategy that is\n *   `page - pageStart + 1 >= totalPages` — `page >= totalPages` when pages\n *   start at 1, `page + 1 >= totalPages` when they start at 0 — for\n *   `offset` it is `floor(offset / limit) + 1 >= totalPages`, and for\n *   `cursor`, whose opaque cursor carries no page number, it is the number\n *   of requests made so far `>= totalPages`.\n * - `totalCount` — an integer count of items; stop once the items received\n *   so far reach it.\n *\n * An empty page ends the iteration under every kind and every strategy.\n */\nexport interface PaginationEndOfIteration {\n  kind: 'hasMore' | 'totalPages' | 'totalCount';\n  path: string;\n}\n\n/**\n * Structured pagination metadata for auto-paging iterator generation.\n *\n * Present only when a query parameter the operation declares drives the\n * iterator — the one detection recognized, or the one an override names —\n * so `param` is always a query parameter of the operation. A list envelope\n * returned by an operation that declares no such parameter (a `page`\n * without a page size, no paging parameter at all) is kept as a plain\n * response model and has no entry here.\n */\nexport interface PaginationMeta {\n  strategy: PaginationStrategy;\n  /** Query parameter that selects the page: the cursor, the offset, or the page number. */\n  param: string;\n  /** Query parameter that sets the page size (`offset` and `page` strategies). */\n  limitParam?: string;\n  /**\n   * First page number the API expects; set for the `page` strategy only. The\n   * page parameter's integer `default`, else its `minimum`, else 1 — read\n   * from the parameter's schema as written, through a `$ref`, `allOf`\n   * members and nullable wrappers — or the value an override sets (an\n   * override may set it under the `page` strategy only). An\n   * iterator sends `pageStart` first and `pageStart + n` after `n` pages;\n   * `PaginationEndOfIteration` shows how the base enters the `totalPages`\n   * stop rule, so emitters never re-derive it.\n   */\n  pageStart?: number;\n  /**\n   * Path to the data array the response was unwrapped on (`data`,\n   * `result.items`); absent when the response is the array itself. The\n   * property is the array in every spelling a field is typed as one:\n   * written as an array, under a nullable wrapper or an `allOf` read as\n   * its member, a `$ref` to an array component, or a JSON Pointer deeper\n   * into a component that lands on a schema typed as an array where it\n   * stands (`#/components/schemas/Holder/properties/owners`; #609), read\n   * ahead from the document as the settle will type it — so `response` is\n   * the pointed array once settled and `itemType` its items, the model the\n   * pointed schema's items built, never a copy.\n   */\n  dataPath?: string;\n  /**\n   * The description the document gives the data array property itself — the\n   * one `dataPath` names — so an emitter that documents what a list method\n   * returns can read it here instead of from the document. Like a `Field`'s\n   * `description` it is the property's own text, never the item schema's.\n   *\n   * Present only when the property declares one; absent whenever `dataPath`\n   * is, since there is no property to take it from.\n   */\n  dataDescription?: string;\n  itemType: TypeRef;\n  /**\n   * Every property the list envelope carries besides the data array, in\n   * document order: the pagination companion (`list_metadata`, `pagination`,\n   * `has_more`, …, recognized in any spelling — `pageInfo` as much as\n   * `page_info`) and any discriminant such as `object: \"list\"`. Together\n   * with `dataPath` and `itemType` this is the envelope's full shape, so an\n   * emitter can type what the endpoint returns and read the page details it\n   * needs for the next request without parsing the document itself.\n   *\n   * An inline companion object is lifted to a model. Because the same envelope\n   * recurs on every list endpoint of an API, copies that agree structurally\n   * share one model named from the property alone (`list_metadata` →\n   * `ListMetadata`, or the component schema of that name when one exists); a\n   * copy whose shape differs keeps an operation-qualified name\n   * (`ListUsersListMetadata`) so it can never change another type's shape.\n   *\n   * Absent when the response is a bare array, or when pagination was inferred\n   * from query parameters alone and no envelope was detected.\n   */\n  envelopeFields?: Field[];\n  /**\n   * Where the response says the iteration is over (see\n   * `PaginationEndOfIteration`). Detected from a recognized list envelope\n   * when it carries an obvious field — a boolean `has_more`/`hasMore`, an\n   * integer `total_pages`/`totalPages`, or an integer `total`/`total_count`,\n   * each in any spelling that separates its words (`HasMore`, `has-more`) —\n   * beside the array a nested `dataPath` names (`result.total_pages`), beside\n   * each object the path passes through on its way there, nearest the array\n   * first, at the top level, or one level down inside a pagination companion\n   * object (`pagination.totalPages`), in that order, and the same way from\n   * the body an explicit `dataPath` keeps as a wrapper — a component the\n   * response is a `$ref` to, or an inline body detection did not recognize;\n   * a `hasMore` field is preferred over a\n   * `totalPages` one, which is preferred over a count. The operation's\n   * `x-pagination` extension or its `operationHints` entry can set it\n   * explicitly, to a field of the primary response whose type fits the kind.\n   * Absent when nothing recognizable is declared; an emitter then\n   * stops on an empty page (and, for `cursor`, on a missing next cursor).\n   */\n  endOfIteration?: PaginationEndOfIteration;\n}\n\nexport type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'head' | 'options' | 'trace';\n\n/**\n * JSON Schema validation keywords declared directly on a schema, carried so an\n * emitter can document a value's limits (\"at most 100\"), check a value before\n * sending it, or keep a generated example within range. Every member is\n * optional and present only when the document declares it; a schema with no\n * validation keyword has no `constraints` at all.\n *\n * Numeric bounds use the OpenAPI 3.1 / JSON Schema 2020-12 shape, where\n * `exclusiveMinimum` / `exclusiveMaximum` are the bound itself. OpenAPI 3.0\n * spells them as booleans that make `minimum` / `maximum` exclusive; the\n * parser normalizes that form, so `{ minimum: 0, exclusiveMinimum: true }`\n * arrives as `{ exclusiveMinimum: 0 }` with no `minimum`, and a `false` is\n * dropped. Emitters read one shape whichever version produced it.\n *\n * The keywords on the field, parameter or model schema itself are carried,\n * conjoined with those of its inline `allOf` members (a single-member\n * `allOf` is unwrapped by the parser, so its limit is the value's own; a\n * `$ref` member contributes the keywords written beside the reference while\n * the referenced model keeps its own). A nullable wrapper — `oneOf`/`anyOf`\n * with a single non-null, non-`$ref` branch — conjoins that branch's\n * keywords with its own.\n *\n * The types carry them too (#545). Every `TypeRef` the parser builds from a\n * schema it types in place — a `primitive`, `literal`, `array`, `map` or\n * `union` — carries that schema's keywords as `constraints`, read exactly\n * as a field's are: the schema's own conjoined with its `allOf` members'\n * and, through a nullable wrapper, the wrapper's with its branch's (so\n * `nullable` itself carries none; its `inner` does), and for a `$ref` to\n * an array or primitive component the component's and each alias's\n * conjoined with any written beside the reference, as `Field.constraints`\n * conjoins them, and for a JSON Pointer `$ref` deeper into a component\n * (#539) the limits the pointed schema's own type carries, conjoined the\n * same way once the site is settled. A `model` or `enum` reference carries none: the model it\n * names carries its own (`Model.constraints`), and what is written around\n * such a `$ref` is the field's or parameter's alone. So a field's or\n * parameter's `constraints` equal those of its type (under its nullable\n * wrapper) whenever the type can carry them — the field keeps its own copy\n * so an emitter can read a value's limits without descending into its type\n * — and the type carries them where no field could: an array's `items`, a\n * union's variants, a map's values, a response header's or a body's type.\n * `{ type: 'array', items: { type: 'string', pattern: '^tag_' } }` has\n * `{ pattern: '^tag_' }` on its `items`; `anyOf: [{ type: 'string',\n * pattern: '^pet_' }, { type: 'string' }]` has it on its first variant and\n * none on the second, so an emitter can type the two apart\n * (`` `pet_${string}` | (string & {}) ``). A union built from a type list\n * (`type: ['string', 'integer']`) carries the schema's keywords itself and\n * its variants none: each variant is the same schema read as one of its\n * types, so the limits are read from the union for whichever type the\n * value takes.\n *\n * `oagen diff` compares them on every node that carries them, the type's\n * at every level included, and reports each keyword tightened or loosened\n * (`field-constraints-changed`, `param-constraints-changed`,\n * `header-constraints-changed`, `variant-constraints-changed`,\n * `constraintsChanged` on a model), breaking when tightened on a\n * request-facing site (#599; see docs/cli.md).\n */\nexport interface Constraints {\n  /** Inclusive lower bound (`minimum`). */\n  minimum?: number;\n  /** Inclusive upper bound (`maximum`). */\n  maximum?: number;\n  /** Exclusive lower bound as a number; the OAS 3.0 boolean form is normalized to this. */\n  exclusiveMinimum?: number;\n  /** Exclusive upper bound as a number; the OAS 3.0 boolean form is normalized to this. */\n  exclusiveMaximum?: number;\n  /** The value must be an integer multiple of this (`multipleOf`). */\n  multipleOf?: number;\n  /** Minimum string length in characters (`minLength`). */\n  minLength?: number;\n  /** Maximum string length in characters (`maxLength`). */\n  maxLength?: number;\n  /** ECMA-262 regular expression the string must match (`pattern`), verbatim from the document. */\n  pattern?: string;\n  /** Minimum number of array items (`minItems`). */\n  minItems?: number;\n  /** Maximum number of array items (`maxItems`). */\n  maxItems?: number;\n  /** Present, and `true`, when array items must be unique; `uniqueItems: false` restates the default and is dropped. */\n  uniqueItems?: boolean;\n  /** Minimum number of items matching the schema's `contains` (`minContains`). */\n  minContains?: number;\n  /** Maximum number of items matching the schema's `contains` (`maxContains`). */\n  maxContains?: number;\n  /** Minimum number of object properties (`minProperties`). */\n  minProperties?: number;\n  /** Maximum number of object properties (`maxProperties`). */\n  maxProperties?: number;\n  /** Property name → properties that must also be present when it is (`dependentRequired`). */\n  dependentRequired?: Record<string, string[]>;\n}\n\nexport interface Parameter {\n  /**\n   * The name as the document wrote it (`X-Pet-Token`); emitters apply their\n   * own casing. A parameter's identity is its location and name —\n   * `parameterKey` in `ir/parameter-key.ts`, which compares a header's name\n   * case-insensitively (RFC 9110 §5.1) and every other as written. The\n   * parser merges a path item's parameters into its operations on that\n   * identity, and the differ pairs parameters on it.\n   */\n  name: string;\n  /**\n   * The parameter schema's type. The parameter's schema is its `schema` or,\n   * for a parameter declared with a `content` map in its place, the schema\n   * of the entry read from that map: `application/json` or a `+json` media\n   * type when the entry declares a schema, else `text/plain` with or without\n   * one, each matched by media type essence (parameters and case stripped).\n   * A `text/plain` entry without a schema types the parameter as a string;\n   * a map none of whose media types is read does too, with a parser warning\n   * that names them; a `schema` beside a `content` map wins. Every field of\n   * this interface that reads \"the parameter's schema\" reads this schema,\n   * so a parameter declared either way is typed by one rule.\n   *\n   * An inline object schema (a `deepObject` query parameter, say), or an\n   * array, map, union or nullable wrapper holding one, references a model\n   * the parser creates for it, named from the service and parameter\n   * (`PetsFilter`; a header's name lower-cased first, so `X-RateLimit-Meta`\n   * and `x-ratelimit-meta` both reference `PetsXRatelimitMeta`) and\n   * qualified by location or operation when that name already belongs to\n   * another shape (see \"Response Headers\" in docs/architecture/ir-types.md);\n   * a webhook's is named under the webhook's stem. A primitive, a `$ref`, an\n   * inline enum (named the same way) or an array of either is typed as\n   * written.\n   */\n  type: TypeRef;\n  required: boolean;\n  description?: string;\n  deprecated?: boolean;\n  /**\n   * The parameter schema's `externalDocs`, when it declares a usable one;\n   * a schema that is a `$ref` falls back to the component it points at,\n   * the way `description` and `deprecated` do. A Parameter Object has no\n   * `externalDocs` of its own. Absent when neither level gives one.\n   */\n  externalDocs?: ExternalDocs;\n  default?: unknown;\n  /**\n   * A single illustrative value, resolved level by level: the parameter's own\n   * `example` (else the first entry of its `examples` map), then — for a\n   * parameter declared with `content` — the same on the Media Type Object\n   * its schema was read from, then the parameter schema's `example` (else\n   * the first of its `examples` list), then the same on the component schema\n   * its `$ref` points at. A level with neither falls through; an explicit\n   * `null` is kept. Absent when no level gives one.\n   */\n  example?: unknown;\n  /**\n   * Every example value the document gives, in document order: the\n   * parameter's `examples` map of Example Objects (each entry's `value`, with\n   * `$ref`s resolved against `components.examples`), else — for a parameter\n   * declared with `content` — the same map on the Media Type Object its\n   * schema was read from, else the JSON Schema `examples` list on the\n   * parameter's schema, else the list on the component schema its `$ref`\n   * points at. Present only when at least one value exists.\n   */\n  examples?: unknown[];\n  style?: 'form' | 'simple' | 'label' | 'matrix';\n  explode?: boolean;\n  /**\n   * The media type the parameter's value is serialized in: the `content`\n   * key its schema was read from, as written (`application/json;\n   * charset=utf-8`). Present exactly when the parameter is declared with\n   * `content` and the map is read (see `type`) — a schema-less `text/plain`\n   * entry included; absent for a `schema` parameter, and for a `content`\n   * map none of whose media types is read, whose string value is sent as\n   * written (`contentTypes` keeps that map's media types). An emitter that\n   * serializes parameters by `style` and `explode` must instead serialize\n   * such a value in this media type: JSON-encode an `application/json` or\n   * `+json` value, send a `text/plain` value as text. `oagen diff` compares\n   * it by essence — an unread map by the first of its `contentTypes` — and\n   * reports a change as a `param-content-type-changed`, breaking unless both\n   * sides are read from a JSON media type.\n   */\n  contentType?: string;\n  /**\n   * The media types the parameter's `content` map declares: its keys, in\n   * document order and exactly as written. Present when the parameter is\n   * declared with `content` and the map declares at least one media type,\n   * whether or not one of them is read (`contentType` is the one that is),\n   * as `Operation.requestBodyContentTypes` is for a request body; absent for\n   * a `schema` parameter, a `schema` beside the map included. OpenAPI allows\n   * the map one entry. For a map none of whose media types is read, this is\n   * where the media type the document declares the value in is kept: the\n   * value is typed as a string and sent as written, so an emitter has\n   * nothing to encode.\n   */\n  contentTypes?: string[];\n  /**\n   * Validation keywords from the parameter's schema, read as a field's are\n   * (`schemaConstraints`; #545 review): the schema's own conjoined with its\n   * `allOf` members' and a nullable wrapper's with its branch's, level by\n   * level, so a keyword written beside an `allOf` member that writes it too\n   * reads as the field and the type read it (`pattern: '^a'` beside `allOf:\n   * [{ pattern: 'z$' }]` is `{ pattern: '^a' }` on all three, the schema's\n   * own winning as `combineConstraints` keeps it; #587 review); for a `$ref`\n   * to a primitive or array component, or to an alias of an enum component,\n   * every entry's conjoined from the component outward, since no model\n   * carries them (the alias's own above the enum's; #560). When the schema\n   * is a `$ref` to a model or enum, the target's keywords are merged\n   * underneath the parameter's own — the per-value fallback `default` and\n   * `example` use — so a parameter can be read on its own without chasing\n   * the target. Absent when neither declares any. Equal to the limits\n   * `type` carries (under its nullable wrapper) whenever it can carry them\n   * — a JSON Pointer `$ref` deeper into a component included, once the\n   * pointer is settled (see `Field.constraints`) — while a `$ref` to a\n   * model or enum keeps the parameter's own here alone (see `Constraints`).\n   */\n  constraints?: Constraints;\n}\n\n/** Type reference — the core type system of the IR */\nexport type TypeRef = PrimitiveType | ArrayType | ModelRef | EnumRef | UnionType | NullableType | LiteralType | MapType;\n\nexport interface PrimitiveType {\n  kind: 'primitive';\n  type: 'string' | 'integer' | 'number' | 'boolean' | 'unknown';\n  format?: string;\n  /**\n   * The validation keywords of the schema this primitive was built from —\n   * `pattern`, `minLength`, `minimum`, … — read as a field's are and\n   * present only when it declares any (see `Constraints`; #545): a field's\n   * own string, an array's items, a union's variant, a map's values and a\n   * `$ref` to a primitive component (the component's own) alike, so\n   * `items: { type: 'string', pattern: '^tag_' }` is readable from `items`.\n   */\n  constraints?: Constraints;\n}\n\nexport interface ArrayType {\n  kind: 'array';\n  items: TypeRef;\n  /**\n   * The validation keywords of the array schema itself — `minItems`,\n   * `maxItems`, `uniqueItems`, … — read as a field's are and present only\n   * when it declares any (see `Constraints`; #545). The items' own keywords\n   * are on `items`, so a nested array carries each level's where it sits:\n   * `{ type: 'array', minItems: 1, items: { type: 'array', uniqueItems:\n   * true, items: { type: 'string', pattern } } }` is `{ minItems: 1 }`\n   * here, `{ uniqueItems: true }` on `items` and `{ pattern }` on its items.\n   */\n  constraints?: Constraints;\n}\n\nexport interface ModelRef {\n  kind: 'model';\n  name: string;\n}\n\nexport interface EnumRef {\n  kind: 'enum';\n  name: string;\n  values?: (string | number)[];\n}\n\nexport interface LiteralType {\n  kind: 'literal';\n  value: string | number | boolean | null;\n  /** The validation keywords written beside the `const` or single-member `enum`, read as a field's are and present only when it declares any (see `Constraints`; #545). */\n  constraints?: Constraints;\n}\n\nexport interface UnionType {\n  kind: 'union';\n  /**\n   * The variants, in the document's order: a `oneOf`/`anyOf`'s non-null\n   * variants, or — for an OAS 3.1 type list naming several types (`type:\n   * ['object', 'string']`) — one per non-null type in the list's order,\n   * each the schema read as that type alone: keeping the keywords that\n   * apply to an instance of it (`properties` for the object, `items` for\n   * an array, `format` and `pattern` for a string; `const`, `enum` and a\n   * composition for every type) and left out when the schema's\n   * `allOf`/`oneOf`/`anyOf` admits no instance of it (#616). `{ type:\n   * ['object', 'string'], allOf: [{ $ref: Owner }] }` is `Owner | string`\n   * when `Owner` declares `properties` and no `type`, and `Owner` alone —\n   * no union — when `Owner` is `type: 'object'`, which no string\n   * satisfies. Never one type twice: copies typed alike are one variant,\n   * and a lone variant is the type itself.\n   */\n  variants: TypeRef[];\n  /**\n   * When set, the union is discriminated on `property`, and `mapping` names\n   * the variant each value selects. Resolved from the same sources, in the\n   * same order, as a named union's (`Model.discriminator`), from the same\n   * reading of the variants (#568): the spec's own `discriminator.mapping`,\n   * each target as the document spelled it with a leading\n   * `#/components/schemas/` stripped — an inline union's values are not IR\n   * model names, unlike a named union's — except an entry whose target is a\n   * pointer variant's schema, settled with the variant to the model's IR\n   * name as a named union's is (#539); else, under the keyword, each\n   * variant's const on the property paired with the model it is referenced\n   * by, `{}` when any variant pins none or is unnamed; else, for a `oneOf`\n   * without the keyword, the first property the first variant pins whose\n   * values tell every variant apart. A `$ref` variant is named by its\n   * component and its const read from it — through the component's `allOf`\n   * members, a `$ref` member followed to the component it names, and\n   * through a `$ref` on the property to a component pinning one value\n   * (`Cat: { allOf: [{ $ref: CatBase }, …] }` pins what `CatBase` pins;\n   * `kind: { $ref: HamsterKind }` pins what `HamsterKind` does) — the\n   * declaration read as the type builder reads it, at every hop: a `$ref`\n   * to its component, a nullable wrapper to its one variant, an `allOf`\n   * read as one member to that member, then the `const` or one-value\n   * `enum:` written there, so `kind: { allOf: [{ const: 'cat' }] }`,\n   * `kind: { allOf: [{ $ref: HamsterKind }], description }` and a `$ref`\n   * to `RabbitKind: { allOf: [{ $ref: RabbitConst }] }` pin as `kind: {\n   * const: … }` does, in OAS 3.0 and 3.1 alike (#607) — a\n   * variant wrapping one model `$ref` through that reference, an inline\n   * object variant by the model extracted for it, so `oneOf: [{ $ref: Cat },\n   * { $ref: Dog }]` carries `{ cat: \"Cat\", dog: \"Dog\" }` on a field as it\n   * does as a component.\n   * A request body's union carries only the spec's own mapping; a body\n   * that is a `oneOf` of inline objects under the keyword, each pinning the\n   * property by the same reading, is folded into one object instead.\n   */\n  discriminator?: { property: string; mapping: Record<string, string> };\n  /** Which OAS composition keyword produced this union. Emitters can use this to\n   *  distinguish inheritance (allOf) from exclusive union (oneOf) from open union (anyOf). */\n  compositionKind?: 'allOf' | 'oneOf' | 'anyOf';\n  /**\n   * The validation keywords of the union schema itself — written beside\n   * its `oneOf`/`anyOf`, or on a type list's schema — read as a field's are\n   * and present only when it declares any (see `Constraints`; #545). Each\n   * `oneOf`/`anyOf` variant carries its own, so `anyOf: [{ type: 'string',\n   * pattern: '^pet_' }, { type: 'string' }]` has `{ pattern: '^pet_' }` on\n   * its first variant and nothing here, while `{ anyOf: [...], maxLength:\n   * 10 }` has `{ maxLength: 10 }` here. A type list's variants carry none:\n   * `{ type: ['string', 'integer'], maxLength: 20, minimum: 1 }` has both\n   * here, to read for whichever type the value takes.\n   */\n  constraints?: Constraints;\n}\n\n/**\n * A type that admits `null` beside `inner`. Carries no `constraints` of its\n * own: a nullable wrapper's validation keywords are the value's, conjoined\n * onto `inner` as a field's conjoin through the wrapper (see `Constraints`).\n */\nexport interface NullableType {\n  kind: 'nullable';\n  inner: TypeRef;\n}\n\nexport interface MapType {\n  kind: 'map';\n  valueType: TypeRef;\n  keyType?: TypeRef;\n  /**\n   * The validation keywords of the map's object schema itself —\n   * `minProperties`, `maxProperties`, `dependentRequired` — read as a\n   * field's are and present only when it declares any (see `Constraints`;\n   * #545). The values' own keywords are on `valueType`.\n   */\n  constraints?: Constraints;\n}\n\n/**\n * A generic type parameter on a model.\n * Example: `DirectoryUser<TCustomAttributes = Record<string, unknown>>`\n * → `{ name: 'TCustomAttributes', default: { kind: 'map', valueType: { kind: 'primitive', type: 'unknown' } } }`\n */\nexport interface TypeParam {\n  name: string;\n  /** Default type when the param is not specified. */\n  default?: TypeRef;\n}\n\n/**\n * Model definition (maps to an SDK model/data class). Every\n * `components/schemas` entry becomes one, except an enum (`Enum`) and an\n * alias of one, an array component and a primitive component. An alias of\n * an enum component — a bare `$ref` to it, a nullable `oneOf`/`anyOf`\n * around that `$ref`, or an `allOf` read as the reference, alone or beside\n * members that only annotate it (`PetKind: { allOf: [{ $ref: Kind }, {\n * description }] }`) — becomes no model and no enum (#560): a `$ref` to it\n * resolves to the enum (`{ kind: 'enum' }`, under `nullable` when the alias\n * or the enum admits null), what the alias declares is read by a field that\n * names it with a bare `$ref` (`Field`), and the enum keeps its own on the\n * `Enum`. An alias is only a chain that ends at a `$ref` to an enum\n * component: a component that declares its enum inside a lone `allOf`\n * member (`Kind: { allOf: [{ type: 'string', enum }], description }`) or\n * inside a nullable `oneOf`/`anyOf` wrapper (`Kind: { oneOf: [{ allOf: [{\n * type: 'string', enum }] }, { type: 'null' }] }`, `Color: { oneOf: [{\n * type: 'string', enum }, { type: 'null' }] }`; #606) is the enum `Kind`\n * or `Color` itself, nullable for the wrapper, never an alias and never a\n * model. An array component — a schema\n * that is an array and declares `items` (a nullable `oneOf`/`anyOf` around\n * one included), or an alias of one (a bare `$ref`, a nullable\n * `oneOf`/`anyOf` around a `$ref`, or an `allOf` of a `$ref` and limits)\n * — becomes no model at all: a `$ref` to it resolves to the array it\n * declares (`{ kind: 'array' }`, under `nullable` when the component admits\n * null), and what its items reference is extracted under `<Component>Item…`.\n * A primitive component — a `string`, `integer`, `number` or `boolean`\n * schema, a `const` of any value, a type list of such primitives\n * (`['string', 'integer']`) or a schema that declares no type at all (`{\n * description: 'Any value.' }`, `{}`, and the same inside an `allOf` whose\n * members each declare none: `{ allOf: [{ description }] }`), nullable in\n * any spelling, or an alias of one — becomes no model either: a `$ref` to\n * it resolves to what it declares, as the same schema written inline is\n * typed — the primitive\n * (`{ kind: 'primitive' }` with its `format`), the literal (`{ kind:\n * 'literal' }`), the union of primitives (`{ kind: 'union' }`) or `unknown`\n * (`{ kind: 'primitive', type: 'unknown' }`), under `nullable` when the\n * component admits null (#512, #569). What either component and its\n * aliases declare beside the items or the type — text, link, flags,\n * limits, `default`, `x-*` keys — is read by a field that names it with a\n * bare `$ref` (`Field`). A component that is only a `$ref` to a component\n * that becomes a model — `CatAlias: { $ref: Cat }`, with or without\n * `description`, `deprecated`, `externalDocs`, limits or `x-*` keys beside\n * the `$ref`, which are the alias's own — is a model of its own carrying\n * `Cat`'s fields, `required` and discriminator, exactly as `CatAlias: {\n * allOf: [{ $ref: Cat }] }` is, through a chain of such aliases (nothing\n * else an alias writes beside its `$ref` — `properties`, `required`, an\n * `allOf`, a union, a `discriminator` — is read, at any hop, as nothing\n * but annotations is read beside any `$ref`; only the `allOf` spelling\n * composes them) and into a component that itself composes; a `$ref` to it resolves to the alias\n * (`{ kind: 'model', name: 'CatAlias' }`), never to `Cat`, at every site,\n * and as a union variant it pins what `Cat` pins (#618: it was a model with\n * no fields). A chain of bare `$ref`s that returns to itself names nothing:\n * each such component is a model with no fields, reported once. The inline\n * schemas the parser materializes — request bodies,\n * responses, union variants, nested objects, array items, map values — are\n * models too.\n */\nexport interface Model {\n  name: string;\n  /**\n   * The schema's own `description`; for a model built from an `allOf` — a\n   * component's, or an inline merge — the wrapper layer's: the schema's\n   * own, else the first `allOf` member's that declares no type (`allOf:\n   * [{ $ref: Base }, { properties: { name } }, { description: 'An owner.'\n   * }]`; #555 review). A typing member's text stays on that member, a\n   * `$ref` member's on its component.\n   */\n  description?: string;\n  /** The schema's `externalDocs`, when it declares a usable one; for an `allOf` model, the wrapper layer's, as `description` is. */\n  externalDocs?: ExternalDocs;\n  /**\n   * Present, and `true`, when the schema this model was built from says\n   * `deprecated: true` — a component, a discriminated-union variant, or an\n   * inline request body, response or field object. Only that schema's own\n   * top-level keyword counts, read as `Field.deprecated` is: a nullable\n   * branch's flag is not read, nor an `allOf` member's that declares a type\n   * (a `$ref` member's stays on the referenced model) — one that declares\n   * none, `{ deprecated: true }` beside the members, is part of the wrapper\n   * and deprecates the model (#555 review) — and a folded `<Name>Json`\n   * model's flag does not deprecate the `<Name>` it collapses into. Absent\n   * otherwise. An inline\n   * schema that shares the name of a model the document declares has no\n   * model of its own: a deprecated schema identical to a live component\n   * keeps its flag on the `Field`, `Parameter`, `ResponseHeader` or envelope\n   * field that wrote it, and a site with no node of its own carries none — a\n   * request body or response, an array's items, a `oneOf` variant, a webhook\n   * payload variant, an error or secondary body — so deprecating only the\n   * items of `Pet.owners` beside a live component of their shape leaves no\n   * trace in the IR, as it leaves none when two inline copies fold. An\n   * inline schema named like a deprecated component shares nothing with it,\n   * whatever its flag: it keeps a model of its own, qualified by its site\n   * (`GetLegacyWidgetWidget` beside a deprecated `Widget`), which carries\n   * the schema's flag, so deprecating the schema flips this flag on that\n   * model and renames nothing (#441).\n   */\n  deprecated?: boolean;\n  fields: Field[];\n  /**\n   * The components a composed component's `allOf` names, one `{ kind:\n   * 'model' }` reference per `$ref` member, in document order, each once:\n   * `Pet: { allOf: [{ $ref: Animal }], properties: { nickname } }` has\n   * `bases: [Animal]`, `allOf: [{ $ref: Animal }, { $ref: Owned }]` has\n   * `[Animal, Owned]`. Each model names only its direct bases: with\n   * `Animal: { allOf: [{ $ref: Living }], … }`, `Animal.bases` is\n   * `[Living]` and `Pet.bases` stays `[Animal]`, since `Animal` already\n   * covers `Living`. A member names the component its reference resolves\n   * to, as the inline merge records a property's origin\n   * (`mergeAllOfMembers`): a bare alias (`Hop: { $ref: Animal }`) is read\n   * as `allOf: [{ $ref: Animal }]`, a model of its own (#618), so it is the\n   * base and `Animal` is its own base in turn, as an `allOf` component\n   * (`Hop: { allOf: [{ $ref: Animal }] }`) is; a nullable alias (`Alias: {\n   * oneOf: [{ $ref: Animal }, { type: 'null' }] }`) declares nothing of its\n   * own, so the base is `Animal`. A `$ref` member\n   * naming an enum, array or primitive component — which builds no model\n   * and contributes nothing to the fields — is no base. A `$ref` member\n   * whose component an earlier member's chain already read declares\n   * nothing more but is a direct base all the same: `allOf: [{ $ref:\n   * Animal }, { $ref: Living }]` over `Animal: { allOf: [{ $ref: Living }]\n   * }` has `[Animal, Living]`, and `[Living, Animal]` the other way\n   * round, the fields it carries naming the first member that declares\n   * them; the same `$ref` twice is one base, a component naming\n   * itself, or an alias of itself, is no base of its own, and two bases a\n   * rename sends to one name (`Bar` beside a `BarJson` folded onto it)\n   * are one, the first kept (`renameModelRefs`). A `…Json`\n   * component folded onto its base carries its bases with its fields,\n   * less one whose own chain reaches the folded model, which would close\n   * a cycle (see `collapseJsonSuffixModels`); and the parser's last pass\n   * (`settleBases`) settles both keys against the models as they end: no\n   * model's chain of bases reaches itself — a base that does, in a cyclic\n   * document or once a fold collapsed it onto a kept model of the same\n   * shape, is dropped — and a base stays a base only while every field\n   * it ends with is on the model either as the model's own declaration,\n   * which overrides the base's, or as the same field, the base's\n   * declaration and not another's (every key; the type as its final\n   * shape, an inline model built under either model as it ends and an\n   * inline enum by its values), so the model is its own fields plus its\n   * bases' and an emitter writing `extends` or an intersection types\n   * every field as `fields` does: two bases declaring one property\n   * differently (`Tagged.tag: string` beside `Kinded.tag: enum [cat,\n   * dog]`) keep at most the one whose declaration the model carries, the\n   * other's fields the model's own, and a fold that loosens a base, or a\n   * model nested under it, after the model took its fields drops that\n   * base. A field carries `inheritedFrom` only while its base stays. A `$ref` member naming a named union — flattened into\n   * the fields or dispatched, as the union's own model reads it — is a\n   * base like any other model. Present exactly when at least one base is\n   * named, on a model built from a component schema (a dispatcher\n   * included); never on a model built from an inline `allOf` — a request\n   * or response body, a field — nor on a dispatcher's variant models.\n   * `fields` stays complete, the inherited fields included, in the order\n   * the members are read, so an emitter that reads neither this key nor\n   * `Field.inheritedFrom` sees the model it always saw; one that reads\n   * them may write `Pet` as `Animal & { nickname?: string }` or `interface\n   * Pet extends Animal` (see `Field.inheritedFrom`). Provenance, not\n   * shape: two models that differ only here are one shape to the differ\n   * and to the parser's fingerprints, and `collectModelTypeRefs` leaves\n   * the references out, while `renameModelRefs` repoints them,\n   * `validateModelRefs` checks them and reachability for emission\n   * (`collectReferencedNames`) chases them, so the base of an emitted\n   * model is emitted; `collectFieldDependencies` does not list them — an\n   * emitter that writes `extends` imports the base itself.\n   */\n  bases?: TypeRef[];\n  /** Generic type parameters. Empty/undefined for non-generic models. */\n  typeParams?: TypeParam[];\n  /**\n   * Set when the model is a named union: a component schema that is itself a\n   * `oneOf`/`anyOf` with no `properties` of its own. One TypeRef per non-null\n   * variant, in document order, built exactly as an inline union's are: a\n   * `$ref` variant is a `model`/`enum` ref, an inline object variant is a ref\n   * to a model extracted for it (named from this model with the inline\n   * variant rules, never this model's own name), a primitive stays a\n   * primitive. A `type: 'null'` variant is dropped, as an inline union lifts\n   * it into a `nullable` wrapper; a Model has no such wrapper. `fields` keeps\n   * the optional merge of the inline variants' properties it always had, so\n   * an emitter that does not read `variants` sees the same model as before.\n   */\n  variants?: TypeRef[];\n  /** Which composition keyword produced `variants`. Present exactly when `variants` is. */\n  compositionKind?: 'oneOf' | 'anyOf';\n  /**\n   * When set, this model is a discriminated union — over its `variants` (a\n   * named `oneOf`/`anyOf` with a `discriminator:` keyword or a const-pinned\n   * property shared by every variant, a `$ref` variant's read from its\n   * component as `UnionType.discriminator` reads it) or over allOf+oneOf variants (where\n   * `variants` is absent and the mapping alone names them: the union a\n   * composed component carries, as an `allOf` member, beside the `allOf`\n   * or beside the component's own `properties`, whose every variant pins\n   * one property to a distinct const — a `$ref` variant's read from its\n   * component — or that the document declares a `discriminator:` for, on\n   * the union or on the component itself). Emitters should generate a\n   * dispatcher (factory) instead of a regular dataclass. The `property`\n   * field is the discriminator key (e.g. \"event\"), and `mapping` maps each\n   * discriminator value to the concrete variant model name (an IR model\n   * name, after `schemaNameTransform`): an inline variant's model, built\n   * for it and named from the const it pins (`PetCat`), or a `$ref`\n   * variant's component (`{ cat: \"Cat\", dog: \"Dog\" }`), which stands for\n   * it (#398). The const is read as `UnionType.discriminator` reads one —\n   * through a `$ref`, a nullable wrapper and an `allOf` read as one member,\n   * at every hop — for the value and the variant's name alike, so `kind:\n   * { allOf: [{ const: 'cat' }] }` dispatches to `PetCat` as `kind: {\n   * const: 'cat' }` does (#607).\n   */\n  discriminator?: {\n    property: string;\n    mapping: Record<string, string>;\n  };\n  /**\n   * Validation keywords declared on the model's own schema — for an object\n   * schema, `minProperties`, `maxProperties` and `dependentRequired`. Absent\n   * when the schema declares none.\n   */\n  constraints?: Constraints;\n  /**\n   * The `x-*` keys of the schema the model was built from (see\n   * `Extensions`), less `x-enum-descriptions` / `x-enumDescriptions`: a\n   * component's own, or the inline schema's — a request body, a response,\n   * a `oneOf` variant, an object nested in a field, array items, an\n   * `allOf` wrapper's (a member's keys stay on that member, a `$ref`\n   * member's on its component). A nullable `oneOf`/`anyOf` or single-member\n   * `allOf` wrapper the parser collapses carries its keys onto the model\n   * built from its branch, the wrapper's value winning for a key both\n   * declare, as its link rides onto it. Present only when at least one key\n   * remains. Not shape: an inline schema that differs from a model only\n   * here shares that model, which keeps its own keys.\n   */\n  extensions?: Extensions;\n}\n\nexport interface Field {\n  name: string;\n  /**\n   * Optional domain-facing name override. When set, emitters derive the\n   * domain-side identifier (in their own casing) from this instead of `name`,\n   * while serialization still uses `name` for the wire key. Lets an SDK expose\n   * a wire field under a friendlier name (e.g. `connection_type` → `type`)\n   * without changing the API contract. Set via the `fieldHints` config and\n   * honored by any emitter that reads it.\n   */\n  domainName?: string;\n  type: TypeRef;\n  required: boolean;\n  /**\n   * The direct base — an entry of `Model.bases` — this field is taken from\n   * unchanged, as a `{ kind: 'model' }` reference; absent when the model\n   * declares the field itself, or when a declaration of its own — written\n   * beside the `allOf` or in an inline member, before or after the `$ref`\n   * — changes what the base declares, by any key: its type, its\n   * `description`, a `nullable` or `deprecated` flip, or its `required`\n   * (the model requiring a field the base leaves optional). A declaration\n   * the merge sets aside — a later typing one, which the first typing\n   * declaration outranks (`declareProperty`) — changes nothing, and the\n   * field stays the base's. `Pet: { allOf: [{ $ref: Animal }], required:\n   * [name], properties: { name: { type: 'string', enum: [rex, max] },\n   * nickname } }` over `Animal { name?, species? }` carries `name` and\n   * `nickname` without it and `species` with `inheritedFrom: Animal`, so\n   * an emitter can write `Pet` as `Animal & { name: PetName; nickname?:\n   * string }`; `Pet: { allOf: [{ $ref: Animal }], required: [species] }`\n   * carries `species` without it. A field a base inherits in turn names\n   * the direct base: with `Animal: { allOf: [{ $ref: Living }] }`,\n   * `Living`'s `born` is on `Pet` with `inheritedFrom: Animal`. A field\n   * a base's flattened `oneOf`/`anyOf` variants declare is the model's own\n   * (optional on both, with no origin), as a field the model's own\n   * variants declare is. Unchanged means as the document declares it: the\n   * field's `type` is still built under this model's name, so an inline\n   * object `Animal.meta` declares is `AnimalMeta` on `Animal` and\n   * `PetMeta` on `Pet` — the same shape — with `inheritedFrom: Animal`.\n   * Only on a field of a model that carries `bases`. Provenance, not\n   * shape: two fields that differ only here are one shape to the differ\n   * and to the fingerprints; `renameModelRefs` repoints it and\n   * `validateModelRefs` checks it.\n   */\n  inheritedFrom?: TypeRef;\n  /**\n   * The field schema's own `description`; for a bare `$ref` to an array or\n   * primitive component — which names no model to carry the component's\n   * text — the nearest the reference passes on its way to the array or\n   * primitive (an alias's own, else the component's), as `example` falls\n   * back to it. A `$ref` to a model, named union or enum leaves the text on\n   * it; a bare `$ref` to an alias of an enum component reads the nearest\n   * alias's own — an `allOf` member of its that declares no type included —\n   * and leaves the enum's on the enum (#560). Under a wrapper — a nullable\n   * one, an `allOf` read as the reference\n   * (`{ allOf: [{ $ref: PetId }, { description }] }`) — the field documents\n   * itself: the wrapper's text or a member's written beside the `$ref`,\n   * never the component's; the same holds for every annotation, flag, default\n   * and key below, while `constraints` conjoin through a wrapper. An `allOf`\n   * member that declares no type — `{ description }`, `{ deprecated: true }`,\n   * `{ readOnly: true }`, `{ maxLength: 3 }`, `{ 'x-internal': true }` — is\n   * part of the field's schema, whatever the other members: beside a `$ref`\n   * (`{ allOf: [{ $ref: Kind }, { description }] }` is `Kind` with that\n   * text on the field), beside the one member that types the schema\n   * (`{ allOf: [{ type: 'string', enum: [...] }, { description }] }` is the\n   * enum, read as `{ allOf: [{ type: 'string', enum: [...] }], description }`\n   * is; #555) or beside a merge — the schema's own value first, then the\n   * first such member's, for every keyword below.\n   */\n  description?: string;\n  /**\n   * The field schema's own `externalDocs`, when it declares a usable one —\n   * read like `description`: for a `$ref` with an `externalDocs` sibling\n   * (legal in OAS 3.1), the sibling's link, while the referenced model keeps\n   * its own; a bare `$ref` yields none, unless it names an array or\n   * primitive component, or an alias of an enum component, whose link the\n   * field then carries. Absent otherwise. Documentation, not shape: two\n   * fields that differ only here are one shape.\n   */\n  externalDocs?: ExternalDocs;\n  /**\n   * `true` when the field schema says `readOnly: true` — itself, or an\n   * `allOf` member of its that declares no type (`allOf: [{ $ref: Kind },\n   * { readOnly: true }]`; #555) — or when a bare `$ref` names an array or\n   * primitive component that says so, or an alias of it, or of an enum\n   * component, on the way (see `description`). `writeOnly` is read the same\n   * way.\n   */\n  readOnly?: boolean;\n  writeOnly?: boolean;\n  /**\n   * Present, and `true`, when the field schema says `deprecated: true` — a\n   * keyword written beside a `$ref` included, and an `allOf` member that\n   * declares no type (`allOf: [{ $ref: Kind }, { deprecated: true }]`; #555)\n   * — or when a bare `$ref` names an array or primitive component that says\n   * so, or an alias of it, or of an enum component (#560), on the way, since\n   * no model carries that component's or alias's flag. The flag of a model,\n   * named union or enum a `$ref` names stays on it.\n   */\n  deprecated?: boolean;\n  /**\n   * The field schema's own `default`, an explicit `null` included; for a\n   * bare `$ref` to an array or primitive component that declares none, or to\n   * an alias of an enum component, the nearest the reference passes (see\n   * `description`).\n   */\n  default?: unknown;\n  /**\n   * A single illustrative value. The field schema's `example` when present,\n   * otherwise the first entry of its `examples`; when the schema is a `$ref`\n   * with neither, the same taken from the component it points at — for an\n   * array or primitive component, from the nearest level the reference\n   * passes on its way to the array or primitive (an alias's own, else the\n   * component's), as `description` is read; for an alias of an enum\n   * component, the aliases' own first, then the enum's. An explicit `null`\n   * is kept. Absent when no level gives one.\n   */\n  example?: unknown;\n  /**\n   * Every example value the schema gives, in document order, from the JSON\n   * Schema `examples` list (OAS 3.1 deprecates `example` in its favour) —\n   * on the field schema, else on the component its `$ref` points at, an\n   * array or primitive component's read like `example`: the nearest\n   * non-empty list the reference passes on its way to the array, primitive\n   * or enum. Present only when the list has at least one entry.\n   */\n  examples?: unknown[];\n  /**\n   * Validation keywords declared on the field's schema, including any\n   * written beside a `$ref` (OpenAPI 3.1 allows siblings). A `$ref` to a\n   * model, named union or enum adds none, since the referenced node carries\n   * its own limits; a `$ref` to an array or primitive component, which\n   * names no model, conjoins the component's limits and its aliases' with\n   * the field's own (`{ $ref: Tags, maxItems: 3 }` beside `Tags`'s\n   * `minItems: 1, maxItems: 5` is `{ minItems: 1, maxItems: 3 }`), and one\n   * to an alias of an enum component conjoins the aliases' own, the enum's\n   * staying on the enum (#560) — bare\n   * or under a wrapper the type builder reads through, since the wire\n   * enforces them either way and nothing else carries them: `{ allOf: [{\n   * $ref: PetId }, { description }] }` beside `PetId`'s `pattern` carries\n   * that `pattern`, as `{ allOf: [{ $ref: PetId }] }` and `oneOf: [{ $ref:\n   * PetId }, { type: 'null' }]` do. A JSON Pointer `$ref` deeper into a\n   * component (#539) conjoins the same way with the limits the schema it\n   * lands on carries on its own type, once the pointer is settled\n   * (`resolveSchemaPointers`; #545 review): `{ $ref: '#/components/schemas/\n   * Owner/properties/code', maxLength: 3 }` to `{ type: 'string', pattern:\n   * '^own_', maxLength: 8 }` is `{ maxLength: 3, pattern: '^own_' }`, and\n   * the bare pointer `{ maxLength: 8, pattern: '^own_' }`; a pointer to a\n   * property typed as a model or enum adds none, as a `$ref` to a model\n   * does. Absent when no level declares any. Equal to the limits `type`\n   * carries (under its nullable wrapper) whenever it can carry them — a\n   * `$ref` to a model, named union or enum keeps the field's own here\n   * alone — while the limits of an array's items, a union's variants or a\n   * map's values are on those types only (see `Constraints`; #545).\n   */\n  constraints?: Constraints;\n  /**\n   * The field schema's own `x-*` keys (see `Extensions`), less\n   * `x-enum-descriptions` / `x-enumDescriptions`, read like `constraints`:\n   * keys written beside a `$ref` (legal in OAS 3.1) are the field's, a bare\n   * `$ref` yields none — the referenced model, union or enum carries its\n   * own — unless it names an array or primitive component, or an alias of\n   * an enum component, whose keys and its aliases' the field then carries\n   * under its own, the field's winning per key, as it carries that\n   * component's `description`. A property\n   * several `allOf` members always declare is typed by the first typing\n   * declaration, keys included (a typeless one fills in what it leaves\n   * unset); a property only variants declare carries exactly the keys\n   * every declaration as written agrees on, value for value, whether or\n   * not the declarations share one shape — in an inline `allOf` and under\n   * a component (a bare `oneOf` component, a union member of a component\n   * `allOf`) alike. Present only when at least one\n   * key remains. Not shape: two fields that differ only here are one shape.\n   */\n  extensions?: Extensions;\n}\n\n/** Enum definition */\nexport interface Enum {\n  name: string;\n  /**\n   * The enum schema's own `description`: a component enum's, as\n   * `Model.description` is a component model's — the wrapper layer's over\n   * the member's when the component declares its members inside an\n   * `allOf` read as its one typing member (`Kind: { allOf: [{ type:\n   * 'string', enum }], description }`), or the wrapper's over the branch's\n   * when it declares them inside a nullable `oneOf`/`anyOf` wrapper\n   * (`Kind: { oneOf: [{ allOf: [{ type: 'string', enum }, { description\n   * }] }, { type: 'null' }] }`; #606), as its link, `deprecated`,\n   * `default` and keys are read (`enumComponentDeclaration`) — or — for an\n   * enum lifted\n   * from an inline schema on a property, parameter, response header,\n   * request or response body (primary, secondary-media-type, error or\n   * fallback) or webhook parameter or payload, including array items,\n   * `oneOf` variants and a `oneOf` of string consts collapsed into one enum\n   * — the text of the schema that declares its members, read as its\n   * `externalDocs` is: a nullable `oneOf`/`anyOf` or single-member `allOf`\n   * wrapper the parser collapses gives its own text when it has content,\n   * and the branch's own counts only when the wrapper has none. A\n   * Parameter or Header Object's `description` is that parameter's or\n   * header's, never the enum's. Present only when the text has\n   * non-whitespace content, kept verbatim. When several inline schemas lift\n   * to one name, the first lifted gives the text, as it gives the values and\n   * the link, so the key is absent when that schema declared none even if a\n   * later one does. Documentation, not shape: the differ does not report a\n   * change to it, and two inline enums that differ only in it are one enum.\n   */\n  description?: string;\n  values: EnumValue[];\n  /** Spec-level default value (the value of `default:` on the schema). Optional. */\n  default?: string | number;\n  /**\n   * The enum schema's `externalDocs`, when it declares a usable one: a\n   * component enum's own, or — for an enum lifted from an inline schema on a\n   * property, parameter or response header — that schema's. A nullable\n   * wrapper the parser collapses carries its link onto the enum, as it does\n   * onto a model; when several inline schemas lift to one name, the first\n   * lifted gives the link, as it gives the values.\n   */\n  externalDocs?: ExternalDocs;\n  /** Present, and `true`, when the component enum schema says `deprecated: true`; absent otherwise. */\n  deprecated?: boolean;\n  /**\n   * The `x-*` keys of the schema that declares the members (see\n   * `Extensions`), less `x-enum-descriptions` / `x-enumDescriptions`, which\n   * the values' `description` is read from: a component enum's own, or —\n   * for an enum lifted from an inline schema — that schema's, read as its\n   * `description` and `externalDocs` are: a nullable `oneOf`/`anyOf` or\n   * single-member `allOf` wrapper the parser collapses carries its keys\n   * onto the branch, the wrapper's value winning for a key both declare.\n   * The field the inline schema types carries the same keys when the enum\n   * schema is the field's own schema; under such a collapsed wrapper the\n   * field carries the wrapper's keys alone (see `Field.extensions`), and\n   * the branch's stay on the enum. When several inline schemas lift to one\n   * name, the first lifted gives the keys, as it gives the values. Present\n   * only when at least one key remains. Not shape: two inline enums that\n   * differ only here are one enum.\n   */\n  extensions?: Extensions;\n}\n\n/**\n * One member of an enum. An enum schema is an `enum:` list or a\n * `oneOf`/`anyOf` whose every non-null variant is a string `const` schema\n * (the OAS 3.1 spelling that documents values one by one); both give one\n * `EnumValue` per member, in document order.\n */\nexport interface EnumValue {\n  /** UPPER_SNAKE_CASE form of `value`. */\n  name: string;\n  /** The value as written; a number stays a number. */\n  value: string | number;\n  /**\n   * The value's own documentation: a `const` member's `description`, else\n   * the entry for the value in the enum schema's `x-enum-descriptions` /\n   * `x-enumDescriptions` extension. Present only when that text has\n   * non-whitespace content; absent otherwise.\n   */\n  description?: string;\n  /**\n   * Present, and `true`, when the value's `const` member says\n   * `deprecated: true`; absent otherwise. An `enum:` list has no per-value\n   * keyword, so its values never carry it.\n   */\n  deprecated?: boolean;\n}\n\n/**\n * Exhaustive check helper for TypeRef switches.\n * If a new kind is added to TypeRef, any switch that doesn't handle it\n * will fail to compile because `never` won't accept the unhandled variant.\n *\n * Usage:\n *   switch (ref.kind) {\n *     case 'primitive': ...\n *     case 'array': ...\n *     // If you forget 'literal', TypeScript errors here:\n *     default: assertNever(ref);\n *   }\n */\nexport function assertNever(x: never): never {\n  // Inline to avoid importing from ../errors.js (ir/ is layer 0, must not import upward)\n  const kind = (x as TypeRef).kind;\n  const err = new Error(\n    `Unexpected TypeRef kind: ${kind}\\nHint: If you added a new TypeRef variant, handle it in every switch/case that calls assertNever.`,\n  );\n  err.name = 'InternalError';\n  throw err;\n}\n\n/**\n * The validation keywords `ref` carries (see `Constraints`; #545): its\n * `constraints` for a `primitive`, `literal`, `array`, `map` or `union`,\n * `undefined` for a `model` or `enum` reference, which carries none, and\n * for a `nullable` wrapper, whose `inner` carries the value's. The one\n * read for every kind, so a reader need not know which kinds carry them.\n */\nexport function typeRefConstraints(ref: TypeRef): Constraints | undefined {\n  switch (ref.kind) {\n    case 'primitive':\n    case 'literal':\n    case 'array':\n    case 'map':\n    case 'union':\n      return ref.constraints;\n    case 'model':\n    case 'enum':\n    case 'nullable':\n      return undefined;\n  }\n  return assertNever(ref);\n}\n\n/**\n * Generic depth-first walker for TypeRef trees.\n * Handles recursion into array/nullable/union/map children and provides\n * an exhaustive `assertNever` check so callers don't need to repeat the\n * switch boilerplate.  Supply callbacks only for the leaf kinds you care about.\n */\nexport function walkTypeRef(\n  ref: TypeRef,\n  visitor: {\n    model?: (ref: ModelRef) => void;\n    enum?: (ref: EnumRef) => void;\n    primitive?: (ref: PrimitiveType) => void;\n    literal?: (ref: LiteralType) => void;\n  },\n): void {\n  switch (ref.kind) {\n    case 'model':\n      visitor.model?.(ref);\n      break;\n    case 'enum':\n      visitor.enum?.(ref);\n      break;\n    case 'array':\n      walkTypeRef(ref.items, visitor);\n      break;\n    case 'nullable':\n      walkTypeRef(ref.inner, visitor);\n      break;\n    case 'union':\n      for (const v of ref.variants) walkTypeRef(v, visitor);\n      break;\n    case 'map':\n      if (ref.keyType) walkTypeRef(ref.keyType, visitor);\n      walkTypeRef(ref.valueType, visitor);\n      break;\n    case 'literal':\n      visitor.literal?.(ref);\n      break;\n    case 'primitive':\n      visitor.primitive?.(ref);\n      break;\n    default:\n      assertNever(ref);\n  }\n}\n\n/**\n * Generic depth-first mapper for TypeRef trees.\n * Like walkTypeRef but returns a transformed value instead of void.\n * Handles recursion into array/nullable/union/map children, passing\n * already-mapped child values to the parent callback.\n */\nexport function mapTypeRef<T>(\n  ref: TypeRef,\n  mapper: {\n    primitive: (ref: PrimitiveType) => T;\n    array: (ref: ArrayType, mappedItems: T) => T;\n    model: (ref: ModelRef) => T;\n    enum: (ref: EnumRef) => T;\n    union: (ref: UnionType, mappedVariants: T[]) => T;\n    nullable: (ref: NullableType, mappedInner: T) => T;\n    literal: (ref: LiteralType) => T;\n    map: (ref: MapType, mappedValue: T, mappedKey?: T) => T;\n  },\n): T {\n  switch (ref.kind) {\n    case 'primitive':\n      return mapper.primitive(ref);\n    case 'array':\n      return mapper.array(ref, mapTypeRef(ref.items, mapper));\n    case 'model':\n      return mapper.model(ref);\n    case 'enum':\n      return mapper.enum(ref);\n    case 'union':\n      return mapper.union(\n        ref,\n        ref.variants.map((v) => mapTypeRef(v, mapper)),\n      );\n    case 'nullable':\n      return mapper.nullable(ref, mapTypeRef(ref.inner, mapper));\n    case 'literal':\n      return mapper.literal(ref);\n    case 'map':\n      return mapper.map(\n        ref,\n        mapTypeRef(ref.valueType, mapper),\n        ref.keyType ? mapTypeRef(ref.keyType, mapper) : undefined,\n      );\n    default:\n      return assertNever(ref);\n  }\n}\n\n// --- IR traversal utilities ---\n\n/**\n * Every TypeRef a model owns: each field's type, then each union variant\n * (`Model.variants`). Every pass that walks a model's type refs (reachability,\n * service assignment, ref rewriting and validation, dependency collection,\n * inline-enum promotion, fingerprinting) goes through this so a type reached\n * only through a named union's variant is treated the way a field type is.\n * A model's `bases` and its fields' `inheritedFrom` name the models it is\n * built on, not types it owns — provenance, not shape (#591) — and are left\n * out, so the fingerprints and the differ read a model with and without\n * them as one shape; `renameModelRefs`, `validateModelRefs` and\n * reachability for emission (`collectReferencedNames`) reach them on their\n * own.\n */\nexport function collectModelTypeRefs(model: Model): TypeRef[] {\n  return [...model.fields.map((field) => field.type), ...(model.variants ?? [])];\n}\n\n/**\n * Rename the models a type refers to, in place: every `model` ref under\n * `ref` — at any depth of array, map, nullable and union wrapper — that\n * `renames` maps and `admit` accepts is pointed at the new name, and each\n * `discriminator.mapping` entry of a union follows the variant it belongs\n * to (`mappingEntriesByVariant`), so a mapping never keeps naming a model\n * that was renamed away and never moves off a variant that stayed: beside a\n * `$ref` to `Comp` (`kind: legacy`) an inline variant titled `Comp`\n * (`kind: new`) renamed to `ThingComp` leaves `{ legacy: 'Comp', new:\n * 'ThingComp' }`. Each reference is looked up once, so `{ A → B, B → C }`\n * moves `A` to `B`, never on to `C`. Without an `admit` every reference is\n * renamed, and so is every mapping target `renames` maps, those naming no\n * variant included: a document's own mapping may send a value to a model\n * that is not among the variants, and a fold that removes that model\n * (`FooJson` into `Foo`) must not leave the mapping naming it. Under an\n * `admit` — the parser's merge passes pass one that tells a reference minted\n * for an inline model from an explicit `$ref` to a same-named component —\n * only an entry a moved variant owns follows it, since a target has no\n * identity to admit. Returns whether any reference moved. Every rename site\n * — the merge passes, the shape registry,\n * the list-envelope pass, the Json fold — goes through this or\n * `renameModelRefs`, so every reference kind a rename can touch is rewritten\n * alike: a field's type, a union's variants and mapping, an operation's\n * bodies, pagination types, headers and secondary bodies, a webhook's\n * payload and parameters.\n */\nexport function renameTypeRefModels(\n  ref: TypeRef,\n  renames: ReadonlyMap<string, string>,\n  admit?: (ref: ModelRef) => boolean,\n): boolean {\n  switch (ref.kind) {\n    case 'model': {\n      const renamed = renames.get(ref.name);\n      if (renamed === undefined || (admit && !admit(ref))) return false;\n      ref.name = renamed;\n      return true;\n    }\n    case 'array':\n      return renameTypeRefModels(ref.items, renames, admit);\n    case 'nullable':\n      return renameTypeRefModels(ref.inner, renames, admit);\n    case 'map': {\n      const key = ref.keyType ? renameTypeRefModels(ref.keyType, renames, admit) : false;\n      const value = renameTypeRefModels(ref.valueType, renames, admit);\n      return key || value;\n    }\n    case 'union':\n      return renameVariants(ref.variants, ref.discriminator?.mapping, renames, admit);\n    case 'enum':\n    case 'literal':\n    case 'primitive':\n      return false;\n    default:\n      return assertNever(ref);\n  }\n}\n\n/**\n * Rename the models `variants` refer to, each `mapping` entry following the\n * variant it belongs to. Returns whether any variant moved.\n */\nfunction renameVariants(\n  variants: TypeRef[],\n  mapping: Record<string, string> | undefined,\n  renames: ReadonlyMap<string, string>,\n  admit: ((ref: ModelRef) => boolean) | undefined,\n): boolean {\n  // By name, every entry follows its target; under a filter, only an entry a\n  // moved variant owns.\n  const owned = mapping && admit ? mappingEntriesByVariant(variants, mapping) : undefined;\n  let moved = false;\n  variants.forEach((variant, index) => {\n    if (!renameTypeRefModels(variant, renames, admit)) return;\n    moved = true;\n    const model = variantModel(variant);\n    if (owned && model) for (const value of owned.get(index) ?? []) mapping![value] = model.name;\n  });\n  if (mapping && !admit) renameMappingTargets(mapping, renames);\n  return moved;\n}\n\n/** The model a variant names — directly, or under its nullable wrapper — which its mapping entry targets; none for any other variant. */\nfunction variantModel(variant: TypeRef): ModelRef | undefined {\n  if (variant.kind === 'nullable') return variantModel(variant.inner);\n  return variant.kind === 'model' ? variant : undefined;\n}\n\n/**\n * Which variant each `mapping` entry belongs to, by the variants' positions:\n * a name one variant carries owns every entry naming it (a document's own\n * mapping may send several values to one schema); a name several variants\n * carry — a `$ref` to a component beside an inline variant titled like it —\n * hands the j-th entry naming it to the j-th such variant, since the parser\n * derives one entry per discriminated variant in variant order. A variant's\n * model is read through its nullable wrapper. An entry naming no variant\n * belongs to none and stays as written.\n */\nfunction mappingEntriesByVariant(variants: readonly TypeRef[], mapping: Record<string, string>): Map<number, string[]> {\n  const indexesByName = new Map<string, number[]>();\n  variants.forEach((variant, index) => {\n    const model = variantModel(variant);\n    if (model) indexesByName.set(model.name, [...(indexesByName.get(model.name) ?? []), index]);\n  });\n  const owned = new Map<number, string[]>();\n  const handed = new Map<string, number>();\n  for (const [value, target] of Object.entries(mapping)) {\n    const indexes = indexesByName.get(target);\n    if (!indexes) continue;\n    let index = indexes[0]!;\n    if (indexes.length > 1) {\n      const j = handed.get(target) ?? 0;\n      handed.set(target, j + 1);\n      if (j >= indexes.length) continue;\n      index = indexes[j]!;\n    }\n    owned.set(index, [...(owned.get(index) ?? []), value]);\n  }\n  return owned;\n}\n\n/** Point every target of `mapping` that `renames` maps at the new name: a rename by name, which reaches an entry naming no variant too. */\nfunction renameMappingTargets(mapping: Record<string, string>, renames: ReadonlyMap<string, string>): void {\n  for (const [value, target] of Object.entries(mapping)) {\n    const renamed = renames.get(target);\n    if (renamed !== undefined) mapping[value] = renamed;\n  }\n}\n\n/**\n * Rename the models a model refers to: every `model` ref in its fields' types\n * and its union variants that `renames` maps and `admit` accepts is pointed\n * at the new name (`renameTypeRefModels`, so a union's mapping inside a field\n * follows its variant) — its `bases` and its fields' `inheritedFrom` with\n * them, so a base renamed or folded away is named by its new name, and two\n * bases the rename sends to one name (`Bar` beside a `BarJson` folded onto\n * it) are one base, the first kept, so `bases` names each once (#591,\n * Greptile) — and the model's own `discriminator.mapping` is\n * rewritten with it: without an `admit`, every target `renames` maps, by\n * name — whether it names a variant, a model outside the variants a\n * document's own mapping sends a value to, or a member an allOf+oneOf\n * dispatcher holds in the mapping alone — so a fold that removes a model\n * never leaves a dispatcher naming it; under an `admit`, only an entry a\n * moved variant owns (`mappingEntriesByVariant`), since a target has no\n * identity to admit. Each reference is looked up once, so a map `{ A → B, B → C }`\n * moves `A` to `B`, never on to `C`. The model's own `name` is left to the\n * caller. Every rename and fold site goes through this, so a dispatcher's\n * mapping can never keep naming a model that was renamed away while its\n * variants moved on. Returns whether any reference moved.\n */\nexport function renameModelRefs(\n  model: Model,\n  renames: ReadonlyMap<string, string>,\n  admit?: (ref: ModelRef) => boolean,\n): boolean {\n  let moved = false;\n  for (const field of model.fields) {\n    if (renameTypeRefModels(field.type, renames, admit)) moved = true;\n    if (field.inheritedFrom && renameTypeRefModels(field.inheritedFrom, renames, admit)) moved = true;\n  }\n  if (model.bases) {\n    for (const base of model.bases) if (renameTypeRefModels(base, renames, admit)) moved = true;\n    const named = new Set<string>();\n    const distinct = model.bases.filter((base) => {\n      if (base.kind !== 'model') return true;\n      if (named.has(base.name)) return false;\n      named.add(base.name);\n      return true;\n    });\n    if (distinct.length !== model.bases.length) model.bases.splice(0, model.bases.length, ...distinct);\n  }\n  const mapping = model.discriminator?.mapping;\n  if (model.variants) {\n    if (renameVariants(model.variants, mapping, renames, admit)) moved = true;\n  } else if (mapping && !admit) {\n    renameMappingTargets(mapping, renames);\n  }\n  return moved;\n}\n\n/**\n * Collect all model names referenced (directly or transitively) by a TypeRef.\n */\nexport function collectModelRefs(ref: TypeRef): string[] {\n  const names: string[] = [];\n  walkTypeRef(ref, { model: (r) => names.push(r.name) });\n  return names;\n}\n\n/**\n * Collect all enum names referenced by a TypeRef.\n */\nexport function collectEnumRefs(ref: TypeRef): string[] {\n  const names: string[] = [];\n  walkTypeRef(ref, { enum: (r) => names.push(r.name) });\n  return names;\n}\n\n/**\n * Collect all TypeRef-referenced model and enum names from a model's fields\n * and, for a named union, its variants.\n * Returns { models, enums } sets for generating import statements.\n */\nexport function collectFieldDependencies(model: Model): {\n  models: Set<string>;\n  enums: Set<string>;\n} {\n  const models = new Set<string>();\n  const enums = new Set<string>();\n\n  for (const ref of collectModelTypeRefs(model)) {\n    for (const name of collectModelRefs(ref)) {\n      if (name !== model.name) models.add(name);\n    }\n    for (const name of collectEnumRefs(ref)) {\n      enums.add(name);\n    }\n  }\n\n  return { models, enums };\n}\n\n/**\n * Assign each model to the service that first references it.\n * Models referenced by multiple services are assigned to the first.\n * Models not referenced by any service are unassigned (absent from the map).\n *\n * @param hints - Optional pin overrides keyed by IR model name → IR service\n *   name. Applied after the natural assignment loop. A hint only pins a model\n *   present in THIS `models` slice; the target service is resolved by name\n *   downstream, so a hint pointing at a service outside `services` still lands\n *   the model in the right directory. Callers may pass a PARTIAL slice (e.g.\n *   discriminated-union planning, per-service barrels, or a `--services`-scoped\n *   run), so this function never rejects a hint — typo validation lives in\n *   {@link validateModelHints}, which runs once against the full spec.\n */\nexport function assignModelsToServices(\n  models: Model[],\n  services: Service[],\n  hints?: Record<string, string>,\n): Map<string, string> {\n  const modelToService = new Map<string, string>();\n  const modelNames = new Set(models.map((m) => m.name));\n\n  for (const service of services) {\n    const referencedModels = new Set<string>();\n\n    for (const op of service.operations) {\n      if (op.requestBody) {\n        for (const name of collectModelRefs(op.requestBody)) {\n          referencedModels.add(name);\n        }\n      }\n      for (const name of collectModelRefs(op.response)) {\n        referencedModels.add(name);\n      }\n      for (const param of [\n        ...op.pathParams,\n        ...op.queryParams,\n        ...(op.bodyOwnedQueryParams ?? []),\n        ...op.headerParams,\n        ...(op.cookieParams ?? []),\n      ]) {\n        for (const name of collectModelRefs(param.type)) {\n          referencedModels.add(name);\n        }\n      }\n      if (op.pagination) {\n        for (const name of collectModelRefs(op.pagination.itemType)) {\n          referencedModels.add(name);\n        }\n        for (const field of op.pagination.envelopeFields ?? []) {\n          for (const name of collectModelRefs(field.type)) {\n            referencedModels.add(name);\n          }\n        }\n      }\n      for (const error of op.errors) {\n        if (!error.type) continue;\n        for (const name of collectModelRefs(error.type)) {\n          referencedModels.add(name);\n        }\n      }\n      for (const header of collectResponseHeaders(op)) {\n        for (const name of collectModelRefs(header.type)) {\n          referencedModels.add(name);\n        }\n      }\n      for (const { type } of collectResponseBodyTypes(op)) {\n        for (const name of collectModelRefs(type)) {\n          referencedModels.add(name);\n        }\n      }\n      for (const { type } of collectRequestBodyTypes(op)) {\n        for (const name of collectModelRefs(type)) {\n          referencedModels.add(name);\n        }\n      }\n      // A callback's payload and parameters are the operation's too: the\n      // request is tied to it, so its models land in the operation's\n      // service as the operation's own do (#382). A webhook's callbacks\n      // belong to no service, as the webhook does.\n      for (const callback of op.callbacks ?? []) {\n        for (const ref of collectWebhookTypeRefs(callback)) {\n          for (const name of collectModelRefs(ref)) {\n            referencedModels.add(name);\n          }\n        }\n      }\n    }\n\n    // Transitively collect models referenced by the directly-referenced models\n    // (through their fields and, for a named union, its variants)\n    const toVisit = [...referencedModels];\n    while (toVisit.length > 0) {\n      const name = toVisit.pop()!;\n      const model = models.find((m) => m.name === name);\n      if (!model) continue;\n      for (const typeRef of collectModelTypeRefs(model)) {\n        for (const ref of collectModelRefs(typeRef)) {\n          if (!referencedModels.has(ref) && modelNames.has(ref)) {\n            referencedModels.add(ref);\n            toVisit.push(ref);\n          }\n        }\n      }\n    }\n\n    for (const name of referencedModels) {\n      if (!modelToService.has(name)) {\n        modelToService.set(name, service.name);\n      }\n    }\n  }\n\n  if (hints) {\n    for (const [modelName, serviceName] of Object.entries(hints)) {\n      // Only pin models present in THIS slice; an out-of-slice hint is applied\n      // where its own slice is processed. The target service resolves by name\n      // downstream, so it need not appear in this slice's `services`. Genuine\n      // typos are caught up front by validateModelHints against the full spec.\n      if (!modelNames.has(modelName)) continue;\n      modelToService.set(modelName, serviceName);\n    }\n  }\n\n  return modelToService;\n}\n\n/**\n * Validate model-placement hints against the FULL spec. Run once at the start of\n * generation — where the complete model/service universe is known — so typos in\n * `modelHints` fail loud even though {@link assignModelsToServices} is\n * intentionally lenient about the partial slices it may be handed.\n */\nexport function validateModelHints(models: Model[], services: Service[], hints: Record<string, string>): void {\n  const modelNames = new Set(models.map((m) => m.name));\n  const serviceNames = new Set(services.map((s) => s.name));\n  for (const [modelName, serviceName] of Object.entries(hints)) {\n    if (!modelNames.has(modelName)) {\n      const err = new Error(\n        `modelHints: unknown model \"${modelName}\". Hint keys must match an IR model name (post-cleanSchemaName/schemaNameTransform).`,\n      );\n      err.name = 'ConfigError';\n      throw err;\n    }\n    if (!serviceNames.has(serviceName)) {\n      const err = new Error(\n        `modelHints: unknown service \"${serviceName}\" for model \"${modelName}\". Hint values must match an IR service name (PascalCase, derived from the operation's first tag).`,\n      );\n      err.name = 'ConfigError';\n      throw err;\n    }\n  }\n}\n\n/**\n * Collect all model names referenced as request bodies across all services:\n * each operation's `requestBody`, and the body of every other media type it\n * declares (`collectRequestBodyTypes`).\n */\nexport function collectRequestBodyModels(services: Service[]): Set<string> {\n  const result = new Set<string>();\n  for (const service of services) {\n    for (const op of service.operations) {\n      if (op.requestBody) {\n        for (const name of collectModelRefs(op.requestBody)) {\n          result.add(name);\n        }\n      }\n      for (const { type } of collectRequestBodyTypes(op)) {\n        for (const name of collectModelRefs(type)) {\n          result.add(name);\n        }\n      }\n    }\n  }\n  return result;\n}\n\n/**\n * Every response header an operation declares: the primary response's, each\n * alternate success entry's, and each error entry's. The primary list is the\n * same array as its `successResponses` entry when both exist, so it is yielded\n * once. Every pass that walks an operation's type refs (reachability, model\n * assignment, ref rewriting and validation, direction, compat filtering, enum\n * collection) goes through this so a type reached only through a header is\n * treated the way a body or parameter type is.\n */\nexport function collectResponseHeaders(op: Operation): ResponseHeader[] {\n  const result: ResponseHeader[] = [];\n  const seen = new Set<ResponseHeader[]>();\n  const lists = [\n    op.responseHeaders,\n    ...(op.successResponses ?? []).map((r) => r.headers),\n    ...op.errors.map((e) => e.headers),\n    op.defaultResponse?.headers,\n    ...(op.rangeResponses ?? []).map((r) => r.headers),\n  ];\n  for (const list of lists) {\n    if (!list || seen.has(list)) continue;\n    seen.add(list);\n    result.push(...list);\n  }\n  return result;\n}\n\n/**\n * The body type of every fallback response an operation declares: the\n * `default` response's, then each range response's in declaration order,\n * skipping entries that declare no body. Feeds `collectResponseBodyTypes`,\n * which every pass that walks an operation's type refs goes through (as it\n * goes through `collectResponseHeaders` for headers), so a model reached\n * only as the body of a `default` or `4XX` response is materialized,\n * assigned, renamed and validated like a primary response body.\n */\nexport function collectFallbackResponseTypes(op: Operation): TypeRef[] {\n  const result: TypeRef[] = [];\n  if (op.defaultResponse?.type) result.push(op.defaultResponse.type);\n  for (const range of op.rangeResponses ?? []) {\n    if (range.type) result.push(range.type);\n  }\n  return result;\n}\n\n/**\n * Every type reference a webhook carries: its parameters' types, its\n * request body, the payload of every other media type it declares (each\n * `requestBodyContents` entry whose type is not `requestBody`'s own), and\n * — after its own — everything each of its `callbacks` carries, nested\n * callbacks included, since a `Callback` is a `Webhook` (#382). Every pass\n * that walks an operation's type refs (reachability, ref rewriting and\n * validation, the differ's direction index, inline-enum collection) walks a\n * webhook's through this, so a model reached only through a webhook or\n * callback payload or header is treated the way one reached through an\n * operation is, and a field added to `Webhook` later has one place to join.\n */\nexport function collectWebhookTypeRefs(webhook: Webhook): TypeRef[] {\n  const refs: TypeRef[] = [];\n  for (const param of [...webhook.headerParams, ...webhook.queryParams, ...(webhook.cookieParams ?? [])]) {\n    refs.push(param.type);\n  }\n  if (webhook.requestBody) refs.push(webhook.requestBody);\n  for (const content of webhook.requestBodyContents ?? []) {\n    if (content.type !== webhook.requestBody) refs.push(content.type);\n  }\n  for (const callback of webhook.callbacks ?? []) refs.push(...collectWebhookTypeRefs(callback));\n  return refs;\n}\n\n/**\n * Every type reference an operation carries: its parameters' types in every\n * location (the query parameters the body owns included), its request body\n * and the body of every other request media type (`collectRequestBodyTypes`),\n * its primary response and every other success body, every error body, the\n * pagination iterator's item type and envelope fields, every response header\n * (`collectResponseHeaders`), every secondary, fallback and range body\n * (`collectResponseBodyTypes`), and — last — everything each of its\n * `callbacks` carries, through `collectWebhookTypeRefs`, nested callbacks\n * included (#382). The one list for a pass that reserves or\n * collects names across an operation's references — the enum names held\n * before the deferred schemas are named, the names a merge pass must mint\n * around, the names a webhook must step around — as `collectWebhookTypeRefs`\n * is for a webhook's, so a field added to `Operation` later has one place to\n * join and every reader gets the same list. When `successResponses` exists\n * the primary entry's `type` is the very reference `response` carries, so\n * that reference appears twice; a reader that only collects names is\n * unaffected.\n */\nexport function collectOperationTypeRefs(op: Operation): TypeRef[] {\n  const refs: TypeRef[] = [];\n  for (const param of [\n    ...op.pathParams,\n    ...op.queryParams,\n    ...(op.bodyOwnedQueryParams ?? []),\n    ...op.headerParams,\n    ...(op.cookieParams ?? []),\n  ]) {\n    refs.push(param.type);\n  }\n  if (op.requestBody) refs.push(op.requestBody);\n  for (const { type } of collectRequestBodyTypes(op)) refs.push(type);\n  refs.push(op.response);\n  for (const entry of op.successResponses ?? []) refs.push(entry.type);\n  for (const error of op.errors) if (error.type) refs.push(error.type);\n  if (op.pagination) {\n    refs.push(op.pagination.itemType);\n    for (const field of op.pagination.envelopeFields ?? []) refs.push(field.type);\n  }\n  for (const header of collectResponseHeaders(op)) refs.push(header.type);\n  for (const { type } of collectResponseBodyTypes(op)) refs.push(type);\n  for (const callback of op.callbacks ?? []) refs.push(...collectWebhookTypeRefs(callback));\n  return refs;\n}\n\n/**\n * A header a response declares, typed like a parameter. `name` is kept exactly\n * as written in the spec (e.g. `Content-Disposition`); emitters apply their\n * own casing. Header names are case-insensitive (RFC 9110 §5.1), so one\n * response declares each header once: of two keys that differ in case\n * alone, the parser keeps the later (`foldHeaderName` in\n * `ir/parameter-key.ts` decides which keys are one header).\n */\nexport interface ResponseHeader {\n  name: string;\n  /**\n   * The header schema's type. The header's schema is resolved as a\n   * parameter's is (see `Parameter.type`): the Header Object's `schema`\n   * (resolved through `components/headers`) or, in its place, the schema of\n   * the `content` entry read by the same media type rule. A header with\n   * neither, a `text/plain` entry without a schema, or a map none of whose\n   * media types is read — the last with a parser warning — is a string.\n   */\n  type: TypeRef;\n  required: boolean;\n  /** The Header Object's own `description`; the schema's is never the header's. */\n  description?: string;\n  /**\n   * `true` when the Header Object says `deprecated: true`, or the schema\n   * `type` is read from does — on its own keys, or on an `allOf` member of\n   * it that declares no type and so only annotates it (`allOfWrapperLayer`;\n   * #555), as a field reads the flag. Absent otherwise.\n   */\n  deprecated?: boolean;\n  /**\n   * The header schema's `externalDocs`, when it declares a usable one — the\n   * schema `type` is read from, whether the Header Object's `schema` or the\n   * `content` entry's: its own, else the first `allOf` member's that\n   * declares no type and so only annotates the schema (`allOfWrapperLayer`;\n   * #605), so `allOf: [{ type: 'integer' }, { externalDocs }]` gives the\n   * header the link `allOf: [{ type: 'integer' }], externalDocs` does, as it\n   * gives a field, a parameter and the model built from the schema. A\n   * Header Object has no `externalDocs` of its own. Absent otherwise.\n   */\n  externalDocs?: ExternalDocs;\n}\n\nexport interface ErrorResponse {\n  statusCode: number;\n  type?: TypeRef;\n  /** Declared response headers. Present only when the spec declares at least one. */\n  headers?: ResponseHeader[];\n  /**\n   * Media types declared under `content`, in document order and as written.\n   * `type` is by definition the JSON body (`application/json`, else the first\n   * `+json` media type), so the list is present only when it says something\n   * `type` does not: the error declares another media type, a JSON media type\n   * other than plain `application/json` (`application/problem+json` alone,\n   * `application/json; charset=utf-8`), or a JSON body `type` could not be\n   * read from. An error that declares only `application/json` with a schema\n   * keeps its shape.\n   */\n  contentTypes?: string[];\n  /**\n   * One entry per `contentTypes` entry, in the same order. The entry for the\n   * media type `type` was read from carries the same TypeRef as `type`.\n   * Present only when `contentTypes` is.\n   */\n  contents?: ResponseContent[];\n  /**\n   * The response's `description` as written in the document (e.g. \"Not\n   * found\"). Present only when it has non-whitespace content; kept verbatim.\n   */\n  description?: string;\n}\n\n/**\n * One entry of `Operation.successResponses`: a declared 2xx or 3xx response.\n * A 3xx entry's `type` is always `unknown`. A 2xx body that is itself an\n * inline enum is promoted to `spec.enums` as `<Op>Response`, and an array of\n * one as `<Op>Item`, the name an array body's items take; every entry of one\n * shape derives the same name, so a second body with other members is\n * qualified with its status code (`CheckPetKindResponse202`,\n * `CheckPetKindItem202`), while identical members share one enum.\n */\nexport interface SuccessResponse {\n  statusCode: number;\n  type: TypeRef;\n  /** Declared response headers. Present only when the spec declares at least one. */\n  headers?: ResponseHeader[];\n  /**\n   * Media types declared under `content`, in document order and as written.\n   * Present only when there is at least one.\n   */\n  contentTypes?: string[];\n  /**\n   * One entry per `contentTypes` entry, in the same order. The entry for the\n   * media type `type` was read from carries that same TypeRef. Present only\n   * when `contentTypes` is.\n   */\n  contents?: ResponseContent[];\n  /**\n   * The response's `description` as written in the document (e.g. \"The pet,\n   * with its owner.\"). Present only when it has non-whitespace content; kept\n   * verbatim.\n   */\n  description?: string;\n}\n\n/**\n * One media type a response declares under `content`, with the type its\n * schema resolves to. `contentType` is kept exactly as written in the spec,\n * parameters and all, so it can be sent back verbatim in an `Accept` header.\n */\nexport interface ResponseContent {\n  contentType: string;\n  type: TypeRef;\n}\n\n/**\n * One media type a request body declares under `content`, with the type it\n * resolves to. `contentType` is kept exactly as written in the spec,\n * parameters and all, so it can be sent verbatim as a `Content-Type`.\n */\nexport interface RequestBodyContent {\n  contentType: string;\n  type: TypeRef;\n}\n\n/**\n * A response body type other than `Operation.response`, with where it comes\n * from for diagnostics.\n */\nexport interface ResponseBodyType {\n  type: TypeRef;\n  /**\n   * The entry it belongs to: `contents.<media type>` for a secondary media\n   * type, `defaultResponse` for the `default` response's body,\n   * `rangeResponses.<range>` (`rangeResponses.4XX`) for a range response's.\n   */\n  source: string;\n}\n\n/**\n * Every response body type an operation declares besides `response`: the\n * bodies of its secondary media types (`collectAlternateResponseContents`,\n * fallback responses' included), then the fallback bodies of its `default`\n * and range responses (`collectFallbackResponseTypes`), and any body a later\n * field adds. The primary type of each alternate 2xx and error entry is not\n * included — walkers reach those through `successResponses[].type` and\n * `errors[].type` where they do today. Every pass that walks an operation's\n * type refs (reachability, model assignment, ref rewriting and validation,\n * direction, compat filtering, enum collection) calls this beside\n * `collectResponseHeaders`, so a new kind of body is reached everywhere by\n * extending this one function.\n */\nexport function collectResponseBodyTypes(op: Operation): ResponseBodyType[] {\n  const result: ResponseBodyType[] = alternateResponseContents(op).map(({ content, source }) => ({\n    type: content.type,\n    source: `${source}.${content.contentType}`,\n  }));\n  if (op.defaultResponse?.type) result.push({ type: op.defaultResponse.type, source: 'defaultResponse' });\n  for (const range of op.rangeResponses ?? []) {\n    if (range.type) result.push({ type: range.type, source: `rangeResponses.${range.range}` });\n  }\n  return result;\n}\n\n/**\n * A request body type other than `Operation.requestBody`, with where it\n * comes from for diagnostics.\n */\nexport interface RequestBodyType {\n  type: TypeRef;\n  /** The entry it belongs to: `requestBodyContents.<media type>`. */\n  source: string;\n}\n\n/**\n * Every request body type an operation declares besides `requestBody`: the\n * bodies of its other media types (`collectAlternateRequestBodyContents`).\n * The request-side twin of `collectResponseBodyTypes`: every pass that walks\n * an operation's type refs (reachability, model assignment, ref rewriting\n * and validation, direction, compat filtering, enum collection) calls this\n * beside it, so a body declared only for a secondary media type is reached\n * everywhere `requestBody` is, and a new kind of request body is reached\n * everywhere by extending this one function.\n */\nexport function collectRequestBodyTypes(op: Operation): RequestBodyType[] {\n  return collectAlternateRequestBodyContents(op).map((content) => ({\n    type: content.type,\n    source: `requestBodyContents.${content.contentType}`,\n  }));\n}\n\n/**\n * Every request content entry whose type is reachable only through it: the\n * entries of `requestBodyContents` other than the one `requestBody` was read\n * from, which shares that very TypeRef and is already reached through\n * `requestBody`. Every entry when no media type was read as `requestBody`.\n * Feeds `collectRequestBodyTypes`, which the walkers call.\n */\nexport function collectAlternateRequestBodyContents(op: Operation): RequestBodyContent[] {\n  return (op.requestBodyContents ?? []).filter((content) => content.type !== op.requestBody);\n}\n\n/**\n * Every response content entry whose type is reachable only through it: the\n * entries of each success, error and fallback response other than the one\n * the response's own `type` was read from, which shares that very TypeRef\n * and is already reached through `response`, `successResponses[].type`,\n * `errors[].type` or `collectFallbackResponseTypes`. The primary list is the\n * same array as its `successResponses` entry when both exist, so it is\n * visited once. Feeds `collectResponseBodyTypes`, which the walkers call.\n */\nexport function collectAlternateResponseContents(op: Operation): ResponseContent[] {\n  return alternateResponseContents(op).map(({ content }) => content);\n}\n\n/** `collectAlternateResponseContents`, each entry with the list it was read from (`contents`, `defaultResponse.contents`, `rangeResponses.4XX.contents`). */\nfunction alternateResponseContents(op: Operation): Array<{ content: ResponseContent; source: string }> {\n  const result: Array<{ content: ResponseContent; source: string }> = [];\n  const seen = new Set<ResponseContent[]>();\n  const owners: Array<{ contents?: ResponseContent[]; type?: TypeRef; source: string }> = [\n    { contents: op.responseContents, type: op.response, source: 'contents' },\n    ...(op.successResponses ?? []).map((entry) => ({ ...entry, source: 'contents' })),\n    ...op.errors.map((entry) => ({ ...entry, source: 'contents' })),\n    ...(op.defaultResponse ? [{ ...op.defaultResponse, source: 'defaultResponse.contents' }] : []),\n    ...(op.rangeResponses ?? []).map((entry) => ({ ...entry, source: `rangeResponses.${entry.range}.contents` })),\n  ];\n  for (const { contents, type, source } of owners) {\n    if (!contents || seen.has(contents)) continue;\n    seen.add(contents);\n    for (const content of contents) if (content.type !== type) result.push({ content, source });\n  }\n  return result;\n}\n\n/**\n * The `default` response: the body and headers for every status the\n * operation does not list. See `Operation.defaultResponse`.\n */\nexport interface DefaultResponse {\n  /**\n   * Response body type: the `application/json` body, else the first `+json`\n   * one; absent when the response declares neither.\n   */\n  type?: TypeRef;\n  /** Declared response headers. Present only when the spec declares at least one. */\n  headers?: ResponseHeader[];\n  /**\n   * Media types declared under `content`, in document order and as written,\n   * exactly as on `SuccessResponse`. Present only when there is at least one.\n   */\n  contentTypes?: string[];\n  /**\n   * One entry per `contentTypes` entry, in the same order. The entry for the\n   * media type `type` was read from carries that same TypeRef. Present only\n   * when `contentTypes` is.\n   */\n  contents?: ResponseContent[];\n  /** The response's own `description`, as on `SuccessResponse`/`ErrorResponse`; present only with non-whitespace content. */\n  description?: string;\n}\n\n/** A Responses Object range key, uppercase as OpenAPI writes it (`4xx` is read as `4XX`). */\nexport type StatusRange = '1XX' | '2XX' | '3XX' | '4XX' | '5XX';\n\n/**\n * A range response: the body and headers for every status in one hundred\n * (`4XX` → 400–499) that the operation does not list explicitly. See\n * `Operation.rangeResponses`.\n */\nexport interface RangeResponse {\n  range: StatusRange;\n  /**\n   * Response body type: the `application/json` body, else the first `+json`\n   * one; absent when the response declares neither.\n   */\n  type?: TypeRef;\n  /** Declared response headers. Present only when the spec declares at least one. */\n  headers?: ResponseHeader[];\n  /** Media types declared under `content`, as on `DefaultResponse`. */\n  contentTypes?: string[];\n  /** One entry per `contentTypes` entry, as on `DefaultResponse`. */\n  contents?: ResponseContent[];\n  /** The response's own `description`, as on `SuccessResponse`/`ErrorResponse`; present only with non-whitespace content. */\n  description?: string;\n}\n","/**\n * Known compound tokens that the regex-based splitter over-splits.\n * Each entry is [lowercase-word-sequence, canonical-form].\n * Sorted longest-first so greedy matching works correctly.\n */\nconst COMPOUND_WORDS: [string[], string][] = [\n  [['m', '2', 'm'], 'M2M'],\n  [['o', 'auth'], 'OAuth'],\n];\n\n/**\n * Recombine adjacent words that form a known compound token.\n */\nfunction recombineCompounds(words: string[]): string[] {\n  const result: string[] = [];\n  let i = 0;\n  while (i < words.length) {\n    let matched = false;\n    for (const [pattern, canonical] of COMPOUND_WORDS) {\n      if (i + pattern.length <= words.length) {\n        const matches = pattern.every((p, j) => words[i + j].toLowerCase() === p);\n        if (matches) {\n          result.push(canonical);\n          i += pattern.length;\n          matched = true;\n          break;\n        }\n      }\n    }\n    if (!matched) {\n      result.push(words[i]);\n      i++;\n    }\n  }\n  return result;\n}\n\n/**\n * Split a string into words, handling:\n * - camelCase / PascalCase boundaries\n * - snake_case / kebab-case separators\n * - Consecutive capitals (e.g., \"HTTPClient\" → [\"HTTP\", \"Client\"])\n * - Numbers as word boundaries (e.g., \"OAuth2Token\" → [\"OAuth\", \"2\", \"Token\"])\n * - Known compounds are recombined (e.g., \"M2M\" stays as one word)\n */\nexport function splitWords(s: string): string[] {\n  if (!s) return [];\n\n  const words = s\n    .replace(/[^a-zA-Z0-9_\\-\\s.]/g, '_') // replace non-alphanumeric chars with separator\n    .replace(/([a-z])([A-Z])/g, '$1\\0$2') // camelCase boundary\n    .replace(/([A-Z]+)([A-Z][a-z])/g, '$1\\0$2') // consecutive caps boundary\n    .replace(/([a-zA-Z])(\\d)/g, '$1\\0$2') // letter to number\n    .replace(/(\\d)([a-zA-Z])/g, '$1\\0$2') // number to letter\n    .split(/[\\0_\\-\\s.]+/)\n    .filter((w) => w.length > 0);\n\n  return recombineCompounds(words);\n}\n\nexport const ACRONYM_SET = new Set(['SSO', 'FGA', 'SAML', 'SCIM', 'JWT', 'HMAC', 'M2M']);\n\nexport function toPascalCase(s: string, acronyms?: Set<string>): string {\n  const merged = acronyms ? new Set([...ACRONYM_SET, ...acronyms]) : ACRONYM_SET;\n  return splitWords(s)\n    .map((w) => {\n      const upper = w.toUpperCase();\n      if (merged.has(upper)) return upper;\n      // Special case: OAuth should stay as OAuth, not OAUTH\n      if (upper === 'OAUTH') return 'OAuth';\n      return w.charAt(0).toUpperCase() + w.slice(1).toLowerCase();\n    })\n    .join('');\n}\n\nexport function toCamelCase(s: string, acronyms?: Set<string>): string {\n  const merged = acronyms ? new Set([...ACRONYM_SET, ...acronyms]) : ACRONYM_SET;\n  const words = splitWords(s);\n  if (words.length === 0) return '';\n  return words\n    .map((w, i) => {\n      if (i === 0) return w.toLowerCase();\n      const upper = w.toUpperCase();\n      if (merged.has(upper)) return upper;\n      if (upper === 'OAUTH') return 'OAuth';\n      return w.charAt(0).toUpperCase() + w.slice(1).toLowerCase();\n    })\n    .join('');\n}\n\nexport function toSnakeCase(s: string): string {\n  return splitWords(s)\n    .map((w) => w.toLowerCase())\n    .join('_');\n}\n\nexport function toKebabCase(s: string): string {\n  return splitWords(s)\n    .map((w) => w.toLowerCase())\n    .join('-');\n}\n\nexport function toUpperSnakeCase(s: string): string {\n  return splitWords(s)\n    .map((w) => w.toUpperCase())\n    .join('_');\n}\n\n/**\n * `name` with the numeric suffix `n`, the one spelling of every numbered\n * operation, model and enum name: `list` + 2 is `list2`. A name that already\n * ends in a digit takes the number behind `No`, so that it cannot be read as\n * part of the number the name ends with: `listV1` + 2 is `listV1No2`, never\n * `listV12`, which reads as version 12 of the API, and `PetSizeV2` + 2 is\n * `PetSizeV2No2`. The hex hash that sets a path-derived or webhook stem\n * apart is appended the same way, so one that starts with a digit is set off\n * too (`PetsTop10` + `567B59` is `PetsTop10No567B59`, never\n * `PetsTop10567B59`) and one that starts with a letter follows the name as\n * it is (`PetsTop10Ba41B5`). An underscore would not do: splitWords reads a\n * digit run as a word of its own, so `listV1_2` re-cased by toPascalCase or\n * toCamelCase is `ListV12` or `listV12` again. The name is read as given, so\n * a caller numbers a name in its final spelling; one that is cased only\n * later is numbered by numberedProperty.\n */\nexport function numberedName(name: string, n: number | string): string {\n  const suffix = String(n);\n  return /\\d$/.test(name) && /^\\d/.test(suffix) ? `${name}No${suffix}` : `${name}${suffix}`;\n}\n\n/**\n * `property` with the numeric suffix `n`, for a property name that is cased\n * only later: the raw parameter or header name the shape registry and a\n * webhook's `mintParameter` extract a schema under, which toPascalCase turns\n * into the model name. The number is spelled as numberedName spells it on the\n * cased name, so one that ends in a digit once the characters that are\n * neither letters nor digits are dropped (`filter[v2]`, `x-meta-v2_`,\n * `filter_v2_`) takes it behind `No` too: `filter[v2]` + 2 is\n * `filter[v2]No2`, cased `FilterV2No2`, never `filter[v2]2`, which cases to\n * `FilterV22` and reads as version 22 (#533); `query_payload` + 2 is still\n * `query_payload2`. The property is returned as written, not cased: the\n * stems a site's siblings settled on are compared as strings, and\n * toPascalCase is not idempotent (`sso_v2` is `SSOV2`, re-cased `Ssov2`).\n */\nexport function numberedProperty(property: string, n: number | string): string {\n  const cased = toPascalCase(property);\n  return `${property}${numberedName(cased, n).slice(cased.length)}`;\n}\n\nconst BACKEND_SUFFIXES = ['Controller'];\n\nexport function stripBackendSuffixes(name: string): string {\n  for (const suffix of BACKEND_SUFFIXES) {\n    if (name.endsWith(suffix) && name.length > suffix.length) {\n      return name.slice(0, -suffix.length);\n    }\n  }\n  return name;\n}\n\nexport function stripBackendPrefixes(name: string): string {\n  return name.replace(/Userland/g, '').replace(/Controller/g, '');\n}\n\n/**\n * Remove ListItem / ByExternalId / ByResourceId / ForResource markers from PascalCase names.\n * E.g. \"DirectoriesListItemState\" → \"DirectoriesState\"\n */\nexport function stripListItemMarkers(name: string): string {\n  return name\n    .replace(/ListItem/g, '')\n    .replace(/ByExternalId/g, '')\n    .replace(/ByResourceId/g, '')\n    .replace(/ForResource/g, '');\n}\n\n/** Words that look plural but must NOT be singularized. */\nconst SINGULAR_SAFE_LIST = new Set([\n  'Status',\n  'Address',\n  'Access',\n  'Process',\n  'Progress',\n  'Success',\n  'Radius',\n  'Canvas',\n  'Alias',\n  'Basis',\n  'Bus',\n  'Species',\n  'Series',\n]);\n\n/**\n * The singular of a word read as a plural, by suffix alone: `word` ends in\n * `s`, and the caller has ruled out whatever it does not read as a plural.\n * The one set of rules `singularize` and `singularizePathSegment` share, so a\n * field, a component and a path segment spell one noun's singular the same\n * way (`causes` is `cause` as an array field and as a resource; #620):\n * - `-ies` → `-y` when the word is longer than four letters (`directories` →\n *   `directory`; a short `-ies` word keeps its `ie`, `pies` → `pie`);\n * - `-yses` → `-ysis` (`analyses` → `analysis`);\n * - the `es` of a sibilant stem is dropped — `-sses`, `-uses` after a\n *   consonant, `-iases`, `-xes`, `-ches`, `-shes` (`addresses` → `address`,\n *   `statuses` → `status`, `aliases` → `alias`, `boxes` → `box`, `batches` →\n *   `batch`, `hashes` → `hash`) — except `-aches` after a consonant, which\n *   is an `-ache` noun's plain `s` (`caches` → `cache`, `headaches` →\n *   `headache`, `mustaches` → `mustache`; an `-ach` noun has a vowel before\n *   the `a`, `coaches` → `coach`, `beaches` → `beach`);\n * - any other `s` is a plain plural `s` (`notes` → `note`, `causes` →\n *   `cause`, `licenses` → `license`, `responses` → `response`, `releases` →\n *   `release`, `warehouses` → `warehouse`).\n * Case is preserved — the rules only slice, except the `y` and `is` they\n * write, which take the case of the letters they replace (`DIRECTORIES` →\n * `DIRECTORY`, `ANALYSES` → `ANALYSIS`).\n */\nfunction stripPluralSuffix(word: string): string {\n  const lower = word.toLowerCase();\n  // `directories` → `directory`; a short `-ies` word keeps its `ie` (`pies` → `pie`).\n  if (lower.endsWith('ies') && lower.length > 4) {\n    return word.slice(0, -3) + (word.endsWith('IES') ? 'Y' : 'y');\n  }\n  // `analyses` → `analysis`: every English `-yses` noun is the plural of a\n  // `-ysis` noun (`paralyses`, `dialyses`, `catalyses`).\n  if (lower.endsWith('yses')) return word.slice(0, -2) + (word.endsWith('ES') ? 'IS' : 'is');\n  // An `es` added to a sibilant stem: `addresses`, `statuses`, `aliases`,\n  // `boxes`, `batches`, `hashes`. A vowel before `uses` is a plain `s` instead\n  // (`warehouses`), and so is any letter but `i` before `ases` (`cases`,\n  // `releases`): no English noun ends in `-iase`, so `aliases` and `biases`\n  // are `-ias` nouns.\n  if (lower.endsWith('sses') || /[^aeiou]uses$/.test(lower) || lower.endsWith('iases')) return word.slice(0, -2);\n  // An `-ache` noun (`caches`, `headaches`, `mustaches`) is the `-aches` word\n  // with a consonant before the `a`; an `-ach` noun has a vowel there\n  // (`coaches`, `beaches`, `approaches`) and drops its `es` below.\n  if (/[^aeiou]aches$/.test(lower)) return word.slice(0, -1);\n  if (lower.endsWith('xes') || lower.endsWith('ches') || lower.endsWith('shes')) return word.slice(0, -2);\n  return word.slice(0, -1);\n}\n\n/**\n * Conservative singularize for one word of a model name — the leading word\n * of a component name (`cleanSchemaName`), the trailing word of an inline\n * model's name (`qualifyInlineModelName`), the field a nested error body's\n * items are reached through (`collapseErrorBodies`), the array a `dataPath`\n * hint ends in (`inlineItemNameForPath`) — or a raw field name. The suffix\n * rules are the ones a path segment is singularized by (`stripPluralSuffix`,\n * shared with `singularizePathSegment`), so a field and a resource of one\n * noun spell its singular alike: `Directories` → `Directory`, `Organizations`\n * → `Organization`, `Statuses` → `Status`, `Addresses` → `Address`, `Boxes`\n * → `Box`, `Batches` → `Batch`, `Causes` → `Cause`, `Licenses` → `License`,\n * `Responses` → `Response`, `Analyses` → `Analysis`, `Caches` → `Cache`\n * (#620; before it, every `-ses` word lost its `es` — `Caus`, `Licens`,\n * `Respons` — and every other `-es` word only its `s` — `Boxe`, `Batche`).\n * What is read as a plural at all is decided here, not by the path\n * segment's guards: a safe-listed word (`Status`, `Address`, `Series`, …)\n * and its `-es` plural (`Canvases` → `Canvas`, `Radiuses` → `Radius`,\n * whatever the suffix rules would make of them), a word of four letters or\n * fewer (`Pets`, `Tags`, `Bus`, `Gas`, `News`, `Axes` are kept as they are,\n * since a short word is as likely a singular) and a word ending in `ss`\n * (`Class`) are never singularized, and neither is a `-ysis` word, the\n * singular the `-yses` rule writes (`Analysis`); any other `-us` or `-is`\n * word is read as a plural, as it always was (`Menus` → `Menu`, `Emojis` →\n * `Emoji`, at the price of `Campus` → `Campu`). The suffix rules' limits\n * are the ones documented on `singularizePathSegment`, and reach a model\n * name as they reach an operation's: `Gases` → `Gase`, `Lenses` → `Lense`,\n * `Atlases` → `Atlase`, `Niches` → `Nich`, `Diagnoses` → `Diagnose` (where\n * the two-branch rule before #620 happened to give `Gas`, `Lens`, `Atlas`\n * and `Niche`). Every singular the `-ies`, `-yses` and sibilant rules write\n * is returned as it is when passed back in, so `cleanSchemaName` is\n * idempotent on it; the `-us` a consonant + `-uses` plural gives is not,\n * since a `-us` word is read as a plural (`Bonuses` → `Bonus` → `Bonu`,\n * `Campuses` → `Campus` → `Campu`, `Viruses` → `Virus` → `Viru`, as on\n * every version before this one).\n */\nexport function singularize(word: string): string {\n  if (SINGULAR_SAFE_LIST.has(word) || word.length <= 4) return word;\n  // `-ss` is never a plural (`Class`), and neither is `-ysis`, the singular\n  // the `-yses` rule writes (`Analysis`), so the singulars the suffix rules\n  // write are returned as they are when passed back in, as cleanSchemaName\n  // requires — all but the `-us` a consonant + `-uses` plural gives, which\n  // is read as a plural again (`Bonuses` → `Bonus` → `Bonu`).\n  if (!word.endsWith('s') || word.endsWith('ss') || word.endsWith('ysis')) return word;\n  // A safe-listed word's `-es` plural is that word (`Canvases` → `Canvas`,\n  // `Radiuses` → `Radius`), whatever the suffix rules would make of it.\n  if (word.endsWith('es') && SINGULAR_SAFE_LIST.has(word.slice(0, -2))) return word.slice(0, -2);\n  return stripPluralSuffix(word);\n}\n\n/**\n * Conservative singularisation of a path segment, for naming an operation on\n * one item of a collection: `pets` → `pet`, `api_keys` → `api_key`,\n * `directories` → `directory`, `addresses` → `address`, `statuses` → `status`,\n * `aliases` → `alias`, `analyses` → `analysis`, `boxes` → `box`, `batches` →\n * `batch`, `caches` → `cache`, `responses` → `response`.\n *\n * Suffix rules only (`stripPluralSuffix`, the rules `singularize` applies to\n * a model name's word, so `/causes/{id}` and a `causes` field spell one\n * `cause`), no dictionary, so anything that does not look plural is returned\n * as it is: a segment that does not end in `s`, or ends in `ss`, `us`, `is`\n * or `ias` (`status`, `analysis`, `alias`), or is an invariant plural\n * (`series`). Case is preserved — the rules only slice, except `-ies` → `-y`\n * and `-yses` → `-ysis`, whose `y` and `is` take the case of the letters they\n * replace (`DIRECTORIES` → `DIRECTORY`, `ANALYSES` → `ANALYSIS`, so splitWords\n * still sees one word) — and only the trailing word of a compound segment\n * matters. Idempotent: every singular it produces is returned as it is when\n * passed back in (`aliases` → `alias` → `alias`), so a comparison of two\n * words by their singular forms (see appendQualifier) is sound.\n *\n * Deliberately not handled — a resource that stems wrong should carry an\n * `operationId`: irregular plurals (`people`, `children`, `data`), `-ies`\n * words whose singular keeps the `ie` (`cookies` → `cooky`), `-oes` (`heroes`\n * → `heroe`), `-ches` nouns ending in `-che` other than a consonant + `-ache`\n * (`niches` → `nich`, `avalanches` → `avalanch`, `tranches` → `tranch`,\n * where `caches` → `cache` and `branches` → `branch` are the common\n * readings), `-uses`\n * nouns ending in `-use` (`excuses` → `excus`), `-zes` plurals of a doubled\n * `z` (`quizzes` → `quizze`, where `sizes` → `size` is the common reading),\n * `-ases` nouns ending in `-as`\n * other than `-ias` (`canvases` → `canvase`, where `cases` → `case` is the\n * common reading), `-es` plurals of `-is` nouns other than `-ysis` (`crises`\n * → `crise`, `theses` → `these`, where `premises` → `premise` and `cheeses`\n * → `cheese` are the common readings), singular nouns ending in `-as` other\n * than `-ias`, or in `-ns` (`canvas` → `canva`, `lens` → `len`, where `areas`\n * → `area` and `tokens` → `token` are the common readings), plurals of `-ia`\n * nouns (`utopias` is kept as it is, so that `alias` is), plurals of\n * `-u`/`-i` nouns (`menus`, `apis` are kept as they are) and acronyms (`sms`\n * → `sm`). These limits reach every segment the parser singularises — the\n * resource of an item operation, a deeper segment a path parameter follows\n * and the service noun a name restores — so `/messages/sms/{smsId}/attachments`\n * contributes `Sm` and `/design/canvas/{id}/layers/{layerId}` contributes\n * `Canva` to a qualified name.\n */\nexport function singularizePathSegment(segment: string): string {\n  const lower = segment.toLowerCase();\n  if (lower.length <= 2 || !lower.endsWith('s')) return segment;\n  if (lower.endsWith('series') || lower.endsWith('species') || lower.endsWith('news')) return segment;\n  // `-ias` is kept for `alias` and `bias`, the singulars the `-iases` rule\n  // below produces, at the price of the rarer `-ia` plurals (`utopias`).\n  if (lower.endsWith('ss') || lower.endsWith('us') || lower.endsWith('is') || lower.endsWith('ias')) return segment;\n  return stripPluralSuffix(segment);\n}\n\n/**\n * Compose all backend name cleaning transforms in order:\n * 1. Strip backend prefixes (Userland, Controller)\n * 2. Strip backend suffixes (Dto, DTO, Controller)\n * 3. Strip ListItem / ByExternalId markers\n * 4. Singularize leading resource word\n *\n * Must be idempotent: `cleanSchemaName(cleanSchemaName(x)) === cleanSchemaName(x)`\n * — which holds for every name but one whose leading word is a consonant +\n * `-uses` plural, since `singularize` reads the `-us` it writes as a plural\n * again (`Bonuses` → `Bonus` → `Bonu`; see singularize).\n */\n/** Strip `.js` extensions from import/export specifiers for dedup comparison. */\nexport function normalizeJsExtension(text: string): string {\n  return text.replace(/\\.js(['\"])/g, '$1');\n}\n\nexport function cleanSchemaName(name: string): string {\n  return singularizeLeadingWord(stripListItemMarkers(stripBackendPrefixes(stripBackendSuffixes(name))));\n}\n\n/**\n * `name` with its leading PascalCase word singularized (`NotesList` →\n * `NoteList`, `Pets` → `Pet`): the last step of cleanSchemaName, read on its\n * own where an id the cleaning only singularized must be told from one it\n * stripped a marker or a backend word from (resolveContestedOperationIdStems,\n * #627).\n */\nexport function singularizeLeadingWord(name: string): string {\n  const match = name.match(/^([A-Z][a-z]*)/);\n  if (!match) return name;\n  const leadWord = match[1];\n  const singular = singularize(leadWord);\n  return singular === leadWord ? name : singular + name.slice(leadWord.length);\n}\n","import type { ExternalDocs } from '../ir/types.js';\n\n/**\n * An External Documentation Object as written in the OpenAPI document, before\n * validation. Any key may be missing or of the wrong type; `readExternalDocs`\n * decides what reaches the IR.\n */\nexport interface RawExternalDocs {\n  url?: string;\n  description?: string;\n}\n\n/**\n * Read an `externalDocs` value from the document into the IR.\n *\n * Only `url` makes the object meaningful, so an entry is kept when `url` is a\n * string with non-whitespace content and dropped otherwise — a non-object, a\n * missing `url`, a blank one. The parser ignored `externalDocs` entirely\n * before it was read, so a malformed value must keep parsing the way a\n * malformed document tag does: it is skipped, neither warned about nor thrown\n * on, and nothing the IR used to carry is lost.\n *\n * `url` is kept exactly as written. OpenAPI allows it to be relative to the\n * document's own location, which the parser does not know, so it neither\n * resolves nor rewrites it. `description` is carried only when it has\n * non-whitespace content, matching how a blank operation summary or tag\n * description is treated as absent; text with content is kept verbatim.\n */\nexport function readExternalDocs(raw: unknown): ExternalDocs | undefined {\n  if (typeof raw !== 'object' || raw === null) return undefined;\n  const { url, description } = raw as RawExternalDocs;\n  if (typeof url !== 'string' || url.trim() === '') return undefined;\n  const described = typeof description === 'string' && description.trim() !== '';\n  return described ? { url, description } : { url };\n}\n\n/**\n * `{ externalDocs }` when `raw` is a usable entry and `{}` otherwise, for\n * spreading into an IR node literal so the key stays absent — not present but\n * `undefined` — on nodes without one. Same shape as `constraintsEntry`.\n */\nexport function externalDocsEntry(raw: unknown): { externalDocs?: ExternalDocs } {\n  const externalDocs = readExternalDocs(raw);\n  return externalDocs ? { externalDocs } : {};\n}\n","import type { Extensions } from '../ir/types.js';\nimport type { SchemaObject } from './schemas.js';\n\n/**\n * The Schema Object extensions the parser reads into typed IR fields, so\n * they are not repeated in a model's, field's or enum's `extensions`:\n * `x-enum-descriptions` / `x-enumDescriptions` give each enum value its\n * `description` (`enumValueDescriptions` in `schemas.ts`).\n */\nexport const SCHEMA_CONSUMED_EXTENSIONS: ReadonlySet<string> = new Set(['x-enum-descriptions', 'x-enumDescriptions']);\n\n/**\n * The Operation Object extensions the parser reads into typed fields, so\n * they are not repeated in an operation's `extensions`: `x-pagination`\n * (`pagination`, through `resolvePaginationOverride`), `x-oagen-async`\n * (`async`), `x-mutually-exclusive-parameter-groups` and\n * `x-mutually-exclusive-body-groups` (`parameterGroups`).\n */\nexport const OPERATION_CONSUMED_EXTENSIONS: ReadonlySet<string> = new Set([\n  'x-pagination',\n  'x-oagen-async',\n  'x-mutually-exclusive-parameter-groups',\n  'x-mutually-exclusive-body-groups',\n]);\n\nconst NONE_CONSUMED: ReadonlySet<string> = new Set();\n\n/**\n * The specification extensions `source` declares — every own key that\n * starts with `x-`, in document order, each with its value exactly as\n * written (an object or array value is the document's own, not a copy) —\n * less the keys in `consumed`, which the parser reads into typed fields\n * elsewhere. `undefined` when none remains, so an IR node built from the\n * result has no `extensions` key at all rather than an empty object.\n */\nexport function extensionsOf(source: object, consumed: ReadonlySet<string> = NONE_CONSUMED): Extensions | undefined {\n  let out: Extensions | undefined;\n  for (const [key, value] of Object.entries(source)) {\n    if (!key.startsWith('x-') || consumed.has(key)) continue;\n    (out ??= {})[key] = value;\n  }\n  return out;\n}\n\n/**\n * `{ extensions }` when a Schema Object declares at least one extension the\n * parser does not consume (`SCHEMA_CONSUMED_EXTENSIONS`), `{}` otherwise —\n * spread into a `Model`, `Field` or `Enum` literal so the key stays absent\n * rather than present-but-undefined, as `constraintsEntry` and\n * `deprecatedEntry` are.\n */\nexport function schemaExtensionsEntry(schema: SchemaObject): { extensions?: Extensions } {\n  const extensions = extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS);\n  return extensions ? { extensions } : {};\n}\n\n/**\n * `{ extensions }` when an Operation Object declares at least one extension\n * the parser does not consume (`OPERATION_CONSUMED_EXTENSIONS`), `{}`\n * otherwise — spread into the `Operation` literal.\n */\nexport function operationExtensionsEntry(op: object): { extensions?: Extensions } {\n  const extensions = extensionsOf(op, OPERATION_CONSUMED_EXTENSIONS);\n  return extensions ? { extensions } : {};\n}\n","import type { EnumRef, EnumValue, Extensions, ExternalDocs, TypeRef } from '../ir/types.js';\nimport { assertNever } from '../ir/types.js';\nimport { toUpperSnakeCase } from '../utils/naming.js';\nimport { readExternalDocs } from './external-docs.js';\n\n/**\n * One member of an enum as the document declares it: the value, and the\n * documentation the document can attach to that one value — a `description`\n * (from the member's own `const` schema or an `x-enum-descriptions` /\n * `x-enumDescriptions` entry) and `deprecated: true` (from a `const` member\n * only; a plain `enum:` list has no per-value keyword). `enumMembersOf` in\n * `schemas.ts` reads them; `toEnumValue` turns one into the IR's `EnumValue`.\n */\nexport interface EnumMember {\n  value: string | number;\n  description?: string;\n  /** Only ever `true`; the key is absent otherwise, as on every IR node. */\n  deprecated?: boolean;\n}\n\n/**\n * What an inline enum ref carries besides its `values`, for the pass that\n * lifts it to a top-level `Enum`: each member's documentation, and the\n * `description` and link its schema declared. A side table rather than keys\n * on the ref: the ref is the field's or parameter's *type*, which the\n * sameness passes compare by serialization, and documentation is not shape\n * — it sits beside the type on the `Field`, not inside it. Per-value\n * deprecation is shape, though, so every pass that serializes a ref to\n * compare shapes reads it back through `shapeWithEnumFlags`. Keyed by\n * identity because every pass between building a ref and lifting it mutates\n * refs in place (renames, nullable wraps) and none clones them; an\n * unreachable ref drops out on its own.\n */\ninterface InlineEnumMeta {\n  members: EnumMember[];\n  description?: string;\n  externalDocs?: ExternalDocs;\n  /** The schema's own `x-*` keys, less the consumed ones (`extensionsOf`), read like its link. */\n  extensions?: Extensions;\n}\n\nconst inlineEnumMeta = new WeakMap<EnumRef, InlineEnumMeta>();\n\n/** `raw` when it is a string with non-whitespace content, kept verbatim; `undefined` otherwise. */\nfunction textWithContent(raw: unknown): string | undefined {\n  return typeof raw === 'string' && raw.trim() !== '' ? raw : undefined;\n}\n\n/**\n * Build an inline `EnumRef` from its members, recording for the lift pass\n * their documentation and what the schema declares for the enum as a whole:\n * its `description` (`rawDescription`, kept when it is a string with\n * non-whitespace content, as `Model.description` is) and its link\n * (`rawExternalDocs`, when usable). The schema is the one that declares the\n * members — the `enum:` list or the `oneOf`/`anyOf` of consts — as the\n * caller hands it over: `schemaToTypeRef` passes a collapsed nullable or\n * single-member `allOf` wrapper's text and link onto its branch first, and a\n * single-member `oneOf`/`anyOf`'s onto its variant (`withWrapperDocs`), so\n * all are read by one rule.\n */\nexport function inlineEnumRef(\n  name: string,\n  members: readonly EnumMember[],\n  rawExternalDocs: unknown,\n  rawDescription?: unknown,\n  extensions?: Extensions,\n): EnumRef {\n  const ref: EnumRef = { kind: 'enum', name, values: members.map((member) => member.value) };\n  const description = textWithContent(rawDescription);\n  const externalDocs = readExternalDocs(rawExternalDocs);\n  inlineEnumMeta.set(ref, {\n    members: [...members],\n    ...(description !== undefined ? { description } : {}),\n    ...(externalDocs ? { externalDocs } : {}),\n    // The schema's extensions, already read by the caller (`extensionsOf`,\n    // the consumed keys left out), so the lifted enum carries them as it\n    // carries the link.\n    ...(extensions ? { extensions } : {}),\n  });\n  return ref;\n}\n\n/** The `description` recorded for an inline enum ref by `inlineEnumRef`; none for a ref built any other way, or from a schema whose text has no content. */\nexport function inlineEnumDescriptionOf(ref: EnumRef): string | undefined {\n  return inlineEnumMeta.get(ref)?.description;\n}\n\n/** The link recorded for an inline enum ref by `inlineEnumRef`; none for a ref built any other way. */\nexport function inlineEnumExternalDocsOf(ref: EnumRef): ExternalDocs | undefined {\n  return inlineEnumMeta.get(ref)?.externalDocs;\n}\n\n/** The extensions recorded for an inline enum ref by `inlineEnumRef`; none for a ref built any other way, or from a schema that declares none. */\nexport function inlineEnumExtensionsOf(ref: EnumRef): Extensions | undefined {\n  return inlineEnumMeta.get(ref)?.extensions;\n}\n\n/** Give `to`, a copy of `from`, the members, description and link recorded for `from`: a copy made any other way is a bare name to every pass that reads them (`cloneTypeRef`). */\nexport function copyInlineEnumMeta(from: EnumRef, to: EnumRef): void {\n  const meta = inlineEnumMeta.get(from);\n  if (meta) inlineEnumMeta.set(to, { ...meta, members: [...meta.members] });\n}\n\n/** The IR's `EnumValue` for one member: the display name is the value's UPPER_SNAKE_CASE form; `description` and `deprecated` only when the member carries them. */\nexport function toEnumValue(member: EnumMember): EnumValue {\n  return {\n    name: toUpperSnakeCase(String(member.value)),\n    value: member.value,\n    ...(member.description !== undefined ? { description: member.description } : {}),\n    ...(member.deprecated === true ? { deprecated: true } : {}),\n  };\n}\n\n/**\n * The `EnumValue`s an inline enum ref lifts to: one per entry of its\n * `values`, in that order, each with the documentation `inlineEnumRef`\n * recorded for that position — by occurrence, not by value, so a repeated\n * `const` branch keeps its own description and flag, as the same schema under\n * `components.schemas` does. Should a ref's `values` no longer match the\n * recorded members one for one (nothing in the parser edits them), each\n * value takes the first member recorded for it. A ref built without\n * `inlineEnumRef` (a test's, a plugin's) lifts to bare values; a ref without\n * `values` (a component's) lifts to none.\n */\nexport function enumValuesOf(ref: EnumRef): EnumValue[] {\n  const values = ref.values ?? [];\n  const members = inlineEnumMeta.get(ref)?.members ?? [];\n  const aligned = members.length === values.length && members.every((member, i) => member.value === values[i]);\n  if (aligned) return members.map(toEnumValue);\n  const first = new Map<string | number, EnumMember>();\n  for (const member of members) if (!first.has(member.value)) first.set(member.value, member);\n  return values.map((value) => toEnumValue(first.get(value) ?? { value }));\n}\n\n/**\n * The shape of one enum member, as a JSON text so no two members read alike:\n * `[value, deprecated]`, the value with its primitive type (the IR keeps\n * numeric `5` and string `\"5\"` distinct, and so do the emitters) and the flag\n * as a boolean — a live `\"active!deprecated\"` and a deprecated `\"active\"` are\n * `[\"active!deprecated\",false]` and `[\"active\",true]`. Two inline enums with\n * the same values are shared under one name only when they also deprecate\n * the same ones, so a field whose schema does not deprecate a value never\n * resolves to an enum that marks it. `description` is documentation, not\n * shape, and does not count — a value's, and the enum's own alike: the first\n * lifted copy's text wins, as its link does.\n */\nexport function enumValueShapeKey(value: Pick<EnumValue, 'value' | 'deprecated'>): string {\n  return JSON.stringify([value.value, value.deprecated === true]);\n}\n\n/**\n * The shape of a whole member list, order-insensitive: the sorted\n * `enumValueShapeKey`s as one JSON array text, so a fingerprint that embeds\n * it cannot read one list as another.\n */\nexport function enumShapeKey(values: readonly Pick<EnumValue, 'value' | 'deprecated'>[]): string {\n  return `[${values.map(enumValueShapeKey).sort().join(',')}]`;\n}\n\n/**\n * Order-insensitive: a reordering of the same members (`enumValueShapeKey`)\n * is the same type. Compared as complete sorted lists (`enumShapeKey`), not\n * as sets, so a repeated member counts each time it occurs: `[a, a!, b]`\n * and `[a, a, b]` are different types, and the second never shares the\n * first's deprecation.\n */\nexport function sameEnumShape(\n  a: readonly Pick<EnumValue, 'value' | 'deprecated'>[],\n  b: readonly Pick<EnumValue, 'value' | 'deprecated'>[],\n): boolean {\n  return enumShapeKey(a) === enumShapeKey(b);\n}\n\n/**\n * `ref` as a plain value for shape comparison: the same tree, with each\n * inline enum ref's deprecated values spelled out beside its `values`\n * (`deprecatedValues`, in `values` order, present only when there is one),\n * so a pass that serializes types to decide whether two models are one shape\n * — `modelFingerprint`, the merge passes' field and variant signatures, the\n * named-union shape key — sees what the side table holds, and two shapes\n * that differ only in a member's deprecation never serialize alike.\n * Descriptions are documentation and are not added. The result is not a\n * `TypeRef`: it is only ever serialized, never handed back to the IR.\n */\nexport function shapeWithEnumFlags(ref: TypeRef): unknown {\n  switch (ref.kind) {\n    case 'primitive':\n    case 'literal':\n    case 'model':\n      return ref;\n    case 'enum': {\n      if (!ref.values) return ref;\n      const deprecatedValues = enumValuesOf(ref)\n        .filter((value) => value.deprecated === true)\n        .map((value) => value.value);\n      return deprecatedValues.length > 0 ? { ...ref, deprecatedValues } : ref;\n    }\n    case 'array':\n      return { ...ref, items: shapeWithEnumFlags(ref.items) };\n    case 'nullable':\n      return { ...ref, inner: shapeWithEnumFlags(ref.inner) };\n    case 'map':\n      return {\n        ...ref,\n        valueType: shapeWithEnumFlags(ref.valueType),\n        ...(ref.keyType ? { keyType: shapeWithEnumFlags(ref.keyType) } : {}),\n      };\n    case 'union':\n      return { ...ref, variants: ref.variants.map(shapeWithEnumFlags) };\n    default:\n      return assertNever(ref);\n  }\n}\n","import type { Model, TypeRef } from '../ir/types.js';\n\n/** A model's dispatch rules: the discriminator property and the mapping from each value to a variant model name. */\nexport type Discriminator = NonNullable<Model['discriminator']>;\n\n/**\n * The part of a model's shape its named-union metadata contributes to a\n * structural fingerprint: `''` for a model that is no union, else its\n * variants — each through `variantKey`, in document order or sorted when the\n * caller treats member order as irrelevant, the list JSON-encoded so a\n * variant key containing `,` cannot read as two variants — followed by\n * `unionRulesKey`, its mapping targets read under `options.modelName` when\n * the caller gives one. Every model fingerprint (envelope companions,\n * parameter-group wrappers) appends this, so two unions with the same\n * members but different dispatch rules never fingerprint alike.\n */\nexport function unionShapeKey(\n  model: Model,\n  variantKey: (ref: TypeRef) => string,\n  options: { sorted?: boolean; modelName?: (name: string) => string } = {},\n): string {\n  const variants = (model.variants ?? []).map(variantKey);\n  if (options.sorted) variants.sort();\n  const members = model.variants ? `|${model.compositionKind ?? ''}${JSON.stringify(variants)}` : '';\n  return `${members}${unionRulesKey(model, options.modelName)}`;\n}\n\n/**\n * The rules a named union dispatches by, independent of its members: the\n * composition keyword and the discriminator property and mapping (entries\n * sorted by value, so key order in the document plays no part; each entry\n * JSON-encoded, so a value or target containing `=` or `,` cannot read as\n * another mapping). `''` when the model declares neither. A mapping target\n * is a model name, and is read under `modelName` when the caller gives one\n * (`readDiscriminator`).\n */\nexport function unionRulesKey(model: Model, modelName?: (name: string) => string): string {\n  const parts: string[] = [];\n  if (model.compositionKind) parts.push(`kind:${model.compositionKind}`);\n  if (model.discriminator) {\n    const { property, mapping } = readDiscriminator(model.discriminator, modelName);\n    const entries = Object.entries(mapping).sort(([a], [b]) => a.localeCompare(b));\n    parts.push(`disc:${JSON.stringify(property)}${JSON.stringify(entries)}`);\n  }\n  return parts.length > 0 ? `|${parts.join('|')}` : '';\n}\n\n/**\n * `discriminator` with every mapping target — a model name — read under\n * `modelName`; the discriminator itself when no `modelName` is given. Every\n * shape comparison that reads a model reference under a renaming\n * (`ShapeReadOptions.modelName`) reads the mapping's targets through this,\n * since a rename (`renameModelRefs`) repoints them as it repoints the\n * variants.\n */\nexport function readDiscriminator(\n  discriminator: Discriminator,\n  modelName: ((name: string) => string) | undefined,\n): Discriminator {\n  if (!modelName) return discriminator;\n  const mapping = Object.fromEntries(\n    Object.entries(discriminator.mapping).map(([value, target]) => [value, modelName(target)]),\n  );\n  return { property: discriminator.property, mapping };\n}\n","/**\n * Resolution of a Path Item written as a `$ref`.\n *\n * The bundler never inlines internal refs (`dereference: false`), so an entry\n * under `paths` or `webhooks` written as `{ $ref: '#/components/pathItems/Pets' }`,\n * or as a `$ref` to another entry of either map (`#/paths/~1pets`,\n * `#/webhooks/petAdopted`; #422), reaches extraction as a Reference Object\n * with no operations, `parameters`, `servers`, `summary` or `description` of\n * its own. This module is self-contained so both maps resolve the same way,\n * through one function: `extractOperations` resolves every `paths` entry\n * before reading any of them (issue #300), and `collectWebhookEntries`\n * resolves each `webhooks` entry.\n */\nimport { unescapePointerFragment } from '@redocly/openapi-core';\n\n/** Where a path item is read from, for diagnostics. */\nexport interface PathItemSite {\n  /**\n   * `'path'` for an entry under `paths`, `'webhook'` for one under\n   * `webhooks`, `'callback'` for the path item under one runtime expression\n   * of a Callback Object (#382).\n   */\n  kind: 'path' | 'webhook' | 'callback';\n  /**\n   * The entry's key: the path template (`/pets`), the webhook name\n   * (`petAdopted`), or, for a callback, the site down to its expression\n   * (`createPet.callbacks.petAdopted.{$request.body#/callbackUrl}`).\n   */\n  key: string;\n}\n\n/** The noun a path item site's diagnostics name it by. */\nconst SITE_NOUNS: Record<PathItemSite['kind'], string> = { path: 'Path', webhook: 'Webhook', callback: 'Callback' };\n\n/**\n * The document's own `paths` and `webhooks` maps, as written: a Path Item's\n * `$ref` may name an entry of either beside a `components/pathItems` one,\n * since OpenAPI lets it point at any Path Item Object. A map that is absent,\n * or not an object, names nothing.\n */\nexport interface DocumentPathItems {\n  paths?: unknown;\n  webhooks?: unknown;\n}\n\n/**\n * The path item an entry denotes: the entry itself, or the Path Item a\n * `$ref` chain leads to — a `components/pathItems` component, or another\n * entry of the document's `paths` or `webhooks` (`pathItemRefTarget`).\n * Fields written beside a `$ref` — on the entry or on a link of its chain —\n * are not merged in: OpenAPI leaves a field present on both sides undefined,\n * and the referenced item is taken whole so the rule does not depend on\n * which fields clash. They are reported once per entry, naming the site and\n * the keys, so a `post` written beside a ref to an item that declares only\n * `get` is not lost silently; an `x-` extension beside the `$ref` is not\n * reported, since the parser reads none off a path item. Returns\n * `undefined`, after one warning naming the site, for an entry that is not\n * an object, a `$ref` that is not a string, a ref that names no Path Item\n * (into another section, deeper into an entry, or to an `x-` extension\n * under `paths`), a dangling ref, or a cycle; the caller skips the entry. A\n * dangling ref and a cycle are only reachable when the document bypassed\n * the bundler, which fails on either before parsing (`Can't resolve $ref`;\n * `Self-referencing circular pointer`).\n */\nexport function resolvePathItemRef(\n  raw: unknown,\n  componentPathItems: Record<string, Record<string, unknown>> | undefined,\n  site: PathItemSite,\n  documentPathItems?: DocumentPathItems,\n): Record<string, unknown> | undefined {\n  const label = `${SITE_NOUNS[site.kind]} \"${site.key}\"`;\n  const seenRefs = new Set<string>();\n  /** Keys written beside a `$ref` along the chain, in document order; reported once the item is resolved. */\n  const droppedKeys: string[] = [];\n  let current: unknown = raw;\n  while (true) {\n    if (!isRecord(current)) {\n      console.warn(`[oagen] Warning: ${label} is not a path item object; skipping it.`);\n      return undefined;\n    }\n    const ref = current.$ref;\n    if (ref === undefined) {\n      if (droppedKeys.length > 0) {\n        console.warn(\n          `[oagen] Warning: ${label} has fields beside its $ref (${droppedKeys.map((key) => `\"${key}\"`).join(', ')}) ` +\n            'that are not read: the referenced path item is taken whole.',\n        );\n      }\n      return current;\n    }\n    if (typeof ref !== 'string') {\n      console.warn(`[oagen] Warning: ${label} has a non-string $ref; skipping it.`);\n      return undefined;\n    }\n    for (const key of Object.keys(current)) {\n      if (key !== '$ref' && !key.startsWith('x-') && !droppedKeys.includes(key)) droppedKeys.push(key);\n    }\n    if (seenRefs.has(ref)) {\n      console.warn(\n        `[oagen] Warning: Circular path item $ref chain starting at \"${ref}\" for ${site.kind} \"${site.key}\"; skipping it.`,\n      );\n      return undefined;\n    }\n    seenRefs.add(ref);\n    const resolved = pathItemRefTarget(ref, componentPathItems, documentPathItems);\n    if (!resolved) {\n      console.warn(\n        `[oagen] Warning: Unresolved path item $ref \"${ref}\" for ${site.kind} \"${site.key}\": ` +\n          `no matching entry under ${documentMapOf(ref) ?? 'components/pathItems'}. Skipping the ${site.kind}.`,\n      );\n      return undefined;\n    }\n    current = resolved;\n  }\n}\n\n/**\n * What one Path Item `$ref` points at: an entry of `components/pathItems`\n * (`resolveComponentRef`), or of the document's `paths` or `webhooks`, or\n * `undefined` when it points at none. A pointer into either map names one\n * entry whole: a single reference token, decoded as the bundler decodes it\n * (`unescapePointerFragment`: `~1` and `~0` unescaped, percent-escapes\n * decoded, RFC 6901 §6), so `#/paths/~1pets~1%7BpetId%7D` names\n * `/pets/{petId}`. A pointer deeper into an entry names no Path Item, and\n * nor does an `x-` key under `paths`: a specification extension, which\n * `extractOperations` never reads as a path. Shared by `resolvePathItemRef`\n * and `sentOnlyComponentNames`, which follows a path item ahead of the\n * readers.\n */\nexport function pathItemRefTarget(\n  ref: string,\n  componentPathItems: Record<string, Record<string, unknown>> | undefined,\n  documentPathItems: DocumentPathItems | undefined,\n): unknown {\n  const map = documentMapOf(ref);\n  if (!map) return resolveComponentRef(ref, 'pathItems', componentPathItems);\n  const token = ref.slice(`#/${map}/`.length);\n  const entries = documentPathItems?.[map];\n  if (token === '' || token.includes('/') || !isRecord(entries)) return undefined;\n  const key = unescapePointerFragment(token);\n  if (map === 'paths' && key.startsWith('x-')) return undefined;\n  return Object.hasOwn(entries, key) ? entries[key] : undefined;\n}\n\n/** The document map a `#/paths/…` or `#/webhooks/…` pointer names an entry of; `undefined` for any other. */\nfunction documentMapOf(ref: string): 'paths' | 'webhooks' | undefined {\n  if (ref.startsWith('#/paths/')) return 'paths';\n  if (ref.startsWith('#/webhooks/')) return 'webhooks';\n  return undefined;\n}\n\n/** The `components` sections a pointer the resolvers below follow may name. */\ntype ComponentSection =\n  | 'pathItems'\n  | 'parameters'\n  | 'requestBodies'\n  | 'responses'\n  | 'headers'\n  | 'examples'\n  | 'callbacks'\n  | 'securitySchemes';\n\n/**\n * The entry a `#/components/<section>/<name>` pointer names, with its name\n * decoded, whatever the entry holds — an object, or a value that is no\n * object (`Gone: []`, `\"oops\"`, `null`), which a caller reports as the\n * malformed entry it is rather than as missing (#617) — or `undefined` when\n * the pointer points anywhere else or at a name the section holds nothing\n * under. The whole pointer is matched, so a ref into another section never\n * names a same-named entry of this one.\n */\nexport function componentRefEntry(\n  ref: string,\n  section: ComponentSection,\n  components: Record<string, Record<string, unknown>> | undefined,\n): { name: string; value: unknown } | undefined {\n  const prefix = `#/components/${section}/`;\n  if (!ref.startsWith(prefix)) return undefined;\n  // JSON Pointer escapes (RFC 6901 §4): `~1` -> `/`, then `~0` -> `~`, in that order.\n  const name = ref.slice(prefix.length).replace(/~1/g, '/').replace(/~0/g, '~');\n  if (name === '' || components === undefined || !Object.hasOwn(components, name)) return undefined;\n  return { name, value: components[name] };\n}\n\n/**\n * The component a `#/components/<section>/<name>` pointer names, or\n * `undefined` when it points anywhere else or at nothing\n * (`componentRefEntry`). The entry is returned as the document holds it, so\n * a caller reads it only once it has checked it is an object. Shared by the\n * path item resolution above and every Reference Object resolver\n * (`followReference` in `reference-objects.ts`).\n */\nexport function resolveComponentRef(\n  ref: string,\n  section: ComponentSection,\n  components: Record<string, Record<string, unknown>> | undefined,\n): Record<string, unknown> | undefined {\n  return componentRefEntry(ref, section, components)?.value as Record<string, unknown> | undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","import type { ApiSpec, Service, Operation, HttpMethod, PaginationEndOfIteration, PaginationStrategy } from './types.js';\n\n/** Minimal snake_case converter for path segments (avoids cross-layer import). */\nfunction toSnake(s: string): string {\n  return s\n    .replace(/([a-z])([A-Z])/g, '$1_$2')\n    .replace(/[-\\s.]+/g, '_')\n    .toLowerCase();\n}\n\n/**\n * snake_case for a method name read from an `operationId` (`Operation.name`,\n * as the parser spelled it). The parser's camelCase keeps an acronym in\n * capitals (`getSSOAuthorizationUrl`, `createM2MApp`, `createJWTToken`), and\n * an `operationIdTransform` can hand the id back as written (`list-pets`,\n * `create_m2m_app`, `pets:adopt`), so a boundary is read wherever such a\n * name writes one, not only at the lower-to-upper step that is all `toSnake`\n * looks for in a path segment:\n *\n * - a lower-case letter before a capital (`createPet` → `create_pet`);\n * - a run of capitals before a capitalized word (`SSOAuthorization` →\n *   `sso_authorization`, `JWTToken` → `jwt_token`, `M2MApp` → `m2m_app`);\n * - a digit before a capitalized word (`V2Users` → `v2_users`); a digit\n *   otherwise stays in the word it was written in (`m2m`, `v2`, `oauth2`);\n * - any character that is not a letter or digit — `-`, `:`, `.`, `/`, a\n *   space, a bracket — is a separator, and a run of them is one.\n *\n * `OAuth`, which the parser's camelCase spells so and the acronym rule would\n * read as `o_auth`, is put back together (`getOAuth2Token` → `get_oauth2_token`).\n */\nexport function snakeCaseOperationName(name: string): string {\n  const words = name\n    .replace(/[^a-zA-Z0-9]+/g, '_')\n    .replace(/([a-z])([A-Z])/g, '$1_$2')\n    .replace(/([0-9])([A-Z][a-z])/g, '$1_$2')\n    .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')\n    .toLowerCase()\n    .split('_')\n    .filter((word) => word.length > 0);\n  const joined: string[] = [];\n  for (const word of words) {\n    if (joined[joined.length - 1] === 'o' && /^auth\\d*$/.test(word)) {\n      joined[joined.length - 1] = `o${word}`;\n    } else {\n      joined.push(word);\n    }\n  }\n  return joined.join('_');\n}\n\n/** One segment of a path template as readPath reads it. */\nexport interface PathSegment {\n  /** A `{param}`, a literal, or the verb of a custom method. */\n  text: string;\n  /** `true` for a verb written after a colon: `adopt` in `/pets/{petId}:adopt`. */\n  customMethod: boolean;\n}\n\n/**\n * The segments of a path template, with a custom method split off the\n * segment it is written on. An API in the Google AIP-136 style appends an\n * action to a resource or collection after a colon, so `/pets/{petId}:adopt`\n * and `/pets:batchGet` each end in one URL segment that names both a thing\n * and a verb. Every name read from a path goes through this function (or\n * pathSegments, its text alone) and sees such a segment as the two it stands\n * for — `{petId}` then `adopt`, `pets` then `batchGet` — so a custom method\n * is named like the same action written with a slash (`/pets/{petId}/adopt`,\n * `/pets/batchGet`), and the verb never lands inside a parameter word. The\n * verb is marked `customMethod` for the two readings that treat it apart\n * from a slash-written literal: it never names a service, and it counts\n * against a path's plainness when inline model names collide (see the\n * parser's serviceSegmentIndex and pathDeviation). A colon inside a\n * parameter's braces, wherever they sit in the segment, is part of its name\n * and does not split it: `file-{file_path:path}` is one segment. AIP-136\n * appends a single verb, so a custom method starts only at a segment's one\n * colon outside braces: a segment with several, such as the literal\n * `urn:pet:1`, is kept whole, and is a literal even when a parameter opens\n * it (see isParameterSegment).\n * Empty segments — a leading, trailing or doubled slash, or an empty side of\n * a colon — are dropped. The operation's `path` itself is never rewritten: it\n * is the URL the SDK requests.\n */\nexport function readPath(path: string): PathSegment[] {\n  const segments: PathSegment[] = [];\n  for (const segment of path.split('/')) {\n    const outside = blankBracedColons(segment);\n    const colon = outside.indexOf(':');\n    const single = colon !== -1 && colon === outside.lastIndexOf(':');\n    const parts = single ? [segment.slice(0, colon), segment.slice(colon + 1)] : [segment];\n    parts.forEach((part, i) => {\n      if (part) segments.push({ text: part, customMethod: i > 0 });\n    });\n  }\n  return segments;\n}\n\n/** The text of each segment readPath reads: `/pets/{petId}:adopt` → `pets`, `{petId}`, `adopt`. */\nexport function pathSegments(path: string): string[] {\n  return readPath(path).map((segment) => segment.text);\n}\n\n/**\n * Whether a segment readPath reads is a path parameter: it starts with a\n * parameter's braces (`{petId}`, `{pet:id}`, `{tag}.json`) and has no colon\n * outside braces. A segment readPath keeps whole for its several colons is\n * one literal even when a parameter opens it, as `urn:pet:1` is, so the\n * parser reads `{petId}:adopt:now` as a literal and its words reach the\n * names read from it, instead of a parameter whose tail drops out.\n */\nexport function isParameterSegment(segment: string): boolean {\n  return segment.startsWith('{') && !blankBracedColons(segment).includes(':');\n}\n\n/** A segment with the colons inside its braces blanked out, every index kept in place. */\nfunction blankBracedColons(segment: string): string {\n  return segment.replace(/\\{[^}]*\\}/g, (param) => param.replaceAll(':', ' '));\n}\n\n// ---------------------------------------------------------------------------\n// Hint types — consumer-provided overrides for operation resolution\n// ---------------------------------------------------------------------------\n\n/** Per-operation override keyed by \"METHOD /path\" (e.g. \"POST /auth/token\"). */\nexport interface OperationHint {\n  /** Override the algorithm-derived method name. */\n  name?: string;\n  /** Remount this operation to a different service/namespace (PascalCase). */\n  mountOn?: string;\n  /** Split a union-body operation into N typed wrapper methods. */\n  split?: SplitHint[];\n  /** Inject constant body defaults (e.g. { grant_type: 'password' }). */\n  defaults?: Record<string, string | number | boolean>;\n  /** Fields the SDK reads from client config at runtime (e.g. ['client_id']). */\n  inferFromClient?: string[];\n  /**\n   * Marks this operation as a URL builder rather than a real HTTP call. Emitters\n   * should generate a method that returns the constructed URL (typically as a\n   * string) without performing any I/O. Used for OAuth-style redirect endpoints\n   * such as /auth/authorize and /accounts/sessions/logout.\n   */\n  urlBuilder?: boolean;\n  /**\n   * Explicit pagination for this operation, applied by the parser (through\n   * `ParseOptions.operationHints`) rather than by `resolveOperations`. Same\n   * shape as the spec's `x-pagination` Operation Object extension; a field set\n   * here wins over the extension, which wins over name-based detection.\n   */\n  pagination?: PaginationHint;\n}\n\n/**\n * Explicit pagination for one operation — the object a spec can carry as\n * `x-pagination` on an Operation Object and that `OperationHint.pagination`\n * accepts from config. Every field is optional and layers over the\n * lower-precedence sources (config hint > `x-pagination` > detection), so\n * `{ strategy: 'page' }` alone keeps the detected `param` and `limitParam`.\n *\n * `strategy: 'none'` turns pagination off for the operation; a list envelope\n * is then kept as a plain response model rather than unwrapped. Any other\n * strategy needs a `param`, from some source, that names one of the\n * operation's query parameters. An override that fails validation — unknown\n * strategy, missing or undeclared parameter, one parameter as both `param`\n * and `limitParam`, a `pageStart` under a strategy other than `page`, a\n * `dataPath` that does not reach an array, an `endOfIteration` whose path\n * does not resolve in the primary response to a field of its kind's type,\n * malformed field — is reported with an `[oagen] Warning:` and ignored,\n * leaving the detected metadata as is.\n */\nexport interface PaginationHint {\n  strategy?: PaginationStrategy | 'none';\n  /** Query parameter that selects the page (cursor, offset, or page number). */\n  param?: string;\n  /** Query parameter that sets the page size; not the one `param` names. */\n  limitParam?: string;\n  /**\n   * First page number the API expects (`page` strategy only; set under\n   * another strategy, it makes the override unusable). Defaults to the page\n   * parameter's integer `default`, else its `minimum`, else 1.\n   */\n  pageStart?: number;\n  /**\n   * Dotted path to the data array inside the response. Resolved against the\n   * response, so the array's element type — not the wrapper — becomes\n   * `itemType`.\n   */\n  dataPath?: string;\n  /**\n   * Response field that ends the iteration. Its `path` must resolve in the\n   * primary response to a field whose type fits its `kind` — a boolean for\n   * `hasMore`, an integer or number for `totalPages` and `totalCount` — or\n   * the override is unusable.\n   */\n  endOfIteration?: PaginationEndOfIteration;\n}\n\nexport interface SplitHint {\n  /** Wrapper method name (snake_case). */\n  name: string;\n  /** The discriminated union variant model name (e.g. 'PasswordSessionAuthenticateRequest'). */\n  targetVariant: string;\n  /** Constant body fields injected by the wrapper. */\n  defaults?: Record<string, string | number | boolean>;\n  /** Fields the SDK reads from client config at runtime. */\n  inferFromClient?: string[];\n  /** Only these body fields are exposed as method params. If omitted, all non-default/non-inferred fields are exposed. */\n  exposedParams?: string[];\n  /**\n   * Subset of exposedParams that should be emitted as optional even when the\n   * variant model would otherwise mark them required (or when the variant has\n   * no addressable model, as happens for inline oneOf branches).\n   */\n  optionalParams?: string[];\n}\n\n// ---------------------------------------------------------------------------\n// Resolved output — consumed by emitters\n// ---------------------------------------------------------------------------\n\nexport interface ResolvedOperation {\n  /** The original IR operation (preserves description, params, types, etc.). */\n  operation: Operation;\n  /** The original IR service that owns this operation. */\n  service: Service;\n  /** Resolved snake_case method name (emitters convert to their convention). */\n  methodName: string;\n  /** Resolved target service/namespace (PascalCase). */\n  mountOn: string;\n  /** For split operations: one wrapper per union variant. */\n  wrappers?: ResolvedWrapper[];\n  /** Constant defaults injected into query/body at runtime (from operation-level hint). */\n  defaults: Record<string, string | number | boolean>;\n  /** Fields the SDK reads from client config at runtime (from operation-level hint). */\n  inferFromClient: string[];\n  /** Marks this operation as a URL builder; emitters should not generate an HTTP call. */\n  urlBuilder: boolean;\n}\n\nexport interface ResolvedWrapper {\n  /** Wrapper method name (snake_case). */\n  name: string;\n  /** The discriminated union variant model name. */\n  targetVariant: string;\n  /** Constant body defaults injected by the wrapper. */\n  defaults: Record<string, string | number | boolean>;\n  /** Fields read from client config at runtime. */\n  inferFromClient: string[];\n  /** Body fields exposed as method params. */\n  exposedParams: string[];\n  /** Optional body fields (not required in the variant). */\n  optionalParams: string[];\n  /** Response model name (if any). */\n  responseModelName: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// Algorithm\n// ---------------------------------------------------------------------------\n\n/**\n * Action verbs recognised at the terminal path segment.\n * When a path ends with one of these, we use it as the verb instead of\n * deriving a CRUD verb from the HTTP method.\n */\nconst ACTION_VERBS = new Set([\n  'accept',\n  'activate',\n  'authorize',\n  'challenge',\n  'check',\n  'complete',\n  'confirm',\n  'deactivate',\n  'disable',\n  'enable',\n  'enroll',\n  'generate',\n  'reactivate',\n  'resend',\n  'revoke',\n  'send',\n  'verify',\n]);\n\n/** Map HTTP method → default CRUD verb. */\nconst CRUD_VERB: Record<HttpMethod, string> = {\n  get: 'list',\n  post: 'create',\n  put: 'update',\n  patch: 'update',\n  delete: 'delete',\n  head: 'get',\n  options: 'list',\n  trace: 'list',\n};\n\n/**\n * Naive singularization: strips trailing \"s\" with common-sense exceptions.\n * Good enough for API resource nouns; not a general-purpose English stemmer.\n */\nfunction singularize(word: string): string {\n  if (word.length <= 2) return word;\n  if (word.endsWith('ies')) return word.slice(0, -3) + 'y';\n  if (\n    word.endsWith('ses') ||\n    word.endsWith('zes') ||\n    word.endsWith('xes') ||\n    word.endsWith('ches') ||\n    word.endsWith('shes')\n  ) {\n    return word.slice(0, -2);\n  }\n  if (word.endsWith('ss') || word.endsWith('us') || word.endsWith('is')) return word;\n  if (word.endsWith('s')) return word.slice(0, -1);\n  return word;\n}\n\n/**\n * Derive a snake_case method name from an operation's HTTP method and path.\n *\n * Rules:\n * 1. Strip path-param segments (`{id}`, `{slug}`, etc.); a custom method\n *    written after a colon (`{id}:verify`, `factors:enroll`) is read as its\n *    segment followed by the verb (see pathSegments), so it is named like\n *    `{id}/verify` and `factors/enroll`, and a segment kept whole for its\n *    several colons is a literal (see isParameterSegment), even one braces\n *    open and close (`{id}:a:b{ext}`)\n * 2. If the terminal segment is an action verb, use it as the verb\n * 3. Otherwise, use the CRUD verb for the HTTP method\n * 4. For GET on a collection (no trailing {id}), use \"list\"; with {id}, use \"get\"\n * 5. For POST on a resource path, if only one path param, use \"create\" singular\n * 6. Singularize the resource noun for single-resource operations\n */\nexport function deriveMethodName(op: Operation, _service: Service): string {\n  const segments = pathSegments(op.path);\n\n  // Separate static segments from param segments\n  const staticSegments: string[] = [];\n  let trailingParam = false;\n  for (const seg of segments) {\n    if (isParameterSegment(seg) && seg.endsWith('}')) {\n      trailingParam = true;\n    } else {\n      staticSegments.push(seg);\n      trailingParam = false;\n    }\n  }\n\n  if (staticSegments.length === 0) {\n    return `${CRUD_VERB[op.httpMethod] ?? 'get'}_root`;\n  }\n\n  const terminal = toSnake(staticSegments[staticSegments.length - 1]);\n\n  // Check if terminal is an action verb\n  if (ACTION_VERBS.has(terminal)) {\n    // Resource context from preceding segments\n    const context = staticSegments.slice(0, -1).filter((s) => !isParameterSegment(s));\n    const resource = context.length > 0 ? toSnake(singularize(context[context.length - 1])) : '';\n    if (resource) {\n      return `${terminal}_${resource}`;\n    }\n    return terminal;\n  }\n\n  // Determine verb from HTTP method\n  let verb = CRUD_VERB[op.httpMethod] ?? 'get';\n\n  // GET with trailing {id} → \"get\" instead of \"list\"\n  if (op.httpMethod === 'get' && trailingParam) {\n    verb = 'get';\n  }\n\n  // Build resource name from static segments.\n  // When path params separate static segments, include the penultimate static\n  // segment (singularized) as a parent-context prefix to disambiguate nested paths.\n  // e.g. /projects/{id}/roles → \"project_roles\"\n  let resource = toSnake(terminal);\n  if (staticSegments.length >= 2) {\n    const penultimate = staticSegments[staticSegments.length - 2];\n    // Check if a path param appears between the penultimate and terminal segments\n    // in the original path by finding both positions and looking for {…} between them.\n    const penIdx = segments.lastIndexOf(penultimate);\n    const termIdx = segments.lastIndexOf(staticSegments[staticSegments.length - 1]);\n    const hasParamBetween = segments.slice(penIdx + 1, termIdx).some((s) => s.startsWith('{'));\n    if (hasParamBetween) {\n      const prefix = toSnake(singularize(penultimate));\n      resource = `${prefix}_${resource}`;\n    }\n  }\n\n  // Singularize when:\n  //   * there's a trailing path param (single-resource read/update/delete), or\n  //   * the verb itself implies a single-resource operation (e.g. POST → create\n  //     always creates one item even when posted to a collection endpoint).\n  const isSingleResource = trailingParam || verb === 'create';\n  const noun = isSingleResource ? singularize(resource) : resource;\n\n  // For \"list\" verb, keep plural\n  const finalNoun = verb === 'list' ? resource : noun;\n\n  return `${verb}_${finalNoun}`;\n}\n\n/**\n * Resolve a service name to its mount target.\n *\n * Rule keys are either exact service names or trailing-`*` prefix patterns\n * (e.g. `UserManagement*`). Precedence:\n *\n *   1. An exact key always wins.\n *   2. Otherwise the wildcard with the longest prefix wins, so\n *      `UserManagementOrganizationMembership*` beats `UserManagement*`.\n *\n * Matching is plain string comparison (`startsWith`) — `*` is only recognised\n * as the final character and no regex is ever built from rule keys.\n *\n * @param name - The IR service name to resolve.\n * @param mounts - Exact-name or trailing-`*` pattern → target service mappings.\n * @returns The mount target, or `name` unchanged when no rule matches.\n */\nexport function resolveMountTarget(name: string, mounts: Record<string, string>): string {\n  const exact = mounts[name];\n  if (exact !== undefined) return exact;\n\n  let best: string | undefined;\n  let bestLen = -1;\n  for (const [pattern, target] of Object.entries(mounts)) {\n    if (!pattern.endsWith('*')) continue;\n    const prefix = pattern.slice(0, -1);\n    if (name.startsWith(prefix) && prefix.length > bestLen) {\n      best = target;\n      bestLen = prefix.length;\n    }\n  }\n  return best ?? name;\n}\n\n/**\n * Where a method name comes from when no `name` hint sets it: `path` derives\n * it from the HTTP method and path (`deriveMethodName`); `operationId` takes\n * the operation's own name when the document declares an `operationId`\n * (`Operation.name`, as the parser spelled it, in snake_case — see\n * {@link snakeCaseOperationName} for where the word boundaries are read) and\n * derives it from the path only for a path-named operation.\n */\nexport type OperationNaming = 'path' | 'operationId';\n\n/**\n * The settings {@link resolveOperations} resolves a spec's operations with —\n * the config's `operationHints`, `mountRules` and `operationNaming` — which\n * together decide the class (`mountOn`) and the method (`methodName`) that\n * `generate` writes each operation as. Every command that reads the SDK\n * `generate` writes resolves with the same settings: `compat-extract` matches\n * the SDK's callables by the names they resolve to, and `verify`'s compat\n * scope and staleness check read the classes and methods they resolve to\n * (see `specDerivedNames`, `specDerivedMethodPaths` and `detectStaleSymbols`\n * in `compat`). Under `mountRules: { Pets: 'Animals' }` and\n * `operationHints: { 'GET /pets': { name: 'list_all' } }`, `GET /pets` and\n * `GET /pets/{id}` tagged `Pets` resolve to `Animals.list_all` and\n * `Animals.get_pet`; with no settings, to `Pets.list_pets` and `Pets.get_pet`.\n */\nexport interface OperationResolution {\n  operationHints?: Record<string, OperationHint>;\n  mountRules?: Record<string, string>;\n  operationNaming?: OperationNaming;\n}\n\n/**\n * Resolve all operations in the spec, applying hints and mount rules.\n *\n * @param spec - The parsed API spec\n * @param hints - Per-operation overrides keyed by \"METHOD /path\"\n * @param mountRules - Service name → target service mappings; keys may be\n *   exact names or trailing-`*` prefix patterns (see {@link resolveMountTarget})\n * @param operationNaming - Where an unhinted method name comes from; `path`\n *   unless the consumer asks for `operationId` (see {@link OperationNaming})\n * @returns Resolved operations ready for emitter consumption\n */\nexport function resolveOperations(\n  spec: ApiSpec,\n  hints?: Record<string, OperationHint>,\n  mountRules?: Record<string, string>,\n  operationNaming: OperationNaming = 'path',\n): ResolvedOperation[] {\n  const resolved: ResolvedOperation[] = [];\n  const hintMap = hints ?? {};\n  const mounts = mountRules ?? {};\n\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      const key = `${op.httpMethod.toUpperCase()} ${op.path}`;\n      const hint = hintMap[key];\n\n      // Resolve method name: hint > algorithm, or — when the consumer asked\n      // for `operationId` naming — hint > operationId > algorithm. An operation\n      // the document named then keeps that name (as the parser spelled it, so\n      // an operationIdTransform is honoured), snake_cased word by word (the\n      // parser's camelCase writes acronyms in capitals, and a transform may\n      // keep the id's own separators); only a path-named operation gets a\n      // name derived from its method and path.\n      const fromOperationId = operationNaming === 'operationId' && op.operationId !== undefined;\n      const methodName =\n        hint?.name ?? (fromOperationId ? snakeCaseOperationName(op.name) : deriveMethodName(op, service));\n\n      // Resolve mount target: per-op hint > service mount rule > original service\n      const mountOn = hint?.mountOn ?? resolveMountTarget(service.name, mounts);\n\n      // Build wrappers for split operations\n      let wrappers: ResolvedWrapper[] | undefined;\n      if (hint?.split) {\n        wrappers = hint.split.map((sh) => ({\n          name: sh.name,\n          targetVariant: sh.targetVariant,\n          defaults: sh.defaults ?? {},\n          inferFromClient: sh.inferFromClient ?? [],\n          exposedParams: sh.exposedParams ?? [],\n          optionalParams: sh.optionalParams ?? [],\n          responseModelName: resolveResponseModelName(op),\n        }));\n      }\n\n      resolved.push({\n        operation: op,\n        service,\n        methodName,\n        mountOn,\n        wrappers,\n        defaults: hint?.defaults ?? {},\n        inferFromClient: hint?.inferFromClient ?? [],\n        urlBuilder: hint?.urlBuilder ?? false,\n      });\n    }\n  }\n\n  return resolved;\n}\n\n/** Extract the response model name from an operation (for wrapper metadata). */\nfunction resolveResponseModelName(op: Operation): string | null {\n  if (op.httpMethod === 'delete') return null;\n  const ref = op.response;\n  if (ref.kind === 'model') return ref.name;\n  if (ref.kind === 'nullable' && ref.inner.kind === 'model') return ref.inner.name;\n  return null;\n}\n\n/** One pair of distinct paths that resolved to the same `mountOn.methodName`. */\nexport interface ResolvedMethodCollision {\n  /** The shared `Service.method_name` key both paths resolved to. */\n  key: string;\n  first: { httpMethod: string; path: string };\n  second: { httpMethod: string; path: string };\n}\n\n/**\n * Find every pair of distinct paths that resolve to the same SDK method name.\n *\n * Emitters already refuse to generate on a collision, but they only run inside\n * the per-language build matrix — so a spec addition that collides fails every\n * matrix job minutes in, with no cheap way to catch it first. Surfacing the same\n * check from `oagen resolve` turns that into a seconds-long precheck.\n *\n * Returns every collision rather than throwing on the first, so a spec that\n * introduces several is fixed in one pass instead of one CI round-trip each.\n *\n * Callers that generate a subset of services must filter to the operations they\n * will actually emit before calling this: a collision between two out-of-scope\n * paths is not that run's problem.\n */\nexport function findResolvedMethodCollisions(resolved: ResolvedOperation[]): ResolvedMethodCollision[] {\n  const seen = new Map<string, { httpMethod: string; path: string }>();\n  const collisions: ResolvedMethodCollision[] = [];\n\n  for (const r of resolved) {\n    const key = `${r.mountOn}.${r.methodName}`;\n    const current = { httpMethod: r.operation.httpMethod.toUpperCase(), path: r.operation.path };\n    const existing = seen.get(key);\n\n    // The same path AND method twice is one operation seen through two\n    // services, not a collision. Both have to match: two *different* methods\n    // on one path (`GET /x` and `POST /x` hinted to the same name) are\n    // distinct operations competing for a single SDK method, and a path-only\n    // comparison accepts them silently.\n    if (existing && (existing.path !== current.path || existing.httpMethod !== current.httpMethod)) {\n      collisions.push({ key, first: existing, second: current });\n      continue;\n    }\n    if (!existing) seen.set(key, current);\n  }\n\n  return collisions;\n}\n","import type { ServerEntry, ServerVariable } from './types.js';\n\n/** Outcome of filling a server URL template with its variables' defaults. */\nexport interface ResolvedServerUrl {\n  /** The template with every placeholder that names a declared variable replaced by that variable's `default`. */\n  url: string;\n  /**\n   * Placeholder names still in `url` because the server declares no variable\n   * for them, in order of first appearance and without repeats.\n   */\n  unresolved: string[];\n}\n\n/**\n * Fill a server URL template with its variables' defaults.\n *\n * Each `{name}` is replaced by `variables[name].default`; a placeholder with no\n * declared variable is kept verbatim and reported in `unresolved`. The same\n * variable may appear more than once, and a declared variable the template\n * never mentions is simply unused (`serverUrlPlaceholders` lists the names the\n * template does mention). The substituted value is spliced in as text and not\n * scanned again, so a default such as `{other}` cannot trigger a second\n * substitution. A `{` with no closing `}`, an empty `{}`, and a `{` that opens\n * another `{` before closing are all literal text.\n *\n * Plain string scanning only: no pattern is built from the variable names, so\n * a name containing `.`, `+` or any other character is matched as written.\n *\n * The parser uses this for `ApiSpec.baseUrl`; an emitter that offers every\n * server (an environment picker, say) can resolve each `spec.servers[i]` the\n * same way instead of reading the OpenAPI document again.\n */\nexport function resolveServerUrl(server: Pick<ServerEntry, 'url' | 'variables'>): ResolvedServerUrl {\n  const template = server.url;\n  const variables = server.variables ?? {};\n  const unresolved: string[] = [];\n  let url = '';\n  let cursor = 0;\n\n  for (const { name, start, end } of scanPlaceholders(template)) {\n    url += template.slice(cursor, start);\n    // Own keys only: a placeholder named `constructor` or `__proto__` resolves\n    // when the document declares that variable (the parser defines it as an own\n    // data property), never to Object.prototype's member of that name.\n    if (Object.hasOwn(variables, name)) {\n      url += variables[name].default;\n    } else {\n      url += template.slice(start, end);\n      if (!unresolved.includes(name)) unresolved.push(name);\n    }\n    cursor = end;\n  }\n\n  url += template.slice(cursor);\n  return { url, unresolved };\n}\n\n/**\n * The placeholder names a server URL template references, in order of first\n * appearance and without repeats: `['region', 'port']` for\n * `https://{region}.example.com:{port}/{region}`. Read from the template\n * alone, by the same scan as `resolveServerUrl` (so the same literal-brace\n * rules apply), whether or not the server declares a variable for each name.\n *\n * A declared variable whose name is not listed here is one the template never\n * references: its default and its allowed values cannot reach any resolved\n * URL. The differ classifies a change to such a variable as additive on that\n * basis; an emitter that exposes a server's variables can use it to offer\n * only the ones that take effect.\n */\nexport function serverUrlPlaceholders(url: string): string[] {\n  const names: string[] = [];\n  for (const { name } of scanPlaceholders(url)) {\n    if (!names.includes(name)) names.push(name);\n  }\n  return names;\n}\n\n/** One `{name}` in a server URL template: `start` is the index of its `{`, `end` the index just past its `}`. */\ninterface Placeholder {\n  name: string;\n  start: number;\n  end: number;\n}\n\n/**\n * Walk a template's placeholders left to right. A `{` with no closing `}`\n * ends the scan (the rest is literal); an empty `{}` and a `{` that opens\n * another `{` before closing are literal, and scanning resumes right after\n * that `{` so a well-formed placeholder later in the text is still found.\n * The one reading of braces every caller shares, so `resolveServerUrl`,\n * `serverUrlPlaceholders` and `normalizeServerUrl` (through `templateUnits`)\n * cannot disagree about what counts as one.\n */\nfunction* scanPlaceholders(template: string): Generator<Placeholder> {\n  let cursor = 0;\n  while (cursor < template.length) {\n    const open = template.indexOf('{', cursor);\n    if (open === -1) break;\n    const close = template.indexOf('}', open + 1);\n    if (close === -1) break;\n\n    const name = template.slice(open + 1, close);\n    if (name === '' || name.includes('{')) {\n      cursor = open + 1;\n      continue;\n    }\n\n    yield { name, start: open, end: close + 1 };\n    cursor = close + 1;\n  }\n}\n\n/**\n * One unit of a server URL template: a single literal character, or a whole\n * `{name}` placeholder, which is never split, folded or decoded.\n */\ninterface TemplateUnit {\n  text: string;\n  placeholder: boolean;\n}\n\n/**\n * Split a server URL template into literal characters and `{name}`\n * placeholders, read by `scanPlaceholders` so the literal-brace rules are\n * the ones `resolveServerUrl` applies. A literal `{` from an unclosed, empty\n * or reopened brace is a character like any other.\n */\nfunction templateUnits(template: string): TemplateUnit[] {\n  const units: TemplateUnit[] = [];\n  const literal = (text: string): void => {\n    for (const char of text) units.push({ text: char, placeholder: false });\n  };\n  let cursor = 0;\n\n  for (const { start, end } of scanPlaceholders(template)) {\n    literal(template.slice(cursor, start));\n    units.push({ text: template.slice(start, end), placeholder: true });\n    cursor = end;\n  }\n\n  literal(template.slice(cursor));\n  return units;\n}\n\n/** The port each scheme uses when the URL names none (RFC 9110 §4.2, RFC 6455 §3). */\nconst DEFAULT_PORTS: Readonly<Record<string, number>> = { http: 80, https: 443, ws: 80, wss: 443 };\n\n/**\n * A server URL in the form two equivalent spellings share, for comparing\n * server URLs — templates as written and resolved URLs alike. The IR never\n * stores it: `ServerEntry.url` and `ApiSpec.baseUrl` stay as written, and\n * the differ reports every URL as written in the document that declares it.\n *\n * The rules are those of RFC 3986 §6.2.2 (syntax-based) and §6.2.3\n * (scheme-based normalization) that apply to a base URL:\n *\n * - The scheme and the host are case-insensitive and are lower-cased\n *   (`HTTPS://PETS.example.com` and `https://pets.example.com` are one\n *   server). Userinfo, path, query and fragment are case-sensitive and keep\n *   their case, so `/V1` and `/v1` stay two servers.\n * - A port that is empty or is the scheme's default is dropped\n *   (`https://pets.example.com:443`, `https://pets.example.com:` and\n *   `https://pets.example.com` are one server; `http` and `ws` default to\n *   80, `https` and `wss` to 443). Any other port stays.\n * - An empty path after a wholly literal authority is `/`\n *   (`https://pets.example.com` and `https://pets.example.com/` are one\n *   server). Nothing else is done to the path: `/v1` and `/v1/` stay two\n *   servers, and dot-segments are kept.\n * - In a percent-encoded octet the hex digits are upper-cased (`%2f` is\n *   `%2F`) and one that encodes an unreserved character — a letter, a digit,\n *   `-`, `.`, `_` or `~` — is decoded (`%7E` is `~`). Every other octet is\n *   kept encoded, and a `%` not followed by two hex digits is literal.\n *\n * A `{name}` placeholder is kept exactly as written wherever it sits, so a\n * variable name is never case-folded (`{Region}` and `{region}` are different\n * variables) and a template is never confused with what it resolves to\n * (`https://{region}.api.example.com` and `https://eu.api.example.com` stay\n * two servers). A placeholder also ends what can be known about the URL's\n * structure: its value may carry any delimiter — `@` (which makes the text\n * before it in the authority a username), `:` and a port, `/` and a path,\n * `://` and a whole URL — so nothing from the first placeholder on is folded,\n * and a component is folded only when it is complete before that point: the\n * scheme when its `:` comes first, the authority when its end (`/`, `?`, `#`\n * or the end of the template) comes first. So `HTTPS://API.example.com/{v}`\n * is `https://api.example.com/{v}` and `HTTPS://API.example.com{basePath}`\n * is `https://API.example.com{basePath}`, while `…{basePath}` and\n * `…{basePath}/`, `https://{host}:443/v2` and `https://{host}/v2`,\n * `https://USER{suffix}/v1` and `https://user{suffix}/v1` (a `suffix` of\n * `@api.example.com` makes `USER` a username), and `{prefix}://api.example.com`\n * and `{prefix}://api.example.com/` (a `prefix` of\n * `https://gateway.example.com/path` makes the rest a path) all stay two\n * servers. From the first placeholder on not even percent-encoding is\n * folded, and neither is it in an authority the placeholder sits in: a value\n * may put the text in a scheme or a port, where `%` has no meaning\n * (`{scheme}%73://…` and `{scheme}s://…`, `…{x}%34%34%33` and `…{x}443`,\n * `https://api.example.com:4{port}` and `https://api.example.com:%34{port}`,\n * `{scheme}://host:%34%34%33` and `{scheme}://host:443` stay two servers),\n * or end in a `%` that joins with the text after it into a different octet\n * (`https://{host}/{x}7e` and `https://{host}/{x}%37e` stay two servers).\n * Percent-encoding before the first placeholder in a path, query or\n * fragment is folded, since a complete octet there is a complete octet under\n * every value. Every folding therefore applies to text whose part and bytes\n * no variable value can change, and two templates that come out as one\n * string resolve to one URL under every value of their variables. Not folded at\n * all: dot-segments (`/v1/../v2` is compared as written) and\n * internationalised host names (`bücher.example.com` and\n * `xn--bcher-kva.example.com` are two hosts). A relative reference (`/v1`,\n * `//api.example.com/v1`) goes through the same rules from wherever its\n * syntax starts.\n */\nexport function normalizeServerUrl(url: string): string {\n  const units = templateUnits(url);\n  // A placeholder's value may carry any delimiter, so it can change which\n  // part every later character belongs to and, through a `@`, which part\n  // the text before it in its authority belongs to; it may also end in a `%`\n  // or a partial escape that joins with the text after it into a different\n  // percent-encoded octet. So from the first placeholder on nothing is\n  // folded, not even percent-encoding, and a component before it is folded\n  // only when it is complete before that point. Percent-encoding before the\n  // first placeholder in a path, query or fragment is folded: a complete\n  // octet there is a complete octet under every value.\n  const firstPlaceholder = units.findIndex((unit) => unit.placeholder);\n  const literalEnd = firstPlaceholder === -1 ? units.length : firstPlaceholder;\n  /** Units `from` to `to` as written. */\n  const verbatim = (from: number, to: number): string => render(units.slice(from, to), (text) => text);\n  /** Units `from` to `to`: percent-encoding folded before the first placeholder, as written from it on. */\n  const emit = (from: number, to: number): string =>\n    render(units.slice(from, Math.min(to, literalEnd)), normalizePercentEncoding) +\n    verbatim(Math.max(from, literalEnd), to);\n  let out = '';\n  let cursor = 0;\n\n  // Scheme: the units before the first `:`, provided every character among\n  // them may appear in a scheme and the first one is a letter (RFC 3986\n  // §3.1); a `/`, `?`, `#` or `@` before any `:` makes the URL a relative\n  // reference with no scheme. Folded only when that `:` comes before the\n  // first placeholder: a scheme with a placeholder in it (`{prefix}://…`)\n  // may resolve to anything, so the whole template is kept as written.\n  const schemeEnd = schemeLength(units);\n  let scheme: string | undefined;\n  if (schemeEnd !== undefined && schemeEnd >= literalEnd) return verbatim(0, units.length);\n  if (schemeEnd !== undefined) {\n    scheme = render(units.slice(0, schemeEnd), (text) => text.toLowerCase());\n    out += scheme + ':';\n    cursor = schemeEnd + 1;\n  }\n\n  // Authority: after `//`, up to the first `/`, `?` or `#`. Folded only when\n  // that end comes before the first placeholder: a placeholder inside the\n  // authority may resolve to a host suffix, a port, a path, or a `@` that\n  // makes the text before it a username, so an authority with one is kept\n  // as written from its `//` on — the text before the placeholder included,\n  // which may be a port (`:4{port}`), where `%` is not decoded — and gets no\n  // `/` for an empty path.\n  let literalAuthority = false;\n  if (isLiteral(units[cursor], '/') && isLiteral(units[cursor + 1], '/')) {\n    const start = cursor + 2;\n    cursor = start;\n    while (cursor < units.length && !isLiteral(units[cursor], '/', '?', '#')) cursor++;\n    literalAuthority = cursor <= literalEnd;\n    out += '//' + (literalAuthority ? normalizeAuthority(units.slice(start, cursor), scheme) : verbatim(start, cursor));\n  }\n\n  // Path: up to the first `?` or `#`; `/` when a wholly literal authority is\n  // followed by none (`…{basePath}` and `…{basePath}/` stay two templates).\n  const pathStart = cursor;\n  while (cursor < units.length && !isLiteral(units[cursor], '?', '#')) cursor++;\n  const path = emit(pathStart, cursor);\n  out += literalAuthority && path === '' ? '/' : path;\n\n  // Query and fragment: kept as written, percent-encoding aside.\n  out += emit(cursor, units.length);\n  return out;\n}\n\n/** The number of units before the `:` that ends a scheme, or `undefined` when the URL has none. */\nfunction schemeLength(units: TemplateUnit[]): number | undefined {\n  for (let i = 0; i < units.length; i++) {\n    const unit = units[i];\n    if (unit.placeholder) continue;\n    if (unit.text === ':') return i > 0 ? i : undefined;\n    const char = unit.text;\n    const first = i === 0;\n    if (isAlpha(char) || (!first && (isDigit(char) || char === '+' || char === '-' || char === '.'))) continue;\n    return undefined;\n  }\n  return undefined;\n}\n\n/**\n * A wholly literal authority with userinfo kept as written, the host\n * lower-cased and a port that is empty or the scheme's default dropped. The\n * port is what follows the last `:` after any `]` that closes an IP literal,\n * so the colons inside `[2001:db8::1]` are never read as one.\n */\nfunction normalizeAuthority(units: TemplateUnit[], scheme: string | undefined): string {\n  const at = units.findIndex((unit) => isLiteral(unit, '@'));\n  const hostUnits = units.slice(at + 1);\n  let closeBracket = -1;\n  for (let i = hostUnits.length - 1; i >= 0; i--) {\n    if (isLiteral(hostUnits[i], ']')) {\n      closeBracket = i;\n      break;\n    }\n  }\n  let colon = -1;\n  for (let i = hostUnits.length - 1; i > closeBracket; i--) {\n    if (isLiteral(hostUnits[i], ':')) {\n      colon = i;\n      break;\n    }\n  }\n\n  if (colon === -1) return foldUserinfoAndHost(units);\n\n  const port = render(hostUnits.slice(colon + 1), (text) => text);\n  const withoutPort = foldUserinfoAndHost(units.slice(0, at + 1 + colon));\n  if (port === '' || isDefaultPort(port, scheme)) return withoutPort;\n  return withoutPort + ':' + port;\n}\n\n/** Userinfo — up to the first `@` — as written and the host lower-cased, percent-encoding normalised in both. */\nfunction foldUserinfoAndHost(units: TemplateUnit[]): string {\n  const at = units.findIndex((unit) => isLiteral(unit, '@'));\n  const userinfo = at === -1 ? '' : render(units.slice(0, at), normalizePercentEncoding) + '@';\n  return userinfo + render(units.slice(at + 1), foldHost);\n}\n\n/**\n * A host lower-cased outside its percent-encoded octets, which keep their\n * upper-cased hex digits (`p%C3%A9ts.EXAMPLE.com` is `p%C3%A9ts.example.com`);\n * an octet that encodes a letter is decoded first and so lower-cased too\n * (`%41PI` is `api`).\n */\nfunction foldHost(text: string): string {\n  const encoded = normalizePercentEncoding(text);\n  let out = '';\n  for (let i = 0; i < encoded.length; i++) {\n    const char = encoded[i];\n    if (char === '%' && i + 2 < encoded.length && isHexDigit(encoded[i + 1]) && isHexDigit(encoded[i + 2])) {\n      out += encoded.slice(i, i + 3);\n      i += 2;\n    } else {\n      out += char.toLowerCase();\n    }\n  }\n  return out;\n}\n\n/** Whether a literal port, read as a decimal number, is the one `scheme` implies. */\nfunction isDefaultPort(port: string, scheme: string | undefined): boolean {\n  if (scheme === undefined || !Object.hasOwn(DEFAULT_PORTS, scheme)) return false;\n  for (const char of port) if (!isDigit(char)) return false;\n  return Number(port) === DEFAULT_PORTS[scheme];\n}\n\n/**\n * Upper-case the hex digits of every percent-encoded octet and decode the\n * ones that encode an unreserved character (RFC 3986 §6.2.2.1–§6.2.2.2).\n */\nfunction normalizePercentEncoding(text: string): string {\n  let out = '';\n  for (let i = 0; i < text.length; i++) {\n    const char = text[i];\n    if (char === '%' && i + 2 < text.length && isHexDigit(text[i + 1]) && isHexDigit(text[i + 2])) {\n      const hex = text.slice(i + 1, i + 3);\n      const decoded = String.fromCharCode(Number.parseInt(hex, 16));\n      out += isUnreserved(decoded) ? decoded : '%' + hex.toUpperCase();\n      i += 2;\n    } else {\n      out += char;\n    }\n  }\n  return out;\n}\n\n/** Join units back into text, passing each run of literal characters through `transform` and every placeholder as written. */\nfunction render(units: TemplateUnit[], transform: (text: string) => string): string {\n  let out = '';\n  let run = '';\n  for (const unit of units) {\n    if (unit.placeholder) {\n      out += transform(run) + unit.text;\n      run = '';\n    } else {\n      run += unit.text;\n    }\n  }\n  return out + transform(run);\n}\n\n/** Whether `unit` is a literal character that is one of `chars`. */\nfunction isLiteral(unit: TemplateUnit | undefined, ...chars: string[]): boolean {\n  return unit !== undefined && !unit.placeholder && chars.includes(unit.text);\n}\n\nfunction isAlpha(char: string): boolean {\n  return (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z');\n}\n\nfunction isDigit(char: string): boolean {\n  return char >= '0' && char <= '9';\n}\n\nfunction isHexDigit(char: string): boolean {\n  return isDigit(char) || (char >= 'a' && char <= 'f') || (char >= 'A' && char <= 'F');\n}\n\n/** RFC 3986 §2.3: a character that needs no percent-encoding anywhere in a URI. */\nfunction isUnreserved(char: string): boolean {\n  return isAlpha(char) || isDigit(char) || char === '-' || char === '.' || char === '_' || char === '~';\n}\n\n/**\n * Whether two server lists are the same, entry for entry.\n *\n * Structural: the same length, and at each position the same `url` — up to\n * `normalizeServerUrl`, so a scheme or host that differs only in case, a\n * default port written or not, and a trailing `/` after a bare authority\n * are the same URL, and that form folds nothing a placeholder's value could\n * change, so two entries it calls equal resolve to one URL under every value\n * of their variables, which `resolveAlike` checks value by value all the\n * same — and the same `description` and the same `variables`:\n * the same names, each with the same `default`, the same `enum` (same values\n * in the same order) and the same `description`, all compared as written.\n * Position matters because `servers[0]` is the one a client defaults to. A\n * key that is absent and one set to `undefined` compare equal. Variables are\n * compared by own key only, so one named `__proto__` or `constructor` is\n * compared like any other and never read off `Object.prototype`.\n *\n * The parser uses this to decide whether an operation's effective servers\n * differ from the document's (`Operation.servers` is set only when they do):\n * the IR carries exactly what the document says. The differ's\n * `serversChanged` deliberately uses a looser rule — descriptions, enum order\n * and position ignored, matching the document-level diff — so a description\n * edit sets the field without being reported as a change.\n */\nexport function serverListsEqual(a: readonly ServerEntry[], b: readonly ServerEntry[]): boolean {\n  if (a.length !== b.length) return false;\n  return a.every((entry, i) => serverEntriesEqual(entry, b[i]));\n}\n\nfunction serverEntriesEqual(a: ServerEntry, b: ServerEntry): boolean {\n  if (normalizeServerUrl(a.url) !== normalizeServerUrl(b.url) || a.description !== b.description) return false;\n  const aVariables = a.variables ?? {};\n  const bVariables = b.variables ?? {};\n  const names = Object.keys(aVariables);\n  if (names.length !== Object.keys(bVariables).length) return false;\n  if (\n    !names.every((name) => Object.hasOwn(bVariables, name) && serverVariablesEqual(aVariables[name], bVariables[name]))\n  ) {\n    return false;\n  }\n  // `normalizeServerUrl` folds nothing a placeholder's value could change, so\n  // equal forms with equal variables resolve to one URL under every value;\n  // checked all the same, value by value, so the guarantee does not rest on\n  // that reading alone.\n  return resolveAlike(a, b);\n}\n\n/**\n * Whether every allowed substitution resolves `a` and `b` to the same URL up\n * to `normalizeServerUrl`: the defaults, then each enum value of each\n * variable in turn with every other variable at its default. Both entries\n * are resolved with `a`'s variables, which the caller has found equal to\n * `b`'s. Substituted maps are built with `Object.fromEntries`, so a variable\n * named `__proto__` stays an own key.\n */\nfunction resolveAlike(a: ServerEntry, b: ServerEntry): boolean {\n  const variables = a.variables ?? {};\n  const substitutions: Array<Record<string, ServerVariable>> = [variables];\n  for (const [name, variable] of Object.entries(variables)) {\n    for (const value of variable.enum ?? []) {\n      if (value === variable.default) continue;\n      substitutions.push(\n        Object.fromEntries(\n          Object.entries(variables).map(([other, v]) => [other, other === name ? { ...v, default: value } : v]),\n        ),\n      );\n    }\n  }\n  return substitutions.every(\n    (vars) =>\n      normalizeServerUrl(resolveServerUrl({ url: a.url, variables: vars }).url) ===\n      normalizeServerUrl(resolveServerUrl({ url: b.url, variables: vars }).url),\n  );\n}\n\nfunction serverVariablesEqual(a: ServerVariable, b: ServerVariable): boolean {\n  if (a.default !== b.default || a.description !== b.description) return false;\n  const aEnum = a.enum ?? [];\n  const bEnum = b.enum ?? [];\n  return aEnum.length === bEnum.length && aEnum.every((value, i) => value === bEnum[i]);\n}\n\n/** The server OpenAPI gives a document that declares none: a single entry at `/`. */\nconst DEFAULT_SERVER_URL = '/';\n\n/**\n * Whether a server entry is OpenAPI's default server: its `url` is `/`.\n * Neither its `description` nor its `variables` count. The default server\n * has neither; a description changes nothing about where a request goes; and\n * `/` contains no placeholder (`serverUrlPlaceholders('/')` is empty), so a\n * variable declared on it is never referenced and cannot change where it\n * points either (#292). A template that merely resolves to `/` (a referenced\n * variable whose default is `/`) is a template, not the default server.\n */\nexport function isDefaultServerEntry(server: ServerEntry): boolean {\n  // `/` is its own RFC 3986 form; read through `normalizeServerUrl` so that\n  // every server URL comparison in this module goes through one function.\n  return normalizeServerUrl(server.url) === DEFAULT_SERVER_URL;\n}\n\n/**\n * Whether a server list means OpenAPI's default server. OpenAPI gives a\n * document with no `servers`, or `servers: []`, a single server at `/`; a\n * document that writes that server out declares nothing beyond it, and\n * neither does one that writes it out twice. So `undefined`, an empty list,\n * and a list whose every entry is the default by `isDefaultServerEntry` are\n * all the default. A list with any other entry is not, wherever `/` sits in\n * it, because position decides the default host.\n *\n * The parser asks this of an operation's list and the document's: both at\n * the default means the operation inherits (`Operation.servers`, #291). The\n * differ asks it to tell the `/` a document is only implied to have, which\n * is never reported as added or removed, from one it lists beside another\n * server, which is.\n */\nexport function isDefaultServerList(servers: readonly ServerEntry[] | undefined): boolean {\n  return !servers || servers.every(isDefaultServerEntry);\n}\n\n/**\n * The servers a document is served from: its list as written (the same\n * array, not a copy) when it declares anything beyond the default, else\n * OpenAPI's default server, a single `{ url: '/' }`. A document without\n * `servers`, one with `servers: []`, one whose only server is `/`, and one\n * that writes `/` out twice all come out as `[{ url: '/' }]` (a description\n * on the entry is not carried: the default server has none), while\n * `[/, host]` stays `[/, host]`, because there `/` is a server the document\n * lists, not one it is implied to have. The differ matches servers on this,\n * so the three spellings of the default pair with each other and with a `/`\n * listed beside a host.\n */\nexport function serversOrDefault(servers: readonly ServerEntry[] | undefined): readonly ServerEntry[] {\n  return servers && !isDefaultServerList(servers) ? servers : [{ url: DEFAULT_SERVER_URL }];\n}\n\n/**\n * A document's default address beyond OpenAPI's default: `''` when\n * `baseUrl` is `''` (the parser's value for a document with no server) or\n * `/` (the resolved address of the default server, written out or not),\n * else `baseUrl` as given. The differ compares `base-url-changed` on this,\n * so the three spellings of the default share one address and a document\n * whose first server merely resolves to `/` has not moved from it. Any other\n * `baseUrl` — a host, or `/v1` — is compared as written, even with no\n * `servers` beside it (an IR built by hand, which the parser never\n * produces).\n */\nexport function baseUrlBeyondDefault(baseUrl: string): string {\n  // Read through `normalizeServerUrl` like every other server URL comparison\n  // in this module; `/` is its own form, so only `/` itself is the default.\n  return normalizeServerUrl(baseUrl) === DEFAULT_SERVER_URL ? '' : baseUrl;\n}\n","/**\n * How one parameter is told apart from another on an operation, a webhook or\n * a response. OpenAPI identifies a parameter by its `name` and its `in`\n * location — a path `id` may sit beside a query `id` — so the two are\n * compared together. Header names are case-insensitive (RFC 9110 §5.1), so a\n * header's name is folded before it is compared; path, query and cookie\n * names are case-sensitive and compared as written. The IR keeps every name\n * as written: only the comparison folds. Every place that asks whether two\n * parameters are the same one — the parser merging a path item's parameters\n * with an operation's, the parser reading a response's `headers` map, the\n * differ pairing a parameter across two documents — goes through this\n * module, so one rule answers it.\n */\n\n/** Where a parameter lives, as OpenAPI's `in` names it. */\nexport type ParameterLocation = 'path' | 'query' | 'header' | 'cookie';\n\n/**\n * A header name as it is compared: lower-cased, since RFC 9110 §5.1 makes\n * header names case-insensitive (`X-Request-Id` and `x-request-id` name one\n * header). A header name is an ASCII token, so plain case folding is exact.\n * It is also the name the parser mints a header's inline model or enum\n * from (`X-RateLimit-Policy` → `…XRatelimitPolicy`, whatever its case), so\n * two spellings of one header type the same way; the IR's `name` stays as\n * written.\n */\nexport function foldHeaderName(name: string): string {\n  return name.toLowerCase();\n}\n\n/**\n * A parameter name as it is compared at `location`: a header's is folded by\n * `foldHeaderName`; a path, query or cookie name is case-sensitive and kept\n * as written (`Limit` and `limit` are two query parameters). It is also the\n * name the parser mints a parameter's inline model or enum from, so a\n * header's type name does not move with the header's case.\n */\nexport function foldParameterName(location: ParameterLocation, name: string): string {\n  return location === 'header' ? foldHeaderName(name) : name;\n}\n\n/**\n * The identity of a parameter within one operation or webhook:\n * `location:name`, the name folded by `foldParameterName`. Two parameters\n * with one key are one parameter — the parser lets the later declaration\n * (an operation's over its path item's) replace the earlier, and the differ\n * pairs the old and new declarations rather than reporting a removal beside\n * an addition.\n */\nexport function parameterKey(location: ParameterLocation, name: string): string {\n  return `${location}:${foldParameterName(location, name)}`;\n}\n","import { toPascalCase } from './naming.js';\n\n/** One `name=value` parameter of a media type, the name lower-cased and the value decoded. */\nexport interface MediaTypeParameter {\n  name: string;\n  value: string;\n}\n\n/** A media type read into its essence and its parameters (`parseMediaType`). */\nexport interface ParsedMediaType {\n  /** `type/subtype`, trimmed and lower-cased. */\n  essence: string;\n  /** The parameters in document order, names lower-cased, quoted values decoded. */\n  parameters: MediaTypeParameter[];\n}\n\n/**\n * A media type read as RFC 9110 §8.3.1 writes it: `type/subtype`, then\n * `;`-separated `name=value` parameters whose value is a token or a\n * quoted-string. A `;` inside a quoted-string does not end a parameter\n * (`profile=\"https://example.com/a;b\"` is one parameter), a backslash inside\n * one escapes the next character (`\"say \\\"hi\\\"\"` reads `say \"hi\"`), and the\n * quotes are not part of the value. The essence is trimmed and lower-cased,\n * and so is every parameter name (they are case-insensitive); a value keeps\n * its case, since whether it matters depends on the parameter. A parameter\n * written without `=` has the empty value, an empty segment (`a;;b`) is\n * skipped, and a quoted-string nobody closes runs to the end of the key.\n * This is the one reader every media-type question goes through — the\n * essence, the model-name fragment and the differ's comparison of\n * parameters — so they agree on where a parameter ends.\n */\nexport function parseMediaType(contentType: string): ParsedMediaType {\n  const segments: string[] = [];\n  let segment = '';\n  let quoted = false;\n  for (let i = 0; i < contentType.length; i++) {\n    const char = contentType[i];\n    if (quoted) {\n      if (char === '\\\\' && i + 1 < contentType.length) {\n        segment += char + contentType[++i];\n        continue;\n      }\n      if (char === '\"') quoted = false;\n      segment += char;\n      continue;\n    }\n    if (char === ';') {\n      segments.push(segment);\n      segment = '';\n      continue;\n    }\n    if (char === '\"') quoted = true;\n    segment += char;\n  }\n  segments.push(segment);\n  const [first = '', ...rest] = segments;\n  const parameters: MediaTypeParameter[] = [];\n  for (const raw of rest) {\n    const parameter = raw.trim();\n    if (parameter.length === 0) continue;\n    const separator = parameter.indexOf('=');\n    const name = (separator === -1 ? parameter : parameter.slice(0, separator)).trim().toLowerCase();\n    const value = separator === -1 ? '' : unquote(parameter.slice(separator + 1).trim());\n    parameters.push({ name, value });\n  }\n  return { essence: first.trim().toLowerCase(), parameters };\n}\n\n/** A parameter value decoded: a quoted-string without its quotes and with its escapes resolved, a token as written. */\nfunction unquote(raw: string): string {\n  if (!raw.startsWith('\"')) return raw;\n  let value = '';\n  for (let i = 1; i < raw.length; i++) {\n    const char = raw[i];\n    if (char === '\\\\' && i + 1 < raw.length) {\n      value += raw[++i];\n      continue;\n    }\n    if (char === '\"') break;\n    value += char;\n  }\n  return value;\n}\n\n/**\n * A media type's essence — `type/subtype` without parameters, trimmed and\n * lower-cased (RFC 9110 §8.3.1): `application/json; charset=utf-8`,\n * `APPLICATION/JSON` and ` application/json ` are all `application/json`.\n * The essence is what decides how a request or response body is typed and\n * encoded; the content keys themselves stay as written wherever the IR\n * carries them (`responseContentTypes`, `contentTypes`).\n */\nexport function mediaTypeEssence(contentType: string): string {\n  return parseMediaType(contentType).essence;\n}\n\n/**\n * Whether a media type is `application/json` itself, by essence\n * (`application/json; charset=utf-8`, `APPLICATION/JSON`): the JSON\n * spelling a request body pick and a response body read prefer over a\n * `+json` type declared beside it.\n */\nexport function isPlainJsonMediaType(contentType: string): boolean {\n  return mediaTypeEssence(contentType) === 'application/json';\n}\n\n/**\n * Whether a media type is JSON by essence: `application/json` itself, or any\n * type with the `+json` structured-syntax suffix (`application/vnd.api+json`,\n * `application/merge-patch+json`, `application/problem+json`). The one rule\n * for what a JSON body is, on a request and on a response alike; which JSON\n * spelling wins when several are declared is `isPlainJsonMediaType`'s.\n */\nexport function isJsonMediaType(contentType: string): boolean {\n  const essence = mediaTypeEssence(contentType);\n  return essence === 'application/json' || essence.endsWith('+json');\n}\n\n/**\n * A media type's parameters other than `charset`, in one form whatever the\n * spelling: each parameter as `parseMediaType` reads it — name lower-cased,\n * quoted value decoded, so a `;` inside the quotes is part of the value and\n * `profile=\"print\"` is `profile=print` — as `[name, value]` pairs sorted by\n * name, then value. So `application/pdf; version=1.7` reads\n * `[['version', '1.7']]`, `text/html; Charset=UTF-8` and `text/html` both\n * read `[]`, and `; a=1; b=2` is `; b=2 ;a=1`. The pairs stay structured\n * (compared JSON-encoded, never joined into one string), so `title=\"report;\n * version=2\"` — one parameter — and `title=report; version=2` — two — are\n * different parameters. `charset` is left out because it never selects\n * another representation of a JSON or text body (RFC 8259 §8.1 has no\n * charset for JSON at all); any other parameter — `version`, `profile` —\n * may. The one reading of parameters `oagen diff` compares two keys by (what\n * `reparameterized` reports) and a secondary body's model is named by\n * (`mediaTypeNameFragment`), so the two agree on what changed a key.\n */\nexport function mediaTypeParameters(contentType: string): Array<[string, string]> {\n  return parseMediaType(contentType)\n    .parameters.filter((parameter) => parameter.name !== 'charset')\n    .map((parameter): [string, string] => [parameter.name, parameter.value])\n    .sort(([aName, aValue], [bName, bValue]) =>\n      aName < bName ? -1 : aName > bName ? 1 : aValue < bValue ? -1 : aValue > bValue ? 1 : 0,\n    );\n}\n\n/**\n * The PascalCase fragment that qualifies a model minted for a non-primary\n * media type among the `content` keys it is declared beside (`siblings`,\n * the key itself included or not), built from what `oagen diff` compares two\n * keys by: the essence's token (`text/html` → `TextHtml`, `application/json;\n * charset=utf-8` → `ApplicationJson`), so a key keeps its model name however\n * it is spelled — plus, only when another key of the same essence sits\n * beside it, the key's parameters other than `charset`, sorted\n * (`mediaTypeParameters`: `application/yaml; version=2` →\n * `ApplicationYamlVersion2`, `; b=2; a=1` → `A1B2`), lower-cased before\n * casing — plus `Charset`, without its value, when the key declares a\n * `charset` and nothing else tells it apart from such a key\n * (`application/yaml; charset=utf-8` beside `application/yaml` →\n * `ApplicationYamlCharset`). So neither the keys' order, nor a parameter's,\n * nor a `charset`'s value reaches a name, and a key with no parameter but a\n * `charset` keeps its name when a key told apart by another parameter is\n * declared beside it (`application/yaml; charset=utf-8` beside a new\n * `application/yaml; version=2`). Keys left with one fragment — they differ\n * only in case or whitespace, the order or quoting of their parameters, or\n * the value of the `charset` they both declare — are named in\n * `mediaTypeNamingOrder`. A wildcard segment reads as `Any` (`application/*`\n * → `ApplicationAny`); nothing left reads as `Content`.\n */\nexport function mediaTypeNameFragment(contentType: string, siblings: Iterable<string> = []): string {\n  const { essence, parameters } = parseMediaType(contentType);\n  const token = toPascalCase(essence.split('*').join('Any'));\n  const compared = mediaTypeParameters(contentType);\n  const beside = [...siblings].filter((sibling) => sibling !== contentType && mediaTypeEssence(sibling) === essence);\n  let fragment = token;\n  if (beside.length > 0) {\n    fragment += toPascalCase(compared.map(([name, value]) => `${name} ${value}`.toLowerCase()).join(' '));\n    const told = JSON.stringify(compared);\n    const charset =\n      parameters.some((parameter) => parameter.name === 'charset') &&\n      beside.some((sibling) => JSON.stringify(mediaTypeParameters(sibling)) === told);\n    if (charset) fragment += 'Charset';\n  }\n  return fragment.length > 0 ? fragment : 'Content';\n}\n\n/**\n * `contentTypes` in the order their models are named: as written, except that\n * keys deriving one fragment among them (`mediaTypeNameFragment`) take the\n * places of that fragment's keys in one order whatever the document's — by\n * the key in one spelling (`namingSpelling`), case folded, then lower case\n * before upper case where only case differs. The first takes the bare name\n * and the next steps from it (or shares it, when its shape is identical), so\n * which key steps depends neither on the keys' order nor on how a key\n * quotes, spaces or orders its parameters: `application/yaml` beside\n * `Application/YAML` is named first wherever either is written, and so is\n * `application/yaml; profile=print` beside `Application/YAML;\n * profile=\"print\"`. Keys alike in that spelling differ in nothing but syntax\n * (`; b=2; a=1` beside `; a=1; b=2`), so they keep their document order: the\n * key as written never decides, or respelling one could swap them. An edit\n * that changes this order still swaps two keys' models — a case edit to one\n * of two case-only keys, a `charset` edit to one of two keys that differ in\n * nothing else, or a reorder of two keys that differ only in syntax — since\n * no order stays put both when two keys are reordered and when one of them\n * is respelled.\n */\nexport function mediaTypeNamingOrder(contentTypes: readonly string[]): string[] {\n  const fragments = contentTypes.map((contentType) => mediaTypeNameFragment(contentType, contentTypes));\n  const turns = new Map<string, string[]>();\n  contentTypes.forEach((contentType, i) => turns.set(fragments[i], [...(turns.get(fragments[i]) ?? []), contentType]));\n  // `sort` is stable, so keys alike in `namingSpelling` keep their document order.\n  for (const keys of turns.values()) keys.sort((a, b) => bySpelling(namingSpelling(a), namingSpelling(b)));\n  return fragments.map((fragment) => turns.get(fragment)!.shift()!);\n}\n\n/**\n * A key in one spelling whatever its quotes, spaces or parameter order: its\n * essence as written, so its case still orders case-only spellings, then its\n * parameters other than `charset` as `oagen diff` reads them\n * (`mediaTypeParameters`: decoded, sorted), then its `charset`.\n */\nfunction namingSpelling(contentType: string): string {\n  const charsets = parseMediaType(contentType)\n    .parameters.filter((parameter) => parameter.name === 'charset')\n    .map((parameter) => parameter.value);\n  return JSON.stringify([contentType.split(';')[0].trim(), mediaTypeParameters(contentType), charsets]);\n}\n\n/** Case folded, then lower case first where only case differs (`application/yaml` before `Application/YAML`). */\nfunction bySpelling(a: string, b: string): number {\n  const [foldedA, foldedB] = [a.toLowerCase(), b.toLowerCase()];\n  if (foldedA !== foldedB) return foldedA < foldedB ? -1 : 1;\n  return a === b ? 0 : a > b ? -1 : 1;\n}\n","import type { TypeRef } from '../ir/types.js';\nimport { mediaTypeEssence } from '../utils/media-type.js';\n\n/**\n * How the operation reader types a response body by the media type it is\n * declared under: `binary` and `text` without reading its schema, `schema`\n * through the schema it declares (`unknown` when it declares none).\n */\nexport type ResponseBodyReading = 'binary' | 'text' | 'schema';\n\n/**\n * The media types a response body is typed as a binary string under, by\n * essence, in the order the fixed-order pick tries them\n * (`primaryBodySchema`). Their schema is never read.\n */\nexport const BINARY_RESPONSE_MEDIA_TYPES: readonly string[] = ['application/octet-stream', 'application/pdf'];\n\n/**\n * The media types a response body is typed as a plain string under, by\n * essence, in the order the fixed-order pick tries them\n * (`primaryBodySchema`). Their schema is never read.\n */\nexport const TEXT_RESPONSE_MEDIA_TYPES: readonly string[] = ['text/plain', 'text/html', 'text/xml', 'application/xml'];\n\n/**\n * How a response body under `contentType` is read, by essence — parameters\n * and case aside, so `application/pdf; version=1.7` is as binary as\n * `application/pdf` and `TEXT/PLAIN; charset=utf-8` as much a string as\n * `text/plain`: `binary` for `application/octet-stream` and\n * `application/pdf`, `text` for `text/plain`, `text/html`, `text/xml` and\n * `application/xml`, each typed without its schema being read, whatever it\n * says; `schema` for every other media type — `application/json`, a `+json`\n * type, `application/*+json`, `*\\/*`, `application/yaml`, `text/csv`, a\n * `+xml` type such as `application/atom+xml` — typed from the schema it\n * declares. The one classification of a response body's media type, read by\n * the fixed-order pick of the primary body (`primaryBodySchema`), by every\n * secondary entry of a 2xx, 3xx, error, `default` or range response\n * (`typeSecondaryContent`), and by the sent/received walk\n * (`sentOnlyComponentNames`), which reads a response body by exactly the\n * media types whose schema the reader reads — so a body of `$ref: Pet` under\n * `application/xml` neither types anything as `Pet` nor counts as receiving\n * it (workos/oagen#610). A request body has no such list: every media type\n * that declares a schema is typed through it, as the primary pick\n * (`selectRequestBodyContent`) or a secondary entry\n * (`typeSecondaryRequestContent`, a webhook's `mintPayload`), and one\n * without is typed by `schemalessRequestContentType`, so the walk reads a\n * request body — an operation's, sent, a webhook's or a callback's, received\n * — under every media type it declares.\n */\nexport function responseBodyReading(contentType: string): ResponseBodyReading {\n  const essence = mediaTypeEssence(contentType);\n  if (BINARY_RESPONSE_MEDIA_TYPES.includes(essence)) return 'binary';\n  if (TEXT_RESPONSE_MEDIA_TYPES.includes(essence)) return 'text';\n  return 'schema';\n}\n\n/**\n * The type of a response body read without its schema: a binary string for\n * a `binary` media type, a string for a `text` one — what the primary pick\n * and a secondary entry alike give such a body. Each call returns a new\n * object.\n */\nexport function unreadResponseBodyType(reading: Exclude<ResponseBodyReading, 'schema'>): TypeRef {\n  return reading === 'binary'\n    ? { kind: 'primitive', type: 'string', format: 'binary' }\n    : { kind: 'primitive', type: 'string' };\n}\n","import { isDeepStrictEqual } from 'node:util';\nimport type {\n  Field,\n  TypeRef,\n  Parameter,\n  Model,\n  ModelRef,\n  PaginationMeta,\n  PaginationEndOfIteration,\n  PaginationStrategy,\n} from '../ir/types.js';\nimport type { PaginationHint } from '../ir/operation-hints.js';\nimport type { SchemaObject } from './schemas.js';\nimport { componentKeyOf, isPendingSchemaRef } from './schema-refs.js';\nimport {\n  allOfReadAsMember,\n  classifyInlineSchema,\n  componentUnionDispatches,\n  declaresNull,\n  isArraySchema,\n  isNullSchema,\n  nullableAxisBranch,\n  resolveComponentSchemaRef,\n  resolveSchemaName,\n  unionAxesOf,\n  unionTypesSchema,\n  unwrapNullableSchema,\n  wrapperDiscriminatorOf,\n} from './schemas.js';\nimport { toSnakeCase } from '../utils/naming.js';\nimport {\n  annotatedTypingMember,\n  combineDeclarations,\n  declareVariant,\n  readInlineAllOf,\n  schemaShapeKey,\n  unionOfDeclarations,\n  type PropertyDeclarations,\n} from './inline-models.js';\n\nconst CURSOR_PARAMS = ['cursor', 'after', 'before', 'starting_after', 'ending_before', 'page_token', 'next_token'];\n\nconst OFFSET_PARAMS = ['offset', 'skip'];\nconst PAGE_PARAMS = ['page', 'page_number', 'page_num'];\nconst LIMIT_PARAMS = ['limit', 'page_size', 'per_page', 'size', 'count'];\n\n/**\n * Detect if an operation uses pagination and return structured metadata\n * for auto-paging iterator generation.\n *\n * Recognizes three strategies from the query parameter names, in this order:\n * 1. **Cursor-based**: a cursor-like parameter (`cursor`, `after`, …)\n * 2. **Offset-based**: an item offset (`offset`, `skip`) plus a limit-like parameter\n * 3. **Page-number**: a page number (`page`, `page_number`, `page_num`) plus a\n *    limit-like parameter — the iterator advances it by one per request, not\n *    by the number of items received, starting at `pageStart`\n *\n * An offset or page parameter without a page-size parameter is not treated as\n * pagination. Returns null if no pattern is detected — and then no iterator\n * is built from the query parameters: an iterator is driven only by a\n * parameter the operation declares, never by one guessed from the response\n * (`describeUndetectedPaging` says what was missing).\n */\nexport function detectPagination(\n  response: TypeRef,\n  queryParams: Parameter[],\n  dataPath?: string,\n  options: { pageStartOf?: PageStartResolver } = {},\n): PaginationMeta | null {\n  // Try cursor-based first (preferred). Scan in CURSOR_PARAMS priority order\n  // rather than queryParams order so that an endpoint exposing both `before`\n  // and `after` reports `after` (forward iteration) — matches the wire\n  // convention where `after` advances through pages.\n  const cursorParam = CURSOR_PARAMS.map((name) => queryParams.find((p) => p.name === name)).find(\n    (p): p is Parameter => p !== undefined,\n  );\n\n  if (cursorParam) {\n    return {\n      strategy: 'cursor',\n      param: cursorParam.name,\n      dataPath: dataPath,\n      itemType: paginatedItemType(response),\n    };\n  }\n\n  // Offset and page-number pagination both need a page-size parameter.\n  const limitParam = queryParams.find((p) => LIMIT_PARAMS.includes(p.name));\n  if (!limitParam) return null;\n\n  const itemType = paginatedItemType(response);\n\n  const offsetParam = queryParams.find((p) => OFFSET_PARAMS.includes(p.name));\n  if (offsetParam) {\n    return {\n      strategy: 'offset',\n      param: offsetParam.name,\n      limitParam: limitParam.name,\n      dataPath: dataPath,\n      itemType: paginatedItemType(response),\n    };\n  }\n\n  const pageParam = queryParams.find((p) => PAGE_PARAMS.includes(p.name));\n  if (pageParam) {\n    return {\n      strategy: 'page',\n      param: pageParam.name,\n      limitParam: limitParam.name,\n      pageStart: (options.pageStartOf ?? derivePageStart)(pageParam),\n      dataPath: dataPath,\n      itemType,\n    };\n  }\n\n  return null;\n}\n\n/**\n * Why `detectPagination` finds no strategy in `queryParams`, for the warning\n * on an operation whose list envelope nothing pages: the recognized\n * parameters it declares and what is missing beside them — an offset or page\n * parameter without a page-size one, a page-size one on its own, or none of\n * the names at all. Meaningful only when `detectPagination` returned null,\n * so a cursor parameter, which alone makes an iterator, is never among the\n * declared ones.\n */\nexport function describeUndetectedPaging(queryParams: Parameter[]): string {\n  const declared = (names: readonly string[]): string[] =>\n    queryParams.filter((p) => names.includes(p.name)).map((p) => `\"${p.name}\"`);\n  // `\"page\" is` / `\"offset\" and \"page\" are` / `\"a\", \"b\" and \"c\" are`.\n  const listed = (names: string[]): string =>\n    names.length === 1 ? `${names[0]} is` : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]} are`;\n  const selectors = [...declared(OFFSET_PARAMS), ...declared(PAGE_PARAMS)];\n  if (selectors.length > 0) {\n    return `${listed(selectors)} declared without a page-size parameter: ${LIMIT_PARAMS.join(', ')}`;\n  }\n  const sizes = declared(LIMIT_PARAMS);\n  if (sizes.length > 0) return `${listed(sizes)} declared without a cursor, offset or page parameter`;\n  return 'no cursor, offset or page query parameter is declared';\n}\n\n/** Decides the first page number for a page parameter; see `derivePageStart`. */\nexport type PageStartResolver = (param: Parameter | undefined) => number;\n\n/**\n * The first page number an API expects: the page parameter's `default`, else\n * its `minimum`, else 1. Only a non-negative integer counts — a `default` of\n * `\"1\"` or `1.5` is not a page number, so the next source is tried.\n *\n * `schema` is the parameter's schema as written. The IR parameter carries a\n * `default`/`minimum` declared inline or on a bare `$ref` target, but not one\n * behind `allOf: [{ $ref }]` or a nullable wrapper; those are read from the\n * schema through `resolveSchemaKeyword`, so a component declaring `default:\n * 0` still starts the iterator at page 0.\n */\nexport function derivePageStart(\n  param: Parameter | undefined,\n  schema?: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): number {\n  const candidates = [\n    param?.default,\n    schema && resolveSchemaKeyword(schema, 'default', componentSchemas),\n    param?.constraints?.minimum,\n    schema && resolveSchemaKeyword(schema, 'minimum', componentSchemas),\n  ];\n  for (const candidate of candidates) {\n    if (typeof candidate === 'number' && Number.isInteger(candidate) && candidate >= 0) return candidate;\n  }\n  return 1;\n}\n\n/**\n * A keyword's value on a schema or on what it is composed of: the schema's\n * own value, else the component its `$ref` names, else its `allOf` members in\n * declaration order (the first that declares it wins), else the single\n * non-null variant of a nullable `oneOf`/`anyOf`. `undefined` when no level\n * declares it.\n */\nexport function resolveSchemaKeyword(\n  schema: SchemaObject,\n  keyword: 'default' | 'minimum',\n  componentSchemas?: Record<string, SchemaObject>,\n  seen: Set<string> = new Set(),\n): unknown {\n  if (schema[keyword] !== undefined) return schema[keyword];\n  if (schema.$ref) {\n    if (seen.has(schema.$ref)) return undefined;\n    seen.add(schema.$ref);\n    const resolved = resolveComponentSchemaRef(schema, componentSchemas);\n    return resolved ? resolveSchemaKeyword(resolved, keyword, componentSchemas, seen) : undefined;\n  }\n  for (const member of schema.allOf ?? []) {\n    const value = resolveSchemaKeyword(member, keyword, componentSchemas, seen);\n    if (value !== undefined) return value;\n  }\n  const variants = schema.oneOf ?? schema.anyOf;\n  if (variants) {\n    const nonNull = variants.filter((variant) => !isNullSchema(variant));\n    if (nonNull.length === 1) return resolveSchemaKeyword(nonNull[0], keyword, componentSchemas, seen);\n  }\n  return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// End of iteration — the envelope field that says the list is exhausted\n// ---------------------------------------------------------------------------\n\n/** Boolean companions that are `false` on the last page. */\nexport const HAS_MORE_FIELDS: readonly string[] = [\n  'has_more',\n  'hasMore',\n  'has_next',\n  'hasNext',\n  'has_next_page',\n  'hasNextPage',\n];\n/** Integer companions counting the pages. */\nexport const TOTAL_PAGES_FIELDS: readonly string[] = ['total_pages', 'totalPages', 'page_count', 'pageCount'];\n/** Integer companions counting the items. */\nexport const TOTAL_COUNT_FIELDS: readonly string[] = [\n  'total',\n  'total_count',\n  'totalCount',\n  'total_items',\n  'totalItems',\n  'total_results',\n  'totalResults',\n];\n/**\n * Every companion name that can end an iteration, each in any spelling\n * (`spellsOneOf`). List-envelope detection treats a companion with one of\n * these names as pagination metadata, and `detectEndOfIteration` reads it,\n * so the two can never disagree about which envelopes carry a stop field.\n */\nexport const END_OF_ITERATION_FIELDS: readonly string[] = [\n  ...HAS_MORE_FIELDS,\n  ...TOTAL_PAGES_FIELDS,\n  ...TOTAL_COUNT_FIELDS,\n];\nconst END_KIND_PRIORITY: ReadonlyArray<PaginationEndOfIteration['kind']> = ['hasMore', 'totalPages', 'totalCount'];\n\n/**\n * Substrings that mark an envelope companion as pagination metadata (`meta`,\n * `pagination`, `page_info`, `cursor`, ...), written in snake_case: the\n * spelling `looksLikePaginationMetadata` matches a companion's name in,\n * whatever case or separators the document uses. List-envelope detection\n * reads them to recognize an envelope, and `detectEndOfIteration` reads them\n * to decide which object companions to look inside for a stop field.\n */\nexport const PAGINATION_METADATA_PATTERNS: readonly string[] = [\n  'meta',\n  'metadata',\n  'pagination',\n  'cursor',\n  'has_more',\n  'page_info',\n  'total',\n  'next_page',\n  'previous_page',\n  'offset',\n];\n\n/**\n * Whether a companion's name says it carries pagination metadata: its\n * snake_case spelling (`toSnakeCase`, which splits the name into words as\n * `toPascalCase` does) contains one of `PAGINATION_METADATA_PATTERNS`. The\n * name is read by its words, so case and separators do not matter —\n * `page_info`, `pageInfo`, `PageInfo` and `page-info` are all `page_info` —\n * while a pattern never straddles a word boundary: `nameTag` is `name_tag`,\n * which does not contain `meta`. A name that runs its words together is one\n * word, so a pattern of several is not found in it (`pageinfo` and\n * `PAGEINFO` are no `page_info`), while a one-word pattern still is\n * (`listmetadata` holds `meta`). The one recognizer for list-envelope\n * detection and the nested stop-field scan, so the two cannot disagree\n * about which companions are pagination metadata.\n */\nexport function looksLikePaginationMetadata(name: string): boolean {\n  const spelled = toSnakeCase(name);\n  return PAGINATION_METADATA_PATTERNS.some((pattern) => spelled.includes(pattern));\n}\n\n/**\n * Whether `name` is one of `fields` in some spelling: read by its words, in\n * the snake_case spelling `looksLikePaginationMetadata` reads a companion's\n * name in (`toSnakeCase`), it is a listed name read the same way. Case and\n * separators do not matter, so `has_more`, `hasMore`, `HasMore`, `has-more`\n * and `HAS_MORE` are all `has_more`, while a name that runs its words\n * together is one word: `hasmore` is no `has_more` and `totalpages` no\n * `total_pages`. A name holding a `.` is none of them: a stop field's path\n * is dotted, so `has.more` would be read as `more` inside `has`. The one\n * test of a stop field's name, for list-envelope detection\n * (`END_OF_ITERATION_FIELDS`) and for `detectEndOfIteration` (each kind's\n * list), so the two cannot disagree about which companion is a stop field.\n */\nexport function spellsOneOf(name: string, fields: readonly string[]): boolean {\n  if (name.includes('.')) return false;\n  const spelled = toSnakeCase(name);\n  return fields.some((field) => toSnakeCase(field) === spelled);\n}\n\n/**\n * Find the envelope field that ends an iteration, when the envelope declares\n * an obvious one. `properties` are the envelope's merged properties — those\n * every instance carries (`collectObjectProperties`, `onEveryInstance`: a\n * member's, or declared by every variant of a `oneOf`/`anyOf` the `allOf`\n * flattens, so a stop field only some variants declare, or one they type\n * differently, ends no iteration; workos/oagen#622) — and `dataPath` names\n * the data array among them.\n *\n * The fields beside the array are considered first: when the path is\n * nested, the other properties of the object the array sits in, under\n * whatever name that object has (`result.total_pages` beside\n * `result.items`, `data.page.has_more` beside `data.page.items`), then\n * those of each object the path passes through on its way there, nearest\n * the array first (`result.total_pages` beside `result.page` for\n * `result.page.items`), every one reached exactly as the path itself is\n * resolved (`resolveSchemaPath` from the merged properties), so one behind\n * a `$ref`, an `allOf` or a nullable wrapper is read as the walk reads it.\n * Then the top-level fields, then the fields one level down inside each\n * top-level object companion whose name says it is pagination metadata\n * (`looksLikePaginationMetadata`: `meta`, `pagination`, `page_info`, ..., in\n * any spelling — `pageInfo` and `PageInfo` as much as `page_info`; an\n * inline object, a `$ref` to a component, an `allOf` of those, or a nullable\n * wrapper around one), so a `stats.total` beside `pagination.page` is not\n * taken for the list's size. Nothing the path passes through — the array,\n * or an object on the way to it — is ever a stop field, whatever it is\n * called. The path follows the `dataPath` convention — `has_more`,\n * `result.total_pages` or `pagination.totalPages` — and spells each\n * segment as the document does (`pageInfo.hasNextPage`). A candidate is a\n * stop field by its name in any spelling (`spellsOneOf`), so `HasMore` and\n * `PageInfo.HasNextPage` are read as `has_more` and\n * `page_info.has_next_page` are, each kept as written; a name holding a\n * `.` is neither a stop field nor a companion looked inside, since the\n * dotted path could not address it (`has.more`, `page.info`). When several\n * candidates exist, a `hasMore` boolean wins over a `totalPages` integer,\n * which wins over a `totalCount` integer; within one kind the first in scan\n * order wins. A candidate whose type does not fit its kind (a string\n * `total`) is ignored.\n */\nexport function detectEndOfIteration(\n  properties: Record<string, SchemaObject | undefined>,\n  dataPath: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): PaginationEndOfIteration | undefined {\n  const found = new Map<PaginationEndOfIteration['kind'], string>();\n  const record = (name: string, path: string, schema: SchemaObject): void => {\n    const kind = classifyEndField(name, schema, componentSchemas);\n    if (kind && !found.has(kind)) found.set(kind, path);\n  };\n\n  // Every object on the path, nearest the array first, without the property\n  // the path goes on through; the top level, the outermost, comes last.\n  const segments = dataPath.split('.');\n  for (let depth = segments.length - 1; depth > 0; depth--) {\n    const parentPath = segments.slice(0, depth).join('.');\n    const parent = resolveSchemaPath({ properties }, parentPath, componentSchemas);\n    for (const [inner, innerSchema] of Object.entries(parent ? objectProperties(parent, componentSchemas) : {})) {\n      if (innerSchema && inner !== segments[depth]) record(inner, `${parentPath}.${inner}`, innerSchema);\n    }\n  }\n\n  const companions = Object.entries(properties).filter(\n    (entry): entry is [string, SchemaObject] => entry[0] !== segments[0] && entry[1] !== undefined,\n  );\n  for (const [name, schema] of companions) record(name, name, schema);\n  for (const [name, schema] of companions) {\n    // A `.` in the name would split the path inside it.\n    if (name.includes('.') || !looksLikePaginationMetadata(name)) continue;\n    for (const [inner, innerSchema] of Object.entries(objectProperties(schema, componentSchemas))) {\n      if (innerSchema) record(inner, `${name}.${inner}`, innerSchema);\n    }\n  }\n\n  for (const kind of END_KIND_PRIORITY) {\n    const path = found.get(kind);\n    if (path) return { kind, path };\n  }\n  return undefined;\n}\n\nfunction classifyEndField(\n  name: string,\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): PaginationEndOfIteration['kind'] | undefined {\n  // The name decides the kind, in any spelling (`spellsOneOf`), and only a\n  // named stop field has its schema read: a companion of any other name is\n  // never resolved at all.\n  const kind: PaginationEndOfIteration['kind'] | undefined = spellsOneOf(name, HAS_MORE_FIELDS)\n    ? 'hasMore'\n    : spellsOneOf(name, TOTAL_PAGES_FIELDS)\n      ? 'totalPages'\n      : spellsOneOf(name, TOTAL_COUNT_FIELDS)\n        ? 'totalCount'\n        : undefined;\n  if (!kind) return undefined;\n  return endDeclarationFits(kind, schema, componentSchemas) ? kind : undefined;\n}\n\n/**\n * Whether a stop field's bare schema (`resolveBareSchema`) has the type its\n * kind is tested against: a `boolean` for `hasMore`, an `integer` or\n * `number` for `totalPages` and `totalCount`, under a type list too. The\n * test `endDeclarationFits` applies to a declaration, or to each variant\n * of one.\n */\nfunction endFieldFits(kind: PaginationEndOfIteration['kind'], schema: SchemaObject): boolean {\n  return kind === 'hasMore' ? hasType(schema, 'boolean') : isNumeric(schema);\n}\n\n/**\n * Whether a stop field's declaration fits its kind: its bare schema\n * (`resolveBareSchema`) has the kind's type (`endFieldFits`) — `total: {\n * type: 'integer', anyOf: [{ maximum: 100 }, { minimum: 200 }] }` is the\n * integer its own `type` says, the union only limiting it, as\n * `classifyInlineSchema` reads such a schema (PR #643 review round 5:\n * every union was walked, so the limits were tested without the `type`,\n * the detected stop rule disappeared and an explicit `endOfIteration`\n * naming the field was rejected) — or, where it declares no such type, it\n * is a `oneOf`/`anyOf` that is what types it (`unionTypesSchema`: a\n * variant carries a typing keyword) and each non-null variant's\n * declaration fits in turn. The declaration the model types a property\n * only variants declare as is such a union when the variants' declarations\n * differ (`unionOfDeclarations`: `has_more: { type: 'boolean', const: true\n * }` in one variant and `{ type: 'boolean', const: false }` in the other,\n * or `{ $ref: Flag }` beside `{ type: 'boolean' }`), so it is tested as the\n * override walk tests the field it lands on one level down, in every\n * variant (`endOfIterationProblem`, `fieldsAtPath`) — PR #643 review\n * (MichaelDeBoey): the union was tested as one schema, so such a `has_more`\n * ended no iteration at the top level and an explicit `endOfIteration`\n * naming it was rejected as \"not a boolean field\", while `meta.has_more`\n * through the same union was accepted. A union reached again through\n * another variant — `Flag`, an `anyOf` of boolean consts, declared `{\n * $ref: Flag }` in one variant and `{ anyOf: [{ $ref: Flag }, { type:\n * 'boolean' }] }` in the other — is a shared reference, tested once and\n * read in each (`DeclarationWalk.done`; PR #643 review round 7: one `seen`\n * set served both variants, so the second reading was taken for a cycle,\n * the stop rule dropped and the override rejected, while `meta.has_more`\n * through the same declarations passed); only a union met again below\n * itself, on the way down (`DeclarationWalk.path`), fits nothing, which\n * ends a component that reaches itself. The one test for a field\n * detection names and for one an override names.\n */\nfunction endDeclarationFits(\n  kind: PaginationEndOfIteration['kind'],\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n  walk: DeclarationWalk = { path: new Set(), done: new Map() },\n): boolean {\n  const bare = resolveBareSchema(schema, componentSchemas);\n  if (endFieldFits(kind, bare)) return true;\n  const variants = bare.oneOf ?? bare.anyOf;\n  if (!variants || !unionTypesSchema(variants)) return false;\n  const known = walk.done.get(bare);\n  if (known !== undefined) return known;\n  if (walk.path.has(bare)) return false;\n  walk.path.add(bare);\n  const nonNull = variants.filter((variant) => !isNullSchema(variant));\n  const fits =\n    nonNull.length > 0 && nonNull.every((variant) => endDeclarationFits(kind, variant, componentSchemas, walk));\n  walk.path.delete(bare);\n  walk.done.set(bare, fits);\n  return fits;\n}\n\n/**\n * The bookkeeping of one declaration's test (`endDeclarationFits`): the\n * unions on the way down (`path`), so a union met again below itself fits\n * nothing and the test ends where the document repeats, and the unions\n * tested so far with their result (`done`), so a union reached again\n * through another variant — a shared reference, not a cycle — is tested\n * once. A result reached by closing a cycle is kept: a union that reaches\n * one on the way down reaches it from anywhere, since the way down came\n * through it.\n */\ninterface DeclarationWalk {\n  path: Set<SchemaObject>;\n  done: Map<SchemaObject, boolean>;\n}\n\n/**\n * Why an explicit `endOfIteration` cannot be read from a body whose\n * properties are `properties`, or `undefined` when it can. `properties` is\n * the map a detected stop field is read from — the body's own and every\n * `allOf` member's, through `$ref`s and nullable wrappers, with what every\n * variant of a `oneOf`/`anyOf` the `allOf` flattens declares\n * (`onEveryInstance`), as `detectEndOfIteration` receives it — so an\n * override and detection look at\n * one map: a field detection would read is one an override may name, and a\n * field it would not see is not there for an override either. `end.path` is\n * walked over that map as an explicit `dataPath` is (`fieldsAtPath`, the\n * one walk `resolveDataPathArray` makes too: through `$ref`s, `allOf`\n * members and nullable wrappers at every further segment, and, where an\n * object on the way does not declare the next segment itself, through each\n * non-null variant of a `oneOf`/`anyOf` that object is or has among its\n * `allOf` members, a variant that is itself a union through each of its\n * own in turn), so it lands on one field per variant; each must fit\n * `end.kind` by the test detection applies to a field it names\n * (`endDeclarationFits`: under `resolveBareSchema` as a detected one is,\n * and, for a declaration that is itself a union of the variants'\n * declarations, in each variant). With no `properties` — an operation\n * whose primary response declares no body — the path resolves to nothing.\n *\n * The text is the reason alone; the caller names the override's source and\n * the operation, and says what it does about it.\n */\nexport function endOfIterationProblem(\n  end: PaginationEndOfIteration,\n  properties: Record<string, SchemaObject | undefined> | undefined,\n  componentSchemas?: Record<string, SchemaObject>,\n): string | undefined {\n  const fields = properties && fieldsAtPath({ properties }, end.path, componentSchemas);\n  if (!fields) return `endOfIteration path \"${end.path}\" does not resolve to a field in the response`;\n  if (fields.every((field) => endDeclarationFits(end.kind, field, componentSchemas))) return undefined;\n  const expected = end.kind === 'hasMore' ? 'a boolean' : 'an integer or number';\n  return `endOfIteration path \"${end.path}\" is not ${expected} field, as kind \"${end.kind}\" requires`;\n}\n\n/**\n * Every field `path` lands on below `schema` — the walk an explicit\n * `endOfIteration` path (`endOfIterationProblem`) and an explicit `dataPath`\n * (`resolveDataPathArray`) share. Each segment is looked up among the\n * properties of the object the path has reached, as `resolveSchemaPath`\n * looks it up — through `$ref`s, `allOf` members and nullable wrappers —\n * and, when that object does not declare it but is a\n * `oneOf`/`anyOf` or has one among its `allOf` members (`fieldsNamed`), in\n * each non-null variant of that union instead: whichever variant the wire\n * carries, the field must be there, so the path goes on in every one and\n * lands on one field per variant (`meta.has_more` with `meta` a `oneOf` of\n * two objects that each declare `has_more`, or `meta` an `allOf` of that\n * `oneOf` and a `trace_id` member, every member applying whichever variant\n * is sent). `undefined` when the object does not declare the segment and no\n * union it has declares it in every variant (and, for a union an `allOf`\n * flattens, in one written inline, as its model does). A variant that is\n * itself a union — written inline, or a `$ref` to a union component — is\n * read by the same rule: the field must be in each of its non-null\n * variants in turn, however deep the unions nest, since whichever leaf the\n * wire carries the field must be there (`meta.has_more` with `meta` an\n * `anyOf` of a `oneOf` of two objects and a third, every object declaring\n * `has_more`; PR #585 review).\n * The walk goes one segment at a time over every schema reached so far,\n * each counted once — by its `$ref`, else by the schema itself — so a\n * component several variants reach is walked on once, however many\n * variants reach it and however long the path; and within a segment a\n * node is read once however many routes through nested unions reach it\n * (`FieldLookup`).\n */\nfunction fieldsAtPath(\n  schema: SchemaObject,\n  path: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): SchemaObject[] | undefined {\n  let reached = [schema];\n  const lookup = newFieldLookup();\n  for (const segment of path.split('.')) {\n    const next = new Map<string | SchemaObject, SchemaObject>();\n    for (const node of reached) {\n      const named = fieldsNamed(node, segment, componentSchemas, lookup);\n      if (!named) return undefined;\n      for (const { schema: field } of named) next.set(field.$ref ?? field, field);\n    }\n    reached = [...next.values()];\n  }\n  return reached;\n}\n\n/**\n * The fields `segment` names in `node` (`fieldsAtPath`): its own property of\n * that name, else that property in each non-null variant of the first\n * `oneOf`/`anyOf` `node` is composed of — `node` itself or an `allOf`\n * member, however deep, as `collectObjectProperties` walks them — whose\n * every such variant declares it, in the variants' order with the `null`\n * ones left out, each with the variant it came from (`via`: the variant's\n * place as written and the union's keyword, `variantsOf`), so a reader can\n * say which variant a field came from (`resolveDataPathArray`). A variant\n * declares the segment as `node` does — as its own property, or in every\n * non-null variant of a union it is or has — so a variant that is itself a\n * union, written inline or a `$ref` to a union component (`PetPage: {\n * oneOf: [A, B] }`), is walked by this same rule (`unionFields`) and yields\n * one field per leaf, each `via` the steps down to it, outermost first\n * (PR #585 review: such a variant was read as declaring no field, though\n * each of its own variants declared it). A node met again below itself\n * (`PetPage: { oneOf: [{ $ref: PetPage }, A] }`) is not read a second\n * time: the walk ends where it repeats, as `collectObjectProperties` ends\n * on a `$ref` it has followed, so such a variant declares nothing and the\n * union does not count. A lookup once made is kept for the walk\n * (`lookup`, one per path: the `(node, segment)` pairs read so far), so a\n * node several routes reach — two references to one component in one\n * union, or a chain of such unions, where the routes double at every link\n * — is read once, and its fields are collapsed to one per distinct field\n * as they are met (`unionFields`), with the first route that reached it\n * (PR #585 review: twenty components each an `anyOf` of two references to\n * the next built over a million fields, each copying its route). A lookup\n * a cycle closed above — one that ended on a node still on the way down\n * above this one — depends on where the walk came from, and is not kept;\n * one the cycle closed on itself, or no cycle touched, is the same from\n * wherever the walk reaches the node. A `node` that is a union is typed as its\n * variants' models, a `$ref` variant's component among them; one that is an\n * `allOf`, or reaches a component composed with one (its own model, even\n * of a lone member), is one model its unions are flattened into or\n * dispatched by — a `$ref` variant's component read into the flattened\n * model as an inline variant is, and a union a `$ref` member's component\n * carries read as that component's model reads it, inline exactly as for a\n * component (`mergeAllOfMembers`, `extractAllOfModel`; #398, #429) — so a\n * field every variant declares is one the model has, or one the model\n * dispatches to a variant that has it, wherever the union sits and however\n * its variants are written (workos/oagen#527: the flattened model left a\n * `$ref` variant's fields to its component and read no union behind a\n * `$ref` member, so the field was rejected there as one the model lacked).\n * A union the walk meets counts exactly when the model carries its fields\n * (`unionCounts`): one a `$ref` member's component dispatches is left to\n * that component, as the model leaves it, and contributes nothing here.\n * `undefined` when there is none.\n */\nfunction fieldsNamed(\n  node: SchemaObject,\n  segment: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  lookup: FieldLookup = newFieldLookup(),\n): NamedField[] | undefined {\n  const done = lookup.memo.get(node);\n  if (done?.has(segment)) return done.get(segment);\n  // Met again below itself: it declares nothing, and the walk ends where the document repeats.\n  const above = lookup.stack.indexOf(node);\n  if (above !== -1) {\n    lookup.closed = Math.min(lookup.closed, above);\n    return undefined;\n  }\n  const depth = lookup.stack.push(node) - 1;\n  const outer = lookup.closed;\n  lookup.closed = Infinity;\n  const fields = readFieldsNamed(node, segment, componentSchemas, lookup);\n  lookup.stack.pop();\n  // Kept unless a cycle closed above this node, which would make the reading depend on the way down.\n  if (lookup.closed >= depth) {\n    const entry = done ?? new Map<string, NamedField[] | undefined>();\n    entry.set(segment, fields);\n    lookup.memo.set(node, entry);\n  }\n  lookup.closed = Math.min(outer, lookup.closed);\n  return fields;\n}\n\n/**\n * One walk's bookkeeping for `fieldsNamed`: the lookups completed so far,\n * by node and segment (`memo`); the nodes on the way down (`stack`), so a\n * node met again below itself ends the walk where the document repeats; and\n * the shallowest of those a cycle closed on during the lookup in progress\n * (`closed`, the node's place on the stack, `Infinity` when none), which\n * decides whether that lookup is kept. One per path walked (`fieldsAtPath`,\n * `resolveDataPathArray`).\n */\ninterface FieldLookup {\n  memo: Map<SchemaObject, Map<string, NamedField[] | undefined>>;\n  stack: SchemaObject[];\n  closed: number;\n}\n\nfunction newFieldLookup(): FieldLookup {\n  return { memo: new Map(), stack: [], closed: Infinity };\n}\n\n/** The reading `fieldsNamed` keeps: the rule itself, see there. */\nfunction readFieldsNamed(\n  node: SchemaObject,\n  segment: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  lookup: FieldLookup,\n): NamedField[] | undefined {\n  // The walk's own bookkeeping is handed on, so a flattened union among the\n  // node's members is read with it (`readFlattenedUnion`) and ends where the\n  // document repeats.\n  const { properties, unions, named } = collectObjectProperties(node, componentSchemas, lookup);\n  const own = properties[segment];\n  if (own) return [{ schema: own }];\n  // A union counts exactly when the model carries its fields (`unionCounts`):\n  // one a `$ref` member's component dispatches is left to that component.\n  for (const union of unions) {\n    if (!unionCounts(union, named, componentSchemas)) continue;\n    const fields = unionFields(union, segment, componentSchemas, lookup);\n    if (fields && fields.length > 0) return fields;\n  }\n  return undefined;\n}\n\n/** One step down into a `oneOf`/`anyOf`: the variant's place as written, `null` variants counted, and the union's keyword. */\ninterface VariantStep {\n  index: number;\n  keyword: 'oneOf' | 'anyOf';\n}\n\n/** A field a path segment names (`fieldsNamed`), with the variants it was reached through, outermost first — none for an object's own property. */\ninterface NamedField {\n  schema: SchemaObject;\n  via?: VariantStep[];\n}\n\n/**\n * Each non-null variant of a `oneOf`/`anyOf` `union` with its step: its\n * place among the variants as written, the `null` ones counted (the third\n * listed is `index` 3 whatever sits before it, as `variantLabel` names it),\n * and the union's keyword.\n */\nfunction variantsOf(union: CollectedUnion): Array<{ step: VariantStep; variant: SchemaObject }> {\n  return union.variants.flatMap((variant, index) =>\n    isNullSchema(variant) ? [] : [{ step: { index: index + 1, keyword: union.keyword }, variant }],\n  );\n}\n\n/**\n * The fields `segment` names in every non-null variant of `union`, by the\n * rule `fieldsNamed` applies to any object — so a variant that is itself a\n * union contributes one field per leaf — each `via` its own step and the\n * steps below it; `undefined` when a variant declares none. Repeated\n * fields are collapsed as they are met: one entry per distinct field — by\n * its `$ref`, else the schema itself, as `fieldsAtPath` counts them — with\n * the first route that reached it, so two references to one component\n * yield its fields once, and a chain of such unions yields at each link\n * as many fields as there are distinct ones below, not routes. `lookup`\n * carries the walk's completed lookups and cycle guard (`fieldsNamed`).\n */\nfunction unionFields(\n  union: CollectedUnion,\n  segment: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  lookup: FieldLookup,\n): NamedField[] | undefined {\n  const fields = new Map<string | SchemaObject, NamedField>();\n  for (const { step, variant } of variantsOf(union)) {\n    const named = fieldsNamed(variant, segment, componentSchemas, lookup);\n    if (!named) return undefined;\n    for (const field of named) {\n      const key = field.schema.$ref ?? field.schema;\n      if (!fields.has(key)) fields.set(key, { schema: field.schema, via: [step, ...(field.via ?? [])] });\n    }\n  }\n  return [...fields.values()];\n}\n\n/**\n * Whether a union the walk met (`collectObjectProperties`) is one the\n * node's model carries the fields of — flattened in, or dispatched to\n * variant models of its own — so that a field its every variant declares\n * is one the model has (`fieldsNamed`). The node's own unions are: an\n * inline `allOf` flattens every union of its inline members, and a\n * component flattens or dispatches its own. A union a `$ref` member's\n * component carries is read as the model reads the member (#429):\n * flattened into the model when the component's model flattens it, and\n * left to the component when that model dispatches it\n * (`componentUnionDispatches`, the one decision the inline merge and the\n * component reader apply) — the model then carries the base fields the\n * dispatcher carries and no variant's, so the field is not one it has,\n * whatever the variants declare (#398 review: every union counted, so\n * `meta: { allOf: [{ $ref: MetaDispatcher }, { trace_id }] }` accepted a\n * `has_more` every dispatched variant declares, and the iterator read a\n * field `Meta { base, trace_id }` lacks). One exception, the component\n * reader's own (`readComponentAllOfMember`): a component's direct `$ref`\n * member to a plain object that carries the union — no `allOf` of its own\n * nor on the way to it — dispatches the component itself (`Dog: { allOf:\n * [{ $ref: Pet }] }` with `Pet: { properties: { id }, oneOf: [cat, dog] }`\n * dispatches to `DogCat` and `DogDog`), whose variant models carry the\n * field; an inline merge of the same member carries the base fields only.\n */\nfunction unionCounts(union: CollectedUnion, named: boolean, componentSchemas?: Record<string, SchemaObject>): boolean {\n  if (union.origin === null) return true;\n  if (named && union.origin.direct) return true;\n  return !componentUnionDispatches(union.variants, union.origin.name, componentSchemas, union.discriminator);\n}\n\nfunction hasType(schema: SchemaObject, type: string): boolean {\n  return Array.isArray(schema.type) ? schema.type.includes(type) : schema.type === type;\n}\n\nfunction isNumeric(schema: SchemaObject): boolean {\n  return hasType(schema, 'integer') || hasType(schema, 'number');\n}\n\n/**\n * The schema under every `$ref`, nullable wrapper and lone `allOf` member:\n * a `$ref` is followed to its component; a nullable wrapper — an OAS 3.1\n * type list naming `'null'`, OAS 3.0 `nullable: true`, a `oneOf`/`anyOf`\n * with one non-null variant — is stripped by `unwrapNullableSchema`, the\n * one definition the model side unwraps by; and an `allOf` with one member\n * that is what types the schema (`classifyInlineSchema`: a `$ref` member,\n * or an inline member with a type of its own — not an `allOf` of bare\n * limits beside the schema's own `type`) is read as that member exactly\n * when `schemaToTypeRef` types the schema as it (`readInlineAllOf`:\n * `'unwrapped'` or `'reference'`; a `required` beside a lone `$ref`\n * member to a component that declares properties makes the schema the\n * merged model, which is left as written), so\n * `has_more: { allOf: [{ $ref: Flag }], description }` with `Flag: { type:\n * boolean }` is a boolean here as it is in the IR. The three alternate\n * until the schema is\n * none of them, so `{ oneOf: [{ $ref: 'Tags' }, { type: 'null' }] }` with\n * `Tags: { type: ['array', 'null'], items }` reaches the array. Sibling\n * `properties` are folded into the `allOf` by the unwrap\n * (`foldSiblingProperties`), so a member with properties beside it is\n * never alone, and an `allOf` of several members is left as written for\n * the readers that merge them (`objectProperties`,\n * `collectObjectProperties`). A `$ref` met a second time\n * (`Flag: { oneOf: [{ $ref: Flag }, { type: 'null' }] }`) ends the walk on\n * the reference instead of looping on it, as `resolveSchemaKeyword` and\n * `objectProperties` stop; so does a `$ref` with no component map or to no\n * component. Shared by the stop-field check and the document walk an\n * explicit `dataPath` makes (`resolveDataPathArray`), so a stop field\n * and a data array behind the same wrappers are read the same way.\n */\nexport function resolveBareSchema(\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n  seen: Set<string> = new Set(),\n): SchemaObject {\n  if (schema.$ref) {\n    if (seen.has(schema.$ref)) return schema;\n    seen.add(schema.$ref);\n    const resolved = resolveComponentSchemaRef(schema, componentSchemas);\n    return resolved ? resolveBareSchema(resolved, componentSchemas, seen) : schema;\n  }\n  const bare = unwrapNullableSchema(schema);\n  if (bare.$ref) return resolveBareSchema(bare, componentSchemas, seen);\n  const reading =\n    bare.allOf && classifyInlineSchema(bare) === 'allOf'\n      ? readInlineAllOf(bare.allOf, bare, componentSchemas)\n      : undefined;\n  // The member the type builder types the `allOf` as: the one unwrapped —\n  // a lone member, or the one typing member beside members that only\n  // annotate or limit it (`annotatedTypingMember`; #555) — or the `$ref`\n  // member of a plain reference, whatever is written beside it.\n  const lone =\n    reading === 'unwrapped'\n      ? annotatedTypingMember(bare)\n      : reading === 'reference'\n        ? bare.allOf?.find((member) => member.$ref !== undefined)\n        : undefined;\n  return lone ? resolveBareSchema(lone, componentSchemas, seen) : bare;\n}\n\n/**\n * The properties of an object schema as `collectObjectProperties` collects\n * them — the one walk through `$ref`s, `allOf` members and nullable wrappers,\n * with a name two members declare settled by `combineDeclarations` — for a\n * site that reads the properties alone: those every instance carries\n * (`onEveryInstance`), a member's or every variant's of a union the `allOf`\n * flattens, since the sites are the stop-field scan and the walk to each\n * object on a `dataPath` (`detectEndOfIteration`, `resolveSchemaPath`).\n * Anything that is not an object yields none.\n */\nfunction objectProperties(\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): Record<string, SchemaObject | undefined> {\n  return collectObjectProperties(schema, componentSchemas).onEveryInstance;\n}\n\n/**\n * Every property the object `schema` describes declares, merged across its\n * `allOf` members, with the `required` lists that go with them — the one\n * walk through a composite schema: a list envelope's companions\n * (`extractListResponse`), a kept wrapper's stop field\n * (`bodyEndOfIteration`), a metadata companion's fields and each object\n * on the path to a nested array (`detectEndOfIteration`) and every\n * segment of a `dataPath` (`resolveSchemaPath`, `fieldsNamed`) are all read\n * through it, so they see one shape at every level.\n *\n * Every node the walk meets — the body, then each `allOf` member, however\n * deep — is read through `resolveBareSchema`, the resolver the explicit\n * `dataPath` walk reads the document with: a `$ref` is followed to its\n * component and a nullable wrapper of any spelling (a type list naming\n * `null`, OAS 3.0 `nullable: true`, a `oneOf`/`anyOf` with one non-null\n * variant) is stripped, however the two alternate. So fields an envelope\n * inherits from a shared base (`trace_id` on every response, say) are not\n * silently dropped whether the member is written `$ref: Base`, `{ oneOf: [{\n * $ref: Base }, { type: 'null' }] }`, a `$ref` to such a wrapper, or an\n * `allOf` nested inside one — and a stop field declared in any of them is\n * read. The one place the walk resolves a node, so the companions and the\n * stop field are read from the same shape, at every level, that the path\n * walk reaches the data array through. One `seen` runs through the whole\n * walk: the `$ref` strings `resolveBareSchema` records as it follows them,\n * handed to every call the walk makes, so a reference reached inside a\n * wrapper is as seen as one written on the member; and, for an inline\n * node, the schema object itself. No node is entered twice, under whatever\n * wrapper or at whatever depth it reappears, so a component that reaches\n * itself (`Base.allOf` holding `{ oneOf: [{ $ref: Base }, { type: 'null'\n * }] }`, or `{ $ref: Base }` outright), two components that reach each\n * other, and a document whose objects form a cycle are each read once and\n * end the walk where they repeat. An `allOf` member's own `properties`\n * beside its `allOf` are folded in as its first member\n * (`foldSiblingProperties`, through `unwrapNullableSchema`). A property\n * declared by more than one member is settled exactly as every `allOf`\n * merge settles it for a model's field (`combineDeclarations`): two inline\n * objects merge their properties — `pagination.next` from one member and\n * `pagination.total` from another both belong to the response, as they do\n * to the wrapper's model — two arrays combine their `items` by the same\n * rule, two declarations that each describe an object — an inline object,\n * a `$ref` to an object component, an `allOf` that reaches one — become\n * the `allOf` of both, read through as any `allOf` member is\n * (`result.items` from `PetPage` beside `result.total_pages`, written\n * inline or under an `allOf`; #432, #571), and otherwise the first\n * declaration that declares a type types it, a typeless one only annotating\n * it.\n *\n * A `oneOf`/`anyOf` member with more than one non-null variant declares no\n * property of its own here: it is listed in `unions`, with every other\n * `oneOf`/`anyOf` the walk meets — the body itself first, then the members\n * in the order walked — each with the component a `$ref` member on the way\n * names and the `discriminator` the document declares for it\n * (`CollectedUnion`), and `named` says whether the body is typed as a\n * component's model (a `$ref`, or a nullable wrapper or lone `allOf` member\n * around one), for the override check, which reads a field every variant\n * of one declares exactly when the model carries it (`fieldsNamed`,\n * `unionCounts`). What such a union's variants declare is read beside\n * `properties` for a union among the members that the model flattens into\n * the node's one model (`unionCounts`: every inline member's, and a `$ref`\n * member's component's unless that component dispatches it — never the\n * node's own union, a union of models that no field of the node belongs\n * to): `fields` is every property that model has, in the order first\n * declared — `properties` and, for each flattened union, every property\n * any non-null variant declares (`readFlattenedUnion`, through the branch\n * reader the model flattens a variant with), typed as the model types a\n * property only variants declare (`unionOfDeclarations`: one shape is that\n * declaration, several are their `oneOf`) where no member always declares\n * it — and `onEveryInstance` is the part of `fields` an instance carries\n * whichever variant the wire sends: `properties`, and a branch-only\n * property every non-null variant of its union declares, as the override\n * walk resolves a path segment through the union (`unionFields`). An\n * envelope's companions are its `fields` (`extractEnvelopeCompanions`);\n * the array it is unwrapped on and the stop field it stops on must be\n * `onEveryInstance` (`detectListEnvelope`, `detectEndOfIteration`,\n * `bodyEndOfIterationProblem`), so a stop field written in each variant of\n * a `oneOf` beside the `allOf` ends the iteration as one written flat does\n * (workos/oagen#622: `{ allOf: [{ data }], oneOf: [{ has_more }, {\n * has_more, total }] }` built the model `{ data, has_more?, total? }` and\n * was no envelope, the variants read by the model alone), while a field\n * only some variants declare, or one they type differently, is a companion\n * and no stop field. A body that is not an envelope is merged by\n * `mergeAllOfMembers`, whose reading of a variant `readFlattenedUnion`\n * shares. `lookup` is the override walk's bookkeeping when that walk is\n * what reads the node (`readFieldsNamed`), so the variants are read once\n * per walk and a variant met again below itself ends the reading where\n * the document repeats.\n */\nexport function collectObjectProperties(\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n  lookup?: FieldLookup,\n): CollectedProperties {\n  const properties: Record<string, SchemaObject> = {};\n  const required: string[] = [];\n  const unions: CollectedUnion[] = [];\n  const seenRefs = new Set<string>();\n  const seenNodes = new WeakSet<SchemaObject>();\n  let named: boolean | undefined;\n  // Every name met, in the order first declared, by a member or by a\n  // variant; what the variants of each flattened union declare of a name\n  // (`readFlattenedUnion`), and the names every variant of one declares.\n  const order: string[] = [];\n  const noted = new Set<string>();\n  const note = (name: string): void => {\n    if (noted.has(name)) return;\n    noted.add(name);\n    order.push(name);\n  };\n  const branchOnly = new Map<string, SchemaObject[]>();\n  const carried = new Set<string>();\n  const walk = lookup ?? newFieldLookup();\n\n  // The component a member's `$ref` names, as the model reads the member\n  // (`CollectedUnion.origin`): the first reference the resolver followed\n  // for the member, counting from the `from`th it recorded; `direct` when\n  // the member is one of the node's own and every component on the way to\n  // the schema it lands on is a plain object or an alias — none composed\n  // with `allOf`, which the component reader reads as a nested component\n  // whose own dispatcher stays its own. `null` for an inline member.\n  const memberOrigin = (from: number, depth: number): CollectedUnion['origin'] => {\n    const refs = [...seenRefs].slice(from);\n    const key = componentKeyOf(refs[0]);\n    if (key === undefined) return null;\n    const direct =\n      depth === 1 &&\n      refs.every((ref) => resolveComponentSchemaRef({ $ref: ref }, componentSchemas)?.allOf === undefined);\n    return { name: resolveSchemaName(key), direct };\n  };\n\n  const visit = (\n    s: SchemaObject,\n    depth: number,\n    inherited: CollectedUnion['origin'],\n    wrapperDiscriminator?: SchemaObject['discriminator'],\n  ): void => {\n    if (seenNodes.has(s)) return;\n    seenNodes.add(s);\n    const followed = seenRefs.size;\n    // A member's references are followed here first, recorded as the\n    // resolver records them, so a component writing both keywords is read\n    // per keyword below rather than collapsed by the resolver onto a\n    // nullable axis's one variant with the other axis lost.\n    let carrier = s;\n    while (depth > 0 && carrier.$ref) {\n      if (seenRefs.has(carrier.$ref)) return;\n      seenRefs.add(carrier.$ref);\n      const target = resolveComponentSchemaRef(carrier, componentSchemas);\n      if (!target) return;\n      carrier = target;\n    }\n    const bare =\n      depth > 0 && carrier.oneOf && carrier.anyOf ? carrier : resolveBareSchema(carrier, componentSchemas, seenRefs);\n    // A reference the walk has followed already, or one nothing resolves:\n    // the walk ends on it, as the resolver did.\n    if (bare.$ref) return;\n    // The node's own unions are its model's, whatever it resolves through;\n    // a member's are read as the component its `$ref` names reads them.\n    named ??= seenRefs.size > followed;\n    const origin = depth === 0 ? null : (inherited ?? memberOrigin(followed, depth));\n    // The `discriminator` declared for a union here: the schema's own, else\n    // the member's own written on a nullable wrapper the resolver collapsed\n    // (`carrier`), else the one handed down from above — as the readers read\n    // it, so `unionCounts` agrees with the model.\n    const discriminator = bare.discriminator ?? carrier.discriminator ?? wrapperDiscriminator;\n    if (depth === 0) {\n      // The node's own union is the one the type builder types it by: its\n      // `oneOf`, else its `anyOf` (`unionVariantsOf`).\n      const variants = bare.oneOf ?? bare.anyOf;\n      if (variants)\n        unions.push({ schema: bare, keyword: bare.oneOf ? 'oneOf' : 'anyOf', variants, origin, discriminator });\n    } else {\n      // A member's unions, one per keyword, as the merge reads them\n      // (`mergeAllOfMembers`, `unionAxesOf`); a nullable wrapper beside the\n      // other keyword is its one variant, read as one more member in the\n      // member's own capacity (`nullableAxisBranch`) — alone, the resolver\n      // collapsed it already (#398 review round 3: a member writing both was\n      // one union read by its `oneOf`, so a stop field only the `anyOf`'s\n      // variants declare, which the model has, resolved to no field).\n      for (const variants of unionAxesOf(bare)) {\n        const keyword = variants === bare.oneOf ? 'oneOf' : 'anyOf';\n        const branch = bare.oneOf && bare.anyOf ? nullableAxisBranch(bare, variants) : undefined;\n        if (branch) {\n          visit(branch, depth, origin, discriminator);\n          continue;\n        }\n        const union: CollectedUnion = { schema: bare, keyword, variants, origin, discriminator };\n        unions.push(union);\n        // What the variants declare, when the model flattens the union into\n        // the node's model (`unionCounts`): branch-only fields of that model,\n        // carried by every instance when every variant declares them.\n        if (!unionCounts(union, named ?? false, componentSchemas)) continue;\n        const read = readFlattenedUnion(union, componentSchemas, walk);\n        for (const [name, declarations] of read.declared) {\n          note(name);\n          const held = branchOnly.get(name);\n          if (held) held.push(...declarations);\n          else branchOnly.set(name, [...declarations]);\n          if (read.carried.has(name)) carried.add(name);\n        }\n      }\n    }\n    for (const sub of bare.allOf ?? []) visit(sub, depth + 1, origin, wrapperDiscriminatorOf(bare));\n    for (const [key, prop] of Object.entries(bare.properties ?? {})) {\n      if (!prop) continue;\n      note(key);\n      const existing = properties[key];\n      properties[key] = existing ? combineDeclarations(existing, prop) : prop;\n    }\n    if (bare.required) required.push(...bare.required);\n  };\n  visit(schema, 0, null);\n\n  // A member's declaration stands whatever a variant says — a variant can\n  // only narrow what every instance carries — and a name only variants\n  // declare is typed as the model types it.\n  const fields: Record<string, SchemaObject> = {};\n  const onEveryInstance: Record<string, SchemaObject> = {};\n  for (const name of order) {\n    const own = properties[name];\n    if (own) {\n      fields[name] = own;\n      onEveryInstance[name] = own;\n      continue;\n    }\n    const declaration = unionOfDeclarations(branchOnly.get(name) ?? []);\n    fields[name] = declaration;\n    if (carried.has(name)) onEveryInstance[name] = declaration;\n  }\n\n  return { properties, required, unions, named: named ?? false, fields, onEveryInstance };\n}\n\n/**\n * What `collectObjectProperties` reads off an object schema: see there.\n * `properties` is what the schema and its always-applying `allOf` members\n * declare, `fields` every property the model built from it has, and\n * `onEveryInstance` the part of `fields` an instance carries whichever\n * variant of a flattened union the wire sends.\n */\nexport interface CollectedProperties {\n  properties: Record<string, SchemaObject>;\n  required: string[];\n  unions: CollectedUnion[];\n  named: boolean;\n  fields: Record<string, SchemaObject>;\n  onEveryInstance: Record<string, SchemaObject>;\n}\n\n/**\n * What a `oneOf`/`anyOf` the model flattens into one model contributes to\n * that model (`collectObjectProperties`, `detectListEnvelope`): `declared`,\n * every property any non-null variant declares, with each variant's\n * declaration of it, in the order first declared — each variant read as the\n * model reads one it flattens (`declareVariant`: its own `properties`, its\n * `allOf` members, the component a `$ref` variant names, the branches of a\n * union nested in it), so the names and the declarations are the merged\n * model's (`mergeAllOfMembers`) — and `carried`, the names every non-null\n * variant declares, resolved as the override walk resolves a path segment\n * through the union (`unionFields`: a variant that is itself a union must\n * declare the name in each of its own variants, and one met again below\n * itself declares nothing), so a field an instance carries whichever\n * variant the wire sends is one the detected stop field and an explicit\n * `endOfIteration` both read, and a field only some variants declare is one\n * neither reads. `lookup` is the walk's bookkeeping (`fieldsNamed`).\n */\nexport function readFlattenedUnion(\n  union: CollectedUnion,\n  componentSchemas?: Record<string, SchemaObject>,\n  lookup: FieldLookup = newFieldLookup(),\n): { declared: Map<string, SchemaObject[]>; carried: Set<string> } {\n  const ledger = new Map<string, PropertyDeclarations>();\n  for (const variant of union.variants) {\n    if (!isNullSchema(variant)) declareVariant(ledger, variant, componentSchemas);\n  }\n  const declared = new Map<string, SchemaObject[]>();\n  const carried = new Set<string>();\n  for (const [name, { conditional }] of ledger) {\n    declared.set(name, conditional);\n    const fields = unionFields(union, name, componentSchemas, lookup);\n    if (fields !== undefined && fields.length > 0) carried.add(name);\n  }\n  return { declared, carried };\n}\n\n/**\n * One `oneOf`/`anyOf` the walk meets (`collectObjectProperties`): the\n * resolved schema that writes it; the component a `$ref` member of an\n * `allOf` on the way names, as the model reads the member (`direct` when\n * that member is one of the node's own and the component itself carries\n * the union), or `null` for a union the node's own model carries — the\n * node itself, or an inline member; and the `discriminator` the document\n * declares for it, on the schema or on the `allOf` wrapper around it\n * (`wrapperDiscriminatorOf`). What the override check decides from\n * (`unionCounts`).\n */\nexport interface CollectedUnion {\n  schema: SchemaObject;\n  keyword: 'oneOf' | 'anyOf';\n  variants: SchemaObject[];\n  origin: { name: string; direct: boolean } | null;\n  discriminator?: SchemaObject['discriminator'];\n}\n\n// ---------------------------------------------------------------------------\n// Resolving a dotted `dataPath`\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a dotted property path (the `dataPath` convention) to the one\n * object it names in a response schema — the walk detection makes to each\n * object on the way to a nested array (`detectEndOfIteration`): each\n * segment is looked up among the object's own properties — through `$ref`s,\n * `allOf` members and nullable wrappers — and the schema it lands on is\n * returned with a final `$ref` resolved. `undefined` when a segment is\n * missing, so also when an object on the way is a `oneOf`/`anyOf` whose\n * variants declare it: a union of models declares no companion a stop\n * field is detected from. A segment every variant of a union the object's\n * `allOf` flattens declares is reached, as the one model's field it is\n * (`onEveryInstance`; workos/oagen#622). An explicit `dataPath` is walked\n * through the variants instead (`resolveDataPathArray`, workos/oagen#556).\n */\nexport function resolveSchemaPath(\n  schema: SchemaObject,\n  path: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): SchemaObject | undefined {\n  let current: SchemaObject | undefined = schema;\n  for (const segment of path.split('.')) {\n    if (!current) return undefined;\n    current = objectProperties(current, componentSchemas)[segment];\n  }\n  if (!current) return undefined;\n  return resolveComponentSchemaRef(current, componentSchemas) ?? current;\n}\n\n/**\n * The array an explicit `dataPath` names in a response body, read from the\n * document: the `items` schema of the array the path lands on, or the reason\n * it lands on none — the text of the warning the override is rejected with\n * (`dataPathProblem`), naming the problem alone.\n *\n * Each segment is looked up as an explicit `endOfIteration` path is\n * (`fieldsAtPath`): among the properties of the object the path has reached,\n * through `$ref`s, `allOf` members and nullable wrappers (what\n * `resolveSchemaPath` reads), and, where that object does not declare the\n * segment itself but is a `oneOf`/`anyOf` or has one among its `allOf`\n * members (`fieldsNamed`), in each non-null variant of that union — and of\n * a variant that is itself a union, inline or a `$ref` to a union\n * component, in each of its own in turn, however deep: whichever\n * variant the wire carries, the array must be there, so `result.items` on\n * `{ result: { oneOf: [A, B] } }` goes on in both `A` and `B`\n * (workos/oagen#556), and on `{ result: { anyOf: [{ oneOf: [A, B] }, B] } }`\n * in all three (PR #585 review). The path then lands on one field per\n * variant, and the override is usable only when every one is an array —\n * under a nullable wrapper too (`resolveBareSchema`) — and the arrays agree\n * on their items, each read as the type builder reads them (`itemsKey`:\n * nullable wrappers and an `allOf` read as one member collapsed, however\n * they alternate): the same component (`$ref: Pet` in both, one of them\n * written `{ allOf: [{ $ref: Pet }], description }`, the OAS 3.0 way of\n * describing a `$ref`) or the same inline shape (`schemaShapeKey`, which\n * reads past descriptions and extensions), admitting `null` alike, since\n * the SDK iterates one item type whichever variant arrives. The first\n * array's `items` stands for them all, as written. A variant that lacks the\n * segment, declares it as something other than an array, or types its items\n * otherwise (`Pet` in one variant, `Cat` in another) makes the path\n * unusable, and the reason says which variant lacks the field — the one of\n * its own, below a variant that is itself a union — or how the variants\n * type it. An array without `items` is no array an iterator can type, as\n * it never was.\n */\nexport function resolveDataPathArray(\n  schema: SchemaObject,\n  dataPath: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): { items: SchemaObject } | { problem: string } {\n  const walked = walkDataPathArray(schema, dataPath, componentSchemas);\n  return 'items' in walked ? { items: walked.items } : walked;\n}\n\n/**\n * Whether an explicit `dataPath` lands on more than one array: it went on\n * through the variants of a union on its way — the body itself, or an\n * object on the way, being a `oneOf`/`anyOf` or having one among its\n * `allOf` members (`fieldsNamed`) — and the variants reach distinct arrays,\n * their `items` distinct schemas in the document. Each variant's model then\n * types inline items under a name of its own, and only the document can\n * type them once, under the path-derived name (#556), so an override whose\n * IR walk crossed a pending pointer reference reads the document at\n * extraction for such a path rather than deferring to the settle, where the\n * IR walk would find the variants' arrays disagreeing by name\n * (`resolveOverrideItemType`; Greptile, #608 review). Variants that reach\n * one array are no fork — every variant holding the same pointer (`{ oneOf:\n * [A, B] }`, both `result: { $ref: '#/components/schemas/Holder/properties/\n * result' }`, with `dataPath: 'result.items'`), or pointers that resolve to\n * one component, as `resolveBareSchema` follows them — since the one schema\n * is built as one model where it stands and the settled walk agrees on its\n * items (`HolderResultItem`), exactly as both holding `$ref: Result` agree\n * on `ResultItem` (MichaelDeBoey, #651 review); the arrays are told apart\n * by their `items` object rather than their own, which a nullable array\n * component unwraps to afresh at each reading. A `null` variant set aside\n * as a nullable wrapper is no fork either. `false` for a path that lands on\n * no array.\n */\nexport function dataPathForks(\n  schema: SchemaObject,\n  dataPath: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): boolean {\n  const walked = walkDataPathArray(schema, dataPath, componentSchemas);\n  return 'items' in walked && walked.forked;\n}\n\n/** The walk `resolveDataPathArray` makes, saying too whether the path landed on more than one array (`forked`; see `dataPathForks`). */\nfunction walkDataPathArray(\n  schema: SchemaObject,\n  dataPath: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): { items: SchemaObject; forked: boolean } | { problem: string } {\n  const missing = `dataPath \"${dataPath}\" does not resolve to an array in the response`;\n  const segments = dataPath.split('.');\n  // The path to the first union the walk went on through (`''` for the body\n  // itself), which the reason names when the variants disagree.\n  let union: string | undefined;\n  // Every schema the path has reached so far, each with the variant it came\n  // through (`variant 2 of the oneOf at \"result\"`), none for the body itself\n  // or a field an object declares on its own.\n  let reached: Array<{ schema: SchemaObject; via?: string }> = [{ schema }];\n  const lookup = newFieldLookup();\n  for (const [depth, segment] of segments.entries()) {\n    const prefix = segments.slice(0, depth).join('.');\n    const next = new Map<string | SchemaObject, { schema: SchemaObject; via?: string }>();\n    for (const { schema: node, via } of reached) {\n      const named = fieldsNamed(node, segment, componentSchemas, lookup);\n      if (!named) {\n        const lacking = variantLacking(node, segment, componentSchemas, lookup);\n        const reason = lacking\n          ? `${variantLabel(lacking, prefix)} declares no \"${segment}\"`\n          : via === undefined\n            ? undefined\n            : `${unionAt(prefix)} declares no \"${segment}\" in ${via}`;\n        return { problem: reason ? `${missing}: ${reason}` : missing };\n      }\n      for (const field of named) {\n        if (field.via) union ??= prefix;\n        const label = field.via ? variantLabel(field.via, prefix) : via;\n        next.set(field.schema.$ref ?? field.schema, { schema: field.schema, via: label });\n      }\n    }\n    reached = [...next.values()];\n  }\n  const bare = reached.map(({ schema: field }) => resolveBareSchema(field, componentSchemas));\n  const arrays = bare.filter((field) => isArraySchema(field) && field.items !== undefined);\n  if (arrays.length < bare.length) {\n    if (union === undefined) return { problem: missing };\n    return { problem: `${missing}: the variants of ${unionAt(union)} type it as ${listed(bare.map(describeSchema))}` };\n  }\n  const items = arrays.map((array) => array.items as SchemaObject);\n  if (new Set(items.map(itemsKey)).size > 1) {\n    return {\n      problem:\n        `dataPath \"${dataPath}\" does not resolve to one array in the response: ` +\n        `the variants of ${unionAt(union ?? '')} type its items as ${listed(items.map(describeItems))}`,\n    };\n  }\n  return { items: items[0], forked: new Set(items).size > 1 };\n}\n\n/**\n * An array's `items` as the type builder reads them, for deciding whether\n * two variants' arrays iterate one type: a nullable wrapper of any spelling\n * (`unwrapNullableSchema`) and an `allOf` read as one member — a lone\n * member with nothing added to it, or a plain reference\n * (`allOfReadAsMember`) — collapsed, however the two alternate, as\n * `arraySchemaOf` finds an array and `resolveBareSchema` reads a stop field\n * (PR #585 review: `{ allOf: [{ $ref: Pet }], description: 'A pet' }` beside\n * `{ $ref: Pet }` was rejected as `Pet and allOf`, though both variants'\n * models type the field `Pet[]` and the OAS 3.1 sibling form `{ $ref: Pet,\n * description }` was accepted). A `$ref` is kept as the reference it is, so\n * two components alike in shape are still two types.\n */\nfunction bareItems(items: SchemaObject): SchemaObject {\n  const bare = unwrapNullableSchema(items);\n  const member = allOfReadAsMember(bare);\n  return member ? bareItems(member) : bare;\n}\n\n/**\n * What an array's `items` type, as one string two arrays share exactly when\n * the SDK iterates one type: whether they admit `null` (`declaresNull`,\n * through the same wrappers `bareItems` collapses), and the shape of what\n * is left (`schemaShapeKey`, which reads past descriptions and extensions).\n */\nfunction itemsKey(items: SchemaObject): string {\n  return `${declaresNull(items) ? 'null | ' : ''}${schemaShapeKey(bareItems(items))}`;\n}\n\n/** An array's `items` in a word, for a warning: what the type builder reads (`describeSchema`), `| null` when they admit null. */\nfunction describeItems(items: SchemaObject): string {\n  const bare = bareItems(items);\n  const word = describeSchema(bare);\n  return declaresNull(items) && !hasType(bare, 'null') ? `${word} | null` : word;\n}\n\n/**\n * Why an explicit `dataPath` cannot be read from the body `schema`, or\n * `undefined` when it can (`resolveDataPathArray`). With no `schema` — an\n * operation whose primary response declares no body — the path resolves to\n * nothing. The text is the reason alone, as `endOfIterationProblem`'s is;\n * the caller names the override's source and the operation, and says what\n * it does about it.\n */\nexport function dataPathProblem(\n  schema: SchemaObject | undefined,\n  dataPath: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): string | undefined {\n  if (!schema) return `dataPath \"${dataPath}\" does not resolve to an array in the response`;\n  const resolved = resolveDataPathArray(schema, dataPath, componentSchemas);\n  return 'problem' in resolved ? resolved.problem : undefined;\n}\n\n/**\n * Which variant of a union `node` is composed of lacks `segment`, when that\n * is why `fieldsNamed` found no field of that name — the steps down to it,\n * which `variantLabel` renders (`variant 2 of the oneOf at \"result\"\n * declares no \"items\"`) — for the warning a `dataPath` is rejected with.\n * The unions are read in the order `fieldsNamed` reads them, the ones it\n * counts (`unionCounts`); the first with\n * a non-null variant that declares no such property, by the rule\n * `fieldsNamed` applies to a variant, explains the miss, and when that\n * variant is itself a union the steps go on into it, to the variant of its\n * own that lacks the field (`variant 2 of the oneOf in variant 1 of the\n * anyOf at \"result\"`), so the warning never says a variant declares no\n * field its own variants all declare (PR #585 review); a variant met again\n * below itself declares nothing, so the steps end at the one it was met\n * below (`variant 1 of the oneOf at \"result\"` for `Loop: { oneOf: [{ $ref:\n * Loop }, A] }`). `undefined` when none does: no union at all, or one left\n * to the component that dispatches it, whatever its variants declare\n * (`unionCounts`), which the plain reason covers. `lookup` is the walk's,\n * so the variants' fields are read once (`fieldsNamed`).\n */\nfunction variantLacking(\n  node: SchemaObject,\n  segment: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  lookup: FieldLookup,\n  walking: Set<SchemaObject> = new Set(),\n): VariantStep[] | undefined {\n  const { unions, named } = collectObjectProperties(node, componentSchemas);\n  for (const union of unions) {\n    if (!unionCounts(union, named, componentSchemas)) continue;\n    for (const { step, variant } of variantsOf(union)) {\n      if (fieldsNamed(variant, segment, componentSchemas, lookup)) continue;\n      // Met again below itself: it declares nothing, and the step above names it.\n      if (walking.has(variant)) return undefined;\n      walking.add(variant);\n      const below = variantLacking(variant, segment, componentSchemas, lookup, walking);\n      walking.delete(variant);\n      return [step, ...(below ?? [])];\n    }\n  }\n  return undefined;\n}\n\n/**\n * A name for the variant `via` leads to, for a `dataPath` warning: its\n * place among the variants of the `oneOf`/`anyOf` at `prefix` (`''` for the\n * body itself), counted as written with the `null` variants in place —\n * `variant 3 of the oneOf at \"result\"` for the third one listed, whatever\n * sits before it; `variant 2 of the response's oneOf` for the body — and,\n * below a variant that is itself a union, each further step in turn:\n * `variant 2 of the oneOf in variant 1 of the anyOf at \"result\"`.\n */\nfunction variantLabel(via: readonly VariantStep[], prefix: string): string {\n  const [outer, ...inner] = via as [VariantStep, ...VariantStep[]];\n  const at = prefix === '' ? `the response's ${outer.keyword}` : `the ${outer.keyword} at \"${prefix}\"`;\n  return inner.reduce(\n    (label, step) => `variant ${step.index} of the ${step.keyword} in ${label}`,\n    `variant ${outer.index} of ${at}`,\n  );\n}\n\n/** The object whose variants a `dataPath` warning speaks of: the body itself, or the property at `path`. */\nfunction unionAt(path: string): string {\n  return path === '' ? 'the response' : `\"${path}\"`;\n}\n\n/** The distinct entries of `words`, as prose: `a`, `a and b`, `a, b and c`. */\nfunction listed(words: string[]): string {\n  const distinct = [...new Set(words)];\n  if (distinct.length < 2) return distinct.join('');\n  return `${distinct.slice(0, -1).join(', ')} and ${distinct[distinct.length - 1]}`;\n}\n\n/**\n * A schema's type in a word, for a warning: a component's name for a `$ref`\n * to one, the `$ref` as written for any other (a pointer deeper into a\n * component; #539), `Pet[]` for an array of them (`array` without `items`),\n * its `type` as written (`string`, `string | null`), else the composition\n * keyword it is.\n */\nfunction describeSchema(schema: SchemaObject): string {\n  if (schema.$ref) return componentKeyOf(schema.$ref) ?? schema.$ref;\n  if (isArraySchema(schema)) return schema.items ? `${describeSchema(schema.items)}[]` : 'array';\n  const { type } = schema;\n  if (type !== undefined) return Array.isArray(type) ? type.join(' | ') : type;\n  return schema.oneOf ? 'oneOf' : schema.anyOf ? 'anyOf' : schema.allOf ? 'allOf' : 'untyped';\n}\n\n/**\n * Resolve a dotted `dataPath` against the IR rather than the document: walk\n * from the response type through model fields, under every nullable wrapper\n * (`containersOf`), and return the element type of the array the path lands\n * on. `models` is where\n * each model along the way is looked up by name, so the item type is exactly\n * the one the parser already assigned — the very `TypeRef` object the field\n * holds, which later renaming passes repoint in place. A `union` on the way\n * is walked through each of its variants, as the document walk goes on\n * through each variant of a `oneOf`/`anyOf` (`resolveDataPathArray`,\n * workos/oagen#556): every variant must be a model that declares the\n * segment — a variant that is itself a union, each of its own in turn\n * (`containersOf`) — and the arrays reached must agree on their items — the\n * same `TypeRef` by value, `Pet` in `ListPetsResponseResult.items` and in\n * `ListPetsResponseResultWithTotal.items` — the first of which is returned.\n * The types reached are counted once per segment — a model or enum by its\n * name, any other by its shape (`typeRefKey`) — as the document walk counts\n * a schema once, so a union two models reach each other through (`A.next`\n * and `B.next` both `A | B`) is read once per segment however long the\n * path, not once per way of reaching it (PR #585 review: a `next.next.….\n * items` path doubled the work at every segment). An empty `dataPath` means\n * `root` itself is the array. `undefined` when a segment is missing, a model\n * is unknown, the path does not end on an array, or the variants disagree —\n * and when the walk crosses a reference `resolveSchemaPointers` has yet to\n * settle, which `walkDataPathItemType` tells apart from the rest; the\n * document walk then answers (`resolveDataPathFromSchema`).\n */\nexport function resolveDataPathItemType(\n  root: TypeRef,\n  dataPath: string,\n  models: readonly Model[],\n): TypeRef | undefined {\n  const walked = walkDataPathItemType(root, dataPath, models);\n  return walked && 'itemType' in walked ? walked.itemType : undefined;\n}\n\n/**\n * The walk `resolveDataPathItemType` makes, telling a path the IR cannot\n * resolve yet from one it does not resolve: `{ pending: true }` when a type\n * the walk reaches — the root, a field's type on the way, a variant of a\n * union there, or the type the path lands on, under its nullable wrapper —\n * is a reference a schema `$ref` deeper into a component left pending\n * (`pendingSchemaRef`; #539), which names no model until\n * `resolveSchemaPointers` settles it. Every type a segment reaches is\n * checked for one before any field is looked up, so the answer never\n * depends on which variant of a union is read first. A named union model\n * on the way, or where the path lands, is read through its variants\n * (`containersOf`), as an inline union is.\n */\nexport function walkDataPathItemType(\n  root: TypeRef,\n  dataPath: string,\n  models: readonly Model[],\n): { itemType: TypeRef } | { pending: true } | undefined {\n  const reader = new ContainerReader(models);\n  let reached: TypeRef[] = [root];\n  for (const segment of dataPath === '' ? [] : dataPath.split('.')) {\n    const containers = new Map<string, TypeRef>();\n    for (const type of reached) {\n      for (const container of reader.containersOf(type)) containers.set(typeRefKey(container), container);\n    }\n    if ([...containers.values()].some(isPendingModelRef)) return { pending: true };\n    const next = new Map<string, TypeRef>();\n    for (const container of containers.values()) {\n      if (container.kind !== 'model') return undefined;\n      const field = models.find((m) => m.name === container.name)?.fields.find((f) => f.name === segment);\n      if (!field) return undefined;\n      next.set(typeRefKey(field.type), field.type);\n    }\n    reached = [...next.values()];\n  }\n  const targets = reached.flatMap((type) => reader.containersOf(type));\n  if (targets.some(isPendingModelRef)) return { pending: true };\n  const items = targets.map((target) => (target.kind === 'array' ? target.items : undefined));\n  const [first, ...rest] = items;\n  return first && rest.every((item) => item !== undefined && isDeepStrictEqual(item, first))\n    ? { itemType: first }\n    : undefined;\n}\n\n/** Whether `type` is a model reference `resolveSchemaPointers` has yet to settle (#539). */\nfunction isPendingModelRef(type: TypeRef): boolean {\n  return type.kind === 'model' && isPendingSchemaRef(type);\n}\n\n/**\n * Where an explicit `dataPath` is walked from in the IR, and the path left\n * to walk from there: the response itself, unless the response was unwrapped\n * on a list envelope (`envelopeFields` present) — it is then the data array,\n * and the path starts at the companion its first segment names, with the\n * rest of the path; `undefined` when the segment names no companion, and the\n * document answers. The one choice for the walk at extraction\n * (`resolveOverrideItemType`) and the walk at the settle\n * (`settleDeferredDataPathItemType`), so the two read one path.\n */\nexport function dataPathWalkStart(\n  response: TypeRef,\n  envelopeFields: readonly Field[] | undefined,\n  dataPath: string,\n): { root: TypeRef; path: string } | undefined {\n  if (!envelopeFields) return { root: response, path: dataPath };\n  const [head, ...rest] = dataPath.split('.');\n  const companion = envelopeFields.find((field) => field.name === head);\n  return companion && { root: companion.type, path: rest.join('.') };\n}\n\n/**\n * The iterator item types an explicit `dataPath` has yet to decide (#608):\n * each a placeholder, typed `unknown`, standing in `PaginationMeta.itemType`\n * from extraction until the settle. The walk from the response crossed a\n * reference a schema `$ref` deeper into a component left pending — the\n * response itself written as `{ $ref: '#/components/schemas/Holder/\n * properties/result' }`, or a field on the way — so the model the pointed\n * schema's items are built as (`HolderResultItem`, which\n * `HolderResult.items` holds) exists but cannot be reached from the response\n * yet; reading the document instead minted a second copy of it under the\n * path-derived name (`ListOwnersItem`). The path is walked again once every\n * reference is settled (`settleDeferredDataPathItemType`), so the iterator\n * yields the very type the settled response's field holds, as it does when\n * the response is a `$ref` to the component (`ResultItem` for `Result`).\n */\nconst deferredDataPathItemTypes = new WeakSet<TypeRef>();\n\n/** A placeholder item type for a `dataPath` the settle decides (`settleDeferredDataPathItemType`). */\nexport function deferDataPathItemType(): TypeRef {\n  const placeholder: TypeRef = { kind: 'primitive', type: 'unknown' };\n  deferredDataPathItemTypes.add(placeholder);\n  return placeholder;\n}\n\n/** Whether `type` is a placeholder `deferDataPathItemType` built, awaiting the settle. */\nexport function isDeferredDataPathItemType(type: TypeRef): boolean {\n  return deferredDataPathItemTypes.has(type);\n}\n\n/**\n * Decide the item type `pagination.dataPath` names, now that `response`,\n * the envelope's companions and every model's fields are settled\n * (`resolveSchemaPointers`): the path is walked from where it was walked at\n * extraction (`dataPathWalkStart`), through `models` — every model built —\n * and `pagination.itemType` becomes the very `TypeRef` the array's field\n * holds, which a later rename repoints in place. A path the settled types\n * reach no array through yields `unknown`, with a warning: the override\n * was accepted on the document walk, which reads through the pointer, but\n * the pointer was typed `unknown` where it stands (an inline `allOf`\n * member the `allOf` is not read as, a chain of pointers that reaches\n * itself), and the iterator cannot yield a model the response does not\n * hold. `context` names the operation as the settle names its sites\n * (`Owners.listOwners`).\n */\nexport function settleDeferredDataPathItemType(\n  pagination: PaginationMeta,\n  response: TypeRef,\n  models: readonly Model[],\n  context: string,\n): void {\n  const { dataPath } = pagination;\n  const start = dataPath === undefined ? undefined : dataPathWalkStart(response, pagination.envelopeFields, dataPath);\n  const itemType = start && resolveDataPathItemType(start.root, start.path, models);\n  if (itemType) {\n    pagination.itemType = itemType;\n    return;\n  }\n  warn(\n    `dataPath \"${dataPath}\" on ${context} reaches no array in the response once its schema $ref is settled — typing the iterator's items as unknown`,\n  );\n  pagination.itemType = { kind: 'primitive', type: 'unknown' };\n}\n\n/**\n * One walk's reading of the types a `dataPath` segment is looked up in\n * below a type (`containersOf`): the type under every nullable wrapper — a\n * site settled from a pointer to a schema that admits null wears two,\n * `nullable<nullable<HolderResult>>` for `oneOf: [{ $ref:\n * …/Holder/properties/result }, { type: null }]` to a nullable `result`\n * (#545; Greptile, #608 review) — or each variant of a `oneOf`/`anyOf`\n * union there, under its own wrappers, and, for a variant that is itself a\n * union, each of its variants in turn, however deep, as the document walk\n * reads a nested union's variants (`fieldsNamed`). Of a union a type list\n * produced (`type: ['object', 'string']`, one variant per type and no\n * `compositionKind`), the variants that are models: the document walk\n * reads such a schema's `properties` whatever else the list names\n * (`objectProperties`), and a pointer steps through it to the member that\n * carries the keyword (#539), so the IR walk reads the object member too\n * rather than failing on the string member and minting a copy of the\n * items the object member's model holds. Of a named union model\n * (`Model.variants`, looked up in `models`; `Page: { oneOf: [{ $ref:\n * Result }, { type: null }] }` is a model `Page` with the one variant\n * `Result` and no fields), its variants, each in turn as above, as the\n * document walk reads the component's `oneOf`/`anyOf` members — a pointer\n * settled to `nullable<Page>` reads `Result`'s fields, rather than failing\n * on `Page`'s none and typing the iterator `unknown` (Greptile, #608\n * review).\n *\n * Each named union model is expanded once per walk, however many routes\n * reach it (`memo`), and the types read are kept distinct as they are\n * collected (`typeRefKey`): expanded once per route, twenty-five\n * components each an `anyOf` of two references to the next expanded the\n * last 2^25 times, and a document of a few hundred lines took seconds, or\n * the memory, before the caller deduped (Greptile, #608 review) — as the\n * document walk reads each schema once per segment (`fieldsNamed`). A\n * model met again while being expanded (a union reaching itself through\n * its variants) contributes nothing more on that route, and a model\n * expanded while such a cycle was open above it is not memoized, since its\n * reading would depend on the route (`closed`, as `fieldsNamed` keeps its\n * memo).\n */\nclass ContainerReader {\n  private readonly memo = new Map<string, TypeRef[]>();\n  /** The named union models being expanded, outermost first. */\n  private readonly stack: string[] = [];\n  /** The lowest depth in `stack` a cycle closed at during the expansion under way; `Infinity` for none. */\n  private closed = Infinity;\n\n  constructor(private readonly models: readonly Model[]) {}\n\n  containersOf(type: TypeRef): TypeRef[] {\n    const bare = underNullable(type);\n    if (bare.kind === 'model') return this.namedUnionContainers(bare);\n    if (bare.kind !== 'union') return [bare];\n    const members = this.distinct(bare.variants);\n    if (bare.compositionKind) return members;\n    const modelMembers = members.filter((member) => member.kind === 'model');\n    return modelMembers.length > 0 ? modelMembers : members;\n  }\n\n  /** `ref` itself for a model with fields; a named union's variants' containers, read once. */\n  private namedUnionContainers(ref: ModelRef): TypeRef[] {\n    const done = this.memo.get(ref.name);\n    if (done) return done;\n    const variants = this.models.find((m) => m.name === ref.name)?.variants;\n    if (!variants) return [ref];\n    const above = this.stack.indexOf(ref.name);\n    if (above !== -1) {\n      this.closed = Math.min(this.closed, above);\n      return [];\n    }\n    const depth = this.stack.push(ref.name) - 1;\n    const outer = this.closed;\n    this.closed = Infinity;\n    const containers = this.distinct(variants);\n    this.stack.pop();\n    if (this.closed >= depth) this.memo.set(ref.name, containers);\n    this.closed = Math.min(outer, this.closed);\n    return containers;\n  }\n\n  /** The containers of each of `types`, one per `typeRefKey`. */\n  private distinct(types: readonly TypeRef[]): TypeRef[] {\n    const out = new Map<string, TypeRef>();\n    for (const type of types) {\n      for (const container of this.containersOf(type)) out.set(typeRefKey(container), container);\n    }\n    return [...out.values()];\n  }\n}\n\n/** `type` under every nullable wrapper it wears. */\nfunction underNullable(type: TypeRef): TypeRef {\n  let bare = type;\n  while (bare.kind === 'nullable') bare = bare.inner;\n  return bare;\n}\n\n/** A key two `TypeRef`s share exactly when they are one type to look a field up in: a model's or enum's name, else the TypeRef's shape. */\nfunction typeRefKey(type: TypeRef): string {\n  return type.kind === 'model' || type.kind === 'enum' ? `${type.kind}:${type.name}` : JSON.stringify(type);\n}\n\n// ---------------------------------------------------------------------------\n// Explicit overrides — `x-pagination` and `operationHints[...].pagination`\n// ---------------------------------------------------------------------------\n\nconst STRATEGIES: ReadonlyArray<PaginationStrategy | 'none'> = ['cursor', 'offset', 'page', 'link-header', 'none'];\n\nexport interface PaginationOverrides {\n  /** The operation's `x-pagination` extension, exactly as written in the document. */\n  extension?: unknown;\n  /** `operationHints[\"METHOD /path\"].pagination` from the consumer's config. */\n  hint?: unknown;\n}\n\n/** The validated, merged override for one operation, with the source(s) it came from for warnings. */\nexport interface ResolvedPaginationOverride {\n  hint: PaginationHint;\n  source: string;\n}\n\n/**\n * Validate and merge the two override sources. Precedence per field: config\n * hint, then `x-pagination`; a source that fails validation is dropped with\n * an `[oagen] Warning:` and the other still applies. `undefined` when neither\n * source is present or usable.\n *\n * Resolved before the response is classified, because `strategy: 'none'`\n * must keep a list envelope from being unwrapped and an explicit `dataPath`\n * is resolved against the response while its schema is at hand.\n */\nexport function resolvePaginationOverride(\n  sources: PaginationOverrides,\n  opLabel: string,\n): ResolvedPaginationOverride | undefined {\n  const extension =\n    sources.extension === undefined ? undefined : validatePaginationHint(sources.extension, 'x-pagination', opLabel);\n  const hint =\n    sources.hint === undefined ? undefined : validatePaginationHint(sources.hint, 'operationHints pagination', opLabel);\n  if (!extension && !hint) return undefined;\n  const source = [extension && 'x-pagination', hint && 'operationHints pagination'].filter(Boolean).join(' / ');\n  return { hint: { ...extension, ...hint }, source };\n}\n\n/**\n * Layer the resolved override onto the detected pagination. A field the\n * override does not set keeps the detected value, so `{ strategy: 'page' }`\n * alone re-labels a detected offset iterator without restating its\n * parameters — except `param`, which is first looked for among the\n * operation's query parameters by the strategy's own names (`page` for\n * `page`, `cursor` or `after` for `cursor`, ...), so a strategy the override\n * names is driven by the parameter that fits it rather than by one detection\n * found for another strategy. `extras.overrideItemType` is the element type an explicit\n * `dataPath` resolved to; without it the detected item type (or the response\n * itself) stands. `extras.envelope` is the list envelope the response was\n * unwrapped on — `dataPath`, `dataDescription`, `itemType`, `envelopeFields`\n * as detection read them — whichever parameter drives the iterator: it is\n * read when `detected` is unset, so an override that creates the iterator\n * where the query parameters yielded none (`{ strategy: 'cursor', param:\n * 'c' }` on `{ data, has_more }`) still describes that envelope; when a\n * parameter was recognized, `detected` carries the same values and is read\n * first. `extras.endOfIteration` is the stop field read from the\n * response, which belongs to the iterator whether detection built one or the\n * override creates it from scratch (no paging parameter recognized, a\n * wrapper kept under an explicit `dataPath`): the override's own\n * `endOfIteration` wins, then the detected iterator's, then it.\n * `extras.pageStartOf` decides the first page for the page\n * parameter in use (default: `derivePageStart` on the IR parameter alone).\n *\n * Returns `detected` unchanged when there is no override or it is unusable —\n * no strategy or no `param` from any source, a `pageStart` under a strategy\n * other than `page`, a resolved `param`/`limitParam` the operation does not\n * declare as a query parameter, one parameter resolved as both — after an\n * `[oagen] Warning:` naming the problem (`resolveOverrideParams`). An\n * explicit `endOfIteration` is checked against the primary response before\n * this is reached (`endOfIterationProblem`, asked by `extractResponses`), so\n * one that arrives here resolves and fits. `strategy: 'none'` yields\n * `undefined`.\n */\nexport function applyPaginationOverride(\n  detected: PaginationMeta | undefined,\n  override: ResolvedPaginationOverride | undefined,\n  queryParams: Parameter[],\n  response: TypeRef,\n  opLabel: string,\n  extras: {\n    overrideItemType?: TypeRef;\n    envelope?: Pick<PaginationMeta, 'dataPath' | 'dataDescription' | 'itemType' | 'envelopeFields'>;\n    endOfIteration?: PaginationEndOfIteration;\n    pageStartOf?: PageStartResolver;\n  } = {},\n): PaginationMeta | undefined {\n  if (!override) return detected;\n  const merged = override.hint;\n  const where = `${override.source} on ${opLabel}`;\n\n  if (merged.strategy === 'none') return undefined;\n\n  const resolved = resolveOverrideParams(detected, merged, queryParams);\n  if ('problem' in resolved) {\n    warn(`${where}${resolved.problem}`);\n    return detected;\n  }\n  const { strategy, param, limitParam } = resolved;\n\n  // What detection read from the response: the detected iterator's own\n  // values, else the envelope unwrapped for an iterator only the override\n  // creates.\n  const list = detected ?? extras.envelope;\n  const dataPath = merged.dataPath ?? list?.dataPath;\n  // The data array's description belongs to the array detection unwrapped;\n  // it survives an override that keeps that array.\n  const dataDescription = dataPath === list?.dataPath ? list?.dataDescription : undefined;\n  const endOfIteration = merged.endOfIteration ?? detected?.endOfIteration ?? extras.endOfIteration;\n  // The page base belongs to the page parameter actually in use, which the\n  // override may have swapped, so it is derived from that parameter rather\n  // than carried over from detection.\n  const pageStartOf = extras.pageStartOf ?? derivePageStart;\n  const pageStart =\n    strategy === 'page' ? (merged.pageStart ?? pageStartOf(queryParams.find((p) => p.name === param))) : undefined;\n  return {\n    strategy,\n    param,\n    ...(limitParam !== undefined && { limitParam }),\n    ...(pageStart !== undefined && { pageStart }),\n    ...(dataPath !== undefined && { dataPath }),\n    ...(dataDescription !== undefined && { dataDescription }),\n    itemType: extras.overrideItemType ?? list?.itemType ?? (response.kind === 'array' ? response.items : response),\n    ...(list?.envelopeFields && { envelopeFields: list.envelopeFields }),\n    ...(endOfIteration && { endOfIteration }),\n  };\n}\n\n/**\n * The strategy, `param` and `limitParam` an override resolves to against\n * what was detected, or the reason it cannot apply (the text of the warning\n * `applyPaginationOverride` emits): no strategy from any source, a\n * `pageStart` under a strategy other than `page`, no `param` from any\n * source, a resolved `param` or `limitParam` the operation does not declare\n * as a query parameter, or one query parameter resolved as both. Shared with\n * `buildOperation`, which asks before classification whether an override\n * will be usable, so an override that will be rejected never changes how\n * the response is read.\n */\nexport function resolveOverrideParams(\n  detected: PaginationMeta | undefined,\n  merged: PaginationHint,\n  queryParams: Parameter[],\n): { strategy: PaginationStrategy; param: string; limitParam?: string } | { problem: string } {\n  const strategy = merged.strategy === 'none' ? undefined : (merged.strategy ?? detected?.strategy);\n  if (!strategy) return { problem: ' sets no strategy and none was detected — ignoring the override' };\n  // A first page number means nothing to an iterator that does not count\n  // pages, so one set for another strategy is a contradiction, not a field\n  // to drop quietly.\n  if (merged.pageStart !== undefined && strategy !== 'page') {\n    return {\n      problem: `: pageStart ${merged.pageStart} applies to the \"page\" strategy only, not to \"${strategy}\" — ignoring the override`,\n    };\n  }\n  const param = merged.param ?? declaredParamFor(strategy, queryParams) ?? detected?.param;\n  if (!param) {\n    return {\n      problem: `: strategy \"${strategy}\" needs a param, and none was given or detected — ignoring the override`,\n    };\n  }\n  const limitParam = merged.limitParam ?? detected?.limitParam;\n  // The resolved values are checked, not only the explicit ones: a `param`\n  // carried over from detection for another strategy is as undeclared as a\n  // misspelled one when the operation does not declare it.\n  for (const [key, name] of [\n    ['param', param],\n    ['limitParam', limitParam],\n  ] as const) {\n    if (name !== undefined && !queryParams.some((p) => p.name === name)) {\n      return { problem: `: ${key} \"${name}\" is not a query parameter of the operation — ignoring the override` };\n    }\n  }\n  // The two are checked against each other as resolved, so `{ param:\n  // 'limit' }` next to a detected `limitParam: 'limit'` is caught as surely\n  // as an override that names the same parameter twice: one parameter\n  // cannot carry both the page and the page size.\n  if (param === limitParam) {\n    return { problem: `: param and limitParam both name \"${param}\" — ignoring the override` };\n  }\n  return { strategy, param, ...(limitParam !== undefined && { limitParam }) };\n}\n\n/** The first query parameter the operation declares under one of `strategy`'s own parameter names, if any. */\nfunction declaredParamFor(strategy: PaginationStrategy, queryParams: Parameter[]): string | undefined {\n  const names =\n    strategy === 'cursor'\n      ? CURSOR_PARAMS\n      : strategy === 'offset'\n        ? OFFSET_PARAMS\n        : strategy === 'page'\n          ? PAGE_PARAMS\n          : [];\n  return names.map((name) => queryParams.find((p) => p.name === name)).find((p) => p !== undefined)?.name;\n}\n\n/**\n * Check one override object's shape. Returns the typed hint with only the\n * keys the author set, or `undefined` after a warning when any field is\n * malformed. An unknown key is reported and skipped without invalidating the\n * rest, and a key set to `undefined` counts as absent. What the fields say\n * about the operation — whether the parameters are declared, the `dataPath`\n * reaches an array, the `endOfIteration` resolves to a field of the fitting\n * type — is checked later, against the operation (`resolveOverrideParams`,\n * `endOfIterationProblem`).\n */\nexport function validatePaginationHint(raw: unknown, source: string, opLabel: string): PaginationHint | undefined {\n  const where = `${source} on ${opLabel}`;\n  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n    warn(`${where} must be an object — ignoring it`);\n    return undefined;\n  }\n\n  const out: PaginationHint = {};\n  for (const [key, value] of Object.entries(raw)) {\n    if (value === undefined) continue;\n    switch (key) {\n      case 'strategy':\n        if (typeof value !== 'string' || !(STRATEGIES as readonly string[]).includes(value)) {\n          const expected = STRATEGIES.map((s) => `\"${s}\"`).join(', ');\n          warn(`${where}: unknown strategy ${JSON.stringify(value)} (expected one of ${expected}) — ignoring it`);\n          return undefined;\n        }\n        out.strategy = value as PaginationStrategy | 'none';\n        break;\n      case 'param':\n      case 'limitParam':\n      case 'dataPath':\n        if (typeof value !== 'string' || value.trim() === '') {\n          warn(`${where}: ${key} must be a non-empty string — ignoring it`);\n          return undefined;\n        }\n        out[key] = value;\n        break;\n      case 'pageStart':\n        if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n          warn(`${where}: pageStart must be a non-negative integer — ignoring it`);\n          return undefined;\n        }\n        out.pageStart = value;\n        break;\n      case 'endOfIteration': {\n        const end = validateEndOfIteration(value);\n        if (!end) {\n          warn(\n            `${where}: endOfIteration must be { kind: \"hasMore\" | \"totalPages\" | \"totalCount\", path: string } — ignoring it`,\n          );\n          return undefined;\n        }\n        out.endOfIteration = end;\n        break;\n      }\n      default:\n        warn(`${where}: unknown key \"${key}\" skipped`);\n    }\n  }\n  return out;\n}\n\n/** The shape alone: a known `kind` and a non-empty `path`. Whether the path resolves is `endOfIterationProblem`'s question. */\nfunction validateEndOfIteration(value: unknown): PaginationEndOfIteration | undefined {\n  if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;\n  const { kind, path } = value as { kind?: unknown; path?: unknown };\n  if (!(END_KIND_PRIORITY as readonly unknown[]).includes(kind)) return undefined;\n  if (typeof path !== 'string' || path.trim() === '') return undefined;\n  return { kind: kind as PaginationEndOfIteration['kind'], path };\n}\n\nfunction warn(message: string): void {\n  console.warn(`[oagen] Warning: ${message}`);\n}\n\n/**\n * The type an iterator yields from `response`: the items of a top-level\n * array, under every nullable wrapper it wears too — one for an OAS 3.0\n * `nullable: true` array response (`nullable<array<T>>`), two for a\n * nullable site settled from a pointer to a schema that admits null\n * (`{ oneOf: [{ $ref: '#/components/schemas/Holder/properties/owners' },\n * { type: 'null' }] }` to `owners: { type: ['array', 'null'] }`, which the\n * settle leaves as `nullable<nullable<array<T>>>`; #609) — else the\n * response itself.\n */\nexport function paginatedItemType(response: TypeRef): TypeRef {\n  let inner = response;\n  while (inner.kind === 'nullable') inner = inner.inner;\n  return inner.kind === 'array' ? inner.items : response;\n}\n","/**\n * Materialize an inline schema that is not a model field — a response\n * header, a `default`/`nXX` body, a secondary content type — under names no\n * other model owns, through the extractor every field goes through.\n *\n * The schema is extracted as if it were a property of a parent (or of no\n * parent), so every shape a field can take is materialized under the name\n * `schemaToTypeRef` references it by, by construction. The resulting models\n * are checked against a spec-wide registry of model shapes; the rules for a\n * taken name are the same everywhere this is used (see\n * `materializeInlineSchema`).\n */\nimport type { EnumRef, EnumValue, Model, TypeRef } from '../ir/types.js';\nimport { collectModelTypeRefs, renameModelRefs, renameTypeRefModels, walkTypeRef } from '../ir/types.js';\nimport { numberedName, toPascalCase } from '../utils/naming.js';\nimport { enumValuesOf, sameEnumShape } from './enum-members.js';\nimport type { SchemaObject } from './schemas.js';\nimport { isComponentModelRef, rehearse, schemaToTypeRef } from './schemas.js';\nimport {\n  deprecatedFoldWarning,\n  extractInlineModelsFromProperties,\n  looserFields,\n  modelFingerprint,\n  modelShares,\n  qualifyInlineModelName,\n} from './inline-models.js';\n\n// The model-shape fingerprint lives beside the schema-shape key in\n// inline-models.ts, where the extractor compares models too; re-exported here\n// for the registry's readers.\nexport { modelFingerprint };\n\n/**\n * Spec-wide record of every name an inline model must not silently reuse:\n * the component models and the models their fields mint (seeded up front,\n * each with the model itself), each operation's primary response and\n * request body models, each header, body and parameter model materialized\n * so far — and every enum name, component or minted (`reserveEnumNames`),\n * since a model and an enum under one name reach an emitter as one public\n * symbol. A model's entry carries its shape fingerprint, so a model whose\n * shape the owner shares can take the name (`ownerShares`), and — for\n * operation-owned models — which operation produced it, so a collision\n * inside one operation can be told apart from one across operations. An\n * enum's entry carries `ENUM_NAME_FINGERPRINT`, which no model's fingerprint\n * equals, so a model minted under an enum's name always clashes and moves on.\n */\nexport type InlineModelRegistry = Map<string, InlineModelOwner>;\n\nexport interface InlineModelOwner {\n  fingerprint: string;\n  operation?: string;\n  /**\n   * The owner itself, for a model the document declares — a component schema\n   * or a model a component's field minted — which shares its name with every\n   * shape it admits (`modelShares`). Absent for an operation's model, which\n   * shares its name on an identical fingerprint only.\n   */\n  model?: Model;\n  /**\n   * Set when `model` is a model a component's field minted rather than a\n   * component schema: it still shares its name with a deprecated copy while\n   * deprecated, where a deprecated component shares it with none\n   * (`ownerFlagAdmits`, #441).\n   */\n  fieldMinted?: boolean;\n}\n\n/**\n * Whether the owner of a name shares it with `model`, whose fingerprint is\n * `fingerprint`: a declared model (`owner.model`) when it admits the shape\n * (`modelShares`: the same fields and types, the owner no stricter on\n * requiredness or nullability, everything else identical, the model's own\n * `deprecated` read apart — a live owner shares with a copy of either flag,\n * a deprecated component with none, so a deprecated header or parameter\n * model beside a deprecated component takes the qualified name its live\n * self takes (#441), a deprecated field model (`owner.fieldMinted`) only\n * with a deprecated copy), and an operation's model when the fingerprints\n * agree, flag included. A shape the SDK sends (`sent`: a request body, a\n * parameter) shares a declared model's name on an identical shape only, the\n * flag read the same way: typed as a looser component, a caller could leave\n * out what the operation requires. The one question every clash check\n * below asks.\n */\nexport function ownerShares(owner: InlineModelOwner, model: Model, fingerprint: string, sent = false): boolean {\n  return owner.model ? modelShares(owner.model, model, sent, !!owner.fieldMinted) : owner.fingerprint === fingerprint;\n}\n\n/**\n * The fingerprint an enum name is registered under. Every model fingerprint\n * (`modelFingerprint`) carries a `#` between its fields and the rest, so no\n * model can match this and share an enum's name.\n */\nexport const ENUM_NAME_FINGERPRINT = 'enum';\n\n/** Record every model of `models` the registry does not know yet as owned by `operation`; the first owner keeps a name. */\nexport function registerInlineModels(registry: InlineModelRegistry, models: Model[], operation?: string): void {\n  for (const model of models) {\n    if (registry.has(model.name)) continue;\n    registry.set(model.name, { fingerprint: modelFingerprint(model), operation });\n  }\n}\n\n/**\n * Record every name of `names` the registry does not know yet as an enum's,\n * so no inline model is materialized under it (`ENUM_NAME_FINGERPRINT`),\n * owned by `operation` when one of that operation's own references carries\n * the enum — so a deferred model of the operation that derives the name is\n * qualified by location, as one that clashes with the operation's models is\n * (`deferredNamingStem`) — and by no operation for a component enum's name\n * or one a component's field or a shared companion carries, which reads as\n * a clash with a component. A name a model or an earlier enum already owns\n * keeps its entry: the first owner keeps a name, and a model's is the\n * document's own clash, not one the registry can move.\n */\nexport function reserveEnumNames(registry: InlineModelRegistry, names: Iterable<string>, operation?: string): void {\n  for (const name of names) {\n    if (!registry.has(name)) registry.set(name, { fingerprint: ENUM_NAME_FINGERPRINT, operation });\n  }\n}\n\n/**\n * One site's settlement, kept for the sites of the same bare name after it:\n * the stem it settled on and, in order, every rename made under that stem —\n * the ones `renameClashing` made (`Circle` → `BodyCircle`) and the ones it\n * replayed from an earlier site. A later site trying the stem replays the\n * renames on its own trial before comparing (`runTrial`), so a schema\n * identical to the earlier site's builds exactly the earlier site's names\n * and shares every model; compared as extracted, its root would still\n * reference `Circle`, fingerprint differently from the earlier root, and a\n * second root and child would be minted.\n */\nexport interface SettledSite {\n  stem: string;\n  renames: ReadonlyArray<readonly [from: string, to: string]>;\n  /**\n   * The site's members when it is itself an inline enum — a body written as\n   * an `enum:` list, or an array of one, which mints no model. A later enum\n   * site shares the stem only on the same members (`sameEnumShape`), and a\n   * site that mints a model never does (`shares`). Unset for a site that\n   * produced a model, and in the string form (`SiblingStems`); a site that\n   * produced neither a model nor an enum records no settlement (`commit`).\n   */\n  enumValues?: readonly EnumValue[];\n}\n\n/**\n * The settlements of the sites that derive from one bare name — the same\n * header on several status codes or operations, one media type's inline body\n * on several status codes — in the order the sites were resolved, one per\n * stem: the one container `materializeInlineSchema` writes to. The caller\n * creates it (`createSiblingSites`) and hands the same object to every site\n * of the bare name. Each call reads `settled`, tries those stems right after\n * the bare name (the bare name itself with the renames of the site that\n * settled on it) — or before its first candidate, for a site with no bare\n * name (`siblingsFirst`) — so a shape identical to an earlier site's shares\n * that site's model under whichever stem it took (a 202's `…Response201`,\n * not a fresh `…Response202`), and a different shape steps past them to the\n * site's own candidates; then it appends the site it settles — the only\n * argument a call mutates, and only this field of it. A site tries only the\n * stems it could share: a site that mints a model those a model settled on,\n * one that is itself an inline enum those an enum of the same members\n * settled on (`SettledSite.enumValues`, `shares`). A site that produced\n * neither — a primitive body, an array of primitives, a `$ref` to a\n * component — owns no name under its stem and records nothing, so no later\n * site takes the free stem it sat on (`commit`).\n */\nexport interface SiblingSites {\n  /** The settlements so far, in the order the sites were resolved; appended to by `materializeInlineSchema`. */\n  readonly settled: SettledSite[];\n}\n\n/**\n * A settlement container for one bare name: empty, or seeded from `stems` —\n * the earlier string form (`SiblingStems`) read as settlements without\n * renames. The strings are copied, never written.\n */\nexport function createSiblingSites(stems: SiblingStems = []): SiblingSites {\n  return { settled: stems.map((stem) => ({ stem, renames: [] })) };\n}\n\n/**\n * The form `siblings` took before a settlement carried its renames: the\n * stems earlier sites settled on, and nothing else. Read-only in type\n * (`readonly`, so a push is a type error) and in fact: `materializeInlineSchema`\n * copies it into a container of its own (`siblingSitesOf`), to the same result\n * a `SiblingSites` would give, and records this call's settlement in that\n * private container only — the array given, empty or frozen, is never\n * touched. A caller that wants the sites after this one to see the settlement\n * creates a `SiblingSites` and passes it to each of them.\n */\nexport type SiblingStems = readonly string[];\n\n/**\n * The form `siblings` took between the string form and the container: a\n * bare list of settlements. Accepted so a caller on that form keeps\n * compiling. A non-empty list is used as the container's `settled` list\n * itself — this call appends to it, as it did then. An empty array has no\n * element to tell it from the string form, so it is read as that form:\n * read-only, never written (`siblingSitesOf`).\n */\nexport type SettledSites = SettledSite[];\n\nexport interface MaterializeInlineOptions {\n  /**\n   * The property name to extract the schema under for the `index`-th stem:\n   * the bare name first, then whatever qualifies it (a status code, an\n   * operation, a numeric suffix). `firstClashOwners` is who owned the names\n   * the first trial clashed with, for a caller that orders its candidates by\n   * where the clash came from; empty while nothing has clashed.\n   */\n  stem: (index: number, firstClashOwners: InlineModelOwner[]) => string;\n  /**\n   * The settlements of the earlier sites of the same bare name, whose stems\n   * are tried between the bare name and the caller's other candidates with\n   * their renames replayed, and which this site's settlement is appended to:\n   * a `SiblingSites` container the caller created, or a non-empty bare list\n   * of settlements (`SettledSites`) — in either, the settled list is the one\n   * thing this call mutates — or the read-only string form, `SiblingStems`,\n   * copied into a container of this call's own; an empty array is read as\n   * the string form. Absent, only the caller's candidates are tried and\n   * nothing is recorded.\n   */\n  siblings?: SiblingSites | SettledSites | SiblingStems;\n  /**\n   * Set for a site with no bare name — a later status code's secondary\n   * body, whose first candidate already carries its status code\n   * (workos/oagen#538): the stems its `siblings` settled on are tried before\n   * its candidates rather than between the first and the rest, so a 202\n   * body identical to the 201's shares `…Response201` instead of taking a\n   * free `…Response202`, and a different one steps to `…Response202`. A\n   * body that is itself an inline enum clashes on nothing, so it shares a\n   * sibling's stem only when that sibling is an enum of the same members\n   * (`SettledSite.enumValues`): a 202 enum `[c, d]` beside a 201 enum\n   * `[a, b]` is `…Response202`, as an object body there would be, and a\n   * 202 enum `[a, b]` shares `…Response201`.\n   */\n  siblingsFirst?: boolean;\n  /** The parent the schema is a property of; none for a body. */\n  parentName?: string;\n  componentSchemas?: Record<string, SchemaObject>;\n  registry: InlineModelRegistry;\n  /** Recorded as the owner of every model registered here. */\n  operation?: string;\n  /** The schema is what the SDK sends (a request body, a parameter): a component shares its name only on an identical shape (`ownerShares`). */\n  sent?: boolean;\n  /** Where the materialized models go. */\n  models: Model[];\n}\n\n/**\n * Attempts before the loop gives up moving names and numbers the clashing\n * ones in place. Each attempt either reserves names or advances the stem, and\n * the fixed-point test below stops it long before this; the cap is the\n * guarantee that no input can keep it going.\n */\nconst MAX_ATTEMPTS = 32;\n\n/**\n * Rename rounds before settling gives up. Every rename picks a name nothing\n * owns and nothing in the trial uses, so each round settles at least one\n * model for good and the rounds end within the trial's size; the cap only\n * backs that.\n */\nconst MAX_RENAME_ROUNDS = 64;\n\n/**\n * Type `schema` and materialize every model it names into `options.models`,\n * under names the registry does not already give another shape.\n *\n * A trial extracts the schema under the current stem and compares every model\n * it minted with the registry: a name whose owner shares it (`ownerShares`:\n * a component or a component field's model admits the shape, an operation's\n * model has the identical one) is shared, so a header or body a component\n * admits simply references it; any other owned name clashes. On a clash the\n * loop makes the cheapest move that can still change something:\n *\n *   1. reserve the clashing names — a `oneOf`/`anyOf` variant named from its\n *      own `title` or const (`Circle`) is minted from the schema, not the\n *      stem, so no stem would move it; reserved, variant naming steps around\n *      it the way it steps around a sibling's model (`CircleListPetsDefault…`);\n *   2. when every clashing name is already reserved and still minted (the\n *      root, nested objects, array items: names derived from the stem),\n *      advance the stem (`…2`, `…3`, or the caller's qualified candidates).\n *\n * The clashing set is compared between attempts: when a stem advance leaves\n * it unchanged, neither move can clear it (a titled variant nested below the\n * top level, where the reservation does not reach) — the fixed point — and\n * the loop stops rather than retrying forever. The earlier trial is then kept\n * and settled in place (`renameClashing`): the clashing names themselves are\n * renamed, qualified by the root model name (`ListPetsDefaultResponseCircle`)\n * then numbered, with every reference among the trial's models and in the\n * returned type rewritten to match; and because renaming a child changes its\n * parent's shape, the trial is checked again on its new fingerprints, so a\n * parent that matched a registered model before and differs from it now\n * moves to the next free stem with its children, instead of being dropped at\n * commit as already defined. That rewrite cannot tell an inline model's\n * reference from a `$ref` to a component MODEL of the same name, so a schema\n * that both inlines a clashing `Circle` and references component model\n * `Circle` fails loudly instead (`componentModelRefTargets`). A component\n * ENUM of the name is no such bar: a `$ref` to it is an `EnumRef`, which the\n * rewrite never touches, so the inline `Circle` is renamed under the root\n * and the enum reference stays. A rename replayed from an earlier site that\n * such a `$ref` to a component model would make unsafe is skipped, not failed\n * (`runTrial`).\n *\n * The stems are tried in the order `candidateStem` gives: the caller's bare\n * name, then the stems earlier sites of the same bare name settled on\n * (`options.siblings`), then the caller's own qualified candidates — or,\n * for a site with no bare name (`options.siblingsFirst`), the siblings'\n * stems and then every candidate of the caller's; a sibling's stem is tried\n * only by a site that could share it — a model's by one that mints a model,\n * an enum's by an enum of the same members (`shares`). A trial under\n * an earlier site's stem replays that site's renames first, so the\n * `application/vnd.pet+json` body of a 202 tries the `…Response201` its 201\n * settled on before its own `…Response202`, and shares the 201's models when\n * the shapes are identical — nested `…Response201Circle` included — where a\n * name-only comparison would mint a second model of the same shape. The\n * site's own settlement — the stem the trial was under or the one its root\n * moved to, with the renames made under it — is appended to\n * `options.siblings` for the sites after it.\n */\nexport function materializeInlineSchema(schema: SchemaObject, given: MaterializeInlineOptions): TypeRef {\n  const siblings = siblingSitesOf(given.siblings);\n  const options: ResolvedOptions = { ...given, siblings };\n  // Read only where there are siblings to share with, or to be shared by.\n  options.enumSite = siblings && enumSiteValues(schema, options);\n  const { registry } = options;\n  const reserved = new Set<string>();\n  let stemIndex = 0;\n  let firstClashOwners: InlineModelOwner[] = [];\n  const candidateAt = (index: number): Candidate => candidateStem(index, options, firstClashOwners);\n  // The last clashing trial and the move made after it.\n  let previous: { trial: Trial; move: 'reserve' | 'stem' } | undefined;\n\n  for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n    const trial = runTrial(schema, candidateAt(stemIndex), reserved, options);\n    if (trial.clashing.length === 0) return commit(trial, options);\n\n    if (firstClashOwners.length === 0) {\n      firstClashOwners = trial.clashing.map((name) => registry.get(name)).filter((o): o is InlineModelOwner => !!o);\n    }\n    const unreserved = trial.clashing.filter((name) => !reserved.has(name));\n    if (unreserved.length > 0) {\n      for (const name of unreserved) reserved.add(name);\n      previous = { trial, move: 'reserve' };\n      continue;\n    }\n    if (previous?.move === 'stem' && sameNames(previous.trial.clashing, trial.clashing)) {\n      // The stem advance changed nothing: the fixed point. The earlier of the\n      // two identical trials carries the lower stem, so it is the one kept.\n      return commit(renameClashing(previous.trial, options, candidateAt), options);\n    }\n    stemIndex++;\n    previous = { trial, move: 'stem' };\n  }\n\n  return commit(renameClashing(previous!.trial, options, candidateAt), options);\n}\n\n/**\n * `MaterializeInlineOptions` with `siblings` in the one form the loop reads\n * (`siblingSitesOf`) and, once there are siblings, the site's own members\n * when it is itself an inline enum (`enumSiteValues`).\n */\ninterface ResolvedOptions extends Omit<MaterializeInlineOptions, 'siblings'> {\n  siblings?: SiblingSites;\n  enumSite?: readonly EnumValue[];\n}\n\n/**\n * `siblings` as the loop reads it, the three accepted forms told apart by\n * shape, never by emptiness: the `SiblingSites` container as given (it\n * carries `settled`) — the very object, since this call's settlement is\n * appended to it; a non-empty array of settlement objects (`SettledSites`),\n * wrapped as the container's settled list itself, so the call appends to the\n * caller's list as it did on that form; and an array of strings\n * (`SiblingStems`) — an empty array among them, which has no element to say\n * otherwise — copied into a fresh container (`createSiblingSites`), so the\n * array given is only read. Absent stays absent.\n */\nfunction siblingSitesOf(siblings: SiblingSites | SettledSites | SiblingStems | undefined): SiblingSites | undefined {\n  if (siblings === undefined) return undefined;\n  if ('settled' in siblings) return siblings;\n  if (siblings.length > 0 && typeof siblings[0] !== 'string') return { settled: siblings as SettledSites };\n  return createSiblingSites(siblings as SiblingStems);\n}\n\n/** A stem to try, with the renames to replay on the trial extracted under it (none for the caller's own candidates). */\ninterface Candidate {\n  stem: string;\n  renames: SettledSite['renames'];\n}\n\n/**\n * The `index`-th candidate to try: the caller's bare name (its first\n * candidate) — with the renames of the earlier site that settled on that\n * very stem, when one did — then each other stem an earlier site of the same\n * bare name settled on (`options.siblings`) that this site could share\n * (`shares`), with its renames, then the caller's other candidates in the\n * caller's order, leaving out any stem a sibling settled on, shareable or\n * not — the same stem tried twice in a row would read to the fixed-point\n * test as an advance that changed nothing, and a stem an enum of other\n * members or a model settled on names that site, not this one. A site with\n * no bare name (`options.siblingsFirst`) tries every shareable sibling's\n * stem first, then every candidate of the caller's, left out the same way.\n * The caller's candidates end in an unbounded numbered run, so at most as\n * many of them as there are siblings are left out and the search is bounded;\n * past the bound the caller's own `index`-th candidate is the fallback.\n */\nfunction candidateStem(index: number, options: ResolvedOptions, firstClashOwners: InlineModelOwner[]): Candidate {\n  const own = (i: number): string => options.stem(i, firstClashOwners);\n  const sites = options.siblings?.settled ?? [];\n  const bare = options.siblingsFirst ? undefined : own(0);\n  if (bare !== undefined && index === 0) {\n    return { stem: bare, renames: sites.find((site) => site.stem === bare)?.renames ?? [] };\n  }\n  // The candidates tried before the siblings' stems: the bare name, or none.\n  const before = bare === undefined ? 0 : 1;\n  const others = sites.filter((site) => site.stem !== bare && shares(options.enumSite, site));\n  if (index - before < others.length) return others[index - before];\n  const leftOut = (stem: string): boolean => sites.some((site) => site.stem === stem);\n  let remaining = index - before - others.length + 1;\n  for (let i = before; i <= index + sites.length; i++) {\n    const stem = own(i);\n    if (leftOut(stem)) continue;\n    if (--remaining === 0) return { stem, renames: [] };\n  }\n  return { stem: own(index), renames: [] };\n}\n\n/**\n * Whether a site may share the stem an earlier sibling settled on: one that\n * mints a model shares a model's, and one that is itself an inline enum\n * (`enumSite`, its members) an enum's of the same members\n * (`SettledSite.enumValues`); every settlement is one or the other, since a\n * site that produced neither records none (`commit`). An enum site clashes on nothing in the\n * registry, so left to the trial it would settle on the first sibling's stem\n * whatever that sibling was, and the enum collector would then number it\n * past that sibling's name (`…Response201No2`) where the site's own status\n * code names it (`…Response202`), as it names an object body there.\n */\nfunction shares(enumSite: readonly EnumValue[] | undefined, site: SettledSite): boolean {\n  if (enumSite === undefined) return site.enumValues === undefined;\n  return site.enumValues !== undefined && sameEnumShape(enumSite, site.enumValues);\n}\n\n/**\n * The members of a site that is itself an inline enum — a body written as an\n * `enum:` list, or an array of one, which mints no model — read off a silent\n * rehearsal of its type under its first candidate (`rehearse`; the members\n * do not depend on the stem); none for a site that mints a model or types a\n * primitive. Decides which sibling's stem the site may share (`shares`) and\n * is recorded with its settlement (`SettledSite.enumValues`).\n */\nfunction enumSiteValues(schema: SchemaObject, options: ResolvedOptions): readonly EnumValue[] | undefined {\n  const ref = enumRefOf(rehearse(() => schemaToTypeRef(schema, options.stem(0, []), options.parentName)));\n  return ref && enumValuesOf(ref);\n}\n\n/** The enum `type` is — itself, or through an array or nullable wrapper; none for any other type. */\nfunction enumRefOf(type: TypeRef): EnumRef | undefined {\n  if (type.kind === 'enum') return type;\n  if (type.kind === 'array') return enumRefOf(type.items);\n  if (type.kind === 'nullable') return enumRefOf(type.inner);\n  return undefined;\n}\n\ninterface Trial {\n  schema: SchemaObject;\n  propertyName: string;\n  reserved: ReadonlySet<string> | undefined;\n  models: Model[];\n  fingerprints: Map<Model, string>;\n  /** Names the registry gives another shape, sorted. */\n  clashing: string[];\n  /** Set once the trial's references have been rewritten and the type must not be rebuilt. */\n  type?: TypeRef;\n  /**\n   * The stem the root is settled under — the trial's own, or the one the root\n   * moved to in `renameClashing`; unset when the root was numbered in place\n   * and no stem names it. Recorded for the site's siblings at commit.\n   */\n  settledStem: string | undefined;\n  /** Every rename made on the trial so far, in order: replayed from an earlier site, then `renameClashing`'s own. */\n  renames: Array<readonly [string, string]>;\n}\n\n/**\n * Extract the schema under the candidate's stem and compare every model with\n * the registry. The candidate's renames — an earlier site's, see\n * `SettledSite` — are replayed first, each only where it applies: the model\n * to move must be among the trial's, the name moved to free in it, and the\n * name moved not one this schema `$ref`s as a component model\n * (`renameModel`), so a schema that differs from the earlier site's (no\n * `Circle` to move, a model of its own already named `BodyCircle`, or an\n * inline `Circle` beside a `$ref` to component `Circle`, which the rewrite\n * could not tell apart) is compared as extracted and settles on its own\n * merits — an inline `Circle` of the component's shape shares the component,\n * and the root takes the site's own next candidate — rather than failing the\n * parse. A replayed rename rewrites the type as the settling pass does, so\n * the type is kept with the trial.\n */\nfunction runTrial(\n  schema: SchemaObject,\n  candidate: Candidate,\n  reservedNames: Set<string>,\n  options: ResolvedOptions,\n): Trial {\n  const { stem: propertyName } = candidate;\n  const reserved = reservedNames.size > 0 ? new Set(reservedNames) : undefined;\n  const models: Model[] = [];\n  extractInlineModelsFromProperties(\n    { properties: { [propertyName]: schema } },\n    models,\n    options.parentName,\n    options.componentSchemas,\n    undefined,\n    reserved,\n  );\n  const renames: Array<readonly [string, string]> = [];\n  let type: TypeRef | undefined;\n  if (candidate.renames.length > 0) {\n    const rewritten = schemaToTypeRef(schema, propertyName, options.parentName, undefined, reserved);\n    const referenced = componentModelRefTargets(rewritten, models);\n    for (const [from, to] of candidate.renames) {\n      if (!models.some((model) => model.name === from) || models.some((model) => model.name === to)) continue;\n      if (!renameModel(models, rewritten, referenced, from, to)) continue;\n      renames.push([from, to]);\n    }\n    if (renames.length > 0) type = rewritten;\n  }\n  const fingerprints = new Map(models.map((model) => [model, modelFingerprint(model)]));\n  const clashing = models\n    .filter((model) => {\n      const owner = options.registry.get(model.name);\n      return owner !== undefined && !ownerShares(owner, model, fingerprints.get(model)!, options.sent);\n    })\n    .map((model) => model.name)\n    .sort();\n  return { schema, propertyName, reserved, models, fingerprints, clashing, type, settledStem: propertyName, renames };\n}\n\nfunction sameNames(a: string[], b: string[]): boolean {\n  return a.length === b.length && a.every((name, i) => name === b[i]);\n}\n\n/**\n * Register and emit the trial's new models. A name the registry already owns\n * is shared only when the owner shares it (`ownerShares`) — decided on the\n * trial's final models, after every rename — so a model whose references were\n * rewritten is never dropped as \"already defined\" in favour of an owner that\n * no longer matches it. A deprecated model a live declared owner shares its\n * name with is dropped the same way, with the warning the merge passes give\n * such a copy, once per site. The trial has no such clash left when it gets here\n * (`runTrial` found none, or `renameClashing` cleared them all), so the\n * remaining branch is a guard against a regression, not an expected path.\n * The site's settlement — the stem it settled on, the renames made under it\n * and, for a site that is itself an inline enum, its members — is recorded\n * for its siblings, whether it minted models or shared every one of them; a\n * stem an earlier site already recorded keeps that site's. A site that\n * produced neither a model nor an enum — a primitive body, an array of\n * primitives, a `$ref` to a component — owns no name under its stem, so it\n * records no settlement: offered as a sibling's, the free stem would be\n * taken by the next object body of the group (a 202's `…Response201`\n * beside a 201 `type: string` body) and given up again once the primitive\n * body is removed.\n */\nfunction commit(trial: Trial, options: ResolvedOptions): TypeRef {\n  for (const model of trial.models) {\n    const fingerprint = trial.fingerprints.get(model)!;\n    const owner = options.registry.get(model.name);\n    if (owner && ownerShares(owner, model, fingerprint, options.sent)) {\n      // A deprecated copy a live declared model admits is announced once per\n      // site, as the merge passes announce one (`settleSharedNames`), with\n      // what the model, when looser, no longer holds the copy to.\n      if (model.deprecated && owner.model && !owner.model.deprecated) {\n        console.warn(deprecatedFoldWarning(model.name, looserFields(owner.model, model)));\n      }\n      continue;\n    }\n    if (owner !== undefined) {\n      throw new Error(\n        `Inline model \"${model.name}\" would overwrite a model of another shape; this is a bug in materializeInlineSchema.`,\n      );\n    }\n    options.registry.set(model.name, { fingerprint, operation: options.operation });\n    options.models.push(model);\n  }\n  const { siblings, enumSite: enumValues } = options;\n  const { settledStem } = trial;\n  const owns = trial.models.length > 0 || enumValues !== undefined;\n  if (siblings && owns && settledStem !== undefined && !siblings.settled.some((site) => site.stem === settledStem)) {\n    siblings.settled.push({ stem: settledStem, renames: [...trial.renames], ...(enumValues && { enumValues }) });\n  }\n  return trial.type ?? schemaToTypeRef(trial.schema, trial.propertyName, options.parentName, undefined, trial.reserved);\n}\n\n/**\n * Rename, in place, the model named `from` among `models` to `to` and rewrite\n * every reference to it — in the models' fields, in `type`, and in the inline\n * enums named from it (`CircleStatus` → `BodyCircleStatus`, since a component\n * enum `CircleStatus` of other values would otherwise be collected first and\n * the renamed model's field would point at it). Returns `false`, having\n * changed nothing, when `from` is a name the schema also `$ref`s as a\n * component model (`referenced`, see `componentModelRefTargets`): the rewrite\n * cannot tell the inline reference from the `$ref`, so the rename is unsafe\n * and the caller decides — the settling pass fails loudly, a sibling's replay\n * skips it (`runTrial`).\n */\nfunction renameModel(\n  models: readonly Model[],\n  type: TypeRef,\n  referenced: ReadonlySet<string>,\n  from: string,\n  to: string,\n): boolean {\n  if (referenced.has(from)) return false;\n  const renames = new Map([[from, to]]);\n  for (const model of models) {\n    if (model.name === from) {\n      model.name = to;\n      // The inline enums of its fields were named from it (`CircleStatus`),\n      // so they follow (`ListPetsDefaultResponseCircleStatus`): left as they\n      // were, a component enum `CircleStatus` of other values would be\n      // collected first and the renamed model's field would point at it.\n      for (const field of model.fields) rewriteEnumPrefix(field.type, from, to);\n    }\n    // Fields, variants and discriminator mappings alike.\n    renameModelRefs(model, renames);\n  }\n  renameTypeRefModels(type, renames);\n  return true;\n}\n\n/**\n * Settle the fixed-point trial in place so it can be committed as it stands:\n * rename every model whose name the registry gives another shape, rewrite\n * every reference to it among the trial's models and in the returned type,\n * and check again, since renaming a child changes its parent's shape. Round\n * by round, until no name is owned by another shape:\n *\n *   - a clashing name other than the root — a titled or const-named variant\n *     the reservation did not reach — is qualified by the root model name\n *     (`ListPetsDefaultResponseCircle`), or kept as is when it already starts\n *     with it, then numbered until free;\n *   - a clashing root — its shape changed when a child under it moved, so a\n *     registered model of that name no longer matches it — moves the body to\n *     the next free stem the caller would have tried next\n *     (`ListPetsDefaultResponse2`; a header's qualified candidates), and with\n *     it every model named under it (`ListPetsDefaultResponse2Circle`), as a\n *     stem advance would have named them — except one whose name an\n *     owner that shares it already holds (`ownerShares`), which stays shared\n *     under that name with the moved parent still referencing it, exactly as\n *     it is shared when nothing moves.\n *\n * Every new name is one nothing owns and nothing in the trial uses, so a\n * renamed model can never clash again, a shared model never changes and so\n * never starts a round, and the rounds end within the trial's size. A name\n * the schema also `$ref`s as a component model cannot be rewritten safely\n * (see `materializeInlineSchema`) and fails loudly.\n *\n * `candidateAt` gives the stems in the order the loop tried them\n * (`candidateStem`), so a moved root takes the next free one of those; the\n * stem it moved to is the one recorded for the site's siblings, and a root\n * numbered in place when none is free records none. Every rename made here\n * is appended to the trial's, after any replayed from an earlier site, so a\n * later site can replay them all in order.\n */\nfunction renameClashing(trial: Trial, options: ResolvedOptions, candidateAt: (index: number) => Candidate): Trial {\n  const { registry } = options;\n  const rootOf = (propertyName: string): string =>\n    qualifyInlineModelName(toPascalCase(propertyName), options.parentName);\n  let rootName = rootOf(trial.propertyName);\n  let settledStem = trial.settledStem;\n  // A trial that replayed an earlier site's renames carries its rewritten type.\n  const type =\n    trial.type ?? schemaToTypeRef(trial.schema, trial.propertyName, options.parentName, undefined, trial.reserved);\n  const referenced = componentModelRefTargets(type, trial.models);\n  const taken = new Set([...registry.keys(), ...trial.models.map((m) => m.name)]);\n\n  /** `candidate(1)`, `candidate(2)`, ... until one nothing owns or uses; claimed. */\n  const claim = (candidate: (n: number) => string): string => {\n    let n = 1;\n    let name = candidate(n);\n    while (taken.has(name)) name = candidate(++n);\n    taken.add(name);\n    return name;\n  };\n  const rename = (from: string, to: string): void => {\n    // Only a reference to a component MODEL of this name is indistinguishable\n    // from the inline model's own references once both are plain names; a\n    // reference to a component enum of the name is an `EnumRef`, which the\n    // rewrite never touches, so the inline model is simply renamed past it.\n    if (!renameModel(trial.models, type, referenced, from, to)) {\n      throw new Error(\n        `Inline schema \"${from}\" under ${rootName} has another shape than component \"${from}\", which the same ` +\n          `schema also references; rename the inline schema's title or the component so the two can be told apart.`,\n      );\n    }\n    trial.renames.push([from, to]);\n  };\n\n  let fingerprints = trial.fingerprints;\n  let clashing = trial.clashing;\n  for (let round = 0; clashing.length > 0; round++) {\n    if (round >= MAX_RENAME_ROUNDS) {\n      throw new Error(\n        `Could not settle the inline models under ${rootName} in ${MAX_RENAME_ROUNDS} rounds; ` +\n          `this is a bug in materializeInlineSchema.`,\n      );\n    }\n    if (clashing.includes(rootName)) {\n      const oldRoot = rootName;\n      let movedRoot: string | undefined;\n      settledStem = undefined;\n      for (let index = 1; index <= MAX_RENAME_ROUNDS && movedRoot === undefined; index++) {\n        const { stem } = candidateAt(index);\n        const candidate = rootOf(stem);\n        if (!taken.has(candidate)) {\n          movedRoot = candidate;\n          settledStem = stem;\n        }\n      }\n      if (movedRoot === undefined) movedRoot = claim((n) => numberedName(oldRoot, n + 1));\n      taken.add(movedRoot);\n      // Decided per model, by shape: a model named under the root whose name\n      // an owner that shares it already holds (a component that admits it,\n      // an earlier operation's identical model) stays shared under that\n      // name, exactly as it would had the root not moved, and the moved\n      // parent keeps referencing it. The root itself, and every other model\n      // named under it, moves.\n      const moving = trial.models\n        .filter((model) => {\n          if (model.name === oldRoot) return true;\n          if (!model.name.startsWith(oldRoot)) return false;\n          const owner = registry.get(model.name);\n          return owner === undefined || !ownerShares(owner, model, fingerprints.get(model)!, options.sent);\n        })\n        .map((model) => model.name);\n      for (const name of moving) {\n        const suffix = name.slice(oldRoot.length);\n        const moved = `${movedRoot}${suffix}`;\n        rename(name, name === oldRoot ? movedRoot : claim((n) => (n === 1 ? moved : numberedName(moved, n))));\n      }\n      rootName = movedRoot;\n    } else {\n      for (const name of clashing) {\n        const base = name.startsWith(rootName) ? name : `${rootName}${name}`;\n        rename(\n          name,\n          claim((n) => (n === 1 ? base : numberedName(base, n))),\n        );\n      }\n    }\n\n    fingerprints = new Map(trial.models.map((model) => [model, modelFingerprint(model)]));\n    clashing = trial.models\n      .filter((model) => {\n        const owner = registry.get(model.name);\n        return owner !== undefined && !ownerShares(owner, model, fingerprints.get(model)!, options.sent);\n      })\n      .map((model) => model.name)\n      .sort();\n  }\n\n  return { ...trial, fingerprints, clashing: [], type, settledStem };\n}\n\n/** Rename, in place, every inline enum under `ref` whose name was built from `oldPrefix` so it is built from `newPrefix`. */\nfunction rewriteEnumPrefix(ref: TypeRef, oldPrefix: string, newPrefix: string): void {\n  walkTypeRef(ref, {\n    enum: (r) => {\n      if (r.values && r.name.startsWith(oldPrefix))\n        (r as { name: string }).name = newPrefix + r.name.slice(oldPrefix.length);\n    },\n  });\n}\n\n/**\n * The names of the component models `type` and the fields of `models`\n * reference: every `ModelRef` that `schemaToTypeRef` built from a `$ref`\n * (`isComponentModelRef`, an identity mark). Only such a reference is\n * indistinguishable from an inline model's own references once the inline\n * model is renamed, so only these block a rename. A `$ref` to a component\n * enum is an `EnumRef`, which `renameTypeRefModels` leaves alone, so it is never\n * collected. One predicate for both renames — the settling pass and a\n * sibling's replay — so the two agree on which `$ref` a rename could hit.\n */\nfunction componentModelRefTargets(type: TypeRef, models: readonly Model[]): Set<string> {\n  const targets = new Set<string>();\n  const collect = (ref: TypeRef): void => {\n    walkTypeRef(ref, {\n      model: (r) => {\n        if (isComponentModelRef(r)) targets.add(r.name);\n      },\n    });\n  };\n  collect(type);\n  for (const model of models) for (const ref of collectModelTypeRefs(model)) collect(ref);\n  return targets;\n}\n","import type { TypeRef, Model, Field, PaginationEndOfIteration, StatusRange } from '../ir/types.js';\nimport { numberedName, toPascalCase, singularize } from '../utils/naming.js';\nimport {\n  collectObjectProperties,\n  detectEndOfIteration,\n  endOfIterationProblem,\n  END_OF_ITERATION_FIELDS,\n  looksLikePaginationMetadata,\n  readFlattenedUnion,\n  resolveDataPathArray,\n  spellsOneOf,\n} from './pagination.js';\nimport type { SchemaObject } from './schemas.js';\nimport {\n  arraySchemaOf,\n  declaresNull,\n  schemaToTypeRef,\n  buildFieldFromSchema,\n  classifyInlineSchema,\n  constraintsEntry,\n  deprecatedEntry,\n  foldSiblingProperties,\n  isArrayComponentRef,\n  namesSeveralTypes,\n  isArrayPointerRef,\n  isNullSchema,\n  collapsedNullableBranch,\n  nullableAxisBranch,\n  referenceTypesAsUnknown,\n  typesAsUnknown,\n  unionAxesOf,\n  warnOnUncarriedProperties,\n  withSchemaConstraints,\n  withWrapperDocs,\n} from './schemas.js';\nimport { isPendingVariant } from './schema-refs.js';\nimport type { EnvelopeCompanion } from './envelope-companion-names.js';\nimport {\n  collectProperties,\n  combineDeclarations,\n  extractInlineModelsFromProperties,\n  mergeAllOfMembers,\n  mergedObjectSchema,\n  readInlineAllOf,\n  unionOfDeclarations,\n  unwrappedAllOfMember,\n} from './inline-models.js';\nimport { externalDocsEntry } from './external-docs.js';\nimport { schemaExtensionsEntry } from './extensions.js';\nimport { materializeInlineSchema, type InlineModelRegistry } from './materialize-inline.js';\n\n/**\n * What settles an array body's or list envelope's item models against the\n * names already decided (see `typeInlineItems`): the spec-wide registry of\n * model shapes the operations fill as they are read, and the operation to\n * record this body's models under.\n */\nexport interface ItemSettlement {\n  registry: InlineModelRegistry;\n  operation: string;\n}\n\nexport interface ResponseExtractionResult {\n  /** The TypeRef to use as the operation's response type */\n  response: TypeRef;\n  /** Any inline models discovered during extraction (to merge into ir.models) */\n  inlineModels: Model[];\n  /** Whether this response indicates a paginated list */\n  isPaginated: boolean;\n  /**\n   * Set when the body is a list envelope detection recognized but did not\n   * unwrap because nothing pages it (`paginationDisabled`): it was read as\n   * any other body, a plain response model carrying every field. The caller\n   * warns about an envelope kept for want of a paging parameter; one kept by\n   * `strategy: 'none'` was asked for.\n   */\n  unpagedEnvelope?: boolean;\n  /** Path to the data array within the response envelope (e.g., 'data') */\n  dataPath?: string;\n  /**\n   * The data array property's own description (see\n   * `PaginationMeta.dataDescription`). Set only for a list envelope whose\n   * data property declares one.\n   */\n  dataDescription?: string;\n  /** TypeRef of individual items in a paginated list */\n  itemType?: TypeRef;\n  /**\n   * The envelope's properties other than the data array (see\n   * `PaginationMeta.envelopeFields`). Set only for a list envelope.\n   */\n  envelopeFields?: Field[];\n  /**\n   * The field that ends an iteration, when the body declares an obvious one\n   * (see `PaginationMeta.endOfIteration`): read beside the array a list\n   * envelope was unwrapped on, and beside the array an explicit `dataPath`\n   * names in a body kept as a wrapper — a `$ref` to a component, an envelope\n   * detection would unwrap on another array, an inline body detection did\n   * not recognize (`bodyEndOfIteration`). Unset for every other body.\n   */\n  endOfIteration?: PaginationEndOfIteration;\n  /**\n   * Models lifted from inline companion objects, still under their\n   * operation-qualified names. They are deliberately not in `inlineModels`:\n   * `resolveEnvelopeCompanionNames` decides their final names once every list\n   * operation has been extracted.\n   */\n  envelopeCompanions?: EnvelopeCompanion[];\n}\n\nexport interface ResponseClassificationOptions {\n  /**\n   * Nothing will page the operation: its pagination was switched off\n   * explicitly (`strategy: 'none'`), or no query parameter it declares\n   * drives an iterator and no override names one. A list envelope is then\n   * not unwrapped: the body becomes a plain response model carrying every\n   * field, exactly as a non-list body does, so the wire shape survives\n   * without a `pagination` entry to describe it (`unpagedEnvelope` says it\n   * was an envelope).\n   */\n  paginationDisabled?: boolean;\n  /**\n   * An explicit `dataPath`, already known to reach an array in the body. One\n   * that restates the path a list envelope is unwrapped on changes nothing.\n   * Any other keeps the body as the wrapper the override iterates — a\n   * recognized envelope, kept exactly as under `paginationDisabled` since\n   * detection was wrong for this operation; an inline body detection did not\n   * recognize; a `$ref` to a component — so `response` is what the wire\n   * returns, the override says where the items are in it, and the wrapper\n   * carries the companions. The wrapper's stop field is still read, keyed by\n   * the override, whatever the wrapper is (`bodyEndOfIteration`). Read only\n   * when `paginationDisabled` is not set: `strategy: 'none'` leaves no\n   * iterator to stop.\n   */\n  dataPathOverride?: string;\n  /**\n   * With it, the items of an array body or a list envelope are typed under\n   * the first `<Op>Item` candidate the registry does not give another shape,\n   * and an identical shape shares the model it finds (`typeInlineItems`).\n   * Absent — the dry run that reads a component response's names, a direct\n   * call — the items take `<Op>Item` as written; the dry run that reads an\n   * operation's own names settles them against a copy of the registry\n   * (`operationBodyModelNames`), so it reads the name the operation takes.\n   */\n  settle?: ItemSettlement;\n}\n\n/**\n * The readings an inline body can take, one per way `buildOperation` decides\n * it (`iteratorSource`): unwrapped on its data array for an iterator a\n * declared query parameter or a usable override drives, or kept as the wire\n * shape — `strategy: 'none'`, nothing to page with, an explicit `dataPath`\n * naming another array (the same reading as `paginationDisabled`, so the\n * same names). A body that is no list envelope reads the same under both.\n * Which reading an operation takes is known only when it is read, so a dry\n * run that reserves a body's names (`bodyModelNames`) classifies it under\n * every reading here: whichever the operation then picks, the names it mints\n * are the reserved ones.\n */\nexport const BODY_READINGS: readonly ResponseClassificationOptions[] = [{}, { paginationDisabled: true }];\n\n/**\n * The word that stands in for a range key wherever a status code would\n * qualify a name: the header models and enums of a `4XX` response are\n * `…ClientError`, and the inline body of a `1XX`–`3XX` response is\n * `<Op><Label>Response` (`<Op>SuccessResponse`), as a `default` body is\n * `<Op>DefaultResponse`. The key itself cannot be used in these names —\n * `toPascalCase('4XX')` is `4Xx`. The inline body of a `4XX` or `5XX`\n * response is an error body (`isErrorStatusRange`), named `<Op>Error4Xx`\n * from the key itself, as a 404's is `<Op>Error404`.\n */\nexport const STATUS_RANGE_LABELS: Record<StatusRange, string> = {\n  '1XX': 'Informational',\n  '2XX': 'Success',\n  '3XX': 'Redirect',\n  '4XX': 'ClientError',\n  '5XX': 'ServerError',\n};\n\n/**\n * Whether a range response is an error response: `4XX` and `5XX` are, as\n * every status code they cover is an error (400–599); `1XX`–`3XX` are not.\n * The one answer for every place a range body is named: its inline body is\n * named and stepped as an explicit error status code's body is\n * (`<Op>Error4Xx`, then `<Op>Error4XxBody`; `<Op>Error4Xx<MediaType>` under\n * a secondary media type), while a `1XX`–`3XX` body keeps the range's label\n * (`<Op>SuccessResponse`).\n */\nexport function isErrorStatusRange(range: StatusRange): boolean {\n  return range === '4XX' || range === '5XX';\n}\n\n/**\n * What a Responses Object key names. OpenAPI defines four kinds of key:\n * `default`; an HTTP status code, exactly three digits in 100–599; a range,\n * `1XX`–`5XX` in either case; and an `x-` specification extension. The\n * whole key decides, never a numeric prefix: `6XX`, `4XXX`, `20X`, `600`,\n * `099` and `200 ` are `unrecognized`, like `error` or `Default`.\n */\nexport type ResponseKey =\n  | { kind: 'status'; code: number }\n  | { kind: 'range'; range: StatusRange }\n  | { kind: 'default' }\n  | { kind: 'extension' }\n  | { kind: 'unrecognized' };\n\n/**\n * Classify a Responses Object key. Every reader of a Responses Object —\n * an operation's responses, the const prefixes it reserves, a webhook's\n * responses — goes through here, so a key is a status code in one place or\n * in none.\n */\nexport function classifyResponseKey(key: string): ResponseKey {\n  if (key === 'default') return { kind: 'default' };\n  if (key.startsWith('x-')) return { kind: 'extension' };\n  if (/^[1-5]\\d{2}$/.test(key)) return { kind: 'status', code: Number(key) };\n  if (/^[1-5]XX$/i.test(key)) return { kind: 'range', range: key.toUpperCase() as StatusRange };\n  return { kind: 'unrecognized' };\n}\n\n/**\n * Warn about a Responses Object key OpenAPI does not define, which the\n * caller then ignores rather than drops silently. `label` names the\n * operation or webhook the key sits on.\n */\nexport function warnUnrecognizedResponseKey(key: string, label: string): void {\n  console.warn(\n    `[oagen] Warning: Ignoring response key \"${key}\" on ${label}: not a status code (three digits, 100–599), a 1XX–5XX range, or \"default\"`,\n  );\n}\n\nexport function classifyAndExtractResponse(\n  schema: SchemaObject,\n  contextName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  options: ResponseClassificationOptions = {},\n): ResponseExtractionResult {\n  const body = classifyBody(schema, contextName, componentSchemas, options);\n  // Under an explicit `dataPath`, a body that was not unwrapped on that path\n  // is the wrapper the override iterates — a `$ref` to a component, an\n  // envelope detection would unwrap on another array, an inline body\n  // detection did not recognize — and its stop field is read here, once for\n  // every such shape, keyed by the path. A path that restates the one the\n  // envelope was unwrapped on (`isPaginated`) has had it read by\n  // `extractListResponse`; under `paginationDisabled` there is no iterator\n  // to stop.\n  const override = options.dataPathOverride;\n  if (override === undefined || options.paginationDisabled || body.isPaginated) return body;\n  const endOfIteration = bodyEndOfIteration(schema, override, componentSchemas);\n  return endOfIteration ? { ...body, endOfIteration } : body;\n}\n\n/**\n * The field that ends an iteration of a body kept as a wrapper under an\n * explicit `dataPath`, read beside the array the path names — the one\n * reader for every kept wrapper, whatever wraps it. The wrapper's\n * properties are collected exactly as a recognized envelope's are\n * (`collectObjectProperties`, which reads the body and every `allOf`\n * member, however deep, through `resolveBareSchema` — the resolver the path\n * walk uses — so a `$ref` body, a nullable wrapper around the body or\n * around any member, and a `$ref` chain to one all reach the same object\n * the path walked), and `detectEndOfIteration` reads them as it reads an\n * unwrapped envelope's: the fields beside the array the path names first,\n * under a parent of any name (`result.total_pages` next to `result.items`),\n * then those beside each object the path passes through, nearest the array\n * first, then the top level, then the metadata companions, and never the\n * array or an object on the path itself. The properties read are those\n * every instance carries (`onEveryInstance`): a member's, or every\n * variant's of a `oneOf`/`anyOf` the `allOf` flattens, so a stop field only\n * some variants declare — an optional field of the wrapper's model — ends no\n * iteration (workos/oagen#622). `undefined` when nothing recognizable is\n * declared, or the body resolves to no object at all.\n */\nfunction bodyEndOfIteration(\n  schema: SchemaObject,\n  dataPath: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): PaginationEndOfIteration | undefined {\n  const { onEveryInstance } = collectObjectProperties(schema, componentSchemas);\n  return detectEndOfIteration(onEveryInstance, dataPath, componentSchemas);\n}\n\n/**\n * Why an explicit `endOfIteration` cannot be read from `schema`, or\n * `undefined` when it can: the override's counterpart of\n * `bodyEndOfIteration`, over the very property map that reader collects\n * (`collectObjectProperties`, `onEveryInstance`: what every instance\n * carries, a stop field each variant of a flattened `oneOf` declares\n * included), so a field detection would read is one an override may name\n * and a field it would not see is not there for an override either;\n * `endOfIterationProblem` then walks the path and tests the type. `schema`\n * is the body as written — a `$ref`, an `allOf`, a nullable wrapper — or\n * `undefined` when the operation declares no body, which no path resolves\n * in.\n */\nexport function bodyEndOfIterationProblem(\n  end: PaginationEndOfIteration,\n  schema: SchemaObject | undefined,\n  componentSchemas?: Record<string, SchemaObject>,\n): string | undefined {\n  const properties = schema && collectObjectProperties(schema, componentSchemas).onEveryInstance;\n  return endOfIterationProblem(end, properties, componentSchemas);\n}\n\n/**\n * Classify one body: a `$ref` names its component; an inline body is a list\n * envelope — unwrapped on its data array, unless an explicit `dataPath`\n * names another array in it — a single-resource wrapper, or a plain model.\n */\nfunction classifyBody(\n  schema: SchemaObject,\n  contextName: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  options: ResponseClassificationOptions,\n): ResponseExtractionResult {\n  // 1. If schema is a $ref, resolve to model name (Phase 1)\n  if (schema.$ref) {\n    return { response: schemaToTypeRef(schema, contextName), inlineModels: [], isPaginated: false };\n  }\n\n  // `properties` written beside a typing `allOf`/`oneOf`/`anyOf` are folded\n  // into the composition, as `schemaToTypeRef` and the field extractor read\n  // them (`foldSiblingProperties`), so a body is read the one way wherever it\n  // appears: the branches below read `properties` before a composition and\n  // would otherwise drop the composition that a field keeps. The variants\n  // that cannot take the properties are reported on the body as written,\n  // under the body's name, since the fold leaves `schemaToTypeRef` nothing\n  // to report.\n  warnOnUncarriedProperties(schema, contextName, undefined);\n  schema = foldSiblingProperties(schema);\n\n  // 2. Check for list envelope (structural detection: array prop + non-array companion)\n  const envelope = detectListEnvelope(schema, componentSchemas);\n  if (envelope.isEnvelope) {\n    const override = options.dataPathOverride;\n    if (!options.paginationDisabled && (override === undefined || override === envelope.dataPath)) {\n      return extractListResponse(schema, contextName, envelope.dataPath!, componentSchemas, options.settle);\n    }\n    // A recognized envelope that is not unwrapped is kept as the wire shape,\n    // one model carrying every field, whichever reason keeps it: nothing\n    // pages the operation (`paginationDisabled` — `strategy: 'none'`, or no\n    // declared query parameter and no usable override), or an explicit\n    // `dataPath` names another array than the one it would be unwrapped on\n    // (detection was wrong for this operation; its stop field is read by the\n    // caller, `bodyEndOfIteration`). It never takes the single-resource\n    // reading below: an envelope with one required companion carrying a\n    // constant `type`/`object` (`{ data, pagination: { type: 'pagination',\n    // total } }` with `required: ['pagination']`) fits that shape, and\n    // unwrapping it would make the companion the whole response and drop\n    // `data`. `unpagedEnvelope` tells the caller which reason kept it, so an\n    // envelope kept for want of a paging parameter is warned about.\n    const kept = extractDirectResource(schema, contextName, componentSchemas, options.settle);\n    return options.paginationDisabled ? { ...kept, unpagedEnvelope: true } : kept;\n  }\n\n  // 3. Check for single-resource wrapper ({ resource_name: { object: \"...\", ... } })\n  if (isSingleResourceWrapper(schema)) {\n    return extractWrappedResource(schema, contextName, componentSchemas);\n  }\n\n  // 4. Direct resource or plain inline object\n  return extractDirectResource(schema, contextName, componentSchemas, options.settle);\n}\n\ninterface ListEnvelopeResult {\n  isEnvelope: boolean;\n  dataPath: string | null;\n}\n\nconst KNOWN_DATA_PATHS = new Set(['data', 'items', 'results', 'records', 'entries', 'values', 'nodes', 'edges']);\n\n/**\n * Whether an inline body is a list envelope — one array property beside a\n * companion that looks like pagination metadata — and the array it is\n * unwrapped on. The properties are read off the set the body's model is\n * built from: the `allOf` members' own `properties` and the body's own,\n * and what the variants of a `oneOf`/`anyOf` a member writes declare\n * (`readFlattenedUnion`, through the reader the model flattens a variant\n * with — its own properties, its `allOf` members, a `$ref` variant's\n * component; a union beside the `allOf` is one such member once folded,\n * `foldSiblingProperties`) — the model's optional fields, typed as it\n * types them (`unionOfDeclarations`) where no member declares the name,\n * since a variant can only narrow what every instance carries. So `{\n * allOf: [{ data }], oneOf: [{ has_more }, { has_more, total }] }` is the\n * envelope `{ data, has_more?, total? }` is (workos/oagen#622: the variants\n * were read by the model alone, and the body was that model, no list). The\n * array must be there whichever variant the wire sends — a member's, or\n * declared by every non-null variant (`carried`), as an explicit `dataPath`\n * is resolved through the union (`resolveDataPathArray`) — and it must be\n * the array the companion walk reads at that name\n * (`collectObjectProperties`, `onEveryInstance`), the one\n * `extractListResponse` unwraps on: a declaration a `$ref` member's\n * component or a nested `allOf` member makes — which detection does not\n * read — stands over the variants' there as in the model\n * (`declareProperty`: an always-applying declaration, typeless or not,\n * over a branch-only one), so `Base: { data: { description } }` beside\n * `oneOf: [{ data: integer[] }, …]` is no envelope but the model (PR #643\n * review round 3: it was unwrapped on an array the walk had no items for,\n * and the response was `string[]`), while `Base: { data: integer[] }` is\n * unwrapped on `Base`'s array — while a\n * companion may be any variant's: a stop field only some variants declare,\n * or one they type differently, still marks the envelope, as an optional\n * `has_more` written flat does, and `detectEndOfIteration` then finds no\n * field to stop on. A bare `oneOf`/`anyOf` body, with or without\n * `properties` beside it, is a union of models and never an envelope, and\n * so is an `allOf` the parser reads as its lone union member\n * (`readInlineAllOf`: `allOf: [{ oneOf: [...] }]`, with or without\n * annotations beside it, is that union, as `resolveBareSchema` reads it\n * for the companion walk and `extractDirectResource` for the model), so\n * the variants are read only for an `allOf` the parser merges (PR #643\n * review: a lone union member was read as a merge here, detected as an\n * envelope, and extracted off a walk that saw no field — `string[]` with\n * no companions). A `$ref` member — and whatever is written beside its\n * `$ref` (`{ $ref: Base, oneOf: [A, B] }`, `{ $ref: Base, properties }`),\n * which the model (`mergeAllOfMembers`) and the companion walk\n * (`collectObjectProperties`) ignore for the component the reference names\n * (PR #643 review round 2: a union beside the `$ref` was read here, so a\n * `data` every variant declared marked an envelope the walk had no `data`\n * in, and the response was `string[]`) — is not read here, as before: a\n * body whose array or companion sits in one is the wrapper an explicit\n * `dataPath` keeps (workos/oagen#308). A nullable wrapper a member writes\n * (`{ oneOf: [{ has_more }, { type: 'null' }] }`, `{ enum: [null] }` on\n * OAS 3.0) is read as its one non-null variant, as the model and the\n * companion walk read it, so `allOf: [{ data }]` beside it is the list\n * `allOf: [{ data }, { has_more }]` is, with one non-null variant as with\n * two (PR #643 review, MichaelDeBoey: the axis was skipped here, and the\n * body stayed the model `ListPetsResponse { data, has_more }` while a\n * second non-null variant made it `Pet[]`); a `$ref` branch is a `$ref`\n * member, unread.\n */\nfunction detectListEnvelope(schema: SchemaObject, componentSchemas?: Record<string, SchemaObject>): ListEnvelopeResult {\n  // Collect all property sources (allOf sub-schemas or flat schema), and\n  // what the variants of a union among the members declare, for an `allOf`\n  // the parser merges into one model.\n  const propSources: Record<string, SchemaObject | undefined>[] = [];\n  const branchOnly = new Map<string, SchemaObject[]>();\n  const carried = new Set<string>();\n  const merges =\n    schema.allOf !== undefined &&\n    classifyInlineSchema(schema) === 'allOf' &&\n    readInlineAllOf(schema.allOf, schema, componentSchemas) === 'merged';\n  const read = new Set<SchemaObject>();\n  const readMember = (member: SchemaObject): void => {\n    // A `$ref` member is its component, whatever is written beside the\n    // reference, as the model and the walk read it; a member met again\n    // (a nullable wrapper around the body itself) declares nothing more.\n    if (member.$ref || read.has(member)) return;\n    read.add(member);\n    if (member.properties) propSources.push(member.properties);\n    if (!merges) return;\n    for (const variants of unionAxesOf(member)) {\n      // A nullable axis is its one non-null variant, read as the member is.\n      const branch = nullableAxisBranch(member, variants);\n      if (branch) {\n        readMember(branch);\n        continue;\n      }\n      const keyword = variants === member.oneOf ? 'oneOf' : 'anyOf';\n      const flattened = readFlattenedUnion({ schema: member, keyword, variants, origin: null }, componentSchemas);\n      for (const [name, declarations] of flattened.declared) {\n        const held = branchOnly.get(name);\n        if (held) held.push(...declarations);\n        else branchOnly.set(name, [...declarations]);\n        if (flattened.carried.has(name)) carried.add(name);\n      }\n    }\n  };\n  for (const sub of schema.allOf ?? []) readMember(sub);\n  if (schema.properties) {\n    propSources.push(schema.properties);\n  }\n\n  if (propSources.length === 0 && branchOnly.size === 0) return { isEnvelope: false, dataPath: null };\n\n  // Merge all properties into a single view. A name two members declare is\n  // settled as every `allOf` merge settles it (`combineDeclarations`): the\n  // first declaration that declares a type, a typeless one only annotating\n  // it, so `data: { type: 'array' }` beside a later `data: { description }`\n  // is still the array detection looks for.\n  const mergedProps: Record<string, SchemaObject> = {};\n  for (const source of propSources) {\n    for (const [key, prop] of Object.entries(source)) {\n      if (!prop) continue;\n      const existing = mergedProps[key];\n      mergedProps[key] = existing ? combineDeclarations(existing, prop) : prop;\n    }\n  }\n  // A name a member declares is on every instance; one only the variants\n  // declare is typed as the model types it.\n  const own = new Set(Object.keys(mergedProps));\n  const onEveryInstance = (name: string): boolean => own.has(name) || carried.has(name);\n  for (const [name, declarations] of branchOnly) {\n    if (!own.has(name)) mergedProps[name] = unionOfDeclarations(declarations);\n  }\n\n  // Find array properties — typed, `items` with no `type`, or either under a\n  // nullable wrapper of any spelling or an `allOf` read as its member\n  // (`arraySchemaOf`), a `$ref` to an array component under such wrappers\n  // (`isArrayComponentRef`), which `schemaToTypeRef` types as the array the\n  // component declares, or a pointer deeper into a component that lands on\n  // a schema typed as an array where it stands (`isArrayPointerRef`; #609),\n  // which the settle types as that array — and non-array companion\n  // properties\n  const arrayProps: string[] = [];\n  const nonArrayKeys: string[] = [];\n  const isArrayDeclaration = (declaration: SchemaObject): boolean =>\n    arraySchemaOf(declaration) !== undefined || isArrayComponentRef(declaration) || isArrayPointerRef(declaration);\n\n  for (const [key, propSchema] of Object.entries(mergedProps)) {\n    if (!propSchema) continue;\n    if (isArrayDeclaration(propSchema)) {\n      arrayProps.push(key);\n    } else {\n      nonArrayKeys.push(key);\n    }\n  }\n\n  // List envelope heuristic: exactly one array property + at least one non-array companion\n  // that looks like pagination metadata.  A `data` array alone (e.g. with only an\n  // `object` discriminant companion) is NOT sufficient — the companion must indicate\n  // actual pagination (cursor, metadata, total, etc.).\n  if (arrayProps.length === 1 && nonArrayKeys.length >= 1) {\n    const arrayPropName = arrayProps[0];\n\n    // The array an iterator unwraps on must be there whichever variant the\n    // wire sends; one only some variants declare leaves the body the model\n    // it is, the array an optional field of it.\n    if (!onEveryInstance(arrayPropName)) return { isEnvelope: false, dataPath: null };\n    // And the shape must be the one the companion walk reads, the one\n    // `extractListResponse` unwraps: a declaration a `$ref` member's\n    // component or a nested `allOf` member makes, which detection does not\n    // read, stands over the variants' there as in the model. So the array\n    // must be an array there (a typeless or object `data` in `Base` beside\n    // variants typing it `integer[]` leaves the body the model it is), and\n    // every other property detection read must be no array there (`Base: {\n    // has_more: integer[] }` beside variants typing it `boolean` is two\n    // arrays and no companion, as `{ data, has_more: integer[] }` written\n    // flat is; PR #643 review round 6: the body was unwrapped on `data` with\n    // the array `has_more` among its companions).\n    const walked = collectObjectProperties(schema, componentSchemas);\n    const walkedArray = walked.onEveryInstance[arrayPropName];\n    if (walkedArray === undefined || !isArrayDeclaration(walkedArray)) return { isEnvelope: false, dataPath: null };\n    const arrayInWalk = (key: string): boolean => {\n      const declaration = walked.fields[key];\n      return declaration === undefined ? arrayProps.includes(key) : isArrayDeclaration(declaration);\n    };\n    if (nonArrayKeys.some(arrayInWalk)) return { isEnvelope: false, dataPath: null };\n\n    // A companion is pagination metadata when it is one of the stop fields\n    // the end-of-iteration detector reads, in any spelling (`hasMore`,\n    // `HasNext`, `page-count`, …: `spellsOneOf`, the test the detector\n    // reads a stop field's name with) — one shared list and one test, so an\n    // envelope that carries a stop field is always recognized — or when its\n    // name, read in any spelling, contains one of the metadata patterns\n    // (`meta`, `pagination`, `cursor`, …: `looksLikePaginationMetadata`, the\n    // recognizer the nested stop-field scan shares, so `pageInfo` marks an\n    // envelope exactly as `page_info` does and `pageInfo.hasNextPage` is\n    // then read as its stop field).\n    const hasPaginationCompanion = nonArrayKeys.some(\n      (key) => spellsOneOf(key, END_OF_ITERATION_FIELDS) || looksLikePaginationMetadata(key),\n    );\n\n    if (KNOWN_DATA_PATHS.has(arrayPropName) && hasPaginationCompanion) {\n      return { isEnvelope: true, dataPath: arrayPropName };\n    }\n\n    // Non-standard array property name — still treat as envelope if pagination companion exists\n    if (hasPaginationCompanion) {\n      return { isEnvelope: true, dataPath: arrayPropName };\n    }\n  }\n\n  return { isEnvelope: false, dataPath: null };\n}\n\nfunction extractListResponse(\n  schema: SchemaObject,\n  contextName: string,\n  dataPath: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  settle?: ItemSettlement,\n): ResponseExtractionResult {\n  let itemTypeRef: TypeRef = { kind: 'primitive', type: 'string' };\n  const inlineModels: Model[] = [];\n\n  // The envelope's fields are its model's (`fields`: a member's, and every\n  // one the variants of a `oneOf`/`anyOf` the `allOf` flattens declare, as\n  // optional fields); the array and the stop field are read among the\n  // fields every instance carries (`onEveryInstance`), the ones detection\n  // found the array in.\n  const { fields, onEveryInstance, required } = collectObjectProperties(schema, componentSchemas);\n\n  const dataProp = onEveryInstance[dataPath];\n  // The property's own text, as `buildFieldFromSchema` keeps it for every\n  // companion beside it; an item schema's description belongs to the item.\n  const dataDescription = dataProp?.description;\n  // The data array's type when it is a `$ref` typed as an array: the array\n  // a component declares, with the component's own nullability, or the\n  // array a pointer deeper into a component settles to.\n  let dataType: TypeRef | undefined;\n  if (dataProp && (isArrayComponentRef(dataProp) || isArrayPointerRef(dataProp))) {\n    // A `$ref` to an array component, under any nullable wrapper, is the\n    // array the component declares, its items named under the component\n    // (`<Component>Item…`) and already materialized by the component pass —\n    // nothing is minted here, and `<Operation>Item` stays free. A pointer\n    // deeper into a component (#609) is a reference settled once every\n    // model is built (`resolveSchemaPointers`), to the array the schema it\n    // lands on is typed as where it stands, its items the model that\n    // schema's items built (`HolderOwner` for `Holder/properties/owners`),\n    // never a copy of it: until then the response is the pending reference,\n    // and the item type is that very reference, so the settle rereads the\n    // item type from the settled array (`visitOperation`), as it does for a\n    // body that is the pointer.\n    dataType = schemaToTypeRef(dataProp, contextName);\n    const array = dataType.kind === 'nullable' ? dataType.inner : dataType;\n    if (array.kind === 'array') itemTypeRef = array.items;\n    else if (isPendingVariant(dataType)) itemTypeRef = dataType;\n  } else {\n    // The array under whatever nullable wrapper or `allOf` the data property\n    // wears (`arraySchemaOf`); its items, whatever their shape, are typed and\n    // materialized as `<Operation>Item` (`typeInlineItems`).\n    const dataArray = dataProp ? arraySchemaOf(dataProp) : undefined;\n    if (dataArray?.items) {\n      const typed = typeInlineItems(\n        dataArray.items,\n        contextName.replace(/Response$/, '') + 'Item',\n        componentSchemas,\n        settle,\n      );\n      itemTypeRef = typed.itemType;\n      inlineModels.push(...typed.inlineModels);\n    }\n  }\n\n  // Everything the envelope carries besides the data array: the pagination\n  // companion (`list_metadata`, `pagination`, `has_more`, …) and any\n  // discriminant such as `object: \"list\"`. Without these an emitter cannot\n  // type the endpoint's actual response or read the next-page details.\n  const { envelopeFields, envelopeCompanions } = extractEnvelopeCompanions(\n    fields,\n    required,\n    dataPath,\n    contextName.replace(/Response$/, ''),\n    componentSchemas,\n  );\n\n  // The field that says the list is exhausted — `has_more`, `total_pages`,\n  // `pagination.totalPages` — so an iterator can stop without a wasted\n  // request: the read `bodyEndOfIteration` makes for a kept wrapper, on the\n  // properties already collected above, those every instance carries.\n  const endOfIteration = detectEndOfIteration(onEveryInstance, dataPath, componentSchemas);\n\n  return {\n    // The data array's own nullability is the response's: a `data` declared\n    // `type: ['array', 'null']`, OAS 3.0 `nullable: true`, or `oneOf`/`anyOf`\n    // with a `null` variant means the list the SDK returns may be null, so\n    // the wrapper `schemaToTypeRef` would give the field stays on `response`\n    // — `envelopeFields` leaves `data` out, so nothing else records it —\n    // while `itemType` is still what an iterator yields (`paginatedItemType`\n    // unwraps the same wrapper). A `$ref` to an array component carries the\n    // component's own nullability, and its wrapper's, the same way.\n    // The array built here carries the data property's own limits\n    // (`minItems`, `uniqueItems`, …), as `schemaToTypeRef` would have it\n    // carry them (#545); the items carry theirs.\n    response:\n      dataType ??\n      (dataProp\n        ? nullableIf(dataProp, withSchemaConstraints({ kind: 'array', items: itemTypeRef }, dataProp))\n        : { kind: 'array', items: itemTypeRef }),\n    inlineModels,\n    isPaginated: true,\n    dataPath,\n    ...(dataDescription !== undefined && { dataDescription }),\n    itemType: itemTypeRef,\n    envelopeFields,\n    endOfIteration,\n    envelopeCompanions: envelopeCompanions.length > 0 ? envelopeCompanions : undefined,\n  };\n}\n\n/**\n * Element type of the array an explicit `dataPath` points at, read from the\n * response document when the IR cannot answer — a `$ref` wrapper whose path\n * runs through a model the parser has not materialized (an array\n * component's, say), an envelope the parser did not recognize, or a\n * `oneOf`/`anyOf` on the way whose variants' models type the same items\n * under names of their own. `undefined` when the path reaches no array\n * (`resolveDataPathArray`, the one walk; `dataPathProblem` says why, for\n * the check `extractResponses` makes before classifying a body).\n *\n * The array may sit under a nullable wrapper of any form — `type: ['array',\n * 'null']`, OAS 3.0 `nullable: true`, `oneOf: [{ type: 'array' }, { type:\n * 'null' }]`, a nullable `$ref` to an array component — which\n * `resolveBareSchema` looks through exactly as the IR walk\n * (`resolveDataPathItemType`) looks through the `nullable` TypeRef those\n * forms become, and the path goes on through each non-null variant of a\n * union an object on the way is, as the IR walk goes through each variant\n * of a `union` (workos/oagen#556), so the two never disagree about whether\n * the path lands on an array; `isArraySchema` then decides, as every other\n * site does, in every variant, whose arrays must agree on their items.\n *\n * The items are typed and materialized as every array response's are\n * (`typeInlineItems`): as a field named for the path (`result.items` →\n * `ListPetsResultItem`, `records` → `ListPetsRecord`; see\n * `inlineItemNameForPath`) under no parent — so the item type never names a\n * model nobody created.\n */\nexport function resolveDataPathFromSchema(\n  schema: SchemaObject,\n  dataPath: string,\n  contextName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  settle?: ItemSettlement,\n): { itemType: TypeRef; inlineModels: Model[] } | undefined {\n  const resolved = resolveDataPathArray(schema, dataPath, componentSchemas);\n  if ('problem' in resolved) return undefined;\n  return typeInlineItems(resolved.items, inlineItemNameForPath(contextName, dataPath), componentSchemas, settle);\n}\n\n/**\n * Type an array's items and materialize every model they reference, as a\n * field named `itemName` under no parent: `schemaToTypeRef` names the\n * reference and `extractInlineModelsFromProperties` builds the models, and\n * the two mirror each other form for form, so the item type never names a\n * model nobody created. The one path for the items of an array response\n * body, a list envelope's data array and an explicit `dataPath`'s array,\n * whatever shape the items take. A `$ref` is a reference and mints nothing;\n * a plain object is that model (`ListPetsItem`); a nullable object\n * (`type: ['object', 'null']`, OAS 3.0 `nullable: true`, a nullable\n * `oneOf`) is a `nullable` reference to it; an inline enum is\n * `<itemName>`; the inline object variants of a union take the union's\n * names (`ListPetsItem`, `ListPetsItemWithSide`); an object that also\n * composes — `properties` beside an `allOf` or `oneOf` — is the\n * composition carrying the properties (`foldSiblingProperties`); the\n * objects of a nested array or map, and whatever any of these reference in\n * turn, are materialized under the name the reference uses.\n *\n * With `settle`, the names are settled against the spec-wide registry\n * through `materializeInlineSchema`, the one retry loop every deferred\n * schema goes through: the items are tried as `<Op>Item`, and when a name\n * they mint — the root, a union variant, a nested object — belongs to\n * another shape (a component model or enum, a component's field model, an\n * earlier operation's model), as `<Op>ResponseItem`, then `<Op>Item2`,\n * `<Op>Item3`, …, the first candidate that clashes with nothing; a shape\n * identical to a name's owner shares it and mints nothing, so items matching\n * a component `ListPetsItem` reference the component. The models minted are\n * recorded under the operation; a reference written by sharing another\n * site's model joins that site (`attachSharedRefs`), so a later rename of\n * the shared model — a deprecated copy named like a live one — reaches this\n * array too. Without `settle` — the dry run that reads a component\n * response's names, a direct call — the items take `<Op>Item` as written;\n * the dry run that reads an operation's own names settles them against a\n * copy of the registry as seeded, so it reads the name the operation takes\n * (`operationBodyModelNames`).\n */\nfunction typeInlineItems(\n  items: SchemaObject,\n  itemName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  settle?: ItemSettlement,\n): { itemType: TypeRef; inlineModels: Model[] } {\n  const inlineModels: Model[] = [];\n  if (settle) {\n    const itemType = materializeInlineSchema(items, {\n      stem: (index) =>\n        index === 0\n          ? itemName\n          : index === 1\n            ? itemName.replace(/Item$/, 'ResponseItem')\n            : numberedName(itemName, index),\n      componentSchemas,\n      registry: settle.registry,\n      operation: settle.operation,\n      models: inlineModels,\n    });\n    return { itemType, inlineModels };\n  }\n  extractInlineModelsFromProperties({ properties: { [itemName]: items } }, inlineModels, undefined, componentSchemas);\n  return { itemType: schemaToTypeRef(items, itemName), inlineModels };\n}\n\n/**\n * Name for inline items reached through an overridden `dataPath`, built from\n * the path the way the inline extractor names a nested field's items: the\n * operation, the enclosing properties, then the singular of the array's own\n * name (`result.items` → `ListPetsResultItem`). It therefore coincides with a\n * model the parser may already have minted for that field, and never takes\n * the bare `<Op>Item` that a recognized envelope's data array owns.\n */\nfunction inlineItemNameForPath(contextName: string, dataPath: string): string {\n  const segments = dataPath.split('.');\n  const parents = segments\n    .slice(0, -1)\n    .map((segment) => toPascalCase(segment))\n    .join('');\n  const own = singularize(toPascalCase(segments[segments.length - 1]));\n  return contextName.replace(/Response$/, '') + parents + own;\n}\n\n/**\n * Type a list envelope's companion properties as fields, lifting any inline\n * object among them (and anything nested inside it) to a model.\n *\n * Models come from `extractInlineModelsFromProperties`, the extractor that\n * mirrors `schemaToTypeRef` form for form — plain, nullable and `allOf`\n * objects, arrays of objects, and every `oneOf`/`anyOf` object variant — so a\n * field's reference always has a model behind it.\n *\n * Each companion is extracted twice: once under the operation's name, which\n * is how its models enter the IR (`ListUsersListMetadata`), and once under no\n * parent, which yields the name each model would carry if named from its\n * property alone (`ListMetadata`). Both runs walk the same code path, so the\n * two model lists line up index for index. `resolveEnvelopeCompanionNames`\n * later picks, per companion, which of the two names survives — the bare one\n * only where every copy of that companion across the API agrees structurally.\n */\nfunction extractEnvelopeCompanions(\n  properties: Record<string, SchemaObject>,\n  required: string[],\n  dataPath: string,\n  operationName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): { envelopeFields: Field[]; envelopeCompanions: EnvelopeCompanion[] } {\n  const envelopeFields: Field[] = [];\n  const envelopeCompanions: EnvelopeCompanion[] = [];\n  const requiredSet = new Set(required);\n  // The companion is extracted from a one-property schema, so hand the\n  // extractor the envelope's full property list: array items and map values\n  // must step aside from a singular sibling exactly as the field does.\n  const siblings = collectProperties({ properties });\n\n  for (const [key, propSchema] of Object.entries(properties)) {\n    if (key === dataPath) continue;\n    const field = buildFieldFromSchema(key, propSchema, operationName, requiredSet, componentSchemas, siblings);\n    envelopeFields.push(field);\n\n    // Both runs get the component map so a companion's `$ref` fields carry\n    // the component's example in the qualified and bare copies alike; it\n    // only feeds field metadata, so the two model lists still line up.\n    const single: SchemaObject = { type: 'object', properties: { [key]: propSchema } };\n    const models: Model[] = [];\n    extractInlineModelsFromProperties(single, models, operationName, componentSchemas, siblings);\n    if (models.length === 0) continue;\n    const bare: Model[] = [];\n    extractInlineModelsFromProperties(single, bare, undefined, componentSchemas, siblings);\n    envelopeCompanions.push({ field, models, bareNames: bare.map((m) => m.name) });\n  }\n\n  return { envelopeFields, envelopeCompanions };\n}\n\nfunction hasDiscriminantConstField(schema: SchemaObject): { property: string; value: string } | null {\n  if (!schema.properties) return null;\n\n  // Prefer well-known discriminant properties for backward compatibility\n  const preferred = ['object', 'type'];\n  for (const name of preferred) {\n    const field = schema.properties[name];\n    if (!field) continue;\n    if (field.const !== undefined && typeof field.const === 'string') {\n      return { property: name, value: field.const };\n    }\n    if (field.enum && field.enum.length === 1 && typeof field.enum[0] === 'string') {\n      return { property: name, value: field.enum[0] };\n    }\n  }\n\n  // Fall back to any property with a const or single-value enum\n  for (const [name, field] of Object.entries(schema.properties)) {\n    if (!field) continue;\n    if (field.const !== undefined && typeof field.const === 'string') {\n      return { property: name, value: field.const };\n    }\n    if (field.enum && field.enum.length === 1 && typeof field.enum[0] === 'string') {\n      return { property: name, value: field.enum[0] };\n    }\n  }\n\n  return null;\n}\n\nfunction isSingleResourceWrapper(schema: SchemaObject): boolean {\n  if (schema.type !== 'object') return false;\n  if (!schema.properties) return false;\n\n  // Find the wrapper property: use required[0] if available, or the single property key\n  let wrapperKey: string | undefined;\n  if (schema.required && schema.required.length === 1) {\n    wrapperKey = schema.required[0];\n  } else {\n    const propKeys = Object.keys(schema.properties);\n    if (propKeys.length === 1) {\n      wrapperKey = propKeys[0];\n    }\n  }\n  if (!wrapperKey) return false;\n\n  const propSchema = schema.properties[wrapperKey];\n  if (!propSchema) return false;\n\n  // A `oneOf`/`anyOf` with more than one variant once every `null` one is\n  // set aside (`isNullSchema`), any of which adds a shape the property does\n  // not already have (`variantAddsShape`), is a union, the body's own field,\n  // however many variants carry a const and whatever properties are written\n  // beside it: unwrapping it would type the response as one variant, or as\n  // those properties alone, and drop the rest (#415). A union whose every\n  // variant only limits the object — bare constraint sets, `type: 'object'`\n  // repeated, refinements of the object's own properties — does not type\n  // the property; the object still unwraps.\n  const variants = (propSchema.oneOf ?? propSchema.anyOf)?.filter((v) => !isNullSchema(v)) ?? [];\n  if (variants.length > 1 && variants.some((variant) => variantAddsShape(variant, propSchema))) return false;\n\n  // Direct object with a discriminant const field\n  if (propSchema.type === 'object' && hasDiscriminantConstField(propSchema) !== null) return true;\n\n  // A `oneOf` of one such object, with or without `null` variants (a\n  // nullable resource).\n  if (propSchema.oneOf) {\n    return variants.length === 1 && variants[0].type === 'object' && hasDiscriminantConstField(variants[0]) !== null;\n  }\n\n  return false;\n}\n\n/**\n * Whether a `oneOf`/`anyOf` variant written beside a wrapped object adds a\n * shape the object does not already have, so the union is the property's\n * type rather than a limit on the object (`isSingleResourceWrapper`, #415):\n * a `$ref`; a `type` other than `object` (a primitive, or a type list\n * naming another type); a `const`, `enum`, `items` or composition that\n * types it as something else (`classifyInlineSchema`); a property the\n * object does not declare; or a const tag of its own (a second tagged\n * object, `hasDiscriminantConstField`). A variant of only `type: 'object'`,\n * `required`, limits, or refinements of properties the object declares\n * (`{ required: ['a'], properties: { a: { minLength: 1 } } }`) adds none:\n * `classifyInlineSchema` calls such a union a `union` all the same, since\n * `type` and `properties` are typing keywords, but it only limits the\n * object the body wraps.\n */\nfunction variantAddsShape(variant: SchemaObject, object: SchemaObject): boolean {\n  if (variant.type !== undefined && [variant.type].flat().some((type) => type !== 'object')) return true;\n  const kind = classifyInlineSchema(variant);\n  if (kind !== 'object' && kind !== 'map' && kind !== 'other') return true;\n  if (hasDiscriminantConstField(variant) !== null) return true;\n  const declared = object.properties ?? {};\n  return Object.keys(variant.properties ?? {}).some((name) => !Object.hasOwn(declared, name));\n}\n\nfunction extractWrappedResource(\n  schema: SchemaObject,\n  contextName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): ResponseExtractionResult {\n  const props = schema.properties!;\n  const wrapperKey = schema.required && schema.required.length === 1 ? schema.required[0] : Object.keys(props)[0];\n  const propSchema = props[wrapperKey]!;\n  const inlineModels: Model[] = [];\n\n  // Derive model name from the object const value or wrapper property name\n  const resourceName = contextName.replace(/Response$/, '');\n\n  if (propSchema.oneOf) {\n    const objectVariant = propSchema.oneOf.find((v) => v.type === 'object' && hasDiscriminantConstField(v) !== null);\n\n    if (objectVariant) {\n      const modelName = deriveModelName(objectVariant, resourceName);\n      // `oneOf: [object, null]` is a nullable wrapper: the model built from\n      // its one branch takes the wrapper's `deprecated` and limits, as every\n      // other nullable unwrap gives it (`collapsedNullableBranch`); otherwise\n      // the variant is built as written.\n      const source = collapsedNullableBranch(propSchema) ?? objectVariant;\n      inlineModels.push(...extractInlineModel(modelName, source, componentSchemas));\n\n      const hasNullVariant = propSchema.oneOf.some(\n        (v) => isNullSchema(v) || (Array.isArray(v.type) && v.type.includes('null')),\n      );\n\n      const modelRef: TypeRef = { kind: 'model', name: modelName };\n      return {\n        response: hasNullVariant ? { kind: 'nullable', inner: modelRef } : modelRef,\n        inlineModels,\n        isPaginated: false,\n      };\n    }\n  }\n\n  // Direct object\n  const modelName = deriveModelName(propSchema, resourceName);\n  inlineModels.push(...extractInlineModel(modelName, propSchema, componentSchemas));\n\n  return {\n    response: { kind: 'model', name: modelName },\n    inlineModels,\n    isPaginated: false,\n  };\n}\n\n/**\n * How `extractDirectResource` reads a body that is no `$ref`, list envelope\n * or single-resource wrapper — the one dispatch it branches on and\n * `bodyTypesAsUnknown` predicts by, so a shape is read one way by both:\n * an object declaring properties of its own (`type: 'object'` or none;\n * `composedWithoutFields` leaves an empty `properties: {}` beside a\n * composition to the composition); a type list naming several types,\n * `typeRef` whatever sits beside it, so an `allOf` beside the list types\n * its `object` copy and the other types stay (`namesSeveralTypes`; #616);\n * an `allOf` that types the schema\n * (`classifyInlineSchema`), read as `readInlineAllOf` reads it — a\n * `reference`, a lone `unwrapped` member carried with the wrapper's limits,\n * flag and link (`unwrappedAllOfMember`), or a `merged` model; an array\n * with items under a nullable wrapper of any spelling, a single-entry type\n * list included (`arraySchemaOf`: `type: ['array']` is an array here as\n * `isArraySchema` reads it); and otherwise `typeRef`, typed by\n * `schemaToTypeRef` — a union, a primitive, a map, or `unknown`.\n */\ntype DirectResourceReading =\n  | { kind: 'object' }\n  | { kind: 'reference' }\n  | { kind: 'unwrapped'; member: SchemaObject }\n  | { kind: 'merged' }\n  | { kind: 'array'; items: SchemaObject }\n  | { kind: 'typeRef' };\n\nfunction directResourceReading(\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): DirectResourceReading {\n  if (schema.properties && !composedWithoutFields(schema) && (schema.type === 'object' || !schema.type)) {\n    return { kind: 'object' };\n  }\n  // A type list naming several types is the union of its per-type copies\n  // (`typeListCopies`; #616), typed by `schemaToTypeRef` with what the\n  // copies reference materialized under the body's name by the `typeRef`\n  // fall-through, so `{ type: ['object', 'string'], allOf: [{ properties:\n  // { nick } }] }` is `CreateNoteResponse | string` — the merge the\n  // `object` copy is, beside the `string` — as the same body is as a\n  // request body (`typePickedRequestBody`) and a field (#616 review: the\n  // `allOf` branch below read the merge alone, and the `string` was lost).\n  if (namesSeveralTypes(schema)) return { kind: 'typeRef' };\n  if (schema.allOf && classifyInlineSchema(schema) === 'allOf') {\n    const reading = readInlineAllOf(schema.allOf, schema, componentSchemas);\n    if (reading === 'reference') return { kind: 'reference' };\n    if (reading === 'unwrapped') return { kind: 'unwrapped', member: unwrappedAllOfMember(schema) };\n    return { kind: 'merged' };\n  }\n  const array = arraySchemaOf(schema);\n  if (array?.items) return { kind: 'array', items: array.items };\n  return { kind: 'typeRef' };\n}\n\n/**\n * Whether classification types a body as the bare `unknown` — the reading\n * `classifyAndExtractResponse` makes, without making it: a `$ref` is a\n * reference, typed as what it names — unknown exactly when it names a\n * primitive component that declares no type, or an alias of one\n * (`referenceTypesAsUnknown`; #569: `{ $ref: Anything }` beside `Anything:\n * { description }` is `unknown`, as the same schema inline is); the body is\n * folded as classification folds it (`foldSiblingProperties`, without the\n * warning it then issues); a list envelope and a single-resource wrapper\n * are typed; and what is left takes `extractDirectResource`'s own dispatch\n * (`directResourceReading`): an object, an `allOf` read as a merge, and an\n * array are typed, an `allOf` read as a reference is its `$ref` member\n * (`referenceTypesAsUnknown` again), a lone `allOf` member is read as the\n * member exactly as `extractDirectResource` recurses into it, and a\n * `typeRef` reading is typed by `schemaToTypeRef` and is `unknown` exactly\n * when `typesAsUnknown` holds. The one answer a reader that must know\n * before any body is read asks (`bodyIsTyped`, choosing the primary\n * response), so no shape is typed by classification and unknown to it, or\n * the reverse — `type: ['array']` with items is an array to both.\n */\nexport function bodyTypesAsUnknown(schema: SchemaObject, componentSchemas?: Record<string, SchemaObject>): boolean {\n  if (schema.$ref) return referenceTypesAsUnknown(schema);\n  const folded = foldSiblingProperties(schema);\n  if (detectListEnvelope(folded, componentSchemas).isEnvelope || isSingleResourceWrapper(folded)) return false;\n  return directResourceTypesAsUnknown(folded, componentSchemas);\n}\n\n/**\n * `bodyTypesAsUnknown` from `extractDirectResource`'s dispatch on, where its\n * recursion into a lone `allOf` member lands. A `reference` reading is typed\n * by `schemaToTypeRef` as its `$ref` member, so it is unknown exactly when\n * that reference is (`referenceTypesAsUnknown`; #569).\n */\nfunction directResourceTypesAsUnknown(schema: SchemaObject, componentSchemas?: Record<string, SchemaObject>): boolean {\n  const reading = directResourceReading(schema, componentSchemas);\n  if (reading.kind === 'unwrapped') return directResourceTypesAsUnknown(reading.member, componentSchemas);\n  if (reading.kind === 'reference') return referenceTypesAsUnknown(schema);\n  return reading.kind === 'typeRef' && typesAsUnknown(schema);\n}\n\n/**\n * `wrapper` is the single-member `allOf` wrapper the body was unwrapped\n * from, when it was (the `'unwrapped'` reading below): the schema the\n * document wrote for the body, whose `description` and link the type built\n * from the member takes, as `schemaToTypeRef` gives the same wrapper on a\n * field or a parameter (`withWrapperDocs`). It reaches only the one site\n * that types the member itself, the fall-through at the end, so an inline\n * enum body under the wrapper lifts with the wrapper's text; a model built\n * from an object member keeps the member's own `description`, as a field's\n * does. Through nested wrappers the outermost text wins, then the next, then\n * the member's own: each level composes its own wrapper with the one handed\n * down before passing it on.\n */\nfunction extractDirectResource(\n  schema: SchemaObject,\n  contextName: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  settle?: ItemSettlement,\n  wrapper?: SchemaObject,\n): ResponseExtractionResult {\n  const inlineModels: Model[] = [];\n  const reading = directResourceReading(schema, componentSchemas);\n\n  // Direct object with properties (with or without explicit type: 'object').\n  // An empty `properties: {}` beside a composition that types the schema is\n  // not the body's object — the fold leaves it as written\n  // (`hasFoldableProperties`) and the `allOf` or `oneOf` branch below reads\n  // it, as `{ allOf: [Pet] }` alone is read — so a body declaring no field of\n  // its own never becomes an empty model that drops the composition.\n  if (reading.kind === 'object') {\n    const modelName = deriveModelName(schema, contextName);\n    inlineModels.push(...extractInlineModel(modelName, schema, componentSchemas));\n    return {\n      response: { kind: 'model', name: modelName },\n      inlineModels,\n      isPaginated: false,\n    };\n  }\n\n  // allOf — read the one way every site reads an inline `allOf`\n  // (`readInlineAllOf`), when the `allOf` is what types the body\n  // (`classifyInlineSchema`; an `allOf` of bare limits leaves the body to\n  // its own keywords below). A single `$ref` member with nothing beside it\n  // that adds to the component is that component, and nothing is minted —\n  // as a field of the same schema is typed (workos/oagen#307: the body was\n  // a copy of the component under its own name); a ref no component answers\n  // is that reference too. A second `$ref`, or a `required` beside the\n  // `$ref`, makes the body the merge below, as it makes a field (every\n  // component's properties and every `required` kept). A lone member with\n  // nothing added to it is the body itself, carrying the wrapper's limits,\n  // flag and link (`unwrappedAllOfMember`), read by the branches of this\n  // function as if written in its place, and the type built from it takes\n  // the wrapper's text and link too (`wrapper`, see above); a `required`\n  // beside a lone object member makes the body the merge too, so `name`\n  // stays required. Every other\n  // `allOf` is merged into a single model through `mergeAllOfMembers`: $ref\n  // branches are resolved against component schemas so the referenced\n  // model's fields are merged rather than silently dropped, and the inline\n  // object variants of a `oneOf`/`anyOf` member contribute their fields as\n  // optional ones (workos/oagen#283), as the same schema's component model\n  // has them. Earlier members win on a shared name there, and the fold\n  // places the body's own properties first, so an own `kind` enum beside a\n  // member's plain `kind` stays the enum here as it does in a field or an\n  // array's items.\n  if (reading.kind === 'reference') {\n    return { response: schemaToTypeRef(schema, contextName), inlineModels, isPaginated: false };\n  }\n  if (reading.kind === 'unwrapped') {\n    const outer = wrapper ? withWrapperDocs(schema, wrapper) : schema;\n    return extractDirectResource(reading.member, contextName, componentSchemas, settle, outer);\n  }\n  if (reading.kind === 'merged') {\n    const merged = mergeAllOfMembers(schema, componentSchemas);\n    const mergedRefFields = merged.resolvedRefs.length > 0;\n\n    // An unresolvable $ref branch (no component schema map) would drop the\n    // referenced model's fields entirely — prefer the referenced model as\n    // the response type over a merge that silently guts it.\n    if (merged.unresolvedRefs.length === 1 && !mergedRefFields) {\n      return {\n        response: schemaToTypeRef({ $ref: merged.unresolvedRefs[0] }, contextName),\n        inlineModels,\n        isPaginated: false,\n      };\n    }\n\n    if (merged.properties.length > 0) {\n      // The rebuilt schema carries the wrapper's limits, conjoined with its\n      // inline members', so it still declares what an instance must satisfy,\n      // and the wrapper layer's text, link, `deprecated` flag and `x-*` keys\n      // — the wrapper's own, else an annotating member's — as a component\n      // `allOf` model and a field's merge carry them; a member's stay on\n      // that member (a `$ref` member's on its component). So the model built\n      // below is described as the same schema's request-body model is\n      // (#604: the text alone was left off, and `CreatePetResponse` had none\n      // while `CreatePetRequest` did).\n      const rebuilt = mergedObjectSchema(merged);\n      // Fields merged from a $ref carry the referenced model's const\n      // discriminant (e.g. object: 'magic_auth'); deriving the name from it\n      // would collide with the component model, so keep the context name.\n      // A const only variants declare holds on a branch: it names nothing.\n      const branchOnly = new Set(merged.properties.filter((p) => p.conditional).map((p) => p.name));\n      const modelName = mergedRefFields ? toPascalCase(contextName) : deriveModelName(rebuilt, contextName, branchOnly);\n      inlineModels.push(...extractInlineModel(modelName, rebuilt, componentSchemas));\n      return {\n        response: { kind: 'model', name: modelName },\n        inlineModels,\n        isPaginated: false,\n      };\n    }\n  }\n\n  // Array — `type: 'array'` or, since JSON Schema does not require `type`\n  // beside `items`, bare `items`, under a nullable wrapper of any spelling\n  // (`type: ['array', 'null']`, OAS 3.0 `nullable: true`, `oneOf`/`anyOf`\n  // with a `null` variant, with or without `items` beside it) or none:\n  // `arraySchemaOf`, which unwraps as `schemaToTypeRef` does and then asks\n  // `isArraySchema`, the one test every site makes. The items, whatever\n  // their shape, are typed and materialized as `<Operation>Item` under no\n  // parent (`typeInlineItems`) — a `$ref` stays the reference, a plain\n  // object is `<Operation>Item`, a union's inline object variants take the\n  // union's names from it — with the nullable wrapper `schemaToTypeRef`\n  // would give the array. Read before the `oneOf` branch below, which\n  // would otherwise materialize a nullable array's items a second time\n  // under the response's own name.\n  if (reading.kind === 'array') {\n    const typed = typeInlineItems(\n      reading.items,\n      contextName.replace(/Response$/, '') + 'Item',\n      componentSchemas,\n      settle,\n    );\n    return {\n      // The array carries the body's own limits, as `schemaToTypeRef` would\n      // have it carry them (#545); the items carry theirs.\n      response: nullableIf(schema, withSchemaConstraints({ kind: 'array', items: typed.itemType }, schema)),\n      inlineModels: [...inlineModels, ...typed.inlineModels],\n      isPaginated: false,\n    };\n  }\n\n  // oneOf — delegate to schemaToTypeRef (returns union) and materialize the\n  // inline object variants through the field extractor, as a field of this\n  // name under no parent: it names them exactly as the union below references\n  // them (`nameInlineVariants` from the context name — `GetThingResponse`,\n  // `GetThingResponseWithSide`, `SquareGetThingResponse`), covers a nullable\n  // (`type: ['object', 'null']`) or multi-type variant that a plain\n  // `type === 'object'` test would skip, and recurses into everything nested\n  // under each variant, so the response never references a model the parser\n  // did not create.\n  if (schema.oneOf) {\n    extractInlineModelsFromProperties(\n      { properties: { [contextName]: schema } },\n      inlineModels,\n      undefined,\n      componentSchemas,\n    );\n  }\n\n  // Anything else is typed by schemaToTypeRef (primitive, union, map, array\n  // of unions, nullable object, …). Such a TypeRef can still reach an inline\n  // model — a map whose values are an inline object (`additionalProperties`),\n  // an array whose items are a union of inline objects, a nullable\n  // `type: ['object', 'null']` object, a map of arrays of objects — so\n  // materialize them the way the oneOf branch does: as a field of this name\n  // under no parent, which names every nested model exactly as the TypeRef\n  // references it. The oneOf branch may already have pushed some of them, so\n  // dedupe by name.\n  const nested: Model[] = [];\n  extractInlineModelsFromProperties({ properties: { [contextName]: schema } }, nested, undefined, componentSchemas);\n  const known = new Set(inlineModels.map((m) => m.name));\n  for (const model of nested) {\n    if (known.has(model.name)) continue;\n    known.add(model.name);\n    inlineModels.push(model);\n  }\n  // The one site that types the unwrapped member itself: it carries the\n  // wrapper's text and link, as the type builder gives the same wrapper on\n  // a field (`withWrapperDocs`), so an inline enum lifted here documents\n  // itself by the wrapper. The models materialized above are built from the\n  // member as written.\n  return {\n    response: schemaToTypeRef(wrapper ? withWrapperDocs(schema, wrapper) : schema, contextName),\n    inlineModels,\n    isPaginated: false,\n  };\n}\n\n/**\n * Whether `schema` writes an empty `properties: {}` beside an `allOf`,\n * `oneOf` or `anyOf` that types it (`classifyInlineSchema`). Such a schema\n * declares no field of its own, so the object branch of a body path must\n * not claim it: the composition is read instead, as it is when the\n * `properties` keyword is absent. Shared by the response and request-body\n * paths.\n */\nexport function composedWithoutFields(schema: SchemaObject): boolean {\n  if (!schema.properties || Object.keys(schema.properties).length > 0) return false;\n  const kind = classifyInlineSchema(schema);\n  return kind === 'allOf' || kind === 'union';\n}\n\n/**\n * Wrap `ref` in `nullable` when `schemaToTypeRef` would wrap the schema's\n * own type (`declaresNull`). For the places the response path builds an\n * array TypeRef itself instead of delegating.\n */\nfunction nullableIf(schema: SchemaObject, ref: TypeRef): TypeRef {\n  return declaresNull(schema) ? { kind: 'nullable', inner: ref } : ref;\n}\n\n/**\n * The name a response object takes from a string `const` it declares\n * (`object: 'note'` names it `Note`), else `fallback`. A property in\n * `branchOnly` holds on one branch of the body, not on every instance (only\n * an inline `allOf`'s `oneOf`/`anyOf` variants declare it:\n * `MergedProperty.conditional`), so its const names nothing\n * (workos/oagen#396: one variant's `kind: cat` named the body `Cat`, and a\n * `kind: dog` added to another variant renamed it); it still counts toward\n * the list envelope, which is the whole body's shape.\n */\nfunction deriveModelName(schema: SchemaObject, fallback: string, branchOnly?: ReadonlySet<string>): string {\n  if (!schema.properties) return toPascalCase(fallback);\n  // A list envelope's const (`object: 'list'`) names the envelope's kind, which\n  // every envelope of the API shares, not what it lists (workos/oagen#418).\n  if (detectListEnvelope(schema).isEnvelope) return toPascalCase(fallback);\n\n  // Prefer well-known discriminant properties for backward compatibility\n  const preferred = ['object', 'type'];\n  for (const name of preferred) {\n    const field = branchOnly?.has(name) ? undefined : schema.properties[name];\n    if (field && field.const && typeof field.const === 'string') {\n      return toPascalCase(field.const);\n    }\n  }\n\n  // Fall back to any property with a const string value\n  for (const [name, field] of Object.entries(schema.properties)) {\n    if (!branchOnly?.has(name) && field && field.const && typeof field.const === 'string') {\n      return toPascalCase(field.const);\n    }\n  }\n\n  return toPascalCase(fallback);\n}\n\n/**\n * Materialise an inline response object (and every nested inline object\n * under it) as models. `componentSchemas` only feeds `buildFieldFromSchema`,\n * so a response field that `$ref`s a component takes the component's\n * `example`/`examples` exactly as a request-body or component-model field\n * does; nested models get the same map so the fallback reaches every level.\n */\nfunction extractInlineModel(\n  name: string,\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): Model[] {\n  const requiredSet = new Set(schema.required ?? []);\n  const fields: Field[] = [];\n  const properties = schema.properties ?? {};\n  const nestedModels: Model[] = [];\n\n  const siblings = collectProperties(schema);\n  for (const [fieldName, fieldSchema] of Object.entries(properties)) {\n    if (!fieldSchema) continue;\n    fields.push(buildFieldFromSchema(fieldName, fieldSchema, name, requiredSet, componentSchemas, siblings));\n  }\n\n  // Every nested inline model a field references — an inline object, array\n  // items, map values, an `allOf` merge or `$ref` augmentation, every\n  // `oneOf`/`anyOf` variant (numbered, const-prefixed, nullable, multi-type,\n  // with `<Variant>Item` members), with sibling-aware item/value names —\n  // comes from the same extractor that materializes them for component\n  // schemas and request bodies. `buildFieldFromSchema` above named the\n  // references through `schemaToTypeRef`; this names the models the same way,\n  // so they agree by construction instead of through a response-local copy of\n  // the rules.\n  extractInlineModelsFromProperties(schema, nestedModels, name, componentSchemas);\n\n  return [\n    {\n      name,\n      description: schema.description,\n      ...externalDocsEntry(schema.externalDocs),\n      fields,\n      ...deprecatedEntry(schema),\n      ...constraintsEntry(schema),\n      ...schemaExtensionsEntry(schema),\n    },\n    ...nestedModels,\n  ];\n}\n","/**\n * Resolution of Reference Objects: `{ $ref: '#/components/<section>/<name>' }`\n * written where OpenAPI allows one in place of a Parameter, Request Body,\n * Response, Header, Example or Security Scheme Object. The bundler never inlines internal refs\n * (`dereference: false`), so each reaches the parser as written and is\n * followed here, through one walk, with one reading of the text written\n * beside the `$ref`.\n *\n * OAS 3.1 (§4.8.23) gives a Reference Object a `summary` and a `description`\n * that override the referenced component's; OAS 3.0 gives it no field but\n * `$ref`, so there anything written beside one is ignored\n * (`siblingDocsMode`). Each ref in a chain overrides what it points at, so\n * the outermost text with non-whitespace content wins over an inner ref's\n * and over the component's own; a blank sibling is no text and falls\n * through, as a blank `summary` on an operation falls through to its path\n * item's. `summary` is applied only where the referenced object type has one\n * — an Example Object; OpenAPI says it has no effect elsewhere — so a\n * Parameter, Request Body, Response or Header never gains a `summary` key\n * (`REFERENCE_DOC_FIELDS`). Neither version lets a Reference Object carry\n * anything else — \"any properties added SHALL be ignored\" — so a `content`\n * or `headers` written beside a response `$ref`, or a `value` beside an\n * example's, is never read: a ref that resolves reads the component, and\n * one that fails is returned with nothing but its `$ref` and the text the\n * rule above keeps (#562).\n *\n * A Path Item's `$ref` is not a Reference Object: OpenAPI leaves a field\n * present on both sides undefined, and `resolvePathItemRef` takes the\n * referenced item whole. A Schema Object's `$ref` is JSON Schema's, whose\n * siblings the field extractor reads (`Field.description`).\n */\nimport { componentRefEntry } from './path-item-refs.js';\n\n/** Whether text written beside a `$ref` overrides the referenced component's (OAS 3.1) or is ignored (OAS 3.0). */\nexport type SiblingDocs = 'override' | 'ignore';\n\n/** `'ignore'` for an OAS 3.0 document, where nothing beside a `$ref` is read; `'override'` for 3.1 and for a version not recognised. */\nexport function siblingDocsMode(openapiVersion: string | undefined): SiblingDocs {\n  return openapiVersion?.startsWith('3.0') ? 'ignore' : 'override';\n}\n\n/** The `components` sections a Reference Object may point into. */\nexport type ReferenceSection =\n  | 'parameters'\n  | 'requestBodies'\n  | 'responses'\n  | 'headers'\n  | 'examples'\n  | 'securitySchemes';\n\n/** A Reference Object as written, with the documentation OAS 3.1 lets it carry beside the `$ref`. */\nexport interface ReferenceObject {\n  $ref: string;\n  summary?: string;\n  description?: string;\n}\n\ntype ReferenceDocField = 'summary' | 'description';\n\n/** The documentation a Reference Object overrides on each object type: `description` everywhere, `summary` only where the type has one. */\nconst REFERENCE_DOC_FIELDS: Record<ReferenceSection, readonly ReferenceDocField[]> = {\n  parameters: ['description'],\n  requestBodies: ['description'],\n  responses: ['description'],\n  headers: ['description'],\n  examples: ['summary', 'description'],\n  securitySchemes: ['description'],\n};\n\n/**\n * How a walk ended: at the component (or at an inline object that was no\n * reference), at a ref already seen on the chain, at a ref nothing under the\n * section answers (a pointer into another section included, since the whole\n * pointer is matched), or at a `$ref` that is not a string.\n */\nexport type ReferenceOutcome = 'resolved' | 'circular' | 'unresolved' | 'malformed';\n\nexport interface FollowedReference<T> {\n  outcome: ReferenceOutcome;\n  /**\n   * The object the walk ended on, with the text kept from the refs along the\n   * chain applied over its own: the component for `resolved`, else the\n   * Reference Object the walk stopped at, reduced to what one may carry —\n   * its `$ref` and, under `'override'`, that text. Every other key written\n   * beside the `$ref` is left out (#562), and under `'ignore'`, where no\n   * ref's text is read, so is the text (#444). The object itself when\n   * nothing was kept or left out, so an inline object or an undescribed ref\n   * keeps its identity. Typed as the caller expects; for a failure it is the\n   * ref.\n   */\n  value: T;\n  /** The `$ref` the walk stopped at, for a failure (`String()` of a malformed one); absent when resolved. */\n  ref?: string;\n  /**\n   * For `unresolved` only: the entry the section does hold under the ref's\n   * name when it is no object — `null`, a string, a number, a boolean or an\n   * array — and so answers nothing, with the name decoded, so a reader can\n   * report it as the malformed entry it is rather than as missing (#617).\n   * Absent when the section holds nothing under that name at all.\n   */\n  found?: { name: string; value: unknown };\n}\n\n/**\n * Follow `raw` through `#/components/<section>/…` refs to the object it\n * denotes, keeping the text written beside each ref by the rule above, and\n * say how the walk ended. What a failure means — fail the parse, drop the\n * node, read the ref as written — is each caller's own; the walk itself\n * never reports. A `$ref` key holding `undefined` is no reference, and a\n * component that is not an object — an array included — answers nothing:\n * the walk ends `unresolved` on the ref, handing the entry back as `found`.\n */\nexport function followReference<T extends object>(\n  raw: T | ReferenceObject,\n  section: ReferenceSection,\n  components: Record<string, Record<string, unknown>> | undefined,\n  siblings: SiblingDocs,\n): FollowedReference<T> {\n  const fields = REFERENCE_DOC_FIELDS[section];\n  const seen = new Set<string>();\n  const kept: Partial<Record<ReferenceDocField, string>> = {};\n  let current: object = raw;\n  const ended = (\n    outcome: ReferenceOutcome,\n    ref?: string,\n    found?: FollowedReference<T>['found'],\n  ): FollowedReference<T> => {\n    let value: object;\n    if (outcome === 'resolved') {\n      value = Object.keys(kept).length === 0 ? current : { ...current, ...kept };\n    } else {\n      // A failed walk stops at a Reference Object, which carries nothing but\n      // its `$ref` and the text the rule above keeps: the text beside it is\n      // read under 'override' and, as every other ref's, ignored under\n      // 'ignore' (#444), and every other key written beside the `$ref` — a\n      // response's `content` or `headers`, an example's `value` — is left\n      // out, as OpenAPI says of any property added to a Reference Object\n      // (#562), so no reader takes it for the object's own. The ref itself\n      // when that leaves it as written, so an undescribed ref keeps its\n      // identity.\n      const reference: Record<string, unknown> = { $ref: (current as { $ref: unknown }).$ref, ...kept };\n      value = holdsExactly(current, reference) ? current : reference;\n    }\n    return {\n      outcome,\n      value: value as T,\n      ...(ref !== undefined ? { ref } : {}),\n      ...(found !== undefined ? { found } : {}),\n    };\n  };\n\n  while ('$ref' in current) {\n    const ref = (current as { $ref: unknown }).$ref;\n    if (ref === undefined) break;\n    // The text beside this ref is read before the walk can end on it, so a\n    // malformed ref's own travels with it as a dangling one's does.\n    if (siblings === 'override') {\n      for (const field of fields) {\n        const text = (current as Partial<Record<ReferenceDocField, unknown>>)[field];\n        if (kept[field] === undefined && typeof text === 'string' && text.trim() !== '') kept[field] = text;\n      }\n    }\n    if (typeof ref !== 'string') return ended('malformed', String(ref));\n    if (seen.has(ref)) return ended('circular', ref);\n    seen.add(ref);\n    const entry = componentRefEntry(ref, section, components);\n    if (entry === undefined) return ended('unresolved', ref);\n    // The section holds the name, but no object: nothing to walk into. The\n    // entry travels with the outcome so a reader can say what it found.\n    if (!isRecord(entry.value)) return ended('unresolved', ref, entry);\n    current = entry.value;\n  }\n  return ended('resolved');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Whether `object` holds exactly `entries`, key for key and value for value, so it can stand for them as it is. */\nfunction holdsExactly(object: object, entries: Record<string, unknown>): boolean {\n  const own = object as Record<string, unknown>;\n  const keys = Object.keys(own);\n  return (\n    keys.length === Object.keys(entries).length && keys.every((key) => key in entries && own[key] === entries[key])\n  );\n}\n","/**\n * Resolution of Reference Objects into `components/responses`.\n *\n * The bundler never inlines internal refs (`dereference: false`), so a\n * response written as `{ $ref: '#/components/responses/Problem' }` reaches\n * extraction as a Reference Object whose `headers` and `content` are\n * nowhere to be read. This module is self-contained so every response path\n * — fallback, explicit status code, webhook — can resolve the same way.\n */\n\nimport { followReference, type ReferenceObject, type SiblingDocs } from './reference-objects.js';\n\nexport type { ReferenceObject };\n\n/**\n * Resolve a raw response to a concrete Response Object, following `$ref`\n * chains into `components/responses` (`followReference`, the walk every\n * Reference Object takes). The text written beside a ref follows the one\n * rule stated there: in an OAS 3.1 document the outermost sibling\n * `description` with content wins over an inner ref's and over the\n * component's; under `siblingDescriptions: 'ignore'` (OAS 3.0, where\n * properties beside a `$ref` are ignored) the component's own is kept. A ref\n * nothing under `components/responses` answers (a pointer into another\n * section, or one a bundler wrote to the first place it inlined a repeated\n * external ref, `#/paths/~1pets/get/responses/200`) is warned about and\n * returned as the Reference Object it is: its `$ref` and its sibling\n * `description`, kept under `'override'` and, as beside every ref, ignored\n * under `'ignore'` — never a `content` or `headers` written beside the\n * `$ref`, which OpenAPI says to ignore there as it is ignored beside a ref\n * that resolves (#562), so the response has no body and no headers, as the\n * warning says. So is a `$ref` that is not a string (`{ $ref: 42 }`), direct\n * or at the end of a chain, with a warning naming the value as JSON — `42`,\n * `true`, `null`, `[]`, `[\"#/components/responses/NotFound\"]`,\n * `{\"name\":\"x\"}` — so an array or an object never reads as nothing or as the\n * string it is not, as the webhook reader warns about the same ref (#563).\n * A document that parsed before any response ref was resolved still parses.\n * An entry that is no object at all — `200: \"oops\"`, `null`, `7` — never\n * reaches here: every reader checks `isResponseEntry` first and skips it.\n * A chain that ends on a `components/responses` entry that is no object —\n * `Gone: []`, `\"oops\"`, `null`, `7`, `true` — is that same malformed entry\n * behind a pointer (`followed.found`), so it goes through `isResponseEntry`\n * here: warned about naming the component and the site (`components/responses/Gone\n * (the 200 response of listPets) is not a Response Object ([]); skipping\n * it.`) under `'report'`, silently under `'silent'`, and `undefined` is\n * returned for the caller to skip the entry as it skips the inline one, so\n * the two spellings of one malformed response give one IR (#617). Only a\n * circular chain throws, since no reader could resolve it. Under\n * `onFailure: 'silent'` no failure is reported and a bad ref is returned\n * the same way; that is for a reader that only pre-computes names, leaving\n * the report to the operation that declares the ref.\n */\nexport function resolveResponseRef<T extends object>(\n  raw: T | ReferenceObject,\n  componentResponses: Record<string, Record<string, unknown>> | undefined,\n  context: string,\n  siblingDescriptions: SiblingDocs = 'override',\n  onFailure: 'report' | 'silent' = 'report',\n): T | undefined {\n  const followed = followReference<T>(raw, 'responses', componentResponses, siblingDescriptions);\n  if (followed.outcome === 'unresolved' && followed.found !== undefined) {\n    const { name, value } = followed.found;\n    const site = onFailure === 'report' ? `components/responses/${name} (the ${context})` : undefined;\n    if (!isResponseEntry(value, site)) return undefined;\n  }\n  if (onFailure === 'report') {\n    if (followed.outcome === 'circular') {\n      throw new Error(`Circular response $ref chain starting at \"${followed.ref}\" in ${context}.`);\n    }\n    // `silent` is for a reader that only pre-computes names from the\n    // component map (`resolvePathModelBaseNames`): the operation that\n    // declares the ref reports the problem once when it reads it, so this\n    // reader neither warns nor throws and returns the ref as written.\n    if (followed.outcome === 'unresolved') {\n      console.warn(\n        `[oagen] Warning: Unresolved response $ref \"${followed.ref}\" in ${context}: no matching entry under components/responses — reading the response as written, without a body or headers`,\n      );\n    }\n    // A `$ref` that is not a string ends the walk as `malformed` and is read\n    // as written like a ref nothing answers; it is warned about the same\n    // way, naming the value, as the webhook reader warns about it (#563).\n    // The value is rendered as JSON, read off the object the walk stopped at\n    // (`followed.ref` is `String()` of it, which prints `[]` as nothing and\n    // `[\"#/components/responses/NotFound\"]` as the string it is not).\n    if (followed.outcome === 'malformed') {\n      const { $ref } = followed.value as { $ref?: unknown };\n      console.warn(\n        `[oagen] Warning: Malformed response $ref ${JSON.stringify($ref)} in ${context}: a $ref must be a string — reading the response as written, without a body or headers`,\n      );\n    }\n  }\n  return followed.value;\n}\n\n/**\n * Whether a Responses Object entry is something a reader can read at all:\n * a Response Object or a Reference Object, which are objects. An entry\n * written as a string, a number, a boolean, `null` or an array — `200:\n * \"oops\"`, `200: null`, `200: 7`, `200: true`, `200: []` — is neither, so\n * nothing could be read from it, not even a `$ref`: it is skipped and the\n * operation is read from its other entries, rather than failing the parse\n * with a `TypeError` that names neither the operation nor the key (#617).\n * The reader that reports — the operation's (`extractResponses`) or the\n * webhook's (`extractWebhookResponses`) — passes the site and warns once,\n * naming the value as JSON: `200 response of listPets is not a Response\n * Object (null); skipping it.` A reader that only pre-computes names\n * passes no site and skips the entry silently, leaving the report to the\n * operation that declares it, as `resolveResponseRef` does under\n * `'silent'`. A `$ref` whose chain ends on a `components/responses` entry\n * that is no object is put through the same check by the resolvers\n * (`resolveResponseRef`, the webhook's `resolveResponseDescription`), with\n * the component named in the site.\n */\nexport function isResponseEntry(raw: unknown, site?: string): raw is Record<string, unknown> {\n  if (typeof raw === 'object' && raw !== null && !Array.isArray(raw)) return true;\n  if (site !== undefined) {\n    console.warn(`[oagen] Warning: ${site} is not a Response Object (${JSON.stringify(raw)}); skipping it.`);\n  }\n  return false;\n}\n\n/**\n * Whether an operation's or a webhook's `responses` is a Responses Object\n * at all: an object. One written as a string, a number, a boolean, `null`\n * or an array — `responses: \"oops\"` — declares no response under any key:\n * it is warned about once, naming the operation or webhook and the value as\n * JSON (`responses of listPets is not a Responses Object (\"oops\"); reading\n * no response from it.`), and read as absent, never as the map of its\n * characters' or elements' indexes, which are no status codes (#617).\n */\nexport function isResponsesObject(responses: unknown, label: string): responses is Record<string, unknown> {\n  if (typeof responses === 'object' && responses !== null && !Array.isArray(responses)) return true;\n  console.warn(\n    `[oagen] Warning: responses of ${label} is not a Responses Object (${JSON.stringify(responses)}); reading no response from it.`,\n  );\n  return false;\n}\n","import type { SecurityRequirementSet } from '../ir/types.js';\n\n/**\n * An OpenAPI security requirement list as written in the document: each\n * object is one alternative whose keys are scheme names and whose values are\n * the scopes that scheme needs.\n */\nexport type RawSecurityRequirements = Array<Record<string, string[] | undefined> | null | undefined>;\n\n/**\n * Convert a document- or operation-level `security` list into the IR shape,\n * preserving what the list says rather than flattening it:\n *\n * - absent (or not a list) → `undefined`: nothing declared here.\n * - `[]` → `[]`: no authentication required.\n * - `[{ a: [] }, { b: [] }]` → `[[a], [b]]`: either scheme suffices.\n * - `[{ a: [], b: [] }]` → `[[a, b]]`: both schemes are required together.\n * - `[{ a: [] }, {}]` → `[[a], []]`: the empty set is an anonymous alternative,\n *   which is how a document marks authentication optional.\n *\n * An entry that is not an object (`null`, say) is not a requirement object.\n * Reading it as `{}` would declare an anonymous alternative and make the\n * operation look open, so it is dropped with an `[oagen] Warning:` naming\n * `context` (the operation, or the document). A non-empty list left with no\n * valid entry is treated as undeclared (`undefined`) rather than as `[]`:\n * the document never said \"no authentication\", so the operation keeps\n * inheriting the default.\n *\n * The previous flattening collapsed the alternatives onto one list and turned\n * `[]` into `undefined`, so \"no auth\" read the same as \"use the default\" and\n * \"either of\" the same as \"all of\" (#182).\n */\nexport function extractSecurityRequirements(\n  security: RawSecurityRequirements | undefined,\n  context: string,\n): SecurityRequirementSet[] | undefined {\n  if (!Array.isArray(security)) return undefined;\n\n  const sets: SecurityRequirementSet[] = [];\n  for (const entry of security) {\n    if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {\n      console.warn(\n        `[oagen] Warning: Ignoring security requirement ${JSON.stringify(entry)} on ${context} — not a requirement object`,\n      );\n      continue;\n    }\n    sets.push(\n      Object.entries(entry).map(([schemeName, scopes]) => ({\n        schemeName,\n        scopes: Array.isArray(scopes) ? scopes : [],\n      })),\n    );\n  }\n  if (security.length > 0 && sets.length === 0) {\n    console.warn(`[oagen] Warning: No valid security requirement on ${context}; treating security as undeclared`);\n    return undefined;\n  }\n  return sets;\n}\n","import type { ServerEntry, ServerVariable } from '../ir/types.js';\nimport { resolveServerUrl } from '../ir/server-url.js';\n\n/** A `servers` entry as written in the OpenAPI document; narrowed field by field. */\nexport interface RawServerObject {\n  url?: unknown;\n  description?: unknown;\n  variables?: unknown;\n}\n\n/** What the document's `servers` list contributes to `ApiSpec`. */\nexport interface ExtractedServers {\n  /** One entry per server that has a URL, in document order; `undefined` when there is none. */\n  servers: ServerEntry[] | undefined;\n  /** The first server's URL with its variables' defaults filled in, or `''` without a server. */\n  baseUrl: string;\n}\n\n/**\n * Convert the document's `servers` list into `ApiSpec.servers` and\n * `ApiSpec.baseUrl`.\n *\n * `ServerEntry.url` stays as written — placeholders included — so an emitter\n * can offer the variables; `baseUrl` is `servers[0]` resolved with\n * `resolveServerUrl`, which fills each `{name}` with the variable's `default`\n * (OpenAPI requires one). The list itself is normalised by\n * `extractServerList`, the same way a Path Item's or an Operation's is.\n *\n * A document that writes OpenAPI's default server out (`servers: [{ url:\n * '/' }]`) is carried as written — `servers: [{ url: '/' }]`, `baseUrl: '/'`\n * — while one that declares none has `servers` absent and `baseUrl: ''`. The\n * two mean the same thing, and everywhere server lists are compared they are\n * read as one: `isDefaultServerList` for `Operation.servers`,\n * `serversOrDefault` and `baseUrlBeyondDefault` in the differ, all in\n * `ir/server-url.ts` (#291).\n */\nexport function extractServers(rawServers: unknown): ExtractedServers {\n  const servers = extractServerList(rawServers, 'the document');\n  const baseUrl = servers ? resolveServerUrl(servers[0]).url : '';\n  return { servers, baseUrl };\n}\n\n/**\n * Normalise a `servers` list — the document's, a Path Item's or an\n * Operation's — into `ServerEntry[]`, or `undefined` when it declares nothing\n * usable. All three levels go through here so they come out identical: the\n * same handling of non-object entries, blank URLs, `variables` and\n * prototype-named keys, and the same warnings, each naming `context` (\"the\n * document\", \"path item /pets\", \"operation listPets\").\n *\n * A non-array, an empty list, and a list whose entries are all unusable (not\n * an object, no `url`, or an empty `url`) all yield `undefined`. OpenAPI gives\n * `servers: []` no meaning as an override — only the document-level default\n * of `/` is defined for an empty list — so at path and operation level\n * `undefined` means \"inherit\".\n *\n * Server variables are the same shape in OpenAPI 3.0 and 3.1. Every server is\n * checked, not only the first, because an emitter may resolve any of them,\n * and each problem is reported once with an `[oagen] Warning:`:\n *\n * - A variable without a usable `default` has no IR representation\n *   (`ServerVariable.default` is required) and is omitted; its placeholder\n *   stays in the URL.\n * - A placeholder that names no declared variable stays in the URL.\n * - A `default` outside the variable's `enum` is kept as written.\n *\n * A declared variable the URL never mentions is kept without comment; it is\n * harmless and an emitter may still expose it. `default` and `enum` entries\n * are strings; a number or boolean (YAML reads `default: 8443` as a number)\n * is carried as its text, anything else is ignored. An empty `enum`, which\n * the specification forbids, is treated as undeclared.\n */\nexport function extractServerList(rawServers: unknown, context: string): ServerEntry[] | undefined {\n  if (!Array.isArray(rawServers)) return undefined;\n  const servers: ServerEntry[] = [];\n  for (const raw of rawServers) {\n    const entry = buildServerEntry(raw, context);\n    if (entry) servers.push(entry);\n  }\n  return servers.length > 0 ? servers : undefined;\n}\n\nfunction buildServerEntry(raw: unknown, context: string): ServerEntry | undefined {\n  if (!isRecord(raw) || typeof raw.url !== 'string' || raw.url === '') return undefined;\n  const url = raw.url;\n  const entry: ServerEntry = { url, description: typeof raw.description === 'string' ? raw.description : undefined };\n\n  const declared = isRecord(raw.variables) ? raw.variables : {};\n  // Collected in a Map and materialized with Object.fromEntries, which defines\n  // own data properties: `variables[name] = …` on a plain object would set its\n  // prototype instead when the document names a variable `__proto__`. The\n  // result is still an ordinary object, so `Object.keys`, JSON and snapshots\n  // see nothing unusual.\n  const variables = new Map<string, ServerVariable>();\n  for (const [name, value] of Object.entries(declared)) {\n    const variable = buildServerVariable(url, context, name, value);\n    if (variable) variables.set(name, variable);\n  }\n  // Absent, not `undefined`, when the document declares none (or none usable).\n  if (variables.size > 0) entry.variables = Object.fromEntries(variables);\n\n  for (const name of resolveServerUrl(entry).unresolved) {\n    // A declared variable that was omitted above has already been reported.\n    if (Object.hasOwn(declared, name)) continue;\n    console.warn(\n      `[oagen] Warning: Server URL \"${url}\" on ${context} uses {${name}} but declares no such variable; the placeholder stays in the URL`,\n    );\n  }\n  return entry;\n}\n\nfunction buildServerVariable(url: string, context: string, name: string, raw: unknown): ServerVariable | undefined {\n  const declared: Record<string, unknown> = isRecord(raw) ? raw : {};\n  const defaultValue = scalarText(declared.default);\n  if (defaultValue === undefined) {\n    console.warn(\n      `[oagen] Warning: Server variable \"${name}\" of \"${url}\" on ${context} has no default (a string is required) and is omitted; its placeholder stays in the URL`,\n    );\n    return undefined;\n  }\n\n  const variable: ServerVariable = { default: defaultValue };\n  const enumValues = Array.isArray(declared.enum)\n    ? declared.enum.map(scalarText).filter((value): value is string => value !== undefined)\n    : [];\n  if (enumValues.length > 0) {\n    variable.enum = enumValues;\n    if (!enumValues.includes(defaultValue)) {\n      console.warn(\n        `[oagen] Warning: Server variable \"${name}\" of \"${url}\" on ${context} defaults to \"${defaultValue}\", which is not one of its enum values (${enumValues.join(', ')}); kept as written`,\n      );\n    }\n  }\n  if (typeof declared.description === 'string') variable.description = declared.description;\n  return variable;\n}\n\n/** A string as itself; a number or boolean as its text; anything else is not a value. */\nfunction scalarText(value: unknown): string | undefined {\n  if (typeof value === 'string') return value;\n  if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n  return undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","import type { Field, Model, TypeRef } from '../ir/types.js';\nimport { assertNever, collectModelRefs, renameModelRefs, renameTypeRefModels } from '../ir/types.js';\nimport {\n  deprecatedFoldWarning,\n  fieldPropertiesAdmit,\n  fieldPropertiesKey,\n  looserFields,\n  modelPropertiesAdmit,\n  modelPropertiesKey,\n  ownerFlagAdmits,\n  type InlineModelBundle,\n} from './inline-models.js';\nimport { enumShapeKey, enumValueShapeKey, enumValuesOf } from './enum-members.js';\nimport { unionRulesKey, unionShapeKey } from './union-shape.js';\n\n/**\n * A list-envelope companion that was lifted to one or more inline models:\n * `field` is the envelope field (shared by identity with\n * `Operation.pagination.envelopeFields`), `models[0]` is the companion's own\n * model and the rest are models nested inside it. Every model is named under\n * the operation (`ListUsersListMetadata`); `bareNames[i]` is the name\n * `models[i]` would carry if it were named from its property alone\n * (`ListMetadata`).\n */\nexport interface EnvelopeCompanion {\n  field: Field;\n  models: Model[];\n  bareNames: string[];\n}\n\n/**\n * Decide the final name of every lifted companion model, across all list\n * operations at once, and return the models to merge into the IR.\n *\n * The same envelope recurs on every list endpoint of an API, so naming each\n * copy after its operation would mint one identical `ListMetadata` per\n * endpoint. But naming by property alone is only safe while the copies agree:\n * among inline models `mergeInlineResponseModels` keeps the largest model of\n * a name, so a `pagination` with three fields would absorb another endpoint's\n * two-field `pagination`, and one named like a `Pagination` component that\n * does not admit it would be moved to an operation-qualified name by the\n * merge rather than by this pass.\n *\n * So a companion takes its bare name only when that cannot change any other\n * type's shape:\n *\n * Copies are compared structurally — field names, requiredness and each\n * field's shape, with nested models resolved and inline enums compared by\n * value — never by name alone. A copy collapses onto a target shape only when\n * the target *admits* every value the copy can hold: the same fields with the\n * same types, where the target may be looser (a field the copy requires may be\n * optional on the target, a non-null copy field may be nullable there) but\n * never stricter. Widening a response type loses no data a reader can see;\n * narrowing it would promise fields the wire may omit.\n *\n * - When a component model of that name exists — compared after the parser's\n *   own renaming, so `PaginationDto` → `Pagination` is caught — the copies it\n *   admits collapse onto it (the component stays as written); the others keep\n *   their operation-qualified name.\n * - Otherwise the most common exact shape (first declared, on a tie) becomes\n *   the target: it and every copy it admits take the bare name; any other\n *   copy keeps its operation-qualified name.\n * - `deprecated` is part of a copy's shape among copies, so deprecation never\n *   reaches a live operation and never depends on document order: a copy\n *   folds onto another copy's definition only with the same flag, and while\n *   any live copy exists the target is chosen among the live copies, so a\n *   deprecated copy keeps its operation-qualified name\n *   (`ListLegacyUsersListMetadata`). Only when every copy is deprecated does\n *   a deprecated shape take the bare name. Beside a component, the\n *   companion's own flag is read as every declared model reads it\n *   (`ownerFlagAdmits`): a live component admits a deprecated companion —\n *   the envelope field keeps the flag the schema wrote (`Field.deprecated`),\n *   so nothing is lost — with the warning the merge passes give such a copy,\n *   and a deprecated component schema (`componentNames`) no companion of\n *   either flag, so a companion's name beside one is the same whichever flag\n *   it carries (#441); a deprecated model a component's field minted, standing\n *   in for a component, admits only a deprecated one. A model nested in the\n *   companion still folds only onto a component of the same flag; the\n *   model's own properties beside the flag — its limits (`minProperties`,\n *   `dependentRequired`, …), type parameters, whatever else the IR adds —\n *   are read as every component fold reads them (`modelPropertiesAdmit`):\n *   identical, so a companion declaring `minProperties: 1` never shares a\n *   component declaring `2`, nor the reverse; and every field is read in\n *   everything but its type as `fieldAdmits` reads it\n *   (`fieldPropertiesAdmit`): its own flag must agree in either direction,\n *   the target may be looser on requiredness only, and limits, default,\n *   access flags and every other property must be identical, since the\n *   target's definition is what every site reads after the fold — a\n *   companion whose `next` is deprecated, or allows 64 characters, never\n *   shares a component whose `next` is live, or allows 8, nor the other way\n *   round, flag or no flag on the root. Among copies the same properties are\n *   part of the shape (`modelPropertiesKey`, `fieldPropertiesKey`), so a\n *   copy that deprecates or limits itself or a field as the others do not\n *   keeps its own name.\n *\n * The comparison covers the companion's whole field type, so a `oneOf`\n * companion is judged on every variant, not just the first, and a copy folds\n * among copies only when its lifted models line up name for name with the\n * target's (same variants, same order); onto a component, only a companion\n * whose field references exactly its own lifted model can fold.\n *\n * Only the target's definition survives a collapse. The admitted copies'\n * models are dropped rather than handed to the merge pass, which keeps the\n * first model of a name and would let a stricter copy declared earlier\n * narrow the shared type for everyone; their field references are repointed\n * at the target's models instead.\n *\n * Enums declared inline in a companion stay operation-qualified, exactly like\n * enums declared inline in a parameter.\n *\n * `foldedOnto`, when given, receives every copy that folded onto another\n * companion's definition, keyed to that companion (a copy folded onto a\n * component is not recorded: nothing of it is emitted), so the caller can\n * tell which envelope fields a surviving companion's models serve\n * (`companionBundles`).\n *\n * `componentNames`, when given, names the component schemas among\n * `componentModels`; the rest are models a component's field minted, which\n * admit a deprecated companion while deprecated, where a component admits\n * none (`ownerFlagAdmits`, #441). Absent, every model there is a component.\n */\nexport function resolveEnvelopeCompanionNames(\n  companions: EnvelopeCompanion[],\n  componentModels?: Model[],\n  foldedOnto?: Map<EnvelopeCompanion, EnvelopeCompanion>,\n  componentNames?: ReadonlySet<string>,\n): Model[] {\n  const byBareName = new Map<string, EnvelopeCompanion[]>();\n  /** Copies folded onto another definition; their own models are not emitted. */\n  const folded = new Set<EnvelopeCompanion>();\n  for (const companion of companions) {\n    if (companion.models.length === 0) continue;\n    const bare = companion.bareNames[0];\n    const group = byBareName.get(bare) ?? [];\n    group.push(companion);\n    byBareName.set(bare, group);\n  }\n\n  const componentMap = new Map((componentModels ?? []).map((m) => [m.name, m]));\n  const localMap = (c: EnvelopeCompanion): Map<string, Model> => new Map(c.models.map((m) => [m.name, m]));\n  // A folded copy keeps its own field wrapper and only its references move, so\n  // whether the envelope field itself is nullable has no bearing on folding.\n  const unwrap = (t: TypeRef): TypeRef => (t.kind === 'nullable' ? t.inner : t);\n\n  for (const [bare, group] of byBareName) {\n    // What every copy is measured against: a field type, the map its model\n    // references resolve through (a component through the other components, a\n    // copy through its own models), and the names a folded copy's references\n    // are repointed to.\n    let folds: (c: EnvelopeCompanion) => boolean;\n    let finalNames: string[];\n    let owner: EnvelopeCompanion | undefined;\n\n    const component = componentMap.get(bare);\n    if (component) {\n      const targetType: TypeRef = { kind: 'model', name: component.name };\n      finalNames = [component.name];\n      const fieldMinted = componentNames !== undefined && !componentNames.has(bare);\n      folds = (c) => {\n        // Only a field that references exactly its own lifted model can be\n        // repointed at the component; a union of variants has nowhere to go.\n        const own = c.models[0]!;\n        const refs = collectModelRefs(c.field.type);\n        if (refs.length !== 1 || refs[0] !== own.name) return false;\n        // The component's flag is read as every declared model reads it\n        // (`ownerFlagAdmits`, #441): a deprecated component schema admits no\n        // companion, a deprecated field model only a deprecated one. A live\n        // one is compared with a deprecated companion as if the companion\n        // were live, since its envelope field keeps the flag. Its nested\n        // models are compared with theirs (`admits`), flag included.\n        if (!ownerFlagAdmits(component, own, fieldMinted)) return false;\n        const local = localMap(c);\n        if (own.deprecated && !component.deprecated) local.set(own.name, { ...own, deprecated: undefined });\n        return typeAdmits(targetType, componentMap, unwrap(c.field.type), local, new Set());\n      };\n    } else {\n      const counts = new Map<string, { n: number; first: EnvelopeCompanion }>();\n      // The bare name is owned by a live copy while one exists: a deprecated\n      // copy keeps its operation-qualified name rather than deprecating the\n      // name every live operation shares.\n      const live = group.filter((c) => !c.models[0].deprecated);\n      const candidates = live.length > 0 ? live : group;\n      for (const c of candidates) {\n        const key = `${fingerprintType(unwrap(c.field.type), localMap(c), new Set())}|${c.bareNames.join(',')}`;\n        const seen = counts.get(key);\n        if (seen) seen.n += 1;\n        else counts.set(key, { n: 1, first: c });\n      }\n      let best = { n: 0, first: candidates[0] };\n      for (const entry of counts.values()) if (entry.n > best.n) best = entry;\n      owner = best.first;\n      finalNames = owner.bareNames;\n      const ownerType = unwrap(owner.field.type);\n      const ownerMap = localMap(owner);\n      const ownerNames = owner.bareNames;\n      folds = (c) =>\n        c.bareNames.length === ownerNames.length &&\n        c.bareNames.every((name, i) => name === ownerNames[i]) &&\n        typeAdmits(ownerType, ownerMap, unwrap(c.field.type), localMap(c), new Set());\n    }\n\n    // Decide every copy before renaming any: renaming the target repoints its\n    // nested references to the bare names, which its map no longer resolves.\n    const collapsing = group.filter(folds);\n    for (const companion of collapsing) {\n      // A deprecated copy a live component admits is announced once per\n      // companion, as the merge passes announce one (`settleSharedNames`),\n      // with what the component, when looser, no longer holds the copy to.\n      if (component && !component.deprecated && companion.models[0]!.deprecated) {\n        console.warn(deprecatedFoldWarning(component.name, looserThanCompanion(component, componentMap, companion)));\n      }\n      renameCompanion(companion, finalNames);\n      if (companion !== owner) {\n        folded.add(companion);\n        if (owner) foldedOnto?.set(companion, owner);\n      }\n    }\n  }\n\n  return companions.filter((c) => !folded.has(c)).flatMap((c) => c.models);\n}\n\n/**\n * One site (`InlineModelBundle`) per companion that kept its models after\n * `resolveEnvelopeCompanionNames`: the envelope field that lifted it, plus\n * the envelope field of every copy that folded onto it (`foldedOnto`) — those\n * fields were repointed at its models and reference nothing else — so a merge\n * pass that later renames one of its models (a deprecated companion named\n * like a live component field's model, say) repoints every operation that\n * shares it, and nothing else. `survivingModels` is what the resolver\n * returned; a companion is a survivor when its own model is among them.\n * `qualifiers` gives each companion the stem the models of the operation\n * that lifted it are named from (`ListUsers` for `listUsers`, `UserList`\n * for `users.list`, or `UsersGet` for `GET /users` without an\n * `operationId`), to prefix a renamed model with.\n */\nexport function companionBundles(\n  companions: EnvelopeCompanion[],\n  survivingModels: Model[],\n  foldedOnto: ReadonlyMap<EnvelopeCompanion, EnvelopeCompanion>,\n  qualifiers: ReadonlyMap<EnvelopeCompanion, string>,\n): InlineModelBundle[] {\n  const surviving = new Set(survivingModels);\n  const bundles: InlineModelBundle[] = [];\n  for (const companion of companions) {\n    const own = companion.models[0];\n    if (!own || !surviving.has(own)) continue;\n    const sharers = companions.filter((c) => foldedOnto.get(c) === companion);\n    bundles.push({\n      qualifier: qualifiers.get(companion) ?? '',\n      roots: [companion.field.type, ...sharers.map((c) => c.field.type)],\n      models: companion.models,\n    });\n  }\n  return bundles;\n}\n\n/**\n * Rename a companion's models to `names` (index-aligned with `models`) and\n * repoint every reference, in its field and inside its models — a union\n * companion's discriminator mapping with its variants (`renameTypeRefModels`).\n */\nfunction renameCompanion(companion: EnvelopeCompanion, names: string[]): void {\n  const renames = new Map<string, string>();\n  companion.models.forEach((model, i) => {\n    const name = names[i];\n    if (name !== undefined && model.name !== name) renames.set(model.name, name);\n  });\n  if (renames.size === 0) return;\n\n  renameTypeRefModels(companion.field.type, renames);\n  for (const model of companion.models) {\n    model.name = renames.get(model.name) ?? model.name;\n    renameModelRefs(model, renames);\n  }\n}\n\n/**\n * How `component` is looser than `companion`'s own model, which it admits\n * (`admits`), for the warning the fold is announced with\n * (`deprecatedFoldWarning`): what `modelAdmits` would read on the fields\n * themselves (`looserFields`: a field the companion requires, a type it\n * leaves non-null), then each field whose type the component loosens below\n * its own nullable wrapper — a nested model's requiredness or null, an\n * enum's members (`loosens \"cursor\"`). The component admits each type, so\n * one that admits the component's back (`typeAdmits`, read the other way\n * round) is the same shape. Empty when the two are the same shape but for\n * the flag.\n */\nfunction looserThanCompanion(\n  component: Model,\n  componentMap: Map<string, Model>,\n  companion: EnvelopeCompanion,\n): string[] {\n  const own = companion.models[0]!;\n  const local = new Map(companion.models.map((m) => [m.name, m]));\n  const inner = (type: TypeRef): TypeRef => (type.kind === 'nullable' ? type.inner : type);\n  const targets = new Map(component.fields.map((field) => [field.name, field]));\n  const deeper = own.fields\n    .filter((field) => {\n      const target = targets.get(field.name);\n      return target !== undefined && !typeAdmits(inner(field.type), local, inner(target.type), componentMap, new Set());\n    })\n    .map((field) => `\"${field.name}\"`);\n  return [...looserFields(component, own), ...(deeper.length > 0 ? [`loosens ${deeper.join(', ')}`] : [])];\n}\n\n/**\n * Whether `target` admits every value `copy` can hold: the same field names,\n * each field's type admitted (see `typeAdmits`), and no field the target\n * requires that the copy leaves optional. Nested models resolve through their\n * respective maps and are compared the same way; a model neither map resolves\n * is compared by name.\n */\nfunction admits(\n  target: Model,\n  targetMap: Map<string, Model>,\n  copy: Model,\n  copyMap: Map<string, Model>,\n  visiting: Set<string>,\n): boolean {\n  const key = `${target.name}|${copy.name}`;\n  if (visiting.has(key)) return true;\n  visiting.add(key);\n  try {\n    // Deprecation is part of the shape among copies: a live target must not\n    // absorb a deprecated copy (its flag would vanish), and a deprecated\n    // target must not absorb a live one (a live operation would then\n    // reference it). Beside a component the caller has already read the\n    // root flag by `ownerFlagAdmits` and stripped it from the copy.\n    if (!!target.deprecated !== !!copy.deprecated) return false;\n    // Every other property of the model itself — its limits\n    // (`minProperties`, `dependentRequired`, …), type parameters, whatever\n    // else the IR adds — is read as every component fold reads it\n    // (`modelPropertiesAdmit`): identical, since the target's definition is\n    // what every site reads after a fold.\n    if (!modelPropertiesAdmit(target, copy)) return false;\n    if (target.fields.length !== copy.fields.length) return false;\n    const targetFields = new Map(target.fields.map((f) => [f.name, f]));\n    for (const field of copy.fields) {\n      const expected = targetFields.get(field.name);\n      if (!expected) return false;\n      // Everything but the type is read as `fieldAdmits` reads it\n      // (`fieldPropertiesAdmit`): the flag agrees in either direction, the\n      // target is no stricter on requiredness, and limits, default, access\n      // flags and every other property are identical — the target's fields\n      // are what every site reads after a fold. The type is compared by\n      // structure below, since a companion's nested models and inline enums\n      // are named per operation.\n      if (!fieldPropertiesAdmit(expected, field)) return false;\n      if (!typeAdmits(expected.type, targetMap, field.type, copyMap, visiting)) return false;\n    }\n    // A named union is its variants — the same ones, in the same order —\n    // dispatched by the same rules (composition keyword, discriminator).\n    if (unionRulesKey(target) !== unionRulesKey(copy)) return false;\n    const targetVariants = target.variants ?? [];\n    const copyVariants = copy.variants ?? [];\n    if (targetVariants.length !== copyVariants.length) return false;\n    for (let i = 0; i < copyVariants.length; i++) {\n      if (!typeAdmits(targetVariants[i]!, targetMap, copyVariants[i]!, copyMap, visiting)) return false;\n    }\n    return true;\n  } finally {\n    visiting.delete(key);\n  }\n}\n\n/**\n * Whether `target` admits every value of `copy`'s type. A nullable target\n * admits a nullable or a non-null copy; a non-null target admits only a\n * non-null copy. An enum with known values admits a copy whose members are a\n * subset of its own — a member being a value with its deprecation\n * (`enumValueShapeKey`), so a copy deprecating a value the target does not\n * is not admitted. Everything else must match exactly, by fingerprint.\n */\nfunction typeAdmits(\n  target: TypeRef,\n  targetMap: Map<string, Model>,\n  copy: TypeRef,\n  copyMap: Map<string, Model>,\n  visiting: Set<string>,\n): boolean {\n  if (target.kind === 'nullable') {\n    return typeAdmits(target.inner, targetMap, copy.kind === 'nullable' ? copy.inner : copy, copyMap, visiting);\n  }\n  if (copy.kind === 'nullable') return false;\n  if (target.kind !== copy.kind) return false;\n  switch (target.kind) {\n    case 'model': {\n      const t = targetMap.get(target.name);\n      const c = copyMap.get((copy as typeof target).name);\n      if (t && c) return admits(t, targetMap, c, copyMap, visiting);\n      return target.name === (copy as typeof target).name;\n    }\n    case 'array':\n      return typeAdmits(target.items, targetMap, (copy as typeof target).items, copyMap, visiting);\n    case 'enum': {\n      const c = copy as typeof target;\n      if (target.values && c.values) {\n        const allowed = new Set(enumValuesOf(target).map(enumValueShapeKey));\n        return enumValuesOf(c).every((v) => allowed.has(enumValueShapeKey(v)));\n      }\n      return target.name === c.name;\n    }\n    default:\n      return fingerprintType(target, targetMap, new Set()) === fingerprintType(copy, copyMap, new Set());\n  }\n}\n\n/**\n * Structural fingerprint of a companion model: the model's own properties as\n * `modelPropertiesAdmit` reads them (`modelPropertiesKey`: whether it is\n * deprecated, its limits, its type parameters), its field names, each\n * field's properties as `fieldPropertiesAdmit` reads them\n * (`fieldPropertiesKey`: requiredness, its own deprecation, limits, default,\n * access flags) and each field's shape, with models nested\n * inside the companion compared by shape rather than by (operation-qualified)\n * name, and inline enums compared by their members — each value with its\n * deprecation (`enumValueShapeKey`), so a copy deprecating a value the others\n * do not keeps its own name, as a deprecated copy of a model does. Models\n * outside the companion are compared by name.\n */\nfunction fingerprintModel(model: Model, local: Map<string, Model>, visiting: Set<string>): string {\n  if (visiting.has(model.name)) return `rec:${model.name}`;\n  visiting.add(model.name);\n  const fields = [...model.fields]\n    .sort((a, b) => a.name.localeCompare(b.name))\n    .map((f) => `${f.name}${fieldPropertiesKey(f)}:${fingerprintType(f.type, local, visiting)}`);\n  // A named union's variants, in document order, and its dispatch rules are\n  // part of its shape.\n  const union = unionShapeKey(model, (v) => fingerprintType(v, local, visiting));\n  visiting.delete(model.name);\n  return `${modelPropertiesKey(model)}{${fields.join(',')}}${union}`;\n}\n\nfunction fingerprintType(ref: TypeRef, local: Map<string, Model>, visiting: Set<string>): string {\n  switch (ref.kind) {\n    case 'primitive':\n      return `p:${ref.type}${ref.format ? `:${ref.format}` : ''}`;\n    case 'literal':\n      return `l:${typeof ref.value}:${String(ref.value)}`;\n    case 'nullable':\n      return `n<${fingerprintType(ref.inner, local, visiting)}>`;\n    case 'array':\n      return `a<${fingerprintType(ref.items, local, visiting)}>`;\n    case 'map':\n      return `m<${ref.keyType ? `${fingerprintType(ref.keyType, local, visiting)},` : ''}${fingerprintType(ref.valueType, local, visiting)}>`;\n    case 'union':\n      return `u:${ref.compositionKind ?? ''}<${ref.variants\n        .map((v) => fingerprintType(v, local, visiting))\n        .sort()\n        .join(',')}>`;\n    case 'enum':\n      return ref.values ? `e<${enumShapeKey(enumValuesOf(ref))}>` : `e:${ref.name}`;\n    case 'model': {\n      const nested = local.get(ref.name);\n      return nested ? fingerprintModel(nested, local, visiting) : `ref:${ref.name}`;\n    }\n    default:\n      return assertNever(ref);\n  }\n}\n","import type {\n  Service,\n  Operation,\n  HttpMethod,\n  Parameter,\n  ParameterGroup,\n  TypeRef,\n  ErrorResponse,\n  SuccessResponse,\n  ResponseHeader,\n  ResponseContent,\n  RequestBodyContent,\n  Enum,\n  EnumRef,\n  DefaultResponse,\n  RangeResponse,\n  Model,\n  Field,\n  PaginationMeta,\n  PaginationEndOfIteration,\n  ExternalDocs,\n  ServerEntry,\n  StatusRange,\n  Webhook,\n} from '../ir/types.js';\nimport { isParameterSegment, pathSegments, readPath, type OperationHint } from '../ir/operation-hints.js';\nimport { isDefaultServerList, serverListsEqual } from '../ir/server-url.js';\nimport { foldHeaderName, foldParameterName, parameterKey } from '../ir/parameter-key.js';\nimport { createHash } from 'node:crypto';\nimport {\n  toPascalCase,\n  toCamelCase,\n  splitWords,\n  cleanSchemaName,\n  stripListItemMarkers,\n  singularizeLeadingWord,\n  singularizePathSegment,\n  numberedName,\n  numberedProperty,\n} from '../utils/naming.js';\nimport {\n  isJsonMediaType,\n  isPlainJsonMediaType,\n  mediaTypeEssence,\n  mediaTypeNameFragment,\n  mediaTypeNamingOrder,\n} from '../utils/media-type.js';\nimport {\n  BINARY_RESPONSE_MEDIA_TYPES,\n  TEXT_RESPONSE_MEDIA_TYPES,\n  responseBodyReading,\n  unreadResponseBodyType,\n} from './body-media-types.js';\nimport type { SchemaObject } from './schemas.js';\nimport {\n  schemaToTypeRef,\n  buildFieldFromSchema,\n  nameInlineVariant,\n  resolveSchemaName,\n  nonEmptyExamples,\n  resolveExamples,\n  resolveComponentSchemaRef,\n  extractConstraints,\n  schemaConstraints,\n  componentReference,\n  constraintsEntry,\n  deferInlineUnionMappingEntries,\n  deprecatedEntry,\n  enumComponentDeclaration,\n  collapsedNullableBranch,\n  foldSiblingProperties,\n  inlineEnumSpelling,\n  inlineMappingTargets,\n  isComponentModelRef,\n  isInlineObjectSchema,\n  isNullSchema,\n  nonObjectVariantContexts,\n  fieldSettings,\n  pinnedDeclarationAdmitsNull,\n  pinnedDeclarationValue,\n  rehearse,\n  unwrapCollapsedWrappers,\n  unwrapNullableField,\n  unwrapNullableSchema,\n  warnOnUncarriedProperties,\n  withSchemaConstraints,\n  withWrapperDocs,\n} from './schemas.js';\nimport {\n  collectResponseHeaders,\n  collectModelRefs,\n  collectModelTypeRefs,\n  collectEnumRefs,\n  collectOperationTypeRefs,\n  renameModelRefs,\n  renameTypeRefModels,\n  walkTypeRef,\n  type ModelRef,\n} from '../ir/types.js';\nimport {\n  agreedDeclarationKeys,\n  LIFTED_DECLARATION_KEYWORDS,\n  allOfWrapperLayer,\n  annotatingAllOfMembers,\n  agreedExtensions,\n  collectProperties,\n  extractInlineModelsFromProperties,\n  isInheritedModelRef,\n  shapeFingerprint,\n  takeModelDocumentation,\n  withAgreedExtensions,\n  type InlineModelBundle,\n} from './inline-models.js';\nimport {\n  SCHEMA_CONSUMED_EXTENSIONS,\n  extensionsOf,\n  operationExtensionsEntry,\n  schemaExtensionsEntry,\n} from './extensions.js';\nimport {\n  detectPagination,\n  derivePageStart,\n  describeUndetectedPaging,\n  paginatedItemType,\n  resolvePaginationOverride,\n  resolveOverrideParams,\n  applyPaginationOverride,\n  dataPathForks,\n  dataPathProblem,\n  dataPathWalkStart,\n  deferDataPathItemType,\n  walkDataPathItemType,\n} from './pagination.js';\nimport {\n  BODY_READINGS,\n  bodyEndOfIterationProblem,\n  bodyTypesAsUnknown,\n  classifyAndExtractResponse,\n  composedWithoutFields,\n  classifyResponseKey,\n  isErrorStatusRange,\n  resolveDataPathFromSchema,\n  STATUS_RANGE_LABELS,\n  warnUnrecognizedResponseKey,\n} from './responses.js';\nimport type { ResponseKey } from './responses.js';\nimport type { ItemSettlement, ResponseExtractionResult } from './responses.js';\nimport { isResponseEntry, isResponsesObject, resolveResponseRef, type ReferenceObject } from './response-refs.js';\nimport { shapeWithEnumFlags } from './enum-members.js';\nimport {\n  materializeInlineSchema,\n  modelFingerprint,\n  ownerShares,\n  registerInlineModels,\n  reserveEnumNames,\n  type InlineModelRegistry,\n  type InlineModelOwner,\n  type SiblingSites,\n  createSiblingSites,\n} from './materialize-inline.js';\nimport { extractSecurityRequirements, type RawSecurityRequirements } from './security.js';\nimport { extractServerList } from './servers.js';\nimport { resolveEnvelopeCompanionNames, companionBundles, type EnvelopeCompanion } from './envelope-companion-names.js';\nimport { externalDocsEntry, readExternalDocs, type RawExternalDocs } from './external-docs.js';\nimport { resolvePathItemRef } from './path-item-refs.js';\nimport { componentKeyOf } from './schema-refs.js';\nimport { followReference, siblingDocsMode, type SiblingDocs } from './reference-objects.js';\n\nexport interface PathItem {\n  /**\n   * A reference to another Path Item, which OpenAPI 3.1 lets a `paths` entry\n   * be written as (`$ref: '#/components/pathItems/Pets'`, or another `paths`\n   * or `webhooks` entry: `$ref: '#/paths/~1pets'`). Resolved by\n   * `resolvePathItems` before anything else is read from the entry, so no\n   * item the passes of `extractOperations` read carries one.\n   */\n  $ref?: string;\n  /**\n   * The Path Item's own `summary`, which OpenAPI applies to every operation\n   * on it; read for an operation that declares none (`resolveOperationDocs`).\n   */\n  summary?: string;\n  /** The Path Item's own `description`, applied to its operations the same way. */\n  description?: string;\n  get?: OperationObject;\n  post?: OperationObject;\n  put?: OperationObject;\n  patch?: OperationObject;\n  delete?: OperationObject;\n  head?: OperationObject;\n  options?: OperationObject;\n  trace?: OperationObject;\n  parameters?: RawParameterObject[];\n  /** The Path Item's own `servers`, narrowed entry by entry by `extractServerList`. */\n  servers?: unknown;\n}\n\ninterface ParameterGroupExtension {\n  optional: boolean;\n  variants: Record<string, string[]>;\n  /** Per-variant names that may be omitted when the variant is used. */\n  optionalFields?: Record<string, string[]>;\n}\n\nexport interface OperationObject {\n  operationId?: string;\n  summary?: string;\n  description?: string;\n  tags?: string[];\n  externalDocs?: RawExternalDocs;\n  parameters?: RawParameterObject[];\n  requestBody?: RawRequestBodyObject;\n  responses?: Record<string, ResponseObject>;\n  deprecated?: boolean;\n  'x-oagen-async'?: boolean;\n  /** Explicit pagination override; validated by `applyPaginationOverrides`. */\n  'x-pagination'?: unknown;\n  security?: RawSecurityRequirements;\n  /** The operation's own `servers`, narrowed entry by entry by `extractServerList`. */\n  servers?: unknown;\n  'x-mutually-exclusive-parameter-groups'?: Record<string, ParameterGroupExtension>;\n  'x-mutually-exclusive-body-groups'?: Record<string, ParameterGroupExtension>;\n  /**\n   * The Operation Object's `callbacks` map, as written: Callback Objects, or\n   * `$ref`s into `components/callbacks`, keyed by name. Not read here — the\n   * operations pass records it with the operation's label and model stem\n   * (`DeclaredCallbacks`) for `extractCallbacks` to read once every webhook\n   * is named, so a callback's models step around every name in the\n   * document (#382).\n   */\n  callbacks?: unknown;\n}\n\n/**\n * The `callbacks` map an Operation Object declares, held for the callback\n * reader (`extractCallbacks` in `callbacks.ts`) with what reading it needs:\n * the IR node the callbacks hang off — a `paths` operation or a `webhooks`\n * entry — that node's diagnostic label, which a callback's sites are\n * labelled under (`<label>.callbacks.<key>.<expression>.<method>`), and\n * the stem the node's own models are named from, which a key-named\n * callback's are prefixed with (`CreatePet` + `petAdopted` →\n * `CreatePetPetAdoptedPayload`). Recorded whenever the Operation Object\n * carries the key, whatever its value: the reader decides what declares a\n * callback (#382).\n */\nexport interface DeclaredCallbacks {\n  /** The operation or webhook that declares the map; its `callbacks` field is set by the reader. */\n  owner: Operation | Webhook;\n  /** The map as written. */\n  callbacks: unknown;\n  /** The owner's label as its own diagnostics name it: the `operationId`, else `METHOD /path`; `webhooks.<key>.<method>`. */\n  label: string;\n  /**\n   * The stem the owner's own models are named from: an operation's\n   * `modelQualifier` (the one `<Stem>Request` and `<Stem>Response` use), a\n   * webhook's resolved stem (`resolveWebhookModelStems`).\n   */\n  stem: string;\n  /**\n   * The owner's stable identity, which a key-named callback's collision\n   * hash is taken from (`WebhookEntry.identity`): an operation's\n   * operationId — the one its models are named from — else `METHOD /path`;\n   * a webhook's operationId when its stem is named from one, else its\n   * label. Two owners whose stems coincide (`createPet`, `create_pet`) have\n   * two identities, while two `webhooks` keys sharing a path item with an\n   * operationId have one, so their callbacks hash alike whichever key comes\n   * first. Defaults to `label`.\n   */\n  identity?: string;\n}\n\n/**\n * An OAS Example Object, as the entries of a parameter's `examples` map and\n * of `components.examples`. Only `value` is read: a `$ref` entry is first\n * resolved against `components.examples` (see `resolveExampleRef`), and an\n * entry that carries `externalValue` instead has no inline value to surface.\n */\ninterface ExampleObject {\n  summary?: string;\n  description?: string;\n  value?: unknown;\n  externalValue?: string;\n  $ref?: string;\n}\n\n/**\n * The Media Type Object a Parameter Object's or Header Object's `content`\n * map holds under a media type: the schema that types the value and the\n * examples beside it. `encoding` is not read.\n */\nexport interface ParameterMediaTypeObject {\n  schema?: SchemaObject;\n  example?: unknown;\n  /** Media-type-level examples: a map of Example Objects, as the parameter's own `examples` is. */\n  examples?: Record<string, ExampleObject>;\n}\n\n/**\n * What a Parameter Object or Header Object types its value with: a\n * `schema`, or a `content` map in its place — per OAS one or the other,\n * never both, and the map holds one entry. `parameterTyping` resolves the\n * schema either way.\n */\nexport interface SchemaOrContent {\n  schema?: SchemaObject;\n  content?: Record<string, ParameterMediaTypeObject>;\n}\n\nexport interface ParameterObject extends SchemaOrContent {\n  name: string;\n  in: 'path' | 'query' | 'header' | 'cookie';\n  required?: boolean;\n  description?: string;\n  deprecated?: boolean;\n  example?: unknown;\n  /** Parameter-level examples: a map of Example Objects, not a JSON Schema list. */\n  examples?: Record<string, ExampleObject>;\n  style?: string;\n  explode?: boolean;\n}\n\n/**\n * A parameter entry as it appears in an operation's (or path item's) raw\n * `parameters` array: either an inline Parameter Object, or a Reference\n * Object (`{ $ref: '#/components/parameters/X' }`). The bundler\n * (`refs.ts`) runs with `dereference: false`, so refs to\n * `components/parameters` are never inlined — they arrive here exactly as\n * written in the spec and must be resolved before use.\n */\nexport type RawParameterObject = ParameterObject | { $ref: string };\n\n/**\n * Resolve a raw parameter entry to a concrete Parameter Object, following\n * `$ref`s into `components/parameters` when present — chains included, with\n * a cycle guard — through `followReference`, the walk every Reference Object\n * takes. A `description` written beside a ref is the parameter's own under\n * `siblingDocs: 'override'` (OAS 3.1), the outermost with content winning\n * along a chain, and is ignored under `'ignore'` (OAS 3.0).\n *\n * Throws when a `$ref` can't be resolved so a malformed spec fails loudly at\n * parse time instead of silently losing the parameter (see `extractParams`,\n * which used to drop any entry with no `in` field — every `$ref` object has\n * none).\n */\nexport function resolveParameterRef(\n  raw: RawParameterObject,\n  componentParameters: Record<string, Record<string, unknown>> | undefined,\n  operationContext: string,\n  siblingDocs: SiblingDocs = 'override',\n): ParameterObject {\n  const followed = followReference<ParameterObject>(raw, 'parameters', componentParameters, siblingDocs);\n  if (followed.outcome === 'circular') {\n    throw new Error(`Circular parameter $ref chain starting at \"${followed.ref}\" in ${operationContext}.`);\n  }\n  if (followed.outcome !== 'resolved') {\n    throw new Error(\n      `Unresolved parameter $ref \"${followed.ref}\" in ${operationContext}: no matching entry under components/parameters.`,\n    );\n  }\n  return followed.value;\n}\n\n/** The header parameter names OpenAPI says to ignore, folded (`foldHeaderName`). */\nconst IGNORED_HEADER_PARAMETERS: ReadonlySet<string> = new Set(['accept', 'content-type', 'authorization']);\n\n/**\n * Whether `param` is a header parameter whose definition OpenAPI says\n * \"SHALL be ignored\" (OAS 3.x, Parameter Object): one named `Accept`,\n * `Content-Type` or `Authorization`, whatever its case, headers the\n * request's media types and `security` already set. Asked once its `$ref`\n * is resolved (`resolveParameterRef`) and before anything types it, so an\n * operation or a webhook never carries it, nor a model or enum its schema\n * would mint.\n */\nexport function isIgnoredHeaderParameter(param: ParameterObject): boolean {\n  return param.in === 'header' && IGNORED_HEADER_PARAMETERS.has(foldHeaderName(param.name));\n}\n\n/** The response header name OpenAPI says to ignore, folded (`foldHeaderName`). */\nconst IGNORED_RESPONSE_HEADER = 'content-type';\n\n/**\n * Whether a response header named `name` is one OpenAPI says \"SHALL be\n * ignored\" (OAS 3.x, Response Object): `Content-Type`, whatever its case,\n * since the response's `content` map already carries the media type. A\n * narrower rule than a parameter's (`isIgnoredHeaderParameter`): an\n * `Accept` or `Authorization` response header is read. Asked by the key the\n * `headers` map declares the header under — its name, whatever a `$ref`\n * there leads to — before anything types it, so neither\n * `extractResponseHeaders` nor the sent-only component walk\n * (`sentOnlyComponentNames`, #540) reads the components its schema names.\n */\nexport function isIgnoredResponseHeader(name: string): boolean {\n  return foldHeaderName(name) === IGNORED_RESPONSE_HEADER;\n}\n\nexport interface RequestBodyObject {\n  description?: string;\n  required?: boolean;\n  content?: Record<string, { schema?: SchemaObject }>;\n}\n\n/**\n * A request body as written in the spec: an inline Request Body Object or a\n * Reference Object into `components/requestBodies`. The bundler never inlines\n * those refs (`dereference: false`), so they must be resolved before use.\n */\nexport type RawRequestBodyObject = RequestBodyObject | { $ref: string };\n\n/**\n * Resolve a raw request body to a concrete Request Body Object, following\n * `$ref` chains into `components/requestBodies` with a cycle guard, through\n * `followReference`, the walk every Reference Object takes. A `description`\n * written beside a ref is the body's own under `siblingDocs: 'override'`\n * (OAS 3.1), the outermost with content winning along a chain, and is\n * ignored under `'ignore'` (OAS 3.0) — so `requestBodyDescriptionOf` reads\n * it ahead of the shared body's. Throws on an unresolvable ref so a\n * malformed spec fails at parse time instead of silently losing the body —\n * and with it the body-ownership rule that keeps duplicated secrets out of\n * the query string.\n */\nexport function resolveRequestBodyRef(\n  raw: RawRequestBodyObject | undefined,\n  componentRequestBodies: Record<string, Record<string, unknown>> | undefined,\n  operationContext: string,\n  siblingDocs: SiblingDocs = 'override',\n): RequestBodyObject | undefined {\n  if (!raw) return undefined;\n  const followed = followReference<RequestBodyObject>(raw, 'requestBodies', componentRequestBodies, siblingDocs);\n  if (followed.outcome === 'circular') {\n    throw new Error(`Circular request body $ref chain starting at \"${followed.ref}\" in ${operationContext}.`);\n  }\n  if (followed.outcome !== 'resolved') {\n    throw new Error(\n      `Unresolved request body $ref \"${followed.ref}\" in ${operationContext}: no matching entry under components/requestBodies.`,\n    );\n  }\n  return followed.value;\n}\n\n/**\n * A Header Object as it appears in a Response Object's `headers` map. Per OAS\n * it carries either `schema` or a single-entry `content` map, never both;\n * the schema that types it is resolved as a parameter's is\n * (`parameterTyping`).\n */\ninterface HeaderObject extends SchemaOrContent {\n  description?: string;\n  required?: boolean;\n  deprecated?: boolean;\n}\n\n/**\n * A header entry as written in the spec: an inline Header Object or a\n * Reference Object into `components/headers`. The bundler never inlines those\n * refs (`dereference: false`), so they must be resolved before use. In OAS 3.1\n * a Reference Object may carry its own `description`, which overrides the\n * referenced component's.\n */\ntype RawHeaderObject = HeaderObject | { $ref: string; description?: string };\n\n/**\n * Resolve a raw response header to a concrete Header Object, following `$ref`\n * chains into `components/headers` with a cycle guard, through\n * `followReference`, the walk every Reference Object takes. A `description`\n * written beside a ref is the header's own under `siblingDocs: 'override'`\n * (OAS 3.1), the outermost with content winning along a chain, and is\n * ignored under `'ignore'` (OAS 3.0).\n *\n * Unlike parameters and request bodies, a header that cannot be resolved is\n * warned about and dropped rather than failing the parse: a response header\n * is informational, so losing one costs an emitter a typed accessor, not a\n * wire contract, and should not block generating the rest of the SDK.\n */\nfunction resolveHeaderRef(\n  raw: RawHeaderObject,\n  componentHeaders: Record<string, Record<string, unknown>> | undefined,\n  headerName: string,\n  operationContext: string,\n  siblingDocs: SiblingDocs = 'override',\n): HeaderObject | undefined {\n  const followed = followReference<HeaderObject>(raw, 'headers', componentHeaders, siblingDocs);\n  if (followed.outcome === 'circular') {\n    console.warn(\n      `[oagen] Warning: Circular header $ref chain starting at \"${followed.ref}\" for response header ` +\n        `\"${headerName}\" in ${operationContext}. Skipping the header.`,\n    );\n    return undefined;\n  }\n  if (followed.outcome !== 'resolved') {\n    console.warn(\n      `[oagen] Warning: Unresolved header $ref \"${followed.ref}\" for response header \"${headerName}\" ` +\n        `in ${operationContext}: no matching entry under components/headers. Skipping the header.`,\n    );\n    return undefined;\n  }\n  return followed.value;\n}\n\nexport interface ResponseObject {\n  description?: string;\n  headers?: Record<string, RawHeaderObject>;\n  content?: Record<string, { schema?: SchemaObject }>;\n}\n\nexport const HTTP_METHODS: HttpMethod[] = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'];\n\n/**\n * The `paths` map with every entry resolved to the Path Item it denotes —\n * the entry itself, or the `components/pathItems` item or the other `paths`\n * or `webhooks` entry its `$ref` leads to (OpenAPI 3.1; #422) — in document\n * order, through `resolvePathItemRef`, the resolver a `webhooks` entry goes\n * through too. A key starting with `x-` is\n * a specification extension of the Paths Object, not a path, and is\n * stepped over without a warning whatever its value; the `webhooks` map\n * takes no extensions, so `collectWebhookEntries` reads every key (#421).\n * Resolved once,\n * before any pass reads the map, so the model-name reservation\n * (`resolvePathModelBaseNames`), the API root (`documentApiRoot`) and the\n * operation loop all see the same items, and a referenced item's\n * operations, `parameters`, `servers`, `summary` and `description` are read\n * exactly as an inline item's (fields written beside the `$ref` are not, and\n * the resolver reports them). An entry the resolver rejects — not an\n * object, a non-string `$ref`, a ref that names no Path Item, a dangling\n * ref, a cycle — is warned about once, naming the path, and left out. Two\n * paths that `$ref` one entry, or one path that `$ref`s another, map to one\n * object, read once per path.\n */\nfunction resolvePathItems(\n  paths: Record<string, PathItem>,\n  componentPathItems: Record<string, Record<string, unknown>> | undefined,\n  webhooks: unknown,\n): Record<string, PathItem> {\n  const resolved: Record<string, PathItem> = {};\n  for (const [path, raw] of Object.entries(paths)) {\n    // A specification extension of the Paths Object, never a path item:\n    // stepped over whatever its value, before the resolver can warn about it.\n    if (path.startsWith('x-')) continue;\n    const pathItem = resolvePathItemRef(raw, componentPathItems, { kind: 'path', key: path }, { paths, webhooks });\n    if (pathItem) resolved[path] = pathItem as PathItem;\n  }\n  return resolved;\n}\n\n/**\n * Whether an `operationId` — as the document declares it, or as an\n * `operationIdTransform` returns it (#570) — names nothing: no ASCII letter\n * or digit is left once its trailing overload markers are stripped\n * (normalizeOperationIdForNaming), so it camel-cases to nothing — `''`,\n * `' '`, `'-'`, `'[1]'` and `'[1][2]'` alike, since every marker at the end\n * goes (#565). The one reading of the rule, so the document's id and what a\n * transform makes of it cannot be judged differently — and the reading a\n * webhook's `operationId` gets too (`collectWebhookEntries`, `buildWebhook`),\n * so a webhook and an operation declaring the same id are judged alike (#564).\n */\nexport function namesNothing(id: string): boolean {\n  return toCamelCase(normalizeOperationIdForNaming(id)) === '';\n}\n\n/** The resolved `paths` map read for its operationIds (readOperationIds). */\ninterface OperationIdReading {\n  /** `paths`, with every `operationId` that names nothing left out of its operation. */\n  paths: Record<string, PathItem>;\n  /** What each kept `operationId` names, by operation key (`${method} ${path}`): its operation's name. */\n  names: ReadonlyMap<string, string>;\n}\n\n/**\n * The resolved `paths` map with every `operationId` that names nothing read\n * as absent, and the name every other one gives its operation, settled once\n * before any pass reads an `operationId`.\n *\n * An `operationId` names nothing when it has no ASCII letter or digit once\n * its trailing overload markers are stripped (namesNothing) — `' '`, `'-'`,\n * `'[1]'`, `'[1][2]'` — and, when an `operationIdTransform` is set, when what\n * the transform returns for one that names something names nothing by the\n * same reading, or is not a string at all (`(id) => id.split('.').at(1)`\n * returns `undefined` for `getPet`): the transform is asked for the name, so\n * its result is read as the document's `operationId` is (#570). The first\n * is left out silently and never handed to the transform; the second is\n * warned about once, by the document's id and the operation, since the\n * transform was given a name and made nothing of it. Either operation is\n * read as one without an `operationId`, as one declaring `''` always was:\n * named from its method and path, and renamed as a path-named operation when\n * that name collides (planOperations), its models named from its path, and\n * given no `Operation.operationId`, so `resolveOperations` derives its method\n * name from the path under either `operationNaming` (#526). A Path Item\n * without one is kept as it is; one with one is copied, its other operations\n * kept as they are.\n *\n * `names` is the one place the transform is called — once per operation,\n * with the id's trailing markers stripped (operationIdName) — so a transform\n * sees each id once and every pass after reads the one name it gave\n * (planOperations, through inferOperationName).\n */\nfunction readOperationIds(\n  paths: Record<string, PathItem>,\n  operationIdTransform: ((id: string) => string) | undefined,\n): OperationIdReading {\n  const result: Record<string, PathItem> = {};\n  const names = new Map<string, string>();\n  for (const [path, pathItem] of Object.entries(paths)) {\n    let item = pathItem;\n    for (const method of HTTP_METHODS) {\n      const op = item[method];\n      if (typeof op?.operationId !== 'string') continue;\n      if (!namesNothing(op.operationId)) {\n        const name: unknown = operationIdName(op.operationId, operationIdTransform);\n        if (typeof name === 'string' && !namesNothing(name)) {\n          names.set(`${method} ${path}`, name);\n          continue;\n        }\n        const returned = typeof name === 'string' ? JSON.stringify(name) : String(name);\n        console.warn(\n          `[oagen] Warning: operationIdTransform returned ${returned}, which names nothing, for operationId ` +\n            `\"${op.operationId}\" on ${method.toUpperCase()} ${path}; naming the operation from its path`,\n        );\n      }\n      item = { ...item, [method]: { ...op, operationId: undefined } };\n    }\n    result[path] = item;\n  }\n  return { paths: result, names };\n}\n\nexport interface OperationExtractionResult {\n  services: Service[];\n  inlineModels: Model[];\n  /**\n   * Where the operations' inline models came from — one bundle per response\n   * and per request body that produced any — so a merge pass can rename a\n   * copy that must not share its name and repoint exactly that operation's\n   * references. List-envelope companions are not bundled:\n   * `resolveEnvelopeCompanionNames` settles their names once and for all.\n   */\n  inlineModelBundles: InlineModelBundle[];\n  /**\n   * Every type reference a site shared through `components/responses` wrote\n   * (`componentSite`: the component's fallback or error body, a secondary\n   * body, a header) and each 2xx entry's `type` a component declares (typed\n   * with its operation, never deferred), by identity — the parser's one\n   * record of which sites a component owns, which the IR alone cannot tell\n   * (`CardXMode` is a shared header's enum name wherever the component is\n   * returned). The enum\n   * collector reads it so an enum such a site carries steps by number from\n   * the component's stem (`CardXMode2`), never by the status code or\n   * fallback label that mounted the component, nor by the `Body` an\n   * operation's own error body steps by: an error site — `errors[].type`, a\n   * secondary body of an error entry, a `4XX`/`5XX` range's body — that is\n   * not here is the operation's own, written as `<Op>Error<code>…`, and\n   * steps to `…Body` (`collectInlineEnumsFromOperations`).\n   */\n  componentSites: ReadonlySet<TypeRef>;\n  /**\n   * Every `callbacks` map a `paths` operation declares, in document order,\n   * for `extractCallbacks` to read after the webhooks are named (#382).\n   */\n  declaredCallbacks: DeclaredCallbacks[];\n}\n\n/** A top-level `tags[]` entry as it appears in the OpenAPI document. */\nexport interface TagObject {\n  name?: string;\n  description?: string;\n  externalDocs?: RawExternalDocs;\n}\n\nexport function extractOperations(\n  paths: Record<string, PathItem> | undefined,\n  operationIdTransform?: (id: string) => string,\n  componentSchemas?: Record<string, SchemaObject>,\n  componentParameters?: Record<string, Record<string, unknown>>,\n  componentRequestBodies?: Record<string, Record<string, unknown>>,\n  componentModels?: Model[],\n  documentTags?: TagObject[],\n  componentExamples?: Record<string, Record<string, unknown>>,\n  componentHeaders?: Record<string, Record<string, unknown>>,\n  componentResponses?: Record<string, Record<string, unknown>>,\n  componentFieldModels?: Model[],\n  documentServers?: ServerEntry[],\n  openapiVersion?: string,\n  operationHints?: Record<string, OperationHint>,\n  /** The component enums, whose names no deferred or item model may take (see `reserveEnumNames`). */\n  componentEnums?: readonly Enum[],\n  componentPathItems?: Record<string, Record<string, unknown>>,\n  /** The document's `webhooks` map, as written, whose entries a `paths` entry's `$ref` may name. */\n  documentWebhooks?: unknown,\n): OperationExtractionResult {\n  if (!paths) {\n    return { services: [], inlineModels: [], inlineModelBundles: [], componentSites: new Set(), declaredCallbacks: [] };\n  }\n\n  // Every pass below reads the resolved map: each entry as itself, or as the\n  // Path Item its `$ref` leads to, with an entry that resolves to nothing\n  // left out after one warning (see resolvePathItems), and an `operationId`\n  // that names nothing — or that the operationIdTransform makes nothing of —\n  // left out of its operation, every other one's name settled (see\n  // readOperationIds).\n  const { paths: resolvedPaths, names: operationIdNames } = readOperationIds(\n    resolvePathItems(paths, componentPathItems, documentWebhooks),\n    operationIdTransform,\n  );\n\n  // Whether text written beside a `$ref` overrides the referenced component's\n  // (OAS 3.1, and a version not recognised) or is ignored (OAS 3.0), for every\n  // Reference Object the operations resolve (`followReference`): parameters,\n  // request bodies, responses, headers and examples alike.\n  const refSiblingDescriptions = siblingDocsMode(openapiVersion);\n\n  // An API root the untagged paths sit under (`/api`, `/v1`) tells the\n  // services apart no better than nothing, so untagged operations skip it\n  // when their service and fallback name are taken from the path (see\n  // documentApiRoot). Tagged operations are named exactly as before.\n  const apiRoot = documentApiRoot(resolvedPaths);\n  // Every operation's service and name are settled before any operation is\n  // built (see planOperations), so the models of an operation whose\n  // operationId the document reuses can follow the name it ends up with, and\n  // no two such operations name their models alike (see\n  // resolveReusedOperationIds). Nor do two operations whose distinct ids\n  // clean to one stem (`createPet` beside `create_pet`): the one spelled as\n  // the stem keeps it and every other one is path-named (see\n  // resolveContestedOperationIdStems).\n  const plan = planOperations(resolvedPaths, apiRoot, operationIdNames);\n  const { modelOperationIds, sharedWith } = resolveReusedOperationIds(resolvedPaths, plan);\n  resolveContestedOperationIdStems(resolvedPaths, plan, modelOperationIds, sharedWith);\n\n  // Operations without an operationId — or left none by the reuse of their\n  // own (see resolveReusedOperationIds) or by the contest of their stem (see\n  // resolveContestedOperationIdStems) — name their inline models from the\n  // path, and two distinct paths — or a path and an operationId, component\n  // schema or component response — can produce the same name, so the prefix\n  // for every such operation is decided up front (see resolvePathModelBaseNames).\n  // The spec-wide registry of model shapes (`InlineModelRegistry`), seeded\n  // with every name decided before the operations — the component models\n  // and enums, the components' field models (a nested object, a map's\n  // values; not among `componentModels`, see parseSpec) and the enums their\n  // fields mint — and filled as the operations are read: each operation's\n  // models once it is built, its array items as they are typed\n  // (`typeInlineItems` settles them against it), the envelope companions\n  // once named, and every enum the operations mint. The deferred schemas are\n  // named against all of it last. Seeded before the component responses are\n  // named, so the names an operation's array items settle on can be read\n  // against a copy of it (`operationBodyModelNames`).\n  const registry: ModelShapeRegistry = new Map();\n  const registeredModels = [...(componentModels ?? []), ...(componentFieldModels ?? [])];\n  // The component schemas' names, as the models carry them: a component\n  // shares its name with no copy while deprecated, where a model a\n  // component's field minted — among `componentModels` when the schema pass\n  // lifted it, among `componentFieldModels` otherwise — still shares it\n  // with a deprecated one (`InlineModelOwner.fieldMinted`, #441).\n  const componentNames = new Set(Object.keys(componentSchemas ?? {}).map(resolveSchemaName));\n  // Each seeded with the model itself: a declared model shares its name with\n  // every shape it admits (`ownerShares`), an operation's with an identical\n  // one only.\n  for (const model of registeredModels) {\n    if (registry.has(model.name)) continue;\n    registry.set(model.name, {\n      fingerprint: modelFingerprint(model),\n      model,\n      ...(componentNames.has(model.name) ? {} : { fieldMinted: true }),\n    });\n  }\n  // Every enum name decided so far, held as names no model may take\n  // (`reserveEnumNames`): the component enums', and every enum the component\n  // models and the components' field models reference (an inline enum's\n  // `EnumRef`, named before the enum collector may rename it; a `$ref` to a\n  // component enum names one already held). None is an operation's. The\n  // operations' own join once they are read, below.\n  const enumRefsOf = (model: Model): string[] => collectModelTypeRefs(model).flatMap(collectEnumRefs);\n  reserveEnumNames(registry, [...(componentEnums ?? []).map((e) => e.name), ...registeredModels.flatMap(enumRefsOf)]);\n\n  // Every model name the operations' own inline request and success bodies\n  // mint (see operationBodyModelNames), read once, and only when a name must\n  // step past them: a component response's body\n  // (resolveComponentResponseModelNames), or a path-derived prefix that\n  // extends an operation's stem (resolvePathModelBaseNames).\n  let operationBodyNames: string[] | undefined;\n  const readOperationBodyNames = (): readonly string[] => {\n    operationBodyNames ??= operationBodyModelNames(\n      resolvedPaths,\n      modelOperationIds,\n      componentSchemas,\n      componentResponses,\n      componentRequestBodies,\n      registry,\n    );\n    return operationBodyNames;\n  };\n  // The model name each component response's inline body takes, decided once\n  // for every operation that returns it (see resolveComponentResponseModelNames),\n  // past every name an operation's own inline body mints (read only when\n  // there is a component to step).\n  const componentResponseNaming = resolveComponentResponseModelNames(\n    componentResponses,\n    registeredModels,\n    componentSchemas,\n    Object.keys(componentResponses ?? {}).length > 0 ? readOperationBodyNames() : [],\n  );\n  const componentResponseModelNames = new Map(\n    [...componentResponseNaming].map(([componentName, naming]) => [componentName, naming.name]),\n  );\n  const pathModelBaseNames = resolvePathModelBaseNames(\n    resolvedPaths,\n    componentModels,\n    componentRequestBodies,\n    componentResponseNaming,\n    modelOperationIds,\n    sharedWith,\n    readOperationBodyNames,\n  );\n\n  /** Every operation built, by its plan key (`${method} ${path}`). */\n  const operationsByKey = new Map<string, Operation>();\n  const inlineModels: Model[] = [];\n  const inlineModelBundles: InlineModelBundle[] = [];\n  const envelopeCompanions: EnvelopeCompanion[] = [];\n  /** The qualifier of the operation each companion was lifted under (`modelQualifier`), should a merge pass rename it. */\n  const companionQualifiers = new Map<EnvelopeCompanion, string>();\n  // Service name each tagged operation was grouped under, keyed by operation\n  // identity. The path-prefix split moves operations between services, so\n  // this is how a split-off service is traced back to the tag it came from.\n  const tagServiceByOperation = new Map<Operation, string>();\n  // Header, secondary-body, fallback-body, error-body and parameter schemas\n  // are typed only after this loop, once every primary model is known\n  // (`resolveDeferredInlineTypes`): their names must not collide with a\n  // differently shaped component, request body or primary response of any\n  // operation, or the later merge would overwrite the first. The registry\n  // records which operation minted each model, and which operation's own\n  // reference carries each enum name (`qualifierOf`), so a clash within one\n  // operation can be told from one across two.\n  const deferred: DeferredInlineType[] = [];\n  const qualifierOf = new Map<Operation, string>();\n  // Each success body a `components/responses` entry declares, typed with\n  // its operation rather than deferred (`componentSites` below).\n  const componentBodies: TypeRef[] = [];\n  // Each operation's `callbacks` map, read after the webhooks (`extractCallbacks`).\n  const declaredCallbacks: DeclaredCallbacks[] = [];\n\n  for (const [path, pathItem] of Object.entries(resolvedPaths)) {\n    // Everything read at path-item level — `parameters`, `servers`, and the\n    // `summary`/`description` an operation falls back to — comes from this one\n    // object: the entry itself, or the Path Item its `$ref` leads to,\n    // resolved by `resolvePathItems` above (issues #300, #422).\n    const pathLevelParams = pathItem.parameters ?? [];\n    // Read once per Path Item so a problem in its `servers` is reported once,\n    // not once per operation. The operations that inherit it share the array,\n    // the way `responseHeaders` shares its list with `successResponses`.\n    const pathLevelServers = extractServerList(pathItem.servers, `path item ${path}`);\n\n    for (const method of HTTP_METHODS) {\n      const op = pathItem[method];\n      if (!op) continue;\n\n      // The first tag with a name (`serviceTag`), read from the list\n      // `Operation.tags` carries, so the service is named from one of its\n      // entries, and an entry that is not a string (`42`) never reaches\n      // PascalCasing.\n      const tag = serviceTag(op.tags);\n      const apiRootLength = tag ? 0 : apiRootLengthOf(path, apiRoot);\n      const serviceName = inferServiceName(path, tag, apiRootLength);\n      const key = `${method} ${path}`;\n      // A path that shares another's Operation Object names its models as that path does.\n      const pathModelBaseName =\n        pathModelBaseNames.get(sharedWith.get(key) ?? key) ?? derivePathModelBaseName(path, method);\n      const servers = operationServers(\n        extractServerList(op.servers, `operation ${operationLabel(op, path, method)}`),\n        pathLevelServers,\n        documentServers,\n      );\n\n      const {\n        operation,\n        inlineModels: opModels,\n        inlineModelBundles: opBundles,\n        envelopeCompanions: opCompanions,\n        operationQualifier,\n        modelQualifier,\n        componentBodies: opComponentBodies,\n        declaredCallbacks: opCallbacks,\n      } = buildOperation(\n        method,\n        path,\n        op,\n        pathLevelParams,\n        pathItem,\n        pathModelBaseName,\n        plan.operations.get(key)!.initialName,\n        serviceName,\n        componentSchemas,\n        componentParameters,\n        componentRequestBodies,\n        componentExamples,\n        componentHeaders,\n        componentResponses,\n        deferred,\n        servers,\n        refSiblingDescriptions,\n        componentResponseModelNames,\n        // Same \"METHOD /path\" key the operation resolver uses for the rest of the hint.\n        operationHints?.[`${method.toUpperCase()} ${path}`]?.pagination,\n        registeredModels,\n        registry,\n        modelOperationIds.get(key),\n      );\n      inlineModels.push(...opModels);\n      componentBodies.push(...opComponentBodies);\n      if (opCallbacks) declaredCallbacks.push(opCallbacks);\n      // The operation's models join the registry under its qualifier, so a\n      // later operation's items and every deferred schema step around them;\n      // its settled item models are already there (`typeInlineItems`).\n      registerInlineModels(registry, opModels, operationQualifier);\n      qualifierOf.set(operation, operationQualifier);\n      inlineModelBundles.push(...opBundles);\n      if (opCompanions) {\n        envelopeCompanions.push(...opCompanions);\n        // Qualified as the operation's own models are.\n        for (const companion of opCompanions) companionQualifiers.set(companion, modelQualifier);\n      }\n      // Same truthiness check as inferServiceName: for a tagged operation the\n      // service name *is* the normalized tag, so it doubles as the lookup key.\n      if (tag) tagServiceByOperation.set(operation, serviceName);\n      operationsByKey.set(key, operation);\n    }\n  }\n\n  // Companion models of list envelopes are named once every list operation is\n  // known, so copies of one envelope shape can share a model. They take their\n  // final names before any deferred schema is named, so a fallback variant\n  // titled `ListMetadata` steps around the companion a primary response's\n  // `list_metadata` becomes, instead of the later merge keeping whichever has\n  // more fields under one name.\n  const companionFolds = new Map<EnvelopeCompanion, EnvelopeCompanion>();\n  const companionModels = resolveEnvelopeCompanionNames(\n    envelopeCompanions,\n    componentModels,\n    companionFolds,\n    componentNames,\n  );\n  inlineModels.push(...companionModels);\n  // Each companion that kept its models is a site of its own, owning its\n  // envelope field and the envelope field of every operation whose copy\n  // folded onto it, so a merge pass that must rename one of its models (a\n  // deprecated companion named like a live component field's model, say)\n  // repoints every operation sharing it and nothing else.\n  inlineModelBundles.push(\n    ...companionBundles(envelopeCompanions, companionModels, companionFolds, companionQualifiers),\n  );\n\n  // Headers, secondary bodies, fallback bodies, error bodies and parameters\n  // are named last, in the order below, against every name in the registry —\n  // the component models and enums, the components' field models, every\n  // request body, primary response, item and companion model — and against\n  // every enum name decided so far: the component enums, and every enum\n  // those models' fields or the operations' references — a parameter in any\n  // location, a body, a response of any kind, a response header, the\n  // pagination item type and envelope fields (`collectOperationTypeRefs`) —\n  // carry (an inline enum's `EnumRef`, named before the enum collector may\n  // rename it). An enum one of an operation's own references carries is\n  // registered as that operation's, so a deferred model of the operation\n  // that derives the name is qualified by location, as one that clashes\n  // with the operation's models is; a model's field enums are its\n  // operation's, a companion's no one's. So none of them takes a name one\n  // of those owns, whichever comes first in the document, and no model is\n  // ever named like an enum.\n  registerInlineModels(registry, companionModels);\n  for (const model of inlineModels) reserveEnumNames(registry, enumRefsOf(model), registry.get(model.name)?.operation);\n  for (const [op, qualifier] of qualifierOf) {\n    reserveEnumNames(registry, collectOperationTypeRefs(op).flatMap(collectEnumRefs), qualifier);\n  }\n  // The sites a `components/responses` entry declares (`componentSite`) are\n  // named first, component by component in the order the components' bodies\n  // were settled (`resolveComponentResponseModelNames`), then every\n  // operation's own, each in document order: so of two components whose\n  // sites derive one name the one settled first keeps it (`Card`'s `X-Meta`\n  // is `CardXMeta`, `CardX`'s `Meta` `CardXMeta2`), and an operation's own\n  // site that derives a component's name steps past it (`CardGetCardXMeta`),\n  // whatever the order of the paths (workos/oagen#423). A component is\n  // ranked by the name its body is shared under, which its sites carry\n  // (`componentSite`) and no other component's body takes.\n  const componentRanks = new Map([...componentResponseNaming.values()].map(({ name }, rank) => [name, rank]));\n  const rankOf = ({ componentSite }: DeferredInlineType): number =>\n    componentSite === undefined ? componentRanks.size : (componentRanks.get(componentSite) ?? componentRanks.size);\n  const namingOrder = [...deferred].sort((a, b) => rankOf(a) - rankOf(b));\n  // An enum a deferred site types — a body that is itself an inline enum or\n  // an array of one, or an enum nested in a model the site mints (the `x`\n  // field of a 404 body) — is named only when the site is resolved, after\n  // the models of every site named before it; reserved now\n  // (`deferredEnumNames`), a deferred model of the same name steps past it\n  // whichever of the two the document declares first — an object 404 body\n  // to `GetPetError404Body`, a parameter or header object of another\n  // operation to its operation-qualified name (`SearchPetsError404ListNotesX`)\n  // — as it steps past every other enum in play, so a model never keeps an\n  // enum's name.\n  for (const item of namingOrder) reserveEnumNames(registry, deferredEnumNames(item), registryOwner(item));\n  const deferredTypes = resolveDeferredInlineTypes(deferred, registry, namingOrder);\n  inlineModels.push(...deferredTypes.models);\n  // The root every component-shared site wrote, by identity (every target of\n  // a site carries the one TypeRef its resolution produced), and each\n  // success body a component declares, for the enum collector\n  // (`OperationExtractionResult.componentSites`).\n  const componentSites = new Set<TypeRef>(componentBodies);\n  for (const item of deferred) {\n    if (item.componentSite === undefined) continue;\n    for (const target of item.targets) if (target.type) componentSites.add(target.type);\n  }\n  // Each deferred schema is a site of its own (the references it wrote, the\n  // models it minted). A reference any site wrote by sharing another site's\n  // model — a deferred body or header the registry matched to a primary\n  // body's model or a companion's, an array body's items it matched to an\n  // earlier operation's model — joins that site's roots, so a merge pass\n  // that renames the model (a deprecated copy named like a live one)\n  // repoints every response, header and array that shares it along with\n  // the site's own references.\n  inlineModelBundles.push(...deferredTypes.bundles);\n  attachSharedRefs(inlineModelBundles, new Set(registeredModels.map((model) => model.name)));\n\n  const declaredTags = indexDocumentTags(documentTags);\n  // Each service the plan settled, its operations under the names they\n  // settled on (see planOperations).\n  const services: Service[] = Array.from(plan.services.entries()).map(([name, keys]) => {\n    const operations = keys.map((key) => {\n      const operation = operationsByKey.get(key)!;\n      operation.name = plan.operations.get(key)!.name;\n      return operation;\n    });\n    const { description, externalDocs } = resolveServiceDocs(name, operations, tagServiceByOperation, declaredTags);\n    // Omit each key entirely when no tag gives it so the IR shape is\n    // unchanged for documents without tag descriptions or links.\n    return {\n      name,\n      ...(description !== undefined ? { description } : {}),\n      ...(externalDocs !== undefined ? { externalDocs } : {}),\n      operations,\n    };\n  });\n\n  return { services, inlineModels, inlineModelBundles, componentSites, declaredCallbacks };\n}\n\n/** What `planOperations` settles for one operation. */\ninterface PlannedOperation {\n  /** The name it starts with: its `operationId`'s, else the one its method and path give it (`inferOperationName`). */\n  initialName: string;\n  /** The name it ends with, unique within its service (`disambiguateOperationNames`). */\n  name: string;\n  /** The API root its path sits under for naming: none for a tagged operation, whose service is its tag. */\n  rootLength: number;\n}\n\n/** Every operation's plan, and every service's operations, by key (`${method} ${path}`), services in IR order. */\ninterface OperationPlan {\n  operations: Map<string, PlannedOperation>;\n  services: Map<string, string[]>;\n}\n\n/**\n * Settle the service and the name of every operation before any operation is\n * built, so an operation's models can follow the name it ends up with\n * (resolveReusedOperationIds). Each operation starts in the service its tag\n * or its path gives it (inferServiceName), under the name its `operationId`\n * gives it — settled once, `operationIdTransform` applied, before this pass\n * (readOperationIds) — or its method and path give it (inferOperationName).\n * Then a tagged service whose tag groups\n * operations from several first path segments — `/organizations` and\n * `/organization_domains` both tagged `organizations` — is split into one\n * service per segment, decided over the tagged operations alone, so an\n * untagged operation the service picked up by path never moves its tagged\n * siblings (splitTaggedServices); and the names within each service are made\n * unique, since several operations can take one name — several `list`\n * endpoints in `UserManagement`, for users, invitations and auth factors\n * (disambiguateOperationNames, whose warnings are given here).\n *\n * Both passes read nothing of an operation but its name, path and method,\n * so they run on stand-ins that carry those, and each operation built\n * afterwards takes the service and the name the passes gave its stand-in.\n */\nfunction planOperations(\n  paths: Record<string, PathItem>,\n  apiRoot: readonly string[],\n  operationIdNames: ReadonlyMap<string, string>,\n): OperationPlan {\n  const serviceMap = new Map<string, Operation[]>();\n  const started = new Map<Operation, { key: string; initialName: string }>();\n  // Service name each tagged operation was grouped under, keyed by operation\n  // identity, so a split-off service is traced back to the tag it came from.\n  const tagServiceByOperation = new Map<Operation, string>();\n  // Operations named from the method and path rather than an operationId.\n  // Only these may be renamed when names collide within a service (see\n  // disambiguateOperationNames); a name taken from an operationId is kept as is.\n  const pathNamed = new Set<Operation>();\n  for (const [path, pathItem] of Object.entries(paths)) {\n    for (const method of HTTP_METHODS) {\n      const op = pathItem[method];\n      if (!op) continue;\n      // The same reading the operation loop of extractOperations makes.\n      const tag = serviceTag(op.tags);\n      const apiRootLength = tag ? 0 : apiRootLengthOf(path, apiRoot);\n      const serviceName = inferServiceName(path, tag, apiRootLength);\n      const name = inferOperationName(method, path, operationIdNames.get(`${method} ${path}`), apiRootLength);\n      const stub = { name, path, httpMethod: method } as Operation;\n      started.set(stub, { key: `${method} ${path}`, initialName: name });\n      if (tag) tagServiceByOperation.set(stub, serviceName);\n      if (!op.operationId) pathNamed.add(stub);\n      const ops = serviceMap.get(serviceName) ?? [];\n      ops.push(stub);\n      serviceMap.set(serviceName, ops);\n    }\n  }\n\n  splitTaggedServices(serviceMap, tagServiceByOperation);\n  const rootLengthOf = (op: Operation) => (tagServiceByOperation.has(op) ? 0 : apiRootLengthOf(op.path, apiRoot));\n  for (const [serviceName, operations] of serviceMap) {\n    disambiguateOperationNames(operations, pathNamed, serviceName, rootLengthOf);\n  }\n\n  const operations = new Map<string, PlannedOperation>();\n  for (const [stub, { key, initialName }] of started) {\n    operations.set(key, { initialName, name: stub.name, rootLength: rootLengthOf(stub) });\n  }\n  const services = new Map(\n    [...serviceMap].map(([serviceName, stubs]) => [serviceName, stubs.map((stub) => started.get(stub)!.key)] as const),\n  );\n  return { operations, services };\n}\n\n/**\n * What a document tag contributes to the service it names. Both keys are\n * absent when the tag declares neither, so a declared-but-undocumented tag is\n * an empty record — still an entry in the index, which is what marks its\n * service as one that must not borrow another tag's wording.\n */\ninterface TagDocs {\n  description?: string;\n  externalDocs?: ExternalDocs;\n}\n\n/**\n * `base` with each doc field it lacks filled in from `extra`; a field `base`\n * already has is kept. The one rule for combining tag docs — among duplicate\n * tags in the index and among the tags a split-off service inherits from —\n * so `description` and `externalDocs` cannot resolve by different rules.\n */\nfunction fillMissingTagDocs(base: TagDocs, extra: TagDocs): TagDocs {\n  return { ...extra, ...base };\n}\n\n/**\n * Index the document's top-level `tags[]` by the service name each tag\n * produces, so a tag spelled `user_management`, `User Management`, or\n * `user-management` all map to the `UserManagement` service. Every named tag\n * is indexed — with its description when it declares a non-blank one, with\n * its `externalDocs` when it declares a usable one, and as an empty record\n * otherwise — because a declared-but-undocumented tag still marks its service\n * as one that must not borrow another tag's wording. When several tags\n * normalize to the same service name, each field is taken from the first of\n * them that gives it, so adding a link to one spelling never changes which\n * description the service shows.\n *\n * `parseSpec` ignored `tags` entirely before descriptions were read, so a\n * document with a malformed value — `tags` written as an object, a `null`\n * entry, a numeric `name` — used to parse and must keep parsing. Anything\n * that cannot be matched is skipped rather than thrown on, and a malformed\n * `externalDocs` is dropped the same way (see `readExternalDocs`).\n */\nfunction indexDocumentTags(documentTags: unknown): Map<string, TagDocs> {\n  const index = new Map<string, TagDocs>();\n  if (!Array.isArray(documentTags)) return index;\n  for (const tag of documentTags as unknown[]) {\n    if (typeof tag !== 'object' || tag === null) continue;\n    const { name, description, externalDocs } = tag as TagObject;\n    if (typeof name !== 'string' || name === '') continue;\n    const serviceName = toPascalCase(name);\n    const described = typeof description === 'string' && description.trim() !== '';\n    const docs: TagDocs = { ...(described ? { description } : {}), ...externalDocsEntry(externalDocs) };\n    index.set(serviceName, fillMissingTagDocs(index.get(serviceName) ?? {}, docs));\n  }\n  return index;\n}\n\n/**\n * Pick a service's docs — its `description` and `externalDocs` — from the\n * document's tags. Both fields go through this one path so they cannot\n * resolve to different tags by different rules.\n *\n * A service whose own name is a declared tag is documented by that tag alone:\n * its description and link when it has them, nothing otherwise. Another tag's\n * wording is never borrowed for it — operations tagged `api_keys` that the\n * path-prefix split merges into `UserManagement` must not label that service\n * \"API keys\".\n *\n * A service whose own name is not declared is one the split carved out of a\n * tag (e.g. `OrganizationDomains` from operations tagged `organizations`); it\n * inherits each field on its own from the first tag its operations carry that\n * gives it: the description of the first described tag, the link of the first\n * linked one, which need not be the same tag. Path-named services whose\n * operations have no tag carry nothing and stay undocumented.\n */\nfunction resolveServiceDocs(\n  serviceName: string,\n  operations: Operation[],\n  tagServiceByOperation: Map<Operation, string>,\n  declaredTags: Map<string, TagDocs>,\n): TagDocs {\n  const declared = declaredTags.get(serviceName);\n  if (declared !== undefined) return declared;\n  let docs: TagDocs = {};\n  for (const op of operations) {\n    const tagService = tagServiceByOperation.get(op);\n    if (tagService === undefined) continue;\n    const inherited = declaredTags.get(tagService);\n    if (inherited !== undefined) docs = fillMissingTagDocs(docs, inherited);\n  }\n  return docs;\n}\n\n/**\n * Words that mark where an API is mounted rather than naming a resource.\n * Deliberately tiny: `mountRules` regroup whatever this does not cover.\n */\nconst API_MARKER_SEGMENTS: ReadonlySet<string> = new Set(['api', 'rest']);\n\n/**\n * Whether a path segment marks the API root rather than naming a resource:\n * one of API_MARKER_SEGMENTS in any case, or a version such as `v1`,\n * `v2beta`, `1.0` or `2010-04-01`.\n */\nfunction isApiMarkerSegment(segment: string): boolean {\n  const lower = segment.toLowerCase();\n  return API_MARKER_SEGMENTS.has(lower) || /^v\\d/.test(lower) || /^\\d+([.-]\\d+)*$/.test(lower);\n}\n\n/** Leading literal segments of a path through its last API marker; `0` without one. */\nfunction pathRootLength(segments: readonly string[]): number {\n  let length = 0;\n  for (let i = 0; i < segments.length && !isParameterSegment(segments[i]); i++) {\n    if (isApiMarkerSegment(segments[i])) length = i + 1;\n  }\n  return length;\n}\n\n/**\n * The API root the document's untagged operations sit under, as path\n * segments: `['api', 'v1']` for a document whose untagged paths all start\n * with `/api/v1/`, `[]` when there is none. Untagged operations skip it when\n * their service and fallback name are taken from the path.\n *\n * Each untagged operation's path contributes its own root — its leading\n * literal segments through the last API marker (see isApiMarkerSegment), so\n * `/api/v1/notes` contributes `api/v1`, `/wiki/rest/api/content` contributes\n * `wiki/rest/api`, `/api/user_management/users` contributes `api` alone and\n * `/api/{tenant}/notes` contributes `api`, a parameter ending the run. The\n * document root is the longest marker-terminated prefix shared, compared\n * verbatim, by every contribution that no other contribution extends:\n * `/api/v1/…` beside `/api/v2/…` gives `api`, and `/v1/…` beside `/v2/…`\n * gives nothing, so the two versions stay apart instead of merging into one\n * service per resource. A contribution that is a prefix of another —\n * `/api/openapi.json` or `/api/admin/users` beside `/api/v1/notes` — does not\n * shorten the root to `api` for every path: it skips only its own `api`\n * (see apiRootLengthOf), and `/api/v1/notes` stays `Notes` rather than\n * landing in `V1`. Only a second version disagrees with the first, and that\n * alone is what needs the shorter root.\n *\n * A path with no marker at all (`/health`, `/openapi.json`) contributes\n * nothing: it sits outside any root and keeps its own first segment, and it\n * does not switch the root off for the rest of the document (see\n * apiRootLengthOf). A shared prefix without a marker is therefore kept whole\n * — `/user_management/users` and `/user_management/invitations` stay one\n * `UserManagement` service — because a module prefix every path shares is\n * the service, not noise, and nothing but the word tells it from `/api`.\n * Tagged operations never take part, since only path-named services use the\n * root; nor do path items that declare no operation.\n */\nfunction documentApiRoot(paths: Record<string, PathItem>): string[] {\n  const contributions: string[][] = [];\n  for (const [path, pathItem] of Object.entries(paths)) {\n    // Same read as the service naming above: a tag with a name names the service.\n    const hasUntaggedOperation = HTTP_METHODS.some((method) => {\n      const op = pathItem[method];\n      return Boolean(op) && serviceTag(op?.tags) === undefined;\n    });\n    if (!hasUntaggedOperation) continue;\n    const segments = pathSegments(path);\n    const own = segments.slice(0, pathRootLength(segments));\n    if (own.length > 0) contributions.push(own);\n  }\n  // Every strict prefix of a contribution, so a contribution another one\n  // extends can be left out. Segments never contain `/`, so the join is exact.\n  const extended = new Set<string>();\n  for (const own of contributions) {\n    for (let length = 1; length < own.length; length++) extended.add(own.slice(0, length).join('/'));\n  }\n  let root: string[] | undefined;\n  for (const own of contributions) {\n    if (extended.has(own.join('/'))) continue;\n    if (root === undefined) {\n      root = own;\n      continue;\n    }\n    root = root.slice(0, sharedPrefixLength(root, own));\n  }\n  if (root === undefined) return [];\n  return root.slice(0, pathRootLength(root));\n}\n\n/** How many leading segments two paths share, compared verbatim. */\nfunction sharedPrefixLength(a: readonly string[], b: readonly string[]): number {\n  let shared = 0;\n  while (shared < a.length && shared < b.length && a[shared] === b[shared]) shared++;\n  return shared;\n}\n\n/**\n * How many leading segments of a path are the document's API root: as much\n * of the path's own root (pathRootLength) as the document root shares,\n * compared verbatim. For a path that starts with the whole root that is the\n * root's length; for one that stops short of it — `/api/openapi.json` under a\n * root of `api/v1` — it is the path's own `api`, skipped for that path alone;\n * and `0` for a path outside the root, which is named as if the document had\n * none. The two roots are prefixes of one contribution whenever the path is\n * untagged, so what they share always ends on a marker.\n */\nfunction apiRootLengthOf(path: string, apiRoot: readonly string[]): number {\n  const segments = pathSegments(path);\n  return sharedPrefixLength(apiRoot, segments.slice(0, pathRootLength(segments)));\n}\n\n/**\n * Index of the segment a path-named service takes its name from, among the\n * segments readPath reads. Under an API root it is the first literal segment\n * after the root, so `/v1/notes` and `/v1/{teamId}/notes` both name `Notes`;\n * when nothing literal follows the root, the first segment, so `/api` and\n * `/api/{id}` name `Api` as they always did rather than `Default`. The\n * fallback operation name skips the same segment (see inferResourceFromPath),\n * so it is never echoed as `Api.getApi`.\n *\n * The verb of a custom method is not a resource and never names a service:\n * `/v1/{name}:cancel` stays in `V1` beside `/v1/{name}`, and `/api/v1:reset`\n * lands in `Api`, where the slash-written `/v1/{name}/cancel` names\n * `Cancel`. The resource it is written on is still found first when there is\n * one, so `/v1/pets:batchGet` names `Pets` like `/v1/pets`.\n *\n * Without a root (`apiRootLength` of 0: a root-less document, a path outside\n * the root, or a tagged operation) it is always the first segment, parameter\n * or not, so every such operation is named exactly as before this rule\n * existed: an untagged `/{tenant}/users` stays `Default.listUsers`.\n */\nfunction serviceSegmentIndex(path: string, apiRootLength: number): number {\n  if (apiRootLength === 0) return 0;\n  const index = readPath(path).findIndex(\n    (segment, i) => i >= apiRootLength && !isParameterSegment(segment.text) && !segment.customMethod,\n  );\n  return index === -1 ? 0 : index;\n}\n\n/**\n * The tag an operation's service is named from: the first entry of the\n * `tags` the IR carries (`extractTags`) that still has a name once\n * PascalCased, so `['-', 'Notes']` lands in `Notes` while `tags` keeps the\n * `-`. `undefined` when no entry has one: the operation is then named from\n * its path, as an untagged one is.\n */\nfunction serviceTag(tags: unknown): string | undefined {\n  return extractTags(tags)?.find((tag) => toPascalCase(tag) !== '');\n}\n\n/**\n * The service an operation belongs to: its first tag with a name\n * (`serviceTag`), else a path segment.\n *\n * The path fallback takes the first literal segment after the API root the\n * document sits under (`apiRootLength`, see documentApiRoot): `/widgets/{id}/sub`\n * is `Widgets`, and so are `/api/widgets` and `/api/{tenant}/widgets` when the\n * root is `/api`, instead of the whole API collapsing into one `Api` service.\n * When nothing literal follows the root — the path is the root itself, or\n * only parameters come next — the first segment names the service as it\n * always did, so `/api` and `/api/{id}` land in `Api` rather than in `Default`.\n * The verb of a custom method is read past (see serviceSegmentIndex), so\n * `/v1/{name}:cancel` lands in `V1` as well.\n */\nfunction inferServiceName(path: string, tag: string | undefined, apiRootLength: number): string {\n  // Prefer OpenAPI tag when available — tags represent the logical grouping\n  // (e.g., \"multi-factor-auth\" for /auth/factors/* endpoints).\n  if (tag) {\n    return toPascalCase(tag);\n  }\n  const first = pathSegments(path)[serviceSegmentIndex(path, apiRootLength)] ?? 'Default';\n  // Skip path params\n  if (isParameterSegment(first)) return 'Default';\n  return toPascalCase(first);\n}\n\n/**\n * The service a tagged operation is split off to, named from its first path\n * segment: `/organization_domains/{id}` → `OrganizationDomains`. A path whose\n * first segment is a parameter, or that has no segment at all (`/`), has\n * nothing to be split on and names the service it is already in, so\n * `/{tenant}/notes` beside `/notes` under one tag stays put.\n */\nfunction splitSegmentService(op: Operation, serviceName: string): string {\n  const first = pathSegments(op.path)[0];\n  return first === undefined || isParameterSegment(first) ? serviceName : toPascalCase(first);\n}\n\n/**\n * The service an operation lands in once the service it was grouped under\n * (`serviceName`: its tag, else the segment its path named) is known in full.\n *\n * A tagged operation moves to the service its own first segment names (see\n * splitSegmentService) only when the operations carrying its tag sit under\n * more than one first segment — `segmentServices`, the first-segment services\n * of that service's tagged operations alone. A tag whose operations all share\n * one first segment keeps them together even when that segment is not the\n * tag: `/api/v1/notes` tagged `notes` stays in `Notes`, not `Api`.\n *\n * An untagged operation keeps the service its path named: the segment it\n * would be split on is the one it was named from, so it can neither cause\n * nor prevent a split, nor be moved by one.\n */\nfunction resolveServiceName(\n  op: Operation,\n  serviceName: string,\n  tagged: boolean,\n  segmentServices: ReadonlySet<string>,\n): string {\n  if (!tagged || segmentServices.size <= 1) return serviceName;\n  return splitSegmentService(op, serviceName);\n}\n\n/**\n * Split each service whose tag groups operations from several first path\n * segments into one service per segment: `/organizations` and\n * `/organization_domains` both tagged `organizations` become `Organizations`\n * and `OrganizationDomains`. A part named like a service that already exists\n * — another tag's, or one named from a path — joins it.\n *\n * Every operation's destination is decided by resolveServiceName from the\n * grouping as it stands before any service is split, over each service's\n * tagged operations alone. So an untagged operation a tagged service picked\n * up by path — `/api/v1/notes/{noteId}/export` beside `/api/v1/notes` tagged\n * `notes` — does not add a second segment to the tag's set and move the\n * tagged operations into `Api` (issue #287), and operations a split moves\n * into another tag's service do not add a segment to that tag's set either,\n * whichever service the document lists first.\n *\n * Mutates `serviceMap`: a split service is removed and each of its parts is\n * appended under its own name, or merged into the existing service of that\n * name, in the order the parts first appear.\n */\nfunction splitTaggedServices(\n  serviceMap: Map<string, Operation[]>,\n  tagServiceByOperation: ReadonlyMap<Operation, string>,\n): void {\n  const plan = new Map<string, ServiceSplit>();\n  for (const [serviceName, operations] of serviceMap) {\n    const segmentServices = new Set<string>();\n    for (const op of operations) {\n      if (tagServiceByOperation.has(op)) segmentServices.add(splitSegmentService(op, serviceName));\n    }\n    const parts = new Map<string, Operation[]>();\n    for (const op of operations) {\n      const name = resolveServiceName(op, serviceName, tagServiceByOperation.has(op), segmentServices);\n      const part = parts.get(name) ?? [];\n      part.push(op);\n      parts.set(name, part);\n    }\n    plan.set(serviceName, { operations, own: operations.length, parts });\n  }\n  for (const [serviceName, { operations, own, parts }] of plan) {\n    if (parts.size <= 1) continue;\n    // Parts of services split before this one that joined it were appended to\n    // its array after the plan was read. They resolved to this service's name,\n    // so they stay in the part that keeps it instead of going with the array.\n    const joined = operations.slice(own);\n    if (joined.length > 0) parts.set(serviceName, [...(parts.get(serviceName) ?? []), ...joined]);\n    serviceMap.delete(serviceName);\n    for (const [name, ops] of parts) {\n      const existing = serviceMap.get(name) ?? [];\n      existing.push(...ops);\n      serviceMap.set(name, existing);\n    }\n  }\n}\n\n/** One service's split, planned from the grouping before any service is split (see splitTaggedServices). */\ninterface ServiceSplit {\n  /** The service's operations: the array `serviceMap` holds, which parts of services split earlier may join. */\n  operations: Operation[];\n  /** How many of `operations` the plan was read from; any beyond them joined since. */\n  own: number;\n  /** The service each operation moves to, with its operations in document order; one entry when nothing moves. */\n  parts: Map<string, Operation[]>;\n}\n\n/**\n * Strip overload indices (e.g. NestJS emits `Foo_bar[0]` when a controller\n * method handles multiple routes) from an operationId so derived names never\n * leak the bracketed digit. Without this, `authenticate[0]` would surface as\n * `authenticate0` in method names and `Authenticate0Request` in body model\n * names. Every marker at the end goes, whitespace after each included, so an\n * id that ends in several (`listPets[1][2]`, `listPets[2] [3]`) normalizes\n * to `listPets` and never keeps the first marker's digit (`listPets1`), and\n * one of nothing but markers (`[1][2]`) normalizes to `''` and names nothing\n * (readOperationIds), as `[1]` does (#565). Brackets at the end (or\n * with trailing whitespace) are common in NestJS-style backends; the rule is\n * intentionally narrow to avoid eating legitimate digits like `oauth2`: a\n * marker not at the end (`list[1]Pets`) is left as written, and so is the\n * whitespace before the first (`listPets [1]` keeps `listPets `).\n *\n * A marker is `[`, one or more ASCII digits and `]`, with any whitespace\n * after it (the code units `\\s` matches); nothing else is one, so `[]`,\n * `[1 ]`, `[ 1]` and `[1]-[2]` keep their last character. The id is read\n * once, from its end backwards, one marker at a time. A regex of the repeated\n * group (`/(?:\\[\\d+\\]\\s*)+$/`) retried the match from every marker of an id\n * that ends in something else, quadratic in the number of markers: sixteen\n * thousand of them before one letter stalled the parser for half a second,\n * and the parser reads an `operationId` of any length.\n */\nfunction normalizeOperationIdForNaming(operationId: string): string {\n  let end = operationId.length;\n  for (;;) {\n    // Whitespace is stripped only behind a marker: when none precedes it, it stays.\n    let i = end;\n    while (i > 0 && isWhitespace(operationId.charAt(i - 1))) i--;\n    if (i === 0 || operationId.charAt(i - 1) !== ']') break;\n    const digitsEnd = --i;\n    while (i > 0 && isAsciiDigit(operationId.charAt(i - 1))) i--;\n    if (i === digitsEnd || i === 0 || operationId.charAt(i - 1) !== '[') break;\n    end = i - 1;\n  }\n  return operationId.slice(0, end);\n}\n\n/** Whether one character is `0`–`9`: what `\\d` matches. */\nfunction isAsciiDigit(char: string): boolean {\n  return char >= '0' && char <= '9';\n}\n\n/** Whether one UTF-16 code unit is whitespace: what `\\s` matches, tested on that unit alone. */\nfunction isWhitespace(char: string): boolean {\n  return /\\s/.test(char);\n}\n\n/**\n * The inline request body, response or error body model name of an operation\n * that has an `operationId`. The single source of that name: extractRequestBody,\n * deriveResponseName, deriveFallbackResponseName and deriveErrorModelName use\n * it to name, resolvePathModelBaseNames and operationBodyModelNames to reserve.\n * Read with the `operationId` the operation's models are named from, which\n * the reuse of its own (resolveReusedOperationIds) or the contest of its\n * stem (resolveContestedOperationIdStems) may have taken from it, so no two\n * operations reach it with ids that clean to one stem (#627).\n */\nfunction operationIdModelName(operationId: string, suffix: string): string {\n  return cleanSchemaName(toPascalCase(normalizeOperationIdForNaming(operationId)) + suffix);\n}\n\n/**\n * The stem every model derived from an `operationId` starts with: its\n * `Request`, `Response` and `Error<code>` models, a list's `Item`, nested\n * inline models under those (`…ResponseOwner`) and envelope companions\n * (`…ListMetadata`). Every step of cleanSchemaName is a global replace or acts\n * on the leading word, so this is a true prefix of each of those names. Used\n * to reserve them all.\n */\nexport function operationIdModelBase(operationId: string): string {\n  return cleanSchemaName(toPascalCase(normalizeOperationIdForNaming(operationId)));\n}\n\n/**\n * What an `operationId` that names something names: what\n * `operationIdTransform` returns for it with its trailing overload markers\n * stripped, so the transform never has to know about NestJS-style `[0]`\n * suffixes, else that camelCased. The one place the transform is called,\n * once per operation (readOperationIds), which also reads its result: one\n * that names nothing drops the `operationId` instead of naming the operation\n * (#570).\n */\nfunction operationIdName(operationId: string, operationIdTransform: ((id: string) => string) | undefined): string {\n  const normalized = normalizeOperationIdForNaming(operationId);\n  return operationIdTransform ? operationIdTransform(normalized) : toCamelCase(normalized);\n}\n\n/**\n * An operation's name: what its `operationId` names, when it declares one\n * that names something (`operationIdName`, settled by readOperationIds before\n * any operation is planned), else a name built from its method and path.\n */\nfunction inferOperationName(\n  method: HttpMethod,\n  path: string,\n  nameFromId: string | undefined,\n  apiRootLength = 0,\n): string {\n  if (nameFromId !== undefined) return nameFromId;\n\n  // Fallback when no operationId is available — use method + path to build\n  // a descriptive name like \"listUsers\", \"getOrganization\", \"deleteAuthFactor\",\n  // \"getPetStatus\" for a singleton of one item, or \"adoptPet\" for an action.\n  return fallbackOperationName(method, path, apiRootLength);\n}\n\n/**\n * The name of an operation without an `operationId`, built from its method\n * and path. Three shapes, tried in this order:\n *\n *   - an action (inferAction): the action segment is the verb phrase and\n *     its resource follows — `POST /store/pets/{id}/adopt` is `adoptPet`,\n *     `DELETE /store/pets/bulk-delete` is `bulkDeletePets`, and\n *     `DELETE /pets/bulk-delete` in `Pets` is the bare `bulkDelete`;\n *   - a singleton of one item (inferSingleton): the method's item verb\n *     (inferVerb), the singular parent and the segment —\n *     `GET /store/pets/{id}/status` is `getPetStatus`;\n *   - otherwise the CRUD verb (inferVerb) plus the resource noun\n *     (inferResourceFromPath), singular for an item operation —\n *     `GET /store/pets/{id}` is `getPet` — or the verb alone when the path\n *     names no resource past the service segment: `GET /pets/{id}` in `Pets`\n *     is `get`.\n *\n * The parts of an action or singleton name are joined by appendQualifier,\n * so a word is never repeated across a join:\n * `GET /companies/verification/{id}/verification-status` is\n * `getVerificationStatus`.\n *\n * `actions` false skips the first shape, for an action that gave its name\n * up to an operationId on its path (demoteSamePathNames) or to the CRUD\n * operation that could have it (yieldActionNames):\n * `POST /store/pets/{id}/create` is then `createPetCreate`.\n */\nfunction fallbackOperationName(method: HttpMethod, path: string, apiRootLength: number, actions = true): string {\n  const action = actions ? inferAction(method, path, apiRootLength) : null;\n  if (action) return appendQualifier(toCamelCase(action.verb), action.resource);\n  const singleton = inferSingleton(path, apiRootLength);\n  if (singleton) {\n    return appendQualifier(appendQualifier(inferVerb(method, path), singleton.parent), singleton.resource);\n  }\n  const verb = inferVerb(method, path);\n  const resource = inferResourceFromPath(path, apiRootLength);\n  return resource ? toCamelCase(`${verb}_${resource}`) : verb;\n}\n\n/**\n * The name fallbackOperationName gave an item operation before its resource\n * was singularised: the resource as the path spells it, `getPets` for\n * `GET /store/pets/{id}`. `null` for an action (inferAction) and for a\n * singleton (inferSingleton), whose names are not built from a singularised\n * resource, and for an operation whose resource is not singularised — a\n * collection, a path with no resource, a segment that does not look plural —\n * so a non-null result always differs from the singular name.\n * disambiguateOperationNames falls back to it before a numeric suffix when\n * the singular name is an operationId's, or another path-named operation's\n * whose path differs only by that plural. `actions` is fallbackOperationName's.\n */\nfunction pluralFallbackName(method: HttpMethod, path: string, apiRootLength: number, actions = true): string | null {\n  if ((actions && inferAction(method, path, apiRootLength)) || inferSingleton(path, apiRootLength)) return null;\n  const resource = inferResourceFromPath(path, apiRootLength, false);\n  if (resource === null || resource === inferResourceFromPath(path, apiRootLength)) return null;\n  return toCamelCase(`${inferVerb(method, path)}_${resource}`);\n}\n\n/**\n * The name fallbackOperationName gives a singleton (inferSingleton) with its\n * parent as the path spells it rather than singular: `getPetsStatus` for\n * `GET /shop/pets/{id}/status`, whose name is `getPetStatus`, and that name\n * itself for a parent spelled singular, `GET /shop/pet/{id}/status`. `null`\n * for every other shape, an action among them. disambiguateOperationNames\n * falls back to it before a numeric suffix when the parent's plural is all\n * that tells two singletons apart. `actions` is fallbackOperationName's.\n */\nfunction writtenParentName(method: HttpMethod, path: string, apiRootLength: number, actions = true): string | null {\n  if (actions && inferAction(method, path, apiRootLength)) return null;\n  const singleton = inferSingleton(path, apiRootLength, false);\n  if (singleton === null) return null;\n  return appendQualifier(appendQualifier(inferVerb(method, path), singleton.parent), singleton.resource);\n}\n\n/**\n * The CRUD verb each HTTP method takes on one item and on a collection. Only\n * GET's differ: `get` for one item, `list` for a collection.\n */\nconst METHOD_VERBS: Record<HttpMethod, { readonly item: string; readonly collection: string }> = {\n  get: { item: 'get', collection: 'list' },\n  post: { item: 'create', collection: 'create' },\n  put: { item: 'update', collection: 'update' },\n  patch: { item: 'update', collection: 'update' },\n  delete: { item: 'delete', collection: 'delete' },\n  head: { item: 'check', collection: 'check' },\n  options: { item: 'options', collection: 'options' },\n  trace: { item: 'trace', collection: 'trace' },\n};\n\n/**\n * The verbs a POST on a literal with no parameter before it is read as an\n * action phrase by, when one of them is the segment's last word\n * (inferAction): the CRUD verbs of METHOD_VERBS. `options` and `trace` are\n * left out, since `/settings/display-options` names a collection.\n */\nconst CRUD_VERBS: ReadonlySet<string> = new Set(['get', 'list', 'create', 'update', 'delete', 'check']);\n\n/**\n * The verbs that count as a method's own only as the first word of a segment\n * (segmentCarriesVerb): `list-all` and `check-health` do something, while as\n * a later word `list` and `check` name a thing — `wish-list`, `allow-list`,\n * `health-check`. Every other verb counts in any position: `bulk-delete`,\n * `batch-get`, `force-update`, `auto-create`.\n */\nconst LEADING_ONLY_VERBS: ReadonlySet<string> = new Set(['list', 'check']);\n\n/**\n * Infer the CRUD verb from the HTTP method and the path shape (METHOD_VERBS):\n * the item verb when the path addresses one item — it ends in a path\n * parameter, or in a singleton of the item before it (isSingletonSegment) —\n * and the collection verb otherwise. `GET /pets/{id}` and\n * `GET /pets/{id}/status` are `get`; `GET /pets` and `GET /pets/{id}/photos`\n * are `list`. Not consulted for an action (inferAction), whose verb is the\n * action segment itself.\n */\nfunction inferVerb(method: HttpMethod, path: string): string {\n  const segments = pathSegments(path);\n  const last = segments[segments.length - 1];\n  const item = last !== undefined && (isParameterSegment(last) || isSingletonSegment(segments));\n  return item ? METHOD_VERBS[method].item : METHOD_VERBS[method].collection;\n}\n\n/** The verbs inferVerb can give a method: `get` and `list` for GET, one verb for every other. */\nfunction methodVerbs(method: HttpMethod): string[] {\n  const verbs = METHOD_VERBS[method];\n  return verbs.item === verbs.collection ? [verbs.item] : [verbs.item, verbs.collection];\n}\n\n/**\n * Whether the last segment of a path is a literal whose words include one of\n * the method's own verbs (methodVerbs): `bulk-delete` for a DELETE, `list-all`\n * and `batch-get` for a GET, `update-password` for a PUT or PATCH, and not\n * `bulk-delete` for a POST. `list` and `check` count only as the first word\n * (LEADING_ONLY_VERBS), so `wish-list`, `allow-list` and `health-check` carry\n * no verb. Such a segment is the action for that method (inferAction), and\n * for no method of another verb, declared beside it or not.\n */\nfunction segmentCarriesVerb(method: HttpMethod, path: string): boolean {\n  const segments = pathSegments(path);\n  const last = segments[segments.length - 1];\n  if (last === undefined || isParameterSegment(last)) return false;\n  const words = splitWords(last).map((w) => w.toLowerCase());\n  return methodVerbs(method).some((verb) => (LEADING_ONLY_VERBS.has(verb) ? words[0] === verb : words.includes(verb)));\n}\n\n/** Whether a path segment looks plural: singularizePathSegment would change it. */\nfunction looksPlural(segment: string): boolean {\n  return singularizePathSegment(segment) !== segment;\n}\n\n/**\n * Whether the last segment is a singleton of the item before it: a literal\n * that follows a path parameter and does not look plural (looksPlural), so it\n * names one thing about that item — `status` in `/pets/{id}/status`, `avatar`\n * in `/users/{id}/avatar` — rather than a nested collection of it\n * (`/pets/{id}/photos`, `/orgs/{id}/api_keys`).\n */\nfunction isSingletonSegment(segments: readonly string[]): boolean {\n  if (segments.length < 2) return false;\n  const last = segments[segments.length - 1];\n  return !isParameterSegment(last) && isParameterSegment(segments[segments.length - 2]) && !looksPlural(last);\n}\n\n/**\n * The noun a literal path segment contributes to an operation name. A\n * segment a path parameter follows addresses one item of its collection, so\n * it is singular (`singularizePathSegment`): `pets` in `/store/pets/{id}` is\n * `pet`. Any other segment is kept as the path spells it: `pets` in\n * `/store/pets`, `legacy` in `/users/{id}/legacy/factors`. The one rule for\n * the resource (inferResourceFromPath), the segments between the service and\n * the resource (inferDeeperContext) and the service noun a name restores\n * (inferServiceNoun), so `/store/cats/{id}/toys/{toyId}` and\n * `/api/notes/{noteId}` read `Cat` and `Note`, as `/store/pets/{id}` reads\n * `Pet`. The parent of an action or a singleton (inferItemParent) is singular\n * by that function's own rule, which does not look at the segment after it.\n */\nfunction pathSegmentNoun(segments: readonly string[], index: number): string {\n  const segment = segments[index];\n  return isParameterSegment(segments[index + 1] ?? '') ? singularizePathSegment(segment) : segment;\n}\n\n/**\n * Extract a resource noun from the path for operation naming.\n * Uses the last non-param segment (the resource being operated on). An item\n * operation — the last literal segment is followed by a path parameter —\n * addresses one entity, so its noun is singularised (pathSegmentNoun).\n *\n * Examples:\n *   /accounts/users → \"Users\"\n *   /accounts/users/{id} → \"User\" (singular for item operations)\n *   /accounts/users/{id}/auth_factors → \"AuthFactors\"\n *   /accounts/users/{id}/auth_factors/{factor_id} → \"AuthFactor\"\n *   /organizations/{id}/api_keys → \"ApiKeys\"\n *   /auth/authorize → \"Authorize\" (action endpoint)\n *   /teams/{id}/teams → \"Teams\" (the teams under one team, in `Teams`)\n *   /teams → null (the segment the service was named from)\n *\n * `apiRootLength` is the document's API root the path sits under (see\n * documentApiRoot); the service segment is the first literal one after it.\n * `singularItem` false keeps an item's noun as the path spells it (`Users`\n * for `/accounts/users/{id}`), for pluralFallbackName.\n */\nfunction inferResourceFromPath(path: string, apiRootLength = 0, singularItem = true): string | null {\n  const segments = pathSegments(path);\n  if (segments.length <= 1) return null;\n\n  // Find the last meaningful (non-param) segment past the API root, so a\n  // root word is never the resource: /api/v1/{id} is Api.delete, not deleteV1.\n  let resourceIndex = -1;\n  for (let i = segments.length - 1; i >= apiRootLength; i--) {\n    if (!isParameterSegment(segments[i])) {\n      resourceIndex = i;\n      break;\n    }\n  }\n\n  if (resourceIndex < 0) return null;\n  // Skip the segment the service was named from, compared by position — it\n  // would be redundant: /api/notes is Notes.list, not Notes.listNotes. A\n  // later segment that spells the same word names a resource of its own:\n  // /teams/{id}/teams in Teams is listTeams, the teams under one team, and\n  // never the bare `list` that reads as the service collection.\n  if (resourceIndex === serviceSegmentIndex(path, apiRootLength)) return null;\n\n  return toPascalCase(singularItem ? pathSegmentNoun(segments, resourceIndex) : segments[resourceIndex]);\n}\n\n/**\n * Index of the parent of a path's last segment, when that segment follows a\n * path parameter: the nearest literal before the parameter that is past the\n * document's API root (`apiRootLength`, see documentApiRoot) and is not an\n * API marker (isApiMarkerSegment) — the marker check also covers a tagged\n * operation, which has no root. `pets` in `/pets/{petId}/adopt` and in\n * `/owners/{o}/pets/{p}/vaccinate`; `-1` when no such literal exists, as in\n * `/api/v1/{companyId}/sendDocument` and `/{id}/adopt`. The parent is kept\n * even when it is the service segment: `/pets/{id}/archive` in `Pets` is\n * `archivePet` and `/pets/{id}/status` is `getPetStatus`, the names they\n * have under `/admin` in `Admin` too, so a name never depends on where the\n * service boundary falls.\n */\nfunction itemParentIndex(segments: readonly string[], apiRootLength: number): number {\n  for (let i = segments.length - 3; i >= apiRootLength; i--) {\n    if (!isParameterSegment(segments[i]) && !isApiMarkerSegment(segments[i])) return i;\n  }\n  return -1;\n}\n\n/**\n * The parent of a path's last segment (itemParentIndex) as a noun, singular\n * since the parameter addresses one of it: `Pet` for `/pets/{petId}/adopt`.\n * `null` when there is none. `singular` false keeps it as the path spells it\n * (`Pets`), for writtenParentName.\n */\nfunction inferItemParent(segments: readonly string[], apiRootLength: number, singular = true): string | null {\n  const index = itemParentIndex(segments, apiRootLength);\n  if (index < 0) return null;\n  return toPascalCase(singular ? singularizePathSegment(segments[index]) : segments[index]);\n}\n\n/**\n * Recognise a singleton of one item (isSingletonSegment) and the two nouns\n * its name is built from: the singular parent (inferItemParent) and the\n * segment itself, `Pet` and `Status` for `/pets/{id}/status`, which\n * fallbackOperationName joins after the method's item verb: `getPetStatus`,\n * `updatePetStatus`, `deletePetStatus`, `checkPetStatus`, and\n * `createOrderStatus` for `POST /orders/{id}/status`. A POST on a singleton\n * that does not end in `s` is an action instead (inferAction), so\n * `/users/{id}/avatar` is `getUserAvatar` for a GET but `avatarUser` for a\n * POST; give the POST an `operationId`. `singularParent` false keeps the\n * parent as the path spells it (`Pets`), for writtenParentName.\n */\nfunction inferSingleton(\n  path: string,\n  apiRootLength = 0,\n  singularParent = true,\n): { parent: string | null; resource: string } | null {\n  const segments = pathSegments(path);\n  if (!isSingletonSegment(segments)) return null;\n  return {\n    parent: inferItemParent(segments, apiRootLength, singularParent),\n    resource: toPascalCase(segments[segments.length - 1]),\n  };\n}\n\n/**\n * Recognise an action: the last segment is a literal that names what the\n * operation does rather than a resource, so it is the whole verb phrase of\n * the name and the method's CRUD verb is left off. Three shapes:\n *\n *   - a POST on a literal that follows a path parameter and does not end in\n *     `s`: `/pets/{petId}/adopt`, `/owners/{o}/pets/{p}/vaccinate`. A literal\n *     ending in `s` after the parameter is a nested collection to create into\n *     (`/orgs/{id}/api_keys`) or a singleton of the item (`/orders/{id}/status`,\n *     see inferSingleton), and keeps `create`;\n *   - for any method, a literal that carries the method's own verb\n *     (segmentCarriesVerb), which the name would otherwise repeat:\n *     `bulk-delete` on a DELETE, `list-all` on a GET, `update-password` on a\n *     PUT after a parameter. A literal that carries another method's verb is\n *     not: after a parameter it is a singleton, `GET /users/{id}/last-update`\n *     is `getUserLastUpdate`, and before none it is a collection,\n *     `GET /pets/update` is `listUpdate` and `GET /pets/last-update` is\n *     `listLastUpdate`;\n *   - a POST on a literal with no parameter before it whose last word is any\n *     CRUD verb (CRUD_VERBS): `POST /pets/health-check`. Such a literal is\n *     otherwise read as a collection (`/pets/search` is `createSearch`). The\n *     last word only, so `/pets/delete-candidates` stays a collection, and a\n *     POST only, since a verb that is not the method's own is not what the\n *     method does.\n *\n * A segment is one verb's action, whichever methods the document declares\n * on it: the verb it carries (segmentCarriesVerb), the first method's in\n * HTTP_METHODS order when it carries several, else POST's. A method of\n * another verb is never read as an action on it, so declaring the method\n * whose action it is takes no name from an operation already there:\n * `POST /pets/bulk-delete`, `POST /users/bulk-update` and\n * `POST /v1/pets:batchGet` carry DELETE's, PUT's and GET's verbs and are\n * `createBulkDelete`, `createBulkUpdate` and `createBatchGet`, and\n * `POST /users/{id}/update-password` is the singleton\n * `createUserUpdatePassword`, beside that method or not.\n *\n * The verb is the segment itself. The resource is the singular parent\n * (inferItemParent) when the segment follows a parameter — `adopt` + `Pet` —\n * and otherwise the collection the segment sits under, as\n * inferResourceFromPath reads the path without the segment, so\n * `DELETE /pets/bulk-delete` in `Pets` is the bare `bulkDelete` and\n * `DELETE /store/pets/bulk-delete` is `bulkDeletePets`. The caller leaves the\n * resource off when the verb already ends with it (`restart-id-verification`\n * under `verification` is `restartIdVerification`, see appendQualifier).\n *\n * A custom method written after a colon is read as the segment it is written\n * on followed by the verb (see pathSegments): `/pets/{petId}:adopt` is\n * `{petId}` then `adopt`, so it is the action `adoptPet` exactly as\n * `/pets/{petId}/adopt` is; `DELETE /pets:bulkDelete` is read as\n * `/pets/bulkDelete` and is `bulkDelete`; `/pets:search` is read as\n * `/pets/search` and stays a `create`.\n */\nfunction inferAction(\n  method: HttpMethod,\n  path: string,\n  apiRootLength = 0,\n): { verb: string; resource: string | null } | null {\n  const segments = pathSegments(path);\n  if (segments.length === 0) return null;\n  const last = segments[segments.length - 1];\n  if (isParameterSegment(last)) return null;\n  const afterParam = segments.length >= 2 && isParameterSegment(segments[segments.length - 2]);\n  const words = splitWords(last).map((w) => w.toLowerCase());\n  const postAction = method === 'post' && afterParam && !last.toLowerCase().endsWith('s');\n  const ownVerb = segmentCarriesVerb(method, path);\n  const verbPhrase = method === 'post' && !afterParam && words.length > 0 && CRUD_VERBS.has(words[words.length - 1]);\n  if (!postAction && !ownVerb && !verbPhrase) return null;\n  const owner = HTTP_METHODS.find((m) => segmentCarriesVerb(m, path)) ?? 'post';\n  if (inferVerb(owner, path) !== inferVerb(method, path)) return null;\n\n  const resource = afterParam\n    ? inferItemParent(segments, apiRootLength)\n    : inferResourceFromPath('/' + segments.slice(0, -1).join('/'), apiRootLength);\n  return { verb: last, resource };\n}\n\n/**\n * Detect and resolve name collisions within a service's operations.\n *\n * A name taken from an `operationId` is the author's choice and is never\n * rewritten here. A name derived from the method and path (inferOperationName)\n * is only as unique as the path words it was built from, so when operations on\n * different paths share one, the path-named operations are qualified until\n * every path in the service has a name of its own. Operations on one path\n * share a name only when both are path-named and their methods take the same\n * CRUD verb (PUT and PATCH both `update`); any other sharing on one path is\n * resolved first (demoteSamePathNames), before the qualifiers below, since\n * every consumer that keys a service's operations by name — the differ among\n * them — would otherwise see one of the two. An action that shares a name\n * with a path-named operation of another shape, or whose name one would have\n * on the path without the action's verb, yields next (yieldActionNames),\n * whether or not that operation is declared, so `update` stays with\n * `PUT /pets/{id}` and `PUT /pets/update` is `updatePets` in a document\n * with the item or without it. A name any pass gives an operation is\n * checked against every name the service holds, and once every pass has run\n * the one-path rule is checked once more (numberSamePathNames), since a\n * rename can land on a name an operation on the same path already has.\n *\n * `apiRootLengthOf` gives the API root each operation's path sits under (see\n * documentApiRoot), so neither the resource nor the deeper context echoes the\n * root or the service segment into a name: `DELETE /api/v1/notes/all` in\n * `Notes` is `deleteAll`, never `deleteAllV1Notes`. An action's resource and\n * deeper context are read from its path without the action segment, and a\n * singleton's without its parent (see qualifierPath), so a second `adoptPet`\n * or `getPetStatus` is qualified by what sets its path apart and never by\n * repeating `Adopt` or `Pet`.\n *\n * Qualifiers are tried in order, each on every group still colliding after\n * the one before, and every pass — the qualifiers, the plural and nothing\n * else — goes through one rule, qualifyGroup: a pass renames a group's\n * path-named members only when the names it proposes tell the group apart,\n * and a context two paths write alike is spelled alike for both (see the\n * deeper-context qualifier), so a qualifier the colliding paths all carry —\n * `Teams` in `/org/teams/members` and `/org/teams/{teamId}/members`, written\n * once, singular after `{teamId}` — is never added, and the next pass tells\n * them apart: `listMembers` and `listMembersByTeamId`; a proposal\n * another operation already has is not taken, so a pass never hands a member\n * a name another operation had with the number then landing on it\n * (`/org/members/archived` beside `/org/archived_members` is never\n * `listArchivedMembers2`, and `/api/notes` beside `operationId: listNotes` is\n * never `listNotes2`) — unless every operation that has it is path-named,\n * names the same noun and is one a later pass tells from the member, which\n * the member then joins (nameIsFree): `/notes` restoring `Notes` beside\n * `/notes/{noteId}/notes` is `listNotes` with the nested collection\n * `listNotesByNoteId`, while `/notes/notes`, whose path has nothing `/notes`\n * lacks, keeps `listNotes` and `/notes` is numbered on its plain name,\n * `list2`; and members whose proposals say the same thing take one spelling\n * and stay one group for the next pass, numbered on it when nothing after\n * tells them apart. A qualifier never puts the\n * same word twice in a row into a name, whether the name already ends with it\n * (`listNotes` never becomes `listNotesNotes`) or the qualifier repeats it\n * itself (`/api/analytics/analytics/teams` → `listTeamsAnalytics`), compared\n * word by word on the camelCase boundary rather than as a substring:\n *\n *   1. the resource noun (inferResourceFromPath); for the service's own\n *      path, whose plain name left that noun off, the service noun\n *      (inferServiceNoun) when a path-named operation outside the group\n *      already carries it under the name it would make and a later pass\n *      can tell the two apart, so that `/notes` beside `operationId: list`\n *      joins `/notes/{noteId}/notes` at `listNotes` and the parameter then\n *      tells them apart;\n *   2. the path segments between the service and the resource\n *      (inferDeeperContext), each singular when a path parameter follows it\n *      (pathSegmentNoun): `GET /users/{id}/legacy/factors` next to\n *      `GET /users/{id}/factors` → `listFactorsLegacy`, and\n *      `GET /store/cats/{id}/toys/{toyId}` next to\n *      `GET /store/dogs/{id}/toys/{toyId}` → `getToyCat` and `getToyDog`.\n *      A path whose singular spelling would take the name of an operation\n *      outside the group, or of another path in the group that the\n *      spelling as written sets apart, keeps the segments as written, the\n *      plural being what tells them apart: `/store/pets/{id}/toys/{toyId}`\n *      next to `/store/pet/{id}/toys/{toyId}` → `getToyPets` and\n *      `getToyPet`, and `/store/cats/{id}/toys/{toyId}` next to\n *      `operationId: getToyCat` → `getToyCats`;\n *   3. `By<Param>` for each path parameter the colliding paths do not all\n *      share, in path order, when those are what tell the paths apart:\n *      `GET /v1/notes` keeps `list` while `GET /v1/{teamId}/notes` becomes\n *      `listByTeamId`, with no root `GET /users/teams` keeps `listTeams` while\n *      `GET /users/{id}/teams` becomes `listTeamsById`, and\n *      `GET /api/notes/{noteId}` keeps `get` while\n *      `GET /api/{teamId}/notes/{noteId}` becomes `getByTeamId`, the shared\n *      `noteId` adding nothing;\n *   4. the API root words a path skipped beyond those the colliding rooted\n *      paths all skipped, when the paths sit under different lengths of the\n *      document root: `GET /api/notes` keeps `list` while `GET /api/v1/notes`\n *      becomes `listV1`. A root-less path takes no part;\n *   5. the resource noun the plain name left off because it names the\n *      service (inferServiceNoun), when the colliding paths do not all drop\n *      the same one. This is what tells a path-named operation from an\n *      operationId it collides with, which is never renamed and which the\n *      parameters above cannot touch: `GET /api/notes` beside\n *      `operationId: list` on `GET /api/{teamId}/notes` is `listNotes`.\n *      Singular for an item, as its resource would be:\n *      `GET /api/notes/{noteId}` beside `operationId: get` is `getNote`.\n *      Then an item still colliding because an operation outside the group\n *      has that singular name takes the noun as written, as a deeper\n *      segment does: `getNotes` beside `operationId: getNote` as well;\n *   6. for a path-named item operation whose singular name none of those\n *      could tell apart — `GET /store/pets/{id}` is `getPet`, and so is\n *      `operationId: getPet` on `/store/featured/{id}`, or path-named\n *      `GET /store/pet/{id}`, whose path differs only by the plural the\n *      singular erased — the plural name it had before item resources were\n *      singularised, `getPets` (pluralFallbackName), when no operation\n *      outside the group has it. The plural still says which collection is\n *      read, and it is the name every SDK generated from such a document\n *      already exposes, where a number says nothing. Like the qualifiers\n *      above it runs only when it tells the group apart: an operationId-named\n *      operation, an action, a singleton and a name a qualifier has already\n *      extended have no plural, so any member that has one differs from\n *      them, while a group whose members would all take the same plural\n *      (`/store/Pets/{id}` beside `/store/pets/{id}`) goes straight to the\n *      suffix, since `getPets` beside `getPet` would say nothing about\n *      which is which. Members that share a plural some other member does\n *      not take it together and are numbered on it: beside `/store/pet/{id}`\n *      or an operationId's `getPet`, those two are `getPets` and `getPets2`,\n *      each a variant of its twin rather than of the operationId. A\n *      singleton has one only beside another path-named singleton that\n *      writes its parent otherwise: the name carries the parent singular and\n *      the qualifiers read the path without it (qualifierPath), so the\n *      parent's plural is all that tells the two apart, and the singleton\n *      that writes it plural takes its name with the parent as written\n *      (writtenParentName) — `GET /shop/pets/{id}/status` beside\n *      `GET /shop/pet/{id}/status` is `getPetsStatus` and `getPetStatus`,\n *      as `getToyPets` and `getToyPet` are. Beside an operationId or an\n *      operation of another shape it has none and is numbered\n *      (`getPetStatus2`);\n *   7. a numeric suffix (`listNotes2`, `listNotes3`, …), when no pass above\n *      has a free name that tells the group apart, so an emitter never\n *      sees two methods with one name in one class. A name that already\n *      ends in a digit — the version the root words gave it (`listV1`), a\n *      path word (`listTop10`), an operationId (`getV2`) — takes the number\n *      behind `No` (numberedName): `GET /api/v1` beside `GET /api/v1/` is\n *      `listV1` and `listV1No2`, never `listV12`, which reads as version\n *      12. An operationId-named operation keeps the plain name over a\n *      path-named one; then the path\n *      that skipped the shorter root, so `/health` or a tagged `/notes` keeps\n *      `list` over `/api/health` or `/api/v1/notes`; otherwise the lexically\n *      first path keeps it, whatever the document order. The suffix is silent\n *      for a path-derived name, like a hashed inline model name; it comes\n *      with a warning when the document reuses an operationId, since that\n *      changes a name the author chose.\n *\n * Each qualifier depends only on the paths in the group, never on their\n * document order, and each runs once, so the result is deterministic.\n */\nfunction disambiguateOperationNames(\n  operations: Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  serviceName: string,\n  apiRootLengthOf: (op: Operation) => number,\n): void {\n  const rename = (op: Operation, name: string) => {\n    (op as { name: string }).name = name;\n  };\n  // The noun an operation's path names: its resource, or, for the service's\n  // own path, the service noun the plain name left off (`Notes` for `/notes`\n  // and for `/notes/{noteId}/notes` alike, `Note` for their items). What\n  // nameIsFree compares when another path-named operation holds a proposal.\n  const nounOf = (op: Operation): string | null => {\n    const root = apiRootLengthOf(op);\n    return inferResourceFromPath(op.path, root) ?? inferServiceNoun(op.path, root);\n  };\n  /** The names every operation of the service outside `group` has right now, operationIds included. */\n  const namesOutside = (group: Operation[]): ReadonlySet<string> => {\n    const members = new Set(group);\n    return new Set(operations.filter((op) => !members.has(op)).map((op) => op.name));\n  };\n  /** One pass on one group, through the rule every pass shares (qualifyGroup). */\n  const qualify = (group: Operation[], proposal: (op: Operation) => string) =>\n    qualifyGroup(group, operations, pathNamed, nounOf, apart, proposal, rename);\n\n  // One path first: the qualifiers below tell paths apart and leave a name\n  // shared on one path alone, so that sharing is settled before they run.\n  // Then, before they run (below, once `apart` is defined), an action beside\n  // a CRUD or singleton operation of its name, or one whose name such an\n  // operation would have, declared or not, yields it (yieldActionNames).\n  const demoted = demoteSamePathNames(operations, pathNamed, serviceName, apiRootLengthOf, rename);\n\n  // Each qualifier, given the group, is the word or words a path-named\n  // member would add to its name: `null` or `''` when its path has none.\n  const qualifiers: Array<(group: Operation[]) => (op: Operation) => string | null> = [\n    (group) => (op) => {\n      const root = apiRootLengthOf(op);\n      const resource = inferResourceFromPath(qualifierPath(op, root, !demoted.has(op)), root);\n      if (resource !== null) return resource;\n      // The service's own path left its noun off the plain name (`list` for\n      // `/notes`). It is proposed here, ahead of the service-noun pass, when a\n      // path-named operation outside the group already carries it under the\n      // name it would make — the nested collection of the same word,\n      // `/notes/{noteId}/notes` as `listNotes` — so the two take one spelling\n      // (nameIsFree) and the parameters tell them apart, `listNotes` and\n      // `listNotesByNoteId`, rather than the nested collection keeping the\n      // name the service's own path restores beside an operationId. Only\n      // when a later pass can (apart): `/notes/notes` has nothing `/notes`\n      // lacks, and joined the two would only be numbered.\n      const noun = inferServiceNoun(op.path, root);\n      if (noun === null) return null;\n      const name = appendQualifier(op.name, noun);\n      const held = operations.some((other) => !group.includes(other) && pathNamed.has(other) && other.name === name);\n      return held && nameIsFree(group, operations, pathNamed, nounOf, apart, op, name) ? noun : null;\n    },\n    (group) => {\n      // Singular, like the resource of an item operation, unless that\n      // spelling gives a path the name of an operation outside the group or\n      // of another path in the group whose spelling as written differs: the\n      // plural is then what tells them apart, so the path takes its context\n      // as written. `/store/pets/{id}/toys/{toyId}` beside\n      // `/store/pet/{id}/toys/{toyId}` is `getToyPets` and `getToyPet`, and\n      // `/store/cats/{id}/toys/{toyId}` beside `operationId: getToyCat` is\n      // `getToyCats`. As written, too, when another path in the group\n      // writes the same words but singularises them differently — `teams`\n      // in `/org/teams/members` and in `/org/teams/{teamId}/members` — so\n      // one spelling in the paths is one spelling in the names, `Teams` for\n      // both, which tells nothing apart (qualifyGroup) and leaves the\n      // parameters to do it: `listMembers` and `listMembersByTeamId`, never\n      // `listMembersTeams` beside `listMembersTeam` (issue #288). Two paths\n      // whose contexts agree in both spellings (`/orgs/teams/{id}/members`\n      // and `/orgs/{orgId}/teams/{id}/members`) stay singular and go on to\n      // the parameters together. Both spellings are read before any member\n      // is renamed, so the outcome does not depend on document order.\n      const outside = namesOutside(group);\n      const spelled = new Map(\n        group\n          .filter((op) => pathNamed.has(op))\n          .map((op) => {\n            const root = apiRootLengthOf(op);\n            const path = qualifierPath(op, root, !demoted.has(op));\n            return [\n              op,\n              {\n                singular: inferDeeperContext(path, root),\n                written: inferDeeperContext(path, root, false),\n                singularName: appendQualifier(op.name, inferDeeperContext(path, root)),\n                writtenName: appendQualifier(op.name, inferDeeperContext(path, root, false)),\n              },\n            ] as const;\n          }),\n      );\n      return (op) => {\n        const own = spelled.get(op);\n        if (own === undefined) return null;\n        const asWritten =\n          own.writtenName !== own.singularName &&\n          (outside.has(own.singularName) ||\n            [...spelled].some(\n              ([other, spelling]) =>\n                other.path !== op.path &&\n                (spelling.singularName === own.singularName) !== (spelling.writtenName === own.writtenName),\n            ));\n        return asWritten ? own.written : own.singular;\n      };\n    },\n    (group) => {\n      // Parameters only help when they differ between the colliding paths,\n      // so one every path carries is left out — `/api/notes/{noteId}` and\n      // `/api/{teamId}/notes/{noteId}` are told apart by `teamId` alone —\n      // and when none does, every proposal reads alike and qualifyGroup\n      // skips the pass: `/v1/{id}/notes` and `/v1/{id}/Notes` would both\n      // gain `ById` and still collide, further from the plain name. Every\n      // path-named operation takes part, under an API root or not: a service\n      // must not hand an emitter two methods with one name.\n      const shared = sharedPathParams(group.map((op) => op.path));\n      return (op) => inferByParamsSuffix(op.path, shared);\n    },\n    (group) => {\n      // Paths under the document root that skipped different lengths of it\n      // differ by a version or mount word the plain name left off: `/api/notes`\n      // beside `/api/v1/notes` in `Notes`. The words a path skipped beyond the\n      // root the rooted paths all share are what tell them apart (`listV1`),\n      // the one place a root word belongs in a name. A root-less path — outside\n      // the root, or tagged — is named as if the document had none and takes\n      // no part; it keeps the plain name in the numeric pass instead.\n      const rooted = group.map((op) => pathSegments(op.path).slice(0, apiRootLengthOf(op))).filter((r) => r.length > 0);\n      let shared = rooted[0] ?? [];\n      for (const root of rooted) shared = shared.slice(0, sharedPrefixLength(shared, root));\n      return (op) => toPascalCase(pathSegments(op.path).slice(shared.length, apiRootLengthOf(op)).join('_'));\n    },\n    () => (op) => {\n      // The plain name leaves off the resource noun that names the service\n      // (`GET /api/notes` in `Notes` is `list`); it is restored when it is\n      // what tells the group apart. An operationId-named operation is never\n      // renamed, so it contributes nothing here: next to `operationId: list`\n      // on `/api/{teamId}/notes`, path-named `/api/notes` becomes\n      // `listNotes`. When every path drops the same noun (`/notes` and\n      // `/api/v1/notes`), restoring it would only move the collision, and\n      // qualifyGroup skips the pass.\n      return inferServiceNoun(op.path, apiRootLengthOf(op));\n    },\n    (group) => {\n      // An item the pass above left colliding, because its singular noun\n      // gives it the name of an operation outside the group, takes the noun\n      // as written, as a deeper segment does: `/api/notes/{noteId}` beside\n      // `operationId: get` and `operationId: getNote` is `getNotes`. Not in\n      // the pass above, where the item's `Notes` could match a collection's\n      // beside it and tell neither apart.\n      const outside = namesOutside(group);\n      return (op) => {\n        const root = apiRootLengthOf(op);\n        const taken = outside.has(appendQualifier(op.name, inferServiceNoun(op.path, root)));\n        return taken ? inferServiceNoun(op.path, root, false) : null;\n      };\n    },\n  ];\n\n  // The plural a member could take back: none for an operationId-named\n  // operation, and for a path-named one only while its name is still the one\n  // it was built with — no qualifier above has extended it. Like every pass,\n  // only when it tells the group apart: beside an operationId, which has no\n  // plural, or beside a path that spells the resource singular\n  // (`/store/pet/{id}`). The plural is compared as written, since its number\n  // is the whole point; members that would all take the same plural are left\n  // to the numeric suffix.\n  const pluralOf = (op: Operation): string | null => {\n    const root = apiRootLengthOf(op);\n    const actions = !demoted.has(op);\n    if (op.name !== fallbackOperationName(op.httpMethod, op.path, root, actions)) return null;\n    return pluralFallbackName(op.httpMethod, op.path, root, actions);\n  };\n\n  // The plural of a singleton in `group`: its name with the parent as the\n  // path writes it (writtenParentName), `getPetsStatus` for\n  // `/shop/pets/{id}/status`, while its name is still the one it was built\n  // with. Only when another path-named singleton of the group writes the\n  // parent otherwise (`/shop/pet/{id}/status`): the qualifiers read a\n  // singleton's path without its parent (qualifierPath), so its plural is\n  // all that tells the two apart. Only path-named singletons take part (an\n  // operationId-named member does not, as in the deeper-context pass), so\n  // beside an operationId or an operation of another shape a singleton keeps\n  // its name and is numbered, as before.\n  const parentAsWritten = (group: Operation[]): ((op: Operation) => string | null) => {\n    const written = new Map<Operation, string>();\n    for (const op of group) {\n      if (!pathNamed.has(op)) continue;\n      const root = apiRootLengthOf(op);\n      const actions = !demoted.has(op);\n      const name = writtenParentName(op.httpMethod, op.path, root, actions);\n      if (name !== null && op.name === fallbackOperationName(op.httpMethod, op.path, root, actions)) {\n        written.set(op, name);\n      }\n    }\n    return (op) => {\n      const own = written.get(op);\n      return own !== undefined && own !== op.name && [...written.values()].some((name) => name !== own) ? own : null;\n    };\n  };\n\n  // Whether a later pass would tell `op`, once it has `name`, from `other`,\n  // a path-named operation of its noun that has it — what joining `other`\n  // there counts on (nameIsFree). One of the qualifiers after the first,\n  // which proposes such a join, run on the two alone, must give one of them\n  // a name no other operation has (`listNotesByNoteId` for\n  // `/notes/{noteId}/notes` beside `/notes`), or the plural must, which\n  // `other` can still take back and `op`, its name extended, cannot.\n  // Otherwise the two could only be numbered, the number landing on the name\n  // one of them had: `/notes/notes` has nothing `/notes` lacks, and\n  // `/notes/archive/notes` nothing but a `listNotesArchive` an operationId\n  // may hold.\n  const apart = (op: Operation, other: Operation, name: string): boolean => {\n    const free = (next: string) => next !== name && !operations.some((x) => x !== op && x !== other && x.name === next);\n    const plural = pluralOf(other);\n    return (\n      (plural !== null && free(plural)) ||\n      qualifiers.slice(1).some((qualifier) => {\n        const words = qualifier([op, other]);\n        const [own, theirs] = [appendQualifier(name, words(op)), appendQualifier(name, words(other))];\n        return own !== theirs && (free(own) || free(theirs));\n      })\n    );\n  };\n\n  // An action beside a CRUD or singleton operation of its name, or one whose\n  // name such an operation would have, declared or not: the plain name stays\n  // with the latter, which the qualifiers would rename. It asks `apart`\n  // whether a name a path-named operation holds can be joined, as the\n  // qualifiers ask it, so it runs once `apart` is defined.\n  yieldActionNames(operations, pathNamed, demoted, apiRootLengthOf, apart, rename);\n\n  for (const qualifier of qualifiers) {\n    for (const group of collidingGroups(operations)) {\n      const words = qualifier(group);\n      qualify(group, (op) => appendQualifier(op.name, words(op)));\n    }\n  }\n\n  for (const group of collidingGroups(operations)) {\n    // Like every qualifier, only when it tells the group apart: beside an\n    // operationId, which has no plural, or beside a path that spells the\n    // resource singular (`/store/pet/{id}`). Members that would all take the\n    // same plural are left to the numeric suffix. A plural is blocked by any\n    // name outside the group, an operationId's (`operationId: getPets`) or a\n    // path-named operation's (`PUT /shop/archive/pets` beside\n    // `PUT /shop/pets/{id}`): no qualifier is left to tell a member from an\n    // operation whose name it joined (nameIsFree, `apart`), so the join would\n    // only put a number on the name that operation had. Members that share a\n    // plural some other member does not (`/store/Pets/{id}` and\n    // `/store/pets/{id}` beside `/store/pet/{id}`) take it together and are\n    // numbered below, `getPets` and `getPets2` — the names such a document\n    // produced before item resources were singularised. Two groups never\n    // share a plural: it is the group's singular name with the resource as\n    // written, so one plural means one singular name, and one group. A\n    // singleton's parent as written follows the same rule\n    // (parentAsWritten): `/shop/Pets/{id}/status` and `/shop/pets/{id}/status`\n    // beside `/shop/pet/{id}/status` are `getPetsStatus` and `getPetsStatus2`.\n    const respelled = parentAsWritten(group);\n    const proposal = (op: Operation) => pluralOf(op) ?? respelled(op) ?? op.name;\n    qualifyGroup(group, operations, pathNamed, nounOf, () => false, proposal, rename);\n  }\n\n  const taken = new Set(operations.map((op) => op.name));\n  for (const group of collidingGroups(operations)) {\n    const name = group[0].name;\n    // An operationId-named operation outranks a path-named one for the plain\n    // name; then the path that skipped the shorter API root, so a root-less\n    // path (`/health`, or a tagged `/notes`) keeps the name it has always had\n    // over `/api/health` or `/api/v1/notes`; within that the lexically first\n    // path wins. The outcome never depends on document order, and operations\n    // on one path share it.\n    const rank = (op: Operation) => (pathNamed.has(op) ? 1 : 0);\n    const ordered = [...group].sort(\n      (a, b) => rank(a) - rank(b) || apiRootLengthOf(a) - apiRootLengthOf(b) || comparePaths(a, b),\n    );\n    const keeper = ordered[0];\n    const nameByPath = new Map<string, string>([[keeper.path, name]]);\n    for (const op of ordered) {\n      let next = nameByPath.get(op.path);\n      if (next === undefined) {\n        next = suffixedName(name, taken);\n        taken.add(next);\n        nameByPath.set(op.path, next);\n        // A path-derived name is the parser's own and is refined silently,\n        // like a hashed inline model name. A name the document chose is only\n        // changed when the document reuses it, which is worth saying.\n        if (!pathNamed.has(op)) {\n          console.warn(\n            `[oagen] Warning: Operations ${keeper.httpMethod.toUpperCase()} ${keeper.path} and ` +\n              `${op.httpMethod.toUpperCase()} ${op.path} in service ${serviceName} both take the name ` +\n              `\"${name}\" from their operationId; the latter is renamed \"${next}\" — give each a distinct operationId`,\n          );\n        }\n      }\n      rename(op, next);\n    }\n  }\n\n  // Once more on one path, after every pass: a rename above can land on a\n  // name an operation on the same path holds (see numberSamePathNames).\n  numberSamePathNames(operations, pathNamed, rename);\n}\n\n/**\n * Give operations on one path distinct names when their methods take\n * different CRUD verbs. Two operations on one path share a name only when\n * both are path-named and their methods take the same verb (inferVerb): PUT\n * and PATCH are both `update`, so `/pets/{id}` has one `updatePet` for the\n * two, as it always has. Any other sharing hides one of the two from every\n * consumer that keys a service's operations by name, such as the differ.\n * Two path-named operations of different verbs never share an action name,\n * since a segment is one verb's action whichever methods the document\n * declares on it (inferAction): `POST /pets/bulk-delete` is\n * `createBulkDelete`, beside `DELETE /pets/bulk-delete`'s `bulkDelete` or\n * not. What is left is an operationId on the path.\n *\n * An operationId-named operation keeps its name, since that name is the\n * author's, and every path-named operation that shares it steps aside\n * whatever its verb, taking the name it has without the action rule\n * (fallbackOperationName with `actions` false): `POST /pets/{id}/adopt`\n * beside `operationId: adoptPet` on the GET is the singleton\n * `createPetAdopt`. Should two path-named operations of different verbs share\n * a name on one path — the fallback names give none — the first in\n * HTTP_METHODS order keeps it and the other steps aside the same way. When\n * the name an operation falls back to is still held on the path by an\n * operationId or by another verb — path-named PATCH `updatePet` beside\n * `operationId: updatePet` on the PUT has no action to drop — a numeric\n * suffix free in the service is added, silently, as the\n * numeric pass adds one and spelled as it spells it (numberedName:\n * `updatePet2`, and `updateTop10No2` for a PATCH on `/store/top10/{id}`\n * beside `operationId: updateTop10`). Two operationId-named operations on\n * one path with one name are the document reusing an operationId: the first\n * in HTTP_METHODS order keeps it and the rest are numbered with the warning\n * the numeric pass gives that case. Paths are visited in lexical order and\n * their operations in HTTP_METHODS order, so the result depends only on the\n * document's paths and methods.\n *\n * Returns the path-named operations that gave an action name up, whose\n * qualifiers and plural read their path as the shape they fell back to.\n */\nfunction demoteSamePathNames(\n  operations: Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  serviceName: string,\n  apiRootLengthOf: (op: Operation) => number,\n  rename: (op: Operation, name: string) => void,\n): Set<Operation> {\n  const demoted = new Set<Operation>();\n  const taken = new Set(operations.map((op) => op.name));\n  const verbOf = (op: Operation) => inferVerb(op.httpMethod, op.path);\n\n  for (const onPath of operationsByPath(operations).values()) {\n    const byName = new Map<string, Operation[]>();\n    for (const op of onPath) byName.set(op.name, [...(byName.get(op.name) ?? []), op]);\n    for (const [name, sharing] of byName) {\n      if (sharing.length < 2) continue;\n      const explicit = sharing.filter((op) => !pathNamed.has(op));\n      for (const op of explicit.slice(1)) {\n        const next = suffixedName(name, taken);\n        console.warn(\n          `[oagen] Warning: Operations ${explicit[0].httpMethod.toUpperCase()} ${explicit[0].path} and ` +\n            `${op.httpMethod.toUpperCase()} ${op.path} in service ${serviceName} both take the name ` +\n            `\"${name}\" from their operationId; the latter is renamed \"${next}\" — give each a distinct operationId`,\n        );\n        rename(op, next);\n        taken.add(next);\n      }\n      // `sharing` is in HTTP_METHODS order (operationsByPath).\n      const keeper = explicit.length > 0 ? null : sharing[0];\n      const keptVerb = keeper === null ? null : verbOf(keeper);\n      for (const op of sharing) {\n        if (!pathNamed.has(op) || verbOf(op) === keptVerb) continue;\n        const base = fallbackOperationName(op.httpMethod, op.path, apiRootLengthOf(op), false);\n        // Still held on the path by an operationId or another verb? Number it.\n        const held = onPath.some(\n          (other) => other !== op && other.name === base && (!pathNamed.has(other) || verbOf(other) !== verbOf(op)),\n        );\n        const next = held ? suffixedName(base, taken) : base;\n        if (next !== op.name) {\n          rename(op, next);\n          taken.add(next);\n        }\n        demoted.add(op);\n      }\n    }\n  }\n  return demoted;\n}\n\n/**\n * Keep the plain CRUD name with the CRUD operation an action could take it\n * from. `PUT /pets/update` is the action `update` — its collection `pets` is\n * the service segment, which a name leaves off — and so is `PUT /pets/{id}`.\n * Left to the qualifiers, the pair would be told apart by `By<Param>`, which\n * renames the PUT on the item to `updateById`, and code calling `update`\n * would then reach `PUT /pets/update`. Renaming the action only once the\n * other is declared would not do either: a document that adds `PUT /pets/{id}`\n * would hand it the action's name, and `oagen diff` would read the addition\n * as the action changing path. So before the qualifiers run, a path-named\n * action is renamed alone, whether or not the other operation is declared,\n * when its name is the one its method gives the path without the verb its\n * segment starts with (verblessName): `update` for `PUT /pets/update`, as\n * `PUT /pets` is. So is any other path-named action that shares its name\n * with a path-named operation of another shape — a CRUD operation or a\n * singleton, for which inferAction is null, a demoted action among them. It\n * takes back the collection it dropped, the service noun of the path the\n * action segment sits on (inferServiceNoun of qualifierPath): `updatePets`,\n * `createPets` for `POST /pets/create` (`POST /pets` is `create`),\n * `listAllPets` for `GET /pets/list-all` (`GET /pets/all` is `listAll`).\n * When that adds nothing — the name already ends with it, or there is none,\n * as for `POST /store/pets/{id}/create` (`createPet`, as\n * `POST /store/pets/{id}` is) and `POST /store/pets/create` (`createPets`, as\n * `POST /store/pets` is) — it takes the name it has without the action rule\n * (`createPetCreate`, `createCreate`) and is read from then on as that\n * shape, like a demoted action (demoteSamePathNames). A name another\n * operation holds is skipped, and with both held it is numbered on the\n * latter (`createCreate2` when operationIds hold `createPets` and\n * `createCreate`), as it is when both are its own name (`update2` for\n * `PUT /{id}/update`, which has no collection to take back and whose\n * `PUT /{id}` is `update`). Two kinds of name are not held. The name of\n * another action still to yield here, which gives it up in its turn:\n * `POST /pets/create` takes `createPets` beside `POST /pets/create-pets`,\n * whose `createPets` yields to `createCreatePets`, so no operation is left\n * with a name neither had. And a name held only by path-named operations\n * on other paths naming the noun the action names that a later pass tells\n * from it (nameIsFree with `apart`, the rule by which a qualifier joins such\n * a name): `POST /pets/create` takes `createPets` beside\n * `POST /pets/{id}/pets`, and the parameter then tells the two apart,\n * `createPets` and `createPetsById`, as it tells `POST /pets/pets` from\n * `POST /pets/{id}/pets`; beside `POST /pets/pets`, whose path has nothing\n * `/pets` lacks, the name counts as held and the action is `createCreate`.\n * Declaring either operation beside the action thus never takes its name\n * from it. An action beside an operationId of its name is left to the\n * numeric pass (`adoptPet2`), and two actions of one name to the qualifiers\n * (`adoptPetRescue`). Actions come in name order, then path order, and the\n * renames depend only on each operation's own path, so the result is\n * deterministic. An action that fell back to its non-action name is added\n * to `demoted`, as it is renamed, so every pass after — `apart` among them,\n * asked here for the actions still to come — reads its path as that shape.\n */\nfunction yieldActionNames(\n  operations: Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  demoted: Set<Operation>,\n  apiRootLengthOf: (op: Operation) => number,\n  apart: (op: Operation, other: Operation, name: string) => boolean,\n  rename: (op: Operation, name: string) => void,\n): void {\n  const isAction = (op: Operation) =>\n    pathNamed.has(op) && !demoted.has(op) && inferAction(op.httpMethod, op.path, apiRootLengthOf(op)) !== null;\n  const meeting = new Set(\n    collidingGroups(operations)\n      .filter((group) => group.some((op) => pathNamed.has(op) && !isAction(op)))\n      .flatMap((group) => group.filter(isAction)),\n  );\n  const yielding = operations.filter(\n    (op) => meeting.has(op) || (isAction(op) && verblessName(op.httpMethod, op.path, apiRootLengthOf(op)) === op.name),\n  );\n  yielding.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0) || comparePaths(a, b) || methodOrder(a, b));\n  // The actions still to yield, whose current names every one of them gives up.\n  const pending = new Set(yielding);\n  // Every other name the service holds, kept current as actions are renamed,\n  // so a rename never lands on a name another operation already has — least\n  // of all one on the action's own path, which no later pass looks at again.\n  const taken = new Set(operations.filter((op) => !pending.has(op)).map((op) => op.name));\n  // The noun an operation names, read as the shape it has now (qualifierPath):\n  // an action by the path its segment sits on (`Pets` for `/pets/create`),\n  // one that fell back by its whole path. What nameIsFree compares with the\n  // noun a path-named operation holding a name names.\n  const nounOf = (op: Operation): string | null => {\n    const root = apiRootLengthOf(op);\n    const path = qualifierPath(op, root, !demoted.has(op));\n    return inferResourceFromPath(path, root) ?? inferServiceNoun(path, root);\n  };\n  // The name each path and verb yielded to, which PUT and PATCH on one path share.\n  const yieldedOnPath = new Map<string, string>();\n  for (const op of yielding) {\n    pending.delete(op);\n    const root = apiRootLengthOf(op);\n    const qualified = appendQualifier(op.name, inferServiceNoun(qualifierPath(op, root), root));\n    const plain = fallbackOperationName(op.httpMethod, op.path, root, false);\n    const onPath = `${inferVerb(op.httpMethod, op.path)} ${op.path}`;\n    const free = (name: string) =>\n      name !== op.name &&\n      (!taken.has(name) || nameIsFree([op, ...pending], operations, pathNamed, nounOf, apart, op, name));\n    let next = yieldedOnPath.get(onPath);\n    if (next === undefined && free(qualified)) next = qualified;\n    if (next === undefined) {\n      // Read from here on as the shape it falls back to, by `apart` too.\n      demoted.add(op);\n      // Numbered when both are held, the CRUD operation declared or not, so\n      // declaring it later never moves the action to a number.\n      next = free(plain) ? plain : suffixedName(plain, taken);\n    }\n    yieldedOnPath.set(onPath, next);\n    rename(op, next);\n    taken.add(next);\n    if (next !== qualified) demoted.add(op);\n  }\n}\n\n/**\n * The name an action's method gives its path with the method's verb that\n * the action segment starts with taken off — the whole segment when it is\n * that verb alone: `create` (`POST /pets`) for `POST /pets/create`, `listAll`\n * (`GET /pets/all`) for `GET /pets/list-all`, `createPet`\n * (`POST /store/pets/{id}`) for `POST /store/pets/{id}/create`. `null` when\n * the segment does not start with one of the method's verbs (methodVerbs):\n * `bulk-delete`, `adopt`, `force-update`, and when the segment is the one\n * its service is named from (serviceSegmentIndex), so the path without it\n * sits in another service: `POST /create`, and `PUT /v1/{id}/update`\n * under a `/v1` root, whose `PUT /v1/{id}` is in `V1`. A bare parameter\n * before the segment is no other service: `PUT /{id}/update` and\n * `PUT /{id}` are both in `Default`. GET's item verb reads one item, so\n * `get` is what GET gives an item of what is left: `get` (`GET /pets/{id}`)\n * for `GET /pets/get`. An action whose name this is shares it with an\n * operation the document may declare, and yields it whether or not it\n * does (yieldActionNames).\n */\nfunction verblessName(method: HttpMethod, path: string, apiRootLength: number): string | null {\n  const segments = pathSegments(path);\n  const [verb, ...rest] = splitWords(segments[segments.length - 1] ?? '');\n  const word = verb?.toLowerCase();\n  if (word === undefined || !methodVerbs(method).includes(word)) return null;\n  if (serviceSegmentIndex(path, apiRootLength) === segments.length - 1) return null;\n  const twin = rest.length > 0 ? [...segments.slice(0, -1), rest.join('-')] : segments.slice(0, -1);\n  if (word !== METHOD_VERBS[method].collection && !twin[twin.length - 1].startsWith('{')) twin.push('{id}');\n  return fallbackOperationName(method, '/' + twin.join('/'), apiRootLength);\n}\n\n/**\n * The last check on one path, after every pass has run. Each pass renames\n * path-named operations, and a new name can be one another operation on the\n * same path already holds: the service noun restored to `GET /api/notes`\n * beside `operationId: list` on `/api/{teamId}/notes` is `listNotes`, which\n * `POST /api/notes` may carry as its operationId. No pass after the first\n * looks at one path again, since collidingGroups leaves a name shared on one\n * path alone, so the sharing rule of demoteSamePathNames is applied once\n * more here: a path-named operation that shares its name with an\n * operationId-named operation on its path, or with a path-named one of\n * another CRUD verb, takes the first numeric suffix free in the service,\n * silently, as the numeric pass numbers a path-named operation. The keeper is\n * the operationId-named operation, else the first path-named one in\n * HTTP_METHODS order.\n */\nfunction numberSamePathNames(\n  operations: Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  rename: (op: Operation, name: string) => void,\n): void {\n  const taken = new Set(operations.map((op) => op.name));\n  const verbOf = (op: Operation) => inferVerb(op.httpMethod, op.path);\n  for (const onPath of operationsByPath(operations).values()) {\n    const byName = new Map<string, Operation[]>();\n    for (const op of onPath) byName.set(op.name, [...(byName.get(op.name) ?? []), op]);\n    for (const [name, sharing] of byName) {\n      if (sharing.length < 2) continue;\n      const keeper = sharing.find((op) => !pathNamed.has(op)) ?? sharing[0];\n      for (const op of sharing) {\n        if (op === keeper || !pathNamed.has(op)) continue;\n        if (pathNamed.has(keeper) && verbOf(op) === verbOf(keeper)) continue;\n        const next = suffixedName(name, taken);\n        rename(op, next);\n        taken.add(next);\n      }\n    }\n  }\n}\n\n/**\n * The operations of a service grouped by path, paths in lexical order and\n * each path's operations in HTTP_METHODS order, so a pass over them depends\n * only on the document's paths and methods, never on its order.\n */\nfunction operationsByPath(operations: Operation[]): Map<string, Operation[]> {\n  const byPath = new Map<string, Operation[]>();\n  for (const op of operations) byPath.set(op.path, [...(byPath.get(op.path) ?? []), op]);\n  return new Map([...byPath.keys()].sort().map((path) => [path, (byPath.get(path) ?? []).sort(methodOrder)]));\n}\n\n/** Operations in HTTP_METHODS order (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE). */\nfunction methodOrder(a: Operation, b: Operation): number {\n  return HTTP_METHODS.indexOf(a.httpMethod) - HTTP_METHODS.indexOf(b.httpMethod);\n}\n\n/**\n * `base` with the first numeric suffix, from 2, that no name in `taken` has,\n * spelled by numberedName: `updatePet2`, and `updateTop10No2` for a base\n * that ends in a digit.\n */\nfunction suffixedName(base: string, taken: ReadonlySet<string>): string {\n  let n = 2;\n  while (taken.has(numberedName(base, n))) n++;\n  return numberedName(base, n);\n}\n\n/**\n * The groups of operations that share a name but not a path, in name order.\n * A name shared only by operations on one path is not a collision and is\n * excluded: after demoteSamePathNames such operations are path-named and\n * their methods take one verb (PUT + PATCH).\n *\n * Name order, not document order: the numeric pass draws suffixed names from\n * one pool per service, and two groups can reach the same one (`listNotes1`\n * + `No2` and `listNotes1No` + `2`, see numberedName), so whichever is\n * served first decides. Names are unique per group, so this is a total\n * order, and with the members of a group also sorted the whole assignment\n * depends only on the paths.\n */\nfunction collidingGroups(operations: Operation[]): Operation[][] {\n  const byName = new Map<string, Operation[]>();\n  for (const op of operations) {\n    const group = byName.get(op.name) ?? [];\n    group.push(op);\n    byName.set(op.name, group);\n  }\n  return [...byName.entries()]\n    .filter(([, group]) => new Set(group.map((op) => op.path)).size > 1)\n    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n    .map(([, group]) => group);\n}\n\n/** Operations in path order, by code unit, the one tie-break every pass of disambiguateOperationNames uses. */\nfunction comparePaths(a: Operation, b: Operation): number {\n  return a.path < b.path ? -1 : a.path > b.path ? 1 : 0;\n}\n\n/**\n * One pass of disambiguateOperationNames on one colliding group: the group's\n * path-named members take the names the pass proposes for them when the pass\n * tells the group apart, and only names no operation outside the group has.\n * An operationId-named member is never renamed and stands at its own name.\n *\n * `proposal` is the name a path-named member would take, compared as\n * written: a pass that must not part two paths on a word's number alone\n * spells it alike for both before proposing (the deeper context of\n * `/org/teams/members` and `/org/teams/{teamId}/members` is `Teams` for\n * both, never `Teams` beside `Team`), and a pass whose number is the point\n * (the plural, `getPets` beside `getPet`) proposes it as it is. Three rules\n * follow, each on this one place:\n *\n *   - The pass is skipped for the group when every proposal is one name. A\n *     qualifier the colliding paths all carry — `Teams` above — would move\n *     the collision further from the plain name and tell nothing apart; the\n *     next pass (`ByTeamId`) is what does.\n *   - A proposal an operation outside the group already has is not taken\n *     (nameIsFree): the member keeps its name for this pass and the next pass\n *     is tried, so `/org/members/archived` beside `/org/archived_members`,\n *     whose name is `listArchivedMembers`, is never `listArchivedMembers2`,\n *     which reads as a variant of a path it is unrelated to; a number is for\n *     when no pass is left. Its colliding twin `/org/teams/archived` still\n *     takes `listArchivedTeams`, and `listArchived` is then its own.\n *   - Members with one proposal stay one group for the next pass: they take\n *     it together — `/orgs/{orgId}/groups/members` and\n *     `/orgs/{orgId}/groups/{groupId}/members` beside `/orgs/teams/members`\n *     are `listMembersGroups` both, told apart next by `ByGroupId` — and are\n *     numbered on it when nothing after tells them apart. Members on one path\n *     (PUT + PATCH) share a name by the same rule.\n *\n * Which names are taken is read when the group is reached, so groups a pass\n * served earlier — in name order (collidingGroups) — hold their new names\n * against it, and the outcome depends only on the paths.\n */\nfunction qualifyGroup(\n  group: readonly Operation[],\n  operations: readonly Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  nounOf: (op: Operation) => string | null,\n  apart: (op: Operation, other: Operation, name: string) => boolean,\n  proposal: (op: Operation) => string,\n  rename: (op: Operation, name: string) => void,\n): void {\n  const proposals = new Map(group.map((op) => [op, pathNamed.has(op) ? proposal(op) : op.name]));\n  const clusters = new Map<string, Operation[]>();\n  for (const op of [...group].sort(comparePaths)) {\n    const name = proposals.get(op) ?? op.name;\n    clusters.set(name, [...(clusters.get(name) ?? []), op]);\n  }\n  if (clusters.size <= 1) return;\n  for (const [name, members] of clusters) {\n    if (!members.every((op) => nameIsFree(group, operations, pathNamed, nounOf, apart, op, name))) continue;\n    for (const op of members) {\n      if (pathNamed.has(op)) rename(op, name);\n    }\n  }\n}\n\n/**\n * Whether `name` is free for `op`, a member of `group`: no operation outside\n * the group has it, or every operation that has it is path-named, names the\n * noun `op` names (`nounOf`, compared as sameNoun compares) and is one a\n * later pass tells from `op` (`apart`) — the nested collection of the\n * service's own word, `/notes/{noteId}/notes` as `listNotes` beside `/notes`.\n * Such a name the member takes and joins the group of, and the passes after\n * tell the two apart by what does differ between their paths: `listNotes`\n * and `listNotesByNoteId`, `getNote` and `getNoteByChildId`. A name an\n * operationId-named operation has is never free, nor is one a path-named\n * operation of another noun has: `listArchivedMembers` on\n * `/org/archived_members` beside the `Archived` of `/org/members/archived`,\n * which nothing after could tell apart; nor `listNotes` on `/notes/notes`\n * beside `/notes`, whose path has nothing `/notes` lacks: joined, the two\n * would only be numbered, the number landing on the name one of them had.\n */\nfunction nameIsFree(\n  group: readonly Operation[],\n  operations: readonly Operation[],\n  pathNamed: ReadonlySet<Operation>,\n  nounOf: (op: Operation) => string | null,\n  apart: (op: Operation, other: Operation, name: string) => boolean,\n  op: Operation,\n  name: string,\n): boolean {\n  const noun = nounOf(op);\n  return operations.every((other) => {\n    if (group.includes(other) || other.name !== name) return true;\n    const otherNoun = pathNamed.has(other) ? nounOf(other) : null;\n    return (\n      noun !== null &&\n      otherNoun !== null &&\n      sameNoun(otherNoun.toLowerCase(), noun.toLowerCase()) &&\n      apart(op, other, name)\n    );\n  });\n}\n\n/**\n * Append a qualifier to an operation name without repeating what the name\n * already says. A qualifier never contributes the same word twice in a row:\n * the deeper context of `/api/analytics/analytics/teams` is\n * `AnalyticsAnalytics`, which joins as `listTeamsAnalytics`. Only the same\n * word is a repeat there, compared on the camelCase boundary and\n * case-insensitively: a plural segment and its singular are two words, so\n * `listTags` + `NotesNote`, the deeper context of `/x/notes/{id}/note/tags`\n * as written, is `listTagsNotesNote`, told from the `listTagsNotes` of\n * `/x/notes/{id}/tags`. The words that remain are then joined where they\n * overlap the end of the name: `listNotes` + `Notes` and `listOAuth2Tokens`\n * + `OAuth2Tokens` stay as they are, and `listTeams` + `TeamsAnalytics` is\n * `listTeamsAnalytics`. That overlap compares words as nouns (sameNoun), so\n * a noun the name ends with is not repeated in the other number either:\n * `listNotes` + `Note` and `listAliases` + `Alias`, the deeper contexts of\n * `/orgs/notes/{id}/notes` and `/org/aliases/{id}/aliases`, stay `listNotes`\n * and `listAliases`. Nor is the word the name ends with added right after\n * such an overlap: `listNotes` + `NoteNotes` stays `listNotes`, never\n * `listNotesNotes`. The name's own words are never touched.\n */\nfunction appendQualifier(name: string, qualifier: string | null): string {\n  if (!qualifier) return name;\n  const have = splitWords(name).map((w) => w.toLowerCase());\n  const words = splitWords(qualifier).filter((w, i, all) => i === 0 || w.toLowerCase() !== all[i - 1].toLowerCase());\n  const want = words.map((w) => w.toLowerCase());\n  // The longest run of words that both ends the name and starts the qualifier.\n  let overlap = Math.min(have.length, want.length);\n  while (overlap > 0 && !want.slice(0, overlap).every((w, i) => sameNoun(w, have[have.length - overlap + i]))) {\n    overlap--;\n  }\n  // Past a run in the other number (`Note` against `listNotes`), the next word may be the name's last word itself.\n  if (want[overlap] === have[have.length - 1]) overlap++;\n  const rest = words.slice(overlap);\n  return rest.length === 0 ? name : toCamelCase([name, ...rest].join('_'));\n}\n\n/**\n * Whether two lowercase words name one noun: they are the same word, or\n * their singular forms (singularizePathSegment) are — `notes` and `note`,\n * `aliases` and `alias`, `analyses` and `analysis`. singularizePathSegment\n * is idempotent, so a word that is already singular is its own singular\n * form and is never shortened a second time on one side only (`alias`\n * compares as `alias`, not `alia`, against the `alias` that `aliases`\n * becomes). Two words the stemmer cannot relate, `canvases` and `canvas`,\n * are different nouns here, as they are everywhere else.\n */\nfunction sameNoun(a: string, b: string): boolean {\n  return a === b || singularizePathSegment(a) === singularizePathSegment(b);\n}\n\n/**\n * The path a colliding operation's resource and deeper context are read\n * from: the path without the segments whose words the name already carries\n * ahead of its last word, so that what remains ends with the word the name\n * ends with, which appendQualifier leaves alone, and the rest is what sets\n * the colliding paths apart.\n *\n * For an action (inferAction) it is the path without the action segment:\n * `adoptPet` on `/shop/rescue/pets/{id}/adopt` is read as\n * `/shop/rescue/pets/{id}`, whose resource `Pet` the name ends with and whose\n * deeper context `Rescue` tells it from `/shop/pets/{id}/adopt`, rather than\n * the verb coming back as `adoptPetAdopt`. For a singleton (inferSingleton)\n * it is the path without the parent (itemParentIndex) and the parameter\n * before the segment: `getPetStatus` on `/shop/rescue/pets/{id}/status` is\n * read as `/shop/rescue/status`, whose resource `Status` the name ends with,\n * so the same `Rescue` tells it from `/shop/pets/{id}/status` rather than\n * `Pet` coming back as `getPetStatusPet`. The parent's own spelling is left\n * to the plural pass (writtenParentName), so `/shop/pets/{id}/status` beside\n * `/shop/pet/{id}/status` is `getPetsStatus`. Every other operation is read\n * whole, as is an action that gave its name up (demoteSamePathNames,\n * yieldActionNames; `actions` false), whose name is the next shape's.\n */\nfunction qualifierPath(op: Operation, apiRootLength: number, actions = true): string {\n  const segments = pathSegments(op.path);\n  if (actions && inferAction(op.httpMethod, op.path, apiRootLength)) return '/' + segments.slice(0, -1).join('/');\n  if (inferSingleton(op.path, apiRootLength)) {\n    const parent = itemParentIndex(segments, apiRootLength);\n    return '/' + segments.filter((_, i) => i !== parent && i !== segments.length - 2).join('/');\n  }\n  return op.path;\n}\n\n/**\n * The path parameters in path order, each as the PascalCase word that\n * `By<Param>` spells it with. Mirrors derivePathModelBaseName's spelling of a\n * parameter segment, so `{team_id}` and `{teamId}` read alike. A parameter\n * that carries a custom method (`{petId}:adopt`) is the parameter alone,\n * `PetId`, since pathSegments has split the verb off.\n */\nfunction pathParamWords(path: string): string[] {\n  return pathSegments(path)\n    .filter((segment) => isParameterSegment(segment))\n    .map((segment) => toPascalCase(segment.replace(/[{}]/g, '')));\n}\n\n/** The parameter words (pathParamWords) that every one of the paths carries. */\nfunction sharedPathParams(paths: readonly string[]): ReadonlySet<string> {\n  const words = paths.map((path) => new Set(pathParamWords(path)));\n  return new Set([...(words[0] ?? [])].filter((word) => words.every((set) => set.has(word))));\n}\n\n/**\n * `By<Param>` for each path parameter not in `shared`, in path order, as one\n * qualifier: `/v1/{teamId}/notes` → `ByTeamId`, `/a/{x}/b/{y}/c` → `ByXByY`,\n * and `/api/{teamId}/notes/{noteId}` → `ByTeamId` when the colliding paths\n * all carry `noteId`. Empty for a path with no parameter of its own.\n */\nfunction inferByParamsSuffix(path: string, shared: ReadonlySet<string>): string {\n  return pathParamWords(path)\n    .filter((word) => !shared.has(word))\n    .map((word) => 'By' + word)\n    .join('');\n}\n\n/**\n * The resource noun inferResourceFromPath leaves off because it is the\n * segment the service was named from, spelled as that function would have\n * spelled it (pathSegmentNoun): `Notes` for `/api/notes` and\n * `/api/{teamId}/notes` under an `/api` root and for a root-less `/notes`,\n * `Note` for the item `/api/notes/{id}`. Null when the last literal segment\n * past the API root is a different word (`/api/notes/{id}/tags`, whose `Tags`\n * the plain name already carries) or when nothing literal follows the root\n * (`/api/v1/{id}`). `singularItem` false keeps an item's noun as the path\n * spells it (`Notes` for `/api/notes/{id}`), for the service-noun qualifier\n * when the singular gives a name already taken (disambiguateOperationNames).\n */\nfunction inferServiceNoun(path: string, apiRootLength: number, singularItem = true): string | null {\n  const segments = pathSegments(path);\n  let last = segments.length - 1;\n  while (last >= apiRootLength && isParameterSegment(segments[last])) last--;\n  if (last < apiRootLength || last !== serviceSegmentIndex(path, apiRootLength)) return null;\n  return toPascalCase(singularItem ? pathSegmentNoun(segments, last) : segments[last]);\n}\n\n/**\n * Extract a deeper disambiguation context from the path when the resource\n * noun isn't unique enough: the literal segments between the service segment\n * and the resource, joined in path order, each spelled as pathSegmentNoun\n * spells it — singular when a path parameter follows it, since the segment\n * then addresses one item, and as written otherwise.\n *\n * /users/{id}/legacy/factors → \"Legacy\"\n * /store/cats/{id}/toys/{toyId} → \"Cat\" (one cat's toys), so `getToyCat` beside `/store/dogs/{id}/toys/{toyId}`\n * /store/cats/toys/{toyId} → \"Cats\" (no one cat), so `getToyCats` beside `/store/dogs/toys/{toyId}`\n * /org/analytics/analytics/teams → \"AnalyticsAnalytics\" (appendQualifier collapses the repeat)\n * /users/{id}/auth_factors → null: nothing lies between the service and the resource\n *\n * `Cat` and `Cats` are one noun, so beside each other the two cat paths are\n * not told apart by it (qualifyGroup): `/store/cats/{id}/toys/{toyId}` and\n * `/store/cats/toys/{toyId}` are `getToyById` and `getToy`, by the\n * parameter that does tell them apart.\n *\n * The API root the path sits under (`apiRootLength`, see documentApiRoot) is\n * left out along with the service segment that follows it, so\n * /api/v1/core/auth/permissions in `Core` contributes \"Auth\", not \"V1CoreAuth\".\n * `singularItem` false keeps every segment as the path spells it (`Pets` for\n * `/store/pets/{id}/toys/{toyId}`), for the qualifier that falls back to the\n * plural when the singular does not tell two paths apart (see\n * disambiguateOperationNames). The stemmer's limits reach every segment it\n * singularises: `/messages/sms/{smsId}/attachments` contributes \"Sm\".\n */\nfunction inferDeeperContext(path: string, apiRootLength = 0, singularItem = true): string | null {\n  const segments = pathSegments(path);\n  const nouns: string[] = [];\n  for (let i = apiRootLength; i < segments.length; i++) {\n    if (!isParameterSegment(segments[i])) nouns.push(singularItem ? pathSegmentNoun(segments, i) : segments[i]);\n  }\n  // Skip first (service) and last (already used) — use the middle ones\n  if (nouns.length >= 3) {\n    return toPascalCase(nouns.slice(1, -1).join('_'));\n  }\n  return null;\n}\n\n/**\n * Extract mutually-exclusive parameter groups from the `x-mutually-exclusive-parameter-groups`\n * operation extension. Cross-references grouped parameter names against the already-extracted\n * IR parameter arrays so emitters get object-identity references.\n *\n * `ignoredHeaders` are the case-folded names of the `Accept`, `Content-Type`\n * and `Authorization` headers the operation declared and the parser dropped\n * (`isIgnoredHeaderParameter`, #414). A variant member naming one is in\n * `parameters[]` but is no parameter the SDK sends, so it is dropped from\n * the variant with a warning — as is a variant left with no member, and a\n * group left with no variant — rather than failing the parse with a message\n * that says the parameter does not exist.\n */\nfunction extractParameterGroups(\n  op: OperationObject,\n  allIRParams: Parameter[],\n  operationContext: string,\n  ignoredHeaders: ReadonlySet<string> = new Set(),\n): ParameterGroup[] | undefined {\n  const raw = op['x-mutually-exclusive-parameter-groups'];\n  if (!raw || typeof raw !== 'object') return undefined;\n\n  const paramByName = new Map<string, Parameter>();\n  for (const p of allIRParams) {\n    paramByName.set(p.name, p);\n  }\n\n  const groups: ParameterGroup[] = [];\n\n  for (const [groupName, groupDef] of Object.entries(raw)) {\n    if (!groupDef || typeof groupDef !== 'object') {\n      throw new Error(\n        `Malformed x-mutually-exclusive-parameter-groups.${groupName} in ${operationContext}: expected an object with \"optional\" and \"variants\".`,\n      );\n    }\n\n    if (typeof groupDef.optional !== 'boolean') {\n      throw new Error(\n        `Malformed x-mutually-exclusive-parameter-groups.${groupName}.optional in ${operationContext}: expected a boolean.`,\n      );\n    }\n\n    if (!groupDef.variants || typeof groupDef.variants !== 'object') {\n      throw new Error(\n        `Malformed x-mutually-exclusive-parameter-groups.${groupName}.variants in ${operationContext}: expected an object mapping variant names to parameter name arrays.`,\n      );\n    }\n\n    if (Object.keys(groupDef.variants).length === 0) {\n      throw new Error(\n        `Malformed x-mutually-exclusive-parameter-groups.${groupName} in ${operationContext}: group has zero variants.`,\n      );\n    }\n\n    const variants = Object.entries(groupDef.variants).flatMap(([variantName, paramNames]) => {\n      if (!Array.isArray(paramNames) || paramNames.length === 0) {\n        throw new Error(\n          `Malformed x-mutually-exclusive-parameter-groups.${groupName}.variants.${variantName} in ${operationContext}: expected a non-empty array of parameter names.`,\n        );\n      }\n      const variantPath = `x-mutually-exclusive-parameter-groups.${groupName}.variants.${variantName}`;\n      const parameters: Parameter[] = [];\n      for (const pName of paramNames) {\n        const irParam = paramByName.get(pName);\n        if (irParam) {\n          parameters.push(irParam);\n          continue;\n        }\n        // The member names a header the operation declared and OpenAPI says\n        // to ignore (#414): it is in `parameters[]`, so the error below would\n        // point at the wrong cause. The header is set by the request's media\n        // types or its `security`, never by a parameter, so the member is\n        // dropped from the variant.\n        if (typeof pName === 'string' && ignoredHeaders.has(foldHeaderName(pName))) {\n          console.warn(\n            `[oagen] Warning: ${variantPath} in ${operationContext} names the header parameter \"${pName}\", ` +\n              'which OpenAPI says to ignore (an Accept, Content-Type or Authorization header is set by the ' +\n              \"request's media types and security, not by a parameter). Dropping it from the variant.\",\n          );\n          continue;\n        }\n        throw new Error(\n          `${variantPath} references parameter \"${pName}\" which does not exist in the operation's parameters[] (${operationContext}).`,\n        );\n      }\n      if (parameters.length === 0) {\n        console.warn(\n          `[oagen] Warning: ${variantPath} in ${operationContext} names only header parameters OpenAPI says to ignore. ` +\n            'Dropping the variant.',\n        );\n        return [];\n      }\n      return [{ name: variantName, parameters }];\n    });\n\n    if (variants.length === 0) {\n      console.warn(\n        `[oagen] Warning: x-mutually-exclusive-parameter-groups.${groupName} in ${operationContext} is left with no ` +\n          'variant once the header parameters OpenAPI says to ignore are dropped. Dropping the group.',\n      );\n      continue;\n    }\n\n    groups.push({\n      name: groupName,\n      optional: groupDef.optional,\n      variants,\n    });\n  }\n\n  return groups.length > 0 ? groups : undefined;\n}\n\n/**\n * Extract mutually-exclusive body parameter groups from the\n * `x-mutually-exclusive-body-groups` operation extension. Unlike query\n * parameter groups (whose parameters live in operation.queryParams), body\n * group parameters are synthetic — built from the oneOf variant schemas in\n * the request body. Emitters use the group's presence to generate sum-type\n * interfaces and custom JSON marshalling instead of flat optional fields.\n */\nfunction extractBodyParameterGroups(\n  op: OperationObject,\n  requestBody: RequestBodyObject | undefined,\n  operationContext: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): ParameterGroup[] | undefined {\n  const raw = op['x-mutually-exclusive-body-groups'];\n  if (!raw || typeof raw !== 'object') return undefined;\n\n  // Collect the body schema's oneOf variant fields so we can resolve types.\n  // The body schema has been structurally rewritten to allOf: [base, { oneOf: [...] }]\n  // by the spec generator; the variant properties live inside oneOf branches.\n  // Read from the same pick `requestBody` is typed from, so a body under\n  // `application/json; charset=utf-8` or a `+json` media type resolves its\n  // members like one under plain `application/json`.\n  const bodySchema = selectRequestBodyContent(requestBody)?.schema;\n  const variantFieldSchemas = collectVariantFieldSchemas(bodySchema, componentSchemas);\n\n  const groups: ParameterGroup[] = [];\n\n  for (const [groupName, groupDef] of Object.entries(raw)) {\n    if (!groupDef || typeof groupDef !== 'object') continue;\n    if (typeof groupDef.optional !== 'boolean') continue;\n    if (!groupDef.variants || typeof groupDef.variants !== 'object') continue;\n    if (Object.keys(groupDef.variants).length === 0) continue;\n\n    const variants = Object.entries(groupDef.variants).map(([variantName, paramNames]) => {\n      if (!Array.isArray(paramNames) || paramNames.length === 0) {\n        throw new Error(\n          `Malformed x-mutually-exclusive-body-groups.${groupName}.variants.${variantName} in ${operationContext}: expected a non-empty array of parameter names.`,\n        );\n      }\n      const parameters: Parameter[] = paramNames.map((pName) => {\n        const entry = variantFieldSchemas.get(pName);\n        const fieldSchema = entry?.schema;\n        // No schema found means the body's oneOf branches don't declare this\n        // member. Falling back to `string` silently produces an SDK that\n        // type-checks against itself but misrepresents the wire contract\n        // (object-valued members become plain strings), so say so loudly.\n        if (!fieldSchema) {\n          console.warn(\n            `[oagen] Warning: x-mutually-exclusive-body-groups.${groupName}.variants.${variantName} ` +\n              `references \"${pName}\" in ${operationContext}, but no oneOf branch of the request body ` +\n              `declares that property. Falling back to type: string.`,\n          );\n        }\n        const fieldType: TypeRef = fieldSchema\n          ? schemaToTypeRef(fieldSchema, toPascalCase(pName), entry?.owner)\n          : { kind: 'primitive', type: 'string' };\n        return {\n          name: pName,\n          type: fieldType,\n          required: false, // group variant fields are always optional at the struct level\n          description: fieldSchema?.description,\n        };\n      });\n\n      // Optional variant membership: fields the caller may omit when using\n      // this variant. Only names that actually belong to the variant count —\n      // anything else in the extension is ignored rather than fatal.\n      const rawOptionalFields =\n        groupDef.optionalFields && typeof groupDef.optionalFields === 'object'\n          ? groupDef.optionalFields[variantName]\n          : undefined;\n      const optionalParameters = Array.isArray(rawOptionalFields)\n        ? rawOptionalFields.filter((name): name is string => typeof name === 'string' && paramNames.includes(name))\n        : [];\n\n      return {\n        name: variantName,\n        parameters,\n        ...(optionalParameters.length > 0 ? { optionalParameters } : {}),\n      };\n    });\n\n    groups.push({\n      name: groupName,\n      optional: groupDef.optional,\n      variants,\n    });\n  }\n\n  return groups.length > 0 ? groups : undefined;\n}\n\n/** A response placeholder for detecting a strategy from the query parameters alone. */\nconst UNKNOWN_RESPONSE: TypeRef = { kind: 'primitive', type: 'unknown' };\n\nfunction buildOperation(\n  method: HttpMethod,\n  path: string,\n  op: OperationObject,\n  pathLevelParams: RawParameterObject[],\n  pathItemDocs: PathItemDocs,\n  pathModelBaseName: string,\n  /** The name the operation starts with (`planOperations`); the naming passes settle the one it ends with. */\n  operationName: string,\n  serviceName?: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  componentParameters?: Record<string, Record<string, unknown>>,\n  componentRequestBodies?: Record<string, Record<string, unknown>>,\n  componentExamples?: Record<string, Record<string, unknown>>,\n  componentHeaders?: Record<string, Record<string, unknown>>,\n  componentResponses?: Record<string, Record<string, unknown>>,\n  deferred: DeferredInlineType[] = [],\n  servers?: ServerEntry[],\n  refSiblingDescriptions: SiblingDocs = 'override',\n  componentResponseModelNames?: ReadonlyMap<string, string>,\n  paginationHint?: unknown,\n  /** The component models and the models their fields mint (`PaginationExtractionOptions.componentModels`). */\n  componentModels?: Model[],\n  registry?: ModelShapeRegistry,\n  /**\n   * The `operationId` the operation's models are named from when the\n   * document reuses its own (`resolveReusedOperationIds`) or another id\n   * cleans to its stem (`resolveContestedOperationIdStems`): the name the\n   * reuse renamed it to, or `null` to name them from the path; absent, its\n   * own.\n   */\n  modelOperationId?: string | null,\n): {\n  operation: Operation;\n  inlineModels: Model[];\n  inlineModelBundles: InlineModelBundle[];\n  envelopeCompanions?: EnvelopeCompanion[];\n  /** What the shape registry records as the owner of this operation's models (see `headerOperationQualifier`). */\n  operationQualifier: string;\n  /** What a merge pass prefixes to one of this operation's models it must rename (`InlineModelBundle.qualifier`). */\n  modelQualifier: string;\n  /** Each success body a `components/responses` entry declares (`OperationExtractionResult.componentSites`). */\n  componentBodies: TypeRef[];\n  /** The operation's `callbacks` map, when the Operation Object carries the key, for `extractCallbacks` (#382). */\n  declaredCallbacks?: DeclaredCallbacks;\n} {\n  const opLabel = operationLabel(op, path, method);\n  // The Operation Object as every model name reads it (the request and\n  // response bodies, the error and fallback bodies, the qualifiers): with\n  // the `operationId` the reuse of its own, or the contest of its stem,\n  // leaves it, if any.\n  const namingOp = modelOperationId === undefined ? op : { ...op, operationId: modelOperationId ?? undefined };\n  // Resolve a `components/requestBodies` ref up front so body extraction, body\n  // parameter groups, and the body-ownership rule below all read one object.\n  const requestBodyObject = resolveRequestBodyRef(\n    op.requestBody,\n    componentRequestBodies,\n    opLabel,\n    refSiblingDescriptions,\n  );\n  // An operation-level parameter overrides a path-level one with the same\n  // identity — `parameterKey`: location and name, a header's name\n  // case-folded, so a path-level `X-Pet-Token` and an operation-level\n  // `x-pet-token` are one header (#295) — rather than adding a second entry.\n  // Operation params come last, so last-write-wins; Map.set keeps the\n  // original insertion position, so path-level parameter ordering is\n  // preserved. An `Accept`, `Content-Type` or `Authorization` header is\n  // dropped, as OpenAPI requires (`isIgnoredHeaderParameter`, #414).\n  const paramsByIdentity = new Map<string, ParameterObject>();\n  // The dropped headers' names, case-folded, for `extractParameterGroups`:\n  // a group variant that names one has the member dropped, not the parse failed.\n  const ignoredHeaders = new Set<string>();\n  for (const raw of [...pathLevelParams, ...(op.parameters ?? [])]) {\n    const param = resolveParameterRef(raw, componentParameters, opLabel, refSiblingDescriptions);\n    if (isIgnoredHeaderParameter(param)) {\n      ignoredHeaders.add(foldHeaderName(param.name));\n      continue;\n    }\n    paramsByIdentity.set(parameterKey(param.in, param.name), param);\n  }\n  const allParams = [...paramsByIdentity.values()];\n\n  const hasIdempotencyHeader = allParams.some((p) => p.in === 'header' && foldHeaderName(p.name) === 'idempotency-key');\n  // Reported here, once per parameter the operation types: `extractParams`\n  // runs per location, and the passes that re-read a parameter's schema\n  // stay silent. The idempotency header is not typed (see `extract` below),\n  // so a `content` map on it is not reported.\n  for (const param of allParams) {\n    if (param.in === 'header' && foldHeaderName(param.name) === 'idempotency-key') continue;\n    warnUnreadParameterContent(param, `Parameter \"${param.name}\" (in: ${param.in}) on ${opLabel}`);\n  }\n\n  // A parameter the spec declares both as `in: query` and as a request-body\n  // property is one value with two wire locations. On a body-carrying method\n  // it travels in the body only: duplicating it into the URL puts body-grade\n  // material (OAuth codes, client secrets) into access logs and exception\n  // traces, and emitters that surface both copies grow a second public\n  // parameter for the same field. RFC 6749 §4.1.3 puts token-request\n  // parameters in the body for the same reason. GET/DELETE keep every\n  // declared query parameter — they have no body to prefer.\n  //\n  // One carve-out: a query parameter named by `x-mutually-exclusive-parameter-groups`\n  // stays a parameter. The extension models it as one, the group resolver\n  // below looks it up in the parameter arrays, and emitters already route\n  // groups into the body on body-carrying methods, so nothing reaches the URL.\n  const groupedQueryNames = collectParameterGroupMemberNames(op);\n  const bodyOwnedNames = new Set<string>();\n  if (BODY_CARRYING_METHODS.has(method)) {\n    const bodySchema = selectRequestBodyContent(requestBodyObject)?.schema;\n    for (const name of collectBodyPropertyNames(bodySchema, componentSchemas)) {\n      if (!groupedQueryNames.has(name)) bodyOwnedNames.add(name);\n    }\n  }\n  const wireParams =\n    bodyOwnedNames.size > 0 ? allParams.filter((p) => !(p.in === 'query' && bodyOwnedNames.has(p.name))) : allParams;\n\n  // Use the service name as context so inline parameter enums get qualified\n  // names. e.g., service \"Auth\" + param \"provider\" → \"AuthProvider\".\n  const opContext = serviceName;\n  // Names this operation's models in the shape registry, and qualifies a\n  // deferred model's name when one of them is taken across operations.\n  const operationQualifier = headerOperationQualifier(namingOp, pathModelBaseName, opContext);\n  // What the typing of a parameter, a response header or a secondary,\n  // fallback or error body reads from the operation and the spec; a schema\n  // deferred through it is typed once every operation has been read\n  // (`resolveDeferredInlineTypes`).\n  const typing: ResponseTypingContext = {\n    componentHeaders,\n    componentSchemas,\n    componentResponses,\n    serviceName: opContext,\n    operationQualifier,\n    deferred,\n    refSiblingDescriptions,\n    componentResponseModelNames,\n    registry,\n  };\n  // One location's parameters, typed by `extractParams`. A parameter whose\n  // inline schema mints a model is deferred once the responses have been\n  // read (`deferParameterModels`, after `extractResponses` below), so the\n  // model is created under a name nothing else owns and a response header\n  // the operation types keeps the name it has.\n  const pendingParams: Array<[raw: ParameterObject[], typed: Parameter[], location: ParameterObject['in']]> = [];\n  const extract = (location: ParameterObject['in'], source: ParameterObject[] = wireParams): Parameter[] => {\n    const params = extractParams(\n      source,\n      location,\n      opContext,\n      componentSchemas,\n      componentExamples,\n      opLabel,\n      refSiblingDescriptions,\n    );\n    pendingParams.push([source.filter((p) => p.in === location), params, location]);\n    return params;\n  };\n  const pathParams = extract('path');\n  const queryParams = extract('query');\n  // The idempotency header is the SDK's to inject (`injectIdempotencyKey`), not a parameter to type.\n  const headerParams = extract(\n    'header',\n    wireParams.filter((p) => !(p.in === 'header' && foldHeaderName(p.name) === 'idempotency-key')),\n  );\n  const cookieParams = extract('cookie');\n  // Keep the body-owned declarations on the operation so downstream passes\n  // (inline-enum collection, the compat surface) still see what the spec\n  // declared, even though no emitter serializes them to the URL.\n  const bodyOwnedQueryParams =\n    bodyOwnedNames.size > 0\n      ? extract(\n          'query',\n          allParams.filter((p) => p.in === 'query' && bodyOwnedNames.has(p.name)),\n        )\n      : [];\n\n  const reqBodyModels: Model[] = [];\n  const {\n    body: requestBody,\n    encoding: requestBodyEncoding,\n    contentType: requestBodyContentType,\n    description: requestBodyDescription,\n    contentTypes: requestBodyContentTypes,\n    contents: requestBodyContents,\n  } = extractRequestBody(requestBodyObject, namingOp, pathModelBaseName, reqBodyModels, componentSchemas, opLabel, {\n    deferred,\n    operationQualifier,\n    componentSchemas,\n  });\n  // Read off the resolved body so a `components/requestBodies` ref's flag\n  // counts. Only `true` makes the body required: OpenAPI defaults the flag\n  // to `false`, and a non-boolean value is not a declaration of requiredness.\n  // Set exactly when the body declares a media type, read or not, so a body\n  // carried in `requestBodyContents` alone keeps it, as a webhook's does.\n  const requestBodyRequired = requestBodyContentTypes !== undefined ? requestBodyObject?.required === true : undefined;\n\n  // The page parameter's first value is read from its schema as written —\n  // `schema`, else the picked `content` entry's (`parameterTyping`) — so a\n  // `default`/`minimum` behind `allOf: [{ $ref }]` or a nullable wrapper —\n  // which the IR parameter's own `default` does not carry — still counts.\n  const querySchemas = new Map(\n    wireParams.filter((p) => p.in === 'query').map((p) => [p.name, parameterSchema(p)] as const),\n  );\n  const pageStartOf = (param: Parameter | undefined): number =>\n    derivePageStart(param, param && querySchemas.get(param.name), componentSchemas);\n\n  // Whether an override was written at all, usable or not: an envelope that\n  // ends up with no iterator is warned about only when none was, since a\n  // rejected override has already been warned about by name.\n  const overrideGiven = op['x-pagination'] !== undefined || paginationHint !== undefined;\n  // The explicit pagination override — config hint over `x-pagination` — is\n  // validated before the response is classified: `strategy: 'none'` must keep\n  // a list envelope from being unwrapped into a bare array, and an explicit\n  // `dataPath` is resolved against the response while its schema is at hand.\n  let paginationOverride = resolvePaginationOverride({ extension: op['x-pagination'], hint: paginationHint }, opLabel);\n  const paginationDisabled = paginationOverride?.hint.strategy === 'none';\n  // The pagination the query parameters alone yield, read before the\n  // response is: `UNKNOWN_RESPONSE` stands in for the response, whose item\n  // type this read never uses.\n  const paginationFromParamsAlone =\n    detectPagination(UNKNOWN_RESPONSE, queryParams, undefined, { pageStartOf }) ?? undefined;\n  // Whether the override can apply is decided here, before the response is\n  // read: one that would be rejected (a `param` the operation does not\n  // declare, no strategy from anywhere) must not keep an envelope as a\n  // wrapper that detection then reads as the list. What it is checked\n  // against is the pagination the query parameters alone yield — a\n  // parameter the operation does not declare never makes an override usable.\n  if (paginationOverride && !paginationDisabled) {\n    const resolved = resolveOverrideParams(paginationFromParamsAlone, paginationOverride.hint, queryParams);\n    if ('problem' in resolved) {\n      console.warn(`[oagen] Warning: ${paginationOverride.source} on ${opLabel}${resolved.problem}`);\n      paginationOverride = undefined;\n    }\n  }\n  // What drives the iterator, if anything: a query parameter the operation\n  // declares — the one detection found, or the one a usable override names\n  // (checked above). With neither there is nothing to page with, so a list\n  // envelope is not unwrapped for an iterator that never comes: it is kept as\n  // a plain response model, the wire shape, exactly as `strategy: 'none'`\n  // keeps it.\n  const iteratorSource: 'parameters' | 'override' | undefined = paginationDisabled\n    ? undefined\n    : paginationFromParamsAlone\n      ? 'parameters'\n      : paginationOverride\n        ? 'override'\n        : undefined;\n  const {\n    response,\n    responseHeaders,\n    responseContentTypes,\n    responseContents,\n    responseDescription,\n    responseStatusCode,\n    successResponses,\n    errors,\n    defaultResponse,\n    rangeResponses,\n    inlineModels: responseModels,\n    isPaginated,\n    dataPath: responseDataPath,\n    dataDescription: responseDataDescription,\n    itemType: responseItemType,\n    envelopeFields,\n    endOfIteration: responseEndOfIteration,\n    overrideItemType,\n    overrideProblem,\n    envelopeCompanions,\n    unpagedEnvelope,\n    componentBodies,\n  } = extractResponses(op.responses, namingOp, pathModelBaseName, opLabel, componentSchemas, typing, {\n    disabled: iteratorSource === undefined,\n    dataPath: paginationDisabled ? undefined : paginationOverride?.hint.dataPath,\n    endOfIteration: paginationDisabled ? undefined : paginationOverride?.hint.endOfIteration,\n    componentModels,\n    overrideOnly: iteratorSource === 'override',\n  });\n  const inlineModels = [...responseModels, ...reqBodyModels];\n\n  // The parameters' deferred sites follow the responses' in the registry, so\n  // a response header the operation typed keeps its name (`PetsXMeta`) and a\n  // header parameter of the same name takes the location-qualified one\n  // (`PetsHeaderXMeta`), never the reverse.\n  for (const [raw, typed, location] of pendingParams) deferParameterModels(raw, typed, location, typing);\n\n  // An override the primary response cannot satisfy — a `dataPath` that\n  // reaches no array in it, an `endOfIteration` that resolves in it to no\n  // field of the fitting type — cannot type the iterator's items or would\n  // send it reading a field that is not there, so the whole override falls\n  // back to detection, as every other unusable override does. The decision\n  // was made before any body was read (`extractResponses`), so no success\n  // body was classified with it; one warning names the source, the\n  // operation and the problem.\n  if (paginationOverride && !paginationDisabled && overrideProblem !== undefined) {\n    console.warn(\n      `[oagen] Warning: ${paginationOverride.source} on ${opLabel}: ${overrideProblem} — ignoring the override`,\n    );\n    paginationOverride = undefined;\n  }\n\n  // Build structured pagination metadata from query param detection and\n  // response classification, then let the override correct or disable it.\n  const paginationFromParams = detectPagination(response, queryParams, responseDataPath, { pageStartOf });\n  // The list envelope the response was unwrapped on, whichever parameter\n  // drives the iterator: where the items are, their type, and the companions.\n  const envelope = isPaginated\n    ? {\n        dataPath: responseDataPath,\n        ...(responseDataDescription !== undefined && { dataDescription: responseDataDescription }),\n        itemType: responseItemType ?? paginatedItemType(response),\n        envelopeFields,\n      }\n    : undefined;\n  // An iterator is built around a parameter the operation declares, never an\n  // invented one: with none recognized, nothing is detected, and only an\n  // override can create the iterator — around the same envelope, which it\n  // receives below. An envelope nothing pages was kept as a plain response\n  // model above, so `isPaginated` never holds here without a parameter or a\n  // usable override. The stop field is read beside the unwrapped envelope,\n  // or beside a body kept as a wrapper under an explicit `dataPath` — a\n  // `$ref`, an envelope detection would unwrap on another array, an inline\n  // body detection did not recognize (see\n  // `ResponseClassificationOptions.dataPathOverride`).\n  const detectedPagination: PaginationMeta | undefined = paginationFromParams\n    ? {\n        ...paginationFromParams,\n        ...envelope,\n        ...(responseEndOfIteration && { endOfIteration: responseEndOfIteration }),\n      }\n    : undefined;\n  const pagination = applyPaginationOverride(detectedPagination, paginationOverride, queryParams, response, opLabel, {\n    overrideItemType,\n    // Read from the response above, so an override that creates the iterator\n    // where detection found none still iterates the envelope and stops on\n    // its stop field.\n    envelope,\n    endOfIteration: responseEndOfIteration,\n    pageStartOf,\n  });\n  // One warning per operation whose list envelope nothing pages: the cause\n  // is a missing query parameter, and the fix is to declare it or to name a\n  // declared one through an override. An override that was written and\n  // rejected has been warned about by name already.\n  if (unpagedEnvelope && !overrideGiven) {\n    console.warn(\n      `[oagen] Warning: ${opLabel} returns a list envelope but no query parameter drives an iterator ` +\n        `(${describeUndetectedPaging(queryParams)}) — keeping the body as a plain response model with no ` +\n        'pagination; declare the parameter, set x-pagination / operationHints pagination naming a query ' +\n        'parameter the operation declares, or set strategy \"none\" to accept the plain model',\n    );\n  }\n\n  // Per-operation security requirements; undefined means \"inherit ApiSpec.security\"\n  const security = extractSecurityRequirements(op.security, opLabel);\n  const tags = extractTags(op.tags);\n\n  // Extract mutually-exclusive parameter groups (query/path/header/cookie)\n  const allIRParams = [...pathParams, ...queryParams, ...headerParams, ...cookieParams];\n  const queryParamGroups = extractParameterGroups(op, allIRParams, opLabel, ignoredHeaders);\n\n  // Extract mutually-exclusive body parameter groups\n  const bodyParamGroups = extractBodyParameterGroups(op, requestBodyObject, opLabel, componentSchemas);\n\n  // Merge both sources into a single parameterGroups array\n  const parameterGroups =\n    queryParamGroups || bodyParamGroups ? [...(queryParamGroups ?? []), ...(bodyParamGroups ?? [])] : undefined;\n\n  // The operation's own `summary` and `description`, or its Path Item's for\n  // each it declares none for (`resolveOperationDocs`), each on its own field.\n  // An empty or whitespace-only text counts as absent at either level, so it\n  // gets no field and never hides the Path Item's.\n  const { summary, description } = resolveOperationDocs(op, pathItemDocs);\n\n  const operation: Operation = {\n    name: operationName,\n    // The document's operationId as written; the key is omitted when it\n    // declares none, so `name` alone says the operation is path-named.\n    ...(op.operationId ? { operationId: op.operationId } : {}),\n    // Keep the summary on its own so emitters can tell it apart from the\n    // description; the key is omitted (not set to undefined) when absent.\n    ...(summary !== undefined ? { summary } : {}),\n    description,\n    // Same conditional shape as `summary`: present only when the document\n    // declares a usable link, absent (not undefined) otherwise.\n    ...externalDocsEntry(op.externalDocs),\n    httpMethod: method,\n    path,\n    // Present only when the operation's effective servers differ from the\n    // document's (see operationServers); absent, not undefined, otherwise.\n    ...(servers && { servers }),\n    pathParams,\n    queryParams,\n    bodyOwnedQueryParams: bodyOwnedQueryParams.length > 0 ? bodyOwnedQueryParams : undefined,\n    headerParams,\n    cookieParams: cookieParams.length > 0 ? cookieParams : undefined,\n    requestBody,\n    requestBodyEncoding,\n    // The picked media type's essence, what an emitter sends as Content-Type;\n    // set exactly when the body is.\n    ...(requestBodyContentType && { requestBodyContentType }),\n    // Added only when the operation has a body so bodiless operations keep\n    // their shape.\n    ...(requestBodyRequired !== undefined && { requestBodyRequired }),\n    // The body's doc text, present only when the document gives it some —\n    // the Request Body Object's own, else its picked schema's.\n    ...(requestBodyDescription !== undefined && { requestBodyDescription }),\n    // Every media type the body declares, present only when there is one —\n    // the request-side twin of `responseContentTypes` / `responseContents`.\n    ...(requestBodyContentTypes && { requestBodyContentTypes, requestBodyContents }),\n    response,\n    // Added only when present so operations without headers keep their shape.\n    ...(responseHeaders && { responseHeaders }),\n    ...(responseContentTypes && { responseContentTypes, responseContents }),\n    // Likewise only when the primary response declares a description.\n    ...(responseDescription && { responseDescription }),\n    // And only when a 2xx or 3xx response is declared at all, so the status\n    // code is present exactly when `response` was read from one.\n    ...(responseStatusCode !== undefined && { responseStatusCode }),\n    successResponses,\n    errors,\n    // Added only when the document declares them so operations without\n    // fallback responses keep their shape.\n    ...(defaultResponse && { defaultResponse }),\n    ...(rangeResponses && { rangeResponses }),\n    pagination,\n    injectIdempotencyKey: hasIdempotencyHeader,\n    deprecated: op.deprecated === true || undefined,\n    async: op['x-oagen-async'],\n    security,\n    parameterGroups,\n    // Present only when the document declares at least one usable tag, as on\n    // a webhook; absent, not undefined, otherwise.\n    ...(tags && { tags }),\n    // The Operation Object's own `x-*` keys, less the ones read into typed\n    // fields above (`OPERATION_CONSUMED_EXTENSIONS`); absent when none remain.\n    ...operationExtensionsEntry(op),\n  };\n\n  // Where the models came from, so a merge pass that must rename one — a\n  // deprecated response named like a live one, say — can qualify it by this\n  // operation and repoint only this operation's references: the response\n  // bundle owns the success bodies, the list envelope and the response\n  // headers; the request bundle owns the body. Qualified by the stem the\n  // operation's models are named from, as its list-envelope companions are:\n  // the `operationId`'s (`operationIdModelBase`: `GetLegacyWidgetWidget`;\n  // `UserListWidget` for `users.list`, beside its `UserListRequest`), else\n  // the path-derived prefix (`PetsByIdLegacyWidgetGetWidget`, beside the\n  // operation's `PetsByIdLegacyWidgetGetResponse`). So the name depends on\n  // the `operationId` or on the method and path alone, never on the\n  // operation's name — a change to what inferOperationName derives or to\n  // what an operationIdTransform makes of the `operationId` renames no type,\n  // unless the transform makes nothing of it, which reads the `operationId`\n  // as absent (readOperationIds). The header and parameter models are\n  // qualified by the same stem (`headerOperationQualifier`, since #537) —\n  // or, when another operation's models are named from that stem too, by\n  // the id PascalCased before the cleaning, which no transform changes\n  // either — so the rule holds for every model the operation mints.\n  const modelQualifier = namingOp.operationId ? operationIdModelBase(namingOp.operationId) : pathModelBaseName;\n  const inlineModelBundles: InlineModelBundle[] = [];\n  // The response site is recorded even when it minted nothing: its array\n  // items may have shared another site's model (`typeInlineItems`), and the\n  // reference must follow that model's rename (`attachSharedRefs`).\n  inlineModelBundles.push({ qualifier: modelQualifier, roots: responseTypeRefs(operation), models: responseModels });\n  if (reqBodyModels.length > 0 && requestBody) {\n    inlineModelBundles.push({ qualifier: modelQualifier, roots: [requestBody], models: reqBodyModels, sent: true });\n  }\n\n  return {\n    operation,\n    inlineModels,\n    inlineModelBundles,\n    envelopeCompanions,\n    operationQualifier,\n    modelQualifier,\n    componentBodies,\n    // The callbacks are read after every webhook is named, under this\n    // operation's label and the stem its own models are named from.\n    ...(op.callbacks !== undefined\n      ? {\n          declaredCallbacks: {\n            owner: operation,\n            callbacks: op.callbacks,\n            label: opLabel,\n            stem: modelQualifier,\n            // The operationId the models are named from (the reuse of its\n            // own may have renamed it), else the method and path.\n            identity: namingOp.operationId ?? `${method.toUpperCase()} ${path}`,\n          },\n        }\n      : {}),\n  };\n}\n\n/**\n * The type references an operation's responses own: the primary and every\n * alternate success body, the list envelope's fields and item type, and\n * every response header. Error bodies are left out: a `$ref` body names a\n * component, which a rename never touches, and an inline one is typed\n * through the deferred registry, where it is a site of its own\n * (`resolveDeferredInlineTypes`), so a rename reaches it from there.\n */\nfunction responseTypeRefs(op: Operation): TypeRef[] {\n  return [\n    op.response,\n    ...(op.successResponses ?? []).map((r) => r.type),\n    ...(op.pagination?.envelopeFields ?? []).map((f) => f.type),\n    ...(op.pagination ? [op.pagination.itemType] : []),\n    ...collectResponseHeaders(op).map((h) => h.type),\n  ];\n}\n\n/**\n * The qualifier that tells one operation's header and parameter models from\n * another's (`deferredNamingStem`'s `byOperationName` candidate), and that\n * the shape registry records as the owner of its models. It is the stem the\n * operation's request and response models are built from, so the model name\n * depends only on the `operationId` or on the method and path and never on\n * the operation's name. An operation with an `operationId` uses the id's\n * stem (`operationIdModelBase`), cleaned exactly as its `…Response` model\n * name is: `Animals_ListNotes` gives `Pets` + `AnimalListNotes` + `XMeta`\n * beside `AnimalListNotesResponse`, and `notes.list` gives `PetsNoteListXMeta`\n * beside `NoteListResponse`, whatever an `operationIdTransform` names the\n * operation — the operation's PascalCase name, before #537, renamed the\n * header and parameter models (`PetsListNotesXMeta`) with every change to\n * the transform while the bodies kept their names. The stem is the\n * operation's own: when two distinct ids clean to one stem\n * (`listNotesByExternalId` beside `listNotes`, `create_pet` beside\n * `createPet`), the operation that loses the contest is path-named before\n * any operation is built (`resolveContestedOperationIdStems`, #627) and\n * reaches here with no `operationId`, so its qualifier is the path-derived\n * stem its bodies are built from (`ByIdNotesByExternalIdGet` beside\n * `PetsByIdNotesByExternalIdGetResponse`) — before #627 one stem named\n * both operations' bodies, so it qualified neither one's header and\n * parameter models and each was qualified by its id as written instead\n * (`PetsListNotesByExternalIdXMeta`), and before #537 the second one's\n * clashing models fell to names that say nothing about the operation\n * (`PetsXMeta200`, `PetsQueryFilter`, `PetsHeaderXTrace`). A stem that\n * names nothing (`ListItem` cleans to nothing) qualifies nothing, so the\n * operation is qualified by its id PascalCased before the cleaning instead\n * (`toPascalCase` of the id, its overload markers stripped), which no\n * transform changes either: `PetsListItemXMeta`. A path-named operation\n * uses the path-derived stem, so a verb or singular change in\n * inferOperationName must not rename a generated type either. That stem's\n * leading service word is dropped when it ends on a word boundary, since\n * the model name already starts with the service: `Notes` + `ByIdPinPost` +\n * `XMeta`, beside `NotesByIdPinPostResponse`.\n */\nfunction headerOperationQualifier(\n  op: OperationObject,\n  pathModelBaseName: string,\n  serviceName: string | undefined,\n): string {\n  if (op.operationId) {\n    return operationIdModelBase(op.operationId) || toPascalCase(normalizeOperationIdForNaming(op.operationId));\n  }\n  const parent = serviceName ? toPascalCase(serviceName) : '';\n  const rest = pathModelBaseName.slice(parent.length);\n  return parent && pathModelBaseName.startsWith(parent) && /^[A-Z0-9]/.test(rest) ? rest : pathModelBaseName;\n}\n\n/** The Path Item fields an operation's doc text is read against (see `resolveOperationDocs`). */\nexport type PathItemDocs = Pick<PathItem, 'summary' | 'description'>;\n\n/** An operation's doc text as the IR carries it, under the names `Operation` and `Webhook` share. */\nexport interface OperationDocs {\n  /** The resolved `summary` alone; `undefined` when neither level has one with content. */\n  summary: string | undefined;\n  /** The resolved `description` alone, never built from the summary (text identical to it is kept); `undefined` when neither level has one with content. */\n  description: string | undefined;\n}\n\n/**\n * The `summary` and `description` of an operation — an SDK operation's or a\n * webhook's — read from the Operation Object and, for each field it declares\n * no content for, from the Path Item it sits on: OpenAPI defines a Path\n * Item's `summary` and `description` as applying to every operation on it.\n * The two fields fall back one by one, so an operation with a `summary` of\n * its own and no `description` shows its own `summary` and the Path Item's\n * `description`. Each is kept on its own, as the document writes it: the\n * `description` is never built from the `summary`, and one identical to it\n * is kept in both, since each is the document's own text. Text with content wins at either\n * level, kept verbatim; a value that is not a string, or is blank, counts as\n * absent at either level (`presentText`), so `summary: \"\"` on the operation\n * still takes the Path Item's. Either field is `undefined` when neither level\n * gives it; the caller decides whether the key is then omitted (`Webhook`) or\n * present (`Operation.description`).\n */\nexport function resolveOperationDocs(op: OperationObject, pathItem: PathItemDocs): OperationDocs {\n  const summary = presentText(op.summary) ?? presentText(pathItem.summary);\n  const description = presentText(op.description) ?? presentText(pathItem.description);\n  return { summary, description };\n}\n\n/** The text itself when it has non-whitespace content, otherwise `undefined`. */\nexport function presentText(text: string | undefined): string | undefined {\n  return typeof text === 'string' && text.trim() !== '' ? text : undefined;\n}\n\n/**\n * An operation's `tags` as the IR carries them, on an `Operation` and on a\n * `Webhook` alike: the list in document order with every entry that is not a\n * string with non-whitespace content (`presentText`) dropped and a repeated\n * entry folded onto its first occurrence, or `undefined` when nothing remains\n * (or the keyword is not a list), so the key is omitted rather than set to\n * `[]`. The service an operation is grouped under is named from the first\n * entry of this same list that has a name (`serviceTag`).\n */\nexport function extractTags(tags: unknown): string[] | undefined {\n  if (!Array.isArray(tags)) return undefined;\n  const kept: string[] = [];\n  for (const tag of tags) {\n    if (typeof tag === 'string' && presentText(tag) !== undefined && !kept.includes(tag)) kept.push(tag);\n  }\n  return kept.length > 0 ? kept : undefined;\n}\n\n/**\n * The media types a parameter's or response header's `content` map is read\n * from, in the order the pick tries them (`selectParameterContent`). Each is\n * matched by essence — `type/subtype` with parameters stripped and case\n * folded (`mediaTypeEssence`), so `application/json; charset=utf-8` and\n * `APPLICATION/JSON` read as `application/json` — and a `+json` media type\n * is JSON. A JSON entry is read only when it declares a schema; a\n * `text/plain` entry is read with or without one, a text value the document\n * does not describe being a string. Any other media type is not read.\n */\nconst PARAMETER_CONTENT_MEDIA_TYPES: ReadonlyArray<{\n  matches: (essence: string) => boolean;\n  schemaRequired: boolean;\n}> = [\n  { matches: (essence) => essence === 'application/json', schemaRequired: true },\n  { matches: (essence) => essence.endsWith('+json'), schemaRequired: true },\n  { matches: (essence) => essence === 'text/plain', schemaRequired: false },\n];\n\n/** The `content` entry a parameter or response header is read from: the key as written and its Media Type Object. */\nexport interface SelectedParameterContent {\n  /** The `content` key the entry was read from, exactly as written (`application/json; charset=utf-8`). */\n  contentType: string;\n  media: ParameterMediaTypeObject;\n}\n\n/**\n * Pick the `content` entry a parameter or response header is typed from, by\n * media type essence in the fixed order of `PARAMETER_CONTENT_MEDIA_TYPES`:\n * `application/json`, then a `+json` media type — each only with a schema —\n * then `text/plain`. Within one tier the first matching key in document\n * order wins. OAS allows the map one entry, so the order decides only for a\n * document that declares more. `undefined` when there is no map, or none of\n * its media types is read; `warnUnreadParameterContent` reports the latter.\n */\nexport function selectParameterContent(\n  content: Record<string, ParameterMediaTypeObject> | undefined,\n): SelectedParameterContent | undefined {\n  if (!content) return undefined;\n  const entries = Object.entries(content);\n  for (const { matches, schemaRequired } of PARAMETER_CONTENT_MEDIA_TYPES) {\n    const match = entries.find(\n      ([contentType, media]) => matches(mediaTypeEssence(contentType)) && (!schemaRequired || media?.schema),\n    );\n    if (match) return { contentType: match[0], media: match[1] ?? {} };\n  }\n  return undefined;\n}\n\n/** What types a parameter or response header: its schema, and the Media Type Object the schema was read from under `content`. */\nexport interface ParameterTyping {\n  /** Absent when the declaration types nothing: the value is a string. */\n  schema?: SchemaObject;\n  /** The picked `content` entry, only when the declaration has no `schema` and the map is read. */\n  media?: ParameterMediaTypeObject;\n  /** The `content` key `media` sits under, as written; set exactly when `media` is. */\n  contentType?: string;\n  /** Every `content` key, as written and in document order, read or not; set when the declaration has no `schema` and the map declares at least one. */\n  contentTypes?: string[];\n}\n\n/**\n * The schema that types a parameter or response header: the declaration's\n * `schema` when it has one, else the schema of the `content` entry\n * `selectParameterContent` picks, with that entry's Media Type Object\n * beside it for the examples it may carry. `schema` is absent — and the\n * value a string — when the declaration has neither, when the picked\n * `text/plain` entry declares no schema, or when nothing in the map is read.\n * Every key the map declares comes back as `contentTypes`, read or not, so\n * an unread map keeps the media type it declares the value in.\n * A `schema` beside a `content` map wins and the map is not consulted.\n * Every pass that asks what a parameter's schema is reads it through this\n * one resolution: the typing (`extractParams`), the model deferral\n * (`deferParameterModels`), the page-start read, a webhook's parameter mint\n * and a response header's typing (`extractResponseHeaders`) — so a\n * parameter declared either way is typed, and mints, by one rule.\n */\nexport function parameterTyping(declaration: SchemaOrContent): ParameterTyping {\n  if (declaration.schema) return { schema: declaration.schema };\n  const contentTypes = Object.keys(declaration.content ?? {});\n  const declared = contentTypes.length > 0 ? { contentTypes } : {};\n  const picked = selectParameterContent(declaration.content);\n  return picked\n    ? { schema: picked.media.schema, media: picked.media, contentType: picked.contentType, ...declared }\n    : declared;\n}\n\n/** The schema `parameterTyping` resolves, alone. */\nexport function parameterSchema(declaration: SchemaOrContent): SchemaObject | undefined {\n  return parameterTyping(declaration).schema;\n}\n\n/**\n * Warn that a parameter's or response header's `content` map is not read:\n * it declares no `schema`, at least one media type, and\n * `selectParameterContent` picks none, so the value is typed as a string.\n * Called once per site — for each operation parameter where the operation's\n * parameters are resolved (`buildOperation`), for each webhook parameter\n * where the webhook's entry is built (the mint itself runs twice), and for\n * each response header as it is typed — while `extractParams` and the\n * passes that re-read the schema stay silent. An empty map declares nothing\n * and is not reported; a map beside a `schema` is not consulted and not\n * reported either.\n */\nexport function warnUnreadParameterContent(declaration: SchemaOrContent, subject: string): void {\n  if (declaration.schema) return;\n  const declared = Object.keys(declaration.content ?? {});\n  if (declared.length === 0 || selectParameterContent(declaration.content)) return;\n  console.warn(\n    `[oagen] Warning: ${subject} is typed as a string: none of its content media types (${declared.join(', ')}) ` +\n      `is read. A parameter or response header declared with content is read from application/json or a +json ` +\n      `media type when the entry declares a schema, and from text/plain with or without one, parameters and ` +\n      `case aside.`,\n  );\n}\n\nexport function extractParams(\n  params: ParameterObject[],\n  location: 'path' | 'query' | 'header' | 'cookie',\n  operationContext?: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  componentExamples?: Record<string, Record<string, unknown>>,\n  opLabel?: string,\n  siblingDocs: SiblingDocs = 'override',\n): Parameter[] {\n  return params\n    .filter((p) => p.in === location)\n    .map((p) => {\n      // The schema that types the parameter — `schema`, else the picked\n      // `content` entry's (`parameterTyping`) — and that entry's Media Type\n      // Object for the examples it may carry. Every read below goes through\n      // `schema`, so a parameter declared either way is typed by one rule.\n      const { schema, media, contentType, contentTypes } = parameterTyping(p);\n      // The one component a bare `$ref` names; an enum component on the\n      // schema it declares its members on (`enumComponentDeclaration`), so\n      // `Kind: { allOf: [{ type: 'string', enum }], description, deprecated\n      // }` is read as the plain spelling is.\n      const target = resolveComponentSchemaRef(schema, componentSchemas);\n      const refTarget = target && (enumComponentDeclaration(target) ?? target);\n      // A `$ref` to an array or primitive component, or to an alias of an\n      // enum component (#560), bare or under a wrapper the type builder\n      // reads through, is read as a field reads one (`componentReference`,\n      // #512 review): the component's limits, and its aliases', through\n      // every entry the reference passes; its text, flags, default and\n      // examples too for a bare `$ref` — through the aliases, nearest first,\n      // then the enum an alias resolves to, as a bare `$ref` to that enum\n      // reads it — while under a wrapper those are the parameter's own, read\n      // from the wrapper and the members beside the `$ref`. Any other `$ref`\n      // falls back to the one component it names, as before. Any other\n      // schema reads the `allOf` members that declare no type and so only\n      // annotate or limit it (`annotatingAllOfMembers`; #555: `allOf: [{\n      // type: 'string' }, { description }]` lost the text), as a field reads\n      // them.\n      const reference = schema ? componentReference(schema, componentSchemas) : undefined;\n      const aliased = reference?.bare && reference.enumComponent ? [reference.enumComponent] : [];\n      const fallbacks: SchemaObject[] = reference\n        ? reference.bare\n          ? [...reference.entries, ...aliased]\n          : reference.own.slice(1)\n        : refTarget\n          ? [refTarget]\n          : schema\n            ? annotatingAllOfMembers(schema)\n            : [];\n      const exampleContext = `parameter \"${p.name}\" in ${opLabel ?? location}`;\n      // Each level is resolved on its own — the parameter's declaration, the\n      // Media Type Object its schema was read from (when it was), the schema,\n      // then the component the schema refs — so a schema-level `example`\n      // can't mask the parameter's own `examples` map, and an explicit `null`\n      // at any level is kept rather than fallen through.\n      const { example, examples } = resolveExamples([\n        {\n          example: p.example,\n          examples: exampleObjectValues(p.examples, componentExamples, exampleContext, siblingDocs),\n        },\n        ...(media\n          ? [\n              {\n                example: media.example,\n                examples: exampleObjectValues(media.examples, componentExamples, exampleContext, siblingDocs),\n              },\n            ]\n          : []),\n        { example: schema?.example, examples: nonEmptyExamples(schema?.examples) },\n        ...fallbacks.map((level) => ({ example: level.example, examples: nonEmptyExamples(level.examples) })),\n      ]);\n      // The parameter's own limits are read as a field's are\n      // (`schemaConstraints`; #545 review): the schema's keywords conjoined\n      // with its `allOf` members' and a nullable wrapper's with its branch's,\n      // level by level, so a keyword written beside an `allOf` member that\n      // writes it too reads as the field and the parameter's type read it\n      // (`pattern: '^a'` beside `allOf: [{ pattern: 'z$' }]` is `^a` on all\n      // three, the schema's own winning; #587 review) — and, for an array or\n      // primitive component, or an alias of an enum component, every entry\n      // the reference passes, each read once with its annotating members'\n      // limits (`limitEntries`; #588 review: the entry's own `pattern` wins\n      // over a member's), conjoined from the component outward\n      // (`combineConstraints`), the stricter bound winning: the wire enforces\n      // the component's limit whatever is written beside the `$ref`, and no\n      // model is left to carry it, so `{ $ref: Limit, minimum: 1 }` beside\n      // `Limit`'s `minimum: 5` keeps `5` (Greptile, review round 3).\n      const own = schema ? schemaConstraints(schema, componentSchemas) : undefined;\n      // Like default/example, any other `$ref` target's keywords fall back per\n      // value under the parameter's own, so `{ $ref: Limit, minimum: 5 }`\n      // narrows one bound without discarding the target's others and a\n      // parameter is readable without chasing the target: a `$ref` to a\n      // model or enum keeps the override, as before — through an alias of\n      // the enum too (#560): the alias's own limits conjoin above, since no\n      // node carries them, and the enum's sit underneath as they sit under a\n      // bare `$ref` to it — and so does a pointer deeper into a component\n      // (#539) until `resolveSchemaPointers` settles the type it lands on,\n      // which then gives the parameter the pointed schema's limits conjoined\n      // with its own, as the field reads them, where that type carries them.\n      const inherited = !reference && refTarget ? extractConstraints(refTarget) : undefined;\n      const conjoined = own && inherited ? { ...inherited, ...own } : (own ?? inherited);\n      const underneath = aliased.length > 0 ? extractConstraints(aliased[0]) : undefined;\n      const constraints = conjoined && underneath ? { ...underneath, ...conjoined } : (conjoined ?? underneath);\n      // The schema's link, else the fallbacks' — the same chain `description`\n      // and `deprecated` follow, with an unusable entry at one level falling\n      // through to the next as an empty description does. A Parameter Object\n      // declares no `externalDocs` of its own.\n      const externalDocs =\n        readExternalDocs(schema?.externalDocs) ??\n        fallbacks.map((level) => readExternalDocs(level.externalDocs)).find((docs) => docs !== undefined);\n      return {\n        name: p.name,\n        // Typed under the name the parameter is compared by (`foldParameterName`:\n        // a header's lower-cased), so the inline enum or model its schema mints\n        // keeps its name when the header's case changes (#295); `name` above\n        // stays as written.\n        type: schema\n          ? schemaToTypeRef(\n              schema,\n              foldParameterName(p.in, p.name),\n              operationContext ? toPascalCase(operationContext) : undefined,\n            )\n          : ({ kind: 'primitive', type: 'string' } as TypeRef),\n        required: p.required ?? false,\n        description: firstDescription(\n          p.description,\n          schema?.description,\n          ...fallbacks.map((level) => level.description),\n        ),\n        deprecated:\n          p.deprecated === true ||\n          schema?.deprecated === true ||\n          fallbacks.some((level) => level.deprecated === true) ||\n          undefined,\n        ...(externalDocs ? { externalDocs } : {}),\n        default: schema?.default ?? fallbacks.find((level) => level.default !== undefined)?.default,\n        example,\n        ...(examples ? { examples } : {}),\n        style: p.style as Parameter['style'],\n        explode: p.explode,\n        // The media type the value is serialized in, for a parameter read\n        // from `content`; a `schema` parameter is serialized by style/explode.\n        ...(contentType !== undefined ? { contentType } : {}),\n        // Every media type the `content` map declares, read or not, so a map\n        // none of whose media types is read keeps the one it declares.\n        ...(contentTypes !== undefined ? { contentTypes } : {}),\n        ...(constraints ? { constraints } : {}),\n      };\n    });\n}\n\n/**\n * First non-empty description in precedence order. A parameter that declares\n * `description: \"\"` is treated as undocumented so its schema's text still\n * surfaces, and the result is `undefined` rather than `\"\"` when nothing in\n * the chain is documented.\n */\nfunction firstDescription(...candidates: Array<string | undefined>): string | undefined {\n  return candidates.find((candidate) => typeof candidate === 'string' && candidate.length > 0);\n}\n\n/**\n * Flatten a parameter's `examples` map of Example Objects to the inline\n * values it carries, in document order. A `$ref` entry is resolved against\n * `components.examples` first (see `resolveExampleRef`). Entries that point\n * elsewhere (`externalValue`) or have no `value` are skipped; `null` is a\n * legitimate value and kept. Returns undefined when nothing remains so the\n * caller can fall through to the schema's `examples`.\n */\nfunction exampleObjectValues(\n  examples: Record<string, ExampleObject> | undefined,\n  componentExamples: Record<string, Record<string, unknown>> | undefined,\n  context: string,\n  siblingDocs: SiblingDocs = 'override',\n): unknown[] | undefined {\n  if (!examples || typeof examples !== 'object' || Array.isArray(examples)) return undefined;\n  const values: unknown[] = [];\n  for (const raw of Object.values(examples)) {\n    const entry = resolveExampleRef(raw, componentExamples, context, siblingDocs);\n    if (!entry || typeof entry !== 'object') continue;\n    if (entry.externalValue !== undefined || entry.value === undefined) continue;\n    values.push(entry.value);\n  }\n  return values.length > 0 ? values : undefined;\n}\n\n/**\n * Follow an Example Object's `$ref` into `components.examples`, including a\n * component that is itself a `$ref`, with a cycle guard. The bundler keeps\n * refs (`dereference: false`), so without this every `$ref` entry would be\n * dropped and a map made only of refs would silently yield nothing — the\n * parameter would then take its `examples` from the schema instead of the\n * values the document points at. A ref that can't be resolved is skipped\n * with a warning rather than failing the parse: a missing example is a doc\n * gap, not a broken API surface.\n */\nfunction resolveExampleRef(\n  raw: ExampleObject | undefined,\n  componentExamples: Record<string, Record<string, unknown>> | undefined,\n  context: string,\n  siblingDocs: SiblingDocs = 'override',\n): ExampleObject | undefined {\n  // An entry that is not an object is no example; the caller skips it.\n  if (!raw || typeof raw !== 'object') return undefined;\n  // The walk every Reference Object takes (`followReference`): a `summary`\n  // or `description` written beside a ref overrides the component's under\n  // `'override'` (OAS 3.1) and is ignored under `'ignore'` (OAS 3.0), though\n  // only the example's `value` is read into the IR (`exampleObjectValues`).\n  const followed = followReference<ExampleObject>(raw, 'examples', componentExamples, siblingDocs);\n  if (followed.outcome === 'circular') {\n    console.warn(`[oagen] Warning: Circular example $ref chain starting at \"${followed.ref}\" on ${context}; skipping`);\n    return undefined;\n  }\n  if (followed.outcome !== 'resolved') {\n    console.warn(`[oagen] Warning: Unresolved example $ref \"${followed.ref}\" on ${context}; skipping`);\n    return undefined;\n  }\n  return followed.value;\n}\n\n/**\n * Collect the property schemas of every `oneOf` branch reachable from a request\n * body schema, keyed by property name. These are the candidate members of a\n * mutually-exclusive body group.\n *\n * The bundler runs with `dereference: false`, so the body schema is very often\n * a bare `{ $ref: '#/components/schemas/XDto' }` and the `allOf`/`oneOf`\n * composition that actually declares the variant properties lives on the\n * component. Walking without resolving refs finds nothing, and every group\n * member then falls back to `string` — an SDK that compiles but types\n * object-valued members (e.g. a connection's `saml_options`) as plain strings.\n *\n * Composition keywords nest and may themselves be refs, so resolve and recurse\n * at each level. `seen` guards against a schema that (directly or transitively)\n * refs itself.\n */\nfunction collectVariantFieldSchemas(\n  schema: SchemaObject | undefined,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  owner: string | undefined = undefined,\n  out: Map<string, VariantFieldSchema> = new Map(),\n  seen: Set<string> = new Set(),\n): Map<string, VariantFieldSchema> {\n  if (!schema) return out;\n\n  const ref = (schema as { $ref?: string }).$ref;\n  if (ref) {\n    if (seen.has(ref)) return out;\n    seen.add(ref);\n    const target = resolveComponentSchemaRef(schema, componentSchemas);\n    // Descending into a component makes it the owner of everything below, so\n    // inline members get the same synthesized names the model emitter gives\n    // them (`CreateUser` + `password_hash_type` -> CreateUserPasswordHashType).\n    // A pointer deeper into a component names a schema and no model (#539),\n    // so what it lands on stays under the owner at hand.\n    const key = componentKeyOf(ref);\n    const nextOwner = key !== undefined ? resolveSchemaName(key) : owner;\n    return collectVariantFieldSchemas(target, componentSchemas, nextOwner, out, seen);\n  }\n\n  // A `oneOf` branch is the group-variant carrier: its properties are the\n  // members. Record them, then keep descending — branches nest in real specs.\n  for (const variant of schema.oneOf ?? []) {\n    const variantKey = componentKeyOf((variant as { $ref?: string }).$ref);\n    const resolved = resolveComponentSchemaRef(variant, componentSchemas) ?? variant;\n    const variantOwner = variantKey !== undefined ? resolveSchemaName(variantKey) : owner;\n    for (const [name, fieldSchema] of Object.entries(resolved.properties ?? {})) {\n      if (fieldSchema) out.set(name, { schema: fieldSchema, owner: variantOwner });\n    }\n    collectVariantFieldSchemas(variant, componentSchemas, owner, out, seen);\n  }\n\n  for (const sub of schema.allOf ?? []) collectVariantFieldSchemas(sub, componentSchemas, owner, out, seen);\n  for (const sub of schema.anyOf ?? []) collectVariantFieldSchemas(sub, componentSchemas, owner, out, seen);\n\n  return out;\n}\n\n/** A group member's schema plus the component that owns it, for inline naming. */\ninterface VariantFieldSchema {\n  schema: SchemaObject;\n  owner: string | undefined;\n}\n\nexport type RequestBodyEncoding = 'json' | 'form-data' | 'form-urlencoded' | 'binary' | 'text';\n\n/** HTTP methods whose request body is the primary parameter carrier. */\nconst BODY_CARRYING_METHODS: ReadonlySet<HttpMethod> = new Set<HttpMethod>(['post', 'put', 'patch']);\n\n/**\n * The media types a request body is read from, in the order the pick tries\n * them (`selectRequestBodyContent`). Each is matched by essence — `type/subtype`\n * with parameters stripped and case folded (`mediaTypeEssence`), so\n * `application/json; charset=utf-8`, `APPLICATION/JSON` and\n * `multipart/form-data; boundary=x` read as their bare types — and a `+json`\n * media type (`application/vnd.api+json`, `application/merge-patch+json`) is\n * JSON. A media range (`application/*`, `application/*+json`) is never read:\n * the picked essence is the request's `Content-Type`, which a range cannot\n * be. A JSON or form body is read only when it declares a schema, so an\n * `application/json` entry without one yields to a later media type that has\n * one; a binary or text body may legitimately declare none.\n */\nconst REQUEST_BODY_MEDIA_TYPES: ReadonlyArray<{\n  matches: (essence: string) => boolean;\n  encoding: RequestBodyEncoding;\n  schemaRequired: boolean;\n}> = [\n  // The one JSON rule requests and responses share (`isJsonMediaType`), in\n  // the order `jsonResponseSchema` applies it: `application/json` itself\n  // first, then any `+json` type — on a request a concrete one only, while a\n  // response is still read under `application/*+json`.\n  { matches: isPlainJsonMediaType, encoding: 'json', schemaRequired: true },\n  {\n    matches: (essence) => isJsonMediaType(essence) && !isPlainJsonMediaType(essence) && !essence.includes('*'),\n    encoding: 'json',\n    schemaRequired: true,\n  },\n  { matches: (essence) => essence === 'multipart/form-data', encoding: 'form-data', schemaRequired: true },\n  {\n    matches: (essence) => essence === 'application/x-www-form-urlencoded',\n    encoding: 'form-urlencoded',\n    schemaRequired: true,\n  },\n  { matches: (essence) => essence === 'application/octet-stream', encoding: 'binary', schemaRequired: false },\n  { matches: (essence) => essence === 'text/plain', encoding: 'text', schemaRequired: false },\n];\n\n/** The wire encoding a media type implies by essence (`REQUEST_BODY_MEDIA_TYPES`); `undefined` for one the pick never reads. */\nfunction requestBodyEncodingOf(contentType: string): RequestBodyEncoding | undefined {\n  const essence = mediaTypeEssence(contentType);\n  return REQUEST_BODY_MEDIA_TYPES.find(({ matches }) => matches(essence))?.encoding;\n}\n\n/**\n * The type of a request content entry that declares no schema, by media type\n * essence: a binary string for `application/octet-stream`, a string for\n * `text/plain` (`schemalessRequestBodyType`), and `unknown` for anything\n * else — a JSON or form media type included, since the pick reads those only\n * with a schema. How a secondary entry of `requestBodyContents` is typed, on\n * an operation and on a webhook alike.\n */\nexport function schemalessRequestContentType(contentType: string): TypeRef {\n  const encoding = requestBodyEncodingOf(contentType);\n  return (encoding && schemalessRequestBodyType(encoding)) ?? { kind: 'primitive', type: 'unknown' };\n}\n\n/** The content entry a request body is read from: the key as written, its essence, its wire encoding and its schema. */\nexport interface SelectedRequestBodyContent {\n  /** The `content` key the body was read from, exactly as written (`application/json; charset=utf-8`). */\n  contentType: string;\n  /** The essence of `contentType` (`application/json`): what an emitter sends as the `Content-Type` (`Operation.requestBodyContentType`). */\n  essence: string;\n  encoding: RequestBodyEncoding;\n  /** Absent only for a binary or text body that declares none. */\n  schema?: SchemaObject;\n}\n\n/**\n * Pick the content entry a request body is read from, by media type essence\n * in the fixed order of `REQUEST_BODY_MEDIA_TYPES`: `application/json`, then\n * a concrete `+json` media type, then `multipart/form-data`, then\n * `application/x-www-form-urlencoded` — each only with a schema — then\n * `application/octet-stream`, then `text/plain`. Within one tier the first\n * matching key in document order wins. `undefined` when the body declares no\n * content, or none of its media types is read; `warnUnreadRequestBody`\n * reports the latter. Every pass that asks what the body is — the body\n * extractor, the body-owned query names, the const prefixes, the body\n * parameter groups, a webhook payload — reads it through this one pick.\n */\nexport function selectRequestBodyContent(body: RequestBodyObject | undefined): SelectedRequestBodyContent | undefined {\n  const content = body?.content;\n  if (!content) return undefined;\n  const entries = Object.entries(content);\n  for (const { matches, encoding, schemaRequired } of REQUEST_BODY_MEDIA_TYPES) {\n    const match = entries.find(\n      ([contentType, media]) => matches(mediaTypeEssence(contentType)) && (!schemaRequired || media?.schema),\n    );\n    if (match) {\n      return { contentType: match[0], essence: mediaTypeEssence(match[0]), encoding, schema: match[1]?.schema };\n    }\n  }\n  return undefined;\n}\n\n/**\n * Warn that a request body is not read as `requestBody`: it declares at\n * least one media type and `selectRequestBodyContent` reads none, so\n * `requestBody` and `requestBodyEncoding` stay unset and the body reaches an\n * emitter through `requestBodyContents` alone. Called once per operation\n * (`extractRequestBody`) and once per webhook (where its entry is built: a\n * webhook is minted twice, so the mint itself must not report), while the\n * passes that re-read the pick for an operation (the body-owned query names,\n * the const prefixes, the body parameter groups) stay silent — so such a\n * body is reported once, and never silently. A body with no `content`, or an\n * empty map, declares nothing and is not reported.\n */\nexport function warnUnreadRequestBody(body: RequestBodyObject | undefined, label: string): void {\n  const declared = Object.keys(body?.content ?? {});\n  if (declared.length === 0 || selectRequestBodyContent(body)) return;\n  console.warn(\n    `[oagen] Warning: Request body of ${label} is not read as requestBody: none of its media types ` +\n      `(${declared.join(', ')}) is one the parser reads — application/json or a concrete +json media type, ` +\n      `multipart/form-data or application/x-www-form-urlencoded with a schema, application/octet-stream or ` +\n      `text/plain with or without one, parameters and case aside. It is carried in requestBodyContents only.`,\n  );\n}\n\n/**\n * The doc text an operation or a webhook carries for its request body\n * (`Operation.requestBodyDescription`, `Webhook.requestBodyDescription`): the\n * Request Body Object's own `description` — `body` is read after a\n * `components/requestBodies` `$ref` is resolved — when it has non-whitespace\n * content, else the `description` written on the schema of the content entry\n * the pick reads (`selected`, from `selectRequestBodyContent`), as it stands\n * there: a `$ref` is not followed, so a component's text stays on its model,\n * while a `description` written beside the `$ref` is read, as a field reads\n * one. A wrapper the type builder collapses — a nullable `oneOf`/`anyOf`, a\n * single-member `allOf` — or keeps as a union of one variant it types by the\n * same rule — a single-member `oneOf`/`anyOf` — is read by the rule the enum\n * lifted from its branch follows (`unwrapCollapsedWrappers`): its own text\n * when it has content, else its branch's. `undefined` when neither has content; a\n * body none of whose media types is read has no `selected` and carries its\n * own text alone. The text is kept verbatim. Every reader of a body — the\n * operation extractor and the webhook builder — takes the body's doc text\n * from here.\n */\nexport function requestBodyDescriptionOf(\n  body: RequestBodyObject | undefined,\n  selected: SelectedRequestBodyContent | undefined,\n): string | undefined {\n  const schema = selected?.schema;\n  return (\n    presentText(body?.description) ?? (schema ? presentText(unwrapCollapsedWrappers(schema).description) : undefined)\n  );\n}\n\n/**\n * The type of a picked request body that declares no schema: a binary body is\n * a binary string, a text body a string. A JSON or form body is picked only\n * with a schema (`REQUEST_BODY_MEDIA_TYPES`), so for those encodings this is\n * never reached and returns `undefined`.\n */\nexport function schemalessRequestBodyType(encoding: RequestBodyEncoding): TypeRef | undefined {\n  if (encoding === 'binary') return { kind: 'primitive', type: 'string', format: 'binary' };\n  if (encoding === 'text') return { kind: 'primitive', type: 'string' };\n  return undefined;\n}\n\n/** Parameter names referenced by any `x-mutually-exclusive-parameter-groups` variant. */\nfunction collectParameterGroupMemberNames(op: OperationObject): Set<string> {\n  const names = new Set<string>();\n  const raw = op['x-mutually-exclusive-parameter-groups'];\n  if (!raw || typeof raw !== 'object') return names;\n  // Malformed shapes are left for extractParameterGroups to report.\n  for (const groupDef of Object.values(raw)) {\n    const variants = groupDef && typeof groupDef === 'object' ? groupDef.variants : undefined;\n    if (!variants || typeof variants !== 'object') continue;\n    for (const members of Object.values(variants)) {\n      if (!Array.isArray(members)) continue;\n      for (const member of members) if (typeof member === 'string') names.add(member);\n    }\n  }\n  return names;\n}\n\n/**\n * Every property name a request body is guaranteed to accept, following\n * `$ref`s and descending through composition. `allOf` members all apply, so\n * their properties union. `oneOf` / `anyOf` alternatives are choices, so only\n * a property every non-null alternative declares counts — otherwise a caller\n * on another branch would have no slot for the value in either the body or\n * the query. Used to decide which `in: query` declarations are body-owned.\n */\nfunction collectBodyPropertyNames(\n  schema: SchemaObject | undefined,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  seen: ReadonlySet<string> = new Set(),\n): Set<string> {\n  if (!schema) return new Set();\n\n  const ref = (schema as { $ref?: string }).$ref;\n  if (ref) {\n    // Cycle guard is per path: the same component may legitimately appear in\n    // sibling branches and must count for each of them.\n    if (seen.has(ref)) return new Set();\n    return collectBodyPropertyNames(\n      resolveComponentSchemaRef(schema, componentSchemas),\n      componentSchemas,\n      new Set([...seen, ref]),\n    );\n  }\n\n  const names = new Set(Object.keys(schema.properties ?? {}));\n  for (const sub of schema.allOf ?? []) {\n    for (const name of collectBodyPropertyNames(sub, componentSchemas, seen)) names.add(name);\n  }\n  for (const alternatives of [schema.oneOf, schema.anyOf]) {\n    const branches = (alternatives ?? []).filter((alt) => !isNullSchema(alt));\n    if (branches.length === 0) continue;\n    let common: Set<string> | undefined;\n    for (const branch of branches) {\n      const branchNames = collectBodyPropertyNames(branch, componentSchemas, seen);\n      common = common ? new Set([...common].filter((name) => branchNames.has(name))) : branchNames;\n    }\n    for (const name of common ?? []) names.add(name);\n  }\n  return names;\n}\n\n/** What request body typing needs beyond the body: where deferred schemas go and how their names are qualified. */\ninterface RequestTypingContext {\n  /** Collects every secondary-body schema, named after the operations loop (`resolveDeferredInlineTypes`). */\n  deferred: DeferredInlineType[];\n  /** Qualifies a name taken across operations (see `headerOperationQualifier`). */\n  operationQualifier: string;\n  /** Lets inline models resolve `$ref` siblings and augmentations the way fields do. */\n  componentSchemas?: Record<string, SchemaObject>;\n}\n\n/** The request body an operation carries: the picked entry typed, every declared media type with its type, and its doc text. */\ninterface ExtractedRequestBody {\n  body?: TypeRef;\n  encoding?: RequestBodyEncoding;\n  /** The body's doc text (`Operation.requestBodyDescription`, `requestBodyDescriptionOf`); absent when there is none. */\n  description?: string;\n  /** The picked entry's essence (`Operation.requestBodyContentType`); set exactly when `body` is. */\n  contentType?: string;\n  contentTypes?: string[];\n  contents?: RequestBodyContent[];\n}\n\n/**\n * The name an operation's inline request body is materialized under:\n * `<Op>Request` from the `operationId` (`operationIdModelName`), else the\n * path-derived prefix plus `Request` (see derivePathModelBaseName) so two\n * operations without an `operationId` never share one inline body model —\n * every operationId-less body used to be `RequestBody`, and only the largest\n * survived deduplication, leaving every other operation pointing at a model\n * with someone else's fields.\n */\nfunction requestModelName(op: OperationObject | undefined, pathModelBaseName: string): string {\n  return op?.operationId ? operationIdModelName(op.operationId, 'Request') : pathModelBaseName + 'Request';\n}\n\n/**\n * The stem a secondary request body's model is named from: the primary\n * body's name without its `Request` suffix, followed by the media type and\n * `Request` — `ReplaceWidgetTextCsvRequest` beside `ReplaceWidgetRequest` —\n * the way a secondary response body's stem is the primary response's name\n * without `Response`.\n */\nfunction requestModelStem(op: OperationObject | undefined, pathModelBaseName: string): string {\n  return requestModelName(op, pathModelBaseName).replace(/Request$/, '');\n}\n\n/**\n * Read an operation's request body: the content entry the pick chooses\n * (`selectRequestBodyContent`) typed as `body` with its `encoding`, and every\n * media type the body declares as `contentTypes` / `contents`, the picked\n * entry sharing `body`'s TypeRef (`extractRequestBodyContents`), and the\n * body's doc text as `description` (`requestBodyDescriptionOf`). A body none\n * of whose media types is read is reported once and carried in `contents`\n * alone, with its own `description` when it declares one.\n */\nfunction extractRequestBody(\n  body: RequestBodyObject | undefined,\n  op: OperationObject | undefined,\n  pathModelBaseName: string,\n  inlineModels: Model[],\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  opLabel: string,\n  ctx: RequestTypingContext,\n): ExtractedRequestBody {\n  const selected = selectRequestBodyContent(body);\n  if (!selected) warnUnreadRequestBody(body, opLabel);\n  const primary = selected ? typeRequestBody(selected, op, pathModelBaseName, inlineModels, componentSchemas) : {};\n  const contents = extractRequestBodyContents(\n    body?.content,\n    selected?.contentType,\n    primary.body,\n    requestModelStem(op, pathModelBaseName),\n    ctx,\n  );\n  const description = requestBodyDescriptionOf(body, selected);\n  return { ...primary, ...contents, ...(description !== undefined && { description }) };\n}\n\n/**\n * Read a request body's `content` map into the media types it declares — in\n * document order and verbatim, parameters and vendor suffixes included — with\n * a type for each, as `extractResponseContents` reads a response's. The entry\n * for `primaryContentType` (the one the pick read `primaryType` from) carries\n * that very TypeRef; every other entry goes through\n * `typeSecondaryRequestContent`. `undefined` when the body declares no media\n * type at all, so the caller leaves both keys off.\n */\nfunction extractRequestBodyContents(\n  content: Record<string, { schema?: SchemaObject }> | undefined,\n  primaryContentType: string | undefined,\n  primaryType: TypeRef | undefined,\n  stem: string,\n  ctx: RequestTypingContext,\n): { contentTypes: string[]; contents: RequestBodyContent[] } | undefined {\n  if (!content) return undefined;\n  const contentTypes = Object.keys(content);\n  if (contentTypes.length === 0) return undefined;\n  const contents = contentTypes.map((contentType): RequestBodyContent => ({\n    contentType,\n    type: { kind: 'primitive', type: 'unknown' },\n  }));\n  // Typed — so deferred, and named — in naming order; listed as written.\n  for (const contentType of mediaTypeNamingOrder(contentTypes)) {\n    const entry = contents[contentTypes.indexOf(contentType)];\n    entry.type =\n      primaryType !== undefined && contentType === primaryContentType\n        ? primaryType\n        : typeSecondaryRequestContent(contentType, content[contentType]?.schema, stem, ctx, entry, contentTypes);\n  }\n  return { contentTypes, contents };\n}\n\n/**\n * Type a media type the request body pick did not choose, as it would be\n * typed were it the only one declared: from its schema when it has one — an\n * inline object materialized as `<Op><MediaType>Request`\n * (`ReplaceWidgetTextCsvRequest`), named once every primary model is known\n * (`resolveDeferredInlineTypes`), so the schema is deferred and the\n * placeholder returned here is filled in then — else as\n * `schemalessRequestContentType` types it. The media type's fragment is\n * decided among its `siblings`, the body's content keys\n * (`mediaTypeNameFragment`): two spellings of one media type declared side\n * by side take separate names by the parameters `oagen diff` compares, or by\n * a `charset` when nothing else tells them apart, and spellings still left\n * with one name are told apart by the registry, in the order\n * `extractRequestBodyContents` types them (`mediaTypeNamingOrder`).\n */\nfunction typeSecondaryRequestContent(\n  contentType: string,\n  schema: SchemaObject | undefined,\n  stem: string,\n  ctx: RequestTypingContext,\n  target: RequestBodyContent,\n  siblings: readonly string[],\n): TypeRef {\n  if (!schema) return schemalessRequestContentType(contentType);\n  ctx.deferred.push({\n    kind: 'request',\n    schema,\n    name: `${stem}${mediaTypeNameFragment(contentType, siblings)}Request`,\n    operationQualifier: ctx.operationQualifier,\n    componentSchemas: ctx.componentSchemas,\n    targets: [target],\n  });\n  return target.type;\n}\n\n/**\n * The picked content entry typed as `Operation.requestBody`, with its\n * encoding and its essence (`Operation.requestBodyContentType`), and its\n * inline models pushed to `inlineModels`.\n */\nfunction typeRequestBody(\n  selected: SelectedRequestBodyContent,\n  op: OperationObject | undefined,\n  pathModelBaseName: string,\n  inlineModels: Model[],\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): { body?: TypeRef; encoding?: RequestBodyEncoding; contentType?: string } {\n  const typed = typePickedRequestBody(selected, op, pathModelBaseName, inlineModels, componentSchemas);\n  return typed ? { body: typed, encoding: selected.encoding, contentType: selected.essence } : {};\n}\n\n/**\n * The picked content entry's type: a primitive for a schema-less binary or\n * text body, else typed from its schema. An inline object is the model\n * `<Op>Request`; a `oneOf` of inline objects, `$ref`s or other variants is\n * built as a union, variant by variant, its inline object variants named\n * from the body (`deriveOneOfVariantName`); everything else — an `anyOf`,\n * an array, a map, a `$ref`, a primitive, a nullable wrapper around one of\n * those — is typed by `schemaToTypeRef`, as a field of the same schema is.\n * A `oneOf` whose every non-null variant is a string `const` (an OAS 3.0\n * single-value `enum` counts) — two or more, or any number beside an\n * `enum:` list — declares an enum, not a union to build\n * (`inlineEnumSpelling`), so it is typed by `schemaToTypeRef` too: the\n * body is the enum `<Op>Request` (`AddNoteRequest`), each variant's\n * `description` and `deprecated` its member's, exactly as the same `anyOf`\n * body, the same schema as a webhook payload or on a field, is typed; a\n * `null` variant beside the consts, or `nullable: true` / `type: [...,\n * 'null']` beside the union, makes it `nullable<AddNoteRequest>`\n * (workos/oagen#603: the `oneOf` was built as a union of literals, the\n * members' text lost, and switching `anyOf` to `oneOf` read as breaking).\n * A `oneOf` that mixes consts with any other variant — a `$ref`, an\n * object, a bare `type: 'string'`, a number const — is a union, here as\n * everywhere.\n */\nfunction typePickedRequestBody(\n  selected: SelectedRequestBodyContent,\n  op: OperationObject | undefined,\n  pathModelBaseName: string,\n  inlineModels: Model[],\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): TypeRef | undefined {\n  let schema = selected.schema;\n\n  // Only a binary or text pick comes without a schema; it is a primitive.\n  if (!schema) return schemalessRequestBodyType(selected.encoding);\n\n  const contextName = requestModelName(op, pathModelBaseName);\n\n  // `properties` written beside a typing `allOf`/`oneOf`/`anyOf` are folded\n  // into the composition, as `schemaToTypeRef` and the field extractor read\n  // them (`foldSiblingProperties`), so the body is read the one way a field\n  // of the same schema is: the object branch below reads `properties` first\n  // and would otherwise drop the composition. The variants that cannot take\n  // the properties are reported on the body as written, under the body's\n  // name, since the fold leaves `schemaToTypeRef` nothing to report.\n  warnOnUncarriedProperties(schema, contextName, undefined);\n  schema = foldSiblingProperties(schema);\n\n  // A discriminated-union request body (`oneOf` + an explicit `discriminator`)\n  // compiles to a `oneOf` that code generators can't spread into named method\n  // arguments — the caller is handed an opaque union and the generated snippets\n  // carry no body fields. When every variant is an inline object pinned by a\n  // string-const discriminator, the union is equivalent to a single object, so\n  // fold it into that object and let the normal object path below emit\n  // ergonomic, spread-able arguments. See flattenDiscriminatedUnionBody.\n  if (schema.oneOf && schema.discriminator) {\n    const merged = flattenDiscriminatedUnionBody(schema, componentSchemas);\n    if (merged) schema = merged;\n  }\n\n  // If the request body is an inline object with properties, extract it as a\n  // model. An empty `properties: {}` beside a composition that types the\n  // body is not its object (`composedWithoutFields`): the `oneOf` branch or\n  // the fall-through reads the composition, as for a response body.\n  if (schema.properties && !composedWithoutFields(schema) && (schema.type === 'object' || !schema.type)) {\n    const requiredSet = new Set(schema.required ?? []);\n    const siblings = collectProperties(schema);\n    const fields: Field[] = [];\n    for (const [fieldName, fieldSchema] of Object.entries(schema.properties)) {\n      if (!fieldSchema) continue;\n      fields.push(buildFieldFromSchema(fieldName, fieldSchema, contextName, requiredSet, componentSchemas, siblings));\n    }\n    inlineModels.push({\n      name: contextName,\n      description: schema.description,\n      ...externalDocsEntry(schema.externalDocs),\n      fields,\n      ...deprecatedEntry(schema),\n      ...constraintsEntry(schema),\n      ...schemaExtensionsEntry(schema),\n    });\n    // Nested inline objects (e.g. a `user` property that is itself an inline\n    // object) are referenced by name from the fields above but are not emitted\n    // by this branch. Recurse to materialize them, matching how component\n    // schemas are handled in extractInlineModelsFromSchemas — otherwise the\n    // generated body model references a model that never gets generated.\n    extractInlineModelsFromProperties(schema, inlineModels, contextName, componentSchemas);\n    return { kind: 'model', name: contextName };\n  }\n\n  // A nullable body (`oneOf: [object, null]`) is one schema: the model built\n  // from its object branch takes the wrapper's `deprecated` and limits, as\n  // every other nullable unwrap gives it (`collapsedNullableBranch`). The\n  // null branch still makes the body nullable below. A multi-variant union,\n  // nullable or not, is not collapsed: every variant is built as written. A\n  // nullable wrapper around one branch that is not an inline object — an\n  // array (`oneOf: [{ items }, { type: 'null' }]`), a `$ref`, a primitive —\n  // is not a union to build: it takes the fall-through, where\n  // `schemaToTypeRef` types it as it types the same wrapper on a field or a\n  // parameter (`nullable<CreatePetsRequest[]>`, `nullable<Pet>`) and the\n  // array's inline items are named from the body (`CreatePetsRequest`), the\n  // way `type: ['array', 'null']` and `nullable: true` already are.\n  const branch = collapsedNullableBranch(schema);\n  // Whether the body is such a wrapper is told at the union's own level —\n  // one non-null variant beside `null`, and no `allOf` beside the union —\n  // not by `branch` alone: a nullable `oneOf` whose one variant is a const\n  // read as an enum beside an `enum:` list has no branch, since the enum is\n  // decided first, as the type builder decides it (workos/oagen#535), and is\n  // no union to build either. It takes the fall-through, where\n  // `schemaToTypeRef` types it as the nullable enum it is, as it did while\n  // its const was still read as a branch. Under an `allOf` beside the\n  // union `nullableUnionBranch` gives no branch either, and there the\n  // `oneOf` is still built as written, the `allOf` aside: `{ allOf:\n  // [{ $ref: Owner }], oneOf: [{ type: 'object', properties: { nickname } },\n  // { type: 'null' }] }` is `nullable<union[AddPetRequest]>`, as it was\n  // before #535, not the `Owner` a field with the same schema gets.\n  const nullableWrapper =\n    schema.allOf === undefined &&\n    schema.oneOf !== undefined &&\n    schema.oneOf.some(isNullSchema) &&\n    schema.oneOf.filter((v) => !isNullSchema(v)).length === 1;\n\n  // A `oneOf` of string consts is an enum, not a union to build: whether it\n  // is one is the one decision `schemaToTypeRef` makes (`inlineEnumSpelling`),\n  // on the schema with its nullable wrappers removed, as that builder sees\n  // it (`unwrapNullableSchema`) — so `nullable: true` or `type: ['string',\n  // 'null']` beside the `oneOf` hides nothing, and a lone const beside\n  // `null` with no `enum:` list, which that unwrap collapses to the const,\n  // is no enum and stays the nullable literal the wrapper rule above gives\n  // it. Such a `oneOf` takes the fall-through, where it is typed as the\n  // same `anyOf` is: the enum `<Op>Request`, nullable when the schema is\n  // (workos/oagen#603: it was built below, a union of literals with no\n  // enum and no member text, while `anyOf` and the webhook payload were\n  // the enum).\n  const constUnion = inlineEnumSpelling(unwrapNullableSchema(schema))?.spelling === 'const-union';\n\n  // If the request body is a oneOf, extract each variant as an inline model\n  // and build a union type pointing to them by name.\n  if (schema.oneOf && !constUnion && (!nullableWrapper || (branch !== undefined && isInlineObjectSchema(branch)))) {\n    const variants: TypeRef[] = [];\n    // The inline object variants of this union and the names its const-less\n    // variants have taken so far, for `deriveOneOfVariantName`.\n    const inlineObjectVariants = schema.oneOf.filter(\n      (v) => !v.$ref && v.properties && (v.type === 'object' || !v.type),\n    );\n    const contentNamed: string[] = [];\n\n    // The inline object variants are named and built first, in order, so the\n    // other variants' contexts can step around their names and their\n    // children's (`nonObjectVariantContexts`).\n    const objectVariantNames = new Map<SchemaObject, string>();\n    for (const variant of inlineObjectVariants) {\n      const named = deriveOneOfVariantName(\n        variant,\n        contextName,\n        inlineModels,\n        inlineObjectVariants,\n        contentNamed,\n        Boolean(op?.operationId),\n      );\n      const variantName = named.name;\n      if (named.fromContent) contentNamed.push(variantName);\n      objectVariantNames.set(variant, variantName);\n      const source = branch ?? variant;\n      const requiredSet = new Set(source.required ?? []);\n      const siblings = collectProperties(source);\n      const fields: Field[] = [];\n      for (const [fieldName, fieldSchema] of Object.entries(source.properties ?? {})) {\n        if (!fieldSchema) continue;\n        fields.push(buildFieldFromSchema(fieldName, fieldSchema, variantName, requiredSet, componentSchemas, siblings));\n      }\n      inlineModels.push({\n        name: variantName,\n        description: source.description,\n        ...externalDocsEntry(source.externalDocs),\n        fields,\n        ...deprecatedEntry(source),\n        ...constraintsEntry(source),\n        ...schemaExtensionsEntry(source),\n      });\n      extractInlineModelsFromProperties(source, inlineModels, variantName, componentSchemas);\n    }\n    // Every other variant that mints a name — an array or map, a nested\n    // union, a nullable wrapper around an object, an `allOf`, an inline enum\n    // — is typed under the context `nonObjectVariantContexts` gives it, apart\n    // from the object variants' names, and materialized by the field\n    // extractor under that context, so the body never references a model the\n    // parser did not create: the variants of a union nested under the body's\n    // second variant are `CreateThingRequestVariant2`,\n    // `BCreateThingRequestVariant2`, never `CreateThingRequest` again.\n    const variantContexts = nonObjectVariantContexts(\n      contextName,\n      schema.oneOf,\n      undefined,\n      undefined,\n      objectVariantNames,\n    );\n    for (const [variant, { context, reserved }] of variantContexts) {\n      extractInlineModelsFromProperties(\n        { properties: { [context]: unwrapNullableField(variant) } },\n        inlineModels,\n        undefined,\n        componentSchemas,\n        undefined,\n        reserved,\n      );\n    }\n\n    for (const variant of schema.oneOf) {\n      if (variant.$ref) {\n        const ref = schemaToTypeRef(variant, contextName);\n        variants.push(ref);\n      } else if (isNullSchema(variant)) {\n        // skip null variant in union, handle separately\n      } else {\n        const variantName = objectVariantNames.get(variant);\n        const entry = variantContexts.get(variant);\n        // A `oneOf` of one variant types it with the body's documentation, as\n        // `schemaToTypeRef` types the same union anywhere else (`withWrapperDocs`).\n        const typed = schema.oneOf.length === 1 ? withWrapperDocs(variant, schema) : variant;\n        variants.push(\n          variantName !== undefined\n            ? { kind: 'model', name: variantName }\n            : entry\n              ? schemaToTypeRef(typed, entry.context, undefined, undefined, entry.reserved)\n              : schemaToTypeRef(typed, contextName),\n        );\n      }\n    }\n\n    const hasNull = schema.oneOf.some(\n      (v: SchemaObject) => isNullSchema(v) || (Array.isArray(v.type) && v.type.includes('null')),\n    );\n    // The mapping's targets are read as a field's or a response's inline\n    // union reads them (`inlineMappingTargets`), so the same union carries the\n    // same discriminator at every site — an entry written as a pointer\n    // deeper into a component settled to the model the pointed schema is\n    // built as, as theirs is (`deferInlineUnionMappingEntries`; #619).\n    const mapping = schema.discriminator ? inlineMappingTargets(schema.discriminator.mapping) : undefined;\n    if (mapping) deferInlineUnionMappingEntries(schema, objectVariantNames, variants, mapping);\n    // The union carries the body's own limits, as `schemaToTypeRef` would\n    // have it carry them (#545); each variant carries its own.\n    const union: TypeRef = withSchemaConstraints(\n      {\n        kind: 'union',\n        variants,\n        ...(schema.discriminator && mapping\n          ? { discriminator: { property: schema.discriminator.propertyName, mapping } }\n          : {}),\n      },\n      schema,\n    );\n    return hasNull ? ({ kind: 'nullable', inner: union } as TypeRef) : union;\n  }\n\n  // Anything else is typed by `schemaToTypeRef` (a primitive, an `anyOf`, a\n  // `oneOf`/`anyOf` of string consts read as an enum, an array, a map, a\n  // nullable object, a nullable wrapper around an array, a `$ref` or a\n  // primitive, …). Such a TypeRef can still reach inline models\n  // — the inline object variants of an `anyOf`, an array's inline items or\n  // the variants of an `items.oneOf`, a map's inline values, and whatever is\n  // nested under any of them, a union under a variant included — so\n  // materialize them the way an inline response does: as a property of this\n  // name under no parent, which names every nested model exactly as the\n  // TypeRef references it.\n  extractInlineModelsFromProperties(\n    { properties: { [contextName]: schema } },\n    inlineModels,\n    undefined,\n    componentSchemas,\n  );\n  return schemaToTypeRef(schema, contextName);\n}\n\n/**\n * Fold a discriminated-union request body into the equivalent single object so\n * its fields can be spread into method arguments instead of forcing callers to\n * construct an opaque union.\n *\n * The result is the union of every variant's properties: the discriminator is\n * collapsed to an enum of the pinned const values, and any field that isn't\n * present-and-required in *every* variant becomes optional (it varies by\n * branch, so it can't be unconditionally required). The discriminator itself is\n * always required. This mirrors what a spec author would write by hand to model\n * the same shape as a flat object.\n *\n * Returns null — leaving the union intact — unless the body is a clean\n * inline-object discriminated union: a variant that is a `$ref`, a non-object,\n * or that doesn't pin the discriminator to a string const can't be safely\n * merged. The pin is read as a union's discriminator reads one\n * (`pinnedDeclarationValue`): a `const` or one-value `enum:` as written,\n * or behind a nullable wrapper, an `allOf` read as one member, or — with\n * `componentSchemas` — a `$ref` to a component pinning one value or an\n * alias of one, so `kind: { allOf: [{ const: 'email' }] }` folds as `kind:\n * { const: 'email' }` does (#607: the declaration was read as written, and\n * the body stayed an opaque union of variants named from their content).\n * The rebuilt discriminator admits `null` exactly when a variant's\n * declaration does, at any hop (`pinnedDeclarationAdmitsNull`: a nullable\n * wrapper, a type list naming `null`, OAS 3.0 `nullable: true` beside a\n * type — never a keyword beside a `$ref`, which the type builder gives\n * precedence), so a `kind: { oneOf: [{ const: 'email' }, { type: 'null' }] }`\n * variant beside one pinning `sms` folds to a `kind` typed\n * `nullable<enum>`, as the variant's own field is `nullable<literal>`\n * (#607 review: the fold rebuilt the field without `null`, as it had\n * dropped a `nullable: true` or a type list before). The rebuilt field\n * carries the settings every variant's declaration agrees on — the flags,\n * text, default, examples, link, limits and `x-*` keys a field reads\n * (`LIFTED_DECLARATION_KEYWORDS`), each declaration read off its levels as\n * `buildFieldFromSchema` reads a field's — the one reading, `fieldSettings`,\n * the pin walk kept apart: under a wrapper the declaration documents itself\n * and takes none of the component's text, flags, default, examples or keys,\n * a bare `$ref` reads the entries it passes, and the limits conjoin from\n * every entry either way, the stricter bound winning (#607 review: the\n * settings were read through every hop of the pin walk, so `kind: { allOf:\n * [{ $ref: CatKind }] }` on every variant, `CatKind` read-only, folded to a\n * read-only `kind` where each variant's own field is not) — so two\n * variants writing `kind: { allOf: [{\n * const: … }], readOnly: true }` fold to a read-only `kind`, as each\n * variant's own field is (#607 review: `description` alone was carried,\n * and the fold of a body whose variants all wrote `readOnly: true` dropped\n * the flag, so `buildForModel` put the field into request examples). The\n * declaration as written still documents its value — its own `description`\n * and `deprecated`, the wrapper's for a wrapped const. Gating on an\n * *explicit* `discriminator` keeps undiscriminated `oneOf` bodies untouched.\n */\nfunction flattenDiscriminatedUnionBody(\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): SchemaObject | null {\n  const discProp = schema.discriminator?.propertyName;\n  if (!discProp || !Array.isArray(schema.oneOf) || schema.oneOf.length === 0) return null;\n\n  const variants = schema.oneOf as SchemaObject[];\n  // Every declaration that pins each value, in variant order, the values in\n  // the order they are first pinned.\n  const pins = new Map<string, SchemaObject[]>();\n  // Whether any variant admits `null` beside its value, which the rebuilt\n  // discriminator then admits too.\n  let admitsNull = false;\n\n  for (const variant of variants) {\n    // Every variant must be an inline object that pins the discriminator to a\n    // string const (or single-value enum); anything else can't be merged.\n    if (variant.$ref || !variant.properties || !(variant.type === 'object' || variant.type === undefined)) {\n      return null;\n    }\n    const dp = variant.properties[discProp] as SchemaObject | undefined;\n    const constVal = dp ? pinnedDeclarationValue(dp, componentSchemas) : null;\n    if (constVal === null) return null;\n    if (pinnedDeclarationAdmitsNull(dp!, componentSchemas)) admitsNull = true;\n    const pinning = pins.get(constVal);\n    if (pinning) pinning.push(dp!);\n    else pins.set(constVal, [dp!]);\n  }\n\n  const variantCount = variants.length;\n  // The discriminator's declarations as a field written as each is read\n  // (`fieldSettings`: the reading `buildFieldFromSchema` makes, the pin\n  // walk kept apart), so declarations spelled differently compare alike.\n  const settingsOf = (declared: readonly SchemaObject[]): SchemaObject[] =>\n    declared.map((dp) => fieldSettings(dp, componentSchemas));\n  // Every declaration each property receives, in variant order; the first\n  // types the field, and the extensions are the ones every declaration\n  // agrees on (`agreedExtensions`, the one rule for a property several\n  // declarations give — workos/oagen#369 review: the discriminator was\n  // rebuilt from `type`, `enum` and `description` alone, and a shared field\n  // took the first variant's keys as written).\n  const declarations = new Map<string, SchemaObject[]>([[discProp, []]]);\n  const requiredCounts: Record<string, number> = {};\n\n  for (const variant of variants) {\n    const required = new Set(variant.required ?? []);\n    for (const [name, propSchema] of Object.entries(variant.properties!)) {\n      if (!propSchema) continue;\n      let declared = declarations.get(name);\n      if (!declared) declarations.set(name, (declared = []));\n      declared.push(propSchema as SchemaObject);\n      if (name !== discProp && required.has(name)) requiredCounts[name] = (requiredCounts[name] ?? 0) + 1;\n    }\n  }\n  const order = [...declarations.keys()]; // discriminator leads the merged object\n\n  const properties: Record<string, SchemaObject> = {};\n  for (const name of order) {\n    const declared = declarations.get(name)!;\n    properties[name] =\n      name === discProp\n        ? // The discriminator collapses to an enum of the pinned values: a\n          // `oneOf` of string consts, which gives each `EnumValue` its const's\n          // `description` and `deprecated` (`constUnionEnumMembers`). A value\n          // takes the text of the declaration that pins it — the first's,\n          // for a value two variants pin — and is deprecated only when every\n          // declaration that pins it is, as an inline `allOf` reads a\n          // repeated shape (`shapeVariant`; workos/oagen#501: the flag was\n          // dropped). A lone value stays a one-value `enum`, a literal, where\n          // a `oneOf` of one const would be a union. The enum and the field\n          // carry the settings every declaration agrees on — the flags,\n          // text, default, examples, link, limits and `x-*` keys a field\n          // reads (`LIFTED_DECLARATION_KEYWORDS`), each declaration read\n          // exactly as a field written as it is read (`fieldSettings`) —\n          // (workos/oagen#446: the first variant's text, which documents one\n          // value, was the enum's; #607 review: `description` alone was\n          // carried, so a `readOnly` every variant wrote was dropped).\n          // `null` is admitted when any variant admits it beside its value\n          // — the flag on the one-value enum, a `{ type: 'null' }` variant\n          // among the consts, the spellings the type builder reads as\n          // `nullable`.\n          {\n            type: 'string',\n            ...(pins.size === 1\n              ? { enum: [...pins.keys()], ...(admitsNull ? { nullable: true } : {}) }\n              : {\n                  oneOf: [\n                    ...[...pins].map(([value, pinning]) => ({\n                      const: value,\n                      ...(pinning[0]!.description !== undefined ? { description: pinning[0]!.description } : {}),\n                      ...(pinning.every((dp) => dp.deprecated === true) ? { deprecated: true } : {}),\n                    })),\n                    ...(admitsNull ? [{ type: 'null' }] : []),\n                  ],\n                }),\n            ...agreedDeclarationKeys(settingsOf(declared), LIFTED_DECLARATION_KEYWORDS),\n            ...agreedExtensions(settingsOf(declared)),\n          }\n        : withAgreedExtensions(declared[0]!, agreedExtensions(declared));\n  }\n\n  // Required only when required in every variant; the discriminator is always\n  // required.\n  const requiredFields = order.filter((name) => name === discProp || requiredCounts[name] === variantCount);\n\n  return {\n    type: 'object',\n    properties,\n    required: requiredFields,\n    ...(schema.description ? { description: schema.description } : {}),\n    // The wrapper's deprecation is the body's; a variant's is not carried,\n    // since its fields are merged away into the one body model.\n    ...deprecatedEntry(schema),\n    // The wrapper's link is the body's, like its description.\n    ...externalDocsEntry(schema.externalDocs),\n    // The wrapper's own keywords bind every branch, so they ride along; the\n    // variants' keywords are alternatives and are not carried.\n    ...extractConstraints(schema),\n    // The wrapper's own extensions are the body's, like its link; a\n    // variant's are not carried, since its fields merge into the one model.\n    ...extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS),\n  };\n}\n\n/**\n * Derive a unique variant name for a request-body `oneOf` inline model.\n *\n * A variant with a string-const property is named after it\n * (`RadarEmailChallengeCodeSessionAuthenticateRequest`). Any other variant is\n * named from its content by the same rule every inline union variant follows\n * (`nameInlineVariant`): the first const-less variant keeps the body's name\n * (or its title, when every inline variant of the union is titled), and each\n * later one takes its title, a distinguishing property\n * (`CreateThingRequestWithB`) or, when its property set repeats an earlier\n * variant's, the position counter (`CreateThingRequest2`). `siblings` are the\n * union's inline object variants and `contentNamed` the names its const-less\n * variants have taken so far; `fromContent` tells the caller to record this\n * one there. A clash with a model minted elsewhere still bumps the counter:\n * on the base for a content-named variant (`CreateThingRequest2`), on the\n * const-derived name for a const-named one (`FooCreateThingRequest2`) — so a\n * variant titled `Foo` and a later one pinning `kind: foo` in the same body\n * never share a model.\n *\n * `fromOperationId` says where `baseName` came from. An operationId-derived\n * base is already in cleanSchemaName form and its variants go through\n * resolveSchemaName, so they follow the same project-level naming policy as\n * component schemas. A path-derived base is used verbatim: it is deliberately\n * not cleaned (see derivePathModelBaseName) and resolvePathModelBaseNames\n * reserves names by that exact prefix, so cleaning a variant here would let it\n * slip past the reservation — `NotesPostRequest` became `NotePostRequest` and\n * collided with a component of that name.\n */\nfunction deriveOneOfVariantName(\n  variant: SchemaObject,\n  baseName: string,\n  existingModels: Model[],\n  siblings: readonly SchemaObject[],\n  contentNamed: readonly string[],\n  fromOperationId: boolean,\n): { name: string; fromContent: boolean } {\n  const finalize = (name: string): string => (fromOperationId ? resolveSchemaName(name) : name);\n  const existingNames = new Set(existingModels.map((m) => m.name));\n  // `name`, or `stem` numbered from 2 (numberedName) while a model of that name exists.\n  const unique = (name: string, stem: string): string => {\n    let candidate = name;\n    for (let suffix = 2; existingNames.has(candidate); suffix++) candidate = numberedName(stem, suffix);\n    return candidate;\n  };\n  // Try to use a distinguishing property (e.g., \"grant_type\" field's const/enum value)\n  if (variant.properties) {\n    for (const [, propSchema] of Object.entries(variant.properties)) {\n      if (propSchema?.const && typeof propSchema.const === 'string') {\n        const derivedName = finalize(toPascalCase(propSchema.const) + baseName.replace(/Request$/, '') + 'Request');\n        return { name: unique(derivedName, derivedName), fromContent: false };\n      }\n    }\n  }\n  // Finalize before naming so every candidate stays in the same namespace as\n  // the rest of the IR.\n  const finalBaseName = finalize(baseName);\n  const name = unique(nameInlineVariant(variant, siblings, finalBaseName, contentNamed, null), finalBaseName);\n  return { name, fromContent: true };\n}\n\n/** Human-readable label for an operation in diagnostics: its operationId, else `METHOD /path`. */\nfunction operationLabel(op: OperationObject | undefined, path: string, method: HttpMethod): string {\n  return op?.operationId ?? `${method.toUpperCase()} ${path}`;\n}\n\n/**\n * The servers an operation carries as `Operation.servers`: its own `servers`,\n * else its Path Item's (OpenAPI precedence: the operation overrides the Path\n * Item, which overrides the document), and only when that list differs from\n * the document's by `serverListsEqual`. `undefined` means the operation\n * inherits `ApiSpec.servers` — nothing usable is declared at either level\n * (`servers: []` and all-unusable entries included, since `extractServerList`\n * already reads both as undeclared), or the winning list restates the\n * document's — a restatement whose URLs differ only in scheme or host case,\n * a default port or a `/` after a bare authority included, since\n * `serverListsEqual` compares URLs through `normalizeServerUrl`. Precedence\n * is applied before the comparison, so an operation that restates the\n * document's servers under a Path Item that diverges inherits, not the Path\n * Item's.\n *\n * OpenAPI's default server is one thing however it is spelled (#291): a list\n * that means it — no servers, `servers: []`, or nothing but `/`, by\n * `isDefaultServerList`, description and variables aside (the default server\n * has neither, and `/` references no variable, so one declared on it changes\n * nothing — #292) — under a document whose list means it too is inherited as\n * well. So an operation or Path Item that writes `/` out under a document\n * that declares nothing inherits, the entry's description and variables\n * included. Any other list is compared\n * entry for entry as written, `/` entries included, because position decides\n * the default host: `/` under a document that names a host is kept, a named\n * host under a document that writes `/` out is kept, and a named host alone\n * under a document that lists `/` before that host is kept.\n */\nfunction operationServers(\n  own: ServerEntry[] | undefined,\n  pathLevel: ServerEntry[] | undefined,\n  documentServers: ServerEntry[] | undefined,\n): ServerEntry[] | undefined {\n  const effective = own ?? pathLevel;\n  if (!effective) return undefined;\n  if (serverListsEqual(effective, documentServers ?? [])) return undefined;\n  return isDefaultServerList(effective) && isDefaultServerList(documentServers) ? undefined : effective;\n}\n\n/**\n * The spec-wide registry of inline model shapes (see `InlineModelRegistry`):\n * the component models and the inline models their fields mint, every inline\n * model the operations mint for request bodies and primary responses, the\n * envelope companions, and each deferred model materialized so far. The value\n * carries the model's shape fingerprint, so a schema whose shape matches can\n * share the name, and the operation that minted it (none for a component or\n * a shared envelope companion), so a collision inside one operation can be\n * told apart from one across operations.\n */\ntype ModelShapeRegistry = InlineModelRegistry;\n\n/**\n * A header, secondary-body, fallback-body or error-body schema whose inline\n * models are named only once every primary model of every operation is known\n * (`resolveDeferredInlineTypes`), which then fills in `target.type`. Until\n * then the target carries a placeholder.\n */\ninterface DeferredInlineType {\n  kind: 'header' | 'content' | 'request' | 'fallback' | 'error' | 'param';\n  schema: SchemaObject;\n  /**\n   * The bare name the models derive from: the header name; a success or\n   * fallback entry's secondary body, the stem + media type + `Response`; a\n   * secondary request body's `<Op><MediaType>Request`; a fallback body's\n   * `<Op><Label>Response` (`default`, `1XX`–`3XX`); an error body's\n   * `<Op>Error<code>` — the status code or the `4XX`/`5XX` range key, then\n   * the media type for a secondary body (`<Op>Error<code><MediaType>`); a\n   * parameter's name; or `<Component>Response` for a fallback or error body\n   * a `components/responses` entry declares.\n   */\n  name: string;\n  /**\n   * Set for a site a `components/responses` entry declares — its fallback or\n   * error body (`<Component>Response`), an inline body under another media\n   * type (`<Component><MediaType>Response`), an object-shaped header\n   * (`<Component><Header>`) — to the model name the component's body is\n   * shared under (`CardResponse`, `CardResponse2`; `sharedResponseModelName`),\n   * which no other component's body takes (its stem may: `CardResponse2` is\n   * also the stem of a component `CardResponse2`'s `CardResponse2Response`).\n   * Such a site is named after the component wherever the component is\n   * returned: a 404 of one operation, the `default` or a range of another.\n   * Every such site is a sibling of every other that derives the\n   * same name, whatever its kind, and on a clash steps by number alike\n   * (`ProblemResponse2`, `CardXMeta2`, `CardApplicationYamlResponse2`), never\n   * by the operation or status code that mounted the component; and every\n   * such site is named before any operation's own, component by component\n   * (`extractOperations`), so all settle on one name that depends on the\n   * component alone.\n   */\n  componentSite?: string;\n  /**\n   * What tells this site from another of the same name within one operation:\n   * a status code, the key of a `4XX`/`5XX` range (`4XX`), the label of a\n   * `default` or `1XX`–`3XX` response (`Default`, `Success`), or a\n   * parameter's location (`query`); a request body has none.\n   */\n  statusCode?: number | string;\n  /**\n   * Set for the secondary body of a 2xx entry after the primary, the\n   * operation's own (workos/oagen#538): the body is named for its status\n   * code as the entry's primary body is (`stepSecondaryBody`), so it has no\n   * bare name — `name` is tried with `statusCode` first, then numbered\n   * under that (`deferredNamingStem`) — and its siblings are the earlier\n   * such bodies of the same name, never the primary status code's, whose\n   * model it never shares (`resolveDeferredInlineTypes`). A component response's secondary\n   * body is the component's wherever it is mounted and is never this.\n   */\n  later?: boolean;\n  /** Qualifies a name taken across operations (see `headerOperationQualifier`). */\n  operationQualifier: string;\n  /**\n   * Qualifies a header's names: the service for a header of an inline\n   * response (`Documents` + `X-Meta` → `DocumentsXMeta`), the component's\n   * stem for one of a response shared through `components/responses`\n   * (`Card` + `X-Meta` → `CardXMeta`); a body has none.\n   */\n  parentName?: string;\n  componentSchemas?: Record<string, SchemaObject>;\n  /**\n   * Everything the resolved type is written to: the header or content entry,\n   * and for a fallback or error body both the response entry and the content\n   * entry of the media type it was read from, which share one TypeRef as a\n   * success entry's do.\n   */\n  targets: Array<{ type?: TypeRef }>;\n}\n\n/** What response header and body typing needs from the operation and the spec. */\ninterface ResponseTypingContext {\n  componentHeaders?: Record<string, Record<string, unknown>>;\n  /** Lets inline models resolve `$ref` siblings and augmentations the way fields do. */\n  componentSchemas?: Record<string, SchemaObject>;\n  /** `components/responses`, for a response written as a Reference Object. */\n  componentResponses?: Record<string, Record<string, unknown>>;\n  /**\n   * Whether a `description` written beside a response or header `$ref`\n   * overrides the component's (OAS 3.1) or is ignored (OAS 3.0); see\n   * `followReference`. Absent, it overrides.\n   */\n  refSiblingDescriptions?: SiblingDocs;\n  /**\n   * The model name each component response's inline body is shared under\n   * (`resolveComponentResponseModelNames`). Absent, every component keeps\n   * `componentResponseModelName`.\n   */\n  componentResponseModelNames?: ReadonlyMap<string, string>;\n  /**\n   * Qualifies the header model and enum names of an inline response:\n   * `Documents` + `X-Meta` → `DocumentsXMeta`. A response shared through\n   * `components/responses` qualifies its headers by the component instead\n   * (`responseModelSite`).\n   */\n  serviceName?: string;\n  /** Qualifies a name taken across operations (see `headerOperationQualifier`). */\n  operationQualifier: string;\n  /** Collects every schema whose models are named after the operations loop. */\n  deferred: DeferredInlineType[];\n  /**\n   * The spec-wide registry of model shapes the operations fill as they are\n   * read (see `extractOperations`); with it, the primary body's array items\n   * are settled against every name it holds (`typeInlineItems`). Absent for\n   * a dry run that only reads the names a body would mint.\n   */\n  registry?: ModelShapeRegistry;\n}\n\n/**\n * Name and materialize every deferred header, secondary request-body,\n * secondary response-body, fallback-body, error-body and parameter schema,\n * now that every primary model is known. The registry comes filled from\n * `extractOperations`: the component models first (with the inline models\n * their fields mint), each seeded with the model itself so it shares its\n * name with every shape it admits (`ownerShares`), then every inline model\n * the operations minted — request bodies, primary response bodies with\n * their nested objects, union variants and settled array items, envelope\n * companions — shared on an identical shape only, so no deferred schema\n * can take one of their names for a shape the owner does not share,\n * whichever operation minted it; each resolved schema's own models join it\n * in turn, in `namingOrder` — the sites a `components/responses` entry\n * declares (`componentSite`) first, component by component, then every\n * operation's own (see `extractOperations`), each in document order (path\n * order, then an operation's secondary request bodies in content order,\n * then the response keys as written; a response's headers before its error\n * body and its secondary bodies, a fallback's body before its headers; a\n * body's media types that derive one name in `mediaTypeNamingOrder`) — so\n * the first owner of a name keeps it, and a component's site is never an\n * operation's own (`registryOwner`). Every enum name decided before this\n * pass, component or minted, is held too, as a name no model may take\n * (`reserveEnumNames`): a deferred schema that derives one steps to its\n * next candidate, so a component enum `ReplaceWidgetTextCsvRequest` sends\n * the `text/csv` body's model to `ReplaceWidgetTextCsvRequest2`. The sites\n * that derive from one bare name\n * — one kind, parent and name: the same header on several status codes or\n * operations, one media type's body on the later 2xx entries of an\n * operation, or on its primary 2xx, 3xx and fallback entries (`later`,\n * workos/oagen#538), a component response's header or secondary body from\n * every operation that returns it; or one component response's body,\n * whether the site is an error or a fallback entry (`componentSite`) —\n * share a record of the stems they settled on and the renames made under\n * them, so a later one shares an identical shape under whichever name the\n * earlier took (`materializeInlineSchema`); the later 2xx bodies of a name\n * keep a record apart from the primary's and step through a numbered run of\n * their own (`deferredNamingStem`), so neither group shares the other's\n * model or steps into its names.\n *\n * An enum keeps a name a model also derives, wherever the document declares\n * the two. One typed as an operation is built — one a parameter, a request\n * body, a success body, a pagination field carries — is in the registry\n * before this pass: a `status` query enum on a later operation sends an\n * earlier operation's `status` parameter object to `PetsListPetsStatus`,\n * and the same operation's to `PetsQueryStatus`. One a site named here\n * types — a response header, an error, secondary or fallback body, a\n * parameter model, whether the site is itself the enum or nests it in a\n * model it mints — is reserved before any of these sites is named, under\n * the name the site lifts it under at its first candidate\n * (`deferredEnumNames`): `getPet`'s object 404 is `GetPetError404Body`\n * whether `get-pet`'s enum 404 comes before or after it, and an `x`\n * parameter object of `listNotes` (service `SearchPetsError404`) is\n * `SearchPetsError404ListNotesX` whether the `x` enum nested in\n * `searchPets`'s 404 body comes before or after it. Each site then\n * registers the enums it types as it is resolved, under the stem it settled\n * on. So the IR never declares a model and an enum under one name, and the\n * model is always the one that steps. Returns the models materialized and\n * one bundle per site, in the order of `deferred` (document order) whatever\n * the order the sites were named in, having set each target's `type`.\n */\nfunction resolveDeferredInlineTypes(\n  deferred: readonly DeferredInlineType[],\n  registry: ModelShapeRegistry,\n  namingOrder: readonly DeferredInlineType[],\n): { models: Model[]; bundles: InlineModelBundle[] } {\n  const bundleOf = new Map<DeferredInlineType, InlineModelBundle>();\n  const siblingsByBareName = new Map<string, SiblingSites>();\n  const sitesOf = (key: string): SiblingSites => {\n    let siblings = siblingsByBareName.get(key);\n    if (!siblings) siblingsByBareName.set(key, (siblings = createSiblingSites()));\n    return siblings;\n  };\n  for (const item of namingOrder) {\n    // A component response's site is one site wherever the component is\n    // returned, so its record is keyed by the name the component gives it\n    // alone (its body's, or a header's under the component's stem), not by\n    // whether the site is an error or a fallback entry. The secondary bodies\n    // of an operation's later 2xx entries (`later`) are one group and the\n    // primary's another, so a later body shares an earlier later body's\n    // model, never the primary's, whichever the document declares first;\n    // the two groups' candidates never meet (`deferredNamingStem`), so\n    // neither needs to know the other's stems (workos/oagen#538).\n    const bareName =\n      item.componentSite !== undefined\n        ? `component\\u0000${item.parentName ?? ''}\\u0000${item.name}`\n        : `${item.kind}\\u0000${item.parentName ?? ''}\\u0000${item.name}`;\n    const siblings = sitesOf(item.later ? `later\\u0000${bareName}` : bareName);\n    const models: Model[] = [];\n    const type = materializeDeferredType(item, registry, models, siblings);\n    // An enum this site typed — a body that is itself an enum, one nested in\n    // a model it minted — owns its name from here on, as the site's models do.\n    reserveEnumNames(\n      registry,\n      [type, ...models.flatMap(collectModelTypeRefs)].flatMap(collectEnumRefs),\n      registryOwner(item),\n    );\n    for (const target of item.targets) target.type = type;\n    // The one TypeRef every target shares is the site's root; the models\n    // minted for it are the site's own (a shape that shared another site's\n    // model minted nothing here, see `attachSharedRefs`).\n    bundleOf.set(item, {\n      qualifier: item.operationQualifier,\n      roots: [type],\n      models,\n      ...(isSentSite(item) ? { sent: true } : {}),\n    });\n  }\n  // In document order, whatever order the sites were named in, so the IR\n  // lists their models where it would without a component site among them.\n  const bundles = deferred.map((item) => bundleOf.get(item)!);\n  return { models: bundles.flatMap((bundle) => bundle.models), bundles };\n}\n\n/**\n * Give each reference a site wrote by sharing another site's model to that\n * site. A shape identical to a name's owner takes the name and mints\n * nothing — a deferred header or body matching a primary body's model or a\n * companion's, an array body's or list envelope's items matching a\n * component field's model or an earlier operation's (`typeInlineItems`\n * through `materializeInlineSchema`) — so its reference is not among the\n * owner's roots, and a merge pass that renames the owner (a deprecated copy\n * named like a live one, `settleSharedNames`) would leave the\n * `default` response, header or array on the old name, which the live copy\n * then takes. The first site to mint a name owns it, as the registry\n * decided; the references every other site's roots and its own models'\n * fields make to that name are added to the owner's roots, so they are\n * repointed with the owner's own. A reference to a name the site itself\n * minted is the site's own, not shared, and is left to its own bundle — two\n * operations minting one name with different shapes are the merge's\n * business, and attaching one to the other would drag a live copy's\n * references along with a renamed deprecated one; a component is never\n * renamed, so a reference to one is left alone. Idempotent: run over the\n * operations' bundles once they are complete (`extractOperations`) and again\n * once the components' field bundles exist (`parseSpec`) — there a field's\n * bundle stands for the object the component pass minted for the field\n * (`fieldInlineModelBundles`), so a header or fallback body that shared that\n * object joins the field's site and follows its rename. `sharedRoots` are\n * references that belong to no site and name whatever model they were\n * settled to — a pointer into a component typed as the field it lands on\n * (`resolveSchemaPointers`; #539) — each given to the site of that model\n * the same way.\n */\nexport function attachSharedRefs(\n  bundles: readonly InlineModelBundle[],\n  componentNames: ReadonlySet<string>,\n  sharedRoots: readonly TypeRef[] = [],\n): void {\n  const siteOf = new Map<string, InlineModelBundle>();\n  for (const bundle of bundles) {\n    for (const model of bundle.models) if (!siteOf.has(model.name)) siteOf.set(model.name, bundle);\n  }\n  const sites: readonly Pick<InlineModelBundle, 'roots' | 'models'>[] =\n    sharedRoots.length > 0 ? [...bundles, { roots: [...sharedRoots], models: [] }] : bundles;\n  for (const bundle of sites) {\n    const own = new Set(bundle.models.map((model) => model.name));\n    const refs = [...bundle.roots, ...bundle.models.flatMap((model) => collectModelTypeRefs(model))];\n    for (const ref of refs) {\n      for (const name of collectModelRefs(ref)) {\n        if (componentNames.has(name) || own.has(name)) continue;\n        const site = siteOf.get(name);\n        if (site && site !== bundle && !site.roots.includes(ref)) site.roots.push(ref);\n      }\n    }\n  }\n}\n\n/**\n * Type a deferred schema and materialize the inline models it names, under a\n * property name that does not collide with a different shape anywhere in the\n * spec — through `materializeInlineSchema`, the one retry loop every such\n * schema goes through.\n *\n * A header model is named from the service and header name alone, so an\n * inline `X-Meta` on a `Documents` operation is `DocumentsXMeta`; a secondary\n * body from the operation's response stem and media type,\n * `RenderPetCardTextHtmlResponse`; either, on a response shared through\n * `components/responses`, from the component's stem instead (`CardXMeta`,\n * `CardApplicationYamlResponse`; see `responseModelSite`); a `default` or\n * `1XX`–`3XX` body from the stem and the response's label,\n * `ListPetsDefaultResponse`; an error body from the stem and its status code\n * or `4XX`/`5XX` range key, `GetPetError404`, `GetPetError4Xx`\n * (`deriveErrorModelName`), and a secondary media type's error body from\n * that name and the media type, `GetPetError404ApplicationYaml`; a\n * parameter from the service and parameter name, `PetsFilter`. Any of them\n * is a name a component schema, a model nested in one (`GetPet.error404` owns\n * `GetPetError404`), a primary body, the same header on a 429 or another\n * operation may already own with a different shape, or an enum — a\n * component's, or one a parameter or field lifts — may own outright\n * (`reserveEnumNames`). Left alone, the later\n * merge keeps one definition for the name and every other reference silently\n * gets the wrong fields (a request body using the component would even change\n * type without any emitter reading headers).\n *\n * The first owner of a name keeps it (see `resolveDeferredInlineTypes`), and\n * a later schema with a different shape — at any depth, a nested object that\n * differs counts — is re-derived under the first free candidate of its kind\n * (`deferredNamingStem`):\n *\n *   header    1. the bare name                `DocumentsXMeta`\n *             2. when the name is taken inside this operation, the status\n *                code (`DocumentsXMeta429`); when taken by a component or\n *                another operation, the operation (`DocumentsCreateDocumentXMeta`)\n *             3. the other of those two\n *             4. operation and status code    `DocumentsCreateDocumentXMeta429`\n *             5. a numeric suffix             `DocumentsXMeta2`, `DocumentsXMeta3`, …\n *   content   (the primary 2xx's, a 3xx's or a fallback entry's secondary body)\n *             1. the bare name                `RenderPetCardTextHtmlResponse`\n *             2. the status code              `RenderPetCardTextHtmlResponse200`\n *             3. a numeric suffix             `…Response2`, `…Response3`, …\n *   content   (a later 2xx's secondary body, `later`: named for its status\n *             code as the entry's primary body is, then numbered under it —\n *             a run of its own the primary's never meets, so no edit to the\n *             primary's bodies renames it, workos/oagen#538)\n *             1. the status code              `RenderPetCardTextHtmlResponse201`\n *             2. a numeric suffix under it    `…Response201No2`, `…Response201No3`, …\n *   request   1. the bare name                `ReplaceWidgetTextCsvRequest`\n *             2. a numeric suffix             `ReplaceWidgetTextCsvRequest2`, `…3`, …\n *   fallback  (a `default` or `1XX`–`3XX` body)\n *             1. the bare name                `ListPetsDefaultResponse`\n *             2. a numeric suffix             `ListPetsDefaultResponse2`, `…3`, …\n *   error     (an error entry's JSON body, its secondary bodies, and a\n *             `4XX`/`5XX` range's bodies alike)\n *             1. the bare name                `GetPetError404`, `GetPetError404ApplicationYaml`, `GetPetError4Xx`\n *             2. a `Body` suffix              `GetPetError404Body`\n *             3. a numbered `Body` suffix     `GetPetError404Body2`, `…Body3`, …\n *   a site a `components/responses` entry declares (`componentSite`) — its\n *   fallback or error body, a secondary body, a header — whichever kind it is:\n *             1. the bare name                `ProblemResponse`, `CardXMeta`, `CardApplicationYamlResponse`\n *             2. a numeric suffix             `ProblemResponse2`, `CardXMeta2`, `CardApplicationYamlResponse2`, …\n *\n * Between the bare name and the kind's own qualifiers come the stems the\n * earlier sites of the same kind, parent and bare name settled on\n * (`siblings`, kept by `resolveDeferredInlineTypes`): the `X-Meta` header of\n * a 429 tries the `DocumentsXMeta200` its 200 took before `DocumentsXMeta429`,\n * so an identical shape shares the earlier site's model under whichever\n * name that site settled on, and a different shape steps past it to its own\n * qualifier. A later 2xx's secondary body has no bare name, so its siblings'\n * stems come first: the `application/vnd.pet+json` body of a 202 tries the\n * `…Response201` its 201 took before `…Response202`. Its siblings are the\n * earlier later 2xx's bodies of its name, never the primary's, and its\n * numbered run is its own (`…Response201No2`, never the `…Response2` the\n * primary steps to), so a 201 body identical to the 200's is `…Response201`\n * beside the 200's `…Response`, under whichever name either settled on and\n * whichever the document declares first, and a 201 body that stepped to\n * `…Response201No2` keeps it whatever the 200's bodies gain or lose. A body\n * that is itself an inline enum mints no model and clashes on nothing, so\n * it shares a sibling's stem only when that sibling is an enum of the same\n * members (`SettledSite.enumValues`) and otherwise takes its own status\n * code, as an object would: a 202 enum `[c, d]` beside a 201 enum `[a, b]`\n * is `…Response202`, and a 202 enum `[a, b]` shares `…Response201`. A\n * body that produces neither a model nor an enum — a primitive, an array of\n * primitives, a `$ref` to a component — owns no name and records no\n * settlement, so a 202 object beside a 201 `type: string` body is\n * `…Response202`, not the free `…Response201`, and keeps it when the 201's\n * body is removed (workos/oagen#538). A fallback body named\n * from the operation carries the response's label in its bare name and an\n * error body named from it its status code, so within an operation each has\n * a bare name of its own and no sibling to try. A component response's body\n * carries the component's name wherever the component is returned, so the\n * 404 of one operation and the `default` of another are siblings, and an\n * identical shape — the component's own, every time — shares the first\n * site's model under whichever name it settled on; its headers and\n * secondary bodies are siblings across operations the same way, under the\n * component's stem.\n *\n * Both the type and the models come from the same property name, so nested\n * models (`DocumentsXMeta429Origin`) line up by construction. A shape the\n * name's current owner shares — identical to an operation's model, or one a\n * component admits (`ownerShares`) — takes the name and materializes nothing\n * new, which is how a header reuses a component model. A\n * title-mapped union variant (`Circle`) is named from its title whatever the\n * property name, so `materializeInlineSchema` reserves every taken name and\n * such a variant falls back to its context-qualified name\n * (`CircleDocumentsXMeta`, see `nameInlineVariants`). A clash neither a\n * candidate nor a reservation can clear — a titled variant nested below the\n * top level — is not looped on: the clashing models are renamed under the\n * schema's root (`RenderPetCardTextHtmlResponseCircle`) with every reference\n * rewritten, whatever the kind.\n *\n * Treating the schema as a one-property object reuses the field-level\n * extractor, whose names come from the same `qualifyInlineModelName(name,\n * parent)` rule `schemaToTypeRef` applies — the trick the inline request-body\n * path uses.\n */\nfunction materializeDeferredType(\n  item: DeferredInlineType,\n  registry: ModelShapeRegistry,\n  models: Model[],\n  siblings: SiblingSites,\n): TypeRef {\n  return materializeInlineSchema(item.schema, {\n    stem: deferredNamingStem(item),\n    siblings,\n    ...(item.later && { siblingsFirst: true }),\n    parentName: item.parentName,\n    componentSchemas: item.componentSchemas,\n    registry,\n    operation: registryOwner(item),\n    sent: isSentSite(item),\n    models,\n  });\n}\n\n/** Whether a deferred schema is one the SDK sends — a secondary request body or a parameter — rather than receives. */\nfunction isSentSite(item: DeferredInlineType): boolean {\n  return item.kind === 'request' || item.kind === 'param';\n}\n\n/**\n * The operation the registry records as the owner of a deferred site's models\n * and enums (`InlineModelOwner.operation`): the site's own, or none for a site\n * a `components/responses` entry declares (`componentSite`) — the\n * component's, whichever operation returning it is read first. So an\n * operation's own site that derives a component site's name steps as beside\n * a component (`deferredNamingStem`), by operation (`CardGetCardXMeta`), in\n * either path order and whether or not the operation returns the component.\n */\nfunction registryOwner(item: DeferredInlineType): string | undefined {\n  return item.componentSite === undefined ? item.operationQualifier : undefined;\n}\n\n/**\n * Every enum name a deferred site types when it is resolved under its first\n * candidate (`deferredNamingStem`): the schema itself when it is an inline\n * enum (an error, fallback or secondary body that is an `enum:` list, or an\n * array of one) and every inline enum nested in a model it mints (a field's,\n * a variant's, array items'), the site's parent qualifying them as a\n * header's does. Read off a silent rehearsal of the site's first trial\n * (`rehearse`) — the extractor for the models and `schemaToTypeRef` for the\n * type, as `materializeInlineSchema` runs them — so the names are the ones\n * the site lifts, with no second copy of the naming rules to keep in step. A\n * name one of the site's own models takes too (an `a.b` enum beside an `aB`\n * object, both `GetPetError404AB`) is left to the merge passes, which move\n * the model (`GetPetError404AB2`): reserved, it would only send the site\n * past its own first candidate, where the two meet again. A site that steps\n * past its first candidate lifts its nested enums under the stem it moves to\n * (`GetPetError404BodyX`), so the name reserved for one of them is then held\n * by no enum: a model that derives it has still stepped to its qualified\n * name, the same in either document order.\n */\nfunction deferredEnumNames(item: DeferredInlineType): string[] {\n  const stem = deferredNamingStem(item)(0, []);\n  return rehearse(() => {\n    const models: Model[] = [];\n    extractInlineModelsFromProperties(\n      { properties: { [stem]: item.schema } },\n      models,\n      item.parentName,\n      item.componentSchemas,\n    );\n    const own = new Set(models.map((model) => model.name));\n    return [schemaToTypeRef(item.schema, stem, item.parentName), ...models.flatMap(collectModelTypeRefs)]\n      .flatMap(collectEnumRefs)\n      .filter((name) => !own.has(name));\n  });\n}\n\n/** The candidate property names of a deferred schema, by kind (see `materializeDeferredType`). */\nfunction deferredNamingStem(item: DeferredInlineType): (index: number, firstClashOwners: InlineModelOwner[]) => string {\n  const { name, statusCode = '', operationQualifier } = item;\n  const byStatus = `${name}${statusCode}`;\n  // Numbered as the cased name will read, not as the raw parameter or header\n  // name is written (`numberedProperty`): `filter[v2]` and `x-meta-v2_` end\n  // in a digit once cased, so their number goes behind `No` (`FilterV2No2`,\n  // `XMetaV2No2`) as `filterV2`'s does, never `FilterV22` (#533).\n  const numbered = (index: number): string => numberedProperty(name, index + 2);\n  const byNumber = (index: number): string => (index === 0 ? name : numbered(index - 1));\n  // A site a component response declares — its body, a secondary body, a\n  // header — steps the same way from every operation, at a 404, at `default`\n  // and in a range: by number, as the pre-pass that named the body steps\n  // (`resolveComponentResponseModelNames`), never by the operation or status\n  // code below, which belong to operation-owned sites; so every site that\n  // returns the component reaches the same name (workos/oagen#302).\n  if (item.componentSite !== undefined) return byNumber;\n  switch (item.kind) {\n    case 'header': {\n      // Decide the preference between candidates 2 and 3 from the bare\n      // name's owners: a clash within this operation reads best by status\n      // code, one with a component, a primary body or another operation by\n      // operation name. Joined with `_`, as a parameter's are, since the\n      // bare name is the lower-cased header name (`ListDocuments_x-meta` →\n      // `ListDocumentsXMeta`, not `ListDocumentsxMeta`).\n      const byOperationName = `${operationQualifier}_${name}`;\n      const byOperationAndStatus = `${operationQualifier}_${name}${statusCode}`;\n      return (index, firstClashOwners) => {\n        const withinOperation = firstClashOwners.every((owner) => owner.operation === operationQualifier);\n        const candidates = withinOperation\n          ? [name, byStatus, byOperationName, byOperationAndStatus]\n          : [name, byOperationName, byStatus, byOperationAndStatus];\n        return index < candidates.length ? candidates[index] : numbered(index - candidates.length);\n      };\n    }\n    case 'content':\n      // A later 2xx's secondary body has no bare name: it is named for its\n      // status code as its primary body is, then numbered under that\n      // (`…Response201No2`, behind `No` since the code ends in a digit,\n      // #533) — a run of its own, never the `…Response2`, `…Response3` the\n      // primary's bodies step through, so whichever of those the primary\n      // takes or gives up, the later body's name stands (workos/oagen#538).\n      if (item.later) return (index) => (index === 0 ? byStatus : numberedProperty(byStatus, index + 1));\n      return (index) => (index === 0 ? name : index === 1 ? byStatus : numbered(index - 2));\n    case 'request':\n    case 'fallback':\n      return byNumber;\n    case 'error':\n      return (index) => (index === 0 ? name : index === 1 ? `${name}Body` : numberedProperty(`${name}Body`, index));\n    case 'param': {\n      // Named like a header, with the location where a header has its\n      // status code: a clash within this operation (one name in two\n      // locations) reads best by location, one with a component, a primary\n      // body or another operation by operation name. Joined with `_` so a\n      // lower-case parameter name still starts a word (`ListPets_filter` →\n      // `ListPetsFilter`).\n      const byLocation = `${statusCode}_${name}`;\n      const byOperationName = `${operationQualifier}_${name}`;\n      const byOperationAndLocation = `${operationQualifier}_${statusCode}_${name}`;\n      return (index, firstClashOwners) => {\n        const withinOperation = firstClashOwners.every((owner) => owner.operation === operationQualifier);\n        const candidates = withinOperation\n          ? [name, byLocation, byOperationName, byOperationAndLocation]\n          : [name, byOperationName, byLocation, byOperationAndLocation];\n        return index < candidates.length ? candidates[index] : numbered(index - candidates.length);\n      };\n    }\n  }\n}\n\n/**\n * Defer the typing of every parameter of one location whose inline schema\n * mints a model — an object (`style: deepObject`), an array or map of\n * objects, a union with an inline object variant, a nullable wrapper around\n * one, at any depth — so the model is created, as a response header's is,\n * once every primary model is known (`resolveDeferredInlineTypes`), under a\n * name nothing else owns: `<Service><Param>` (`PetsFilter`), else the\n * location-, operation- or number-qualified candidates `deferredNamingStem`\n * lists; a name an enum has or will have — a component enum's, or the name\n * another parameter's or a field's inline enum is lifted under (`PetsKind`)\n * — is reserved in the registry, so the model steps to the\n * operation-qualified name (`PetsSearchPetsKind`). Called after the\n * operation's responses have been read, so a parameter's site follows the\n * response headers' in the registry: a response header the operation\n * already typed keeps its name (`PetsXMeta`), and a header parameter of the\n * same name takes the location-qualified one (`PetsHeaderXMeta`).\n * `extractParams` typed the parameter as the property of its name under the\n * service, and the trial extraction here reads the same synthetic property,\n * so the deferred site's first candidate is the name the parameter already\n * references and a parameter that mints no model — a primitive, a `$ref`,\n * an inline enum, an array of either — keeps the type it has and is not\n * deferred. `raw` and `typed` are the location's parameters in document\n * order, `typed[i]` built from `raw[i]` (`extractParams` maps the filtered\n * list one to one).\n */\nfunction deferParameterModels(\n  raw: readonly ParameterObject[],\n  typed: readonly Parameter[],\n  location: ParameterObject['in'],\n  ctx: ResponseTypingContext,\n): void {\n  const parentName = ctx.serviceName ? toPascalCase(ctx.serviceName) : undefined;\n  raw.forEach((param, index) => {\n    const target = typed[index];\n    // The schema `extractParams` typed the parameter from: `schema`, else the\n    // picked `content` entry's (`parameterTyping`).\n    const schema = parameterSchema(param);\n    if (!schema || !target) return;\n    // The name the models derive from is the one `extractParams` typed the\n    // parameter under — a header's lower-cased (`foldParameterName`) — so the\n    // reference and the model agree, and neither moves with the header's case.\n    const name = foldParameterName(location, param.name);\n    const trial: Model[] = [];\n    extractInlineModelsFromProperties({ properties: { [name]: schema } }, trial, parentName, ctx.componentSchemas);\n    if (trial.length === 0) return;\n    ctx.deferred.push({\n      kind: 'param',\n      schema,\n      name,\n      statusCode: location,\n      operationQualifier: ctx.operationQualifier,\n      parentName,\n      componentSchemas: ctx.componentSchemas,\n      targets: [target],\n    });\n  });\n}\n\n/**\n * Read a Response Object's `headers` map into IR response headers, resolving\n * `components/headers` refs. Returns `undefined` rather than `[]` when nothing\n * survives so callers can leave the `headers` key off entirely.\n *\n * An object-shaped header schema (directly, inside an array, or as a oneOf\n * variant) becomes a `ModelRef`, so the model it names must be materialized\n * — otherwise the ref would dangle with nothing to emit. That naming waits\n * for every primary model (`resolveDeferredInlineTypes`), so a header with a\n * schema is deferred and its `type` filled in then, qualified by\n * `site.headerParent`: the service for a header of an inline response\n * (`Notes` + `X-Meta` → `NotesXMeta`), the component's stem for one of a\n * response shared through `components/responses` (`Card` + `X-Meta` →\n * `CardXMeta`), as `responseModelSite` decides; the latter is a component\n * site (`componentSite`), so on a clash it steps by number (`CardXMeta2`)\n * rather than by the operation or status code.\n *\n * Header names are case-insensitive (RFC 9110 §5.1; OpenAPI says so of this\n * map), so two keys that differ in case alone (`X-Request-Id` beside\n * `x-request-id`) declare one header: the later declaration is kept, in the\n * earlier one's position, with a warning — the way an operation-level\n * parameter replaces a path-level one, except that the document gave these\n * two no precedence (#295).\n *\n * A header's `deprecated` and `externalDocs` are read from the layer its\n * schema documents itself with (`allOfWrapperLayer`): the schema's own\n * keys, then each `allOf` member's that declares no type and so only\n * annotates it — the first such member's winning among members — so a link\n * or flag written in such a member is the header's exactly as the same key\n * beside the `allOf` is, as a field, a parameter and the model built from\n * the schema read it (#555, #605). The Header Object's own `deprecated`\n * counts too; its `description` is the header's alone.\n */\nfunction extractResponseHeaders(\n  headers: Record<string, RawHeaderObject> | undefined,\n  operationLabel: string,\n  // A status code, or the label of a fallback response (`Default`, `ClientError`).\n  statusCode: number | string,\n  ctx: ResponseTypingContext,\n  site: ResponseModelSite,\n): ResponseHeader[] | undefined {\n  if (!headers) return undefined;\n\n  const declarations = new Map<string, { name: string; raw: RawHeaderObject }>();\n  for (const [name, raw] of Object.entries(headers)) {\n    const folded = foldHeaderName(name);\n    const earlier = declarations.get(folded);\n    if (earlier) {\n      console.warn(\n        `[oagen] Warning: Response header \"${name}\" on ${operationLabel} ${statusCode} is also declared as \"${earlier.name}\"; header names are case-insensitive, so the later declaration is used.`,\n      );\n    }\n    declarations.set(folded, { name, raw });\n  }\n\n  const result: ResponseHeader[] = [];\n  for (const [folded, { name, raw }] of declarations) {\n    // OAS 3.x: a response header named `Content-Type` SHALL be ignored; the\n    // media type is already carried by the response's `content` map. The\n    // sent-only component walk skips it by the same rule (#540).\n    if (isIgnoredResponseHeader(name)) continue;\n\n    const header = resolveHeaderRef(raw, ctx.componentHeaders, name, operationLabel, ctx.refSiblingDescriptions);\n    if (!header) continue;\n\n    // A Header Object declares `schema` or a single-entry `content` map; the\n    // schema that types the header is resolved as a parameter's is\n    // (`parameterTyping`): `schema`, else the picked `content` entry's. A map\n    // none of whose media types is read leaves the header a string, with a\n    // warning — once, here, as the header is typed.\n    const schema = parameterSchema(header);\n    warnUnreadParameterContent(header, `Response header \"${name}\" (${statusCode}) in ${operationLabel}`);\n    // The layer the header documents itself from: the schema's own keys,\n    // with each `allOf` member's that declares no type and so only annotates\n    // it folded in — the schema's own winning, then the first member's that\n    // declares one (`allOfWrapperLayer`; #555) — the one reading a field, a\n    // parameter and the model built from the schema give such a member, so\n    // `allOf: [{ type: 'integer' }, { externalDocs }]` and `allOf: [{ type:\n    // 'integer' }], externalDocs` are one header (#605: the flag read the\n    // members but the link the schema's own keys alone, so a link written\n    // in a member was dropped). The typing member's own keys stay on that\n    // member, and a `$ref` member's on its component, as for a field.\n    const layer = schema && allOfWrapperLayer(schema);\n    const entry: ResponseHeader = {\n      name,\n      type: { kind: 'primitive', type: 'string' },\n      required: header.required ?? false,\n      description: header.description,\n      // The Header Object's flag or its schema layer's — so a deprecated\n      // schema that folds onto a live component leaves it on the header; the\n      // model or enum a bare `$ref` names keeps its own, as for a field.\n      deprecated: header.deprecated === true || layer?.deprecated === true || undefined,\n      // The header schema layer's link — a Header Object has none — read from\n      // whichever of `schema` and `content` types the header, as the type is.\n      ...externalDocsEntry(layer?.externalDocs),\n    };\n    if (schema) {\n      // Named from the lower-cased header name, as a header parameter's inline\n      // type is, so the model or enum a header mints keeps its name when the\n      // header's case changes; `entry.name` stays as written.\n      ctx.deferred.push({\n        kind: 'header',\n        schema,\n        name: folded,\n        statusCode,\n        operationQualifier: ctx.operationQualifier,\n        parentName: site.headerParent,\n        componentSchemas: ctx.componentSchemas,\n        targets: [entry],\n        ...(site.component !== undefined && { componentSite: site.component }),\n      });\n    }\n    result.push(entry);\n  }\n\n  return result.length > 0 ? result : undefined;\n}\n\n/**\n * Build the prefix (`NotesByIdPinPost`) that names both inline models — the\n * request body (`…Request`) and the response (`…Response`) — of an operation\n * that has no `operationId`, from the only thing that identifies it: its path\n * and method.\n *\n * Every non-parameter segment is PascalCased in order and every parameter\n * segment becomes `By` + PascalCase(param name); then the optional\n * disambiguator and the method are appended. The whole is normalized with\n * toPascalCase so it is a fixed point of that function: responses.ts re-cases\n * the response name in `deriveModelName`, and without this step `POST /a/b`\n * named its body `ABPostRequest` but its response `AbPostResponse`.\n *\n *   GET  /widgets                   → WidgetsGet\n *   POST /notes                     → NotesPost\n *   POST /notes/{id}/pin            → NotesByIdPinPost\n *   GET  /users/{user_id}/sessions  → UsersByUserIdSessionsGet\n *\n * This tells the common path shapes apart (list vs. item, sibling and nested\n * sub-resources) but is not unique by construction: `/foo-bar` and `/foo/bar`,\n * `/notes/by-id` and `/notes/{id}`, `/notes` and `/notes/`, and a custom\n * method beside its slash form, `/pets/{id}:adopt` and `/pets/{id}/adopt`\n * (pathSegments reads the first as `{id}` then `adopt`), all flatten to the\n * same words. `resolvePathModelBaseNames` detects such collisions: the path\n * spelled most plainly keeps the plain name and every other one gets a\n * `disambiguator` derived from its raw path.\n *\n * A single-segment path keeps the name the old first-segment rule produced.\n * The result is deliberately not passed through cleanSchemaName (the old\n * fallback wasn't either): the segments are the resource names as the API\n * spells them.\n */\nexport function derivePathModelBaseName(path: string, method: HttpMethod, disambiguator = ''): string {\n  const segments = pathSegments(path);\n  const parts = segments.map((segment) =>\n    isParameterSegment(segment) ? 'By' + toPascalCase(segment.replace(/[{}]/g, '')) : toPascalCase(segment),\n  );\n  const resource = parts.length > 0 ? parts.join('') : 'Unknown';\n  // `_` separators guarantee a word boundary on each side of the disambiguator\n  // and the method, whatever the resource ends with; splitWords drops them,\n  // so the disambiguator is the suffix numberedName gives the resource: a\n  // hash that starts with a digit is set off from a resource that ends in one\n  // as a number is (`PetsTop10No567B59Get`, never `PetsTop10567B59Get`).\n  const hash = numberedName(resource, disambiguator).slice(resource.length);\n  return toPascalCase([resource, hash, method].filter(Boolean).join('_'));\n}\n\n/** `derivePathModelBaseName` plus the `Request` / `Response` suffix. */\nexport function derivePathBasedName(\n  path: string,\n  method: HttpMethod,\n  suffix: 'Request' | 'Response',\n  disambiguator = '',\n): string {\n  return derivePathModelBaseName(path, method, disambiguator) + suffix;\n}\n\n/**\n * The order the naming passes take operations in where a choice must not\n * depend on document order — the one the numeric pass of\n * disambiguateOperationNames keeps a name in: the shorter API root, then the\n * path by code unit, then the method in HTTP_METHODS order. Orders the\n * claims of resolveReusedOperationIds and the paths of an Operation Object\n * resolveContestedOperationIdStems path-names.\n */\nfunction compareOperationOrder(\n  a: { rootLength: number; path: string; method: HttpMethod },\n  b: { rootLength: number; path: string; method: HttpMethod },\n): number {\n  return (\n    a.rootLength - b.rootLength ||\n    (a.path < b.path ? -1 : a.path > b.path ? 1 : 0) ||\n    HTTP_METHODS.indexOf(a.method) - HTTP_METHODS.indexOf(b.method)\n  );\n}\n\n/**\n * What the models of each operation whose `operationId` the document reuses\n * are named from, keyed by `${method} ${path}`. `modelOperationIds` holds\n * the name to read as its `operationId`, or `null` for one that names them\n * from its path, as an operation without an `operationId` does\n * (resolvePathModelBaseNames); an operation not there names them from its\n * own. `sharedWith` holds, for a path that `$ref`s the Operation Object of\n * another, the path whose models it shares. Reused means declared on more\n * than one Operation Object, which OpenAPI forbids — as written, or up to\n * the trailing overload markers (normalizeOperationIdForNaming): `listPets[1]`\n * and `listPets[2]` or `listPets[1][2]` take one name and one stem, so\n * they are one id, reused, exactly as `listPets` declared twice is (#565).\n * Every such operation would otherwise name its models alike\n * (`CreateNoteRequest`), and the merge would keep one body for all of them.\n *\n * Each Operation Object claims the stem (operationIdModelBase) of the name\n * the first of its paths ends up with (planOperations): its `operationId`'s\n * while the operation keeps the name it took from it, and its new name's\n * when the reuse renamed it within its service — `createNote2` names its\n * models `CreateNote2Request` beside `createNote`'s `CreateNoteRequest`.\n * Paths and claims are taken in the order the numeric pass of\n * disambiguateOperationNames keeps a name in — the shorter API root, then\n * the path by code unit, then the method in HTTP_METHODS order\n * (compareOperationOrder) — so the outcome never depends on document\n * order. The stems the document wrote\n * are served first, each granted while no earlier claim and no `operationId`\n * declared on one Operation Object holds it; then the new names, which the\n * parser made, each granted, as a path-derived prefix is, only while no\n * stem held starts with it: a renamed `getNote2` that returns a `request`\n * object would name it `GetNote2ResponseRequest`, the request body of\n * `operationId: getNote2Response`. An operation whose claim is not granted\n * names its models from its path: one that kept the name in another service\n * as well (`createNote` in `Notes` and in `ArchivedNotes`: `/archived-notes`\n * sorts first, so `/notes` sends a `NotesPostRequest`), or one renamed to a\n * name another `operationId` holds. Every other path of the Operation\n * Object reads its one body and shares its models. An `operationId`\n * declared on one Operation Object is not reused, even when two paths\n * `$ref` the Path Item it is on.\n */\nfunction resolveReusedOperationIds(\n  paths: Record<string, PathItem>,\n  plan: OperationPlan,\n): { modelOperationIds: Map<string, string | null>; sharedWith: Map<string, string> } {\n  const declaring = new Map<string, Array<{ key: string; path: string; method: HttpMethod; op: OperationObject }>>();\n  for (const [path, pathItem] of Object.entries(paths)) {\n    for (const method of HTTP_METHODS) {\n      const op = pathItem[method];\n      if (!op?.operationId) continue;\n      // Ids that strip to one (`listPets[1]`, `listPets[2]`, `listPets[1][2]`)\n      // take one name and one stem, so they are one id, reused.\n      const id = normalizeOperationIdForNaming(op.operationId);\n      const entries = declaring.get(id) ?? [];\n      entries.push({ key: `${method} ${path}`, path, method, op });\n      declaring.set(id, entries);\n    }\n  }\n  const reused = (entries: Array<{ op: OperationObject }>) => new Set(entries.map(({ op }) => op)).size > 1;\n  // Every stem an `operationId` declared on one Operation Object holds.\n  const held = new Set(\n    [...declaring.values()]\n      .filter((entries) => !reused(entries))\n      .map(([{ op }]) => operationIdModelBase(op.operationId!)),\n  );\n  const claims = [...declaring.values()]\n    .filter(reused)\n    .flat()\n    .map((entry) => ({ ...entry, ...plan.operations.get(entry.key)! }))\n    .sort(compareOperationOrder);\n\n  // One claim per Operation Object, made by the first of its paths.\n  const claimants = new Map<OperationObject, (typeof claims)[number]>();\n  const sharedWith = new Map<string, string>();\n  for (const claim of claims) {\n    const first = claimants.get(claim.op);\n    if (first) sharedWith.set(claim.key, first.key);\n    else claimants.set(claim.op, claim);\n  }\n\n  const modelOperationIds = new Map<string, string | null>();\n  for (const { key, op, initialName, name } of claimants.values()) {\n    if (name !== initialName) continue;\n    const stem = operationIdModelBase(op.operationId!);\n    if (held.has(stem)) modelOperationIds.set(key, null);\n    held.add(stem);\n  }\n  for (const { key, initialName, name } of claimants.values()) {\n    if (name === initialName) continue;\n    const stem = operationIdModelBase(name);\n    modelOperationIds.set(key, [...held].some((taken) => taken.startsWith(stem)) ? null : name);\n    held.add(stem);\n  }\n  for (const [key, first] of sharedWith) {\n    if (modelOperationIds.has(first)) modelOperationIds.set(key, modelOperationIds.get(first)!);\n  }\n  return { modelOperationIds, sharedWith };\n}\n\n/**\n * Settle every stem (operationIdModelBase) more than one Operation Object\n * would name its models from, so that no two operations' bodies share a\n * model (#627). Two distinct `operationId`s can clean to one stem:\n * `createPet` beside `create_pet` or `CreatePet` (each PascalCases to\n * `CreatePet`) or beside `createPetController` (`Controller` is a backend\n * word cleanSchemaName strips), `listNotes` beside `listNotesByExternalId`\n * (`ByExternalId` is a marker it strips), `Notes_List` beside `Note_List`\n * (the leading word is singularized). Every model the stem names —\n * `CreatePetRequest`, `CreatePetResponse`, `CreatePetError404`, a list's\n * `CreatePetItem`, the nested models and envelope companions under them and\n * the enums the bodies mint — was minted once per operation, and the merge\n * kept the first definition for both, so one operation was typed with\n * fields it does not take, and which one followed the order of the paths.\n *\n * Of the Operation Objects that contest a stem, the one the cleaning moved\n * least keeps the stem and the plain names, and every other one names its\n * models from its path (`PetDraftsPostRequest`), exactly as a reused id's\n * later operation does (resolveReusedOperationIds). An id the cleaning\n * stripped a marker or a backend word from (`listNotesByExternalId`,\n * `createPetController`) never keeps a contested stem. Among the rest, one\n * whose PascalCase form — read with the overload markers at its end\n * stripped (normalizeOperationIdForNaming) — is the stem as written\n * (`createPet`, `create_pet` and `CreatePet` alike for `CreatePet`;\n * `list_notes` or `ListNotes` for `ListNotes`) outranks one whose leading\n * word was only singularized (`Notes_List`, `NotesList` to `NoteList`), so\n * `Note_List` keeps `NoteList` beside `Notes_List`, and `Notes_List` keeps\n * it beside `Notes_ListByExternalId`. A tie — ids that differ in case or\n * separators alone, `createPet` beside `create_pet` or `CreatePet` — goes\n * to the one written in camelCase (the id is its own PascalCase form with\n * the first letter lowered) when there is exactly one, and to none when\n * there is none (`create_pet` beside `CreatePet`); two cannot be, since one\n * id as written names the models of one Operation Object once the reuse\n * pass has run. So adding `create_pet` beside `createPet`, or\n * `list_notes_by_external_id` beside `list_notes`, adds models and renames\n * none of the existing operation's, whatever the order of the paths and\n * whatever case the document writes its ids in: the outcome depends on the\n * document's `operationId`s alone. Whether the contested bodies agree in\n * shape takes no part, so that a change to one body never renames its model.\n *\n * Read off the `operationId` each operation's models are named from\n * (`modelOperationIds`: the one the reuse of its own left it, or its own),\n * with a path that shares another's Operation Object (`sharedWith`) and a\n * second path onto one Path Item both reading as the one Operation Object\n * they are, so an `operationId` declared once holds its stem alone however\n * many paths reach it. An Operation Object that loses its stem names its\n * models from the first of its paths in the order the reuse pass takes\n * claims in (compareOperationOrder), and every other path of it shares\n * them. Written into `modelOperationIds` (`null`: path-named) and\n * `sharedWith`, which every later pass reads.\n */\nfunction resolveContestedOperationIdStems(\n  paths: Record<string, PathItem>,\n  plan: OperationPlan,\n  modelOperationIds: Map<string, string | null>,\n  sharedWith: Map<string, string>,\n): void {\n  /** One path's operation: its plan key, and what orders it among the paths of its Operation Object. */\n  interface Site {\n    key: string;\n    path: string;\n    method: HttpMethod;\n    rootLength: number;\n  }\n  /** An Operation Object whose models a stem would name: the id they are read from, its PascalCase form, and the paths that reach it. */\n  interface Holder {\n    id: string;\n    pascal: string;\n    sites: Site[];\n  }\n  const holders = new Map<string, Map<OperationObject, Holder>>();\n  for (const [path, pathItem] of Object.entries(paths)) {\n    for (const method of HTTP_METHODS) {\n      const op = pathItem[method];\n      if (!op) continue;\n      const key = `${method} ${path}`;\n      if (sharedWith.has(key)) continue;\n      const operationId = modelOperationIds.has(key) ? modelOperationIds.get(key) : op.operationId;\n      if (!operationId) continue;\n      const stem = operationIdModelBase(operationId);\n      const ops = holders.get(stem) ?? new Map<OperationObject, Holder>();\n      const id = normalizeOperationIdForNaming(operationId);\n      const holder = ops.get(op) ?? { id, pascal: toPascalCase(id), sites: [] };\n      holder.sites.push({ key, path, method, rootLength: plan.operations.get(key)!.rootLength });\n      ops.set(op, holder);\n      holders.set(stem, ops);\n    }\n  }\n  /** How far the cleaning moved an id from its stem: not at all, its leading word singularized, or a marker or backend word stripped. */\n  const distance = ({ pascal }: Holder, stem: string) =>\n    pascal === stem ? 0 : singularizeLeadingWord(pascal) === stem ? 1 : 2;\n  /** Whether an id is written in camelCase: its own PascalCase form with the first letter lowered. */\n  const camelCased = ({ id, pascal }: Holder) => id === pascal.charAt(0).toLowerCase() + pascal.slice(1);\n  for (const [stem, ops] of holders) {\n    if (ops.size < 2) continue;\n    const least = Math.min(...[...ops.values()].map((holder) => distance(holder, stem)));\n    const nearest = least < 2 ? [...ops.values()].filter((holder) => distance(holder, stem) === least) : [];\n    const camel = nearest.filter(camelCased);\n    const keeper = nearest.length === 1 ? nearest[0] : camel.length === 1 ? camel[0] : undefined;\n    for (const holder of ops.values()) {\n      if (holder === keeper) continue;\n      const [first, ...rest] = holder.sites.sort(compareOperationOrder);\n      modelOperationIds.set(first.key, null);\n      for (const { key } of rest) {\n        modelOperationIds.set(key, null);\n        sharedWith.set(key, first.key);\n      }\n    }\n  }\n}\n\n/**\n * Decide the path-derived model prefix of every operation that names its\n * models from its path — one without an `operationId`, or one whose\n * `operationId` the document reuses and leaves it none\n * (resolveReusedOperationIds) — keyed by `${method} ${path}`.\n * A path that shares another's Operation Object (`sharedWith`) takes no part:\n * it names its models as that path does.\n *\n * A prefix collides when two distinct raw paths with the same method flatten\n * to it (see derivePathModelBaseName), or when a reserved name starts with\n * it. The reserved names are every resolved component model name and, for\n * every operation that names its models from an `operationId`, their stem\n * (operationIdModelBase). A prefix is the stem of several emitted names —\n * `…Request`, `…Response`, a list's `…Item`, nested inline models such as\n * `…ResponseOwner`, envelope companions such as `…ListMetadata` — so the\n * check is on the stem, not on an enumeration of suffixes: an unnamed\n * `GET /audit/events` must not overwrite `components/schemas/AuditEventsGetItem`\n * any more than an unnamed `POST /audit/events` may overwrite the models of\n * a `POST /legacy-audit` whose operationId is `auditEventsPost`. A prefix\n * that extends such a stem is the one case the stem check does not reach:\n * `GET /create/pet/response/drafts` beside `createPet` flattens to\n * `CreatePetResponseDraftsGet`, and its `…Response` is exactly the name of\n * a `drafts_get_response` object nested in `createPet`'s response\n * (`CreatePetResponseDraftsGetResponse`), which starts with the stem rather\n * than the other way round; the later merge would keep one shape for both.\n * So when any prefix extends an operation's stem, every name the operations'\n * inline request and success bodies mint — nested models included — is\n * reserved too (`operationBodyNames`, see operationBodyModelNames), and\n * read only then, since the reading rehearses every body. Reserved names\n * never change.\n *\n * This is deliberately a superset: a component named `AuditEventsGetter`, or\n * an operationId `auditEventsGetSummary`, also pushes `GET /audit/events`\n * onto a hashed name although no emitted name would coincide. Determinism\n * and never sharing a name wrongly matter more than the rare extra hash, and\n * the reservation is unconditional — an inline body is never merged into a\n * same-named component even when the shapes agree — so the rule stays\n * simple and order-free. Every name derived from a path-based prefix uses it\n * verbatim (body `oneOf` variants included; see deriveOneOfVariantName), and\n * as a second line of defence the check also runs on the cleaned spellings\n * of the prefix (see prefixSpellings), so `GET /notes` yields to a component\n * `NoteGetItem` although its own item model is `NotesGetItem`. Names that\n * embed the prefix behind a const value — a body `oneOf` variant pinning\n * `kind: email` is `EmailTagsPostRequest`, a nested variant\n * `<Const><Parent><Field>` — are checked too, with each const the operation\n * can mint prepended to every spelling (see collectOperationConstPrefixes);\n * the hash then lands inside those names as well (`EmailTags151Dd5PostRequest`).\n *\n * These names are types SDK users read and import, so a collision costs the\n * plain name only where it must. Within a group of paths that flatten to one\n * prefix, the path spelled most plainly (see pathDeviation: no trailing\n * slash, `{id}` rather than a literal `by-id`) is canonical and keeps the\n * plain prefix; every other path gets a six-character disambiguator, the\n * start of the SHA-1 of its raw path, inserted before the method\n * (`POST /foo-bar` next to `POST /foo/bar` → `FooBar546F12Post`). When two\n * paths tie for plainest, or the prefix is reserved, nobody is canonical and\n * every path in the group is disambiguated. The outcome depends only on the\n * document's paths, operationIds and component names, never on their order,\n * and a path that stops colliding returns to its plain name.\n */\nfunction resolvePathModelBaseNames(\n  paths: Record<string, PathItem>,\n  componentModels?: Model[],\n  componentRequestBodies?: Record<string, Record<string, unknown>>,\n  componentResponseNaming: ReadonlyMap<string, ComponentResponseNaming> = new Map(),\n  modelOperationIds: ReadonlyMap<string, string | null> = new Map(),\n  sharedWith: ReadonlyMap<string, string> = new Map(),\n  /** Every name the operations' inline request and success bodies mint (operationBodyModelNames), read only when a prefix extends an operation's stem. */\n  operationBodyNames: () => readonly string[] = () => [],\n): Map<string, string> {\n  const candidates: Array<{ key: string; path: string; method: HttpMethod; plain: string }> = [];\n  const rawPathsByPlainName = new Map<string, Set<string>>();\n  const constPrefixesByPlainName = new Map<string, Set<string>>();\n  const reservedNames = new Set<string>();\n  /** The stem of every operation that names its models from an `operationId`, which a prefix may extend. */\n  const operationStems = new Set<string>();\n\n  for (const model of componentModels ?? []) {\n    reservedNames.add(model.name);\n  }\n  // A shared response names its inline body after the component, not the\n  // operation (see componentResponseModelName), so its stem is reserved like\n  // an operationId's — and so is every name that body mints, the model and\n  // everything nested under it (`OwnerCardResponseAddressGetResponse` for an\n  // `address_get_response` object in `OwnerCard`): a path stem that merely\n  // extends the component's (`GET /owner/card/response/address` →\n  // `OwnerCardResponseAddressGet`) starts with none of the stems above, yet\n  // its `…Response` is exactly such a nested name, and the later merge would\n  // keep one shape for both. The names are the ones\n  // `resolveComponentResponseModelNames` read with the extractor the\n  // operation will use, under the same context name, so they agree by\n  // construction.\n  for (const [componentName, naming] of componentResponseNaming) {\n    reservedNames.add(componentResponseModelBase(componentName));\n    reservedNames.add(naming.name);\n    for (const name of naming.minted) reservedNames.add(name);\n  }\n\n  for (const [path, pathItem] of Object.entries(paths)) {\n    for (const method of HTTP_METHODS) {\n      const op = pathItem[method];\n      if (!op) continue;\n      const key = `${method} ${path}`;\n      if (sharedWith.has(key)) continue;\n      const modelOperationId = modelOperationIds.has(key) ? modelOperationIds.get(key) : op.operationId;\n      if (modelOperationId) {\n        const stem = operationIdModelBase(modelOperationId);\n        reservedNames.add(stem);\n        operationStems.add(stem);\n        continue;\n      }\n      const plain = derivePathModelBaseName(path, method);\n      candidates.push({ key, path, method, plain });\n      const rawPaths = rawPathsByPlainName.get(plain) ?? new Set<string>();\n      rawPaths.add(path);\n      rawPathsByPlainName.set(plain, rawPaths);\n      const constPrefixes = constPrefixesByPlainName.get(plain) ?? new Set<string>();\n      for (const prefix of collectOperationConstPrefixes(\n        op,\n        componentRequestBodies,\n        operationLabel(op, path, method),\n      )) {\n        constPrefixes.add(prefix);\n      }\n      constPrefixesByPlainName.set(plain, constPrefixes);\n    }\n  }\n\n  // Every stem a name minted from each prefix can start with: the prefix in\n  // each of its cleaned spellings, and each const value the operation can\n  // prepend to it (`EmailTagsPostRequest` is `Email` + `TagsPost…`).\n  const stemsByPlainName = new Map(\n    [...rawPathsByPlainName.keys()].map((plain) => {\n      const spellings = prefixSpellings(plain);\n      const constPrefixes = ['', ...(constPrefixesByPlainName.get(plain) ?? [])];\n      return [plain, constPrefixes.flatMap((constPrefix) => spellings.map((spelling) => constPrefix + spelling))];\n    }),\n  );\n  // A prefix that extends an operation's stem (`CreatePetResponseDraftsGet`\n  // beside `createPet`) can mint a name that operation's bodies nest\n  // (`CreatePetResponseDraftsGetResponse`), which the stem check below does\n  // not reach, so the names the bodies mint are reserved as well — read\n  // only now, since the reading rehearses every body.\n  const extendsOperationStem = (stem: string) =>\n    [...operationStems].some((held) => stem.length > held.length && stem.startsWith(held));\n  if ([...stemsByPlainName.values()].some((stems) => stems.some(extendsOperationStem))) {\n    for (const name of operationBodyNames()) reservedNames.add(name);\n  }\n\n  const reservedList = [...reservedNames];\n  const canonicalByPlainName = new Map<string, string | undefined>();\n  for (const [plain, rawPaths] of rawPathsByPlainName) {\n    const stems = stemsByPlainName.get(plain)!;\n    const reserved = stems.some((stem) => reservedList.some((name) => name.startsWith(stem)));\n    canonicalByPlainName.set(plain, reserved ? undefined : canonicalPath(rawPaths));\n  }\n\n  const resolved = new Map<string, string>();\n  for (const { key, path, method, plain } of candidates) {\n    const keepsPlainName = canonicalByPlainName.get(plain) === path;\n    resolved.set(key, keepsPlainName ? plain : derivePathModelBaseName(path, method, pathDisambiguator(path)));\n  }\n  return resolved;\n}\n\n/**\n * The one path in a group that is spelled most plainly by pathDeviation, or\n * undefined when two or more tie for it, so the choice never depends on the\n * order the paths were written in.\n */\nfunction canonicalPath(rawPaths: Iterable<string>): string | undefined {\n  let best: string | undefined;\n  let bestScore: PathDeviation | undefined;\n  let tied = false;\n  for (const path of rawPaths) {\n    const score = pathDeviation(path);\n    const cmp = bestScore ? compareDeviation(score, bestScore) : -1;\n    if (cmp < 0) {\n      best = path;\n      bestScore = score;\n      tied = false;\n    } else if (cmp === 0) {\n      tied = true;\n    }\n  }\n  return tied ? undefined : best;\n}\n\n/** See pathDeviation. */\ntype PathDeviation = [trailingSlash: number, customMethods: number, irregularSegments: number];\n\n/**\n * How far a raw path's spelling is from the plain prefix it flattens to:\n * `[trailing slash, custom methods written after a colon, literal segments\n * with any character outside a-z0-9]`, compared lexicographically. `/notes`\n * scores [0, 0, 0] and `/notes/` [1, 0, 0]; `/notes/{id}` scores [0, 0, 0]\n * and `/notes/by-id` [0, 0, 1]. A custom method is counted on its own rather\n * than as an irregular segment, so the slash form wins whatever the verb's\n * spelling: `/pets/{id}:adopt` scores [0, 1, 0] against `/pets/{id}/adopt`\n * at [0, 0, 0], and `/pets/{id}:batchAdopt` [0, 1, 1] against\n * `/pets/{id}/batchAdopt` at [0, 0, 1]. A parameter segment is never\n * irregular, whatever follows its braces, so a path without a colon scores\n * as it did before custom methods were read: `/tags/{tag}.json` and\n * `/tags/{tag}/json` still tie. A segment kept whole for its several colons\n * is a literal even when a parameter opens it (isParameterSegment), so\n * `/pets/{id}:adopt:now` scores [0, 0, 1].\n */\nfunction pathDeviation(rawPath: string): PathDeviation {\n  const trailingSlash = rawPath.length > 1 && rawPath.endsWith('/') ? 1 : 0;\n  const segments = readPath(rawPath);\n  const customMethods = segments.filter((segment) => segment.customMethod).length;\n  const irregularSegments = segments.filter(\n    (segment) => !isParameterSegment(segment.text) && /[^a-z0-9]/.test(segment.text),\n  ).length;\n  return [trailingSlash, customMethods, irregularSegments];\n}\n\nfunction compareDeviation(a: PathDeviation, b: PathDeviation): number {\n  return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];\n}\n\n/** The first six hex characters of the SHA-1 of a raw path. */\nfunction pathDisambiguator(rawPath: string): string {\n  return createHash('sha1').update(rawPath).digest('hex').slice(0, 6);\n}\n\n/**\n * The spellings a path-based prefix could take if a name derived from it were\n * run through one of the parser's cleaning steps: the prefix itself (every\n * path-derived name uses it verbatim), cleanSchemaName's form (lead-word\n * singularization plus backend and ListItem-marker stripping),\n * resolveSchemaName's form (the same plus the project's schemaNameTransform),\n * and stripListItemMarkers alone, which nested-model and inline-enum\n * qualification apply to a parent name. Reserving by every spelling is the\n * second line of defence behind \"use the base verbatim\": a cleaning step added\n * later cannot let a derived name slip past the reservation. Empty spellings\n * are dropped so a degenerate prefix cannot match every reserved name.\n */\nfunction prefixSpellings(prefix: string): string[] {\n  const spellings = [prefix, cleanSchemaName(prefix), resolveSchemaName(prefix), stripListItemMarkers(prefix)];\n  return [...new Set(spellings)].filter((spelling) => spelling.length > 0);\n}\n\n/**\n * The PascalCase const values an operationId-less operation can prepend to a\n * name minted from its prefix, read from the schemas its request body and 2xx\n * responses declare inline. A body `oneOf` variant pinning `kind: email`\n * yields `EmailTagsPostRequest` (deriveOneOfVariantName); a nested\n * `oneOf`/`anyOf` object variant yields `<Const><Parent><Field>`\n * (nameOneOfVariant, nameVariantModel). Every string const or single-value\n * enum of every inline object variant is collected (`constStringOf`: as\n * written, or behind a nullable wrapper or an `allOf` read as one member,\n * as the naming reads it; #607), top level and nested — a\n * superset of whichever property each of those picks as the discriminator, so\n * the reservation can never be narrower than the naming. `$ref` targets are\n * components with names of their own and are not followed. A request body\n * `$ref` that cannot be resolved is left for buildOperation to report.\n *\n * Names that do not embed the prefix at all — a response `oneOf` variant\n * named from its bare const (`Email`, see deriveModelName in responses.ts)\n * or a `title`-mapped variant — are outside what a disambiguator can\n * separate and are not reserved here.\n */\nfunction collectOperationConstPrefixes(\n  op: OperationObject,\n  componentRequestBodies: Record<string, Record<string, unknown>> | undefined,\n  opLabel: string,\n): Set<string> {\n  const prefixes = new Set<string>();\n  let body: RequestBodyObject | undefined;\n  try {\n    body = resolveRequestBodyRef(op.requestBody, componentRequestBodies, opLabel);\n  } catch {\n    body = undefined;\n  }\n  collectConstPrefixes(selectRequestBodyContent(body)?.schema, prefixes, 0);\n  for (const [statusCode, response] of Object.entries(op.responses ?? {})) {\n    // Only a key `extractResponses` reads as a 2xx status code: a range, a\n    // fallback or a key OpenAPI does not define reserves nothing.\n    const responseKey = classifyResponseKey(statusCode);\n    if (responseKey.kind !== 'status' || responseKey.code < 200 || responseKey.code >= 300) continue;\n    // An entry that is not an object reserves nothing; the operation warns\n    // about it once when it reads it (#617).\n    if (!isResponseEntry(response)) continue;\n    // A Reference Object is not followed, and nothing beside its `$ref` is\n    // read (#562): a `$ref` into `components/responses` names its inline\n    // body after the component, so the consts it pins never prefix a\n    // path-derived name, and a ref nothing answers gives the operation no\n    // body at all — not the `content` written beside it either.\n    if ('$ref' in response) continue;\n    for (const media of Object.values(response.content ?? {})) {\n      collectConstPrefixes(media?.schema, prefixes, 0);\n    }\n  }\n  return prefixes;\n}\n\nfunction collectConstPrefixes(schema: SchemaObject | undefined, out: Set<string>, depth: number): void {\n  if (!schema || schema.$ref || depth > 16) return;\n  for (const variants of [schema.oneOf, schema.anyOf]) {\n    for (const variant of variants ?? []) {\n      if (variant.$ref || !variant.properties) continue;\n      for (const property of Object.values(variant.properties)) {\n        const value = constStringOf(property);\n        const prefix = value === null ? '' : toPascalCase(value);\n        if (prefix) out.add(prefix);\n      }\n    }\n  }\n  const children: Array<SchemaObject | undefined> = [\n    ...(schema.oneOf ?? []),\n    ...(schema.anyOf ?? []),\n    ...(schema.allOf ?? []),\n    schema.items,\n    ...Object.values(schema.properties ?? {}),\n    typeof schema.additionalProperties === 'object' ? schema.additionalProperties : undefined,\n  ];\n  for (const child of children) {\n    collectConstPrefixes(child, out, depth + 1);\n  }\n}\n\n/**\n * A property's pinned string value, read as the naming reads an inline\n * variant's own property (`pinnedDeclarationValue` without the component\n * map, the reading `getConstPropertyValue` makes): a string `const` or a\n * single-value string `enum`, written on the property or behind a nullable\n * wrapper or an `allOf` read as one member (`kind: { allOf: [{ const:\n * 'email' }] }`; #607), so the reservation reads every const the naming\n * reads. A `$ref` on the property is followed by neither.\n */\nfunction constStringOf(property: SchemaObject | undefined): string | null {\n  return property ? pinnedDeclarationValue(property) : null;\n}\n\nfunction deriveResponseName(op: OperationObject | undefined, pathModelBaseName: string): string {\n  if (op?.operationId) {\n    return operationIdModelName(op.operationId, 'Response');\n  }\n  return pathModelBaseName + 'Response';\n}\n\n/**\n * Element type of the array an overridden `dataPath` names in one response\n * body. The IR answers first — the detected data array itself, an envelope\n * companion's field (companion models included, so the parser's own item\n * model is reused and follows any later renaming), or the response model's\n * fields, through the models a component's fields mint too (`result.items`\n * through a `result` two `allOf` members of `PetPage` conjoin yields the\n * items `PetPageResult` holds), the walk starting where `dataPathWalkStart`\n * says. A walk that crosses a reference `resolveSchemaPointers` has yet to\n * settle — the response written as a `$ref` deeper into a component\n * (`#/components/schemas/Holder/properties/result`), or a field on the way\n * written so — answers nothing yet: the model the pointed schema's items\n * are built as exists, and reading the document now would mint a copy of\n * it (`ListOwnersItem` beside `HolderResultItem`; #608), so the item type\n * is a placeholder the settle decides from the settled types\n * (`settleDeferredDataPathItemType`) — unless the path goes on through the\n * variants of a union to more than one array (`dataPathForks`): each\n * variant's model types inline items under a name of its own, so the\n * document answers now, under the path-derived name, as it does for such a\n * union the IR already holds (#556), and a `$ref` or primitive the variants\n * share is the one type the settle would find; variants that all hold one\n * pointer land on one array and are settled like any other path. The\n * document (`schema`, classified under\n * `contextName`) answers otherwise only when the path crosses a model the\n * parser has not materialized, minting inline items under a path-derived\n * name.\n */\nfunction resolveOverrideItemType(\n  result: ResponseExtractionResult,\n  schema: SchemaObject,\n  contextName: string,\n  dataPath: string,\n  componentModels: Model[],\n  componentSchemas?: Record<string, SchemaObject>,\n  settle?: ItemSettlement,\n): { itemType: TypeRef; inlineModels: Model[] } | undefined {\n  if (dataPath === result.dataPath && result.itemType) return { itemType: result.itemType, inlineModels: [] };\n\n  const pool = [\n    ...result.inlineModels,\n    ...(result.envelopeCompanions ?? []).flatMap((companion) => companion.models),\n    ...componentModels,\n  ];\n  const start = dataPathWalkStart(result.response, result.envelopeFields, dataPath);\n  const walked = start && walkDataPathItemType(start.root, start.path, pool);\n  if (walked && 'itemType' in walked) return { itemType: walked.itemType, inlineModels: [] };\n  if (walked?.pending && !dataPathForks(schema, dataPath, componentSchemas)) {\n    return { itemType: deferDataPathItemType(), inlineModels: [] };\n  }\n\n  return resolveDataPathFromSchema(schema, dataPath, contextName, componentSchemas, settle);\n}\n\n/** What the explicit pagination override asks of response extraction. */\ninterface PaginationExtractionOptions {\n  /**\n   * Nothing pages the operation — `strategy: 'none'`, or no query parameter\n   * drives an iterator and no override names one: keep a list envelope as a\n   * plain response model instead of unwrapping it.\n   */\n  disabled?: boolean;\n  /** An explicit `dataPath` to resolve to the element type of the array it names. */\n  dataPath?: string;\n  /**\n   * An explicit `endOfIteration` to check against the primary response\n   * (`decidePaginationOverride`): its path must land on a field whose type\n   * fits its kind, or the override is unusable.\n   */\n  endOfIteration?: PaginationEndOfIteration;\n  /**\n   * Component models and the models their fields mint (a nested object, an\n   * `allOf` merge, array items), so the IR walk can follow a `$ref`\n   * wrapper's fields into the models the parser already built for them.\n   */\n  componentModels?: Model[];\n  /**\n   * The override is the only source of an iterator: no query parameter\n   * yields one. A body its `dataPath` reaches no array in, or its\n   * `endOfIteration` resolves in to no field of the fitting type, is then\n   * kept as a plain response model too, since the override will be dropped\n   * (`buildOperation` warns) and nothing else pages the body. For the\n   * primary body that is exactly the case in which the override is dropped;\n   * a secondary 2xx body that cannot satisfy it is kept the same way.\n   */\n  overrideOnly?: boolean;\n}\n\n/** Whether the pagination override applies to the operation's responses, decided once against the primary body. */\ninterface PaginationOverrideDecision {\n  /**\n   * The override applies: its `dataPath` is handed to classification in\n   * every success body it reaches an array in, and its stop field is the\n   * iterator's.\n   */\n  usable: boolean;\n  /** Why it does not — the text `buildOperation` warns with; unset when it does. */\n  problem?: string;\n}\n\n/** One 2xx or 3xx entry, with the body `primaryBodySchema` picks from a 2xx (`{}` for a 3xx, which never types one). */\ninterface SuccessEntry {\n  code: number;\n  pick: ReturnType<typeof primaryBodySchema>;\n}\n\n/**\n * The primary response among the 2xx and 3xx entries — the one\n * `Operation.response` describes and the pagination override is decided\n * against — chosen by one rule, before any body is classified, so the two\n * never diverge: the lowest 2xx whose body is typed (`bodyIsTyped`), else\n * the lowest declared code (an untyped 2xx, or a 3xx when there is no 2xx).\n * `undefined` when no 2xx or 3xx is declared.\n */\nfunction primaryResponseEntry(\n  entries: readonly SuccessEntry[],\n  componentSchemas?: Record<string, SchemaObject>,\n): SuccessEntry | undefined {\n  const sorted = [...entries].sort((a, b) => a.code - b.code);\n  return sorted.find((entry) => entry.code < 300 && bodyIsTyped(entry.pick, componentSchemas)) ?? sorted[0];\n}\n\n/**\n * Whether a 2xx body will type as anything but `unknown` once classified: a\n * media type typed without a schema (binary, text), or a schema\n * classification types as something — asked of classification's own\n * reading of the body (`bodyTypesAsUnknown`: the same `$ref`, fold,\n * envelope, wrapper and `extractDirectResource` dispatch, ending on\n * `typesAsUnknown` where classification ends on `schemaToTypeRef`), before\n * any body is typed and without the warnings typing issues, so a body is\n * `unknown` after classification exactly when this says so before it.\n */\nfunction bodyIsTyped(\n  pick: ReturnType<typeof primaryBodySchema>,\n  componentSchemas?: Record<string, SchemaObject>,\n): boolean {\n  return pick.type !== undefined || (pick.schema !== undefined && !bodyTypesAsUnknown(pick.schema, componentSchemas));\n}\n\n/**\n * Accept or reject the override against the primary response, once, before any\n * success body is classified — the one check for the fields that depend on\n * the response, in the order `buildOperation` reports them: a `dataPath`\n * must reach an array in that body — in every variant of a union on the\n * way, and the same array in each (`dataPathProblem`, the walk that later\n * types the items, `resolveDataPathFromSchema`) — then an `endOfIteration`\n * must resolve in it to a field of the fitting type\n * (`bodyEndOfIterationProblem`). An override\n * that sets neither asks nothing of the response and is usable; its\n * parameters were checked before the response was read\n * (`resolveOverrideParams`). No primary response (no `responses`, no 2xx or\n * 3xx), a primary without a body (a 204, or a 3xx when no 2xx is\n * declared) and a primary whose schema describes nothing resolve nothing,\n * so an override that sets either field is rejected against them.\n */\nfunction decidePaginationOverride(\n  pagination: PaginationExtractionOptions,\n  primary: SuccessEntry | undefined,\n  componentSchemas?: Record<string, SchemaObject>,\n): PaginationOverrideDecision {\n  if (pagination.dataPath !== undefined) {\n    const problem = dataPathProblem(primary?.pick.schema, pagination.dataPath, componentSchemas);\n    if (problem !== undefined) return { usable: false, problem };\n  }\n  if (pagination.endOfIteration !== undefined) {\n    const problem = bodyEndOfIterationProblem(pagination.endOfIteration, primary?.pick.schema, componentSchemas);\n    if (problem !== undefined) return { usable: false, problem };\n  }\n  return { usable: true };\n}\n\n/**\n * The `components/responses` entry a response is written as a `$ref` to, or\n * undefined for an inline response. Only the outermost ref counts: it is the\n * name the operation uses, and the name a chain resolves through\n * (`resolveResponseRef`) stays the component's own business. The pointer is\n * matched whole and JSON Pointer escapes (RFC 6901 §4) undone, exactly as the\n * resolver does, so the name agrees with what it resolved.\n */\nfunction componentResponseNameOf(resp: ResponseObject | ReferenceObject): string | undefined {\n  if (!('$ref' in resp) || typeof resp.$ref !== 'string') return undefined;\n  const match = /^#\\/components\\/responses\\/(.+)$/.exec(resp.$ref);\n  return match?.[1].replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\n/**\n * The model name a response's inline body is shared under when the response\n * is written as a `$ref` into `components/responses`: the name\n * `resolveComponentResponseModelNames` settled on for the component, or\n * `componentResponseModelName` when no map was built. Undefined for a\n * response written inline, and for a ref no component answers — the\n * operation then names the body as it names an inline one, and the resolver\n * has already warned about the ref. The one answer for every place a\n * response can be written (workos/oagen#301): an explicit status code,\n * success or error, `default` and a `1XX`–`5XX` range read it alike, so a\n * component returned at a 404 by one operation and as `default` by another\n * names one model.\n */\nfunction sharedResponseModelName(\n  resp: ResponseObject | ReferenceObject,\n  ctx: ResponseTypingContext,\n): string | undefined {\n  const componentName = componentResponseNameOf(resp);\n  if (componentName === undefined) return undefined;\n  return ctx.componentResponseModelNames\n    ? ctx.componentResponseModelNames.get(componentName)\n    : componentResponseModelName(componentName);\n}\n\n/**\n * `<Component>Response`: the inline body of a response declared once under\n * `components/responses` and referenced from each operation that returns it.\n * It is named after the component, not the operation, so every referrer\n * shares one model (`PetFound` → `PetFoundResponse`) instead of minting a\n * `<Op>Response` copy each; the suffix is not doubled when the component is\n * already named `…Response`. Cleaned like an operationId-derived name, so\n * the stem (`componentResponseModelBase`) prefixes everything derived from\n * it — a list's `<Component>Item`, nested `<Component>Response…` models,\n * and the component's secondary bodies and headers\n * (`<Component><MediaType>Response`, `<Component><Header>`; see\n * `responseModelSite`).\n */\nfunction componentResponseModelName(componentName: string): string {\n  const base = toPascalCase(componentName);\n  return cleanSchemaName(base.endsWith('Response') ? base : base + 'Response');\n}\n\n/** What a component response's inline body is named, and every model name it mints under that name. */\ninterface ComponentResponseNaming {\n  name: string;\n  /** The root model and everything nested under it, envelope companions included; empty for a body without a schema. */\n  minted: readonly string[];\n}\n\n/**\n * The model name each component response's inline body is shared under,\n * decided once for the document: `componentResponseModelName`, stepped to the\n * first numbered form (`OwnerCardResponse2`, `…3`) under which neither it nor\n * any model the body mints — a nested object (`OwnerCardResponse2Detail`),\n * array items, union variants, envelope companions — is a name a component\n * schema (or a model a component field mints), an operation's own inline\n * success body (`operationBodyModelNames`) or an earlier component response\n * already owns: `OwnerCard` beside a schema `OwnerCardResponse`, or beside a\n * schema `OwnerCardResponse2Detail`, or beside an operation `ownerCard` whose\n * inline 200 is `OwnerCardResponse`, or beside a component response\n * `OwnerCardResponse`. A shared name of another shape would otherwise be\n * folded by the later merge, which compares field names, onto a model with\n * other field types, silently; and naming such a body per operation instead\n * would hand two shared bodies of one operation (`OwnerCard` at 200,\n * `NewOwner` at 201) the same `<Op>Response`. The names are read with the\n * extractor the operation will use, under the candidate name and under\n * every reading an operation can give the body — a list envelope unwrapped\n * for an iterator (`NotePageItem`) or kept as the wire shape\n * (`NotePageResponse`, `NotePageResponseData`), since which one an\n * operation takes (`iteratorSource`) is known only when it is read and two\n * operations returning the same body can differ — so the whole body moves\n * together and the reference and the models agree by\n * construction; a chain of refs is followed to the body silently, since the\n * operation declaring the ref reports a bad one when it reads it. A clash the\n * stem does not reach — a titled variant, named the same under any stem —\n * stops the stepping, and the merge passes settle it as for any operation\n * body. A component already named like its derived name\n * (`OwnerCardResponse` → `OwnerCardResponse`) keeps it ahead of one that\n * only derives it; the rest are decided in document order, so the outcome\n * never depends on which operation is read first. Every component ends up in\n * the map, so every operation that returns it shares the one model.\n */\nfunction resolveComponentResponseModelNames(\n  componentResponses: Record<string, Record<string, unknown>> | undefined,\n  takenModels: readonly Model[],\n  componentSchemas?: Record<string, SchemaObject>,\n  operationBodyNames: readonly string[] = [],\n): ReadonlyMap<string, ComponentResponseNaming> {\n  const taken = new Set([...takenModels.map((model) => model.name), ...operationBodyNames]);\n  const componentNames = Object.keys(componentResponses ?? {});\n  const exact = componentNames.filter((name) => componentResponseModelName(name) === name);\n  const ordered = [...exact, ...componentNames.filter((name) => !exact.includes(name))];\n  const names = new Map<string, ComponentResponseNaming>();\n  for (const componentName of ordered) {\n    const schema = componentResponseBodySchema(componentName, componentResponses ?? {});\n    const mintedUnder = (name: string): string[] => (schema ? bodyModelNames(schema, name, componentSchemas) : []);\n    const base = componentResponseModelName(componentName);\n    let name = base;\n    let minted = mintedUnder(name);\n    let previous: string[] | undefined;\n    // Unbounded on purpose: `taken` is finite and every step is a new\n    // numbered stem, so a free one is always reached; only a clash the stem\n    // does not reach (`stuck`) ends the search without one.\n    for (let n = 2; ; n++) {\n      const clashing = [name, ...minted].filter((candidate) => taken.has(candidate));\n      if (clashing.length === 0) break;\n      const stuck =\n        previous !== undefined && clashing.length === previous.length && clashing.every((c) => previous!.includes(c));\n      if (stuck) break;\n      previous = clashing;\n      name = numberedName(base, n);\n      minted = mintedUnder(name);\n    }\n    taken.add(name);\n    for (const minted_ of minted) taken.add(minted_);\n    names.set(componentName, { name, minted });\n  }\n  return names;\n}\n\n/**\n * Every model name an operation named from an `operationId` mints for its own\n * inline request and success bodies — the request body's `<Op>Request` and\n * everything under it, the primary response's `<Op>Response` and everything\n * under it, and each later status code's under the stem it moves to\n * (`<Op>Response201`, `stepSecondaryBody`), under every reading\n * (`bodyModelNames`) — the `operationId` being the one its models are named\n * by (`modelOperationIds`). A component response's body steps past these\n * names (`resolveComponentResponseModelNames`), so `card`'s inline 200 keeps\n * `CardResponse` and the body of a component `Card` is `CardResponse2`,\n * whatever the order of the paths (workos/oagen#424), while `card`'s inline\n * 201 beside another primary takes `CardResponse201` and nothing from the\n * component; and so does a path-derived prefix that extends an operation's\n * stem (`resolvePathModelBaseNames`), so `GET /create/pet/response/drafts`\n * beside `createPet` never names its response after the `drafts_get_response`\n * object nested in `createPet`'s (#627). The names are read as the\n * operation will settle them: an array body's items are settled against a\n * copy of the registry as it is seeded before any operation is read\n * (`typeInlineItems`), so beside a schema `CardItem` the items of `card`'s\n * inline array are reserved as `CardResponseItem`, the name the operation\n * takes, and a component `Card` whose body nests an `item` steps to\n * `CardResponse2` (`CardResponse2Item`) instead of minting a second\n * `CardResponseItem` of another shape. The primary is chosen by the rule\n * `extractResponses` chooses it by (`primaryResponseEntry`), a `$ref` among\n * the entries resolved to read it, and the request body by the rule\n * `extractRequestBody` picks its content by (`selectRequestBodyContent`), a\n * `$ref` into `components/requestBodies` resolved to read it, and typed\n * exactly as the operation will type it (`typePickedRequestBody`): an array\n * body's items are `<Op>Request` itself and nest `<Op>RequestFooPostRequest`,\n * which a response reading reserved as `<Op>RequestItem…` and so missed\n * (Greptile, #655). A 2xx or a\n * body schema written as a `$ref` mints under its component's name or not\n * at all, and an operation that names its models from its path steps past\n * the components itself (`resolvePathModelBaseNames`), so neither reserves\n * anything. Read silently (`rehearse`): the operation reports its bodies'\n * problems once, when it is built.\n */\nfunction operationBodyModelNames(\n  paths: Record<string, PathItem>,\n  modelOperationIds: ReadonlyMap<string, string | null>,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  componentResponses: Record<string, Record<string, unknown>> | undefined,\n  componentRequestBodies: Record<string, Record<string, unknown>> | undefined,\n  registry: ModelShapeRegistry,\n): string[] {\n  return rehearse(() => {\n    const names: string[] = [];\n    for (const [path, pathItem] of Object.entries(paths)) {\n      for (const method of HTTP_METHODS) {\n        const op = pathItem[method];\n        const key = `${method} ${path}`;\n        const operationId = modelOperationIds.has(key) ? modelOperationIds.get(key) : op?.operationId;\n        if (!op || !operationId) continue;\n        const contextName = operationIdModelName(operationId, 'Response');\n        const settle: ItemSettlement = { registry, operation: operationIdModelBase(operationId) };\n        // The request body, read as `collectOperationConstPrefixes` reads\n        // it: a `$ref` that resolves to nothing is left for buildOperation\n        // to report, and a schema that is itself a `$ref` mints nothing.\n        let requestBody: RequestBodyObject | undefined;\n        try {\n          requestBody = resolveRequestBodyRef(op.requestBody, componentRequestBodies, key);\n        } catch {\n          requestBody = undefined;\n        }\n        const selected = selectRequestBodyContent(requestBody);\n        if (selected) {\n          // Typed exactly as `extractRequestBody` will type it, under the id\n          // the models are named from: an array body's items are\n          // `<Op>Request` itself, where a response reading names them\n          // `<Op>RequestItem` and misses what they nest.\n          const requestModels: Model[] = [];\n          typePickedRequestBody(selected, { ...op, operationId }, '', requestModels, componentSchemas);\n          names.push(...requestModels.map((model) => model.name));\n        }\n        const entries = Object.entries(op.responses ?? {}).flatMap(([statusCode, response]) => {\n          const responseKey = classifyResponseKey(statusCode);\n          if (responseKey.kind !== 'status' || responseKey.code < 200 || responseKey.code >= 400) return [];\n          const code = responseKey.code;\n          // An entry that is not an object mints nothing; the operation\n          // warns about it once when it reads it (#617).\n          if (!isResponseEntry(response)) return [];\n          const resolved = resolveResponseRef<ResponseObject>(response, componentResponses, key, 'override', 'silent');\n          // A ref whose chain ends on a component that is no object is left\n          // out, as the operation leaves it out (#617).\n          if (resolved === undefined) return [];\n          return [{ code, inline: !('$ref' in response), pick: code < 300 ? primaryBodySchema(resolved) : {} }];\n        });\n        const primaryCode = primaryResponseEntry(entries, componentSchemas)?.code;\n        // A later body moves to the stem an earlier one of its shape took,\n        // else to its status code, in status order, as `stepSecondaryBody`\n        // moves it.\n        const stems = new Map<string, string>();\n        for (const { code, inline, pick } of [...entries].sort((a, b) => a.code - b.code)) {\n          if (!inline || !pick.schema) continue;\n          const minted = bodyModelNames(pick.schema, contextName, componentSchemas, settle);\n          if (code === primaryCode || !minted.some((name) => name.includes(contextName))) {\n            names.push(...minted);\n            continue;\n          }\n          const key = bodyShapeKey(pick.schema, contextName, componentSchemas);\n          const stem = stems.get(key) ?? `${contextName}${code}`;\n          stems.set(key, stem);\n          names.push(...minted.map((name) => name.replace(contextName, stem)));\n        }\n      }\n    }\n    return names;\n  });\n}\n\n/** The schema a component response's body is read from, through a chain of refs, silently; undefined without one. */\nfunction componentResponseBodySchema(\n  componentName: string,\n  componentResponses: Record<string, Record<string, unknown>>,\n): SchemaObject | undefined {\n  const component = componentResponses[componentName];\n  // A component that is not an object (`Bad: \"oops\"`) declares no body, and\n  // neither does one whose chain ends on such a component; a `$ref` to\n  // either is reported by the operation that writes it, as the malformed\n  // entry it is (#617).\n  if (!isResponseEntry(component)) return undefined;\n  const resolved = resolveResponseRef<ResponseObject>(\n    component as ResponseObject | ReferenceObject,\n    componentResponses,\n    `components/responses/${componentName}`,\n    'override',\n    'silent',\n  );\n  return resolved === undefined ? undefined : primaryBodySchema(resolved).schema;\n}\n\n/**\n * Every model name a response body mints under `contextName`, under every\n * reading an operation can give it (`BODY_READINGS`): the extractor's models\n * and its envelope companions' when a list envelope is unwrapped\n * (`NotePageItem`), and the plain model's nested models when it is kept as\n * the wire shape (`NotePageResponse`, `NotePageResponseData`). Which reading\n * each operation takes is decided when it is read (`iteratorSource`), and two\n * operations returning one component response can take different ones, so\n * both sets are reserved and the stem steps when either clashes. With\n * `settle`, each reading settles the body's array items against a copy of\n * the registry (`typeInlineItems`) — a fresh one per reading, since an\n * operation takes one reading only — so the names read are the ones the\n * operation will mint beside what the registry already holds, and the\n * registry itself is left as it was. Without it, the items are read as\n * `<Op>Item`, as written.\n */\nfunction bodyModelNames(\n  schema: SchemaObject,\n  contextName: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  settle?: ItemSettlement,\n): string[] {\n  const names = new Set<string>();\n  for (const reading of BODY_READINGS) {\n    const body = classifyAndExtractResponse(schema, contextName, componentSchemas, {\n      ...reading,\n      ...(settle && { settle: { registry: new Map(settle.registry), operation: settle.operation } }),\n    });\n    for (const model of body.inlineModels) names.add(model.name);\n    for (const companion of body.envelopeCompanions ?? []) for (const model of companion.models) names.add(model.name);\n  }\n  return [...names];\n}\n\n/**\n * A response body's shape under `contextName`, under every reading\n * (`BODY_READINGS`): its type and every model it mints, each by name and\n * `shapeFingerprint` — so the order of its fields, its documentation and\n * the model's own `deprecated` do not count, while a titled variant's name,\n * which names a model, does, and so does a field's own flag (a nested\n * object's `deprecated` sits on the field that wrote it too). Two later\n * bodies of one operation with one key are one body, named alike\n * (`stepSecondaryBody`) — a 202 identical to the 201 but for the flag\n * shares `CreatePetResponse201`, and the merge in `extractResponses` keeps\n * the 201's definition, live while either copy is (#630) — and the\n * reservation of a later body's names\n * (`operationBodyModelNames`) asks the same question of the same schema.\n * Read silently (`rehearse`): the body reports its problems once, when it is\n * read.\n */\nfunction bodyShapeKey(\n  schema: SchemaObject,\n  contextName: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): string {\n  return rehearse(() =>\n    JSON.stringify(\n      BODY_READINGS.map((reading) => {\n        const body = classifyAndExtractResponse(schema, contextName, componentSchemas, reading);\n        const models = body.inlineModels.map((model) => `${model.name} ${shapeFingerprint(model)}`).sort();\n        return [shapeWithEnumFlags(body.response), models];\n      }),\n    ),\n  );\n}\n\n/**\n * The stem every model derived from a component response starts with (see\n * operationIdModelBase for the argument): the body (`CardResponse`, or the\n * `CardResponse2` it steps to) and the models nested under it, an inline\n * body under another media type (`CardApplicationYamlResponse`) and an\n * object-shaped header (`CardXMeta`), the last two named from the shared\n * body name less its `Response` (`responseModelSite`), which starts with\n * this stem. Reserved by resolvePathModelBaseNames so no path-derived name\n * takes it.\n */\nfunction componentResponseModelBase(componentName: string): string {\n  return cleanSchemaName(toPascalCase(componentName).replace(/Response$/, ''));\n}\n\n/** Where an inline body declared for a secondary media type gets its name (`typeSecondaryContent`). */\ninterface ContentModelNaming {\n  /**\n   * The stem the media type's token follows (`ResponseModelSite.stem`): the\n   * operation's (`RenderPetCard`; with the response's label for a `default`\n   * or `1XX`–`3XX` range, `ListPetsDefault`), a component response's\n   * (`Card`), or an inline error entry's body name (`GetNoteError404`,\n   * `GetNoteError4Xx`).\n   */\n  base: string;\n  /**\n   * How the body is named and steps. `Response`: `<base><MediaType>Response`\n   * (`RenderPetCardTextHtmlResponse`), deferred as `content` — a success\n   * entry, a `default` or `1XX`–`3XX` range, and a component response\n   * wherever it is mounted. `Error`: `<base><MediaType>`\n   * (`GetNoteError404ApplicationYaml`), deferred as `error`, the kind the\n   * entry's JSON body steps by — an inline error entry, at a 4xx/5xx status\n   * code or in a `4XX`/`5XX` range.\n   */\n  role: 'Response' | 'Error';\n  /** A status code, the key of a `4XX`/`5XX` range (`4XX`), or the label of a `default` or `1XX`–`3XX` response (`Default`, `Success`). */\n  statusCode: number | string;\n  /**\n   * The model name a component response's body is shared under\n   * (`ResponseModelSite.component`), set for a component response: its\n   * bodies are component sites (`componentSite`), stepping by number on a\n   * clash.\n   */\n  component: string | undefined;\n  /**\n   * Whether the entry is a 2xx after the operation's primary, whose\n   * secondary bodies are named for its status code as its primary body is\n   * (`DeferredInlineType.later`, workos/oagen#538): `RenderPetCardTextHtmlResponse201`\n   * for the 201's `text/html` body beside the 200's\n   * `RenderPetCardTextHtmlResponse`. Never set for a component response.\n   */\n  later: boolean;\n}\n\n/**\n * Where the models a response declares besides its primary body — an inline\n * object under another media type, an object-shaped header — get their\n * names (`responseModelSite`). The primary body's own name is decided\n * elsewhere (`componentResponseModelName`, `deriveResponseName`,\n * `deriveErrorModelName`, `deriveFallbackResponseName`).\n */\ninterface ResponseModelSite {\n  /**\n   * The stem every such model starts with: the entry's body name less a\n   * trailing `Response` — the shared body name for a response written as a\n   * `$ref` into `components/responses` (`CardResponse` → `Card`), else the\n   * name the entry's own inline body is materialized under: `<Op>Response`\n   * for a success or redirect entry (`GetNote`), `<Op><Label>Response` for\n   * a `default` or `1XX`–`3XX` range (`ListPetsDefault`), and the error\n   * body's `<Op>Error<code>` for a 4xx/5xx status code or a `4XX`/`5XX`\n   * range (`GetNoteError404`, `GetNoteError4Xx`), which has no `Response`\n   * to drop.\n   */\n  stem: string;\n  /**\n   * The model name a component response's body is shared under\n   * (`componentModelName`), set for a component response: its models are\n   * named from the component alone, so the same names come out of every\n   * operation that returns it, at whatever status code or fallback key, and\n   * the shape registry shares one model among them; on a clash they step by\n   * number (`componentSite`), so the stepped name depends on the component\n   * alone too.\n   */\n  component: string | undefined;\n  /** What qualifies a header's models: `stem` for a component response, the service for an inline one; none without a service. */\n  headerParent: string | undefined;\n}\n\n/**\n * Decide where everything a response declares besides its primary body is\n * named from: the stem is the entry's body name less a trailing `Response`.\n * A response written as a `$ref` into `components/responses` is one thing\n * however many operations return it and whatever key each mounts it at, so\n * an inline object under another media type and an object-shaped header are\n * named from the model its body is shared under (`componentModelName`, see\n * `sharedResponseModelName`): `Card` + `ApplicationYaml` + `Response` for\n * the body under `application/yaml`, `Card` + `XMeta` for an `X-Meta`\n * header, and `CardResponse2…` when the body stepped to `CardResponse2` —\n * the same names from `GET /notes` at 200, from `GET /pets` at 404 and from\n * a `default` or `4XX` that refs it, so every operation shares one model of\n * each (workos/oagen#302). An inline response's are named from the name its\n * own body is materialized under (`bodyName`): `<Op>Response` for a success\n * or redirect entry and `<Op><Label>Response` for a `default` or `1XX`–`3XX`\n * range give `GetNoteApplicationYamlResponse` and\n * `ListPetsDefaultTextPlainResponse`; `<Op>Error<code>` for an error entry\n * — a 4xx/5xx status code or a `4XX`/`5XX` range — gives\n * `GetNoteError404ApplicationYaml` and `GetNoteError4XxApplicationYaml`,\n * with the status code or range key always in the name, as it is in the\n * JSON body's (workos/oagen#304); a header is the service plus header name\n * (`NotesXMeta`) whatever the entry. The names of either kind go through the\n * shape registry as before (`resolveDeferredInlineTypes`), so one a\n * component schema or another site owns with a shape it does not share\n * steps: an inline response's to the kind's next candidate, by status code,\n * operation or `Body`; a component's by number (`CardXMeta2`,\n * `CardApplicationYamlResponse2`), as its body steps to `CardResponse2`, so\n * the stepped name still depends on the component alone (`componentSite`).\n */\nfunction responseModelSite(\n  componentModelName: string | undefined,\n  bodyName: string,\n  ctx: ResponseTypingContext,\n): ResponseModelSite {\n  const stem = (componentModelName ?? bodyName).replace(/Response$/, '');\n  if (componentModelName !== undefined) return { stem, component: componentModelName, headerParent: stem };\n  return {\n    stem,\n    component: undefined,\n    headerParent: ctx.serviceName ? toPascalCase(ctx.serviceName) : undefined,\n  };\n}\n\n/**\n * The naming of an inline body under a secondary media type of one response\n * entry: the site's stem, then the entry's role — `Error` for an error\n * entry (a 4xx/5xx status code, a `4XX`/`5XX` range), `Response` otherwise\n * — except that a component response's bodies are `Response` at any key, as\n * its primary body is `<Component>Response` whether an operation mounts it\n * at 200, at 404 or in a `4XX` range; and, for the operation's own 2xx\n * entry after the primary (`later`), that its bodies are named for its\n * status code (workos/oagen#538), which a component's never are.\n */\nfunction contentModelNaming(\n  site: ResponseModelSite,\n  role: 'Response' | 'Error',\n  statusCode: number | string,\n  later = false,\n): ContentModelNaming {\n  return {\n    base: site.stem,\n    role: site.component === undefined ? role : 'Response',\n    statusCode,\n    component: site.component,\n    later: site.component === undefined && later,\n  };\n}\n\n/**\n * Read a response's `content` map into the media types it declares — in\n * document order and verbatim, parameters, vendor suffixes and wildcards\n * included — with a type for each. A media type is typed the way `response`\n * is when it is the only one declared, so the entry for `primaryContentType`\n * (the one the fixed-order pick read `primaryType` from) carries that very\n * TypeRef and every other entry goes through `typeSecondaryContent`, in\n * `mediaTypeNamingOrder`, so keys that derive one model name take it in one\n * order whatever the document's. Returns\n * `undefined` when the response declares no media type at all, so the caller\n * leaves both keys off.\n */\nfunction extractResponseContents(\n  content: Record<string, { schema?: SchemaObject }> | undefined,\n  primaryContentType: string | undefined,\n  primaryType: TypeRef | undefined,\n  naming: ContentModelNaming,\n  ctx: ResponseTypingContext,\n): { contentTypes: string[]; contents: ResponseContent[] } | undefined {\n  if (!content) return undefined;\n  const contentTypes = Object.keys(content);\n  if (contentTypes.length === 0) return undefined;\n  const contents = contentTypes.map((contentType): ResponseContent => ({\n    contentType,\n    type: { kind: 'primitive', type: 'unknown' },\n  }));\n  // Typed — so deferred, and named — in naming order; listed as written.\n  for (const contentType of mediaTypeNamingOrder(contentTypes)) {\n    const entry = contents[contentTypes.indexOf(contentType)];\n    entry.type =\n      primaryType !== undefined && contentType === primaryContentType\n        ? primaryType\n        : typeSecondaryContent(contentType, content[contentType]?.schema, naming, ctx, entry, contentTypes);\n  }\n  return { contentTypes, contents };\n}\n\n/**\n * Type a media type the fixed-order pick did not choose, exactly as it would\n * have been typed had it been the only one declared: `application/octet-stream`\n * and `application/pdf` are binary and the text and XML types are strings\n * whatever their schema says, any other media type is typed from its schema,\n * and one without a schema is `unknown`. The one addition is that an inline\n * object under such a media type is materialized — the primary pick's name\n * belongs to the primary body, so this one is named after its media type as\n * well, from the stem and role `naming` carries (`responseModelSite`,\n * `contentModelNaming`): `RenderPetCardTextHtmlResponse` for a success\n * entry, `CardApplicationYamlResponse` for a response shared through\n * `components/responses`, and `GetNoteError404ApplicationYaml` or\n * `GetNoteError4XxApplicationYaml` for an inline error entry, whose bodies\n * are deferred as `error` so they step by `Body` as the entry's JSON body\n * does — with the media type's fragment taken from its essence among its\n * `siblings` (the response's content keys), so a key keeps its model name\n * however it is spelled and two spellings of one essence side by side are\n * told apart by the parameters `oagen diff` compares, or by a `charset` when\n * nothing else tells them apart (`mediaTypeNameFragment`). That naming\n * waits for every primary model\n * (`resolveDeferredInlineTypes`), so a schema is deferred and `target.type`\n * — returned here as a placeholder — filled in then.\n */\nfunction typeSecondaryContent(\n  contentType: string,\n  schema: SchemaObject | undefined,\n  naming: ContentModelNaming,\n  ctx: ResponseTypingContext,\n  target: ResponseContent,\n  siblings: readonly string[],\n): TypeRef {\n  // Parameters and case do not change what a body is: `application/pdf;\n  // version=1.7` is as binary as `application/pdf`, `TEXT/PLAIN; charset=utf-8`\n  // as much a string as `text/plain` (`responseBodyReading`, the one\n  // classification the primary pick and `sentOnlyComponentNames` read too).\n  // The key itself stays as written.\n  const reading = responseBodyReading(contentType);\n  if (reading !== 'schema') return unreadResponseBodyType(reading);\n  if (!schema) return { kind: 'primitive', type: 'unknown' };\n  const fragment = mediaTypeNameFragment(contentType, siblings);\n  ctx.deferred.push({\n    kind: naming.role === 'Error' ? 'error' : 'content',\n    schema,\n    name: naming.role === 'Error' ? `${naming.base}${fragment}` : `${naming.base}${fragment}Response`,\n    statusCode: naming.statusCode,\n    operationQualifier: ctx.operationQualifier,\n    componentSchemas: ctx.componentSchemas,\n    targets: [target],\n    ...(naming.component !== undefined && { componentSite: naming.component }),\n    ...(naming.later && { later: true }),\n  });\n  return target.type;\n}\n\n/**\n * `<Op>DefaultResponse`, `<Op>SuccessResponse`: the inline body of a\n * `default` or `1XX`–`3XX` response, named like the primary body's\n * `<Op>Response` with the response's label (`Default`, or the word for its\n * range) in between. A `4XX` or `5XX` body is an error body and is named\n * `<Op>Error4Xx` instead (`deriveErrorModelName`, `isErrorStatusRange`).\n * Starts with the operation's stem, so `operationIdModelBase` reserves it\n * with the rest. A fallback written as a `$ref` into `components/responses`\n * is named after the component instead (`sharedResponseModelName`).\n */\nfunction deriveFallbackResponseName(op: OperationObject | undefined, pathModelBaseName: string, label: string): string {\n  if (op?.operationId) {\n    return operationIdModelName(op.operationId, `${label}Response`);\n  }\n  return `${pathModelBaseName}${label}Response`;\n}\n\n/**\n * The model name an inline error body is materialized under: the operation's\n * stem plus `Error<code>` — the status code (`GetPetError404`) or, for a\n * `4XX`/`5XX` range, the range key in PascalCase (`GetPetError4Xx`) — so two\n * operations' inline 404s never share one model, nor do two status codes or\n * a status code and a range of one operation. The one source of every\n * inline error body's name: the JSON body of a 4xx/5xx status code\n * (`extractResponses`), of a `4XX`/`5XX` range (`fillFallbackResponse`), and\n * through `responseModelSite` the bodies of their secondary media types\n * (`GetPetError404ApplicationYaml`), so the status code is in every one of\n * them (workos/oagen#304). Built by the rule `deriveResponseName` uses for\n * `<Op>Response`: `operationIdModelName` when the operation has an\n * `operationId`, else the path-derived prefix (`PetsByPetIdGetError404`),\n * which `resolvePathModelBaseNames` already keeps clear of every component\n * schema name.\n */\nfunction deriveErrorModelName(\n  op: OperationObject | undefined,\n  pathModelBaseName: string,\n  code: number | StatusRange,\n): string {\n  // A range key is cased as every identifier is (`toPascalCase`: `4XX` →\n  // `4Xx`), which is what the extractor makes of the name anyway; a status\n  // code is digits and stays as written.\n  const suffix = `Error${typeof code === 'number' ? code : toPascalCase(code)}`;\n  if (op?.operationId) {\n    return operationIdModelName(op.operationId, suffix);\n  }\n  return `${pathModelBaseName}${suffix}`;\n}\n\n/**\n * Where the fallback responses (`default`, `1XX`–`5XX`) of one operation\n * land while its responses are read, with what typing their bodies and\n * headers needs. An entry is attached as its key is read; a body with an\n * inline schema is deferred like a header's (`typeFallbackBody` for\n * `default` and `1XX`–`3XX`, `typeErrorBody` for `4XX` and `5XX`) and its\n * `type` filled in once every operation has been read.\n */\ninterface FallbackResponseSink {\n  op: OperationObject | undefined;\n  pathModelBaseName: string;\n  opLabel: string;\n  ctx: ResponseTypingContext;\n  defaultResponse?: DefaultResponse;\n  /** In document order. */\n  rangeResponses: RangeResponse[];\n}\n\n/**\n * Read a Responses Object key that is not a status code into `sink`:\n * `default` and a range are kept; an `x-` key is a specification extension\n * and carries no response; a key OpenAPI does not define (`error`, `6XX`,\n * `600` — see `classifyResponseKey`) is warned about, then ignored, instead\n * of being dropped silently. A status code never reaches here: the caller\n * reads it into `successResponses` or `errors`.\n */\nfunction readFallbackResponse(\n  responseKey: Exclude<ResponseKey, { kind: 'status' }>,\n  key: string,\n  resp: ResponseObject | ReferenceObject,\n  sink: FallbackResponseSink,\n): void {\n  if (responseKey.kind === 'extension') return;\n  if (responseKey.kind === 'unrecognized') {\n    warnUnrecognizedResponseKey(key, sink.opLabel);\n    return;\n  }\n  const range = responseKey.kind === 'range' ? responseKey.range : undefined;\n  if (range && sink.rangeResponses.some((entry) => entry.range === range)) {\n    // `4XX` and `4xx` side by side: JSON allows the pair, OpenAPI does not.\n    console.warn(`[oagen] Warning: Duplicate \"${range}\" response on ${sink.opLabel}; keeping the first`);\n    return;\n  }\n  // The bundler leaves `$ref: '#/components/responses/…'` in place, and a\n  // Reference Object has no `headers` or `content` of its own to read.\n  const resolved = resolveResponseRef<ResponseObject>(\n    resp,\n    sink.ctx.componentResponses,\n    `${key} response of ${sink.opLabel}`,\n    sink.ctx.refSiblingDescriptions,\n  );\n  // A ref whose chain ends on a component that is no object is left out,\n  // after the warning, as an inline entry that is no object is (#617).\n  if (resolved === undefined) return;\n  // A ref into `components/responses` names the body after the component,\n  // as it does at a status code, so every operation that returns the\n  // component — at any status, `default` or a range — shares one model; its\n  // secondary bodies and headers follow the same name (`responseModelSite`).\n  const componentModelName = sharedResponseModelName(resp, sink.ctx);\n  // The entry is filled in place: a deferred body's `type` lands on this\n  // very object once every operation has been read.\n  if (range) {\n    const entry: RangeResponse = { range };\n    fillFallbackResponse(entry, resolved, range, sink, componentModelName);\n    sink.rangeResponses.push(entry);\n  } else {\n    const entry: DefaultResponse = {};\n    fillFallbackResponse(entry, resolved, undefined, sink, componentModelName);\n    sink.defaultResponse = entry;\n  }\n}\n\n/**\n * Read the body, media types and headers of one fallback response onto\n * `entry`; a key is left off when absent (`range` is unset for `default`).\n * The body of a `default` or `1XX`–`3XX` response is named after the\n * operation and the response's label (`deriveFallbackResponseName`) and\n * deferred as a fallback body (`typeFallbackBody`); the body of a `4XX` or\n * `5XX` response is an error body (`isErrorStatusRange`), named\n * `<Op>Error4Xx` and deferred exactly as a 404's is (`deriveErrorModelName`,\n * `typeErrorBody`), with the range key where that has the status code, so\n * it steps by `Body` as that does (workos/oagen#304). A response that is a\n * `$ref` into `components/responses` is named after the component instead\n * (`componentModelName`, see `sharedResponseModelName`), the name every\n * operation returning the component shares, whichever kind of site it is.\n * The body is read before the headers so its deferred models are named\n * first, as they were when every fallback body was typed ahead of every\n * header. The media types are read exactly as a success entry's: every one\n * declared, the one `type` was read from sharing its TypeRef, each other\n * typed on its own — an inline object under `text/plain` of the `default`\n * response is `<Op>DefaultTextPlainResponse`, under `application/yaml` of a\n * `4XX` response `<Op>Error4XxApplicationYaml`. The secondary bodies and\n * headers of a response written as a `$ref` into `components/responses` are\n * named from the component's shared body name (`responseModelSite`), as an\n * explicit status code's are.\n */\nfunction fillFallbackResponse(\n  entry: DefaultResponse | RangeResponse,\n  resp: ResponseObject,\n  range: StatusRange | undefined,\n  sink: FallbackResponseSink,\n  componentModelName: string | undefined,\n): void {\n  const label = range === undefined ? 'Default' : STATUS_RANGE_LABELS[range];\n  // The key a `4XX`/`5XX` body is named and qualified by, as a 404's is by\n  // its status code; a `default` or `1XX`–`3XX` body is named by its label.\n  const errorRange = range !== undefined && isErrorStatusRange(range) ? range : undefined;\n  const operationName =\n    errorRange === undefined\n      ? deriveFallbackResponseName(sink.op, sink.pathModelBaseName, label)\n      : deriveErrorModelName(sink.op, sink.pathModelBaseName, errorRange);\n  const contextName = componentModelName ?? operationName;\n  const site = responseModelSite(componentModelName, operationName, sink.ctx);\n  const json = jsonResponseSchema(resp);\n  // Shared by reference with the deferred body, so the content entry of the\n  // media type `type` was read from can join it once it exists.\n  const targets: Array<{ type?: TypeRef }> = [entry];\n  if (json) {\n    entry.type =\n      errorRange === undefined\n        ? typeFallbackBody(json.schema, contextName, label, sink, targets, componentModelName)\n        : typeErrorBody(json.schema, contextName, errorRange, sink.ctx, targets, componentModelName);\n  }\n  const contents = extractResponseContents(\n    resp.content,\n    json?.contentType,\n    entry.type,\n    errorRange === undefined\n      ? contentModelNaming(site, 'Response', label)\n      : contentModelNaming(site, 'Error', errorRange),\n    sink.ctx,\n  );\n  if (contents) {\n    entry.contentTypes = contents.contentTypes;\n    entry.contents = contents.contents;\n    const own = contents.contents.find((content) => content.contentType === json?.contentType);\n    if (own) targets.push(own);\n  }\n  const headers = extractResponseHeaders(resp.headers, sink.opLabel, label, sink.ctx, site);\n  if (headers) entry.headers = headers;\n  // The response's own `description`, read as for a success or error entry —\n  // a sibling beside a `$ref` included only as `ctx.refSiblingDescriptions`\n  // reads it (kept in an OAS 3.1 document, dropped in a 3.0 one, whether or\n  // not the ref resolved), as the status-code loop below reads one.\n  const description = presentText(resp.description);\n  if (description) entry.description = description;\n}\n\n/**\n * Type a fallback body and materialize every model it names, under a name no\n * other model owns. A `$ref` is the referenced model. An inline schema is\n * deferred like a header's or a secondary body's: once every operation has\n * been read (`resolveDeferredInlineTypes`) it is extracted as if it were a\n * field named `contextName` of a parent with no name, through the extractor\n * every field goes through — so every shape a field can take (a nullable\n * object, an array or map of objects, `oneOf`/`anyOf` variants, an `allOf`\n * merge, nested objects) is materialized under the name `schemaToTypeRef`\n * references it by, by construction — and checked against the spec-wide\n * registry, so a component, or another operation's body, that happens to be\n * named like the fallback is never overwritten by `mergeInlineResponseModels`:\n * a clash moves the whole body to the next free name (`<Op>DefaultResponse2`,\n * `…3`), nested models and ref together. A body a `components/responses`\n * entry declares (`componentSite`) is named after the component\n * (`<Component>Response`) and shares the model of every other site that\n * returns the component, whatever its kind. List envelope and\n * resource-wrapper detection are skipped on purpose: a fallback body is not\n * what the SDK method returns, so it must not drive pagination. Returns the\n * placeholder the resolution replaces on `target`.\n */\nfunction typeFallbackBody(\n  schema: SchemaObject,\n  contextName: string,\n  label: string,\n  sink: FallbackResponseSink,\n  targets: Array<{ type?: TypeRef }>,\n  componentSite: string | undefined,\n): TypeRef {\n  if (schema.$ref) return schemaToTypeRef(schema, contextName);\n  sink.ctx.deferred.push({\n    kind: 'fallback',\n    schema,\n    name: contextName,\n    statusCode: label,\n    operationQualifier: sink.ctx.operationQualifier,\n    componentSchemas: sink.ctx.componentSchemas,\n    targets,\n    ...(componentSite !== undefined && { componentSite }),\n  });\n  return { kind: 'primitive', type: 'unknown' };\n}\n\n/**\n * Type an error response's JSON body and materialize every model it names,\n * under a name no other model owns (workos/oagen#236: `schemaToTypeRef` alone\n * named a model — `Error404` — that nothing created). A `$ref` is the\n * referenced model. An inline schema is deferred exactly like a fallback\n * body's (`typeFallbackBody`): once every operation has been read\n * (`resolveDeferredInlineTypes`) it is extracted as if it were a field named\n * `contextName` of a parent with no name, so every shape a field can take — a\n * plain or nullable object, an array or map of objects, `oneOf`/`anyOf`\n * variants (`GetPetError400`, `GetPetError400WithCode`,\n * `AuthGetPetError400`), an `allOf` merge with `$ref` branches, nested\n * objects (`GetPetError404Detail`) — is materialized under the name\n * `schemaToTypeRef` references it by, by construction, and checked against\n * the spec-wide registry: a name a component schema, a model nested in one\n * (`GetPet.error404` owns `GetPetError404`), a header or another operation's\n * body already owns with a shape it does not share moves the whole body to\n * the next free name (`GetPetError404Body`, `…Body2`), nested models and ref\n * together; a shape the owner shares (`ownerShares`) takes the name. A\n * titled variant that clashes (`Circle`) is\n * reserved and qualified (`CircleGetPetError400`), as under any deferred\n * kind. A body that is itself an inline enum, or an array of one, mints no\n * model and is promoted to `spec.enums` by `collectInlineEnumsFromOperations`.\n * A body a `components/responses` entry declares (`componentSite`) is named\n * after the component (`<Component>Response`) and steps by number\n * (`<Component>Response2`) rather than by `Body`, the way the same\n * component's body steps at a `default` or range site, so every site that\n * returns the component settles on one model. The body of a `4XX` or `5XX`\n * range comes through here too (`fillFallbackResponse`), under\n * `<Op>Error4Xx` with the range key as `code`, so it is named, stepped and\n * qualified exactly as a 404's body is; and so does an error entry's body\n * under a secondary media type (`typeSecondaryContent`), under\n * `<Op>Error<code><MediaType>`. List envelope and resource-wrapper\n * detection are skipped on purpose, as for a fallback body. Returns the\n * placeholder the resolution replaces on every target.\n */\nfunction typeErrorBody(\n  schema: SchemaObject,\n  contextName: string,\n  code: number | StatusRange,\n  ctx: ResponseTypingContext,\n  targets: Array<{ type?: TypeRef }>,\n  componentSite: string | undefined,\n): TypeRef {\n  if (schema.$ref) return schemaToTypeRef(schema, contextName);\n  ctx.deferred.push({\n    kind: 'error',\n    schema,\n    name: contextName,\n    statusCode: code,\n    operationQualifier: ctx.operationQualifier,\n    componentSchemas: ctx.componentSchemas,\n    targets,\n    ...(componentSite !== undefined && { componentSite }),\n  });\n  return { kind: 'primitive', type: 'unknown' };\n}\n\n/**\n * The fixed-order pick of a success response's body: the JSON schema when a\n * JSON media type is declared (`application/json` by essence, then `+json`);\n * else a binary (`BINARY_RESPONSE_MEDIA_TYPES`: `application/octet-stream`,\n * `application/pdf`) or text (`TEXT_RESPONSE_MEDIA_TYPES`: `text/plain`,\n * `text/html`, `text/xml`, `application/xml`) media type, typed as a string\n * without reading its schema — the classification `responseBodyReading`\n * shares with every secondary entry (`typeSecondaryContent`) and with the\n * sent/received walk (`sentOnlyComponentNames`), so a body under such a\n * media type reaches no component (#610); else the first media type that\n * declares a schema; else the first declared, which reads as `unknown`.\n * Media types are compared by essence (`application/pdf; foo=bar` is as\n * binary as `application/pdf`, `TEXT/PLAIN; charset=utf-8` as much a string\n * as `text/plain`) and `contentType` is the key as written.\n * `extractResponses` reads a 2xx body through this, and\n * `resolvePathModelBaseNames` asks the same question of a component\n * response, so the names it reserves are the ones the operation will mint,\n * whatever media type the body is declared under.\n */\nfunction primaryBodySchema(resp: ResponseObject): { contentType?: string; schema?: SchemaObject; type?: TypeRef } {\n  const json = jsonResponseSchema(resp);\n  if (json) return { contentType: json.contentType, schema: json.schema };\n  const content = resp.content;\n  if (!content) return {};\n  const keyWithEssence = (essence: string): string | undefined =>\n    Object.keys(content).find((contentType) => mediaTypeEssence(contentType) === essence);\n  const binaryKey = BINARY_RESPONSE_MEDIA_TYPES.map(keyWithEssence).find((key) => key !== undefined);\n  if (binaryKey) return { contentType: binaryKey, type: unreadResponseBodyType('binary') };\n  const textKey = TEXT_RESPONSE_MEDIA_TYPES.map(keyWithEssence).find((key) => key !== undefined);\n  if (textKey) return { contentType: textKey, type: unreadResponseBodyType('text') };\n  // The first media type that declares a schema; when none does, the first\n  // declared is the primary and reads as unknown.\n  const entries = Object.entries(content);\n  const first = entries.find(([, media]) => media?.schema) ?? entries[0];\n  return first ? { contentType: first[0], schema: first[1]?.schema } : {};\n}\n\n/**\n * The schema of a response's JSON body, with the media type it was declared\n * under as written: `application/json` first, else a `+json` media type\n * (`application/problem+json` is the usual shape of a `default` error),\n * matched by essence — parameters (`; charset=utf-8`) stripped, case folded.\n * Other media types type nothing, for an error entry as for a fallback.\n */\nfunction jsonResponseSchema(resp: ResponseObject): { contentType: string; schema: SchemaObject } | undefined {\n  const entries = Object.entries(resp.content ?? {}).filter(([, media]) => media?.schema);\n  // The one JSON rule requests and responses share (`isJsonMediaType`):\n  // `application/json` itself first, then any `+json` type.\n  const match =\n    entries.find(([mediaType]) => isPlainJsonMediaType(mediaType)) ??\n    entries.find(([mediaType]) => isJsonMediaType(mediaType));\n  return match && match[1].schema ? { contentType: match[0], schema: match[1].schema } : undefined;\n}\n\n/**\n * The type of a body the document does not describe:\n * `{ kind: 'primitive', type: 'unknown' }`. A 3xx entry's `type` is always\n * this; a 2xx entry's is this until a media-type rule types it; and an\n * operation's `response` is this when the operation declares no 2xx or 3xx\n * response at all — only `default`, ranges or errors, an empty `responses`\n * map, or no `responses` key — so an emitter never types a return value the\n * document does not describe. Each call returns a new object.\n */\nfunction undescribedBodyType(): TypeRef {\n  return { kind: 'primitive', type: 'unknown' };\n}\n\n/**\n * Read an operation's `responses` map: the primary body (`response` and the\n * paging fields), every 2xx/3xx entry (`successResponses`), the error\n * entries, the `default` and range entries, and the inline models all of\n * them mint. Every 2xx body's models are kept, merged by name: a later\n * body's model of a kept name resolves to the kept definition when the two\n * are the same shape but for the model's own `deprecated`\n * (`shapeFingerprint`), the kept definition — the primary's, its\n * references with it — going live when any copy is and documented as the\n * first live copy is, so a live 202 body identical to a deprecated 200\n * body types both as a live `Pet` carrying the 202's `description`, as a\n * deprecated 202 beside a live 200 does, and the model is deprecated only\n * when every copy is; and to the kept definition with a warning when they\n * differ in a field (#630).\n */\nfunction extractResponses(\n  responses: Record<string, ResponseObject> | undefined,\n  /** The Operation Object as the operation's model names read it (`buildOperation`'s `namingOp`). */\n  op: OperationObject | undefined,\n  pathModelBaseName: string,\n  /** The operation as diagnostics name it (`operationLabel`). */\n  opLabel: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  ctx: ResponseTypingContext = { operationQualifier: '', deferred: [] },\n  pagination: PaginationExtractionOptions = {},\n): {\n  response: TypeRef;\n  responseHeaders?: ResponseHeader[];\n  responseContentTypes?: string[];\n  responseContents?: ResponseContent[];\n  responseDescription?: string;\n  /** The status code of the entry `response` was read from; undefined when no 2xx/3xx is declared. */\n  responseStatusCode?: number;\n  successResponses?: SuccessResponse[];\n  errors: ErrorResponse[];\n  /** The `default` response, when the operation declares one. */\n  defaultResponse?: DefaultResponse;\n  /** The `1XX`–`5XX` range responses in declaration order, when the operation declares any. */\n  rangeResponses?: RangeResponse[];\n  inlineModels: Model[];\n  isPaginated: boolean;\n  dataPath?: string;\n  dataDescription?: string;\n  itemType?: TypeRef;\n  envelopeFields?: Field[];\n  endOfIteration?: PaginationEndOfIteration;\n  /** Element type of the array the override's `dataPath` names — a placeholder the settle decides when the walk crossed a pending reference (`deferDataPathItemType`; #608); unset when the override was rejected or names none. */\n  overrideItemType?: TypeRef;\n  /**\n   * Why the override cannot apply to the primary response — a `dataPath`\n   * that reaches no array in it, or an `endOfIteration` that resolves in it\n   * to no field of the fitting type — in the words `buildOperation` warns\n   * with (`decidePaginationOverride`); unset when it can, or when it sets\n   * neither field.\n   */\n  overrideProblem?: string;\n  envelopeCompanions?: EnvelopeCompanion[];\n  /** The primary body is a list envelope kept as a plain response model because nothing pages it (`ResponseExtractionResult.unpagedEnvelope`). */\n  unpagedEnvelope?: boolean;\n  /** Each 2xx entry's `type` a `components/responses` entry declares, by identity (`OperationExtractionResult.componentSites`). */\n  componentBodies: TypeRef[];\n} {\n  const errors: ErrorResponse[] = [];\n  const componentBodyTypes: TypeRef[] = [];\n  let response: TypeRef = undescribedBodyType();\n  let responseHeaders: ResponseHeader[] | undefined;\n  let responseContentTypes: string[] | undefined;\n  let responseContents: ResponseContent[] | undefined;\n  let responseDescription: string | undefined;\n  let inlineModels: Model[] = [];\n  let isPaginated = false;\n  let dataPath: string | undefined;\n  let dataDescription: string | undefined;\n  let itemType: TypeRef | undefined;\n  let envelopeFields: Field[] | undefined;\n  let endOfIteration: PaginationEndOfIteration | undefined;\n  let overrideItemType: TypeRef | undefined;\n  let envelopeCompanions: EnvelopeCompanion[] | undefined;\n  let unpagedEnvelope: boolean | undefined;\n\n  const allSuccessResponses: SuccessResponse[] = [];\n  // Every 2xx body's classification, by status code. The models of all of\n  // them are kept — `successResponses` references each — while the paging\n  // fields are read from the status chosen as primary once every status code\n  // has been read.\n  const bodyResults = new Map<number, ResponseExtractionResult>();\n  // The name an inline success or redirect body is materialized under\n  // (`<Op>Response`), whose stem names its secondary bodies (`RenderPetCard`\n  // + `TextHtml` + `Response`); an error entry's are named from its own\n  // `<Op>Error<code>` and a component response's from the component\n  // (`responseModelSite`).\n  const operationBodyName = deriveResponseName(op, pathModelBaseName);\n  const fallback: FallbackResponseSink = { op, pathModelBaseName, opLabel, ctx, rangeResponses: [] };\n  // Each classified body's schema, for resolving an overridden `dataPath`\n  // through the document when the IR cannot answer.\n  const bodySchemas = new Map<number, SchemaObject>();\n  // The context each 2xx body's models were named under — `<Op>Response`,\n  // or the component's shared name — the stem a later status code's body\n  // steps from (`stepSecondaryBody`), and whether it is a component's.\n  const bodyContexts = new Map<number, { context: string; component: boolean }>();\n\n  // A `responses` that is not an object — `responses: \"oops\"`, `7`, `null`,\n  // `[…]` — is no Responses Object, so no key could be read from it: it is\n  // warned about once and read as absent, as for an operation that declares\n  // none (#617).\n  if (responses !== undefined && !isResponsesObject(responses, opLabel)) responses = undefined;\n  // One pass over the map decides what the loop below reads, in document\n  // order. An entry that is not an object — `200: \"oops\"`, `null`, `7`,\n  // `true`, `[]` — is no Response Object and no Reference Object, so no\n  // branch below could read it: it is warned about once, naming the\n  // operation and the key, and left out, and the operation is read from its\n  // other entries (#617). Only a key a branch reads is checked: an `x-` key\n  // is an extension, which may hold anything, and a key OpenAPI does not\n  // define is reported on its own (`readFallbackResponse`), whatever it\n  // holds. Every 2xx, 3xx and error entry is then resolved once, here, and\n  // the loop reads it from `resolvedResponses`. The bundler leaves `$ref:\n  // '#/components/responses/…'` in place, and a Reference Object has no\n  // `headers` or `content` of its own to read, so the ref is resolved before\n  // either is — its sibling `description` read by `ctx.refSiblingDescriptions`,\n  // an unresolvable one warned about once, and one whose chain ends on a\n  // component that is no object (`Gone: []`) left out exactly as the inline\n  // entry is, after the same warning (`resolveResponseRef`). Only a status\n  // code one of the branches below reads is resolved here: `default` and a\n  // `2XX` range are resolved as they are read (`readFallbackResponse`), an\n  // `x-` extension is left as written, as nothing here reads it, and a 1xx\n  // is read as written too.\n  const entries: Array<[string, ResponseObject]> = [];\n  const resolvedResponses = new Map<string, ResponseObject>();\n  for (const [key, raw] of Object.entries(responses ?? {})) {\n    const responseKey = classifyResponseKey(key);\n    if (responseKey.kind !== 'extension' && responseKey.kind !== 'unrecognized') {\n      const site = `${key} response of ${opLabel}`;\n      if (!isResponseEntry(raw, site)) continue;\n      if (responseKey.kind === 'status' && responseKey.code >= 200) {\n        const resolved = resolveResponseRef<ResponseObject>(\n          raw,\n          ctx.componentResponses,\n          site,\n          ctx.refSiblingDescriptions,\n        );\n        if (resolved === undefined) continue;\n        resolvedResponses.set(key, resolved);\n      }\n    }\n    entries.push([key, raw]);\n  }\n\n  // The override is accepted or rejected once, before any body is\n  // classified, against the primary response — the entry\n  // `Operation.response` will describe, chosen here by the one rule\n  // (`primaryResponseEntry`) — and every success body below is read with\n  // that one decision (`overrideDecision`): a rejected override is handed\n  // to no body, so a secondary 2xx is read exactly as detection reads it,\n  // never kept as the wrapper the dropped override would have selected; an\n  // accepted one applies to each body its `dataPath` reaches an array in.\n  const successEntries: SuccessEntry[] = [...resolvedResponses.entries()]\n    .map(([statusCode, resp]) => ({ code: Number(statusCode), resp }))\n    .filter(({ code }) => code < 400)\n    .map(({ code, resp }) => ({ code, pick: code < 300 ? primaryBodySchema(resp) : {} }));\n  const primaryEntry = primaryResponseEntry(successEntries, componentSchemas);\n  const overrideDecision = decidePaginationOverride(pagination, primaryEntry, componentSchemas);\n  // The one reason the override cannot apply to the response, decided\n  // before any body is read. It is reported from every exit below: an\n  // operation without `responses` declares nothing an override could name\n  // either.\n  const overrideProblem = pagination.disabled ? undefined : overrideDecision.problem;\n\n  // An operation without a `responses` object declares no success response,\n  // so `response` is `unknown` here as it is for one that declares only\n  // `default`, ranges or errors.\n  if (!responses)\n    return { response, errors, inlineModels, isPaginated, overrideProblem, componentBodies: componentBodyTypes };\n\n  for (const [statusCode, rawResponse] of entries) {\n    // The whole key decides what it names (`classifyResponseKey`): `default`\n    // and `1XX`–`5XX` are routed to their own fields, an `x-` extension is\n    // skipped, and a key OpenAPI does not define (`6XX`, `600`) is warned\n    // about and ignored. Only a three-digit 100–599 key reaches the branches\n    // below, so no digit-prefixed key is ever read as a status code.\n    const responseKey = classifyResponseKey(statusCode);\n    if (responseKey.kind !== 'status') {\n      readFallbackResponse(responseKey, statusCode, rawResponse, fallback);\n      continue;\n    }\n    const code = responseKey.code;\n    // Resolved above for every status code a branch below reads; a 1xx is\n    // read as written.\n    const resp = resolvedResponses.get(statusCode) ?? rawResponse;\n    // Set when the response came from a component: its inline body is then\n    // named after the component, shared by every operation that returns it —\n    // at a status code, as `default` or in a range (`readFallbackResponse`\n    // asks the same helper).\n    const componentModelName = code >= 200 ? sharedResponseModelName(rawResponse, ctx) : undefined;\n    // The name this entry's own inline body is materialized under: the error\n    // body's `<Op>Error<code>` for a 4xx/5xx, else `<Op>Response`.\n    const bodyName = code >= 400 ? deriveErrorModelName(op, pathModelBaseName, code) : operationBodyName;\n    // Where this response's secondary bodies and headers are named from: the\n    // component's shared body name for a `$ref` into `components/responses`,\n    // else `bodyName`.\n    const site = responseModelSite(componentModelName, bodyName, ctx);\n    // Headers belong to the status code they are declared on, success or\n    // error alike: `Location` on a 201/302, `Retry-After` on a 429. A 1xx\n    // response, which no branch below keeps, declares none worth\n    // materializing models for; a fallback response's were read above.\n    const headers = code >= 200 ? extractResponseHeaders(resp.headers, opLabel, code, ctx, site) : undefined;\n    // The response's own `description`, success or error alike. Blank text\n    // counts as absent, the way an operation's summary is read, and the key is\n    // only added when there is something to keep. A `$ref` into\n    // `components/responses` was resolved above, so the component's own\n    // `description` is read; a sibling written next to the `$ref` wins in an\n    // OAS 3.1 document and is ignored in 3.0 (`ctx.refSiblingDescriptions`).\n    const description = presentText(resp.description);\n\n    if (code >= 200 && code < 300) {\n      let extractedType: TypeRef = undescribedBodyType();\n      // The body schema to classify: the JSON one when a JSON media type is\n      // declared (`application/json` by essence, then `+json`), else — past\n      // the binary and text media types typed below without a schema — the\n      // first other media type that declares one. Either way it goes through\n      // `classifyAndExtractResponse`, so its inline models are created and\n      // the response never references a model the parser did not emit.\n      // The fixed-order pick (`primaryBodySchema`): `primaryContentType` is\n      // the media type `extractedType` is read from, as written, so its\n      // `contents` entry can share that TypeRef instead of re-deriving it.\n      const pick = primaryBodySchema(resp);\n      const bodySchema = pick.schema;\n      const primaryContentType = pick.contentType;\n      if (pick.type) extractedType = pick.type;\n      if (bodySchema) {\n        const contextName = componentModelName ?? deriveResponseName(op, pathModelBaseName);\n        // The override as decided above (`overrideDecision`): a rejected one\n        // is handed to no body, and an accepted one hands its `dataPath` to\n        // classification where it reaches an array in this body — the\n        // primary's by the decision itself, a secondary's on its own shape\n        // — so a secondary the path does not reach is read as detection\n        // reads it.\n        const dataPathOverride =\n          pagination.disabled ||\n          !overrideDecision.usable ||\n          pagination.dataPath === undefined ||\n          dataPathProblem(bodySchema, pagination.dataPath, componentSchemas) !== undefined\n            ? undefined\n            : pagination.dataPath;\n        // When only the override can drive an iterator, a body it will not\n        // page — every body once the override is rejected, or a secondary\n        // its `dataPath` reaches no array in, or its `endOfIteration`\n        // resolves in to no field of the fitting type — keeps a list\n        // envelope as a plain response model, as under `disabled`, rather\n        // than unwrapped for an iterator that never comes.\n        const paginationDisabled =\n          pagination.disabled === true ||\n          (pagination.overrideOnly === true &&\n            (!overrideDecision.usable ||\n              (pagination.dataPath !== undefined && dataPathOverride === undefined) ||\n              (pagination.endOfIteration !== undefined &&\n                bodyEndOfIterationProblem(pagination.endOfIteration, bodySchema, componentSchemas) !== undefined)));\n        // The primary body's array items are settled against the registry\n        // (`typeInlineItems`); the dry run that reads a component response's\n        // names (`bodyModelNames`) passes none and mints nothing into it, and\n        // the one that reads an operation's own (`operationBodyModelNames`)\n        // settles against a copy.\n        const result = classifyAndExtractResponse(bodySchema, contextName, componentSchemas, {\n          paginationDisabled,\n          dataPathOverride,\n          ...(ctx.registry && { settle: { registry: ctx.registry, operation: ctx.operationQualifier } }),\n        });\n        extractedType = result.response;\n        bodyResults.set(code, result);\n        bodySchemas.set(code, bodySchema);\n        bodyContexts.set(code, { context: contextName, component: componentModelName !== undefined });\n      }\n      // A 2xx after the primary names its secondary bodies for its status\n      // code, as `stepSecondaryBody` names its primary body (#538); the\n      // primary's keep the bare `<Op><MediaType>Response`.\n      const contents = extractResponseContents(\n        resp.content,\n        primaryContentType,\n        extractedType,\n        contentModelNaming(site, 'Response', code, code !== primaryEntry?.code),\n        ctx,\n      );\n      // The component's body wherever it is mounted, so an enum it is steps\n      // by number, never by this status code (`collectInlineEnumsFromOperations`).\n      if (componentModelName !== undefined) componentBodyTypes.push(extractedType);\n      allSuccessResponses.push({\n        statusCode: code,\n        type: extractedType,\n        ...(headers && { headers }),\n        ...(description && { description }),\n        ...contents,\n      });\n    } else if (code >= 300 && code < 400) {\n      // 3xx redirects — include so emitter can detect redirect endpoints. The\n      // type is not read from any media type, so every content entry is typed\n      // on its own. A component's JSON body is still the component's body\n      // (`CardResponse`), deferred as at a `404` or `default` site, so every\n      // operation that returns the component shares one model of it whatever\n      // the key it mounts it at; the entry's own type stays `unknown`.\n      const json = componentModelName === undefined ? undefined : jsonResponseSchema(resp);\n      const targets: Array<{ type?: TypeRef }> = [];\n      const contents = extractResponseContents(\n        resp.content,\n        json?.contentType,\n        json && typeFallbackBody(json.schema, componentModelName!, String(code), fallback, targets, componentModelName),\n        contentModelNaming(site, 'Response', code),\n        ctx,\n      );\n      const own = json && contents?.contents.find((content) => content.contentType === json.contentType);\n      if (own) targets.push(own);\n      allSuccessResponses.push({\n        statusCode: code,\n        type: undescribedBodyType(),\n        ...(headers && { headers }),\n        ...(description && { description }),\n        ...contents,\n      });\n    } else if (code >= 400) {\n      const json = jsonResponseSchema(resp);\n      // The entry is filled in place: an inline body is materialized under an\n      // operation-qualified name — or the component's, for a `$ref` response\n      // — once every operation has been read, and its `type` lands on this\n      // very object (`typeErrorBody`). The content entry the body was read\n      // from shares that TypeRef, so it joins the targets below.\n      const entry: ErrorResponse = { statusCode: code, type: undefined };\n      const targets: Array<{ type?: TypeRef }> = [entry];\n      const type = json\n        ? typeErrorBody(json.schema, componentModelName ?? bodyName, code, ctx, targets, componentModelName)\n        : undefined;\n      entry.type = type;\n      const contents = extractResponseContents(\n        resp.content,\n        json?.contentType,\n        type,\n        contentModelNaming(site, 'Error', code),\n        ctx,\n      );\n      // An error's `type` is its JSON body by definition — `application/json`,\n      // else a `+json` media type (`jsonResponseSchema`) — so the lists are kept\n      // only when they say something `type` does not: another media type, a\n      // JSON body `type` could not be read from, or a JSON media type that is\n      // not the plain `application/json` a reader would otherwise assume. The\n      // common lone `application/json` with a schema keeps its shape.\n      const beyondType =\n        contents &&\n        (json?.contentType !== 'application/json' || contents.contents.some((content) => content.type !== type))\n          ? contents\n          : undefined;\n      if (headers) entry.headers = headers;\n      if (description) entry.description = description;\n      if (beyondType) {\n        entry.contentTypes = beyondType.contentTypes;\n        entry.contents = beyondType.contents;\n        const own = beyondType.contents.find((content) => content.contentType === json?.contentType);\n        if (own) targets.push(own);\n      }\n      errors.push(entry);\n    }\n  }\n\n  // The primary response was chosen before any body was read\n  // (`primaryResponseEntry`: the lowest 2xx with a typed body, else the\n  // lowest declared code — the rule the override was decided by), and its\n  // entry is read here: type, headers, media types, description. With no\n  // 2xx or 3xx at all, `response` stays `unknown` — the type of a body the\n  // document does not describe — with no headers, description or media\n  // types; a `2XX` range or `default` body is never promoted into it.\n  const primaryStatus = primaryEntry?.code;\n  const primary = allSuccessResponses.find((entry) => entry.statusCode === primaryStatus);\n  if (primary) {\n    response = primary.type;\n    responseHeaders = primary.headers;\n    responseContentTypes = primary.contentTypes;\n    responseContents = primary.contents;\n    // The operation-level description is the primary response's — the same\n    // entry `response` and `responseHeaders` come from.\n    responseDescription = primary.description;\n  }\n\n  // The paging fields describe `response`, so they come from the primary's\n  // body — not from whichever 2xx body happened to be read last.\n  const primaryBody = primaryStatus === undefined ? undefined : bodyResults.get(primaryStatus);\n  if (primaryBody) {\n    isPaginated = primaryBody.isPaginated;\n    dataPath = primaryBody.dataPath;\n    dataDescription = primaryBody.dataDescription;\n    itemType = primaryBody.itemType;\n    envelopeFields = primaryBody.envelopeFields;\n    endOfIteration = primaryBody.endOfIteration;\n    envelopeCompanions = primaryBody.envelopeCompanions;\n    unpagedEnvelope = primaryBody.unpagedEnvelope;\n  }\n\n  // Keep the models of every 2xx body: `successResponses` references each of\n  // them, so keeping only one body's would leave the others dangling. Every\n  // status derives the same `<Op>Response` context name, so the primary's\n  // definition — the one `response` points at — goes first; the other bodies\n  // follow in status order, each named for itself before it is merged\n  // (`stepSecondaryBody`): the operation's own body moves to its own stem —\n  // the one an earlier status code's body of its shape took, else\n  // `<Op>Response<code>`, then a number — whatever the kept bodies hold, so\n  // its `successResponses` entry keeps the shape its status code declared\n  // under a name no other status code's body decides. A model of a later\n  // body the kept one shares (`shapeFingerprint`: the model's own\n  // `deprecated` apart) resolves to the kept definition silently — the kept\n  // definition going live when only the flag tells the two apart, as a live\n  // copy owns a shared name across operations in the merge passes, so a\n  // live 202 body identical to a deprecated 200 body keeps a live `Pet`\n  // with the 200's references and the 202's documentation (`description`,\n  // `externalDocs`, extensions: the first live copy's in status order, as\n  // the merge passes keep a live copy's definition), deprecating either\n  // copy leaves no trace, and the model is deprecated only when every copy\n  // is (#630); only a clash on a model the stem does not name — a field more,\n  // a field's own flag, a limit — is still resolved to the kept definition,\n  // with a warning. The\n  // models only a dropped copy referenced go with it (`reachedModels`): the\n  // primary's models are all read — `response`, the paging fields and their\n  // companions — while another status is read only through its\n  // `successResponses` entry, so of its models only those the entry's type\n  // still reaches are kept, rather than kept with nothing referencing them.\n  const bodiesByPrimacy = [...bodyResults.entries()].sort(([a], [b]) => {\n    if (a === primaryStatus) return -1;\n    if (b === primaryStatus) return 1;\n    return a - b;\n  });\n  const keptByName = new Map<string, { model: Model; status: number }>();\n  // The stem each of the operation's own later bodies settled on, by its\n  // shape (`bodyShapeKey`), so a later body of that shape settles on it too;\n  // and the name each component response's body takes, which such a body\n  // steps past whichever operation returning the component is read first.\n  const settledStems = new Map<string, string>();\n  const componentBodies = new Set(ctx.componentResponseModelNames?.values());\n  for (const [status, result] of bodiesByPrimacy) {\n    if (status !== primaryStatus) {\n      const { context, component } = bodyContexts.get(status)!;\n      const key = component ? undefined : bodyShapeKey(bodySchemas.get(status)!, context, componentSchemas);\n      const ownBody = key === undefined ? undefined : { stems: settledStems, key, componentBodies };\n      stepSecondaryBody(result, context, status, keptByName, ctx.registry, ownBody);\n    }\n    const reached =\n      status === primaryStatus ? undefined : reachedModels(result.response, result.inlineModels, keptByName);\n    for (const model of result.inlineModels) {\n      if (reached && !reached.has(model)) continue;\n      const kept = keptByName.get(model.name);\n      if (!kept) {\n        keptByName.set(model.name, { model, status });\n        inlineModels.push(model);\n      } else if (shapeFingerprint(kept.model) !== shapeFingerprint(model)) {\n        console.warn(\n          `[oagen] Warning: Inline model \"${model.name}\" from the ${status} response has different fields than the ${kept.status} response's — using the ${kept.status} response's`,\n        );\n      } else if (kept.model.deprecated && !model.deprecated) {\n        // Identical but for the model's own flag: the shared model is live\n        // while any copy is (#630). The kept definition stays — its\n        // references with it: an explicit `$ref` the primary wrote where\n        // this body nests an inline object of the same name, repointed\n        // apart by the merge passes — and goes live, documented as this\n        // first live copy is (`takeModelDocumentation`), as the merge passes\n        // keep a live copy's definition across operations; the live copy's\n        // object never replaces it.\n        delete kept.model.deprecated;\n        takeModelDocumentation(kept.model, model);\n      }\n    }\n  }\n\n  // An explicit `dataPath` the decision accepted names the array the\n  // iterator yields from, so its element type — not the wrapper — must\n  // become `itemType`. It is resolved against the primary body, whose models\n  // (companions included) are the ones retained above, so the item type it\n  // selects always has its model — or is a placeholder until the settle, when\n  // the path crosses a pending reference (`resolveOverrideItemType`). An\n  // accepted `dataPath` reached an array in the body the decision was made\n  // against, which is this one: a body an array is reached in is typed, and\n  // the lowest typed 2xx is the primary.\n  const primarySchema = primaryStatus === undefined ? undefined : bodySchemas.get(primaryStatus);\n  if (\n    primaryStatus !== undefined &&\n    primaryBody &&\n    primarySchema &&\n    pagination.dataPath !== undefined &&\n    !pagination.disabled &&\n    overrideDecision.usable\n  ) {\n    const resolved = resolveOverrideItemType(\n      primaryBody,\n      primarySchema,\n      deriveResponseName(op, pathModelBaseName),\n      pagination.dataPath,\n      pagination.componentModels ?? [],\n      componentSchemas,\n      ctx.registry && { registry: ctx.registry, operation: ctx.operationQualifier },\n    );\n    if (resolved) {\n      overrideItemType = resolved.itemType;\n      for (const model of resolved.inlineModels) {\n        if (keptByName.has(model.name)) continue;\n        keptByName.set(model.name, { model, status: primaryStatus });\n        inlineModels.push(model);\n      }\n    }\n  }\n\n  const successResponses = allSuccessResponses.length > 1 ? allSuccessResponses : undefined;\n\n  return {\n    response,\n    responseHeaders,\n    responseContentTypes,\n    responseContents,\n    responseDescription,\n    responseStatusCode: primaryStatus,\n    successResponses,\n    errors,\n    defaultResponse: fallback.defaultResponse,\n    rangeResponses: fallback.rangeResponses.length > 0 ? fallback.rangeResponses : undefined,\n    inlineModels,\n    isPaginated,\n    dataPath,\n    dataDescription,\n    itemType,\n    envelopeFields,\n    endOfIteration,\n    overrideItemType,\n    overrideProblem,\n    envelopeCompanions,\n    unpagedEnvelope,\n    componentBodies: componentBodyTypes,\n  };\n}\n\n/**\n * The models of `own` — one 2xx body's — that `root`, the body's type, still\n * reaches once every name an earlier status kept resolves to that status's\n * model. A reached name's own model is in the set whatever the name's\n * fate, so a copy another status's model replaces is still compared with it\n * (and warned about when the shapes differ); the walk then continues through\n * the model the name resolves to — the kept one when there is one, since its\n * fields are what the reference reads — so a model only the replaced copy\n * referenced is not reached. A name no body minted is a component's and is\n * not followed; every own model of a name is read, so two of one name would\n * both be reached.\n */\nfunction reachedModels(root: TypeRef, own: readonly Model[], kept: ReadonlyMap<string, { model: Model }>): Set<Model> {\n  const ownByName = new Map<string, Model[]>();\n  for (const model of own) {\n    const models = ownByName.get(model.name);\n    if (models) models.push(model);\n    else ownByName.set(model.name, [model]);\n  }\n  const reached = new Set<Model>();\n  const visited = new Set<string>();\n  const queue = collectModelRefs(root);\n  while (queue.length > 0) {\n    const name = queue.pop()!;\n    if (visited.has(name)) continue;\n    visited.add(name);\n    const ownModels = ownByName.get(name) ?? [];\n    for (const model of ownModels) reached.add(model);\n    const resolved = kept.get(name)?.model ?? ownModels[0];\n    if (!resolved) continue;\n    for (const field of resolved.fields) queue.push(...collectModelRefs(field.type));\n  }\n  return reached;\n}\n\n/**\n * Name a later status code's body for itself before its models are merged with\n * the kept ones (workos/oagen#435). The operation's own body (`ownBody` given)\n * was read under the primary's context, `<Op>Response`, and always moves off\n * it, whatever the primary or an earlier status code holds: to the stem an\n * earlier status code settled on for a body of its shape (`bodyShapeKey`), so a\n * 202 identical to the 201 shares `CreatePetResponse201`; else to its status\n * code (`CreatePetResponse201`), then a number (`CreatePetResponse2`, `…3`, …),\n * the chain the entry's secondary media-type bodies step through too\n * (`deferredNamingStem`, `later`: `CreatePetApplicationYamlResponse201`), a\n * candidate being taken when no name it would give is kept under another\n * shape (`shapeFingerprint`: the kept model's own `deprecated` apart, so a\n * copy identical but for the flag takes the name and the caller folds it\n * onto the kept definition, live while any copy is, #630), or owned in the\n * spec-wide registry by a component\n * or another operation, under a shape the owner does not share\n * (`ownerShares`), nor is a component response's body,\n * whichever operation returning it is read first (`CardResponse3` for `card`'s\n * 201 past a component `Card` at `CardResponse2` when a schema owns\n * `CardResponse201`). So no edit to the primary renames it: a 201 identical to\n * the 200 is `CreatePetResponse201` beside `CreatePetResponse`, and a field\n * added to either is an additive change to that one's model, never a move\n * between the two. Two bodies keep the names they were read under unless one of\n * them clashes: a component response's (`ownBody` absent), which is the\n * component's wherever it is mounted, and an array body or a list envelope\n * unwrapped to its items, whose items were settled against the registry as they\n * were read (`typeInlineItems`). Every model the body reaches that its context\n * names moves with it (`CreatePetResponse201Owner`), and so does every inline\n * enum those models and the entry's type carry (`CreatePetResponse201Status`,\n * `CreatePetResponse201OwnerRole`), so each is named under the model it sits\n * in; a model the context does not name (a settled item, `CreatePetItem`; a\n * titled variant) keeps its name, and so does a `$ref` to a component enum,\n * which carries no values. The entry's type and the models' fields are\n * rewritten in place, so the `contents` entry that shares the type follows.\n * Only references the body itself minted are repointed — by identity, never by\n * name alone: an explicit `$ref` to a same-named component\n * (`isComponentModelRef`) and a reference an `allOf` merge copied from another\n * component's field (`isInheritedModelRef`) stay as written, the filter the\n * merge passes hand the same rewriters. Returns whether anything moved: nothing\n * does for a body with no model its context names, nor for one of the two kept\n * bodies above when none of its names clashes; a clash on a model the context\n * does not name is then reported by the caller as before.\n */\nfunction stepSecondaryBody(\n  result: ResponseExtractionResult,\n  context: string,\n  status: number,\n  kept: ReadonlyMap<string, { model: Model; status: number }>,\n  registry: InlineModelRegistry | undefined,\n  /**\n   * Set for the operation's own body, absent for a component's: the stem\n   * each of its earlier later bodies settled on, by shape (`bodyShapeKey`;\n   * `key` is this body's), and the name each component response's body takes.\n   */\n  ownBody?: { stems: Map<string, string>; key: string; componentBodies: ReadonlySet<string> },\n): boolean {\n  const clashes = (model: Model, name: string): boolean => {\n    // A component response's body was named before any operation is read\n    // (`resolveComponentResponseModelNames`), so the operation's own body\n    // steps past it whether or not an operation returning it came first.\n    if (ownBody?.componentBodies.has(name)) return true;\n    // A kept model's shape is read with its own `deprecated` apart: a copy\n    // identical to it but for the flag is folded onto the kept definition by\n    // the caller (#630), not stepped past.\n    const keptModel = kept.get(name)?.model;\n    if (keptModel && shapeFingerprint(keptModel) !== shapeFingerprint(model)) return true;\n    const owner = registry?.get(name);\n    return owner !== undefined && !ownerShares(owner, model, modelFingerprint(model));\n  };\n  // Reached through the body's own models, not the kept ones: the body\n  // keeps its root once it steps, so everything under that root is its.\n  const own = reachedModels(result.response, result.inlineModels, new Map());\n  // A name the context names carries it: as a prefix (the root, a nested\n  // object `…Owner`, a nested variant `…Shape`, a field's enum `…Status`),\n  // as a suffix (a const-named variant, `Square…` — `deriveModelName`) or in\n  // between (a const-named nested variant, `Square…Shape`); it moves by that\n  // one occurrence. A settled item (`<Op>Item`) and a titled variant do not\n  // carry it.\n  const namedByContext = (name: string): boolean => name.includes(context);\n  const movedTo = (name: string, stem: string): string => name.replace(context, stem);\n  const named = [...own].filter((model) => namedByContext(model.name));\n  const root = result.response.kind === 'nullable' ? result.response.inner : result.response;\n  const always = ownBody !== undefined && root.kind !== 'array';\n  if (named.length === 0 || (!always && !named.some((model) => clashes(model, model.name)))) return false;\n\n  // A body of an earlier one's shape takes that one's stem as it stands:\n  // moved under it, it gives the very models that body keeps there.\n  const earlier = always ? ownBody?.stems.get(ownBody.key) : undefined;\n  const under = (stem: string): Map<Model, string> => new Map(named.map((model) => [model, movedTo(model.name, stem)]));\n  let stem = earlier ?? `${context}${status}`;\n  let names = under(stem);\n  if (earlier === undefined) {\n    // Unbounded on purpose: the kept names and the registry are finite and\n    // every step is a new number, so a free stem is always reached.\n    for (let n = 2; [...names].some(([model, name]) => clashes(model, name)); n++) {\n      names = under((stem = numberedName(context, n)));\n    }\n    if (always) ownBody?.stems.set(ownBody.key, stem);\n  }\n\n  // Only a reference the body itself minted moves with it, by the\n  // reference's identity rather than its name: an explicit `$ref` to a\n  // same-named component (`isComponentModelRef`) and a reference an `allOf`\n  // merge copied from another component's field (`isInheritedModelRef`)\n  // stay as written, so `original: { $ref: CreatePetResponseOwner }` beside\n  // an inline `owner` of that name keeps naming the component.\n  const admit = (ref: ModelRef): boolean => !isComponentModelRef(ref) && !isInheritedModelRef(ref);\n  // An inline enum carries its values on the reference, which a `$ref` to a\n  // component enum does not. Every one is found before any is renamed, so a\n  // reference two fields share moves once.\n  const enums = new Set<EnumRef>();\n  for (const ref of [result.response, ...named.flatMap(collectModelTypeRefs)]) {\n    walkTypeRef(ref, {\n      enum: (enumRef) => void (enumRef.values && namedByContext(enumRef.name) && enums.add(enumRef)),\n    });\n  }\n\n  // Every reference moves through the one rewriter every rename site uses\n  // (`renameTypeRefModels`, `renameModelRefs`), under the identity filter\n  // above, so a union's `discriminator.mapping` follows the variant it\n  // belongs to and never keeps naming the model that moved, and a `$ref`\n  // left in place keeps its mapping entry.\n  const byOldName = new Map([...names].map(([model, name]) => [model.name, name]));\n  renameTypeRefModels(result.response, byOldName, admit);\n  for (const model of own) renameModelRefs(model, byOldName, admit);\n  for (const [model, name] of names) model.name = name;\n  for (const enumRef of enums) enumRef.name = movedTo(enumRef.name, stem);\n  return true;\n}\n\n/**\n * Shared with the inline-model merge passes, which decide whether two\n * same-named inline models are the same shape but for `deprecated` by it.\n */\nexport { modelFingerprint };\n","import type {\n  Constraints,\n  EnumRef,\n  Extensions,\n  ExternalDocs,\n  Model,\n  ModelRef,\n  Field,\n  TypeRef,\n  UnionType,\n} from '../ir/types.js';\nimport { collectModelRefs, collectModelTypeRefs, renameTypeRefModels, walkTypeRef } from '../ir/types.js';\nimport { toPascalCase, stripListItemMarkers, singularize } from '../utils/naming.js';\nimport type { SchemaObject } from './schemas.js';\nimport {\n  buildFieldFromSchema,\n  classifyInlineSchema,\n  componentPropertyLedger,\n  admits,\n  componentSchemaOf,\n  componentUnionDispatches,\n  documentComponentSchemas,\n  declaredComponentProperty,\n  nonObjectVariantContexts,\n  unionAxesOf,\n  wrapperDiscriminatorOf,\n  constraintsEntry,\n  deprecatedEntry,\n  extractConstraints,\n  isComponentModelRef,\n  markComponentModelRef,\n  arraySchemaOf,\n  declaresNull,\n  derivedCopy,\n  isInlineObjectSchema,\n  isNullSchema,\n  nullableAxisBranch,\n  unwrapNullableField,\n  unwrapNullableSchema,\n  withWrapperDeprecation,\n  withWrapperDocs,\n  nameInlineVariantEntries,\n  nameInlineVariants,\n  resolveSchemaName,\n  sourceDeclaration,\n  titleMappedVariantNames,\n  variantMemberSchemas,\n  foldSiblingProperties,\n  foldedVariantOrigin,\n} from './schemas.js';\nimport { externalDocsEntry, readExternalDocs } from './external-docs.js';\nimport { SCHEMA_CONSUMED_EXTENSIONS, extensionsOf, schemaExtensionsEntry } from './extensions.js';\nimport { copyInlineEnumMeta, shapeWithEnumFlags } from './enum-members.js';\nimport { readDiscriminator } from './union-shape.js';\nimport { pathItemRefTarget, resolveComponentRef } from './path-item-refs.js';\nimport {\n  carryDeferredMappingEntries,\n  componentKeyOf,\n  isPendingSchemaRef,\n  markPendingSchemaRef,\n  pendingSiteLimitsOf,\n  recordPendingSiteLimits,\n  schemaRefTarget,\n  schemaRefTokens,\n} from './schema-refs.js';\nimport {\n  isIgnoredHeaderParameter,\n  isIgnoredResponseHeader,\n  parameterTyping,\n  type ParameterObject,\n  type SchemaOrContent,\n} from './operations.js';\nimport { classifyResponseKey } from './responses.js';\nimport { responseBodyReading } from './body-media-types.js';\nimport { foldHeaderName, parameterKey, type ParameterLocation } from '../ir/parameter-key.js';\n\n/**\n * Whether `baseName` already carries `cleanParent` as its leading part and\n * adds something after it (`PetOwner` or `PetsItem` under `Pet`), so that\n * qualifying it would only double the parent (`PetPetOwner`). A name that is\n * the parent's own (`Reply` under `Reply`, `Pet` under `Pet`) adds nothing\n * and is not one: it is qualified like any other field's, never left as the\n * name the component holds (workos/oagen#621). The one test for every\n * inline name minted under a parent — a model's (`qualifyInlineModelName`)\n * and an enum's (`inlineEnumName`, `mintedInlineNameEntries`).\n */\nexport function extendsParentName(baseName: string, cleanParent: string): boolean {\n  return baseName.length > cleanParent.length && baseName.startsWith(cleanParent);\n}\n\n/**\n * Qualify an inline model name with the parent schema name.\n * If `parentName` is provided and the field name doesn't already start with\n * the parent and add something after it (`extendsParentName`: Pet + PetOwner\n * → PetOwner), the result is `${parentName}${PascalField}` with the trailing\n * word singularized (e.g., Connection + Domains → ConnectionDomain). A field\n * named like its parent is qualified too — Reply + Reply → ReplyReply, as\n * Reply + Replies names its items on its own (beside each other the field\n * holds ReplyReply and the items step to ReplyRepliesItem) — never left as\n * the parent's own name, which the component holds (workos/oagen#621).\n */\nexport function qualifyInlineModelName(baseName: string, parentName?: string): string {\n  if (!parentName) return baseName;\n  // Strip ListItem/ByExternalId markers from parent name so inline model names\n  // are clean, for response models as much as component ones.\n  // e.g., ConnectionListItem + Domains → Connection + Domain = ConnectionDomain\n  const cleanParent = stripListItemMarkers(parentName);\n  if (extendsParentName(baseName, cleanParent)) return baseName;\n  // Singularize the trailing PascalCase word of the combined name.\n  // Split baseName into leading words + trailing word, singularize trailing.\n  const trailingMatch = baseName.match(/^(.*?)([A-Z][a-z]*)$/);\n  if (trailingMatch) {\n    const [, prefix, trailingWord] = trailingMatch;\n    const singular = singularize(trailingWord);\n    return `${cleanParent}${prefix}${singular}`;\n  }\n  return `${cleanParent}${baseName}`;\n}\n\n/**\n * The inline model or enum names `schemaToTypeRef` would mint for `schema`\n * typed under `contextName` with `parentModelName`; empty when it mints none\n * (a `$ref`, a primitive, an array or map of those). Mirrors the naming\n * branches of `schemaToTypeRef`: an inline object in any form it recognises\n * (`properties`, an `allOf` with object members) takes\n * `qualifyInlineModelName`; a `oneOf`/`anyOf` mints one model per inline\n * object variant, named exactly as the union references them\n * (`nameInlineVariants`: `DrawingLayer`, `DrawingLayerWithOpacity`, or\n * `CircleDrawingLayer` when every variant is titled); an inline enum, or a\n * `oneOf` of string consts that collapses into one, takes the parent-prefixed\n * enum name, which is never singularized; an array or map claims whatever its\n * items or values would.\n */\nexport function mintedInlineNames(\n  contextName: string,\n  schema: SchemaObject,\n  parentModelName: string | undefined,\n): string[] {\n  return mintedInlineNameEntries(contextName, schema, parentModelName).map((entry) => entry.name);\n}\n\n/**\n * An inline name a schema mints, and whether it is context-free: a\n * title-mapped variant's title (`nameInlineVariantEntries`) is the same\n * whatever field, array or map the union sits under, where every other\n * inline name embeds the context it is typed under.\n */\nexport interface MintedInlineName {\n  name: string;\n  contextFree: boolean;\n  /** The variant schema a union variant's name was minted for; `reservedInlineNames` compares shapes through it. */\n  schema?: SchemaObject;\n}\n\n/**\n * The merged `allOf` schemas a deep walk (`mintedInlineNameEntries`) is\n * inside, re-entering their own properties as `materializeMergedAllOf`\n * does. One reached again is the same conjunction built once more\n * (`combinedDeclarations`), for which the extractor builds nothing\n * (workos/oagen#566), so the walk mints nothing for it either. Keyed as\n * `materializingMergedAllOf` is, by the declaration a schema stands for\n * (`sourceDeclaration`), so a merge under a nullable wrapper is met once\n * however often the wrapper is stripped. Empty between walks.\n */\nconst mintingMergedAllOf = new Set<SchemaObject>();\n\n/**\n * `mintedInlineNames`, also telling for each name whether it is context-free.\n * `reserved` are the names the schema's unions must step around\n * (`nameInlineVariantEntries`), as `schemaToTypeRef` receives them for the\n * same schema (`reservedNames`); the sibling-reservation readers leave it\n * unset and read the names in isolation, while `nonObjectVariantContexts`\n * passes a variant's own set so the names it records are the ones taken.\n * `deep` follows each inline model's name with everything its own\n * properties mint under it (`mintedChildNameEntries`), so the names are the\n * whole tree the extractor builds — a merge the walk is already inside\n * minting nothing more (`mintingMergedAllOf`), as the extractor builds\n * nothing for it: `nonObjectVariantContexts` reads them so, and the sibling\n * readers read the top level only.\n */\nexport function mintedInlineNameEntries(\n  contextName: string,\n  schema: SchemaObject,\n  parentModelName: string | undefined,\n  reserved?: ReadonlySet<string>,\n  deep = false,\n): MintedInlineName[] {\n  const s = unwrapNullableSchema(schema);\n  // Dispatch on the one classification `schemaToTypeRef` uses, so the names\n  // predicted here are the names it mints.\n  const kind = classifyInlineSchema(s);\n  if (kind === 'ref') return [];\n  const base = toPascalCase(contextName);\n  const withChildren = (entry: MintedInlineName, properties: SchemaObject['properties']): MintedInlineName[] =>\n    deep ? [entry, ...mintedChildNameEntries(properties, entry.name, entry.contextFree)] : [entry];\n  const modelName = (properties?: SchemaObject['properties']): MintedInlineName[] =>\n    withChildren({ name: qualifyInlineModelName(base, parentModelName), contextFree: false }, properties);\n  const enumName = (): MintedInlineName[] => {\n    const cleanParent = parentModelName ? stripListItemMarkers(parentModelName) : undefined;\n    return [\n      {\n        name: cleanParent && !extendsParentName(base, cleanParent) ? `${cleanParent}${base}` : base,\n        contextFree: false,\n      },\n    ];\n  };\n  if (kind === 'allOf' && s.allOf) {\n    // The one reading `schemaToTypeRef` makes of an `allOf` (`readInlineAllOf`).\n    const reading = readInlineAllOf(s.allOf, s);\n    if (reading === 'unwrapped') {\n      return mintedInlineNameEntries(contextName, annotatedTypingMember(s), parentModelName, reserved, deep);\n    }\n    if (reading !== 'merged') return [];\n    if (!deep) return modelName();\n    // The merged model's own properties, as `materializeMergedAllOf` re-enters\n    // them: a `$ref` member's stay its component's, unless an inline member\n    // declares the property too and the two conjoin. A merge already on the\n    // path of this walk mints nothing more, as the extractor types it as the\n    // model it is building and builds nothing for the re-entry (#566).\n    const declaration = sourceDeclaration(s);\n    if (mintingMergedAllOf.has(declaration)) return [];\n    mintingMergedAllOf.add(declaration);\n    try {\n      const own = mergeAllOfMembers(s, documentComponentSchemas()).properties.filter((p) => p.origin === null);\n      return modelName(Object.fromEntries(own.map((p) => [p.name, p.schema])));\n    } finally {\n      mintingMergedAllOf.delete(declaration);\n    }\n  }\n  const variants = kind === 'union' ? (s.oneOf ?? s.anyOf) : undefined;\n  if (variants) {\n    const nonNull = variants.filter((v) => !isNullSchema(v));\n    if (nonNull.length >= 2 && nonNull.every((v) => typeof v.const === 'string')) return enumName();\n    const variantEntries = nameInlineVariantEntries(s, modelName()[0]!.name, reserved);\n    // Every other variant mints under the context `nonObjectVariantContexts`\n    // gives it (read here without siblings but with the object variants'\n    // names): `<context>_item` / `<context>_value` for an array or map, the\n    // context itself or `<context>_variant_<n>` for a nested union, a nullable\n    // object, an `allOf` or an inline enum — stepping around the names the\n    // entry reserves — so a sibling that would take one of those names steps\n    // around it. Read `deep`, they are the names the decision already read\n    // under that context (`VariantContext.minted`).\n    const objectVariantNames = new Map([...variantEntries].map(([variant, entry]) => [variant, entry.name]));\n    const others = [\n      ...nonObjectVariantContexts(contextName, nonNull, undefined, parentModelName, objectVariantNames, reserved),\n    ].flatMap(([variant, entry]) =>\n      deep\n        ? entry.minted\n        : mintedInlineNameEntries(entry.context, unwrapNullableSchema(variant), parentModelName, entry.reserved),\n    );\n    return [\n      ...[...variantEntries].flatMap(([variant, entry]) =>\n        withChildren({ ...entry, schema: variant }, variant.properties),\n      ),\n      ...others,\n    ];\n  }\n  if (kind === 'const') return [];\n  if (kind === 'enum') return (s.enum ?? []).filter((v) => v !== null).length >= 2 ? enumName() : [];\n  if (kind === 'array' && s.items) {\n    return mintedInlineNameEntries(contextName, s.items, parentModelName, reserved, deep);\n  }\n  if (kind === 'object') return modelName(s.properties);\n  if (kind === 'map') {\n    const value = mapValueSchema(s);\n    return value ? mintedInlineNameEntries(contextName, value, parentModelName, reserved, deep) : [];\n  }\n  return [];\n}\n\n/**\n * Everything the properties of the inline model `modelName` mint under it, at\n * any depth (`mintedInlineNameEntries`, `deep`), each property read in\n * isolation: the models its extraction builds below it. The properties of a\n * kept title's model (`contextFree`) are named from the title, so what they\n * mint is context-free too.\n */\nexport function mintedChildNameEntries(\n  properties: SchemaObject['properties'],\n  modelName: string,\n  contextFree = false,\n): MintedInlineName[] {\n  return Object.entries(properties ?? {}).flatMap(([property, schema]) =>\n    schema\n      ? mintedInlineNameEntries(property, schema, modelName, undefined, true).map((child) =>\n          contextFree ? { ...child, contextFree } : child,\n        )\n      : [],\n  );\n}\n\n/**\n * The inline names the other properties of an object mint\n * (`mintedInlineNameEntries`) which a `oneOf`/`anyOf` under `fieldName` must\n * not give one of its variants (`nameInlineVariants`): beside a\n * `shape_with_side` object, the `{ side }` variant of `shape` cannot become\n * `DrawingShapeWithSide`. Every context-dependent sibling name is reserved.\n * A context-free name — a title-mapped variant's title — names one shape\n * wherever it appears, so it is shared, not reserved, when this field gives\n * the same title a variant of the identical shape (`schemaShapeKey`:\n * documentation keywords ignored, property names verbatim — the rule array\n * items already use to share a singular sibling's model); a sibling giving\n * the same title a different shape, or one this field does not use, reserves\n * it, so this union's variant falls back to its context-qualified name. Each\n * sibling's names are read in isolation, without the reservations that\n * sibling would itself apply, so the set depends on sibling names and content\n * only, two unions beside each other cannot chase each other's names, and\n * the shape test is symmetric: when `Circle` means `{ radius }` on one side\n * and `{ diameter }` on the other, both fall back (`CircleDrawingShape`,\n * `CircleDrawingMarker`) and neither keeps the bare `Circle`. Empty without a\n * sibling set, as for a request body or response that is itself a union.\n *\n * Siblings are the one case decided here. A title two unions at different\n * depths of one root give different shapes — `shape` and `marker.shape` —\n * is decided before any union is named (`markContestedTitles`): such a\n * variant never keeps its title, so by the time its union is named the\n * title is not among the context-free names on either side.\n */\nexport function reservedInlineNames(\n  fieldName: string,\n  siblings: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n): ReadonlySet<string> {\n  const reserved = new Set<string>();\n  if (!siblings) return reserved;\n\n  // The shape this field gives each title it would keep, in isolation.\n  const ownShapes = new Map<string, string[]>();\n  const fieldSchema = siblings.get(fieldName);\n  if (fieldSchema) {\n    for (const own of mintedInlineNameEntries(fieldName, fieldSchema, parentModelName)) {\n      if (!own.contextFree || !own.schema) continue;\n      ownShapes.set(own.name, [...(ownShapes.get(own.name) ?? []), schemaShapeKey(own.schema)]);\n    }\n  }\n\n  for (const [siblingName, siblingSchema] of siblings) {\n    if (siblingName === fieldName) continue;\n    for (const minted of mintedInlineNameEntries(siblingName, siblingSchema, parentModelName)) {\n      if (!minted.contextFree) {\n        reserved.add(minted.name);\n        continue;\n      }\n      const shapes = ownShapes.get(minted.name);\n      const siblingShape = minted.schema ? schemaShapeKey(minted.schema) : undefined;\n      const identical = shapes !== undefined && siblingShape !== undefined && shapes.every((s) => s === siblingShape);\n      if (!identical) reserved.add(minted.name);\n    }\n  }\n  return reserved;\n}\n\n/**\n * Documentation keywords that do not shape a model; ignored by\n * `schemaShapeKey` at a schema's own level. `deprecated` is not one of them:\n * a deprecated copy never shares a live model's name, and a `const` member\n * deprecated on one side only makes a different enum, so `deprecated: true`\n * is shape at every level (a `false` is dropped, like `nullable: false`).\n */\nconst DOC_KEYWORDS = new Set(['description', 'title', 'example', 'examples', 'summary', 'externalDocs']);\n/** Keywords whose value maps NAMES (not keywords) to schemas: names are kept verbatim, values recurse as schemas. */\nconst NAMED_SCHEMA_MAPS = new Set(['properties', 'patternProperties', 'dependentSchemas', '$defs', 'definitions']);\n/** Keywords whose value is a single schema. */\nconst SCHEMA_KEYWORDS = new Set([\n  'items',\n  'additionalProperties',\n  'additionalItems',\n  'contains',\n  'propertyNames',\n  'not',\n  'if',\n  'then',\n  'else',\n  'unevaluatedProperties',\n  'unevaluatedItems',\n]);\n/** Keywords whose value is an ordered list of schemas. */\nconst SCHEMA_LIST_KEYWORDS = new Set(['allOf', 'oneOf', 'anyOf', 'prefixItems']);\n/** Keywords whose list value is a set: compared order-insensitively. */\nconst UNORDERED_LIST_KEYWORDS = new Set(['required', 'type']);\n\n/**\n * A canonical rendering of a schema's shape, for deciding whether two inline\n * schemas describe the same model: every structural keyword (`type`,\n * `properties`, `required`, `items`, `additionalProperties`,\n * `patternProperties`, `allOf`/`oneOf`/`anyOf`, `enum`, `const`, `format`,\n * `nullable`, ...) recursively, with keywords sorted and the `required` and\n * `type` lists order-insensitive. Documentation keywords (`description`,\n * `title`, `example`, `examples`, `summary`, `externalDocs`, `deprecated`)\n * and vendor extensions (`x-*`) are ignored, and so is `nullable: false`,\n * which the nullable unwrap leaves behind — but only where they are a\n * schema's own keywords. Inside `properties`, `patternProperties`,\n * `dependentSchemas`, `dependentRequired` and `$defs` the keys are property\n * names, kept verbatim: a field named `description` or `title` is part of the\n * shape. Enum, const and default values are compared as plain data, in\n * order, as the IR keeps them.\n */\nexport function schemaShapeKey(schema: SchemaObject): string {\n  const isRecord = (value: unknown): value is Record<string, unknown> =>\n    typeof value === 'object' && value !== null && !Array.isArray(value);\n  // Plain data (enum members, const, default): sorted keys, nothing stripped.\n  const dataKey = (value: unknown): unknown => {\n    if (Array.isArray(value)) return value.map(dataKey);\n    if (!isRecord(value)) return value;\n    const out: Record<string, unknown> = {};\n    for (const key of Object.keys(value).sort()) out[key] = dataKey(value[key]);\n    return out;\n  };\n  const schemaKey = (value: unknown): unknown => {\n    if (!isRecord(value)) return value; // boolean schemas such as `additionalProperties: true`\n    const out: Record<string, unknown> = {};\n    for (const keyword of Object.keys(value).sort()) {\n      const v = value[keyword];\n      if (DOC_KEYWORDS.has(keyword) || keyword.startsWith('x-')) continue;\n      if (keyword === 'nullable' && v === false) continue;\n      if (keyword === 'deprecated' && v !== true) continue;\n      if (NAMED_SCHEMA_MAPS.has(keyword) && isRecord(v)) {\n        const named: Record<string, unknown> = {};\n        for (const name of Object.keys(v).sort()) named[name] = schemaKey(v[name]);\n        out[keyword] = named;\n      } else if (keyword === 'dependentRequired' && isRecord(v)) {\n        const named: Record<string, unknown> = {};\n        for (const name of Object.keys(v).sort()) {\n          const names = v[name];\n          named[name] = Array.isArray(names) ? names.map(String).sort() : dataKey(names);\n        }\n        out[keyword] = named;\n      } else if (SCHEMA_KEYWORDS.has(keyword)) {\n        out[keyword] = schemaKey(v);\n      } else if (SCHEMA_LIST_KEYWORDS.has(keyword) && Array.isArray(v)) {\n        out[keyword] = v.map(schemaKey);\n      } else if (UNORDERED_LIST_KEYWORDS.has(keyword) && Array.isArray(v)) {\n        out[keyword] = v.map(String).sort();\n      } else {\n        out[keyword] = dataKey(v);\n      }\n    }\n    return out;\n  };\n  return JSON.stringify(schemaKey(schema));\n}\n\n/** Field properties that only document a field — its extensions included — or say where it comes from (`inheritedFrom`, the base a component's field is taken from; #591); two shapes that differ in these alone are one shape. */\nconst FIELD_DOC_KEYS: ReadonlySet<string> = new Set([\n  'name',\n  'description',\n  'externalDocs',\n  'example',\n  'examples',\n  'extensions',\n  'inheritedFrom',\n]);\n/** Model properties that only document a model — its description, link and extensions — the part of `MODEL_IDENTITY_KEYS` a fold reads from the copy it keeps (`takeModelDocumentation`). */\nconst MODEL_DOC_KEYS = ['description', 'externalDocs', 'extensions'] as const satisfies readonly (keyof Model)[];\n/** Model properties outside its shape: the name, its documentation (`MODEL_DOC_KEYS`), its provenance (`bases`, the components a composed component is built on; #591), and the fields (fingerprinted on their own). */\nconst MODEL_IDENTITY_KEYS: ReadonlySet<string> = new Set(['name', ...MODEL_DOC_KEYS, 'bases', 'fields']);\n\n/**\n * Give `into` the documentation of `from` — every `MODEL_DOC_KEYS` property,\n * one `from` lacks removed — leaving its name, fields, flag, structure and\n * references as they are. What the within-operation merge does to the kept\n * definition when a later copy identical but for the model's own\n * `deprecated` is live (`extractResponses`, #630): the shared model is then\n * documented as that live copy is, as the merge passes keep a live copy's\n * definition whole across operations (`settleSharedNames`), so a description\n * written for the deprecated copy never documents a model that is not.\n */\nexport function takeModelDocumentation(into: Model, from: Model): void {\n  for (const key of MODEL_DOC_KEYS) {\n    if (from[key] === undefined) delete into[key];\n    else Object.assign(into, { [key]: from[key] });\n  }\n}\n/** Model properties `modelStructureKey` reads with the reading options — the named-union parts, whose model references are read under `readModelName`. */\nconst MODEL_STRUCTURE_KEYS: ReadonlySet<string> = new Set(['variants', 'compositionKind', 'discriminator']);\n/** Model properties outside `modelPropertiesKey`: the identity, the fields and the union structure, each read on its own. */\nconst MODEL_PROPERTY_KEYS_OMITTED: ReadonlySet<string> = new Set([...MODEL_IDENTITY_KEYS, ...MODEL_STRUCTURE_KEYS]);\n/** `MODEL_PROPERTY_KEYS_OMITTED` and the model's own `deprecated`, which `modelPropertiesAdmit` reads on its own (`flagAdmits`); every other property is compared verbatim. */\nconst MODEL_ADMIT_KEYS: ReadonlySet<string> = new Set([...MODEL_PROPERTY_KEYS_OMITTED, 'deprecated']);\n\n/**\n * Shape of a model, independent of field order, name and documentation:\n * every field's name, type, requiredness, limits, default and access flags,\n * plus the model's own limits, type parameters, variants and discriminator.\n * Types are read through `shapeWithEnumFlags`, so an inline enum's per-value\n * deprecation counts as its values do. Two schemas share a model only when\n * this agrees, so a body that repeats another's fields with a different\n * `minLength` or `minProperties`, or an enum member deprecated on one side\n * only, keeps its own model and its own limits. `schemaShapeKey` is the same\n * question asked of a schema before any model is built; this is asked of the\n * models, so two built by different paths (an ordinary object and a union\n * variant) compare the same way (`warnOnVariantNameClash`, the shape\n * registry in `materializeInlineSchema`, the response merge).\n */\nexport function modelFingerprint(model: Model): string {\n  const fields = model.fields\n    .map((field) => `${field.name}:${fieldShapeKey(field)}`)\n    .sort()\n    .join('|');\n  return `${fields}#${modelShapeKey(model)}`;\n}\n\n/** A field's shape as `modelFingerprint` reads it: everything but its documentation, the type through `shapeWithEnumFlags`. */\nfunction fieldShapeKey(field: Field): string {\n  return stableStringify({ ...omitKeys(field, FIELD_DOC_KEYS), type: shapeWithEnumFlags(field.type) });\n}\n\n/**\n * `modelFingerprint` read without the model's own `deprecated`: the shape a\n * deprecated copy and a live one of one schema share. What a shape the SDK\n * sends must agree with a declared model on (`modelShares`), and what the\n * merge passes compare two inline copies of one name by when only the flag\n * tells them apart (`differOnlyByDeprecation`).\n */\nexport function shapeFingerprint(model: Model): string {\n  return modelFingerprint({ ...model, deprecated: undefined });\n}\n\n/**\n * A model's shape beside its fields: its limits, type parameters,\n * `deprecated` (unless `omit` leaves it out, as `modelAdmits` does), variants\n * (through `readShape`) and dispatch rules, the mapping's targets read under\n * `options.readModelName` as the variants are.\n */\nfunction modelShapeKey(model: Model, options: ShapeReadOptions = {}): string {\n  return `${modelPropertiesKey(model)}${modelStructureKey(model, options)}`;\n}\n\n/**\n * A model's union structure as one string — its composition keyword, its\n * variants (through `readShape`) and its dispatch rules, the mapping's\n * targets read under `options.readModelName` as the variants are. What\n * `modelAdmits` compares beside the fields and the model's properties\n * (`modelPropertiesAdmit`); the list-envelope pass compares the same parts\n * by structure on its own.\n */\nfunction modelStructureKey(model: Model, options: ShapeReadOptions = {}): string {\n  const structure: Record<string, unknown> = {};\n  if (model.compositionKind) structure.compositionKind = model.compositionKind;\n  if (model.variants) structure.variants = model.variants.map((variant) => readShape(variant, options));\n  if (model.discriminator) structure.discriminator = readDiscriminator(model.discriminator, options.readModelName);\n  return stableStringify(structure);\n}\n\n/**\n * A model's own properties as `modelPropertiesAdmit` reads them, as one\n * string: everything but its identity (name and documentation), its fields\n * and its union structure — `deprecated`, limits (`constraints`), type\n * parameters, whatever else the IR adds to a model. `modelFingerprint`\n * carries it beside the fields and the structure, and the list-envelope\n * pass keys a companion's shape by it (`fingerprintModel`), so the shapes\n * it counts agree with the folds it allows.\n */\nexport function modelPropertiesKey(model: Model): string {\n  return stableStringify(omitKeys(model, MODEL_PROPERTY_KEYS_OMITTED));\n}\n\n/**\n * Whether `owner` admits `candidate` in the model's own properties — what\n * `modelAdmits` reads beside the fields and the union structure: the two\n * agree on `deprecated` as `flagAdmits` reads it (a live owner admits either\n * flag, a deprecated owner only a deprecated candidate), and every other\n * property — the model's limits (`minProperties`, `dependentRequired`, …),\n * its type parameters, whatever else the IR adds to a model — is identical,\n * since the owner's definition is what every site reads after a fold.\n * `MODEL_ADMIT_KEYS` names the properties read on their own, so a property\n * added to `Model` is compared verbatim until it is listed there. The one\n * definition of a model's properties a fold must preserve: `modelAdmits`\n * applies it with the structure read by key, and the list-envelope pass\n * (`admits`) with the structure compared on its own.\n */\nexport function modelPropertiesAdmit(owner: Model, candidate: Model): boolean {\n  if (!flagAdmits(owner, candidate)) return false;\n  return stableStringify(omitKeys(owner, MODEL_ADMIT_KEYS)) === stableStringify(omitKeys(candidate, MODEL_ADMIT_KEYS));\n}\n\n/** Field properties `fieldAdmits` reads on their own — the type and the requiredness — beside the documentation it ignores; every other property is compared verbatim. */\nconst FIELD_ADMIT_KEYS: ReadonlySet<string> = new Set([...FIELD_DOC_KEYS, 'type', 'required', 'deprecated']);\n/** Field properties outside `fieldPropertiesKey`: the documentation and the type, which the list-envelope pass compares by structure on its own. */\nconst FIELD_PROPERTY_KEYS_OMITTED: ReadonlySet<string> = new Set([...FIELD_DOC_KEYS, 'type']);\n\n/**\n * How `modelAdmits`, `fieldAdmits` and `typeShapeKey` read a shape before\n * they compare it. A pass about to rename models hands the name its\n * renaming gives each one, so two shapes compare as that renaming leaves\n * them. Each reader covers the names of one kind and no other: the `…Json`\n * fold (`collapseJsonSuffixModels`) renames a model and an inline enum by\n * one rule but reads each among the names of its own kind (#534), so it\n * hands the two apart, and a reference of a kind no reader is given for is\n * read as it is.\n */\nexport interface ShapeReadOptions {\n  /**\n   * The name every model reference is read under on both sides before the\n   * shapes are compared — in a field's type, a union's variants and a\n   * discriminator's mapping targets alike. Absent, a reference is read\n   * under the name it carries, so a nested inline model that was renamed\n   * keeps a parent from being admitted by one whose child was not. The\n   * `…Json` fold reads `<Name>Json…` as `<Name>…`, so a child it will\n   * rename counts as its namesake, while a reference it will not rename is\n   * still read as it is.\n   */\n  readonly readModelName?: (name: string) => string;\n  /**\n   * The name every inline enum reference — one carrying its `values`,\n   * named by the extractor after the model and field it sits in — is read\n   * under, the same way: `PetJsonStatus` with the members of `PetStatus`\n   * counts as `PetStatus`, and with other members does not, since the\n   * members are compared with the name. Absent, an inline enum reference\n   * is read under the name it carries, whatever `readModelName` would make\n   * of it. A component enum reference carries no values and is never\n   * renamed by any pass, so it is always read as it is.\n   */\n  readonly readEnumName?: (name: string) => string;\n}\n\n/**\n * Whether `owner` admits `candidate`: every value `candidate` describes is\n * one `owner` describes too, so a reference typed as `owner` in place of\n * `candidate` loses strictness and nothing else. The two have the same field\n * names, and each field admits its namesake (`fieldAdmits`): it agrees in\n * everything `modelFingerprint` reads — type, limits, default, access flags,\n * its own `deprecated` — except that `owner` may be looser where `candidate`\n * is strict, never the other way round: a field `candidate` requires may be\n * optional on `owner`, and a field type `candidate` leaves non-null may be\n * `nullable<…>` on `owner`. Only the field type's own nullable wrapper is\n * read that way; a wrapper deeper down (an array's items) must agree. The\n * models' own properties — limits, type parameters, whatever else the IR\n * adds to a model — must be identical (`modelPropertiesAdmit`), their union\n * structure — variants and dispatch rules — must agree\n * (`modelStructureKey`), and a model reference is compared by name — the\n * name it carries, or the one `options.readModelName` reads it under: a nested\n * inline model keeps its name, so a parent whose child was renamed is not\n * admitted by one whose child was not. The models' own `deprecated` is read\n * apart from the shape (`flagAdmits`, through `modelPropertiesAdmit`): a\n * live `owner` admits a deprecated `candidate` — the flag stays on the\n * field, parameter or envelope field that wrote the candidate's schema, not\n * on a second model of the same shape — and a deprecated `owner` admits only\n * a deprecated one, so no live reference comes to resolve to a deprecated\n * model by folding. An identical shape is admitted. A component schema is\n * asked first whether it admits any copy at all (`ownerFlagAdmits`, by\n * `modelShares`): a deprecated one admits none, so a deprecated component\n * reaches this only in the `…Json` fold (#441).\n *\n * The one rule by which an inline model folds onto a model the document\n * declares — a component schema, or a model a component's field minted — in\n * the merge passes (`settleSharedNames`) and in the shape registry of\n * `materializeInlineSchema` (`ownerShares`), both through `modelShares`, and\n * by which the `…Json` fold (`collapseJsonSuffixModels`) collapses a\n * `<Name>Json…` child onto the `<Name>…` model that already holds its folded\n * name, every reference read under the fold; two inline models share a name\n * on an identical fingerprint only. A shape the SDK sends — a request body,\n * a parameter, a field object of a component only those reach — is the\n * callers' exception (`modelShares`): it shares a component on an identical\n * shape only, since typed as a looser component a caller could leave out\n * what the operation requires. The list-envelope pass compares its\n * companions by a structural rule of its own, since a companion's nested\n * models are named per operation; beside a declared model it reads that\n * model's flag by `ownerFlagAdmits` as well.\n */\nexport function modelAdmits(owner: Model, candidate: Model, options: ShapeReadOptions = {}): boolean {\n  if (!modelPropertiesAdmit(owner, candidate)) return false;\n  if (owner.fields.length !== candidate.fields.length) return false;\n  const ownerFields = new Map(owner.fields.map((field) => [field.name, field]));\n  for (const field of candidate.fields) {\n    const own = ownerFields.get(field.name);\n    if (!own || !fieldAdmits(own, field, options)) return false;\n  }\n  return modelStructureKey(owner, options) === modelStructureKey(candidate, options);\n}\n\n/**\n * Whether `owner`'s own `deprecated` admits `candidate`'s, as `modelAdmits`\n * reads the flag between any two models: a live `owner` admits a candidate\n * of either flag, and a deprecated `owner` only a deprecated one, so no live\n * reference comes to resolve to a deprecated model through a fold. The flag\n * is not part of the shape a fold compares: a deprecated inline schema\n * identical to a live model it is named like shares that model, its flag\n * carried by the site that wrote the schema (a `Field`, a `Parameter`, an\n * envelope field) rather than by a second model of the same shape. Read by\n * `modelPropertiesAdmit`, so by `modelAdmits`, and by `ownerFlagAdmits` for\n * a model a component's field minted; for a component schema the\n * deprecated-owner arm decides only in the `…Json` fold's child collapse\n * (`collapseJsonSuffixModels`), since a component is asked\n * `ownerFlagAdmits` first (`modelShares`, the list-envelope pass): a\n * deprecated component admits no copy of either flag (#441), so a copy's\n * name follows the component's flag and never its own — `ownerFlagAdmits`\n * says what that costs when the component is the one deprecated.\n */\nexport function flagAdmits(owner: Model, candidate: Model): boolean {\n  return !owner.deprecated || !!candidate.deprecated;\n}\n\n/**\n * Whether `owner`, a model the document declares, admits `candidate`, an\n * inline copy, on the models' own `deprecated` — the one flag rule a\n * declared owner is read by (`modelShares`, which the merge passes and the\n * shape registry ask, and the list-envelope pass for a companion beside\n * one). A component schema admits a copy of either flag while live (a\n * deprecated copy's flag is carried by the field, parameter or envelope\n * field that wrote its schema, see `flagAdmits`) and none, live or\n * deprecated, while deprecated: a live copy never resolves to a deprecated\n * model (#260, #312), and a deprecated copy keeps the qualified name its\n * live self had, so flipping the copy's `deprecated` changes the flag on\n * that model and nothing else — `getLegacyWidget`'s inline copy of a\n * deprecated `Widget` is `GetLegacyWidgetWidget` live and\n * `GetLegacyWidgetWidget (deprecated)` deprecated, the flip `oagen diff`\n * reports as additive in either direction, where folding the deprecated\n * copy onto `Widget` swapped the operation's type and was reported as\n * breaking (#441). So a copy's name never depends on its own flag, only on\n * the component's, and the component's flip is the one that retypes:\n * deprecating `Widget` together with its identical copy, or alone while\n * the copy stays deprecated, moves the copy from `Widget` to\n * `GetLegacyWidgetWidget` — `model-added` beside a breaking\n * `responseChanged`, exit 2 — as deprecating `Widget` alone has always done\n * to a live copy. No rule keeps both flips additive without a live site\n * resolving to a deprecated model: under a deprecated `Widget` the live\n * copy must leave it, and a deprecated copy can match only one of its two\n * neighbours, its live self or its fold under a live `Widget`; the copy's\n * own flip, the edit made on the copy's side, is the one kept additive. The\n * other trade-off: a copy deprecated from the start beside a deprecated\n * component is a second deprecated model of the shape, on a surface\n * nothing live reaches. A model a component's field minted\n * (`fieldMinted`: a nested object, array items, a union variant the schema\n * pass or the field extractor lifted) is read as `flagAdmits` reads it — a\n * deprecated one admits a deprecated copy and no live one — since the\n * object the schema pass lifted from a field is the owner the field\n * extractor's own copy of that field folds onto when the fields are settled\n * (`settleFieldInlineModels`), and a deprecated field model yields its name\n * to a live copy rather than hold it (`settleSharedNames`). The `…Json` fold\n * asks neither: the model a `<Name>Json…` child collapses onto holds a\n * folded name, and is no declared owner measured against an inline copy.\n */\nexport function ownerFlagAdmits(owner: Model, candidate: Model, fieldMinted = false): boolean {\n  if (fieldMinted) return flagAdmits(owner, candidate);\n  return !owner.deprecated;\n}\n\n/**\n * Whether `owner`, a model the document declares — a component schema, or,\n * with `fieldMinted`, a model a component's field minted — shares its name\n * with `candidate`, an inline model: when its flag admits the candidate's\n * (`ownerFlagAdmits`: a deprecated component never shares, #441) and it\n * admits the shape (`modelAdmits`), or, for a shape the SDK sends (`sent`: a\n * request body, a parameter, a field object of a component only those\n * reach), when the two are identical but for the model's own `deprecated`\n * (`shapeFingerprint`). The one question the merge passes\n * (`settleSharedNames`) and the shape registry (`ownerShares`) ask of a\n * declared model.\n */\nexport function modelShares(owner: Model, candidate: Model, sent = false, fieldMinted = false): boolean {\n  if (!ownerFlagAdmits(owner, candidate, fieldMinted)) return false;\n  if (!sent) return modelAdmits(owner, candidate);\n  return shapeFingerprint(owner) === shapeFingerprint(candidate);\n}\n\n/**\n * How `owner` is looser than `candidate`, which it admits (`modelAdmits`),\n * in the only two ways `modelAdmits` lets it be, each listing the fields in\n * `candidate`'s order: those `candidate` requires that `owner` leaves\n * optional (`does not require \"name\"`), and those whose type `candidate`\n * leaves non-null that `owner` wraps in `nullable<…>` (`allows null in\n * \"id\"`). Empty when the two are the same shape but for the models' own\n * flag. What the fold of a deprecated copy onto a live definition drops,\n * named by the warning it is announced with (`deprecatedFoldWarning`).\n */\nexport function looserFields(owner: Model, candidate: Model): string[] {\n  const owned = new Map(owner.fields.map((field) => [field.name, field]));\n  const optional: string[] = [];\n  const nullable: string[] = [];\n  for (const field of candidate.fields) {\n    const looser = owned.get(field.name);\n    if (!looser) continue;\n    if (field.required && !looser.required) optional.push(`\"${field.name}\"`);\n    if (field.type.kind !== 'nullable' && looser.type.kind === 'nullable') nullable.push(`\"${field.name}\"`);\n  }\n  return [\n    ...(optional.length > 0 ? [`does not require ${optional.join(', ')}`] : []),\n    ...(nullable.length > 0 ? [`allows null in ${nullable.join(', ')}`] : []),\n  ];\n}\n\n/**\n * The warning a deprecated inline copy folded onto a live definition of its\n * name is announced with — by the merge passes (`settleSharedNames`), the\n * shape registry (`materializeInlineSchema`) and the list-envelope pass\n * (`resolveEnvelopeCompanionNames`) alike. It says \"with the same shape\"\n * only for a copy identical to that definition but for the flag; a copy the\n * definition admits while looser (`looser`: how, as `looserFields` words\n * it) is said to be folded onto a looser definition, so what the copy\n * required and the shared name no longer does is named.\n */\nexport function deprecatedFoldWarning(name: string, looser: readonly string[]): string {\n  const shape =\n    looser.length === 0 ? ' with the same shape' : `, with a looser live definition that ${looser.join(' and ')}`;\n  return `[oagen] Warning: Inline model \"${name}\" is declared both deprecated and live${shape} — keeping the live definition under the shared name`;\n}\n\n/**\n * Whether `owner` admits `candidate` as the field of its name: the rule\n * `modelAdmits` applies to each field, on its own. The two agree in\n * everything but their documentation — type (through `fieldTypeAdmits`,\n * model references read under `options.readModelName` and inline enum\n * references under `options.readEnumName`), limits, default, access\n * flags, their own `deprecated` (`fieldFlagAgrees`: in either direction,\n * since the owner's fields are what every site reads after a fold) — except\n * that `owner` may be optional where `candidate` is required, and\n * `nullable<…>` where `candidate` is not. Everything but the type is\n * `fieldPropertiesAdmit`, which the list-envelope pass reads as well. The\n * `…Json` fold asks this of every field the base and the `…Json` model both\n * declare, since the base takes the `…Json` model's fields.\n */\nexport function fieldAdmits(owner: Field, candidate: Field, options: ShapeReadOptions = {}): boolean {\n  return fieldPropertiesAdmit(owner, candidate) && fieldTypeAdmits(owner.type, candidate.type, options);\n}\n\n/**\n * Whether `owner` admits `candidate` as the field of its name in everything\n * but the type — what `fieldAdmits` reads beside `fieldTypeAdmits`: the two\n * agree on their own `deprecated` (`fieldFlagAgrees`), `owner` is no\n * stricter on requiredness (a field `candidate` requires may be optional on\n * `owner`, never the reverse), and every other property — limits, default,\n * access flags, whatever else the IR adds to a field — is identical\n * (`FIELD_ADMIT_KEYS` names the ones read on their own, so a property added\n * to `Field` is compared verbatim until it is listed there). The one\n * definition of a field's properties a fold must preserve: `fieldAdmits`\n * applies it with the type read by shape key, and the list-envelope pass\n * (`admits`) with the type compared by structure, since a companion's nested\n * models are named per operation.\n */\nexport function fieldPropertiesAdmit(owner: Field, candidate: Field): boolean {\n  if (!fieldFlagAgrees(owner, candidate)) return false;\n  if (owner.required && !candidate.required) return false;\n  return stableStringify(omitKeys(owner, FIELD_ADMIT_KEYS)) === stableStringify(omitKeys(candidate, FIELD_ADMIT_KEYS));\n}\n\n/**\n * A field's properties as `fieldPropertiesAdmit` reads them, as one string:\n * everything but its documentation and its type — requiredness, its own\n * `deprecated`, limits, default, access flags. Two fields with the same key\n * admit each other in everything but the type; the list-envelope pass keys\n * a companion's shape by it (`fingerprintModel`) beside the structural key\n * of the type, so the shapes it counts agree with the folds it allows.\n */\nexport function fieldPropertiesKey(field: Field): string {\n  return stableStringify(omitKeys(field, FIELD_PROPERTY_KEYS_OMITTED));\n}\n\n/**\n * Whether `owner` and `candidate`, fields of one name, agree on their own\n * `deprecated`, in either direction. A field's flag has no carrier but the\n * field itself: after a fold every site reads the owner's fields, so an\n * owner whose field is live would drop the notice a candidate's deprecated\n * field gave its readers, and an owner whose field is deprecated would give\n * a candidate's readers a notice its own schema never wrote. Read by\n * `fieldAdmits` for every fold `modelAdmits` decides, and by the\n * list-envelope pass's own structural comparison (`admits`), so no fold\n * changes what any site's readers see of a field's flag.\n */\nexport function fieldFlagAgrees(owner: Field, candidate: Field): boolean {\n  return !!owner.deprecated === !!candidate.deprecated;\n}\n\n/** Whether `owner` admits every value of `candidate`'s type: the same type under the field's own nullable wrapper, which `owner` may carry where `candidate` does not. */\nfunction fieldTypeAdmits(owner: TypeRef, candidate: TypeRef, options: ShapeReadOptions): boolean {\n  if (candidate.kind === 'nullable' && owner.kind !== 'nullable') return false;\n  const inner = (ref: TypeRef): TypeRef => (ref.kind === 'nullable' ? ref.inner : ref);\n  return typeShapeKey(inner(owner), options) === typeShapeKey(inner(candidate), options);\n}\n\n/**\n * A type's shape as the admit predicates read it — every inline enum with\n * its per-value deprecation (`shapeWithEnumFlags`), every model reference\n * under `options.readModelName` and every inline enum reference under\n * `options.readEnumName` — stable-stringified, so two types compare by\n * string equality. The `…Json` fold compares a base union's variants with\n * the `…Json` model's through this, both read under the fold.\n */\nexport function typeShapeKey(ref: TypeRef, options: ShapeReadOptions = {}): string {\n  return stableStringify(readShape(ref, options));\n}\n\n/**\n * `shapeWithEnumFlags(ref)`, with every model reference renamed by\n * `options.readModelName` and every inline enum reference (one carrying its\n * `values`) by `options.readEnumName`, each only when given, on a copy —\n * the flags are read first, since the copy has no identity in the enum\n * side table.\n */\nfunction readShape(ref: TypeRef, options: ShapeReadOptions): unknown {\n  const shape = shapeWithEnumFlags(ref);\n  const { readModelName, readEnumName } = options;\n  if (!readModelName && !readEnumName) return shape;\n  const read = structuredClone(shape) as TypeRef;\n  walkTypeRef(read, {\n    model: (r) => {\n      if (readModelName) (r as { name: string }).name = readModelName(r.name);\n    },\n    enum: (r) => {\n      if (r.values && readEnumName) r.name = readEnumName(r.name);\n    },\n  });\n  return read;\n}\n\n/** The entries of `value` whose key is not in `keys` and whose value is set. */\nfunction omitKeys(value: object, keys: ReadonlySet<string>): Record<string, unknown> {\n  return Object.fromEntries(\n    Object.entries(value).filter(([key, entryValue]) => entryValue !== undefined && !keys.has(key)),\n  );\n}\n\n/** `JSON.stringify` with object keys sorted and unset entries dropped, so equal shapes serialize equally. */\nexport function stableStringify(value: unknown): string {\n  if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n  if (value !== null && typeof value === 'object') {\n    const record = value as Record<string, unknown>;\n    const entries = Object.keys(record)\n      .filter((key) => record[key] !== undefined)\n      .sort()\n      .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`);\n    return `{${entries.join(',')}}`;\n  }\n  return JSON.stringify(value) ?? 'undefined';\n}\n\n/**\n * The title-mapped union variants that must not keep their bare title\n * because a variant of another shape takes the same title under the same\n * root (`markContestedTitles`). Replaced whole whenever a document is marked,\n * so a schema object marked for one document is never read as contested for\n * another; empty outside an extraction, where no title is contested.\n */\nlet contestedTitledVariants = new WeakSet<SchemaObject>();\n\n/**\n * Whether `variant` is a title-mapped union variant whose title another\n * shape takes under the same root (see `markContestedTitles`). The marks are\n * on the document's variants; a folded copy of one (`foldSiblingProperties`)\n * is read through its origin.\n */\nexport function isContestedTitle(variant: SchemaObject): boolean {\n  return contestedTitledVariants.has(foldedVariantOrigin(variant) ?? variant);\n}\n\n/**\n * Decide, for a whole OpenAPI document, which title-mapped union variants\n * (`titleMappedVariantNames`) must not keep their bare title: a kept title\n * is context-free — it names one shape wherever it appears, as a component\n * name would — so when two variants anywhere under one root give the same\n * title different shapes (`schemaShapeKey`), neither can keep it, and both\n * take their context-qualified names instead (`nameInlineVariantEntries`).\n * Identical shapes under one title share one model, as between siblings\n * (`reservedInlineNames`), and a title used once is kept. Within one union\n * only the first variant to carry a title is a claim on it: a later one\n * with the same title never keeps it while the first does, whatever the\n * document holds (`emitted` in `nameInlineVariantEntries`), so its shape\n * is not compared. The same holds across everything one union reaches\n * without entering an object — its nested unions, its array variants'\n * items, its map variants' values, a lone `allOf` member — the names\n * `mintedInlineNameEntries` reads for the union, which\n * `nonObjectVariantContexts` decides in variant order: an earlier variant's\n * kept title is reserved for a later variant of another shape and shared\n * for the identical one. So one claim set spans that group, and only its\n * first variant per title is compared. A later one still carries the title,\n * so it is marked with the rest when the title is contested: the first then\n * takes its context-qualified name, which leaves nothing to step the later\n * one off the bare title, and two groups' later variants of two shapes\n * would meet on it.\n *\n * A root is a schema whose inline models are collected together: every\n * `components.schemas` entry is read as one root, because one pass collects\n * their inline field models into one list and a named union's variants are\n * already compared across every component; every other schema of the\n * document — the `schema` of a request body's or response's media type, of\n * a parameter, of a response header, of a webhook payload, under `paths`,\n * `webhooks` or `components` alike — is a root of its own. The same title\n * given two shapes by two roots is not contested here: the passes that merge\n * the roots' models decide it (the first owner keeps the name, and a later\n * shape is renamed or dropped with a warning). Outside the components root,\n * an inline `allOf` merged into one model (`readInlineAllOf`: `'merged'`) is\n * read as that model, the one every extractor builds from it: its\n * properties as `mergeAllOfMembers` settles them, each once per root, a\n * `$ref` member's component's included — so the component is read with\n * the root as far as the merge reads it — and nothing else of it. A\n * declaration the merge drops, or a union whose variants it flattens into\n * the model's fields, is no model and contests nothing (workos/oagen#374:\n * as a response, `allOf: [{ $ref: Base }, { … }]` kept a title that\n * `Base.shape` and the inline `marker.shape` give different shapes, and one\n * union resolved to the other's models). The components root reads its\n * schemas as written: every component is one of them, and a component's own\n * `allOf` is built by its own reader (`extractAllOfModel`).\n *\n * Within a root, the walk follows the keywords the parser types a schema\n * through only — `properties`, `patternProperties`, `additionalProperties`,\n * `items` and `allOf`/`oneOf`/`anyOf` — so a property named `schema` or\n * `title` is a property, a `$ref` is a reference to a component read under\n * the components root, not descended into (a merged `allOf`'s `$ref` member\n * aside, see above), and a union under `not`, `if`/`then`/`else`,\n * `$defs`/`definitions`, `dependentSchemas`, `contains`, `prefixItems`,\n * `propertyNames` or another keyword the parser never reads never becomes a\n * model, so it contests no title (`schemaShapeKey` still compares them).\n * The roots are found by following the OpenAPI object model\n * (`schemaRootsOf`), the way the operation, response and webhook readers\n * do, so a name is never mistaken for a specification extension: a header\n * named `x-meta`, a component named `x-thing`, a media type `x-custom/json`,\n * a webhook named `x-event` or a property `x-id` is read like any other, and\n * an `x-` key is stepped over only where the readers step over it or read\n * nothing: the Paths Object's (an extension by the specification, which\n * `extractOperations` steps over), a Responses\n * Object's (`readFallbackResponse`) and a Callback Object's (extensions by\n * the specification, which `extractCallbacks` steps over). An object\n * written as a `$ref` — a parameter, request body, response or header, a\n * path item or a callback — is stepped over whole, as the readers step\n * over it, so a union under a `content` or `headers` written beside the\n * `$ref` is under no root and contests nothing, whether the ref resolves\n * or not (#601). Decided from the document's content\n * alone, so declaration order and depth play no part, and once per\n * document, before any union is named (`extractSchemas`), so the union\n * TypeRef and every extractor read the same decision. `undefined` clears\n * the previous document's marks.\n *\n * Each root is read with visited sets of its own, so a schema object two\n * roots share — one a `transformSpec` assigned in both places, a bundled\n * external schema inlined twice as one object — is read under each root and\n * compared with each root's other variants, and a mark from either root\n * stands: the shared variant's title is then qualified wherever it appears.\n * So does a component's union a root reads through a merged `allOf`: a mark\n * there qualifies the component's own variants too (`CircleBaseShape`).\n * Within a root the same holds per claim group: a union object reached\n * under two groups — nested in `shape`, where an earlier union of the group\n * already claimed its title, and again as `wrapper.marker`, where it keeps\n * the title — is read under each, so the two shapes of the title are\n * compared and contested (`markContestedTitlesUnderRoot`). A schema that\n * refers back to itself is stopped by the ancestors on the path to it. The\n * descent over the document keeps a separate guard that never holds a\n * schema. The guards end the walk on a document that refers back to itself.\n */\nexport function markContestedTitles(document: unknown): void {\n  contestedTitledVariants = new WeakSet();\n  if (!isRecord(document)) return;\n  const components = isRecord(document['components']) ? document['components'] : undefined;\n  const schemas = components?.['schemas'];\n  if (isRecord(schemas)) markContestedTitlesUnderRoot(Object.values(schemas).filter(isSchemaRecord));\n  // What a merged `allOf`'s `$ref` members resolve against: this document's\n  // components only, none when it declares none.\n  const componentSchemas = isRecord(schemas) ? (schemas as Record<string, SchemaObject>) : {};\n  for (const root of schemaRootsOf(document, components)) markContestedTitlesUnderRoot([root], componentSchemas);\n}\n\n/** A plain object: the only value that can be a schema or a container of them. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** `isRecord`, typed as a schema for the walks below. */\nfunction isSchemaRecord(value: unknown): value is SchemaObject {\n  return isRecord(value);\n}\n\n/** The Path Item Object's operation fields, the keys the operation readers dispatch on. */\nconst PATH_ITEM_OPERATIONS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'] as const;\n/** The `in` locations a parameter is typed at (`extractParams`); one declared anywhere else is never read. */\nconst PARAMETER_LOCATIONS: ReadonlySet<ParameterLocation> = new Set(['path', 'query', 'header', 'cookie']);\n\n/**\n * Every schema root of the document outside `components.schemas`, found by\n * walking the OpenAPI 3.0/3.1 object model (see `markContestedTitles`):\n *\n *   - the OpenAPI Object's `paths` (a path per key, an `x-` extension\n *     stepped over) and `webhooks` (a name per key) to Path Item Objects;\n *     the Components Object's `responses`,\n *     `parameters`, `requestBodies`, `headers`, `pathItems` and `callbacks`\n *     (a name per key);\n *   - a Path Item's `parameters` list and operations; an Operation's\n *     `parameters`, `requestBody`, `responses` (a status code, `default`, a\n *     range or an `x-` extension per key) and `callbacks` (a name per key,\n *     each a Callback Object: an expression or an `x-` extension per key,\n *     each a Path Item);\n *   - a Parameter's or Header's `schema` and `content`; a Request Body's and\n *     a Response's `content` (a media type per key) and a Response's\n *     `headers` (a name per key); a Media Type's `schema` and `encoding` (a\n *     property name per key, each an Encoding Object with `headers`).\n *\n * A map whose keys are names is read whole, whatever the keys look like,\n * the `webhooks` map among them: OpenAPI gives it no extensions, and\n * `extractWebhooks` reads every key as a webhook (#421).\n * An `x-` key is stepped over in the Paths Object, where the specification\n * makes it an extension and `extractOperations` steps over it, in a\n * Responses Object, as\n * `readFallbackResponse` steps over it, and in a Callback Object, where the\n * specification makes it an extension and `extractCallbacks` steps over it\n * (#382). A `$ref` entry\n * anywhere carries no schema of its own: the target is a component, or\n * another `paths` or `webhooks` entry a Path Item's `$ref` names (#422),\n * read under its own map, and the object around the `$ref` is stepped\n * over whole, as the readers step over it — a Parameter, Header, Request\n * Body or Response Object written as a Reference Object, whose every other\n * key OpenAPI says to ignore (`followReference`, #562), a Path Item's\n * `$ref` entry, whose target is taken whole (`resolvePathItemRef`), and a\n * Callback Object's (`resolveCallbackRef`) — so a `schema`, `content` or\n * `headers` written beside the `$ref` is never read, whether the ref\n * resolves or not, at every site that takes one: on an operation, a\n * webhook or a callback, and as a `components` entry itself (#601: a\n * titled union under a `content` beside a `404`'s `$ref` contested the\n * `Tag` of a component's `collar` and renamed it `TagPetCollar`, though\n * the parser typed nothing from it). A `$ref` key holding `undefined` is\n * no reference, as `followReference` reads it. A `schema` is yielded and\n * not entered, so one shared by two sites is yielded for each; every other\n * object is entered once, which ends the walk on a document that refers\n * back to itself. `example`, `examples`, `links` and extensions are never\n * entered.\n */\nfunction schemaRootsOf(\n  document: Record<string, unknown>,\n  components: Record<string, unknown> | undefined,\n): SchemaObject[] {\n  const roots: SchemaObject[] = [];\n  const entered = new WeakSet<object>();\n  /** Enter an object once; false for a non-object or one entered before. */\n  const enter = (value: unknown): value is Record<string, unknown> => {\n    if (!isRecord(value) || entered.has(value)) return false;\n    entered.add(value);\n    return true;\n  };\n  /** Every entry of a map whose keys are names. */\n  const named = (map: unknown, visit: (entry: unknown) => void): void => {\n    if (!enter(map)) return;\n    for (const entry of Object.values(map)) visit(entry);\n  };\n  /** Every entry of a map whose keys OpenAPI defines beside `x-` extensions. */\n  const keyed = (map: unknown, visit: (entry: unknown) => void): void => {\n    if (!enter(map)) return;\n    for (const [key, entry] of Object.entries(map)) if (!key.startsWith('x-')) visit(entry);\n  };\n  const listed = (list: unknown, visit: (entry: unknown) => void): void => {\n    if (!Array.isArray(list) || entered.has(list)) return;\n    entered.add(list);\n    for (const entry of list) visit(entry);\n  };\n  const schema = (value: unknown): void => {\n    if (isSchemaRecord(value)) roots.push(value);\n  };\n  const encoding = (value: unknown): void => {\n    if (enter(value)) named(value['headers'], parameter);\n  };\n  const mediaType = (value: unknown): void => {\n    if (!enter(value)) return;\n    schema(value['schema']);\n    named(value['encoding'], encoding);\n  };\n  /**\n   * Whether `value` is written as a reference: a `$ref` with a value, which\n   * the readers follow to its target and read nothing else of, so every\n   * key beside it is stepped over (#601). A `$ref` holding `undefined` is\n   * no reference, as `followReference` reads it.\n   */\n  const isReference = (value: Record<string, unknown>): boolean => value['$ref'] !== undefined;\n  /** A Parameter Object or a Header Object: the same schema sites. */\n  const parameter = (value: unknown): void => {\n    if (!enter(value) || isReference(value)) return;\n    schema(value['schema']);\n    named(value['content'], mediaType);\n  };\n  const requestBody = (value: unknown): void => {\n    if (enter(value) && !isReference(value)) named(value['content'], mediaType);\n  };\n  const response = (value: unknown): void => {\n    if (!enter(value) || isReference(value)) return;\n    named(value['headers'], parameter);\n    named(value['content'], mediaType);\n  };\n  const pathItem = (value: unknown): void => {\n    if (!enter(value) || isReference(value)) return;\n    listed(value['parameters'], parameter);\n    for (const method of PATH_ITEM_OPERATIONS) operation(value[method]);\n  };\n  /** A Callback Object: an expression or an `x-` extension per key, each a Path Item; one written as a reference is stepped over. */\n  const callback = (value: unknown): void => {\n    if (isRecord(value) && isReference(value)) return;\n    keyed(value, pathItem);\n  };\n  const operation = (value: unknown): void => {\n    if (!enter(value)) return;\n    listed(value['parameters'], parameter);\n    requestBody(value['requestBody']);\n    keyed(value['responses'], response);\n    named(value['callbacks'], callback);\n  };\n\n  // `paths` steps over `x-` extensions, as `extractOperations` does; every\n  // `webhooks` key is a webhook, as `extractWebhooks` reads it (#421).\n  keyed(document['paths'], pathItem);\n  named(document['webhooks'], pathItem);\n  if (components) {\n    named(components['responses'], response);\n    named(components['parameters'], parameter);\n    named(components['requestBodies'], requestBody);\n    named(components['headers'], parameter);\n    named(components['pathItems'], pathItem);\n    named(components['callbacks'], callback);\n  }\n  return roots;\n}\n\n/** Which way a site moves what it types: out with a request the SDK makes, or in. */\ntype SiteDirection = 'sent' | 'received';\n\n/**\n * The components the SDK only sends, by resolved name (`resolveSchemaName`):\n * those reached by at least one site the parser reads and by none that the\n * SDK receives. What an operation under `paths` sends is its request body,\n * under every media type it declares a schema for — each is typed through\n * it, as `requestBody` or in `requestBodyContents`, so a `postNote` body of\n * `$ref: Pet` under `application/xml` alone, which nothing reads as\n * `requestBody`, still sends `Pet` — and the parameters it types — the Path Item's,\n * then its own, an operation parameter replacing a Path Item one of the same\n * identity (`parameterKey`: location and name, a header's name case-folded)\n * as `buildOperation` merges them, so a Path Item parameter the operation\n * overrides is no site — each written inline or through\n * `components/requestBodies` and `components/parameters`; what it receives\n * is every response `extractResponses` reads — a body and a header under a\n * 200–599 status code, `default` or a `1XX`–`5XX` range, inline or through\n * `components/responses` and `components/headers` — and nothing under a key\n * the reader skips, each key classified as the reader classifies it\n * (`classifyResponseKey`): a 1xx status code, which it keeps as written and\n * types nothing of, an `x-` extension, a key OpenAPI does not define\n * (`600`, `6XX`), warned about and ignored, and the later of two range keys\n * that differ in case alone (`4xx` after `4XX`, `readFallbackResponse`) —\n * so a `103` on `listNotes` with an `X-Pet` header or a body of `$ref: Pet`\n * leaves `Pet` only sent, as the document without it does, while a `1XX`\n * range with the same header receives it (#540 review). The `headers` map\n * is read as `extractResponseHeaders` reads it: of two keys that differ in\n * case alone, the later declaration (#295), and never one keyed\n * `Content-Type`, whatever its case, which OpenAPI says to ignore\n * (`isIgnoredResponseHeader`, #540) — so a `Content-Type` header of\n * `$ref: Pet` on `createPet`'s `204` leaves `Pet` only sent too. A\n * response body is read by the media types whose schema the reader reads\n * (`responseBodyReading`): every one but `application/octet-stream`,\n * `application/pdf`, `text/plain`, `text/html`, `text/xml` and\n * `application/xml`, which `primaryBodySchema` and `typeSecondaryContent`\n * type as a binary string or a string without reading the schema, at a\n * 2xx, 3xx, error, `default` or range entry alike — so a `listNotes` `200`\n * of `$ref: Pet` under `application/xml`, `text/plain` or\n * `application/octet-stream` alone, or under `application/xml` beside a\n * `201` whose `application/json` is `{ type: string }`, leaves `Pet` only\n * sent, as the document without it does, while a body under\n * `application/json`, `application/yaml` or `*\\/*` receives it (#610). A\n * parameter or header is read by the one schema that types it\n * (`parameterTyping`): its `schema`,\n * else the schema of the `content` entry `selectParameterContent` picks, so\n * one the parser types as a string — a `content` map none of whose media\n * types is read, or a map beside a `schema`, which wins — reaches nothing.\n * A parameter the readers never type reaches nothing either: an `Accept`,\n * `Content-Type` or `Authorization` header, which OpenAPI says to ignore\n * (`isIgnoredHeaderParameter`, #414), on an operation or a webhook, a\n * webhook's `path` parameter, which `extractWebhooks` drops, and a\n * `Content-Type` response header (above). A webhook's payload and the\n * parameters it keeps are received, merged the same way (`extractWebhooks`);\n * its responses type no body (`extractWebhookResponses`). An operation's\n * `callbacks` — a webhook's, and a callback operation's own, nested — are\n * read as `extractCallbacks` reads them: each Callback Object (a\n * `components/callbacks` `$ref` followed, a callback referring back to one\n * it sits in read once) maps expressions to path items whose requests the\n * SDK is sent, so their bodies and parameters are received and their\n * responses type no body (#382). A Path Item and every Reference Object are followed as the\n * readers follow them (`resolvePathItemRef`, `followReference`), an `x-` key\n * of `paths` stepped over, a Responses Object's keys read as above and every\n * `webhooks` key read as a webhook. A schema\n * reaches the components it names through the keywords the parser types it\n * through — `properties`, `patternProperties`, `additionalProperties`,\n * `items`, `allOf`/`oneOf`/`anyOf` — and a discriminator's mapping, a `$ref`\n * read as the parser reads one (the component it names, or the one a\n * pointer deeper into a component enters and the schema it lands on there;\n * `schemaRefTarget`, #539), so a component another one reaches is reached by\n * every site that reaches that one. A component no site reaches is no site:\n * one that names `Pet` leaves `Pet` as only sent as it was, and is itself\n * not among the result, since the document does not say which way it goes.\n * Two keys that resolve to one name (`Note` and `note`) count as one\n * component only sent when both are.\n *\n * A component field's object is what the SDK sends when its component is\n * (`fieldInlineModelBundles`, `InlineModelBundle.sent`), so it shares a\n * component named like it on an identical shape only.\n */\nexport function sentOnlyComponentNames(document: unknown): Set<string> {\n  if (!isRecord(document)) return new Set();\n  const components = isRecord(document['components']) ? document['components'] : {};\n  const schemas = isRecord(components['schemas']) ? components['schemas'] : {};\n  /** The directions each component is reached in, by `components/schemas` key. */\n  const reached = new Map<string, Set<SiteDirection>>();\n  const entered: Record<SiteDirection, WeakSet<object>> = { sent: new WeakSet(), received: new WeakSet() };\n  /** What a Reference Object chain into `section` leads to; `undefined` for one that loops or leads nowhere. */\n  const follow = (\n    value: unknown,\n    section: 'pathItems' | 'parameters' | 'requestBodies' | 'responses' | 'headers' | 'callbacks',\n  ): Record<string, unknown> | undefined => {\n    const entries = components[section];\n    const map = isRecord(entries) ? (entries as Record<string, Record<string, unknown>>) : undefined;\n    const seen = new Set<string>();\n    let current = value;\n    while (isRecord(current) && current['$ref'] !== undefined) {\n      const ref = current['$ref'];\n      if (typeof ref !== 'string' || seen.has(ref)) return undefined;\n      seen.add(ref);\n      // A Path Item's `$ref` may also name another `paths` or `webhooks`\n      // entry, as `resolvePathItemRef` reads it (#422).\n      current =\n        section === 'pathItems' ? pathItemRefTarget(ref, map, document) : resolveComponentRef(ref, section, map);\n    }\n    return isRecord(current) ? current : undefined;\n  };\n  const schema = (value: unknown, direction: SiteDirection): void => {\n    if (!isRecord(value) || entered[direction].has(value)) return;\n    entered[direction].add(value);\n    const reach = (ref: unknown): void => {\n      const tokens = schemaRefTokens(ref);\n      const key = tokens?.[0];\n      if (key === undefined || !Object.hasOwn(schemas, key)) return;\n      reached.set(key, (reached.get(key) ?? new Set<SiteDirection>()).add(direction));\n      // A pointer deeper into the component (#539) reaches the component\n      // and, from there, what the schema it lands on names.\n      schema(schemaRefTarget(ref, schemas as Record<string, SchemaObject>) ?? schemas[key], direction);\n    };\n    reach(value['$ref']);\n    const mapping = isRecord(value['discriminator']) ? value['discriminator']['mapping'] : undefined;\n    if (isRecord(mapping)) for (const target of Object.values(mapping)) reach(target);\n    for (const keyword of ['properties', 'patternProperties']) {\n      const properties = value[keyword];\n      if (isRecord(properties)) for (const property of Object.values(properties)) schema(property, direction);\n    }\n    schema(value['additionalProperties'], direction);\n    schema(value['items'], direction);\n    for (const keyword of ['allOf', 'oneOf', 'anyOf']) {\n      const members = value[keyword];\n      if (Array.isArray(members)) for (const member of members) schema(member, direction);\n    }\n  };\n  /**\n   * A request body's `content` map — an operation's, sent, or a webhook's or\n   * a callback's, received — read as the body readers read it: every media\n   * type that declares a schema is typed through it, as the primary pick\n   * (`selectRequestBodyContent`) or a secondary entry\n   * (`typeSecondaryRequestContent`, `mintPayload`: `requestBodyContents`),\n   * so each reaches what its schema names, under `application/xml` as under\n   * `application/json`.\n   */\n  const requestContent = (value: unknown, direction: SiteDirection): void => {\n    if (!isRecord(value)) return;\n    for (const mediaType of Object.values(value)) if (isRecord(mediaType)) schema(mediaType['schema'], direction);\n  };\n  /**\n   * A response's `content` map, read as `extractResponseContents` reads it:\n   * a media type the reader types as a binary string or a string without\n   * reading its schema (`responseBodyReading`: `application/octet-stream`,\n   * `application/pdf`, `text/plain`, `text/html`, `text/xml`,\n   * `application/xml`, by essence) reaches nothing, as the primary pick\n   * (`primaryBodySchema`) and a secondary entry (`typeSecondaryContent`)\n   * alike leave its schema unread; every other media type types its body\n   * through its schema and reaches what it names (#610).\n   */\n  const responseContent = (value: unknown): void => {\n    if (!isRecord(value)) return;\n    for (const [contentType, mediaType] of Object.entries(value)) {\n      if (!isRecord(mediaType) || responseBodyReading(contentType) !== 'schema') continue;\n      schema(mediaType['schema'], 'received');\n    }\n  };\n  /**\n   * A Parameter or Header Object, read by the one schema that types it\n   * (`parameterTyping`): its `schema`, else the schema of the `content`\n   * entry `selectParameterContent` picks. One typed as a string — a\n   * `content` map none of whose media types is read, or no schema at all —\n   * reaches nothing, and a `content` map beside a `schema` is not consulted.\n   */\n  const typed = (declaration: Record<string, unknown>, direction: SiteDirection): void => {\n    const { schema: own, content: map } = declaration;\n    schema(\n      parameterTyping({ schema: own, content: isRecord(map) ? map : undefined } as SchemaOrContent).schema,\n      direction,\n    );\n  };\n  /**\n   * The parameters `operation` types, resolved as `buildOperation` and\n   * `extractWebhooks` resolve them: the Path Item's, then its own, each\n   * Reference Object followed, an operation parameter replacing a Path Item\n   * one of the same identity (`parameterKey`: location and name, a header's\n   * name case-folded). A Path Item parameter the operation overrides is not\n   * read, and one under no operation is read by nothing.\n   */\n  const parameters = (item: Record<string, unknown>, operation: Record<string, unknown>, direction: SiteDirection) => {\n    const byIdentity = new Map<string, Record<string, unknown>>();\n    for (const list of [item['parameters'], operation['parameters']]) {\n      if (!Array.isArray(list)) continue;\n      for (const raw of list) {\n        const resolved = follow(raw, 'parameters');\n        const location = resolved?.['in'];\n        if (!resolved || !PARAMETER_LOCATIONS.has(location as ParameterLocation)) continue;\n        const name = resolved['name'];\n        // Nothing types an `Accept`, `Content-Type` or `Authorization` header\n        // (#414), nor a webhook's `path` parameter, which `extractWebhooks`\n        // drops: neither reaches a component (Greptile, #421 review).\n        if (typeof name === 'string' && isIgnoredHeaderParameter({ in: location, name } as ParameterObject)) continue;\n        if (direction === 'received' && location === 'path') continue;\n        byIdentity.set(parameterKey(location as ParameterLocation, typeof name === 'string' ? name : ''), resolved);\n      }\n    }\n    for (const resolved of byIdentity.values()) typed(resolved, direction);\n  };\n  /**\n   * The Callback Objects on the path to the one being read, by identity\n   * after `$ref` resolution: a callback that refers back to one it sits in\n   * is read once, as `extractCallbacks` reads it (#382).\n   */\n  const readingCallbacks = new Set<object>();\n  /** Each callback of an operation: its path items are read as a webhook's is, since a callback's request is one the SDK is sent. */\n  const callbacks = (map: unknown): void => {\n    if (!isRecord(map)) return;\n    for (const raw of Object.values(map)) {\n      const callback = follow(raw, 'callbacks');\n      if (!callback || readingCallbacks.has(callback)) continue;\n      readingCallbacks.add(callback);\n      for (const [expression, entry] of Object.entries(callback)) {\n        // An `x-` key is a specification extension of the Callback Object.\n        if (expression.startsWith('x-')) continue;\n        const item = follow(entry, 'pathItems');\n        if (item) pathItem(item, true);\n      }\n      readingCallbacks.delete(callback);\n    }\n  };\n  /** A path item's operations, their requests read as sent or — a webhook's or a callback's — received. */\n  const pathItem = (item: Record<string, unknown>, received: boolean): void => {\n    const request: SiteDirection = received ? 'received' : 'sent';\n    for (const method of PATH_ITEM_OPERATIONS) {\n      const operation = item[method];\n      if (!isRecord(operation)) continue;\n      parameters(item, operation, request);\n      requestContent(follow(operation['requestBody'], 'requestBodies')?.['content'], request);\n      callbacks(operation['callbacks']);\n      const responses = operation['responses'];\n      if (received || !isRecord(responses)) continue;\n      // Read as `extractResponses` reads the map, each key classified as\n      // the reader classifies it (`classifyResponseKey`): a 200–599 status\n      // code, `default` and a `1XX`–`5XX` range are read, body and headers\n      // alike, and of two range keys that differ in case alone (`4XX`\n      // beside `4xx`) only the first is (`readFallbackResponse`). A 1xx\n      // status code is kept as written and nothing of it typed, an `x-`\n      // key is an extension, and a key OpenAPI does not define (`600`,\n      // `6XX`) is warned about — once, by the reader — and ignored; none\n      // of those reaches a component (#540 review).\n      const ranges = new Set<string>();\n      for (const [code, entry] of Object.entries(responses)) {\n        const key = classifyResponseKey(code);\n        if (key.kind === 'extension' || key.kind === 'unrecognized') continue;\n        if (key.kind === 'status' && key.code < 200) continue;\n        if (key.kind === 'range') {\n          if (ranges.has(key.range)) continue;\n          ranges.add(key.range);\n        }\n        const response = follow(entry, 'responses');\n        if (!response) continue;\n        responseContent(response['content']);\n        const headers = response['headers'];\n        if (!isRecord(headers)) continue;\n        // Read as `extractResponseHeaders` reads the map: header names are\n        // case-insensitive, so of two keys that differ in case alone the\n        // later declaration is the header (#295), and a `Content-Type`\n        // header, which OpenAPI says to ignore, is skipped by its key,\n        // whatever its `$ref` leads to (`isIgnoredResponseHeader`). Nothing\n        // types the dropped declaration or the ignored header, so neither\n        // reaches a component (#540).\n        const declared = new Map<string, unknown>();\n        for (const [name, header] of Object.entries(headers)) declared.set(foldHeaderName(name), header);\n        for (const [name, header] of declared) {\n          if (isIgnoredResponseHeader(name)) continue;\n          const resolved = follow(header, 'headers');\n          if (resolved) typed(resolved, 'received');\n        }\n      }\n    }\n  };\n  const pathItems = (map: unknown, webhooks: boolean): void => {\n    if (!isRecord(map)) return;\n    for (const [key, raw] of Object.entries(map)) {\n      // An extension under `paths`; a webhook's name under `webhooks` (#421).\n      if (!webhooks && key.startsWith('x-')) continue;\n      const item = follow(raw, 'pathItems');\n      // A webhook's request is one the SDK is sent.\n      if (item) pathItem(item, webhooks);\n    }\n  };\n  pathItems(document['paths'], false);\n  pathItems(document['webhooks'], true);\n\n  const onlySent = new Map<string, boolean>();\n  for (const key of Object.keys(schemas)) {\n    const directions = reached.get(key);\n    const name = resolveSchemaName(key);\n    onlySent.set(name, (onlySent.get(name) ?? true) && directions?.size === 1 && directions.has('sent'));\n  }\n  return new Set([...onlySent].filter(([, only]) => only).map(([name]) => name));\n}\n\n/**\n * Mark every title-mapped variant under `roots` (read as one root) whose\n * title two claims under the same roots give different shapes; see\n * `markContestedTitles` for the walk. The visited sets are this root's own:\n * a schema object another root also holds is read here as well, against\n * this root's variants. Within the root a schema is read once per claim\n * group it is reached from — a union object one group already read (its\n * title no claim there, an earlier variant having claimed it) is read again\n * under a property that starts a group of its own, where the same title is\n * a claim — and a schema that refers back to itself is stopped by the\n * ancestors on the path to it, which ends the walk. `componentSchemas`, given\n * for every root but the components', resolves the `$ref` members of an\n * `allOf` merged into one model, which is read as that model\n * (`mergedAllOfProperties`); without it every schema is read as written.\n * The merges build one object per pair of declarations they combine\n * (`combinedDeclarations`), so the guards stop at a conjunction already\n * read, however often a merge builds it again: `Note.reply`, a `$ref` to\n * `Note` beside an inline object, which every merge of `Note` conjoins\n * (workos/oagen#531: each merge built a new object that no guard had seen,\n * and the walk never ended).\n */\nfunction markContestedTitlesUnderRoot(\n  roots: readonly SchemaObject[],\n  componentSchemas?: Record<string, SchemaObject>,\n): void {\n  const byTitle = new Map<string, { shapes: Set<string>; variants: SchemaObject[] }>();\n  const visitedByGroup = new WeakMap<Set<string>, WeakSet<SchemaObject>>();\n  const ancestors = new Set<SchemaObject>();\n  // The properties of a merged `allOf`'s model, each read once: a property\n  // starts a group of its own, so a second read finds the same claims, and a\n  // chain of components each merging the next would be read once per path.\n  // A conjunction the merges build is one object within the document\n  // (`combinedDeclarations`), so it is read once too.\n  const mergedRead = new WeakSet<SchemaObject>();\n  // `claims` is the group's claim set (see `markContestedTitles`): the titles\n  // already claimed for the union this schema is reached from without\n  // entering an object. Only the first variant of a group to carry a title\n  // can keep it — a later one with the same title is stepped off it by its\n  // own union while the first keeps it (`emitted` in\n  // `nameInlineVariantEntries` within one union; the kept titles\n  // `nonObjectVariantContexts` reserves across a union's non-object\n  // variants) whatever else is in the document — so a later one's shape\n  // competes for nothing. It is still recorded, to be marked when the title\n  // is contested: the first is then qualified, and nothing steps the later\n  // one off the bare title. A schema reached any other way starts a group of\n  // its own, under which a title that was no claim in the first group is a\n  // claim of its own, so the schema is read again there (a union object a\n  // `transformSpec` reused under another property: its title keeps the bare\n  // name there, and contests the first group's).\n  const walk = (schema: SchemaObject, claims: Set<string> = new Set()): void => {\n    if (ancestors.has(schema)) return;\n    let visited = visitedByGroup.get(claims);\n    if (!visited) visitedByGroup.set(claims, (visited = new WeakSet()));\n    if (visited.has(schema)) return;\n    visited.add(schema);\n    if (schema.$ref) return;\n    // The shapes are the ones the variants are named and built with: with\n    // `properties` written beside the union folded into them\n    // (`foldSiblingProperties`). The marks go on the document's variants,\n    // which every later fold's copies are read through (`isContestedTitle`).\n    const folded = foldSiblingProperties(schema);\n    // An `allOf` merged into one model is read as that model, whatever its\n    // members hold: each property the merge settles on, a group of its own\n    // like any property, and nothing else.\n    const merged = componentSchemas && mergedAllOfProperties(folded, componentSchemas);\n    if (merged) {\n      ancestors.add(schema);\n      for (const property of merged) {\n        if (mergedRead.has(property)) continue;\n        mergedRead.add(property);\n        walk(property);\n      }\n      ancestors.delete(schema);\n      return;\n    }\n    for (const [variant, title] of titleMappedVariantNames(folded)) {\n      const entry = byTitle.get(title) ?? { shapes: new Set<string>(), variants: [] };\n      if (!claims.has(title)) {\n        claims.add(title);\n        entry.shapes.add(schemaShapeKey(variant));\n      }\n      entry.variants.push(foldedVariantOrigin(variant) ?? variant);\n      byTitle.set(title, entry);\n    }\n    // Only the keywords the parser types a schema through are walked: a union\n    // under `not`, `if`, `$defs` or any other never becomes a model, so it\n    // contests nothing. The group continues through what\n    // `mintedInlineNameEntries` reads for a union: its variants, an array's\n    // items, a map's values (whether under `additionalProperties` or\n    // `patternProperties`), and the one member of a lone `allOf`.\n    // `properties` and a longer `allOf` begin a new group.\n    ancestors.add(schema);\n    for (const [keyword, value] of Object.entries(schema)) {\n      if ((keyword === 'properties' || keyword === 'patternProperties') && isRecord(value)) {\n        const inherited = keyword === 'patternProperties' ? claims : undefined;\n        for (const sub of Object.values(value)) if (isSchemaRecord(sub)) walk(sub, inherited);\n      } else if ((keyword === 'items' || keyword === 'additionalProperties') && isSchemaRecord(value)) {\n        walk(value, claims);\n      } else if ((keyword === 'allOf' || keyword === 'oneOf' || keyword === 'anyOf') && Array.isArray(value)) {\n        const inherited =\n          keyword === 'oneOf' || keyword === 'anyOf' || (keyword === 'allOf' && value.length === 1)\n            ? claims\n            : undefined;\n        for (const sub of value) if (isSchemaRecord(sub)) walk(sub, inherited);\n      }\n    }\n    ancestors.delete(schema);\n  };\n  for (const root of roots) walk(root);\n  for (const { shapes, variants } of byTitle.values()) {\n    if (shapes.size > 1) for (const variant of variants) contestedTitledVariants.add(variant);\n  }\n}\n\n/**\n * The properties of the one model an inline `allOf` read as merged\n * (`readInlineAllOf`: `'merged'`) builds, as `mergeAllOfMembers` settles\n * them and every extractor builds the model from them: those a `$ref`\n * member's component contributes, its own `allOf` chain included; a property\n * two members declare as the one declaration the merge keeps or conjoins (a\n * `meta` both `Base` and an inline member declare carries `Base`'s\n * `meta.shape` beside the inline `meta.marker`); a property only variants\n * declare as the union of their declarations. A declaration the merge drops,\n * a union whose variants it flattens into the model, a `$ref` it does not\n * follow (one under a variant) and a union a component carries are none of\n * them. `undefined` for any other schema.\n */\nfunction mergedAllOfProperties(\n  schema: SchemaObject,\n  componentSchemas: Record<string, SchemaObject>,\n): SchemaObject[] | undefined {\n  if (!schema.allOf || readInlineAllOf(schema.allOf, schema, componentSchemas) !== 'merged') return undefined;\n  return mergeAllOfMembers(schema, componentSchemas).properties.map((p) => p.schema);\n}\n\n/**\n * The context name an array field's items (`kind: 'item'`) or a map field's\n * values (`kind: 'value'`) are typed and extracted under. By default it is\n * the field itself, so the inline model is the parent plus the singularized\n * field (`layers` on `Drawing` → `DrawingLayer`).\n *\n * When a sibling property of the same object would mint that very name —\n * `layer` as an inline object, an inline enum, an inline union with object\n * variants (any of whose variant names counts), or an array or map of such\n * (`mintedInlineNames`); a primitive `email` beside `emails` claims nothing\n * — the elements step aside to\n * `<field>_item` / `<field>_value`, which qualify to `<Parent><Field>Item` /\n * `<Parent><Field>Value` (`DrawingLayersItem`, `DrawingLayersValue`),\n * matching the `<Variant>Item` convention. Should a sibling mint that name\n * too (a property `layers_item`), the fallback keeps going the way\n * `variantMemberKeys` does for variants: `<field>_array_item`, then\n * `<field>_array_item2`, `<field>_array_item3`, ... for items\n * (`DrawingLayersArrayItem`, ...) and `<field>_member_value`,\n * `<field>_member_value2`, ... for values, taking the first candidate whose\n * minted name no sibling claims.\n *\n * Identical-shape sharing: when every sibling claiming the singular name is\n * an inline object whose shape is structurally identical to the items or\n * values (`schemaShapeKey`: same properties, required, types, nested inline\n * schemas and enum values; description, title and example ignored), the\n * fields share one model under the singular name. They are the same shape,\n * so one model is the right SDK type and a duplicate would only add noise;\n * should a later spec version make the shapes diverge, the split happens\n * then, which is the moment the item type genuinely changes. This\n * deliberately departs from a literal one-model-per-field reading for the\n * identical case.\n *\n * Only context-dependent names take part: a title-mapped variant's title\n * (`MintedInlineName.contextFree`) is the same under every context, so no\n * candidate could step away from it, and such a name is shared by design —\n * two sibling arrays whose items carry the same titled variants both\n * reference `Circle` and `Square` (`nameInlineVariants`). The search always\n * terminates: it stops as soon as a candidate changes nothing about the names\n * (`firstFreeElementContext`'s no-progress rule), and\n * `MAX_ELEMENT_CONTEXT_ATTEMPTS` caps it as a backstop; both return the last\n * candidate tried, deterministically.\n *\n * Decided from sibling names and schema content alone, so document order\n * plays no part. `schemaToTypeRef` and every extractor call this with the\n * same sibling set (`collectProperties`); otherwise the reference and the\n * model disagree.\n */\nexport function elementContextName(\n  fieldName: string,\n  kind: 'item' | 'value',\n  siblings: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n  elementSchema: SchemaObject,\n): string {\n  return elementContextDecision(fieldName, kind, siblings, parentModelName, elementSchema).context;\n}\n\n/** Why `elementContextDecision` settled on a context. */\nexport type ElementContextReason =\n  /** No sibling set: nothing to decide. */\n  | 'no-siblings'\n  /** The elements mint no context-dependent name. */\n  | 'nothing-minted'\n  /** No sibling claims any name the elements mint. */\n  | 'unclaimed'\n  /** Every claimant is an inline object of the identical shape: one model is shared. */\n  | 'shared-shape'\n  /** A later candidate mints only unclaimed names. */\n  | 'free'\n  /** The names did not change from one candidate to the next, so no candidate can avoid the claim. */\n  | 'no-progress'\n  /** `MAX_ELEMENT_CONTEXT_ATTEMPTS` candidates were tried; the last one is kept. */\n  | 'cap';\n\n/** Hard cap on the candidates `firstFreeElementContext` tries; the no-progress rule stops it long before in practice. */\nexport const MAX_ELEMENT_CONTEXT_ATTEMPTS = 256;\n\n/** `elementContextName`, with the reason it decided as it did (see `ElementContextReason`). */\nexport function elementContextDecision(\n  fieldName: string,\n  kind: 'item' | 'value',\n  siblings: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n  elementSchema: SchemaObject,\n): { context: string; reason: ElementContextReason } {\n  if (!siblings) return { context: fieldName, reason: 'no-siblings' };\n  // The names the elements would mint under a context — the context-dependent\n  // ones only, since a context-free name is shared rather than stepped from.\n  const dependentNames = (candidate: string): string[] =>\n    mintedInlineNameEntries(candidate, elementSchema, parentModelName)\n      .filter((entry) => !entry.contextFree)\n      .map((entry) => entry.name);\n  const own = dependentNames(fieldName);\n  if (own.length === 0) return { context: fieldName, reason: 'nothing-minted' };\n\n  // Every inline name the other siblings mint, with the schemas minting it.\n  const claimed = new Map<string, SchemaObject[]>();\n  for (const [siblingName, siblingSchema] of siblings) {\n    if (siblingName === fieldName) continue;\n    for (const minted of mintedInlineNames(siblingName, siblingSchema, parentModelName)) {\n      claimed.set(minted, [...(claimed.get(minted) ?? []), siblingSchema]);\n    }\n  }\n\n  const rivals = [...new Set(own.flatMap((name) => claimed.get(name) ?? []))];\n  if (rivals.length === 0) return { context: fieldName, reason: 'unclaimed' };\n  const element = unwrapNullableSchema(elementSchema);\n  const identical = (rival: SchemaObject): boolean => {\n    const sibling = unwrapNullableSchema(rival);\n    return (\n      isInlineObjectSchema(sibling) &&\n      isInlineObjectSchema(element) &&\n      schemaShapeKey(sibling) === schemaShapeKey(element)\n    );\n  };\n  if (rivals.every(identical)) return { context: fieldName, reason: 'shared-shape' };\n\n  return firstFreeElementContext(fieldName, kind, new Set(claimed.keys()), dependentNames, own);\n}\n\n/**\n * The first fallback context under which the elements mint no claimed name:\n * `<field>_item` / `<field>_value`, then `<field>_array_item` /\n * `<field>_member_value`, then `<field>_array_item2`, `…3`, ... (the way\n * `variantMemberKeys` numbers a variant's members). `mint` gives the names\n * under a candidate and `previous` those under the context tried before the\n * first candidate. The search stops with `no-progress` as soon as a\n * candidate mints the same names as the one before it — the names do not\n * depend on the context, so no candidate can avoid the claim — and with\n * `cap` after `maxAttempts` candidates; both keep the last candidate tried.\n */\nexport function firstFreeElementContext(\n  fieldName: string,\n  kind: 'item' | 'value',\n  claimed: ReadonlySet<string>,\n  mint: (candidate: string) => string[],\n  previous: readonly string[],\n  maxAttempts: number = MAX_ELEMENT_CONTEXT_ATTEMPTS,\n): { context: string; reason: ElementContextReason } {\n  const fallback = kind === 'item' ? 'array_item' : 'member_value';\n  let last = previous;\n  let candidate = fieldName;\n  for (let i = 0; i < maxAttempts; i++) {\n    candidate =\n      i === 0 ? `${fieldName}_${kind}` : i === 1 ? `${fieldName}_${fallback}` : `${fieldName}_${fallback}${i}`;\n    const minted = mint(candidate);\n    if (minted.every((name) => !claimed.has(name))) return { context: candidate, reason: 'free' };\n    if (sameNames(minted, last)) return { context: candidate, reason: 'no-progress' };\n    last = minted;\n  }\n  return { context: candidate, reason: 'cap' };\n}\n\n/** The same names, in any order. */\nfunction sameNames(a: readonly string[], b: readonly string[]): boolean {\n  if (a.length !== b.length) return false;\n  const sortedB = [...b].sort();\n  return [...a].sort().every((name, i) => name === sortedB[i]);\n}\n\n/**\n * Every property the object described by `schema` exposes, by name: its own\n * `properties`, those of its `allOf` members (following a member's `$ref`\n * into `schemas` when given, as `extractAllOfModel` does), those of the\n * component a schema that is itself a bare `$ref` names — a component alias\n * (`CatAlias: { $ref: Cat }`), read as `allOf: [{ $ref: Cat }]` is (#618),\n * followed through a chain of aliases when `schemas` is given, so the\n * alias's fields are typed with `Cat`'s sibling set; nothing written\n * beside a `$ref` is read, as anywhere — those of a\n * nullable `oneOf`/`anyOf` wrapper's one non-null variant, read as the\n * member it wraps (`nullableAxisBranch`, per keyword, the definition the\n * model walks resolve a member by, so a nullable `$ref` member's component\n * is followed here as `mergeAllOfMembers` and `readComponentAllOfMember`\n * follow it, and an `anyOf` beside a nullable `oneOf` is read too), and\n * those of every other `oneOf`/`anyOf` variant, a `$ref` variant's\n * component followed when `schemas` is given, whose fields the model\n * extractors flatten in (`declareVariant`) — in the order first declared,\n * each name with the declaration `declareProperty`'s precedence picks: the\n * first always-applying one, else the union of the variants' declarations\n * (`unionOfDeclarations`, as `declaredComponentProperty` and the merge\n * type such a field). This is the sibling set `elementContextName` decides\n * from; the TypeRef builder and every extractor derive it through this one\n * function so they agree.\n */\nexport function collectProperties(\n  schema: SchemaObject,\n  schemas?: Record<string, SchemaObject>,\n): Map<string, SchemaObject> {\n  const ledger = new Map<string, PropertyDeclarations>();\n  const seen = new Set<SchemaObject>();\n  const visit = (s: SchemaObject | undefined, onBranch: boolean): void => {\n    if (!s || seen.has(s)) return;\n    seen.add(s);\n    if (s.$ref) {\n      // A `$ref` — the root's own, a member's, a variant's — is followed\n      // into `schemas` when given, and nothing written beside it is read,\n      // as beside any `$ref` (#618).\n      if (schemas) visit(schemaRefTarget(s.$ref, schemas), onBranch);\n      return;\n    }\n    for (const [key, value] of Object.entries(s.properties ?? {})) {\n      if (value) declareProperty(ledger, key, value, null, onBranch);\n    }\n    for (const sub of s.allOf ?? []) visit(sub, onBranch);\n    for (const axis of unionAxesOf(s)) {\n      // A nullable wrapper is its one variant, decided per keyword\n      // (`nullableAxisBranch`); a variant's `$ref` is followed as the merges\n      // follow it (`declareVariant`).\n      const branch = nullableAxisBranch(s, axis);\n      if (branch) visit(branch, onBranch);\n      else for (const variant of axis) visit(variant, true);\n    }\n  };\n  // The root's own `$ref` is followed as a member's is: the root is a\n  // component alias, read as the `allOf` of that reference (#618).\n  visit(schema, false);\n  return new Map(\n    [...ledger.values()].map((entry) => [\n      entry.name,\n      entry.unconditional?.schema ?? unionOfDeclarations(entry.conditional),\n    ]),\n  );\n}\n\n/**\n * Walk all component schemas and extract inline Model definitions for fields\n * that are objects with properties, including objects reached through array\n * items, `oneOf` variants, and map (`additionalProperties` /\n * `patternProperties`) values.\n * These correspond to the ModelRef entries created by schemaToTypeRef.\n */\nexport function extractInlineModelsFromSchemas(\n  schemas: Record<string, SchemaObject> | undefined,\n  groups?: FieldInlineModelGroup[],\n): Model[] {\n  if (!schemas) return [];\n\n  const inlineModels: Model[] = [];\n  for (const [schemaName, schema] of Object.entries(schemas)) {\n    extractComponentFieldModels(schemaName, schema, schemas, inlineModels, groups);\n  }\n  return inlineModels;\n}\n\n/**\n * The inline models the fields of one component schema (`key`) mint, into\n * `results`: for every field of its model — the declaration\n * `componentPropertyLedger` chose for it, the component's own, one\n * inherited through a `$ref` member, or a branch's when no member always\n * declares the field — everything the field's type reaches (an inline\n * object, array items, map values, a union's variants, under a nullable\n * wrapper, at any depth), through the field extractor\n * (`extractInlineModelsFromProperties`), under the component's name with the\n * sibling set its fields were typed with. The one path through which the\n * field pass (`extractInlineModelsFromSchemas`, run by `parseSpec` on every\n * component) builds a component field's nested models, so a model is built\n * exactly when a component's field references it — `Puppy.meta`, inherited\n * from `Dog` and typed `PuppyMeta` under `Puppy`, has its `PuppyMeta`, and\n * the values of an inherited map their model (workos/oagen#359 review: an\n * inherited map's values were typed but never built, since the field pass\n * walked only the inline declarations and the nested-model backstop of\n * `extractSchemas` follows a reference only into an array or a union). One\n * field at a time, in field order, so the models each field\n * produced are known (`groups`) and the merge pass can rename one by the\n * field that references it. Every call sees the same siblings, reserved\n * names and results list, so the names are exactly those one call over\n * the whole schema would mint.\n */\nexport function extractComponentFieldModels(\n  key: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  results: Model[],\n  groups?: FieldInlineModelGroup[],\n): void {\n  const parentName = resolveSchemaName(key);\n  // The same sibling set `extractModel` / `extractAllOfModel` type the\n  // component's fields from, `$ref`'d allOf members included.\n  const siblings = collectProperties(schema, schemas);\n  for (const entry of componentPropertyLedger(parentName, schema, schemas).values()) {\n    const before = results.length;\n    extractInlineModelsFromProperties(\n      { properties: { [entry.name]: declaredComponentProperty(entry) } },\n      results,\n      parentName,\n      schemas,\n      siblings,\n    );\n    groups?.push({ parentName, fieldName: entry.name, models: results.slice(before) });\n  }\n}\n\n/**\n * Where a group of inline models came from, so a copy that must give up a\n * name it shares with a differently flagged or differently shaped model can\n * be renamed and exactly its own references repointed (see\n * `settleSharedNames` in the merge passes). `qualifier` is prefixed to the\n * new name — for an operation's bodies and list-envelope companions, the\n * stem they are named from: its `operationId`'s, cleaned as its `…Request`\n * model name is (`UserList` for `users.list`), or without one the\n * path-derived prefix (`PetsByIdLegacyWidgetGet`), never the operation's\n * name; for a component field's, the component name; `roots`\n * are the type references the site owns — an operation's response, its\n * request body, a component field's type; `models` are the models the site\n * produced, whose fields reference one another. Renaming one of `models`\n * repoints `roots` and the other models' fields, and nothing outside the\n * bundle, so a `$ref` to a same-named component elsewhere in the document is\n * never touched.\n */\nexport interface InlineModelBundle {\n  qualifier: string;\n  roots: TypeRef[];\n  models: Model[];\n  /**\n   * Told of every rename of one of `models`, for a site whose references are\n   * copied after it is settled — a component field's, whose inline model an\n   * operation's or webhook's `allOf` merge copies a reference to\n   * (`recordFieldModelRename`). Absent for a site nothing copies from.\n   */\n  renamed?: (from: string, to: string) => void;\n  /**\n   * Set when the site's models are what the SDK sends — an operation's\n   * request body, primary or secondary, an inline parameter, or a field of\n   * a component only those reach (`sentOnlyComponentNames`,\n   * `fieldInlineModelBundles`) — so a component shares a name with one of\n   * them only on an identical shape (`settleSharedNames`, as `ownerShares`\n   * decides for the registry): typed as a looser component, a caller could\n   * leave out what the operation requires. Absent for a shape the SDK\n   * receives — a response body or header, a webhook's payload or\n   * parameter — and for the field of any other component, one a received\n   * site reaches or no site does, whose direction the document does not say.\n   */\n  sent?: boolean;\n  /**\n   * The sites of the copies that folded onto one of `models` (`foldOnto` in\n   * the merge passes), each keyed to the model it folded onto (`owner`): the\n   * copy's references name the owner from then on, so when the owner is\n   * renamed — and only then, by the owner's identity, never by name — the\n   * references in those roots and models that carry the owner's name are\n   * repointed with the site's own (`repointSite`). A rename of another model\n   * of this site leaves them alone: a model of the carried site under that\n   * name is that site's own, decided on its own. Absent until a copy folds\n   * onto one of `models`.\n   */\n  carried?: CarriedSite[];\n}\n\n/** One copy's site, carried into the site of the model it folded onto (`InlineModelBundle.carried`). */\nexport interface CarriedSite {\n  owner: Model;\n  roots: TypeRef[];\n  models: Model[];\n}\n\n/**\n * The inline models one component field produced: `fieldName` of the\n * component resolved to `parentName`. `extractInlineModelsFromSchemas` fills\n * one per field; `fieldInlineModelBundles` turns it into an\n * `InlineModelBundle` once the field's type can be looked up.\n */\nexport interface FieldInlineModelGroup {\n  parentName: string;\n  fieldName: string;\n  models: Model[];\n}\n\n/**\n * Every `ModelRef` an `allOf` merge copied from a referenced component's own\n * property (`buildMergedModel`): `Holder.ext: allOf: [{ $ref: Base }, …]`\n * types the merged model's `meta` exactly as `Base.meta` is typed, so its\n * reference names the inline model `Base.meta` produced. Such a reference\n * belongs to that component field's site, not to the site of the model it\n * sits in: when the merge passes rename the model `Base.meta` produced, the\n * references recorded under `Base.meta` are repointed with the field's own\n * (`fieldInlineModelBundles`), and no other site's rename touches them\n * (`isInheritedModelRef`). An explicit `$ref` among the copied references is\n * a component reference and is not recorded. Reset per document by\n * `extractSchemas`.\n */\n/** Each inherited reference, keyed to the `Parent.field` it was copied from, so a copy of it (`cloneTypeRef`) can be recorded under the same field. */\nconst inheritedModelRefs = new WeakMap<ModelRef, string>();\nconst inheritedModelRefsByField = new Map<string, ModelRef[]>();\n/**\n * The renames the merge passes have applied to the inline models of each\n * component field (`settleFieldInlineModels`, before any operation or\n * webhook is read), keyed `Parent.field`, so a reference an `allOf` merge\n * copies from the field afterwards (`recordInheritedModelRefs`) — typed from\n * the schema, which still mints the original name — is created under the\n * settled name. Reset per document with the inherited references.\n */\nconst fieldModelRenames = new Map<string, Map<string, string>>();\n\n/** Record that the inline model `from` of `fieldName` of the component resolved to `parentName` is now named `to`. */\nexport function recordFieldModelRename(parentName: string, fieldName: string, from: string, to: string): void {\n  const key = `${parentName}.${fieldName}`;\n  const renames = fieldModelRenames.get(key) ?? new Map<string, string>();\n  renames.set(from, to);\n  fieldModelRenames.set(key, renames);\n}\n\n/** Whether `ref` was copied from a component's property by an `allOf` merge (see `inheritedModelRefsOf`). */\nexport function isInheritedModelRef(ref: ModelRef): boolean {\n  return inheritedModelRefs.has(ref);\n}\n\n/** The references `allOf` merges copied from `fieldName` of the component resolved to `parentName`. */\nexport function inheritedModelRefsOf(parentName: string, fieldName: string): ModelRef[] {\n  return inheritedModelRefsByField.get(`${parentName}.${fieldName}`) ?? [];\n}\n\n/**\n * The models the schema pass lifts from a component field's own inline\n * schema (`collectNestedInlineModels` in `extractSchemas`: a nested object,\n * array items or a union variant, named as the field extractor names them),\n * keyed `Parent.field` by the field each was read from. The field's site\n * claims them by that origin (`fieldInlineModelBundles`), never by name:\n * `Foo.barThing` and `FooBar.thing` both spell `FooBarThing`, only one of\n * them is lifted, and the other field's site must not touch it. Reset per\n * document with the inherited references.\n */\nconst liftedFieldModels = new Map<string, Model[]>();\n\n/** Record that the schema pass lifted `model` from `fieldName` of the component resolved to `parentName`. */\nexport function recordLiftedFieldModel(parentName: string, fieldName: string, model: Model): void {\n  const key = `${parentName}.${fieldName}`;\n  const lifted = liftedFieldModels.get(key) ?? [];\n  lifted.push(model);\n  liftedFieldModels.set(key, lifted);\n}\n\n/** The models the schema pass lifted from `fieldName` of the component resolved to `parentName`, in the order it lifted them. */\nexport function liftedFieldModelsOf(parentName: string, fieldName: string): Model[] {\n  return liftedFieldModels.get(`${parentName}.${fieldName}`) ?? [];\n}\n\n/** Forget every inherited reference, field-model rename and lifted field model recorded so far: a new document is being read. */\nexport function resetInheritedModelRefs(): void {\n  inheritedModelRefsByField.clear();\n  fieldModelRenames.clear();\n  liftedFieldModels.clear();\n}\n\nfunction recordInheritedModelRefs(type: TypeRef, parentName: string, fieldName: string): void {\n  const key = `${parentName}.${fieldName}`;\n  // A copy made after the field's models were settled names them as the\n  // schema does; it is moved to the settled names first, every reference\n  // minted for an inline model and never an explicit `$ref`.\n  const renames = fieldModelRenames.get(key);\n  if (renames) renameTypeRefModels(type, renames, (ref) => !isComponentModelRef(ref));\n  walkTypeRef(type, {\n    model: (ref) => {\n      if (!isComponentModelRef(ref)) recordInheritedRef(ref, key);\n    },\n  });\n}\n\nfunction recordInheritedRef(ref: ModelRef, key: string): void {\n  inheritedModelRefs.set(ref, key);\n  const refs = inheritedModelRefsByField.get(key) ?? [];\n  refs.push(ref);\n  inheritedModelRefsByField.set(key, refs);\n}\n\n/**\n * The one way to copy a built type reference. Every pass keys a reference's\n * provenance by its identity — a `$ref` to a component\n * (`isComponentModelRef`), a reference an `allOf` merge copied from a\n * component's field (`isInheritedModelRef`), an inline enum's members and\n * link (`inlineEnumRef`) — so a structural copy (`structuredClone`, a\n * spread) silently turns a component reference into one a merge pass may\n * repoint, drops an inherited reference from its field's site, and leaves an\n * inline enum a bare name to the lift. A copy made here carries every mark\n * its original has: the component mark, the inherited record under the same\n * field, the enum's members and link; a union's mapping is copied with its\n * variants. For a type copied to a second owner — a webhook sharing a path\n * item's minting (`extractWebhooks`). A copy made only to be serialized for\n * comparison, after its flags are spelled out (`foldedVariantKey`), needs\n * none of this.\n */\nexport function cloneTypeRef(ref: TypeRef): TypeRef {\n  switch (ref.kind) {\n    case 'model': {\n      const copy: ModelRef = { ...ref };\n      if (isComponentModelRef(ref)) markComponentModelRef(copy);\n      if (isPendingSchemaRef(ref)) {\n        markPendingSchemaRef(copy);\n        recordPendingSiteLimits(copy, pendingSiteLimitsOf(ref));\n      }\n      const key = inheritedModelRefs.get(ref);\n      if (key !== undefined) recordInheritedRef(copy, key);\n      return copy;\n    }\n    case 'enum': {\n      const copy: EnumRef = { ...ref, ...(ref.values ? { values: [...ref.values] } : {}) };\n      copyInlineEnumMeta(ref, copy);\n      return copy;\n    }\n    case 'array':\n      return { ...ref, items: cloneTypeRef(ref.items) };\n    case 'nullable':\n      return { ...ref, inner: cloneTypeRef(ref.inner) };\n    case 'map':\n      return {\n        ...ref,\n        valueType: cloneTypeRef(ref.valueType),\n        ...(ref.keyType ? { keyType: cloneTypeRef(ref.keyType) } : {}),\n      };\n    case 'union': {\n      const copy: UnionType = {\n        ...ref,\n        variants: ref.variants.map(cloneTypeRef),\n        ...(ref.discriminator\n          ? { discriminator: { ...ref.discriminator, mapping: { ...ref.discriminator.mapping } } }\n          : {}),\n      };\n      // A mapping entry deferred to a pointer variant (#539) follows the\n      // variant's copy, and one deferred to a reference of its own target's\n      // (#619) a copy of that reference, so the copy's mapping is settled\n      // with the copy's own references.\n      if (ref.discriminator && copy.discriminator) {\n        carryDeferredMappingEntries(\n          { variants: ref.variants, mapping: ref.discriminator.mapping },\n          { variants: copy.variants, mapping: copy.discriminator.mapping },\n          cloneTypeRef,\n        );\n      }\n      return copy;\n    }\n    case 'literal':\n    case 'primitive':\n      return { ...ref };\n    default:\n      return assertNeverRef(ref);\n  }\n}\n\n/**\n * Make `target` the type `source` is, in place — for a reference settled\n * where it is held (`resolveSchemaPointers`; #539): a field, a body, a\n * parameter, an array's items keep the object they hold, so the type is\n * written into it. The copy is made as `cloneTypeRef` makes one, so every\n * mark rides along: the nested nodes are the copy's own, and a mark on the\n * copy's root — the component mark, an inherited record, an inline enum's\n * members and link — is set on `target`, which takes the root's place.\n */\nexport function replaceTypeRef(target: TypeRef, source: TypeRef): void {\n  const copy = cloneTypeRef(source);\n  const slot = target as unknown as Record<string, unknown>;\n  for (const key of Object.keys(slot)) delete slot[key];\n  Object.assign(slot, copy);\n  if (copy.kind === 'model') {\n    if (isComponentModelRef(copy)) markComponentModelRef(target as ModelRef);\n    const key = inheritedModelRefs.get(copy);\n    if (key !== undefined) recordInheritedRef(target as ModelRef, key);\n  } else if (copy.kind === 'enum') {\n    copyInlineEnumMeta(copy, target as EnumRef);\n  }\n}\n\nfunction assertNeverRef(ref: never): never {\n  throw new Error(`Unhandled type reference: ${JSON.stringify(ref)}`);\n}\n\n/**\n * Walk a schema's properties and materialise every inline object as a model.\n * `componentSchemas` is optional and only feeds `buildFieldFromSchema`, so a\n * field that `$ref`s a component can take its `example`/`examples` from it;\n * callers without the component map at hand simply omit it.\n * `siblingProperties` is the parent object's full property set, for callers\n * that see more of it than this schema shows (see `elementContextName`).\n * `reservedNames` is set only on the re-entry for a field's array items or\n * map values: the inline names that field's siblings mint, which a union\n * among the items or values must step around exactly as `schemaToTypeRef`\n * does when it hands the same set down (`reservedNamesFor`).\n *\n * The recursion follows the document's own inline structure only: a `$ref`\n * is resolved solely to read a component's property list for typing (an\n * augmentation's inherited fields, a sibling set), never descended into, so\n * the depth is bounded by the document's inline nesting and no component\n * graph — self-extending, mutually extending, or reused at several levels —\n * can make it run away.\n */\nexport function extractInlineModelsFromProperties(\n  schema: SchemaObject,\n  results: Model[],\n  parentName?: string,\n  componentSchemas?: Record<string, SchemaObject>,\n  siblingProperties?: ReadonlyMap<string, SchemaObject>,\n  reservedNames?: ReadonlySet<string>,\n): void {\n  const properties = schema.properties ?? {};\n  const allOfSchemas = schema.allOf ?? [];\n  // Every property the parent object exposes, so array items and map values\n  // can step aside from a sibling that would mint their name (see\n  // `elementContextName`). A caller that sees more siblings than this schema\n  // shows — an `allOf` member, an envelope field — passes them in.\n  const siblings = siblingProperties ?? collectProperties(schema);\n  // The names a union under `fieldName` must not take: the set handed down\n  // for array items / map values, else what the field's siblings mint.\n  const reservedFor = (fieldName: string): ReadonlySet<string> =>\n    reservedNames ?? reservedInlineNames(fieldName, siblings, parentName);\n\n  for (const sub of allOfSchemas) {\n    if (sub.properties) {\n      extractInlineModelsFromProperties(sub, results, parentName, componentSchemas, siblings, reservedNames);\n    }\n  }\n\n  for (const [fieldName, rawFieldSchema] of Object.entries(properties)) {\n    if (!rawFieldSchema) continue;\n    // Dispatch on the shape `schemaToTypeRef` named: it strips nullable\n    // wrappers before deciding whether a field is an object, array, or map,\n    // so a nullable field must be unwrapped here the same way or its inline\n    // object / array items / map values are referenced but never extracted.\n    const fieldSchema = unwrapNullableField(rawFieldSchema);\n    // One keyword types the field (`classifyInlineSchema`, the order\n    // `schemaToTypeRef` follows), so exactly one branch below runs and the\n    // models it builds are the ones the field's type references: a schema\n    // carrying both `items` and `oneOf` yields the union's variants, never an\n    // item model under a variant's name.\n    const kind = classifyInlineSchema(fieldSchema);\n    // Direct inline object with properties (with or without explicit type: 'object',\n    // including the nullable `type: ['object', 'null']` form)\n    if (kind === 'object') {\n      const baseName = toPascalCase(fieldName);\n      const modelName = qualifyInlineModelName(baseName, parentName);\n      results.push(buildInlineModel(modelName, fieldSchema, componentSchemas));\n      extractInlineModelsFromProperties(fieldSchema, results, modelName, componentSchemas);\n    }\n\n    // Array: schemaToTypeRef types the items with the field's own context\n    // name and parent, so every inline model reachable through the items — a\n    // plain inline object, the variants of an `items.oneOf`, a nested array\n    // or map — is named exactly as if the items schema were the field itself\n    // (`shapes` → `CreateDrawingRequestShape`, `SquareCreateDrawingRequestShape`).\n    // Re-enter with a synthetic property named by `elementContextName` — the\n    // field itself, or `<field>_item` when a sibling would take the singular\n    // name — so the branches in this function do the extraction with\n    // byte-for-byte identical naming.\n    const arrayItems = kind === 'array' ? fieldSchema.items : undefined;\n    if (arrayItems) {\n      const itemContext = elementContextName(fieldName, 'item', siblings, parentName, arrayItems);\n      extractInlineModelsFromProperties(\n        { properties: { [itemContext]: arrayItems } },\n        results,\n        parentName,\n        componentSchemas,\n        undefined,\n        reservedFor(fieldName),\n      );\n    }\n\n    // Map (`additionalProperties` / `patternProperties` on a property-less\n    // object): schemaToTypeRef types the values the same way it types array\n    // items, so a map of inline objects references `${Parent}${SingularField}`\n    // (`layers` on `CreateDrawingRequest` → `CreateDrawingRequestLayer`), or\n    // `<Parent><Field>Value` when a sibling takes the singular name. Re-enter\n    // with the value schema as a synthetic property of that name.\n    if (kind === 'map') {\n      const valueSchema = mapValueSchema(fieldSchema);\n      if (valueSchema) {\n        const valueContext = elementContextName(fieldName, 'value', siblings, parentName, valueSchema);\n        extractInlineModelsFromProperties(\n          { properties: { [valueContext]: valueSchema } },\n          results,\n          parentName,\n          componentSchemas,\n          undefined,\n          reservedFor(fieldName),\n        );\n      }\n    }\n\n    // A field expressed via `allOf`, read as `schemaToTypeRef` reads it\n    // (`readInlineAllOf`, the one decision):\n    //  - `'merged'` — a `$ref` member plus an inline object member\n    //    (`isInlineAllOfMember`), or several inline members one of which\n    //    declares properties inline (`declaresInlineProperties`): the field\n    //    is typed as the model `<Parent><Field>`; merge the referenced\n    //    component(s) and the inline members into that model\n    //    (`materializeMergedAllOf`), with every inherited property typed\n    //    under its component — `Base.meta` stays `BaseMeta`, a\n    //    self-reference `Base.child` stays `BaseChild` — and only the inline\n    //    members' own properties, a variant's included, qualified under the\n    //    merged model and recursed into. The component pass already\n    //    materialized whatever the inherited properties reference, so nothing\n    //    is duplicated; a component that extends itself through a field\n    //    simply points back at a model that exists, and a component reused by\n    //    several nested augmentations hands each of them its full field\n    //    list. The model is built whatever fields the merge yields, since the\n    //    reference that names it exists;\n    //  - `'unwrapped'` — a single non-`$ref` member: typed as the field\n    //    itself, so re-enter with it as the field (same siblings);\n    //  - `'reference'` — `$ref` members only: a plain reference to the first\n    //    component, nothing to materialize.\n    if (kind === 'allOf' && fieldSchema.allOf) {\n      const reading = readInlineAllOf(fieldSchema.allOf, fieldSchema, componentSchemas);\n      if (reading === 'merged') {\n        const modelName = qualifyInlineModelName(toPascalCase(fieldName), parentName);\n        materializeMergedAllOf(modelName, fieldSchema, results, componentSchemas);\n      } else if (reading === 'unwrapped') {\n        // Re-enter with the member as the field (same siblings), carrying the\n        // wrapper's limits, flag and link (`unwrappedAllOfMember`).\n        extractInlineModelsFromProperties(\n          { properties: { [fieldName]: unwrappedAllOfMember(fieldSchema) } },\n          results,\n          parentName,\n          componentSchemas,\n          siblings,\n          reservedNames,\n        );\n      }\n    }\n\n    // oneOf/anyOf containing objects — extract every inline object variant as a\n    // model so each gets its own typed class, under the names the union\n    // TypeRef references them by (`nameInlineVariants`, the one place that\n    // decides them): variant 0 keeps the bare qualified inline name\n    // (`ApiKeyCreatedDataOwner`), later variants take their const-\n    // discriminator value (`UserApiKeyCreatedDataOwner`), their title, a\n    // distinguishing property (`DrawingShapeWithSide`) or, for identical\n    // property sets, the position counter — never a name a sibling property\n    // mints (`reservedInlineNames`), nor a title another shape takes under\n    // the same root (`isContestedTitle`), so no variant overwrites another\n    // field's model.\n    const unionVariants = kind === 'union' ? (fieldSchema.oneOf ?? fieldSchema.anyOf) : undefined;\n    if (unionVariants) {\n      const inlineObjectVariants = unionVariants.filter((v) => isInlineObjectSchema(v));\n      // Decided once, for the object variants' models and for the collection\n      // contexts, which step around those models' children.\n      const variantNames: ReadonlyMap<SchemaObject, string> =\n        inlineObjectVariants.length > 0\n          ? nameInlineVariants(\n              fieldSchema,\n              qualifyInlineModelName(toPascalCase(fieldName), parentName),\n              reservedFor(fieldName),\n            )\n          : new Map();\n      if (inlineObjectVariants.length > 0) {\n        const existingByName = new Map(results.map((r) => [r.name, r]));\n        for (const variant of inlineObjectVariants) {\n          const variantName = variantNames.get(variant);\n          if (variantName === undefined) continue;\n          const existing = existingByName.get(variantName);\n          if (existing) {\n            // The name is already in `results`: a context-free title shared\n            // by a variant of the identical shape — the one case the naming\n            // rules let two variants take one name — references the model\n            // already built. Anything else is a clash the naming rules did\n            // not reach (a title coinciding with another field's model, two\n            // roots read into one list), and the union's reference will\n            // resolve to the model that keeps the name, so say so rather\n            // than drop the variant silently.\n            warnOnVariantNameClash(existing, variant, variantName, parentName, componentSchemas, results);\n            continue;\n          }\n          const model = buildInlineModel(variantName, variant, componentSchemas);\n          existingByName.set(variantName, model);\n          results.push(model);\n          extractInlineModelsFromProperties(variant, results, variantName, componentSchemas);\n          // A multi-type variant (`type: ['object', 'array']`) types the\n          // items of its array member under the variant's name\n          // (`<Variant>Item`, see `variantMemberSchemas`); re-enter with\n          // them as a same-named synthetic property so the models line up.\n          extractInlineModelsFromProperties(\n            { properties: variantMemberSchemas(variant, variantName) },\n            results,\n            variantName,\n            componentSchemas,\n          );\n        }\n      }\n      // Every other variant that mints a name is typed under the context\n      // `nonObjectVariantContexts` gives it — `<field>_item` / `<field>_value`\n      // for an array or map; the field itself or `<field>_variant_<n>` for a\n      // nested union, a nullable wrapper around an object, an `allOf`, an\n      // inline enum — apart from the object variants' and each other's names,\n      // so whatever it mints is extracted the same way: re-entered as a\n      // property of that name, the branches above materialize it exactly as\n      // the reference names it (`ReqShapesItem` for a `shapes` variant's\n      // items; `ReqShapeVariant2`, `BReqShapeVariant2` for the inline object\n      // variants of a union nested under the second variant). The context\n      // already stepped around the siblings; the re-entry sees none, exactly\n      // as `schemaToTypeRef` types the variant.\n      for (const [variant, { context, reserved }] of nonObjectVariantContexts(\n        fieldName,\n        unionVariants,\n        siblings,\n        parentName,\n        variantNames,\n        reservedNames,\n      )) {\n        const member = unwrapNullableField(variant);\n        extractInlineModelsFromProperties(\n          { properties: { [context]: member } },\n          results,\n          parentName,\n          componentSchemas,\n          undefined,\n          reserved,\n        );\n      }\n    }\n  }\n}\n\n/**\n * Warn when a union variant named `variantName` finds a model of that name\n * already in the results list and the two are not the same shape: the\n * variant is not extracted, and the union's reference resolves to the model\n * that keeps the name. The comparison is between the models themselves —\n * the one in the list, however it was built (an ordinary object, an `allOf`\n * merge, a variant), and the one the variant would have produced, with the\n * nested models each would build — by `deepModelFingerprint`, so a `detail`\n * that is `{ radius }` under the first and `{ diameter }` under the variant\n * counts as a different shape although both parents reference one\n * `DrawingCircleDetail`, and an ordinary object of exactly the variant's\n * shape, nested models included, shares the name silently, as a sibling\n * variant of the identical shape does. The warning names the nested models\n * that differ when the parents' own fields agree. Once per variant, since\n * each is visited once.\n */\nfunction warnOnVariantNameClash(\n  existing: Model,\n  variant: SchemaObject,\n  variantName: string,\n  parentName: string | undefined,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  results: readonly Model[],\n): void {\n  const candidate = buildInlineModel(variantName, variant, componentSchemas);\n  const built: Model[] = [candidate];\n  extractInlineModelsFromProperties(variant, built, variantName, componentSchemas);\n  if (deepModelFingerprint(existing, results) === deepModelFingerprint(candidate, built)) return;\n  const fieldList = (model: Model): string => model.fields.map((f) => f.name).join(', ') || '(no fields)';\n  const site = parentName ? ` under ${parentName}` : '';\n  const differing =\n    modelFingerprint(existing) === modelFingerprint(candidate)\n      ? `; nested models differ: ${differingNestedModels(existing, results, candidate, built).join(', ')}`\n      : '';\n  console.warn(\n    `[oagen] Warning: Inline model \"${variantName}\" is minted twice with different shapes${site} ` +\n      `(fields: ${fieldList(existing)} | ${fieldList(candidate)}${differing}) ` +\n      `— keeping the first; the second union's reference resolves to it`,\n  );\n}\n\n/**\n * `modelFingerprint` of `model` extended with the deep fingerprint of every\n * inline model its fields and variants reference, read from `models`, the\n * list it was built into — so two models of the same fields whose nested\n * models differ compare as different shapes. A referenced name no model in\n * the list defines is a component's and stays a name, the same on both\n * sides; a model that reaches itself is read once per path. Sorted by name,\n * so field order plays no part here either.\n */\nexport function deepModelFingerprint(model: Model, models: readonly Model[]): string {\n  const byName = new Map(models.map((m) => [m.name, m]));\n  const visiting = new Set<string>();\n  const deep = (m: Model): string => {\n    visiting.add(m.name);\n    const nested = [...new Set(collectModelTypeRefs(m).flatMap((ref) => collectModelRefs(ref)))].sort().map((name) => {\n      const referenced = byName.get(name);\n      return referenced && !visiting.has(name) ? `${name}=${deep(referenced)}` : name;\n    });\n    visiting.delete(m.name);\n    return `${modelFingerprint(m)}@{${nested.join(',')}}`;\n  };\n  return deep(model);\n}\n\n/** The names of the inline models `a` and `b` reference, directly or below, whose deep fingerprints differ or that only one side defines; sorted. */\nfunction differingNestedModels(a: Model, aModels: readonly Model[], b: Model, bModels: readonly Model[]): string[] {\n  const reachable = (model: Model, models: readonly Model[]): Map<string, string> => {\n    const byName = new Map(models.map((m) => [m.name, m]));\n    const found = new Map<string, string>();\n    const visit = (m: Model): void => {\n      for (const name of collectModelTypeRefs(m).flatMap((ref) => collectModelRefs(ref))) {\n        const referenced = byName.get(name);\n        if (!referenced || found.has(name)) continue;\n        found.set(name, deepModelFingerprint(referenced, models));\n        visit(referenced);\n      }\n    };\n    visit(model);\n    return found;\n  };\n  const left = reachable(a, aModels);\n  const right = reachable(b, bModels);\n  const names = new Set([...left.keys(), ...right.keys()]);\n  return [...names].filter((name) => left.get(name) !== right.get(name)).sort();\n}\n\n/** One property of a merged inline `allOf` and the component it is inherited from (null: an inline member's own). */\nexport interface MergedProperty {\n  name: string;\n  schema: SchemaObject;\n  origin: { name: string; schema: SchemaObject } | null;\n  /** `true` when only `oneOf`/`anyOf` variants declare it: it holds on a branch, not on every instance. */\n  conditional?: true;\n}\n\n/** An inline `allOf` read as one object shape; see `mergeAllOfMembers`. */\nexport interface MergedAllOf {\n  /** Every property the members declare, each name once, in the order first declared. */\n  properties: MergedProperty[];\n  /** The wrapper's `required` and every always-applying member's, in order; a variant's is not read. */\n  required: string[];\n  /** The `$ref` members a component schema answered, each once, in order (a member's component chain included). */\n  resolvedRefs: string[];\n  /** The `$ref` members no component schema answers, each once, in order; they contribute nothing. */\n  unresolvedRefs: string[];\n  /** The wrapper layer's text (`allOfWrapperLayer`): the wrapper's own, else the first annotating member's — a member that declares no type (#555 review); a typing member's stays on that member, a `$ref` member's on its component. */\n  description: string | undefined;\n  /** The wrapper layer's link, read like its description. */\n  externalDocs: ExternalDocs | undefined;\n  /** The wrapper's own limits conjoined with its inline members' (a `$ref` member contributes only its sibling keywords). */\n  constraints: Constraints | undefined;\n  /** `true` when the wrapper itself, or an annotating member, says `deprecated: true`; a typing member's flag is not read (a `$ref` member's stays on its model). */\n  deprecated: boolean | undefined;\n  /** The wrapper layer's extensions (`extensionsOf`), read like its link; a typing member's stay on that member, a `$ref` member's on its component. */\n  extensions: Extensions | undefined;\n}\n\n/**\n * Whether a schema declares object properties inline: `properties` of its\n * own, or — through a nested `allOf` member or a `oneOf`/`anyOf` variant —\n * a schema that does. A `$ref` declares none here, whatever its component\n * holds: it is a reference, and the component keeps its own fields.\n *\n * This is the question every site that reads an inline `allOf` asks of a\n * member — `allOfTypesSchema` (through `classifyInlineSchema`),\n * `schemaToTypeRef`, `mintedInlineNameEntries` and\n * `extractInlineModelsFromProperties` — so they agree on whether the `allOf`\n * mints a merged model: a member written as `{ oneOf: [{ properties: … },\n * …] }` carries fields `mergeAllOfMembers` reads, so it counts exactly as a\n * member written as `{ properties: … }` does (workos/oagen#283: it did not,\n * and `allOf: [{ $ref }, { oneOf: […] }]` was typed as the bare reference\n * while the variants' fields were dropped).\n */\nexport function declaresInlineProperties(schema: SchemaObject): boolean {\n  const seen = new Set<SchemaObject>();\n  // `onBranch`: under a variant of a union of two or more non-null\n  // variants, where a `$ref` declares what its component declares — the\n  // merge flattens the component's properties in (`declareVariant`), so\n  // `allOf: [{ $ref: Pet }, { oneOf: [{ $ref: Owner }, { $ref: Shelter }]\n  // }]` is the merged model, not a bare reference to `Pet` with the union\n  // dropped (#398). A nullable wrapper is no union, nor is a union of one\n  // variant: each is read as its one variant, as the type builder reads it\n  // (`nullableAxisBranch`, per keyword; `loneUnionVariant`), so `{ oneOf: [{\n  // $ref: PetId }], nullable: true }` beside a `description` stays the\n  // reference (#555).\n  const declares = (s: SchemaObject, onBranch: boolean): boolean => {\n    if (seen.has(s)) return false;\n    seen.add(s);\n    if (s.$ref) return onBranch;\n    if (s.properties) return true;\n    if ((s.allOf ?? []).some((sub) => declares(sub, onBranch))) return true;\n    return unionAxesOf(s).some((axis) => {\n      const branch = nullableAxisBranch(s, axis);\n      if (branch) return declares(branch, onBranch);\n      const variants = axis.filter((variant) => !isNullSchema(variant));\n      return variants.some((variant) => declares(variant, onBranch || variants.length > 1));\n    });\n  };\n  return declares(schema, false);\n}\n\n/**\n * Whether an `allOf` member is an inline object member — one that, beside a\n * `$ref` member, makes the `allOf` an augmentation model rather than a plain\n * reference (`schemaToTypeRef`): not a `$ref`, and either `type: 'object'`\n * or declaring properties inline (`declaresInlineProperties`).\n */\nexport function isInlineAllOfMember(member: SchemaObject): boolean {\n  return !member.$ref && (member.type === 'object' || declaresInlineProperties(member));\n}\n\n/** How an inline `allOf` is read; see `readInlineAllOf`. */\nexport type InlineAllOfReading = 'merged' | 'unwrapped' | 'reference';\n\n/**\n * The one decision every site makes of an inline `allOf` — `schemaToTypeRef`\n * when it types the schema, `mintedInlineNameEntries` when it predicts the\n * names, the field extractor and `extractInlineModelDeep` when they build\n * the models, `extractDirectResource` when it reads a primary response body\n * — so a model is built exactly when a reference names it:\n *\n *   - `'merged'`: a `$ref` member beside an inline object member\n *     (`isInlineAllOfMember`), or, without a `$ref`, several members one of\n *     which declares properties inline (`declaresInlineProperties`). The\n *     schema is the merged model `mergeAllOfMembers` reads, built with\n *     whatever fields the merge yields: an empty `properties: {}` is an\n *     inline object with no fields, as it is as a plain field or a union\n *     variant (`isInlineObjectSchema`), so its model is built with none\n *     rather than left for the reference to dangle on.\n *   - `'unwrapped'`: a single non-`$ref` member with nothing beside it that\n *     adds to it, typed and extracted as the schema itself\n *     (`unwrappedAllOfMember`, which carries the wrapper's limits, flag and\n *     link onto it). A `required` list the wrapper writes beside a lone\n *     member that declares properties (`declaresInlineProperties`) adds to\n *     it: the schema is then the merged model, which reads both lists\n *     (workos/oagen#359 review: the unwrap carried the member's `required`\n *     only, so `{ allOf: [{ properties: { name } }], required: [name] }`\n *     left `name` optional). Beside a member that declares none — an\n *     array, a primitive, an enum — `required` constrains nothing, and the\n *     member is the schema. Members beside it that declare no type of\n *     their own (`declaresType`: a `description`, a `deprecated`, a\n *     `maxLength`, an `x-*` key, `items` that declare none themselves) add\n *     nothing to it either — they annotate or limit the schema, as the\n *     wrapper's own keywords do — so the one member that declares a type\n *     is the schema when every other member declares none\n *     (`allOfTypingMember`): `allOf: [{ type: 'string', enum: ['cat',\n *     'dog'] }, { description: 'The kind of pet.' }]` is that enum,\n *     documented by the second member, exactly as `{ allOf: [{ type:\n *     'string', enum: [...] }], description }` is (workos/oagen#555: it\n *     was `unknown`, the description lost with it), and `allOf: [{ type:\n *     'array', items: { $ref: Owner } }, { items: { description } }]` is\n *     an `Owner[]` whose items the second member documents\n *     (`annotatedTypingMember`; the #555 review).\n *     Two members that each declare a type, neither of them properties —\n *     two primitives, say — are read as neither, and `allOfTypesSchema`\n *     leaves such a schema to its own keywords.\n *   - `'reference'`: a single `$ref` member with nothing beside it that adds\n *     to the component — a `description`, limits — is that component, and\n *     nothing is minted. A second `$ref` member, or a `required` list\n *     (`wrapper`'s own, or a member's) adds to it: the schema is then the\n *     merged model, which carries every component's properties and every\n *     `required` (workos/oagen#359 review: `allOf: [{ $ref: Pet },\n *     { $ref: Owner }]` was `Pet`, `Owner`'s fields gone; `allOf: [{ $ref:\n *     Pet }], required: [name]` was `Pet` with `name` optional). A\n *     `required` adds to the component only when the component declares\n *     properties the merge would read — its own, or its `allOf` chain's\n *     (`contributesProperties`): JSON Schema applies `required` to an\n *     object instance only, so beside a `$ref` to an array, a primitive, an\n *     enum or a union component it constrains nothing, and the reference\n *     stands (the same review: `{ allOf: [{ $ref: Pets }], required: [name] }`\n *     with `Pets` an array became an empty object model). A ref no\n *     component answers declares nothing here, and stays the reference.\n *\n * `allOfTypesSchema` admits no other shape as an `allOf`. `wrapper` is the\n * schema the `allOf` is written on, for its own `required`; a site reading\n * bare members passes none. `componentSchemas` resolves the `$ref`; a site\n * handed none reads the document's components (`componentSchemaOf`), so\n * every site decides alike.\n */\nexport function readInlineAllOf(\n  members: readonly SchemaObject[],\n  wrapper?: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): InlineAllOfReading {\n  const refs = members.filter((m) => m.$ref !== undefined);\n  if (refs.length > 0) {\n    if (members.some(isInlineAllOfMember) || refs.length > 1) return 'merged';\n    const addsRequired =\n      [wrapper, ...members].some((s) => s !== undefined && (s.required?.length ?? 0) > 0) &&\n      contributesProperties(refs[0]!, componentSchemas);\n    return addsRequired ? 'merged' : 'reference';\n  }\n  if (members.length === 1) {\n    const only = members[0]!;\n    const addsRequired = (wrapper?.required?.length ?? 0) > 0 && declaresInlineProperties(only);\n    return addsRequired ? 'merged' : 'unwrapped';\n  }\n  if (members.some(declaresInlineProperties)) return 'merged';\n  // One member types the schema and the others only annotate or limit it\n  // (#555): read as that member, as a lone member is. Several typing\n  // members, or none, are no reading at all.\n  return allOfTypingMember(members) !== undefined ? 'unwrapped' : 'reference';\n}\n\n/**\n * The one member of an `allOf` that declares a type of its own\n * (`declaresType`) when exactly one does, the others annotating or\n * limiting it — a `description`, `deprecated`, `readOnly`, an `example`, a\n * `maxLength`, an `x-*` key, or `items` that declare no type themselves\n * (`{ items: { description: 'An owner.' } }`, which documents the typing\n * member's items: `annotatedTypingMember`) — which `readInlineAllOf` reads\n * as the schema (`'unwrapped'`, and `allOfTypesSchema` admits as an `allOf`\n * that types it). The member as written: the wrapper's keywords and the\n * annotating members' land on it elsewhere (`annotatedTypingMember`,\n * `unwrappedAllOfMember`, `allOfWrapperLayer`). `undefined` when no member\n * declares a type, or more than one does: two inline objects merge, a\n * `$ref` beside an inline object augments it, and two primitives — or an\n * array beside `{ items: { type: 'string' } }` — are read as neither (#555).\n */\nexport function allOfTypingMember(members: readonly SchemaObject[]): SchemaObject | undefined {\n  const typing = members.filter(declaresType);\n  return typing.length === 1 ? typing[0] : undefined;\n}\n\n/**\n * The members of `schema`'s `allOf` that declare no type of their own\n * (`declaresType`), in document order — each annotating or limiting the\n * schema rather than typing it, so what they write is the schema's own, as\n * a wrapper's keywords are: their limits conjoin (`extractConstraints`),\n * their `description`, link, examples, flags, `default` and `x-*` keys\n * are the schema's wherever it declares none itself (`allOfWrapperLayer`,\n * `buildFieldFromSchema`, `extractParams`), and their `items` document the\n * typing member's (`annotatedTypingMember`). Whatever the other members —\n * one typing member unwrapped (`allOfTypingMember`), a `$ref` read as the\n * reference, a merge — a member that declares no type documents the field\n * the schema is written on and the model built from the schema itself\n * (`mergeAllOfMembers`, `extractAllOfModel`), never a component another\n * member references (#555: `allOf: [{ $ref: Kind }, { description }]` was\n * typed `Kind` with no description on the field, and `{ deprecated: true }`\n * or `{ readOnly: true }` beside the `$ref` was dropped). Empty for a\n * schema with no `allOf`.\n */\nexport function annotatingAllOfMembers(schema: SchemaObject): SchemaObject[] {\n  return (schema.allOf ?? []).filter((member) => !declaresType(member));\n}\n\n/**\n * The member an `allOf` read as `'unwrapped'` (`readInlineAllOf`) is typed\n * and extracted as, as written: the one typing member\n * (`allOfTypingMember`), or the first member where none types, its `items`\n * — when it declares any — carrying what each annotating member's `items`\n * write and they leave unset, the first such member's first\n * (`withAnnotatedItems`, the reading `combineDeclarations` gives the same\n * two declarations of one property; #431), so `allOf: [{ type: 'array',\n * items: { $ref: Owner } }, { items: { description: 'An owner.' } }]` is\n * `{ type: 'array', items: { $ref: Owner, description: 'An owner.' } }` —\n * an `Owner[]` whose items the member documents, and an inline enum lifted\n * from such items carries the text (#555 review: `items` counted as a\n * type, so the member was a second typing member and the schema\n * `unknown`). The wrapper's own keywords and the members' other keys are\n * not read here: `unwrappedAllOfMember` carries the limits, flag and\n * documentation, the type builder the layer's documentation\n * (`allOfWrapperLayer`). Read by both, by `typesAsUnknown`,\n * `mintedInlineNameEntries` and `resolveBareSchema`, so every site reads\n * one member.\n */\nexport function annotatedTypingMember(wrapper: SchemaObject): SchemaObject {\n  const members = wrapper.allOf ?? [];\n  const member = allOfTypingMember(members) ?? members[0] ?? {};\n  return annotatingAllOfMembers(wrapper)\n    .filter((other) => other !== member)\n    .reduce((typing, other) => withAnnotatedItems(typing, other), member);\n}\n\n/**\n * `wrapper` as the layer the member its `allOf` is read as sits under: its\n * own keywords, with the documentation and `deprecated` of each annotating\n * member (`annotatingAllOfMembers`) folded in. The layers compose\n * outermost-first by the one wrapper rule (`withWrapperDocs`): the\n * wrapper's own `description`, link, examples and `x-*` keys win, then the\n * first annotating member's that declares one, then the next — so\n * `{ allOf: [{ type: 'string' }, { description: 'A' }, { description:\n * 'B' }] }` is documented `A`, and `{ allOf: [...], description: 'own' }`\n * `own`. `deprecated` is `true` when the wrapper or any annotating member\n * says so, as `Field.deprecated` reads the levels of a field. The wrapper\n * itself when it has no annotating member. Read wherever a wrapper's\n * documentation lands on what it unwraps to (`unwrappedAllOfMember`, the\n * type builder's unwrapped branch), wherever a wrapper's own text is\n * read as the schema's (`unwrapCollapsedWrappers`), and by the model built\n * from the wrapper itself — a component `allOf` (`extractAllOfModel`) or an\n * inline merge (`mergeAllOfMembers`) — whose `description`, link,\n * `deprecated` and `x-*` keys are the layer's, so `Owner: { allOf: [{ $ref:\n * Base }, { properties: { name } }, { description: 'An owner.',\n * deprecated: true }] }` is a deprecated `Owner` described \"An owner.\", as\n * the same keys beside the `allOf` make it (#555 review: the model read the\n * wrapper's own keys alone, and `oagen diff` between the two spellings\n * reported `deprecatedChanged`).\n */\nexport function allOfWrapperLayer(wrapper: SchemaObject): SchemaObject {\n  const annotating = annotatingAllOfMembers(wrapper);\n  if (annotating.length === 0) return wrapper;\n  // Innermost first: the last member's documentation, each earlier member's\n  // over it, then the wrapper's own over all — `withWrapperDocs` carries\n  // only what the outer layer declares, so a blank `description` on the\n  // wrapper leaves a member's text standing.\n  const docs = annotating.reduceRight<SchemaObject>((inner, member) => withWrapperDocs(inner, member), {});\n  const deprecated = wrapper.deprecated === true || annotating.some((member) => member.deprecated === true);\n  return { ...wrapper, ...withWrapperDocs(docs, wrapper), ...(deprecated && { deprecated: true }) };\n}\n\n/**\n * Whether `schema` contributes properties to an `allOf` merge — declares\n * `properties` of its own, or through its `$ref` or its `allOf` chain (a\n * member's `$ref` followed the same way), the reading `mergeAllOfMembers`\n * makes of a member; a union a component carries is not read there, so it\n * does not count. False for a `$ref` to an array, a primitive, an enum, a\n * union-only component, and for a ref no component answers. A chain that\n * returns to a schema it has read declares nothing more.\n */\nfunction contributesProperties(schema: SchemaObject, componentSchemas?: Record<string, SchemaObject>): boolean {\n  const seen = new Set<SchemaObject>();\n  const declares = (s: SchemaObject | undefined): boolean => {\n    if (!s || seen.has(s)) return false;\n    seen.add(s);\n    if (s.$ref) return declares(componentSchemaOf(s.$ref, componentSchemas));\n    if (Object.keys(s.properties ?? {}).length > 0) return true;\n    return (s.allOf ?? []).some(declares);\n  };\n  return declares(schema);\n}\n\n/**\n * The member of an `allOf` read as `'unwrapped'` (`readInlineAllOf`), read\n * as the schema itself: the lone member, or the one member that declares a\n * type among members that only annotate or limit it, its items documented\n * by theirs (`annotatedTypingMember`; #555). The wrapper's own keywords,\n * conjoined with every member's, are the\n * schema's limits (see `extractConstraints`), so they ride along with the\n * member and the model built from it carries the same constraints; its\n * `deprecated` is the wrapper layer's alone — the wrapper's own, or an\n * annotating member's — as `Field.deprecated` reads it, and its\n * documentation — text, link, examples, extensions — is that layer's\n * wherever the layer has any (`allOfWrapperLayer`), by the one wrapper rule\n * `schemaToTypeRef` applies to the member it types (`withWrapperDocs`), so\n * the model built from the member and an inline enum lifted from it are\n * documented by the wrapper alike. Nested under a nullable wrapper, the\n * outer wrapper's documentation has already landed on this one\n * (`unwrapNullableField`), so the layers compose outermost-first. Read on\n * a schema `readInlineAllOf` reads as `'unwrapped'`; the first member\n * stands in where no member declares a type, a shape no site unwraps.\n */\nexport function unwrappedAllOfMember(wrapper: SchemaObject): SchemaObject {\n  const member = annotatedTypingMember(wrapper);\n  // The wrapper layer's documentation — text, link, examples, extensions —\n  // rides onto the member by the one wrapper rule (`withWrapperDocs`), the\n  // wrapper's winning, as the type builder gives the same wrapper on a field.\n  const layer = allOfWrapperLayer(wrapper);\n  // The copy stands for the member it was spread from (`derivedCopy`), so a\n  // reader that guards by identity meets a merge under the wrapper once.\n  const limited = derivedCopy({ ...member, ...extractConstraints(wrapper) }, member);\n  return withWrapperDocs(withWrapperDeprecation(limited, layer), layer);\n}\n\n/**\n * The declarations one property name received from the members of an\n * `allOf`, in the order first declared; see `declareProperty`.\n */\nexport interface PropertyDeclarations {\n  name: string;\n  /** The always-applying declaration that types the property (`combineDeclarations`), with the component it is inherited from (`null` for the schema's own). */\n  unconditional?: { schema: SchemaObject; origin: MergedProperty['origin'] };\n  /** Each branch-only declaration — a `oneOf`/`anyOf` variant's — in order. */\n  conditional: SchemaObject[];\n}\n\n/**\n * Whether a declaration says what an instance is: a `type`, a `$ref`,\n * `properties`, `items` that say so themselves, an `enum` or `const`, a\n * composition, or an `additionalProperties`/`patternProperties` map. One\n * that declares none — a bare `description`, `title`, `example`,\n * `deprecated`, `default`, a validation keyword on its own (`minimum: 1`),\n * or `items` that only document or limit an array's items (`items: {\n * description }`, `items: {}`, read by this same test) — annotates or\n * constrains a type another declaration gives, and is never read as the\n * type itself (`combineDeclarations`, `allOfTypingMember`): `allOf:\n * [{ type: 'array', items: { $ref: Owner } }, { items: { description: 'An\n * owner.' } }]` is an `Owner[]` whose items the second member documents,\n * as the same two declarations of one property are read (#431), not two\n * typing members read as neither (#555 review: `items` counted as a type,\n * and the schema was `unknown`).\n */\nexport function declaresType(schema: SchemaObject): boolean {\n  return (\n    schema.type !== undefined ||\n    schema.$ref !== undefined ||\n    schema.properties !== undefined ||\n    (schema.items !== undefined && declaresType(schema.items)) ||\n    schema.enum !== undefined ||\n    schema.const !== undefined ||\n    schema.allOf !== undefined ||\n    schema.oneOf !== undefined ||\n    schema.anyOf !== undefined ||\n    schema.additionalProperties !== undefined ||\n    schema.patternProperties !== undefined\n  );\n}\n\n/**\n * The declarations `combineDeclarations` builds for the document being read,\n * by the two each is built from, so every reader that merges the same two\n * declarations again meets one object for the combination, however often\n * the merges build it: a root's title walk (`markContestedTitlesUnderRoot`;\n * workos/oagen#531) and the extraction of a merged `allOf` whose merge\n * reaches its own conjunction (`materializeMergedAllOf`; workos/oagen#566)\n * each end at a conjunction they have already read because it is the same\n * object — or a copy standing for it, once a wrapper it keeps is stripped\n * (`sourceDeclaration`). Keyed by the declarations themselves, which the\n * document owns;\n * what a pair combines into depends on the document's components\n * (`composesObject`), so the memo is reset with them\n * (`resetCombinedDeclarations`).\n */\nlet combinedDeclarations = new WeakMap<SchemaObject, WeakMap<SchemaObject, SchemaObject>>();\n\n/** Forget every combined declaration: a document's components are being set (`extractSchemas`) or released (`clearSchemaNameTransform`). */\nexport function resetCombinedDeclarations(): void {\n  combinedDeclarations = new WeakMap();\n}\n\n/**\n * The always-applying declaration of one property once a second arrives, in\n * document order — the one rule for a name two members declare, applied by\n * `declareProperty` for every `allOf` merge (a merged model's, a component's)\n * and by the one property walk (`collectObjectProperties`) for a list\n * envelope's companions, a wrapper's stop field and every `dataPath`\n * segment, so a model's field and a list's stop field are typed from the\n * same declaration (workos/oagen#308 merge review: the walk conjoined two\n * `result` objects while the model kept the first, so `endOfIteration`\n * named `result.total_pages` on a model whose `result` had no such field).\n *\n * The first declaration that declares a type (`declaresType`) types the\n * property, whatever comes after it; a declaration that declares none never\n * does, before or after, and only fills in the keywords the typing one\n * leaves unset, its `items` — typeless too — those the typing one's items\n * leave unset (`annotateDeclaration`) — so `has_more: { type: 'boolean' }`\n * beside an `allOf` member's `has_more: { description: 'More pages' }` is\n * a described boolean whichever is read first, and `data: { type: 'array',\n * items: { $ref: Pet } }` beside `data: { items: { description: 'A pet' } }`\n * a `Pet[]` whose items carry the text. Two typing declarations conjoin as JSON Schema\n * applies both: two inline objects (`isInlineObjectSchema`) merge their\n * properties — a name both declare by this same rule — and unite their\n * `required`, the later's other keywords (a `description`) over the\n * earlier's; two arrays, each under a nullable wrapper of any spelling or\n * none (`arraySchemaOf`), merge as the bare arrays they wrap, so the `items`\n * land in the one array that is then read, whichever declaration wore the\n * wrapper: the two `items` combined by this same rule when both declare\n * them, else the one declared — so `data: User[]` is not downgraded in\n * either order by `items` that declare no type (`{ description }`, `{}`)\n * or by a declaration that only constrains the array (`minItems: 1`), two\n * inline object `items` conjoin, and `string[]` then `integer[]` stays\n * `string[]` (workos/oagen#431: the later `items` replaced the earlier\n * whenever they had any keyword, so a member documenting the items made\n * `data` an `unknown[]`); the later's other keywords over the earlier's;\n * and `type: ['array', 'null']` when either admits `null`\n * (`declaresNull`), else `type: 'array'`; any two declarations that each\n * describe an object — an inline object, a `$ref` to an object component,\n * or an `allOf` that reaches one (`describesObject`, `composesObject`,\n * the component the document's: `componentSchemaOf`) — become the `allOf`\n * of both in document order, which every reader reads as any inline\n * `allOf` (`mergeAllOfMembers`, `collectObjectProperties`), carrying the\n * keywords a field reads from either (`declarationKeywords`, the later's\n * over the earlier's) and `null` exactly when every declaration admits it\n * (`conjunctionAdmitsNull`: a type list naming `null`, OAS 3.0 `nullable:\n * true` beside a `type`, a `$ref` to a component that admits it, an\n * `allOf` whose every member does), as JSON Schema applies both — `Meta |\n * null` beside a nullable inline `allOf`, a second nullable `$ref` or a\n * nullable inline object is `PetPageResult | null`, beside a declaration\n * that rejects `null` is `PetPageResult`, in either member order\n * (workos/oagen#653 review: the conjunction admitted none, and two inline\n * objects took the later's `type` or either's `nullable: true`); the\n * conjunction writes its `type` — two inline objects' the names both\n * admit beside `object` (`conjoinedObjectType`: `['object', 'string']`\n * twice stays so), an `allOf`'s the names both declarations admit when\n * `object` is among them, else `object` (`conjunctionType`: `{ type:\n * ['object', 'string'], allOf: [{ properties: { a } }] }` beside `{ allOf:\n * [{ properties: { b } }] }` stays `['object', 'string']`, beside `{ $ref:\n * Meta }` it is `object`; a pair one of whose members would type such a\n * name itself keeps the first) — with `null` beside it exactly\n * when admitted, so a part's rejection of `null` is kept for a third\n * declaration to read (the review's round 7: a typed wrapper's `type:\n * object` was spliced away, and a later nullable `$ref` restored the\n * `null`) — so\n * `result: { $ref: PetPage }` beside\n * `result: { properties: { total_pages } }` is a `PetPage` that also has\n * `total_pages`, whichever is read first (workos/oagen#432: the first was\n * kept, so `result` had `items` or `total_pages`, never both, and a\n * `dataPath` through the other was rejected), and so is `result: { $ref:\n * PetPage }` beside `result: { allOf: [{ properties: { total_pages } }]\n * }`, or beside `result: { $ref: Meta }`, with `nullable: true`, `type:\n * 'object'` or a `description` written beside the `allOf` or not\n * (workos/oagen#571: only an inline object beside a composing declaration\n * was conjoined, so these pairs kept the first and `result` had the\n * component's fields or the inline ones by member order). The members of\n * the conjunction are the parts of both (`conjunctionMembers`): a\n * declaration that is a bare `allOf` — nothing beside it but the lifted\n * keywords, a `required` the conjunction hoists, a `type` naming `object`\n * (alone, nullable, or beside other names, which the conjunction's own\n * `type` settles), a `title` or another annotation that constrains\n * nothing (`splicesOpen`) — is spliced open into its members, so `{ allOf: [{\n * $ref: A }] }` beside `{ allOf: [{ $ref: B }] }` is `{ allOf: [{ $ref: A\n * }, { $ref: B }] }`, which the readers type, where the `allOf` of the two\n * wrappers as written is `unknown` to them; a part the first already has\n * — the same object, or a `$ref` to a component it names\n * (`namesOneComponent`) — adds nothing, so two `$ref`s naming one\n * component, or a `$ref` beside its own wrapper, keep the first (a first\n * of several parts the readers would type non-null where every part\n * admits `null` is rebuilt as the conjunction, so the admission is the\n * same in either order); and a\n * pair whose members the readers would not all read — one that is no\n * `$ref`, no inline object member (`isInlineAllOfMember`) and no\n * annotating or limiting member (`declaresType`): an `allOf` of `$ref`s\n * under a `discriminator` or `additionalProperties` — keeps the first too,\n * as before, rather than lose a part to the reference reading\n * (workos/oagen#653 review). A `$ref` to a component that dispatches a\n * union describes an object too, its conjunction read as the same `allOf`\n * written by hand (the shared fields, the union left to the component:\n * `mergeAllOfMembers`, workos/oagen#429), and a `$ref` to an array, an\n * enum, a primitive or a union component is no object to conjoin. Any other pair\n * — an object beside a string, say — keeps the first as written, with no\n * warning, as two arrays of different items do. Returns `held` itself when `next`\n * adds nothing to it, so a lone declaration keeps its identity. The same two\n * declarations combine into the same object throughout the document\n * (`combinedDeclarations`), so a reader that guards by identity meets a\n * conjunction once, however often the merges build it — through whatever\n * wrapper it strips from it, the copy read as the conjunction\n * (`sourceDeclaration`) — (workos/oagen#551 memoized the title walk alone;\n * workos/oagen#566: the extractor still got a new object from every merge,\n * and re-entered it without end).\n */\nexport function combineDeclarations(held: SchemaObject, next: SchemaObject): SchemaObject {\n  let byNext = combinedDeclarations.get(held);\n  if (!byNext) combinedDeclarations.set(held, (byNext = new WeakMap()));\n  let combined = byNext.get(next);\n  if (!combined) byNext.set(next, (combined = combineAfresh(held, next)));\n  return combined;\n}\n\n/** What `combineDeclarations` returns, built anew on every call. */\nfunction combineAfresh(held: SchemaObject, next: SchemaObject): SchemaObject {\n  if (!declaresType(held) && declaresType(next)) return annotateDeclaration(next, held);\n  if (declaresType(held) && declaresType(next)) return conjoinTypedDeclarations(held, next);\n  return declaresType(held) ? annotateDeclaration(held, next) : mergeAnnotations(held, next);\n}\n\n/**\n * Two declarations neither of which declares a type (`declaresType`), as\n * one: `held`'s keys over `next`'s, their `items` — annotations both —\n * combined by this same rule when both declare them, else whichever does.\n * Together they annotate whatever typing declaration arrives after them\n * (`annotateDeclaration`), so everything either writes is kept, `items`\n * included: `{ description: 'Tags' }` then `{ items: { description: 'A\n * tag' } }` then `{ type: 'array', items: { type: 'string', enum: [...]\n * } }` is the array described \"Tags\" whose items carry \"A tag\", as the\n * array first gives (#587 review: the second declaration's `items` were\n * dropped as supplying none, before any declaration had items to\n * annotate). `held` itself when nothing is added.\n */\nfunction mergeAnnotations(held: SchemaObject, next: SchemaObject): SchemaObject {\n  const unset = Object.entries(next).filter(([key]) => !Object.hasOwn(held, key));\n  const items =\n    held.items !== undefined && next.items !== undefined ? combineDeclarations(held.items, next.items) : held.items;\n  if (unset.length === 0 && items === held.items) return held;\n  return { ...Object.fromEntries(unset), ...held, ...(items !== held.items && { items }) };\n}\n\n/**\n * `typing` with what `annotating` — a declaration that declares no type\n * (`declaresType`), before or after it — writes and `typing` leaves unset\n * filled in, the one reading `combineDeclarations` gives such a pair. Its\n * `items`, which declare no type either, fill in the typing declaration's\n * own items the same way (`withAnnotatedItems`) and supply none where it\n * declares none: `{ type: 'array', items: { $ref: Pet } }` beside `{ items:\n * { description: 'A pet' } }` is a `Pet[]` whose items carry the text,\n * whichever is read first (#431), and `{ type: 'string' }` beside it stays\n * a `string`. Two typeless declarations are first merged into one\n * (`mergeAnnotations`), so their `items` wait for the typing declaration\n * rather than being dropped. `typing` itself when nothing is added.\n */\nfunction annotateDeclaration(typing: SchemaObject, annotating: SchemaObject): SchemaObject {\n  const { items: _items, ...keywords } = annotating;\n  const unset = Object.entries(keywords).filter(([key]) => !Object.hasOwn(typing, key));\n  const filled = unset.length === 0 ? typing : { ...Object.fromEntries(unset), ...typing };\n  return withAnnotatedItems(filled, annotating);\n}\n\n/**\n * `typing` with its `items`, when it declares any, carrying what\n * `annotating`'s `items` write and they leave unset\n * (`combineDeclarations`: `annotating` declares no type, so neither do its\n * items) — the reading of a typeless `items` beside a typed one wherever\n * two declarations meet: a property two members declare\n * (`annotateDeclaration`) and the one typing member of an `allOf` beside a\n * member that only documents its items (`annotatedTypingMember`; #555\n * review). `typing` itself when either declares no `items`, or the items\n * gain nothing.\n */\nfunction withAnnotatedItems(typing: SchemaObject, annotating: SchemaObject): SchemaObject {\n  if (typing.items === undefined || annotating.items === undefined) return typing;\n  const items = combineDeclarations(typing.items, annotating.items);\n  return items === typing.items ? typing : { ...typing, items };\n}\n\n/** Two typing declarations of one property, conjoined as `combineDeclarations` describes; `first` when they do not combine. */\nfunction conjoinTypedDeclarations(first: SchemaObject, second: SchemaObject): SchemaObject {\n  if (isInlineObjectSchema(first) && isInlineObjectSchema(second)) {\n    const properties: Record<string, SchemaObject | undefined> = { ...first.properties };\n    for (const [key, schema] of Object.entries(second.properties ?? {})) {\n      if (!schema) continue;\n      const held = properties[key];\n      properties[key] = held ? combineDeclarations(held, schema) : schema;\n    }\n    const required = [...new Set([...(first.required ?? []), ...(second.required ?? [])])];\n    // `null` exactly when both admit it (`conjunctionAdmitsNull`), in the\n    // one spelling, whichever side wrote it and however (workos/oagen#653\n    // review: the later's `type` or either's `nullable: true` won, so one\n    // nullable object beside a plain one was nullable by member order).\n    const { nullable: _firstFlag, ...firstBare } = first;\n    const { nullable: _secondFlag, ...secondBare } = second;\n    return {\n      ...firstBare,\n      ...secondBare,\n      properties,\n      ...conjoinedObjectType(first, second),\n      ...(required.length > 0 && { required }),\n    };\n  }\n  const firstArray = arraySchemaOf(first);\n  const secondArray = firstArray && arraySchemaOf(second);\n  if (firstArray && secondArray) {\n    const items =\n      firstArray.items && secondArray.items\n        ? combineDeclarations(firstArray.items, secondArray.items)\n        : (secondArray.items ?? firstArray.items);\n    const { nullable: _firstFlag, ...firstBare } = firstArray;\n    const { nullable: _secondFlag, ...secondBare } = secondArray;\n    return {\n      ...firstBare,\n      ...secondBare,\n      ...(items !== undefined && { items }),\n      type: declaresNull(first) || declaresNull(second) ? ['array', 'null'] : 'array',\n    };\n  }\n  if (describesObject(first) && describesObject(second)) {\n    const held = conjunctionMembers(first);\n    const added = conjunctionMembers(second);\n    // A part the first already has — the same object, or a `$ref` to the\n    // component one of its `$ref`s names — adds nothing to it.\n    const members = [...held.members];\n    for (const member of added.members) {\n      if (!members.some((present) => present === member || namesOneComponent(present, member))) members.push(member);\n    }\n    const required = [...new Set([...held.required, ...added.required])];\n    // `null` exactly when both declarations admit it, as JSON Schema\n    // applies both (workos/oagen#653 review: the conjunction admitted none,\n    // so `Meta | null` beside a nullable inline `allOf` lost its `null`).\n    const nullable = conjunctionAdmitsNull(first) && conjunctionAdmitsNull(second);\n    // Nothing added — two `$ref`s naming one component, a `$ref` beside its\n    // own wrapper — keeps the first, as a lone declaration does; a first of\n    // several parts that the readers would type non-null where every part\n    // admits `null` (a bare `allOf` of nullable `$ref`s, which an inline\n    // merge types with no `null` of its own) is rebuilt as the conjunction\n    // instead, so the admission is the same in either member order (the\n    // #653 review's round 6).\n    const addsNothing = members.length === held.members.length && required.length === held.required.length;\n    if (addsNothing && (held.members.length === 1 || !nullable || declaresNull(first))) return first;\n    // The readers read a member that is a `$ref` or an inline object member\n    // (`isInlineAllOfMember`), or one that declares no type and only\n    // annotates or limits the schema (`declaresType`; `allOfWrapperLayer`,\n    // `extractConstraints`), and type the `allOf` by one that is a `$ref`\n    // or declares properties inline (`allOfTypesSchema`). A member that is\n    // none of these — a composition no splicing opens, an `allOf` of\n    // `$ref`s under a `discriminator` or `additionalProperties` — would be\n    // dropped by the reference reading or leave the conjunction `unknown`,\n    // so such a pair keeps the first, as before (workos/oagen#653 review;\n    // round 5: `{ description }` spliced out of a wrapper failed this\n    // test, and the pair kept the first where the base merged both).\n    const readable =\n      members.every((member) => member.$ref !== undefined || isInlineAllOfMember(member) || !declaresType(member)) &&\n      members.some((member) => member.$ref !== undefined || declaresInlineProperties(member));\n    if (!readable) return first;\n    // The conjunction writes its `type`: the names both declarations admit\n    // (`conjunctionType`: `object`, unless both admit more), with `null`\n    // beside them when both admit it, so a part's rejection of `null` is\n    // kept on the conjunction for a third declaration to read (the #653\n    // review's round 7: `{ type: 'object', allOf: [{ $ref: A }] }` beside\n    // `{ $ref: B }` spliced the `type` away, and a nullable `{ $ref: C }`\n    // then found three nullable parts and restored the `null`).\n    const type = conjunctionType(first, second, nullable);\n    // A name beyond `object` is the conjunction's to say, on its `type`\n    // alone: the readers type each copy of a type list by the members that\n    // say something of its type (`typeListCopy`), so a member that names\n    // the type itself — a `$ref` to a component typed `['object',\n    // 'string']`, an inline object typed so, neither of which splices open\n    // — would type the `string` copy as the object it describes. Such a\n    // pair keeps the first, its alternatives as written, rather than lose\n    // them (round 9).\n    const beyond = (Array.isArray(type) ? type : [type]).filter((name) => name !== 'object' && name !== 'null');\n    const typedByMember = (member: SchemaObject): boolean => {\n      const names = admittedTypeNames(member);\n      return names !== undefined && beyond.some((name) => admits(new Set(names), name));\n    };\n    if (beyond.length > 0 && members.some(typedByMember)) return first;\n    return {\n      ...declarationKeywords(first),\n      ...declarationKeywords(second),\n      allOf: members,\n      type,\n      ...(required.length > 0 && { required }),\n    };\n  }\n  return first;\n}\n\n/**\n * The `type` of two inline object declarations conjoined\n * (`conjoinTypedDeclarations`): the names both admit — the intersection\n * of their type lists, a lone `type` read as a list of one, a declaration\n * that writes none constraining nothing — with `null` exactly when both\n * admit it (`conjunctionAdmitsNull`), as JSON Schema applies both: `type:\n * ['object', 'string']` twice stays `['object', 'string']`, so a string\n * is still an instance of the conjunction (the #653 review's round 7:\n * the conjunction wrote `object`, and the string alternative both\n * declarations admit was lost); `['object', 'string']` beside `['object',\n * 'integer']` is `object`, the only name both admit, while `['object',\n * 'number']` beside `['object', 'integer']` is `['object', 'integer']`,\n * since `number` admits an integer (`namesBothAdmit`); `['object',\n * 'string', 'null']` beside `['object', 'string']` is `['object',\n * 'string']`. A list of one is written as the name; no `type` at all when\n * neither declaration writes one and the conjunction admits no `null`,\n * as neither did.\n */\nfunction conjoinedObjectType(first: SchemaObject, second: SchemaObject): { type?: string | string[] } {\n  const namesOf = (schema: SchemaObject): string[] | undefined =>\n    Array.isArray(schema.type)\n      ? schema.type.filter((name) => name !== 'null')\n      : schema.type !== undefined\n        ? [schema.type]\n        : undefined;\n  const held = namesOf(first);\n  const added = namesOf(second);\n  const shared = held && added ? namesBothAdmit(held, added) : (held ?? added);\n  const nullable = conjunctionAdmitsNull(first) && conjunctionAdmitsNull(second);\n  if (shared === undefined && !nullable) return {};\n  const names = [...(shared && shared.length > 0 ? shared : ['object']), ...(nullable ? ['null'] : [])];\n  return { type: names.length === 1 ? names[0] : names };\n}\n\n/**\n * The type names two lists both admit, as JSON Schema reads them\n * (`admits`: a list admits a name it writes, and `number` admits an\n * `integer`), each name once in the order first written, the narrower of\n * `number` and `integer` in the wider's place — so `['object', 'number',\n * 'string']` beside `['object', 'integer', 'string']` is `['object',\n * 'integer', 'string']` in either order, since every integer is a number\n * (the #653 review's round 8: the names were matched by spelling, and\n * both numeric names were dropped).\n */\nfunction namesBothAdmit(held: readonly string[], added: readonly string[]): string[] {\n  const heldSet = new Set(held);\n  const addedSet = new Set(added);\n  const names: string[] = [];\n  for (const name of held) {\n    if (admits(addedSet, name)) names.push(name);\n    else if (name === 'number' && addedSet.has('integer')) names.push('integer');\n  }\n  for (const name of added) if (admits(heldSet, name) && !names.includes(name)) names.push(name);\n  return names;\n}\n\n/**\n * The `type` of two declarations conjoined as an `allOf`\n * (`conjoinTypedDeclarations`): the names both admit\n * (`admittedTypeNames`, `namesBothAdmit`) when `object` is among them,\n * else `object`, which both describe — with `null` beside them when the\n * conjunction admits it. So `{ type: ['object', 'string'], allOf: [{\n * properties: { a } }] }` beside `{ allOf: [{ properties: { b } }] }`,\n * which says nothing of type, stays `['object', 'string']` and a string\n * is still an instance of the conjunction, as it is of two inline objects\n * typed so (`conjoinedObjectType`; the #653 review's round 9: the `allOf`\n * conjunction wrote `object`, and the string alternative the first\n * declaration kept on its own was lost); beside `{ $ref: Meta }`, a\n * component typed `object`, it is `object`, the only name both admit.\n */\nfunction conjunctionType(first: SchemaObject, second: SchemaObject, nullable: boolean): string | string[] {\n  const held = admittedTypeNames(first);\n  const added = admittedTypeNames(second);\n  const shared = held && added ? namesBothAdmit(held, added) : (held ?? added);\n  const names = [...(shared?.includes('object') ? shared : ['object']), ...(nullable ? ['null'] : [])];\n  return names.length === 1 ? names[0]! : names;\n}\n\n/**\n * The type names a declaration admits, `null` apart\n * (`conjunctionAdmitsNull` settles that), or `undefined` when it says\n * nothing of type and so constrains none: the names of its own `type`, a\n * lone one read as a list of one; a `$ref`'s the names its component\n * admits (`componentSchemaOf`), nothing written beside the `$ref` read; an\n * `allOf`'s the names every member that says something admits, as JSON\n * Schema applies them all (`namesBothAdmit`), beside the schema's own; a\n * `oneOf`/`anyOf`'s the names any variant admits, when every variant says\n * something. A schema met again on the path being read (`path`) says\n * nothing through the loop.\n */\nfunction admittedTypeNames(schema: SchemaObject, path: Set<SchemaObject> = new Set()): string[] | undefined {\n  if (path.has(schema)) return undefined;\n  path.add(schema);\n  try {\n    if (schema.$ref !== undefined) {\n      const target = componentSchemaOf(schema.$ref);\n      return target === undefined ? undefined : admittedTypeNames(target, path);\n    }\n    const said: string[][] = [];\n    if (schema.type !== undefined) {\n      said.push((Array.isArray(schema.type) ? schema.type : [schema.type]).filter((name) => name !== 'null'));\n    }\n    for (const member of schema.allOf ?? []) {\n      const names = admittedTypeNames(member, path);\n      if (names !== undefined) said.push(names);\n    }\n    const variants = (schema.oneOf ?? schema.anyOf)?.map((variant) => admittedTypeNames(variant, path));\n    if (variants !== undefined && variants.length > 0 && variants.every((names) => names !== undefined)) {\n      said.push([...new Set(variants.flatMap((names) => names ?? []))]);\n    }\n    return said.length === 0 ? undefined : said.reduce((held, added) => namesBothAdmit(held, added));\n  } finally {\n    path.delete(schema);\n  }\n}\n\n/**\n * Whether a declaration of an object admits `null`, as the type builder\n * types it: on its own (`declaresNull`: a type list naming `null`, OAS 3.0\n * `nullable: true` beside a `type`, a nullable `oneOf`/`anyOf` wrapper, an\n * `allOf` read as one member that does), through a `$ref` to a component\n * that does (`componentSchemaOf`, as `componentTypeRef` wraps such a\n * reference), or as an `allOf` whose every typing member does\n * (`declaresType`: a member that only annotates or limits the schema says\n * nothing of `null`), as JSON Schema applies them all. A `type` of its\n * own that names no `null` rejects it,\n * whatever it composes (`{ type: 'object', allOf: [{ $ref: Nullable }] }`),\n * and an inline object with no `type` admits none, as the type builder\n * reads it. The one reading a conjunction settles its own `null` admission\n * by (`conjoinTypedDeclarations`: `null` exactly when every declaration\n * admits it), so `Meta | null` beside a nullable inline `allOf`, a second\n * nullable `$ref` or a nullable inline object is nullable, and beside a\n * declaration that rejects `null` is not, in either member order\n * (workos/oagen#653 review). A schema met again on the path being read\n * (`path`: the schemas above it, not every schema read so far) admits\n * none, which ends a component that names itself, through a hop or\n * outright, while a component two members name is read for each — `{\n * allOf: [{ $ref: A }, { $ref: A }] }` beside `{ $ref: B }`, both\n * nullable, is nullable (the #653 review's round 4: the second `$ref` met\n * `A` in a shared seen set and read it as a cycle, so the conjunction lost\n * its `null`).\n */\nfunction conjunctionAdmitsNull(schema: SchemaObject, path: Set<SchemaObject> = new Set()): boolean {\n  if (path.has(schema)) return false;\n  if (declaresNull(schema)) return true;\n  if (schema.type !== undefined) return false;\n  path.add(schema);\n  try {\n    if (schema.$ref !== undefined) {\n      const target = componentSchemaOf(schema.$ref);\n      return target !== undefined && conjunctionAdmitsNull(target, path);\n    }\n    // A member that declares no type (`declaresType`) only annotates or\n    // limits the schema and says nothing of `null`, so it has no say here\n    // (the #653 review's round 6: `{ allOf: [{ $ref: B }, { $ref: C }, {\n    // description }] }` beside a nullable `$ref` rejected `null` for the\n    // description's sake).\n    const typing = (schema.allOf ?? []).filter(declaresType);\n    return typing.length > 0 && typing.every((member) => conjunctionAdmitsNull(member, path));\n  } finally {\n    path.delete(schema);\n  }\n}\n\n/**\n * The parts a declaration brings to a conjunction\n * (`conjoinTypedDeclarations`), with the `required` it writes beside them:\n * its own `allOf` members, each read the same way, when nothing is written\n * beside the `allOf` that the conjunction does not carry itself — the\n * keywords it lifts (`declarationKeywords`: the declaration's own ride on\n * the conjunction; a wrapper nested inside it keeps its own as a member\n * that declares no type, which the readers conjoin onto the schema as the\n * wrapper's own keywords: the limits with the stricter bound winning,\n * `extractConstraints`, the documentation where the schema writes none,\n * `allOfWrapperLayer`), a `required`, which JSON\n * Schema applies to the instance at any depth of a conjunction, so the\n * conjunction carries it, a `type` naming `object` — alone, nullable, or\n * beside other names — which the conjunction settles for itself from\n * every declaration (its names: `conjunctionType`, which reads a wrapper's\n * `type` at any depth; its `null` admission: `conjunctionAdmitsNull`),\n * and an annotation that constrains nothing, a `title` or a `$comment`\n * (`splicesOpen`), which names no field once spliced — else the\n * declaration itself. JSON Schema reads `{ allOf:\n * [A, B] }` and `{ allOf: [{ allOf: [A] }, B] }` alike, but the readers\n * read a member that is a `$ref` or declares properties inline, so a\n * wrapper around a `$ref` is spliced open: `{ allOf: [{ $ref: A }] }`\n * beside `{ allOf: [{ $ref: B }] }` is `{ allOf: [{ $ref: A }, { $ref: B\n * }] }`, and `{ allOf: [{ $ref: A }], required: ['a'] }` beside `{ $ref: B\n * }` is `{ allOf: [{ $ref: A }, { $ref: B }], required: ['a'] }`\n * (workos/oagen#653 review: the conjunction was the `allOf` of the two\n * wrappers as written, which no reader types — `unknown` — and beside a\n * bare `$ref` the wrapper was dropped by the reference reading).\n */\nfunction conjunctionMembers(declaration: SchemaObject): { members: SchemaObject[]; required: string[] } {\n  const members: SchemaObject[] = [];\n  const required: string[] = [];\n  const splice = (schema: SchemaObject, nested: boolean): void => {\n    if (!splicesOpen(schema)) {\n      members.push(schema);\n      return;\n    }\n    for (const name of schema.required ?? []) if (!required.includes(name)) required.push(name);\n    // A wrapper spliced open inside the declaration keeps what it wrote\n    // for the field — its limits, documentation and extensions — as a\n    // member that declares no type, which the readers conjoin onto the\n    // schema as they do the wrapper's own keywords (`extractConstraints`,\n    // the stricter bound winning; `allOfWrapperLayer`, where the schema\n    // writes none itself). The declaration's own ride on the conjunction\n    // (`declarationKeywords`; workos/oagen#653 review, round 5: `{ allOf:\n    // [{ allOf: [{ $ref: A }], minProperties: 2 }] }` lost the limit).\n    if (nested) {\n      const keywords = declarationKeywords(schema);\n      if (Object.keys(keywords).length > 0) members.push(keywords);\n    }\n    for (const member of schema.allOf ?? []) splice(member, true);\n  };\n  splice(declaration, false);\n  return { members, required };\n}\n\n/**\n * Whether a declaration is a bare `allOf` a conjunction splices open\n * (`conjunctionMembers`): every keyword beside the `allOf` is one the\n * conjunction carries — a lifted keyword (`LIFTED_DECLARATION_KEYWORDS`),\n * an `x-*` extension, `required`, `nullable`, a `type` naming `object`\n * alone or beside other names, which the conjunction writes for itself\n * from what every declaration admits (`conjunctionType`; round 9: a\n * wrapper typed `['object', 'string']` stayed a member, and typed the\n * `string` copy of the conjunction as the object it composes), or an\n * annotation that constrains nothing — a\n * `title`, a `$comment`, an `xml` — which accepts the same instances as\n * its members do (workos/oagen#653 review: a `title` kept the wrapper\n * closed, so the pair kept the first by member order). One that also\n * writes a `discriminator`, `additionalProperties`, a `oneOf`/`anyOf`,\n * `properties` or anything else says more than its members do, and stays\n * a member as written.\n */\nfunction splicesOpen(schema: SchemaObject): boolean {\n  if (schema.allOf === undefined) return false;\n  return Object.entries(schema).every(\n    ([key, value]) =>\n      value === undefined ||\n      key === 'allOf' ||\n      key === 'required' ||\n      key === 'nullable' ||\n      key === 'title' ||\n      key === '$comment' ||\n      key === 'xml' ||\n      (key === 'type' && (value === 'object' || (Array.isArray(value) && value.includes('object')))) ||\n      LIFTED_DECLARATION_KEYWORD_SET.has(key) ||\n      key.startsWith('x-'),\n  );\n}\n\n/**\n * Whether a typing declaration describes an object whose properties an\n * `allOf` merge reads, in either of its two spellings: an inline object\n * (`isInlineObjectSchema`) or a `$ref`/`allOf` that composes one\n * (`composesObject`). Two such declarations of one property conjoin as the\n * `allOf` of both (`conjoinTypedDeclarations`), whichever spelling each\n * uses (workos/oagen#571: only an inline object beside a composing one\n * was conjoined, so a `$ref` beside an inline `allOf`, or two `$ref`s,\n * kept the first).\n */\nfunction describesObject(schema: SchemaObject): boolean {\n  return isInlineObjectSchema(schema) || composesObject(schema);\n}\n\n/**\n * Whether a typing declaration that is no inline object — a `$ref`, or an\n * `allOf` — is an object whose properties an `allOf` merge reads\n * (`contributesProperties`): a `$ref` to a component that declares\n * properties, its own or its `allOf` chain's, or an `allOf` that reaches\n * one. A `$ref` to an array, a primitive, an enum or a union component, or\n * one no component answers, is not, so no object declaration beside it\n * turns it into an object merge (`combineDeclarations`).\n */\nfunction composesObject(schema: SchemaObject): boolean {\n  return (schema.$ref !== undefined || schema.allOf !== undefined) && contributesProperties(schema);\n}\n\n/**\n * Whether two declarations are each a `$ref` to the same component — the\n * one object, by identity (`componentSchemaOf`), whatever each `$ref` is\n * spelled — so conjoining them would read that component twice\n * (`conjoinTypedDeclarations`).\n */\nfunction namesOneComponent(first: SchemaObject, second: SchemaObject): boolean {\n  if (first.$ref === undefined || second.$ref === undefined) return false;\n  const target = componentSchemaOf(first.$ref);\n  return target !== undefined && target === componentSchemaOf(second.$ref);\n}\n\n/**\n * What a declaration says of its property beside the type: the keywords a\n * field reads from its own schema (`LIFTED_DECLARATION_KEYWORDS`) and its\n * extensions, which an `allOf` conjoining it with another declaration\n * carries for the field it types (`combineDeclarations`), as a variant's\n * narrower declaration carries a schema's own beside it\n * (`conjoinSiblingProperties`).\n */\nexport function declarationKeywords(schema: SchemaObject): SchemaObject {\n  const keywords = Object.entries(schema).filter(([key]) => LIFTED_DECLARATION_KEYWORDS.includes(key));\n  return { ...Object.fromEntries(keywords), ...extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS) };\n}\n\n/**\n * Record one declaration of `name` in `ledger`: the one precedence rule\n * every `allOf` merge applies, whether the declaration arrives from a direct\n * member, a nested `allOf` member or a `oneOf`/`anyOf` variant, at any\n * depth. Of the always-applying declarations, the first that declares a\n * type wins, whatever is declared before or after it, and a typeless one\n * only annotates it (`combineDeclarations`); the entry's origin is the\n * typing declaration's. A branch-only declaration (`onBranch`) is only a\n * fallback, kept in order for the reader to use when no member always\n * declares the name — `mergeAllOfMembers` as the union of the distinct\n * branch declarations, the component readers (`extractAllOfModel`,\n * `extractDiscriminatedAllOfVariantModels`) as the first branch's. Names are\n * matched by own name (a `Map`), so `constructor`, `toString` and\n * `__proto__` are properties like any other.\n */\nexport function declareProperty(\n  ledger: Map<string, PropertyDeclarations>,\n  name: string,\n  schema: SchemaObject,\n  origin: MergedProperty['origin'],\n  onBranch: boolean,\n): void {\n  let entry = ledger.get(name);\n  if (!entry) ledger.set(name, (entry = { name, conditional: [] }));\n  if (onBranch) entry.conditional.push(schema);\n  else if (!entry.unconditional) entry.unconditional = { schema, origin };\n  else {\n    const held = entry.unconditional;\n    const combined = combineDeclarations(held.schema, schema);\n    // The origin is the typing declaration's. A declaration conjoined from\n    // two components' (`combined` is neither as written) is no component's\n    // own — no component model builds what it nests — so it becomes the\n    // merged model's own, built under its name like a union of branches.\n    const typesIt = !declaresType(held.schema) && declaresType(schema);\n    const conjoined = combined !== held.schema && combined !== schema && held.origin?.name !== origin?.name;\n    entry.unconditional = { schema: combined, origin: conjoined ? null : typesIt ? origin : held.origin };\n  }\n}\n\n/**\n * Declare into `ledger`, as branch-only (`declareProperty`), every\n * property a `oneOf`/`anyOf` variant declares — one declaration per name,\n * the variant read as the one conjunction it is (`readVariant`): its own\n * `properties`, those of its `allOf` members, those of the one variant of\n * a nullable wrapper it carries (`nullableAxisBranch`, per keyword) and —\n * through a `$ref`, the variant itself or one met anywhere under it —\n * those the component it names declares, read the same way (its own\n * properties, its `allOf` chain, a union of its own), all always-applying\n * within the variant and settled as every `allOf` merge settles a name two\n * members declare (`combineDeclarations`: the first typing declaration\n * types it, a typeless one only annotates it), so a variant `{ allOf: [{\n * properties: { value: { type: 'string' } } }, { properties: { value: {\n * description: 'doc' } } }] }` declares one `value`, a described string\n * (#398 review: each member's declaration was a branch of its own, so the\n * variant declared `value` twice and the field was typed `string |\n * unknown`, where the component kept `string`); and those of every\n * variant of the unions nested in it (`unionAxesOf`, both keywords),\n * branch-only within the variant — the union of their distinct\n * declarations where nothing in the variant always declares the name\n * (`unionOfDeclarations`, as the merge types such a property). A\n * variant's `required` is not read: its properties are present only on\n * that branch. The one branch reader the component reader\n * (`readComponentAllOfMember`) and the inline merge (`mergeAllOfMembers`)\n * flatten a variant with, so a flattened union declares the same\n * properties as a component and inline (#398: the component reader read a\n * variant's own `properties` and its `allOf` wrappers' only, so `{ oneOf:\n * [{ oneOf: [{ a }, { b }] }, { c }] }` gave `c` alone and a `$ref`\n * variant gave nothing, while the inline merge read nested unions but\n * followed no `$ref`). A schema met again within one variant's reading\n * declares nothing more, which ends a component that names itself under a\n * variant; the guard is the variant's own, so a component two variants\n * name declares into each variant's conjunction — `{ allOf: [{ $ref: C },\n * { payload: { b } }] }` beside `{ allOf: [{ $ref: C }, { payload: { c }\n * }] }`, `C.payload { a }`, is `payload: { a, b } | { a, c }` (#398 review\n * round 2: the guard was shared across the variants, so the second read\n * `{ c }` alone). A union nested in the variant is read the same way, one\n * level down: each of its branches is a conjunction of its own, settled\n * before it joins the variant's ledger as branch-only, with a guard of its\n * own — so the same two branches nested in a variant are `payload: { a, b\n * } | { a, c }` too (#398 review round 4: the nested branches were read\n * into the variant's ledger as one more set of alternatives, `{ a } | { b }\n * | { c }`, sharing its guard, so the second skipped `C`). `walking` is\n * the path above the variant — the conjunctions it is nested in — which a\n * schema met again on ends, so a component naming itself under a nested\n * union still terminates.\n */\nexport function declareVariant(\n  ledger: Map<string, PropertyDeclarations>,\n  variant: SchemaObject,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  walking: ReadonlySet<SchemaObject> = new Set(),\n): void {\n  const own = new Map<string, PropertyDeclarations>();\n  readVariant(own, variant, componentSchemas, new Set(), walking);\n  for (const { name, unconditional, conditional } of own.values()) {\n    declareProperty(ledger, name, unconditional?.schema ?? unionOfDeclarations(conditional), null, true);\n  }\n}\n\n/**\n * Read a `oneOf`/`anyOf` variant, or a schema met under one, into\n * `ledger` as `declareVariant` describes: what always applies within the\n * variant — its properties, an `allOf` member's, a nullable wrapper's one\n * variant's, the component a `$ref` names — as always-applying, and each\n * branch of a union nested in it as a conjunction of its own\n * (`declareVariant`, one level down), branch-only in this ledger. `seen` is\n * this one conjunction's: a schema met again within it declares nothing\n * more; `walking` is the path above it, which a schema met again on ends.\n */\nfunction readVariant(\n  ledger: Map<string, PropertyDeclarations>,\n  schema: SchemaObject,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  seen: Set<SchemaObject>,\n  walking: ReadonlySet<SchemaObject>,\n): void {\n  if (seen.has(schema) || walking.has(schema)) return;\n  seen.add(schema);\n  if (schema.$ref) {\n    const target = schemaRefTarget(schema.$ref, componentSchemas);\n    if (target) readVariant(ledger, target, componentSchemas, seen, walking);\n    return;\n  }\n  for (const [key, value] of Object.entries(schema.properties ?? {})) {\n    if (value) declareProperty(ledger, key, value, null, false);\n  }\n  for (const sub of schema.allOf ?? []) readVariant(ledger, sub, componentSchemas, seen, walking);\n  for (const variants of unionAxesOf(schema)) {\n    const branch = nullableAxisBranch(schema, variants);\n    if (branch) {\n      readVariant(ledger, branch, componentSchemas, seen, walking);\n      continue;\n    }\n    // Each nested branch is a conjunction of its own; the path it is on is\n    // this conjunction and everything above it.\n    const above = new Set([...walking, ...seen]);\n    for (const nested of variants) declareVariant(ledger, nested, componentSchemas, above);\n  }\n}\n\n/**\n * Merge an inline `allOf` into one object shape, remembering where each\n * property comes from. Every site that types an inline `allOf` reads it\n * through this one function — a model field (of a component or of any\n * inline model), a request body, a response body of every kind (primary,\n * secondary media type, error, `default` and range), a response header, a\n * webhook payload or parameter, array items, map values, a union's `allOf`\n * variant, and a field nested under a discriminated component variant — so\n * the same schema has the same fields wherever it appears.\n *\n * Members are read in document order, the wrapper's own `properties` and\n * `required` first. A `$ref` member is resolved against `componentSchemas`\n * by its component name, as `extractAllOfModel` does, and contributes its\n * component's `properties` — its own, written beside its `allOf`, and those\n * of its `allOf` chain, in the order `extractAllOfModel` reads them\n * (`componentAllOfMembers`) — tagged with that component's model name, so the merged\n * model can type them exactly as the component's own model does; a ref no\n * component answers contributes nothing and is listed in `unresolvedRefs`.\n * The component tagged is the one whose own model carries the field under\n * its name: an `allOf` component that inherits it stays the origin of\n * everything reached inside its chain (`DogMeta`), and so does a bare\n * alias (`Hop: { $ref: Base }`), whose model is built as `allOf: [{ $ref:\n * Base }]`'s is and carries the field as `HopMeta` (#618) — nothing a\n * `$ref` on the way writes beside itself is read, a bare alias's `required`\n * or `properties` included (#618 review, #622) — while a nullable\n * alias (`Alias: { oneOf: [{ $ref: Base }, { type: 'null' }] }`) declares\n * nothing of its own and builds no model, so a reference met inside one\n * starts its own origin (`Base.meta` stays `BaseMeta`; workos/oagen#308\n * round 4).\n * An inline member contributes its `properties`, those of its nested\n * `allOf` members and, for each `oneOf`/`anyOf` it carries (`unionAxesOf`:\n * a member writing both carries two, a nullable wrapper among them decided\n * per keyword, `nullableAxisBranch`; #398 read only the `oneOf`), those of\n * every variant — read through the variant's own `allOf` members, its\n * nested unions and the component a `$ref` variant names, by the one\n * branch reader the component reader flattens a variant with\n * (`declareVariant`) — tagged as the merged model's own (workos/oagen#283:\n * a variant's fields were dropped, so an inline `allOf: [base, { oneOf:\n * [{ a }, { b }] }]` lost `a` and `b` while the same schema as a component\n * kept them). A union written beside the `allOf` is one more member, the\n * last (`foldSiblingProperties`), so `{ allOf: [base], oneOf: [...] }` is\n * read as `allOf: [base, { oneOf: [...] }]` is.\n *\n * `required` is collected from the wrapper and from every member that always\n * applies; a variant's `required` is not read, since its properties are\n * present only on that branch, so they are optional on the merged model,\n * exactly as `extractAllOfModel` flattens a component's variants. A union a\n * `$ref` member's component carries is read as that component's own model\n * reads it (#429): flattened into the merge when the model flattens it, so\n * `Dog: { allOf: [{ $ref: Pet }] }` with `Pet: { properties: { id }, oneOf:\n * [{ ownerId }, { shelterId }] }` carries `ownerId` and `shelterId` inline\n * as `Dog`'s and `Pet`'s models do; left to the component when its model\n * dispatches it (`componentUnionDispatches`: the variants pin a property\n * to distinct consts, or the document declares a `discriminator` on the\n * union or on the `allOf` wrapper around it, `wrapperDiscriminatorOf`), so\n * the merge carries the base fields the dispatcher model carries and no\n * variant's. An inline member's union is always flattened: an inline\n * `allOf` never dispatches.\n *\n * A property keeps the always-applying declaration `declareProperty` settles\n * on — the first that declares a type, a typeless one before or after it\n * only annotating it, two typing objects or arrays conjoined\n * (`combineDeclarations`); a declaration conjoined from two components' is\n * the merged model's own — whatever a variant says: a\n * variant can only narrow what every instance\n * carries. A property only variants declare is typed as the union of its\n * distinct declarations (`unionOfDeclarations`; the flags, documentation\n * and limits make no shape, at a declaration's top level or inside its\n * array items and map values): one declaration, or several of one shape, is\n * that declaration (the first, carrying only the flags, documentation and\n * limits they agree on); several shapes become a `oneOf` of them, each the\n * first declaration of its shape, deprecated only when every declaration of\n * the shape is, which the type builder reads as it reads any inline union —\n * string consts pinned differently per variant (`kind: cat` | `kind: dog`)\n * collapse to an inline enum, other literals and types to a union — so the\n * field is never typed from one variant's value alone. Such a property is\n * marked `conditional`: it holds on a branch, so its `const` does not name a\n * response body (`extractDirectResource`, workos/oagen#396). Properties keep\n * the order they were first declared in.\n *\n * A schema reached twice is read once in each capacity it is reached in —\n * as an inline member (the merged model's own, unions included), through a\n * `$ref` member (inherited, a union its component dispatches left to the\n * component) or under a variant (`required` unread, once per variant that\n * reaches it: each variant is read as a conjunction of its own,\n * `declareVariant`, so a component two variants name declares into both)\n * — and only an inline reading stands for the others: a schema shared\n * between a variant and a member (a YAML anchor, an object a\n * `transformSpec` hook reuses, a `$ref` written twice) still contributes\n * its `required` and is still followed when the member is reached, and a\n * component's own object reused as an inline member still has a dispatched\n * union flattened after the `$ref` reading left it to the component\n * (`done`). The walk reads property lists only — it never descends into a\n * property — so it is finite for any component graph: a schema already\n * read in the same capacity is not read again, and a variant's walk ends\n * where it meets a schema again, which is what stops a component that\n * extends itself. `required` lists each name once.\n */\nexport function mergeAllOfMembers(\n  schema: SchemaObject,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): MergedAllOf {\n  const declared = new Map<string, PropertyDeclarations>();\n  const required: string[] = [];\n  const resolvedRefs: string[] = [];\n  const unresolvedRefs: string[] = [];\n  // The schemas read so far, by capacity: `inline` (an always-applying\n  // member read as the merged model's own, every union flattened) and\n  // `inherited` (reached through a `$ref` member, a union its component\n  // dispatches left to the component). An inline reading is complete, so\n  // it stands for both; an inherited reading is not, so the same schema\n  // reached again inline is read once more for what that capacity\n  // contributes — a component's own object reused as an inline member (an\n  // object a `transformSpec` hook shares) still has a dispatched union\n  // flattened. A schema already read in the same capacity is not read\n  // again, which is what stops a component that extends itself. A schema\n  // under a variant is read by the variant's own walk (`declareVariant`),\n  // `required` unread, once per variant that reaches it.\n  const done = {\n    inline: new Set<SchemaObject>(),\n    inherited: new Set<SchemaObject>(),\n  };\n  // `wrapperDiscriminator`: the `discriminator` the `allOf` wrapper `s` sits\n  // in writes for a union among its members (`wrapperDiscriminatorOf`), by\n  // which an inherited union dispatches as its component's model does.\n  const visit = (\n    s: SchemaObject,\n    origin: MergedProperty['origin'],\n    wrapperDiscriminator?: SchemaObject['discriminator'],\n  ): void => {\n    const capacity = origin === null ? 'inline' : 'inherited';\n    if (done.inline.has(s) || done[capacity].has(s)) return;\n    done[capacity].add(s);\n    if (s.$ref) {\n      const key = componentKeyOf(s.$ref);\n      const target = schemaRefTarget(s.$ref, componentSchemas);\n      const refs = target ? resolvedRefs : unresolvedRefs;\n      if (!refs.includes(s.$ref)) refs.push(s.$ref);\n      if (!target) return;\n      // The component the properties belong to is the one whose own model\n      // carries them under its name. A ref inside an `allOf` component's own\n      // chain stays that component's: its model inherits through its\n      // members, nullable ones included, and types their fields under its\n      // own name (`DogMeta`); so does one inside a bare alias's (`Hop: {\n      // $ref: Base }`), whose model is built as `allOf: [{ $ref: Base }]`'s\n      // is and types the field `HopMeta` (#618). Any other component met on\n      // the way declares nothing of its own that this reference adds to —\n      // a nullable alias (`Alias: { oneOf: [{ $ref: Base }, { type: 'null'\n      // }] }`), a chain of them — and builds no model for the fields, so\n      // the reference starts its own origin, as a top-level ref member does\n      // (workos/oagen#308 round 4: `HolderValue.meta` named `AliasMeta`,\n      // which nothing built, where `BaseMeta` exists). A pointer deeper into\n      // a component (#539) names a schema and no model of its own, so it\n      // declares as a member written inline does: under the origin at hand.\n      const owner =\n        origin?.schema.allOf || origin?.schema.$ref !== undefined || key === undefined\n          ? origin\n          : { name: resolveSchemaName(key), schema: target };\n      // Nothing written beside the `$ref` is read — not a bare alias's\n      // `required`, `properties`, `allOf` or union (#618 review, #622) —\n      // as the component reader reads none (`componentAllOfMembers`).\n      visit(target, owner);\n      return;\n    }\n    for (const [key, value] of Object.entries(s.properties ?? {})) {\n      if (value) declareProperty(declared, key, value, origin, false);\n    }\n    if (s.required) for (const r of s.required) if (!required.includes(r)) required.push(r);\n    for (const sub of s.allOf ?? []) visit(sub, origin, wrapperDiscriminatorOf(s));\n    // A nullable union wrapper — one non-null variant beside `null`, decided\n    // per keyword by `nullableAxisBranch`, `nullableUnionBranch`'s\n    // definition, the one `unwrapNullableSchema` collapses by, which\n    // `readComponentAllOfMember` reads a component's member through and the\n    // envelope collector reads every member through (`resolveBareSchema`) —\n    // is that variant, applying as the member does: an instance that is not\n    // null is the variant, and beside an object member it is never null. So\n    // the variant is read in the member's own capacity — its `$ref`\n    // followed, its `required` read, its properties always-applying —\n    // wherever the member sits, a `$ref` member's component included\n    // (workos/oagen#308: read as a branch, `Base`'s `has_more` ended the\n    // iteration but was missing from the model). Any other union is\n    // flattened, each variant read as the component reader reads it\n    // (`declareVariant`) — unless a `$ref` member's component dispatches\n    // it, in which case it belongs to that component's model\n    // (`componentUnionDispatches`; #429). Each axis is decided on its own,\n    // so a member writing a nullable `oneOf` beside an `anyOf` has the\n    // `anyOf` flattened, as two members would (#398 review: the wrapper was\n    // decided on the member, which reads one keyword, and the `anyOf` was\n    // never read). The wrapper's `discriminator` goes with the one variant,\n    // as the component reader hands it on (`readComponentAllOfMember`), so a\n    // union a `$ref` member's component dispatches under a nullable wrapper\n    // is left to it here too (#398 review round 5: the merge followed the\n    // wrapper without it, and flattened the fields the component leaves out)\n    // — the member's own, written on the wrapper, first (round 6).\n    for (const variants of unionAxesOf(s)) {\n      const branch = nullableAxisBranch(s, variants);\n      if (branch) {\n        visit(branch, origin, s.discriminator ?? wrapperDiscriminator);\n        continue;\n      }\n      const explicit = s.discriminator ?? wrapperDiscriminator;\n      if (origin !== null && componentUnionDispatches(variants, origin.name, componentSchemas, explicit)) continue;\n      for (const variant of variants) declareVariant(declared, variant, componentSchemas);\n    }\n  };\n  visit(schema, null);\n  const properties: MergedProperty[] = [...declared.values()].map(({ name, unconditional, conditional }) =>\n    unconditional\n      ? { name, schema: unconditional.schema, origin: unconditional.origin }\n      : { name, schema: unionOfDeclarations(conditional), origin: null, conditional: true },\n  );\n  // Limits conjoin the way properties merge, so the merged model declares what\n  // an instance must satisfy; a `$ref` member's target keeps its own limits.\n  // The text, link, flag and extensions are the wrapper layer's: the\n  // wrapper's own, with an annotating member's — one that declares no type\n  // — where it declares none (`allOfWrapperLayer`; #555 review: `allOf:\n  // [{ properties: { a } }, { description: 'D', deprecated: true }]` built\n  // a model with neither, while the same keys beside the `allOf` were its\n  // own). A typing member's stay on that member, a `$ref` member's on its\n  // component.\n  const layer = allOfWrapperLayer(schema);\n  return {\n    properties,\n    required,\n    resolvedRefs,\n    unresolvedRefs,\n    description: layer.description,\n    externalDocs: readExternalDocs(layer.externalDocs),\n    constraints: extractConstraints(schema),\n    deprecated: layer.deprecated === true || undefined,\n    extensions: extensionsOf(layer, SCHEMA_CONSUMED_EXTENSIONS),\n  };\n}\n\n/**\n * The validation keywords `extractConstraints` reads: the limits a field\n * reads from its own schema, and the ones an array's items or a map's\n * values carry on their type (#545). Lifted by `unionOfDeclarations` at a\n * declaration's top level with the rest of `LIFTED_DECLARATION_KEYWORDS`,\n * and inside its array items and map values on their own\n * (`withAgreedNestedLimits`).\n */\nconst LIFTED_LIMIT_KEYWORDS: readonly string[] = [\n  'minimum',\n  'maximum',\n  'exclusiveMinimum',\n  'exclusiveMaximum',\n  'multipleOf',\n  'minLength',\n  'maxLength',\n  'minItems',\n  'maxItems',\n  'minContains',\n  'maxContains',\n  'minProperties',\n  'maxProperties',\n  'pattern',\n  'uniqueItems',\n  'dependentRequired',\n];\n\n/**\n * The keywords a field reads from its own schema — the flags and\n * documentation `buildFieldFromSchema` reads and the validation keywords\n * `extractConstraints` reads (`LIFTED_LIMIT_KEYWORDS`) — which\n * `unionOfDeclarations` lifts onto a combined declaration when every\n * declaration agrees on them, and which therefore make no shape of their\n * own there, at a declaration's top level or inside its array items and\n * map values (`withoutLiftedKeywords`); the request-body fold carries the\n * same keywords onto the discriminator it rebuilds, by the same agreement\n * (`flattenDiscriminatedUnionBody`, each declaration read as a field written\n * as it is read, `fieldSettings`).\n */\nexport const LIFTED_DECLARATION_KEYWORDS: readonly string[] = [\n  'readOnly',\n  'writeOnly',\n  'deprecated',\n  'description',\n  'default',\n  'example',\n  'examples',\n  'externalDocs',\n  ...LIFTED_LIMIT_KEYWORDS,\n];\nconst LIFTED_DECLARATION_KEYWORD_SET: ReadonlySet<string> = new Set(LIFTED_DECLARATION_KEYWORDS);\n\n/**\n * The keywords under which a declaration nests the one schema its array\n * items or map values are typed from (`ArrayType.items`,\n * `MapType.valueType`): the lifted keywords written there make no shape\n * either (`withoutLiftedKeywords`), `deprecated` there follows the shape's\n * agreement (`shapeVariant`), and so do the limits, which the items' or\n * values' type carries (`withAgreedNestedLimits`; #545).\n */\nconst NESTED_DECLARATION_KEYWORDS = ['items', 'additionalProperties'] as const;\n\n/**\n * `schema` as `unionOfDeclarations` compares it: without\n * `LIFTED_DECLARATION_KEYWORDS` at its top level, and without them inside\n * its `items` and `additionalProperties` schemas, recursively\n * (`NESTED_DECLARATION_KEYWORDS`), since none of them shapes an array's\n * items or a map's values: `{ type: array, items: { type: string } }`\n * beside `{ type: array, items: { type: string, readOnly: true } }`, or\n * with `maxLength: 5` on the items, is one `string[]` (workos/oagen#397\n * review: it was `(string[] | string[])`, and two maps `(map | map)`).\n * Inside `properties` they stay: a field reads them, so two objects whose\n * `t` differs in `readOnly` are two shapes.\n */\nfunction withoutLiftedKeywords(schema: SchemaObject): SchemaObject {\n  const stripped = omitKeys(schema, LIFTED_DECLARATION_KEYWORD_SET);\n  for (const keyword of NESTED_DECLARATION_KEYWORDS) {\n    const nested = schema[keyword];\n    if (isRecord(nested)) stripped[keyword] = withoutLiftedKeywords(nested);\n  }\n  return stripped;\n}\n\n/**\n * The schema that stands for one shape in `unionOfDeclarations`: the first\n * declaration of the shape (`group`, in order), as written, except that\n * `deprecated: true` is kept only when every declaration of the shape has\n * it, at the top level and inside `items` and `additionalProperties` alike\n * (`NESTED_DECLARATION_KEYWORDS`): one live declaration means the shape is\n * not deprecated, as the single-shape outcome already reads it. Before\n * (workos/oagen#397 review), the first declaration decided, so `[{ object\n * t, deprecated }, { object t }, { integer }]` gave a deprecated\n * `<Model>Kind` and the swapped order a live one, with `diffSpecs`\n * reporting a `deprecatedChanged` between them; `{ const: cat, deprecated\n * }`, `{ const: cat }` and `{ const: dog }` gave a deprecated `CAT`. Every\n * other keyword stays the first declaration's, so an enum member or a\n * variant model still carries its own description and limits.\n */\nfunction shapeVariant(group: readonly SchemaObject[]): SchemaObject {\n  const first = group[0]!;\n  let variant = first;\n  if (first.deprecated === true && !group.every((declaration) => declaration.deprecated === true)) {\n    variant = omitKeys(first, new Set(['deprecated']));\n  }\n  for (const keyword of NESTED_DECLARATION_KEYWORDS) {\n    const nested = first[keyword];\n    if (!isRecord(nested)) continue;\n    const agreed = shapeVariant(group.map((declaration) => declaration[keyword]).filter(isRecord));\n    if (agreed !== nested) variant = { ...variant, [keyword]: agreed };\n  }\n  return variant;\n}\n\n/**\n * The one schema that types a property several variants declare: the first\n * declaration when every declaration has the same shape (`schemaShapeKey`\n * of the declaration less `LIFTED_DECLARATION_KEYWORDS`, at its top level\n * and inside its array items and map values — `withoutLiftedKeywords` — so\n * documentation, flags and limits ignored), else a `oneOf` of the distinct\n * shapes, each the first declaration of its shape, in order, deprecated only\n * when every declaration of that shape is (`shapeVariant`). See\n * `mergeAllOfMembers`; a component's flattened union types such a property\n * the same way (`declaredComponentProperty`; #398).\n *\n * A field reads its flags, documentation and limits from its own schema\n * (`buildFieldFromSchema`, `extractConstraints`), never from a union's\n * variants, so a combined declaration carries every keyword of\n * `LIFTED_DECLARATION_KEYWORDS` the declarations agree on, value for value:\n * two `kind` declarations both `readOnly: true` with different consts make a\n * read-only enum field; a keyword the declarations disagree on, or one only\n * some declare, is not the field's. Every declaration as written has a say,\n * a repeat of an earlier shape included. The keywords and the extensions\n * (`agreedExtensions`) are read by this agreement under both outcomes: the\n * one declaration a single shape is typed from carries the agreed keywords\n * and keys in place of its own, so two `type: 'string'` declarations, one\n * `readOnly` or documented otherwise, are a plain `string` field\n * (workos/oagen#397: they were `(string | string)`, or the first's\n * description). The declarations themselves are kept as written inside the\n * `oneOf`, so an enum member or a variant model still carries its own\n * description and limits — `deprecated` apart, which a shape's variant keeps\n * only when every declaration of the shape has it, so a `oneOf` of two\n * object declarations and an integer, the first object deprecated and the\n * second not, types a live variant model whichever object comes first. A\n * `null` any declaration admits (`nullable: true`, or a `type` list naming\n * `null`) is a value the property takes on that branch, so the union admits\n * it: the admission moves to a `{ type: 'null' }` variant of the `oneOf` —\n * the one place the type builder reads a union's nullability from, and one\n * a union of string consts would otherwise lose when it collapses to an\n * enum — and off the declarations.\n */\nexport function unionOfDeclarations(declarations: readonly SchemaObject[]): SchemaObject {\n  if (declarations.length === 1) return declarations[0]!;\n  // The extensions and the keywords are decided first, across every\n  // declaration as written, apart from the shape dedupe below: a declaration\n  // dropped as a repeat of an earlier shape still has its say, so `x-since`\n  // written as `1`, `2` and `1` by three declarations is nobody's\n  // (workos/oagen#369 review, which read the keys off the distinct shapes\n  // alone and kept the `1`).\n  const extensions = agreedExtensions(declarations);\n  const agreed = agreedDeclarationKeys(declarations, LIFTED_DECLARATION_KEYWORDS);\n  // The keywords the field reads by that agreement make no shape, nor do\n  // they inside array items or map values; every declaration of a shape is\n  // kept, in order, for the shape's own `deprecated` agreement.\n  const groups = new Map<string, SchemaObject[]>();\n  for (const declaration of declarations) {\n    const key = schemaShapeKey(withoutLiftedKeywords(declaration));\n    const group = groups.get(key);\n    if (group) group.push(declaration);\n    else groups.set(key, [declaration]);\n  }\n  // Each shape is its first declaration, the limits inside its items and\n  // values read by the agreement of every declaration of that shape\n  // (`withAgreedNestedLimits`), whether it is the one shape or one of\n  // several: a limit one array declaration's items write and another's\n  // leave out is no limit of the items whichever array is declared first,\n  // and whether or not an integer is declared beside them (#545 review).\n  const shapes = [...groups.values()].map((group) => withAgreedNestedLimits(shapeVariant(group), group));\n  // One shape: the first declaration, carrying the agreed keywords and\n  // extensions in place of its own.\n  if (shapes.length === 1) {\n    const first = shapes[0]!;\n    const disputed = new Set(\n      LIFTED_DECLARATION_KEYWORDS.filter((key) => Object.hasOwn(first, key) && !Object.hasOwn(agreed, key)),\n    );\n    return withAgreedExtensions(disputed.size > 0 ? omitKeys(first, disputed) : first, extensions);\n  }\n  const anyAdmitsNull = shapes.some(admitsNull);\n  const variants = anyAdmitsNull ? [...shapes.map(withoutNull), { type: 'null' }] : shapes;\n  return { ...agreed, ...extensions, oneOf: variants };\n}\n\n/**\n * `shape`, the declaration one shape is typed from (`shapeVariant`), with\n * the limits inside its array items and map values\n * (`NESTED_DECLARATION_KEYWORDS`, recursively) read by the agreement of\n * `declarations`, the declarations of that shape, as a single shape's own\n * are read by every declaration's: a limit the items or values of every\n * declaration write the same way stays, one any declaration leaves unset\n * or writes otherwise is dropped (`agreedDeclarationKeys`). The items' or\n * values' type carries those limits (#545), and the value takes one\n * branch, so a `maxLength: 5` one declaration's items write and another's\n * leave out is no limit of the field's items; before, nothing in the IR\n * read them there. Read per shape, so two array declarations beside an\n * integer agree on their items as they would without it, whichever array\n * comes first (#545 review: the first array's `pattern` was every item's).\n * Every other lifted keyword written inside the items or values —\n * `readOnly`, `description`, `default`, … — stays the first declaration's,\n * as it did, since a field reads none of them there.\n */\nfunction withAgreedNestedLimits(shape: SchemaObject, declarations: readonly SchemaObject[]): SchemaObject {\n  let out = shape;\n  for (const keyword of NESTED_DECLARATION_KEYWORDS) {\n    const nested = shape[keyword];\n    if (!isRecord(nested)) continue;\n    const nestedDeclarations = declarations.map((declaration) => declaration[keyword]).filter(isRecord);\n    const agreed = agreedDeclarationKeys(nestedDeclarations, LIFTED_LIMIT_KEYWORDS);\n    const disputed = new Set(\n      LIFTED_LIMIT_KEYWORDS.filter((key) => Object.hasOwn(nested, key) && !Object.hasOwn(agreed, key)),\n    );\n    const settled = withAgreedNestedLimits(disputed.size > 0 ? omitKeys(nested, disputed) : nested, nestedDeclarations);\n    if (settled !== nested) out = { ...out, [keyword]: settled };\n  }\n  return out;\n}\n\n/**\n * The entries of `keys` every one of `declarations` declares with one\n * value — compared by `stableStringify`, so an object value agrees whatever\n * its key order — each as the first declaration writes it. A key any\n * declaration leaves unset, or declares with another value, is left out.\n * The one agreement rule for a property several variants declare, read for\n * the lifted keywords and for the extensions alike (`unionOfDeclarations`),\n * and for the text of a flattened body's discriminator\n * (`flattenDiscriminatedUnionBody`).\n */\nexport function agreedDeclarationKeys(\n  declarations: readonly SchemaObject[],\n  keys: Iterable<string>,\n): Record<string, unknown> {\n  const agreed: Record<string, unknown> = {};\n  for (const key of keys) {\n    const values = declarations.map((declaration) => declaration[key]);\n    if (values[0] === undefined) continue;\n    const first = stableStringify(values[0]);\n    if (values.every((value) => value !== undefined && stableStringify(value) === first)) agreed[key] = values[0];\n  }\n  return agreed;\n}\n\n/**\n * The extensions every one of `declarations` agrees on\n * (`agreedDeclarationKeys` over the first declaration's keys, the consumed\n * ones left out as `extensionsOf` leaves them); `undefined` when none. A\n * property several variants declare carries exactly these, whether or not\n * the declarations share one shape: no one declaration is the schema for a\n * key OpenAPI gives no meaning to, and an emitter may act on it, so a key\n * the declarations dispute is nobody's.\n */\nexport function agreedExtensions(declarations: readonly SchemaObject[]): Extensions | undefined {\n  const keys = Object.keys(extensionsOf(declarations[0]!, SCHEMA_CONSUMED_EXTENSIONS) ?? {});\n  const agreed = agreedDeclarationKeys(declarations, keys);\n  return Object.keys(agreed).length > 0 ? agreed : undefined;\n}\n\n/** `schema` with `extensions` in place of its own (consumed keys kept where they are); `schema` itself when neither has any. */\nexport function withAgreedExtensions(schema: SchemaObject, extensions: Extensions | undefined): SchemaObject {\n  const own = extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS);\n  if (!own && !extensions) return schema;\n  const kept = Object.entries(schema).filter(([key]) => !(own && Object.hasOwn(own, key)));\n  return { ...Object.fromEntries(kept), ...extensions };\n}\n\n/** Whether a declaration admits `null` on its own: OAS 3.0 `nullable: true`, or a `type` list naming `null`. */\nfunction admitsNull(schema: SchemaObject): boolean {\n  return schema.nullable === true || (Array.isArray(schema.type) && schema.type.includes('null'));\n}\n\n/** `schema` with its own `null` admission removed (see `admitsNull`); the type list collapses to its one remaining entry. */\nfunction withoutNull(schema: SchemaObject): SchemaObject {\n  const { nullable: _nullable, ...rest } = schema;\n  if (Array.isArray(rest.type)) {\n    const types = rest.type.filter((t) => t !== 'null');\n    rest.type = types.length === 1 ? types[0] : types;\n  }\n  return rest;\n}\n\n/**\n * Build the model for an inline `allOf` read as `'merged'` (`readInlineAllOf`)\n * under `name`, and materialize what its own properties reference, into\n * `results`. The model is built whatever fields the merge yields — none for\n * an `allOf` whose inline members declare only an empty `properties: {}` —\n * since the reference `schemaToTypeRef` made under the same reading exists\n * and must resolve. The model is `buildMergedModel`'s, so an inherited\n * property is typed as its component's model types it (`Base.meta` stays\n * `BaseMeta`) and is not read into again — the component pass materialized\n * whatever it references, and a component that extends itself through a\n * field (`Node.child: allOf: [{ $ref: Node }, …]`) is typed as the\n * `NodeChild` that exists instead of being re-extracted without end. Only\n * the merged model's own properties — the inline members' and the variants'\n * — are re-entered, under `name`, with the full merged property set as\n * siblings. An own property that is itself a merge on the path to this one\n * is not built again: a component that extends itself through a field its\n * inline member redeclares (`Note.reply: allOf: [{ $ref: Note }, {\n * properties: { quoted, reply: { properties: { depth } } } }]`) conjoins\n * `Note.reply` with the inline `reply` into one object every merge of\n * `Note` owns (`combinedDeclarations`), so `NoteReply { id, reply, quoted }`\n * re-enters it as `NoteReplyReply { id, reply, quoted, depth }`, whose own\n * `reply` is that same conjunction — typed as the `NoteReplyReply` being\n * built for it (`materializingMergedAllOfName`), and left there (the\n * typeless `reply: { description }` and the array `replies` forms, and two\n * components that do this to each other, end the same way; workos/oagen#566:\n * each merge built a new conjunction that was re-entered under a longer name\n * without end). The path is keyed by the declaration a schema stands for\n * (`sourceDeclaration`), not by the schema handed in, so the same holds\n * under a nullable wrapper of any spelling, or a single-member `allOf`\n * wrapper: a typeless redeclaration annotates the conjunction without\n * stripping the wrapper, every unwrap of it makes a copy\n * (`unwrapNullableField`), and the copy is read as the declaration it was\n * spread from (workos/oagen#566 review: the guard never met the same copy\n * twice, and a nullable `Note.reply` beside `reply: { description }` still\n * overflowed). Shared by the field extractor and `extractInlineModelDeep`,\n * so a field nested under a discriminated component variant is built exactly\n * as the same field anywhere else.\n */\nexport function materializeMergedAllOf(\n  name: string,\n  schema: SchemaObject,\n  results: Model[],\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): void {\n  // Already being built on this path: the reference that named this\n  // re-entry resolves to the model under construction (see above). The\n  // path is keyed by the declaration `schema` stands for, so a copy a\n  // stripped wrapper left is the merge it was spread from.\n  const declaration = sourceDeclaration(schema);\n  if (materializingMergedAllOf.has(declaration)) return;\n  materializingMergedAllOf.set(declaration, name);\n  try {\n    const merged = mergeAllOfMembers(schema, componentSchemas);\n    results.push(buildMergedModel(name, merged, componentSchemas));\n    // Properties are matched by own name throughout the merge (a `Map` there,\n    // `Object.fromEntries` here), so a property named `constructor`,\n    // `toString` or `__proto__` is kept and re-entered like any other.\n    const own = Object.fromEntries(merged.properties.filter((p) => p.origin === null).map((p) => [p.name, p.schema]));\n    const mergedSiblings = new Map(merged.properties.map((p) => [p.name, p.schema]));\n    extractInlineModelsFromProperties({ properties: own }, results, name, componentSchemas, mergedSiblings);\n  } finally {\n    materializingMergedAllOf.delete(declaration);\n  }\n}\n\n/**\n * The merged `allOf` schemas `materializeMergedAllOf` is building models\n * for, by the name each is built under: the path of merges the extraction\n * is inside, from a component's field or a body down to the own property\n * being re-entered. A merge that reaches one of them again is the one\n * conjunction built once more (`combinedDeclarations`), so the field is\n * typed as the model on the path (`materializingMergedAllOfName`, read by\n * `schemaToTypeRef`) and the re-entry builds nothing (workos/oagen#566).\n *\n * The identity rule: a merge is the declaration that carries its `allOf` —\n * a document's own object, or the conjunction `combineDeclarations`\n * memoizes for two of them — and every schema is keyed by the declaration\n * it stands for (`sourceDeclaration`), so a copy a reader spreads from one\n * — a nullable wrapper stripped, sibling properties folded, a wrapper's\n * documentation or limits carried onto the branch it collapses to, a type\n * list read one type at a time (`derivedCopy`, at each such site) — is the\n * declaration it was spread\n * from, and the extractor and the type builder meet one key for a merge\n * whichever wrapper each strips. A transform that memoizes its copy per\n * declaration composes with the rule, since the one copy is itself a\n * stable key; one that records its copy resolves to the declaration. Under\n * a nullable wrapper the two spellings that flag the schema (`nullable:\n * true`, `type: ['object', 'null']`) key the field's declaration itself,\n * and a `oneOf: [{ allOf }, { type: 'null' }]` or single-member `allOf`\n * wrapper keys the branch or member that carries the `allOf`, which the\n * wrapper and a conjunction annotating it share. Empty between extractions.\n */\nlet materializingMergedAllOf = new Map<SchemaObject, string>();\n\n/** The name `materializeMergedAllOf` is building the model for the declaration `schema` stands for under (`sourceDeclaration`), on the path the extraction is inside; `undefined` off it. */\nexport function materializingMergedAllOfName(schema: SchemaObject): string | undefined {\n  return materializingMergedAllOf.get(sourceDeclaration(schema));\n}\n\n/**\n * `build()` with no merge in progress as far as `schemaToTypeRef` sees\n * (`materializingMergedAllOfName`): how an inherited property is typed, so\n * it carries exactly the TypeRef its component's model carries — typed\n * outside any merge — whatever merge of the same declaration is being built\n * on the path, as `recordInheritedModelRefs` requires of the copy.\n */\nfunction typedOutsideMerges<T>(build: () => T): T {\n  const inside = materializingMergedAllOf;\n  materializingMergedAllOf = new Map();\n  try {\n    return build();\n  } finally {\n    materializingMergedAllOf = inside;\n  }\n}\n\n/**\n * The merged shape as one object schema, for a site that builds its model\n * from a schema rather than from the merged list (`extractDirectResource`:\n * the primary success body and each further success code's — every other\n * body site builds from the list): every property under its name in\n * merged order, the collected `required`, the wrapper's limits conjoined\n * with its inline members', and the wrapper layer's `description`,\n * `deprecated`, link and `x-*` keys, exactly as `buildMergedModel` carries\n * them onto the model a field's merge builds — a member's stay on that\n * member, a `$ref` member's on its component. So the model built from the\n * schema (`buildInlineModel`) is documented as the model built from the\n * list is: a response body `{ allOf: [{ $ref: Base }, { properties: { name\n * } }, { description: 'A pet.' }] }` is described \"A pet.\", as the same\n * schema is as a request body, a field, a secondary media type's or an\n * error body (#604: the text alone was left off here, kept off from before\n * the merge read the wrapper layer at all, so `CreatePetResponse` had none\n * while `CreatePetRequest` did).\n */\nexport function mergedObjectSchema(merged: MergedAllOf): SchemaObject {\n  return {\n    type: 'object',\n    properties: Object.fromEntries(merged.properties.map((p) => [p.name, p.schema])),\n    required: merged.required,\n    ...(merged.description !== undefined ? { description: merged.description } : {}),\n    ...(merged.deprecated ? { deprecated: true } : {}),\n    ...merged.constraints,\n    ...(merged.externalDocs ? { externalDocs: merged.externalDocs } : {}),\n    ...merged.extensions,\n  };\n}\n\n/**\n * Build the model for a merged `allOf` field. An inherited property is typed\n * with its component as naming context and the component's own sibling set,\n * so it carries the same TypeRef as in the component's model (`BaseMeta`,\n * `BaseChild`, ...); the merged model's own properties are typed under its\n * name with the full merged property set as siblings.\n */\nfunction buildMergedModel(name: string, merged: MergedAllOf, componentSchemas?: Record<string, SchemaObject>): Model {\n  const requiredSet = new Set(merged.required);\n  const mergedSiblings = new Map(merged.properties.map((p) => [p.name, p.schema]));\n  const componentSiblings = new Map<string, Map<string, SchemaObject>>();\n  const fields = merged.properties.map((p) => {\n    if (p.origin === null) {\n      return buildFieldFromSchema(p.name, p.schema, name, requiredSet, componentSchemas, mergedSiblings);\n    }\n    const origin = p.origin;\n    const siblings = componentSiblings.get(origin.name) ?? collectProperties(origin.schema, componentSchemas);\n    componentSiblings.set(origin.name, siblings);\n    // The field is a copy of the component's own, typed as the component's\n    // model typed it (`typedOutsideMerges`): whatever inline model its\n    // references name is the one the component's field references, so they\n    // are recorded under that field and follow its model wherever it goes.\n    const field = typedOutsideMerges(() =>\n      buildFieldFromSchema(p.name, p.schema, origin.name, requiredSet, componentSchemas, siblings),\n    );\n    recordInheritedModelRefs(field.type, origin.name, p.name);\n    return field;\n  });\n  return {\n    name,\n    description: merged.description,\n    ...(merged.externalDocs ? { externalDocs: merged.externalDocs } : {}),\n    fields,\n    ...(merged.deprecated ? { deprecated: true } : {}),\n    ...(merged.constraints ? { constraints: merged.constraints } : {}),\n    ...(merged.extensions ? { extensions: merged.extensions } : {}),\n  };\n}\n\n/**\n * The schema that types a map's values, in the precedence `schemaToTypeRef`\n * uses: a non-empty `additionalProperties` object wins, otherwise the first\n * `patternProperties` entry. `additionalProperties: {}` means \"any value\"\n * (typed `unknown`, nothing to extract) and does not fall through to\n * `patternProperties`, matching the type-ref branch.\n */\nexport function mapValueSchema(schema: SchemaObject): SchemaObject | null {\n  const additional = schema.additionalProperties;\n  if (additional && typeof additional === 'object') {\n    return Object.keys(additional).length > 0 ? additional : null;\n  }\n  const patterns = schema.patternProperties ? Object.values(schema.patternProperties) : [];\n  return patterns[0] ?? null;\n}\n\n/**\n * The model for an inline object: its properties as fields, typed under\n * `name`, with its description and constraints. Shared with the named-union\n * extractor in schemas.ts, which materializes a union's inline object variants\n * exactly as the union branch below does.\n */\nexport function buildInlineModel(\n  name: string,\n  schema: SchemaObject,\n  componentSchemas?: Record<string, SchemaObject>,\n): Model {\n  const requiredSet = new Set(schema.required ?? []);\n  const fields: Field[] = [];\n  const siblings = collectProperties(schema);\n\n  for (const [fieldName, fieldSchema] of Object.entries(schema.properties ?? {})) {\n    if (!fieldSchema) continue;\n    fields.push(buildFieldFromSchema(fieldName, fieldSchema, name, requiredSet, componentSchemas, siblings));\n  }\n\n  return {\n    name,\n    description: schema.description,\n    ...externalDocsEntry(schema.externalDocs),\n    fields,\n    ...deprecatedEntry(schema),\n    ...constraintsEntry(schema),\n    ...schemaExtensionsEntry(schema),\n  };\n}\n","/**\n * Settling the references `schemaToTypeRef` leaves pending for a schema\n * `$ref` that names no component (#539): a JSON Pointer deeper into one\n * (`#/components/schemas/Pet/properties/owner`), or a `$ref` into another\n * section of the document.\n *\n * Such a site is typed as the schema the pointer lands on is typed where it\n * stands — `Pet.owner`'s field type for `Pet/properties/owner`, so the\n * site references `PetOwner`, the model the component pass built for the\n * field, and never a copy of it; `string` for `Pet/properties/id`; the\n * items of the array `Pets` resolves to for `Pets/items`. The parser knows\n * that type only once every model is built, so the type builder marks the\n * site pending (`pendingSchemaRef`) and this pass, run once the components,\n * their fields' models, the operations and the webhooks are extracted and\n * before any merge pass renames a model, walks the pointer through the IR\n * alongside the document — from the component's own type\n * (`componentTypeRef`), through `properties/<name>` to that field's type,\n * `items` to the array's items, `additionalProperties` or\n * `patternProperties/<pattern>` to the map's values — through the member\n * of a multi-type schema's union that carries the keyword (`type:\n * ['object', 'string']` is a union of one member per type, so its\n * `properties/<name>` are the object member's fields, its `items` the\n * array member's) — when that schema is\n * the one the map's values are typed from (`mapValueSchema`: a non-empty\n * `additionalProperties`, else the first pattern; `additionalProperties:\n * {}` types them `unknown`), so `patternProperties/^n` beside a first\n * pattern `^s` names no type, never the other pattern's — or, for a model\n * with named properties, to the catch-all `additionalProperties` field's\n * values (`Box/additionalProperties` is `integer` for `Box: { properties:\n * { id }, additionalProperties: { type: integer } }`), `oneOf/<n>` or\n * `anyOf/<n>` to the union's or the named union's n-th non-null variant\n * (the one non-null member of a union collapsed to a nullable wrapper is\n * the wrapper's inner type whole, a union of its own or a named union\n * included),\n * and `allOf/<n>` to the member's own type: a `$ref` member's reference,\n * or, for the one member the `allOf` is read as (its one typing member\n * beside members that only annotate it; #555), the `allOf`'s own type —\n * and writes the type it reaches into the pending reference in place\n * (`replaceTypeRef`), so every holder keeps the object it holds. A pointer\n * that leads nowhere is reported once, at the site, and the site typed\n * `unknown`: one into another section, to a component the document lacks,\n * to no schema (`Pet/properties/id/type`, `Pet/enum/0`), or to a schema\n * the parser builds no type for at that place (a `null` variant, an enum's\n * own members, a keyword it never reads, the fields of an enum or\n * primitive component, and any other inline `allOf` member, which declares\n * into the merged model and has no type of its own — `Pet/allOf/1` beside\n * a `$ref` member, though `Pet/allOf/1/properties/nickname` reads on\n * through it to the merged model's field), and a chain of pointers that\n * reaches itself — through a field whose type is the site, or through an\n * array component whose items point back into it. Pointers are followed as\n * RFC 6901 §4 evaluates them, structurally, never through a `$ref` on the\n * way (`schemaAtPointer`); a pointer that lands on a `$ref` schema is typed\n * as that `$ref` is.\n *\n * The limits are settled with the type (#545 review). A `$ref` to a\n * primitive or array component gives the site the component's limits\n * conjoined with what is written beside the reference (`schemaConstraints`),\n * and a pointer site reads the same once its type is known: the type the\n * site is settled into carries the limits of the schema the pointer lands\n * on — what its own type carries where it stands, under every nullable\n * wrapper it settles into (`underNullableWrappers`: a chain through a\n * nullable link to a nullable schema wears two), the conjoined reading of\n * a chain included — conjoined with the\n * site's own (`combineConstraints`, the component's first, the stricter\n * bound winning: what is written beside the pointer, then around a\n * wrapper the type builder reads through, as `withTypeConstraints`\n * records them), and a field or parameter whose type that is carries the\n * same (`Field.constraints`, `Parameter.constraints`), so `{ $ref:\n * '#/components/schemas/Owner/properties/code', maxLength: 3 }` to `{\n * type: 'string', pattern: '^own_', maxLength: 8 }` is `{ maxLength: 3,\n * pattern: '^own_' }` on the field, the parameter and the type alike, and a\n * bare pointer `{ maxLength: 8, pattern: '^own_' }`. A pointer that lands on\n * a schema typed as a model or enum adds none: that node carries its own,\n * and the site keeps what it wrote beside the `$ref`, as beside a `$ref` to\n * a model component.\n *\n * What a site decided from the pending reference before the settle is\n * decided again from the settled type: an operation whose primary response\n * was pending chooses its iterator's item type from the settled response\n * (`paginatedItemType`), so a paginated response pointing at an array of\n * strings yields strings; an explicit `dataPath` whose walk through the IR\n * crossed a pending reference — that response, or a field on the way — is\n * walked again from the settled types, under every nullable wrapper the\n * site settled into, so the iterator yields the model the pointed schema's\n * items are built as, never a copy read from the document\n * (`settleDeferredDataPathItemType`; #608; a path that forks to more than\n * one array was read from the document at extraction, as any such path is);\n * and a discriminator mapping entry written as a pointer is written as the\n * model the schema it points at is built as — a pointer variant's, settled\n * by the walk, or, for a target outside the variants, one settled here at\n * the mapping site (`settleDeferredMappingEntries`).\n */\nimport type {\n  Callback,\n  Constraints,\n  MapType,\n  Model,\n  ModelRef,\n  Operation,\n  Service,\n  TypeRef,\n  UnionType,\n  Webhook,\n} from '../ir/types.js';\nimport {\n  callbackContext,\n  collectRequestBodyTypes,\n  collectResponseBodyTypes,\n  collectResponseHeaders,\n  typeRefConstraints,\n  walkTypeRef,\n} from '../ir/types.js';\nimport {\n  arraySchemaOf,\n  combineConstraints,\n  componentTypeRef,\n  isArrayComponentRef,\n  isArrayPointerRef,\n  isNullSchema,\n  referenceTypesAsUnknown,\n  schemaToTypeRef,\n  withTypeConstraints,\n  type SchemaObject,\n} from './schemas.js';\nimport { allOfTypingMember, cloneTypeRef, mapValueSchema, readInlineAllOf, replaceTypeRef } from './inline-models.js';\nimport {\n  collectObjectProperties,\n  isDeferredDataPathItemType,\n  paginatedItemType,\n  settleDeferredDataPathItemType,\n} from './pagination.js';\nimport {\n  isPendingSchemaRef,\n  isPendingVariant,\n  pendingSiteLimitsOf,\n  schemaAtPointer,\n  schemaRefTokens,\n  settleDeferredMappingEntries,\n  settlePendingSchemaRef,\n} from './schema-refs.js';\n\n/** Where pending references are held: every model built so far — the components', their fields', the operations', the webhooks' — and the operations and webhooks themselves. */\nexport interface SchemaPointerSites {\n  models: readonly Model[];\n  services: readonly Service[];\n  webhooks: readonly Webhook[];\n}\n\nconst UNKNOWN: TypeRef = { kind: 'primitive', type: 'unknown' };\n\n/** A site that carries its own limits beside its type — a field, an envelope field, a parameter — which stay one reading with the type's (`Field.constraints`, `Parameter.constraints`). */\ninterface LimitedSite {\n  type: TypeRef;\n  constraints?: Constraints;\n}\n\n/**\n * `type` under every nullable wrapper: the node that carries a value's\n * limits (`withTypeConstraints` puts them there). A settled site can wear\n * more than one — a pointer to a schema that admits null, written under a\n * nullable wrapper of its own, or reached through a chain whose link is\n * such a wrapper (`Alias.code: { oneOf: [{ $ref: …/Owner/properties/code\n * }, { type: 'null' }] }` to a nullable `Owner.code`), settles into a\n * wrapper around the copied wrapper — so one level is not enough\n * (Greptile, #545 review round 4: a field pointing through that chain with\n * `maxLength: 20` read no target limits, replaced the target's `8` with\n * the `20` and lost its own).\n */\nfunction underNullableWrappers(type: TypeRef): TypeRef {\n  let bare = type;\n  while (bare.kind === 'nullable') bare = bare.inner;\n  return bare;\n}\n\n/**\n * Settle every pending reference among `sites` against the document's\n * `schemas` (see the module comment), in place. Returns the references\n * settled, so the caller can give each to the site of the model it now\n * names (`attachSharedRefs`): a merge pass that renames that model then\n * repoints the reference with the model's own. A reference settled as a\n * variant of a discriminated union is returned as the union — the inline\n * union holding it, or a view onto a named union model's `variants` and\n * `discriminator` — so the rename reaches the mapping entry naming the\n * variant with the variant (`renameVariants`), as it does for a union a\n * site minted; a bare reference would be repointed alone and leave the\n * mapping naming the old name. A mapping entry written as a pointer\n * outside the union's variants (`dog: Shelter/properties/dog` beside a\n * variant `Zoo/properties/dog`; #619) is settled here too, at the mapping\n * site, to the model the schema it points at is built as (`ShelterDog`),\n * and the union — an allOf+oneOf dispatcher's mapping alone, since it\n * holds no variants — is returned as a view with a copy of each settled\n * entry's reference put before its variants, so every entry has a variant\n * of its own there and the rename reaches it as it reaches a variant's:\n * whether the reference is a target's own, a redirected inline variant's\n * held inside a multi-type variant's union, or a variant the union holds\n * that several keys name at once (`mappingEntriesByVariant` hands the j-th\n * entry naming a model to the j-th variant naming it, so a third key on\n * two such variants would be left behind).\n */\nexport function resolveSchemaPointers(\n  sites: SchemaPointerSites,\n  schemas: Record<string, SchemaObject> | undefined,\n): TypeRef[] {\n  const resolver = new PointerResolver(sites.models, schemas);\n  /** Every discriminated union met — the named union models' and the dispatchers' as views — with the site it was met at; their mapping entries are settled once the walk is done. */\n  const unions: Array<{ union: UnionType; context: string }> = [];\n  const visit = (ref: TypeRef, context: string): void => {\n    walkTypeRef(ref, {\n      model: (reference) => {\n        if (isPendingSchemaRef(reference)) resolver.settle(reference, context, new Set());\n      },\n    });\n    collectDiscriminatedUnions(ref, context, unions);\n  };\n  /** A field's or parameter's type settled, then its own limits aligned with the type's (`alignSiteLimits`). */\n  const visitSite = (site: LimitedSite, context: string): void => {\n    visit(site.type, context);\n    resolver.alignSiteLimits(site);\n  };\n\n  for (const model of sites.models) {\n    for (const field of model.fields) visitSite(field, `${model.name}.${field.name}`);\n    for (const variant of model.variants ?? []) visit(variant, `${model.name}.variants`);\n    // A named union's variants and mapping, or an allOf+oneOf dispatcher's\n    // mapping alone (a dispatcher holds no variants), as a view.\n    if (model.discriminator) {\n      unions.push({\n        union: {\n          kind: 'union',\n          variants: model.variants ?? [],\n          ...(model.compositionKind ? { compositionKind: model.compositionKind } : {}),\n          discriminator: model.discriminator,\n        },\n        context: model.name,\n      });\n    }\n  }\n  for (const service of sites.services) {\n    for (const op of service.operations) {\n      visitOperation(op, `${service.name}.${op.name}`, visit, visitSite, sites.models);\n    }\n  }\n  for (const webhook of sites.webhooks) {\n    visitReceived(webhook, `webhooks.${webhook.name}.${webhook.httpMethod}`, visit, visitSite);\n  }\n\n  // Every variant is settled: a mapping entry written as a pointer takes\n  // the model the schema it points at is built as — a variant's, settled\n  // by the walk, or a target of its own, settled now at the mapping site —\n  // and a union holding a settled variant, or whose entry settled to a\n  // model, stands in for them among the references returned, as a view\n  // with a copy of each such entry's reference put before its variants:\n  // `mappingEntriesByVariant` hands the j-th entry naming a model to the\n  // j-th variant naming it, so every entry has a variant of its own there\n  // and follows the rename whatever else names the model (Greptile, #619\n  // review rounds 2 and 4: a reference held inside a multi-type variant's\n  // union, and a third key sharing one pointed model, kept the old name).\n  // A reference settled by the walk is renamed through the view, never\n  // again as a bare reference.\n  const bare = new Set(resolver.settled);\n  const roots: TypeRef[] = [];\n  for (const { union, context } of unions) {\n    const references = settleDeferredMappingEntries(union.discriminator?.mapping, (target, value) =>\n      resolver.settle(target, `${context}.discriminator.mapping.${value}`, new Set(), 'leaving the entry as written'),\n    );\n    const own = union.variants\n      .map(variantModelRef)\n      .filter((ref): ref is ModelRef => ref !== undefined && bare.has(ref));\n    const followed: TypeRef[] = [];\n    for (const reference of references) {\n      const model = variantModelRef(reference);\n      if (model === undefined) continue;\n      followed.push(cloneTypeRef(reference));\n      bare.delete(model);\n    }\n    if (own.length === 0 && followed.length === 0) continue;\n    for (const ref of own) bare.delete(ref);\n    roots.push(followed.length === 0 ? union : { ...union, variants: [...followed, ...union.variants] });\n  }\n  return [...roots, ...resolver.settled.filter((ref) => bare.has(ref))];\n}\n\n/** The map a model carries its `additionalProperties` values in: the last field named `additionalProperties` that is a map (`extractModel` pushes it after the named properties). */\nfunction catchAllField(model: Model | undefined): MapType | undefined {\n  for (let index = (model?.fields.length ?? 0) - 1; index >= 0; index--) {\n    const field = model!.fields[index]!;\n    if (field.name === 'additionalProperties' && field.type.kind === 'map') return field.type;\n  }\n  return undefined;\n}\n\n/** The model reference `variant` is, directly or under its nullable wrapper; `undefined` for any other variant. */\nfunction variantModelRef(variant: TypeRef): ModelRef | undefined {\n  if (variant.kind === 'nullable') return variantModelRef(variant.inner);\n  return variant.kind === 'model' ? variant : undefined;\n}\n\n/** Collect every discriminated union under `ref`, met at `context`, into `out`, the nested ones first. */\nfunction collectDiscriminatedUnions(\n  ref: TypeRef,\n  context: string,\n  out: Array<{ union: UnionType; context: string }>,\n): void {\n  switch (ref.kind) {\n    case 'union':\n      for (const variant of ref.variants) collectDiscriminatedUnions(variant, context, out);\n      if (ref.discriminator) out.push({ union: ref, context });\n      break;\n    case 'array':\n      collectDiscriminatedUnions(ref.items, context, out);\n      break;\n    case 'nullable':\n      collectDiscriminatedUnions(ref.inner, context, out);\n      break;\n    case 'map':\n      if (ref.keyType) collectDiscriminatedUnions(ref.keyType, context, out);\n      collectDiscriminatedUnions(ref.valueType, context, out);\n      break;\n    default:\n      break;\n  }\n}\n\n/**\n * Every type an operation holds, as `validateModelRefs` reads them and\n * `collectOperationTypeRefs` lists them: every parameter location, the\n * cookies' included, the bodies, the primary response and every other\n * success entry's own type, the iterator's, the errors', the headers',\n * every secondary media type's, and the members of its mutually-exclusive\n * parameter groups — a query group's are the operation's own parameters,\n * settled with them; a body group's are built afresh from the body's\n * variant schemas (`extractBodyParameterGroups`), so a member written as a\n * pointer holds a pending reference of its own. A parameter, a group member\n * or an envelope field goes through `visitSite`, which aligns its own\n * limits with its settled type's too. The iterator's item type an explicit\n * `dataPath` deferred (`deferDataPathItemType`) is decided once the\n * response and the envelope fields are settled, by walking the path through\n * `models`, every model built (`settleDeferredDataPathItemType`; #608).\n */\nfunction visitOperation(\n  op: Operation,\n  context: string,\n  visit: (ref: TypeRef, context: string) => void,\n  visitSite: (site: LimitedSite, context: string) => void,\n  models: readonly Model[],\n): void {\n  for (const p of [\n    ...op.pathParams,\n    ...op.queryParams,\n    ...(op.bodyOwnedQueryParams ?? []),\n    ...op.headerParams,\n    ...(op.cookieParams ?? []),\n  ]) {\n    visitSite(p, `${context}.${p.name}`);\n  }\n  if (op.requestBody) visit(op.requestBody, `${context}.requestBody`);\n  // The iterator's item type was chosen from the response as the pending\n  // reference it was — the response itself, since no reference is an array\n  // — so it is chosen again from the settled response: an array's items, as\n  // `detectPagination` reads any response (`paginatedItemType`). Only the\n  // item type taken from the response itself is reread that way — a body\n  // written as the pointer, or a list envelope unwrapped on a `data` written\n  // as one, which hands the pending response over as its item type for this\n  // very reread (`extractListResponse`; #609); one an override or an\n  // envelope decided from an array it could type stands, and one an\n  // explicit `dataPath` deferred is decided below.\n  const responseWasPending = isPendingVariant(op.response);\n  visit(op.response, `${context}.response`);\n  if (responseWasPending && op.pagination && op.pagination.itemType === op.response) {\n    op.pagination.itemType = paginatedItemType(op.response);\n  }\n  for (const entry of op.successResponses ?? []) visit(entry.type, `${context}.successResponses.${entry.statusCode}`);\n  for (const field of op.pagination?.envelopeFields ?? []) visitSite(field, `${context}.pagination.${field.name}`);\n  // An explicit `dataPath` whose walk crossed a pending reference at\n  // extraction — the response itself, a companion or a field on the way —\n  // left a placeholder (`deferDataPathItemType`): with the response, the\n  // companions and every model's fields settled, the path is walked again\n  // through the IR, so the iterator yields the model the pointed schema's\n  // items are built as, never a copy read from the document (#608).\n  if (op.pagination && isDeferredDataPathItemType(op.pagination.itemType)) {\n    settleDeferredDataPathItemType(op.pagination, op.response, models, context);\n  }\n  if (op.pagination) visit(op.pagination.itemType, `${context}.pagination.itemType`);\n  for (const error of op.errors) if (error.type) visit(error.type, `${context}.errors.${error.statusCode}`);\n  for (const header of collectResponseHeaders(op)) visit(header.type, `${context}.headers.${header.name}`);\n  for (const { type, source } of collectResponseBodyTypes(op)) visit(type, `${context}.${source}`);\n  for (const { type, source } of collectRequestBodyTypes(op)) visit(type, `${context}.${source}`);\n  for (const group of op.parameterGroups ?? []) {\n    for (const variant of group.variants) {\n      for (const p of variant.parameters)\n        visitSite(p, `${context}.parameterGroups.${group.name}.${variant.name}.${p.name}`);\n    }\n  }\n  visitCallbacks(op, context, visit, visitSite);\n}\n\n/** A webhook's or a callback's sites — its parameters, payload and secondary payloads — and its callbacks' after them. */\nfunction visitReceived(\n  node: Webhook,\n  context: string,\n  visit: (ref: TypeRef, context: string) => void,\n  visitSite: (site: LimitedSite, context: string) => void,\n): void {\n  for (const p of [...node.headerParams, ...node.queryParams, ...(node.cookieParams ?? [])]) {\n    visitSite(p, `${context}.${p.name}`);\n  }\n  if (node.requestBody) visit(node.requestBody, `${context}.requestBody`);\n  for (const content of node.requestBodyContents ?? []) {\n    if (content.type !== node.requestBody) visit(content.type, `${context}.requestBodyContents.${content.contentType}`);\n  }\n  visitCallbacks(node, context, visit, visitSite);\n}\n\n/** Each callback of an operation, webhook or callback, under `<context>.callbacks.<name>.<expression>.<method>` (#382). */\nfunction visitCallbacks(\n  node: { callbacks?: Callback[] },\n  context: string,\n  visit: (ref: TypeRef, context: string) => void,\n  visitSite: (site: LimitedSite, context: string) => void,\n): void {\n  for (const callback of node.callbacks ?? []) {\n    visitReceived(callback, callbackContext(context, callback), visit, visitSite);\n  }\n}\n\n/** The keywords a pointer steps through with a name or index after them; every other keyword the walk reads holds one schema. */\nconst KEYED_STEP_KEYWORDS: ReadonlySet<string> = new Set([\n  'properties',\n  'patternProperties',\n  'allOf',\n  'oneOf',\n  'anyOf',\n]);\n\n/** One step of a pointer's walk: from `node`, through `keyword` (and the `name` or index after it), to `next`. */\nexport interface PointerStep {\n  keyword: string;\n  name: string | undefined;\n  node: SchemaObject;\n  next: SchemaObject;\n}\n\n/**\n * The steps a pointer `path` makes from `component`, read from the document\n * alone, or the reason the parser types nothing at the end of it: the one\n * grammar the settle walks (`PointerResolver.resolve`, which then reads the\n * IR along the steps) and the primary-response pick reads ahead of the IR\n * (`pointerTypesAsUnknown`), so a pointer counts as typed exactly when the\n * settle types it. Each step goes through a keyword the IR holds a type\n * under — `properties/<name>`, `items`, `additionalProperties`,\n * `patternProperties/<pattern>`, `oneOf/<n>`, `anyOf/<n>`, `allOf/<n>` —\n * to a schema (`schemaAtPointer`); a `oneOf`/`anyOf` step to the `null`\n * variant leads to no type (the IR carries it as nullability), nor does any\n * other keyword (`not`, `prefixItems`, `$defs`, …: the parser types nothing\n * under it), nor an `additionalProperties` or `patternProperties/<p>` step\n * to a schema the map's values are not typed from (`mapValueSchema`: a\n * non-empty `additionalProperties` wins, else the first pattern, and\n * `additionalProperties: {}` types the values `unknown` on its own) or to\n * a pattern beside named properties, which no field carries, nor an\n * `allOf` step that ends the pointer at an inline member\n * the `allOf` is not read as (`readInlineAllOf`): the member declares into\n * the merged model, or only annotates the member the `allOf` is read as,\n * and has no type of its own — while an `allOf` step on the way through\n * (`allOf/1/properties/nickname`) reads on to the merged model's field.\n */\nexport function pointerSteps(\n  component: SchemaObject,\n  path: readonly string[],\n  schemas: Record<string, SchemaObject> | undefined,\n): PointerStep[] | { problem: string } {\n  const steps: PointerStep[] = [];\n  let node = component;\n  for (let index = 0; index < path.length; index++) {\n    const keyword = path[index]!;\n    const name = KEYED_STEP_KEYWORDS.has(keyword) ? path[++index] : undefined;\n    const next = schemaAtPointer(node, name === undefined ? [keyword] : [keyword, name]);\n    if (!next) return { problem: 'no schema at that pointer' };\n    switch (keyword) {\n      case 'properties':\n      case 'items':\n        break;\n      case 'additionalProperties':\n      case 'patternProperties': {\n        // The IR types a map's values from one schema; a model with named\n        // properties carries a non-empty `additionalProperties` as its\n        // catch-all field and no pattern at all.\n        const represented = mapValueSchema(node);\n        const named = Object.keys(node.properties ?? {}).length > 0;\n        if (keyword === 'patternProperties' && named)\n          return { problem: `a schema with named properties types no \"${keyword}/${name}\" values` };\n        if (represented !== next && !(keyword === 'additionalProperties' && represented === null && !named))\n          return {\n            problem: `the values are typed from another schema than \"${keyword}${name === undefined ? '' : `/${name}`}\"`,\n          };\n        break;\n      }\n      case 'oneOf':\n      case 'anyOf':\n        if (isNullSchema(next))\n          return { problem: `\"${keyword}/${name}\" is the null variant, which the IR carries as nullability` };\n        break;\n      case 'allOf':\n        if (!next.$ref && index === path.length - 1 && !allOfReadAsMember(node, next, schemas))\n          return { problem: `\"${keyword}/${name}\" is an inline allOf member, which has no type of its own` };\n        break;\n      default:\n        return { problem: `the parser types nothing under \"${keyword}\"` };\n    }\n    steps.push({ keyword, name, node, next });\n    node = next;\n  }\n  return steps;\n}\n\n/** Whether `schema`'s `allOf` is read as its inline `member` — the one typing member beside members that only annotate it — so the member's type is the `allOf`'s own. */\nfunction allOfReadAsMember(\n  schema: SchemaObject,\n  member: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): boolean {\n  const members = schema.allOf ?? [];\n  if (readInlineAllOf(members, schema, schemas) !== 'unwrapped') return false;\n  return (allOfTypingMember(members) ?? members[0]) === member;\n}\n\n/**\n * The schema a pointer `ref` lands on, read ahead of the IR from the\n * document alone — the component the `$ref` starts from, then the steps\n * the settle will walk (`pointerSteps`) — or `undefined` when the settle\n * types nothing at the end of it: a `$ref` into another section, to a\n * component the document lacks, to no schema, or to a schema the parser\n * builds no type for at that place. The one read for every reader that\n * must know what a pointer settles to before a body is typed\n * (`pointerTypesAsUnknown`, `pointerTypesAsArray`), so each counts a\n * pointer as typed exactly when the settle types it.\n *\n * A pointer that ends at a `properties/<name>` step lands on the\n * declaration the settle types that step from: the field of the model at\n * hand, which an `allOf` merges from every member that declares the name\n * (`combineDeclarations`: the first declaration that declares a type\n * types it, a typeless one only annotating it) — so the declaration is\n * read as `collectObjectProperties` merges it, from the schema whose\n * `allOf` the step goes through (`Holder` for `Holder/allOf/1/properties/\n * owners`, however many inline `allOf` steps lead there; `box` for\n * `Holder/properties/box/allOf/1/properties/owners`) or the schema the\n * step reads directly (its own `allOf` and sibling `properties` folded\n * in), never as the member's own text alone: `Holder/allOf/1/properties/\n * owners` to a member declaring `owners: { description }` beside one\n * declaring `owners: Owner[]`, or a `$ref` member to a component that\n * does, is the array the merged `Holder.owners` is (Greptile, #609\n * review: the member's text alone read no array, and the envelope's data\n * was not one here while the settle typed it `Owner[]`).\n */\nfunction pointerLanding(ref: string, schemas: Record<string, SchemaObject> | undefined): SchemaObject | undefined {\n  const tokens = schemaRefTokens(ref);\n  if (!tokens) return undefined;\n  const [key, ...path] = tokens;\n  const component = schemas && Object.hasOwn(schemas, key!) ? schemas[key!] : undefined;\n  if (!component) return undefined;\n  const steps = pointerSteps(component, path, schemas);\n  if ('problem' in steps) return undefined;\n  if (steps.length === 0) return component;\n  const last = steps[steps.length - 1]!;\n  if (last.keyword !== 'properties') return last.next;\n  // The schema whose merge the field belongs to: the one before the run of\n  // inline `allOf` steps the `properties` step sits in, else the step's own.\n  let first = steps.length - 1;\n  while (first > 0 && steps[first - 1]!.keyword === 'allOf') first--;\n  const owner = steps[first]!.node;\n  return collectObjectProperties(owner, schemas).properties[last.name!] ?? last.next;\n}\n\n/** The pointers being read ahead of the IR (`pointerTypesAsUnknown`), so a chain that reaches itself ends. */\nconst pointersBeingRead = new Set<string>();\n\n/**\n * Whether a site written as `ref`, a schema `$ref` that names no component,\n * settles to the bare `unknown` — decided from the document before any\n * model is built, for the reader that must know before a body is typed\n * (`referenceTypesAsUnknown`, choosing the primary response: a `200` body\n * pointing at an untyped schema loses to a typed `201`, as the same schema\n * written inline would). True when the pointer leads nowhere (into another\n * section, to a component the document lacks, to no schema) or to a schema\n * the parser builds no type for at that place (`pointerLanding`), and\n * otherwise exactly when the schema it lands on is typed `unknown` where\n * it stands, read as a body written there is (`referenceTypesAsUnknown`:\n * `{}`, a `$ref` to an untyped primitive component, an `allOf` read as\n * one) — a `properties/<name>` step landing on the declaration the merged\n * model's field is typed from, every `allOf` member's combined\n * (`pointerLanding`), so a member's `{ description }` beside a typed\n * declaration is typed. A chain of pointers that reaches itself is read as\n * the settle reads it, `unknown`.\n */\nexport function pointerTypesAsUnknown(ref: string, schemas: Record<string, SchemaObject> | undefined): boolean {\n  if (pointersBeingRead.has(ref)) return true;\n  const landed = pointerLanding(ref, schemas);\n  if (!landed) return true;\n  pointersBeingRead.add(ref);\n  try {\n    return referenceTypesAsUnknown(landed);\n  } finally {\n    pointersBeingRead.delete(ref);\n  }\n}\n\n/** The pointers being read for the array they settle to (`pointerTypesAsArray`), so a chain that reaches itself ends. */\nconst pointersBeingTyped = new Set<string>();\n\n/**\n * Whether a site written as `ref`, a schema `$ref` that names no component,\n * settles to an array (#609) — decided from the document before any model\n * is built, for the reader that asks whether a property is an array before\n * a body is typed (`isArrayPointerRef`, for `detectListEnvelope`: a list\n * envelope's `data` written as `{ $ref: '#/components/schemas/Holder/\n * properties/owners' }` is the array `Holder.owners` is, so the envelope is\n * unwrapped on it as it is on `{ $ref: Owners }`). True exactly when the\n * pointer lands on a schema (`pointerLanding`) typed as an array where it\n * stands, read as a property written there is read: an array in any\n * spelling, under any nullable wrapper or `allOf` read as its member\n * (`arraySchemaOf`), a `$ref` to an array component under the same\n * (`isArrayComponentRef`), or another such pointer in turn\n * (`isArrayPointerRef`). False when the pointer leads nowhere or to a\n * schema the parser builds no type for at that place — the settle reports\n * it and types the site `unknown`, no array — and for a chain of pointers\n * that reaches itself, which the settle types `unknown` too. What the\n * document alone cannot refuse is left to the settle, as\n * `pointerTypesAsUnknown` leaves it: a `properties` step through a\n * component typed as a primitive or an enum reads on to the array here,\n * and the settle reports the site and types it `unknown`.\n */\nexport function pointerTypesAsArray(ref: string, schemas: Record<string, SchemaObject> | undefined): boolean {\n  if (pointersBeingTyped.has(ref)) return false;\n  const landed = pointerLanding(ref, schemas);\n  if (!landed) return false;\n  pointersBeingTyped.add(ref);\n  try {\n    return arraySchemaOf(landed) !== undefined || isArrayComponentRef(landed) || isArrayPointerRef(landed, schemas);\n  } finally {\n    pointersBeingTyped.delete(ref);\n  }\n}\n\n/** The walk one document's pending references are settled by; `settled` collects them. */\nclass PointerResolver {\n  readonly settled: TypeRef[] = [];\n  /** `settled`, by identity, so a site can tell whether its type was one. */\n  private readonly settledRefs = new Set<TypeRef>();\n  private readonly modelsByName = new Map<string, Model>();\n\n  constructor(\n    models: readonly Model[],\n    private readonly schemas: Record<string, SchemaObject> | undefined,\n  ) {\n    for (const model of models) if (!this.modelsByName.has(model.name)) this.modelsByName.set(model.name, model);\n  }\n\n  /**\n   * Write the type `pending` names into it. `stack` holds the `$ref`s being\n   * settled on the way here, so a pointer that leads back to one still\n   * being settled — through a field whose type is that site, a chain of\n   * pointers, or an array component whose items point back into it — is a\n   * cycle, reported and typed `unknown`. The `$ref`s, not the references:\n   * an array component's items are built afresh at every read\n   * (`componentTypeRef`), so the reference met on the way back is never\n   * the one the walk started from, while its `$ref` is. `outcome` is what\n   * a warning says becomes of the site when the pointer names no type:\n   * typed `unknown`, which the reference is settled to, unless the site\n   * reads the reference for a name alone — a mapping entry, left as\n   * written.\n   */\n  settle(pending: ModelRef, context: string, stack: Set<string>, outcome = 'typing the site as unknown'): void {\n    if (!isPendingSchemaRef(pending)) return;\n    const ref = pending.name;\n    let type: TypeRef | undefined;\n    if (stack.has(ref)) {\n      console.warn(`[oagen] Warning: Circular schema $ref chain starting at \"${ref}\" in ${context} — ${outcome}`);\n    } else {\n      stack.add(ref);\n      type = this.resolve(ref, context, stack, outcome);\n      stack.delete(ref);\n    }\n    settlePendingSchemaRef(pending);\n    const site = pendingSiteLimitsOf(pending);\n    replaceTypeRef(pending, type ?? UNKNOWN);\n    // The settled type carries the pointed schema's limits — what the type\n    // reached carries, under every nullable wrapper it settled into\n    // (`underNullableWrappers`) — conjoined with the site's own, as a `$ref`\n    // to a primitive component carries the component's conjoined with the\n    // site's (see the module comment); a model or enum carries none, and\n    // keeps the site's reading off the type. `pending` is the settled type\n    // now: `replaceTypeRef` rewrote it in place.\n    const settled = pending as TypeRef;\n    const bare = underNullableWrappers(settled);\n    withTypeConstraints(settled, combineConstraints(typeRefConstraints(bare), site));\n    this.settled.push(pending);\n    this.settledRefs.add(pending);\n  }\n\n  /**\n   * Give `site` — a field or parameter — the limits its type carries, when\n   * that type is a reference this pass settled into one that can carry\n   * them: the pointed schema's conjoined with the site's own (`settle`), so\n   * the field or parameter and its type stay one reading, as they are for\n   * a `$ref` to a primitive component (`Field.constraints`; #545 review).\n   * A site whose pointer landed on a model or enum keeps what it wrote\n   * beside the `$ref`: that node carries its own. The settled reference is\n   * the site's type itself, or the inner type of a nullable wrapper the\n   * site wrote around the pointer (`oneOf: [{ $ref }, { type: 'null' }]`),\n   * and is looked up before it is unwrapped: a pointer to a schema that\n   * admits null (`{ type: ['string', 'null'], maxLength: 8 }`) settles into\n   * a nullable wrapper itself, whose inner type carries the limits\n   * (Greptile, #545 review round 2: the wrapper was unwrapped first, so\n   * such a field kept none of its own) — into more than one through a\n   * chain whose link is itself a nullable wrapper, so every wrapper is read\n   * through (`underNullableWrappers`; review round 4).\n   */\n  alignSiteLimits(site: LimitedSite): void {\n    const settled = this.settledRefs.has(site.type)\n      ? site.type\n      : site.type.kind === 'nullable' && this.settledRefs.has(site.type.inner)\n        ? site.type.inner\n        : undefined;\n    if (!settled) return;\n    const bare = underNullableWrappers(settled);\n    if (bare.kind === 'model' || bare.kind === 'enum') return;\n    const limits = typeRefConstraints(bare);\n    if (limits) site.constraints = { ...limits };\n    else delete site.constraints;\n  }\n\n  /** The type `ref` names, or `undefined` after one warning saying why it names none and what becomes of the site (`outcome`, as `settle` takes it). */\n  private resolve(ref: string, context: string, stack: Set<string>, outcome: string): TypeRef | undefined {\n    const fail = (reason: string): undefined => {\n      console.warn(`[oagen] Warning: Unresolved schema $ref \"${ref}\" in ${context}: ${reason} — ${outcome}`);\n      return undefined;\n    };\n    const tokens = schemaRefTokens(ref);\n    if (!tokens) return fail('only a $ref into components/schemas is followed');\n    const [key, ...path] = tokens;\n    const component = this.schemas && Object.hasOwn(this.schemas, key!) ? this.schemas[key!] : undefined;\n    if (!component) return fail(`no component schema \"${key}\"`);\n    const steps = pointerSteps(component, path, this.schemas);\n    if ('problem' in steps) return fail(steps.problem);\n\n    // The reference being settled: a type reached on the way that is itself\n    // pending is settled first, in place, so the walk reads what it names.\n    const settled = (type: TypeRef): TypeRef => {\n      if (type.kind === 'model') this.settle(type, context, stack);\n      return type;\n    };\n    /** `type` under any nullable wrapper, each level settled. */\n    const bareOf = (type: TypeRef): TypeRef => {\n      const own = settled(type);\n      return own.kind === 'nullable' ? settled(own.inner) : own;\n    };\n    const describe = (type: TypeRef): string =>\n      type.kind === 'model' || type.kind === 'enum' ? `${type.kind} \"${type.name}\"` : type.kind;\n    /**\n     * The member of a multi-type schema's union that carries `keyword`: a\n     * `type: ['object', 'string']` schema is typed as a union of one member\n     * per type (`schemaToTypeRef`), so its `properties/<name>` are the\n     * object member's fields, its `items` the array member's, its\n     * `additionalProperties` the map member's values — or the object\n     * member's catch-all field, beside named properties. Any other type,\n     * and a union of some other making, is itself.\n     */\n    const memberCarrying = (bare: TypeRef, node: SchemaObject, keyword: string): TypeRef => {\n      if (bare.kind !== 'union' || !Array.isArray(node.type)) return bare;\n      const kinds = keyword === 'properties' ? ['model'] : keyword === 'items' ? ['array'] : ['map', 'model'];\n      for (const kind of kinds) {\n        const members = bare.variants.map(bareOf).filter((member) => member.kind === kind);\n        if (members.length === 1) return members[0]!;\n      }\n      return bare;\n    };\n\n    let type: TypeRef = componentTypeRef(key!);\n    for (const { keyword, name, node, next } of steps) {\n      const bare = memberCarrying(bareOf(type), node, keyword);\n      switch (keyword) {\n        case 'properties': {\n          const model = bare.kind === 'model' ? this.modelsByName.get(bare.name) : undefined;\n          if (!model) return fail(`${describe(bare)} has no fields to read \"${name}\" from`);\n          const field = model.fields.find((candidate) => candidate.name === name);\n          if (!field) return fail(`model \"${model.name}\" declares no field \"${name}\"`);\n          type = field.type;\n          break;\n        }\n        case 'items':\n          if (bare.kind !== 'array') return fail(`${describe(bare)} is no array to read \"items\" from`);\n          type = bare.items;\n          break;\n        case 'additionalProperties':\n        case 'patternProperties': {\n          if (bare.kind === 'map') {\n            type = bare.valueType;\n            break;\n          }\n          // A model with named properties carries its `additionalProperties`\n          // as a catch-all map field (`extractModel`), the last of its fields\n          // so named; its values are that field's. `pointerSteps` admits no\n          // pattern beside named properties.\n          const model = bare.kind === 'model' ? this.modelsByName.get(bare.name) : undefined;\n          const catchAll = keyword === 'additionalProperties' ? catchAllField(model) : undefined;\n          if (!catchAll) return fail(`${describe(bare)} is no map to read \"${keyword}\" from`);\n          type = catchAll.valueType;\n          break;\n        }\n        case 'oneOf':\n        case 'anyOf': {\n          // The IR carries a union's non-null variants only: the `null`\n          // variant is its nullability (`pointerSteps` stops at it), and a\n          // union of one member beside it is collapsed to a nullable wrapper\n          // (`nullableUnionBranch`), so that member is the wrapper's inner\n          // type whatever it is — a union of its own (`type: ['array',\n          // 'string']`), a named union — read before any variants are\n          // indexed, which would take the member's own first variant for it.\n          const members = node[keyword] ?? [];\n          const nonNull = members.filter((member) => !isNullSchema(member));\n          if (nonNull.length === 1 && members.length > nonNull.length) {\n            type = bare;\n            break;\n          }\n          const variant = nonNull.indexOf(next);\n          const variants =\n            bare.kind === 'union'\n              ? bare.variants\n              : bare.kind === 'model'\n                ? this.modelsByName.get(bare.name)?.variants\n                : undefined;\n          if (variants) {\n            if (variants[variant] === undefined)\n              return fail(`${describe(bare)} carries no variant \"${keyword}/${name}\"`);\n            type = variants[variant];\n          } else if (nonNull.length === 1) {\n            type = bare;\n          } else {\n            return fail(`${describe(bare)} is no union to read \"${keyword}/${name}\" from`);\n          }\n          break;\n        }\n        case 'allOf':\n          // A `$ref` member is typed as the reference it is; an inline member\n          // is the merged model's, or the `allOf`'s own when it is read as\n          // that member — `pointerSteps` has ruled out a pointer that ends\n          // at any other inline member — so the type at hand stays.\n          if (next.$ref) type = schemaToTypeRef(next);\n          break;\n        default:\n          return fail(`the parser types nothing under \"${keyword}\"`);\n      }\n    }\n    // Whatever the type reached holds that is still pending is settled\n    // before the copy is made, so the site never carries a pending copy.\n    walkTypeRef(settled(type), { model: (reference) => this.settle(reference, context, stack) });\n    return type;\n  }\n}\n","import type { Model, ModelRef, Enum, EnumValue, Extensions, Field, TypeRef, Constraints } from '../ir/types.js';\nimport { assertNever, walkTypeRef, collectModelTypeRefs } from '../ir/types.js';\nimport { toPascalCase, cleanSchemaName, stripListItemMarkers, splitWords, numberedName } from '../utils/naming.js';\nimport { externalDocsEntry, readExternalDocs, type RawExternalDocs } from './external-docs.js';\nimport { SCHEMA_CONSUMED_EXTENSIONS, extensionsOf, schemaExtensionsEntry } from './extensions.js';\nimport {\n  componentKeyOf,\n  deferMappingEntry,\n  isPendingSchemaRef,\n  isPendingVariant,\n  markPendingSchemaRef,\n  pendingSchemaRef,\n  pendingSiteLimitsOf,\n  recordPendingSiteLimits,\n  schemaRefTarget,\n  schemaRefTokens,\n} from './schema-refs.js';\nimport { pointerTypesAsArray, pointerTypesAsUnknown } from './schema-pointers.js';\nimport {\n  enumShapeKey,\n  enumValuesOf,\n  inlineEnumDescriptionOf,\n  inlineEnumExtensionsOf,\n  inlineEnumExternalDocsOf,\n  inlineEnumRef,\n  toEnumValue,\n  type EnumMember,\n} from './enum-members.js';\n\n/**\n * Module-level transform set during extractSchemas(). Used by schemaToTypeRef()\n * to apply the same name transform to $ref model/enum references.\n *\n * Receives the cleaned PascalCase name and, when the name is a\n * `components.schemas` key, the raw key exactly as spelled in the document.\n * Names oagen synthesises (inline enums, request-body variant models,\n * title-derived names) pass no second argument.\n */\nlet activeSchemaNameTransform: SchemaNameTransform | null = null;\n\n/**\n * Module-level set of raw `components.schemas` keys for the spec being\n * extracted. resolveSchemaName() consults it to decide whether the name it was\n * handed is a real component key (forwarded to the transform as\n * `originalName`) or a name oagen synthesised (no `originalName`).\n */\nlet activeComponentSchemaKeys: Set<string> = new Set();\n\n/**\n * The document's `components/schemas`, by raw key, while they are read —\n * for a reader that resolves a `$ref` but is handed no map of its own\n * (`schemaToTypeRef`, `mintedInlineNameEntries`), so it decides exactly as\n * the extractors, which are handed the map, decide (`readInlineAllOf`).\n * Set by `extractSchemas`, cleared with the name transform.\n */\nlet activeComponentSchemas: Record<string, SchemaObject> | undefined;\n\n/**\n * The schema a `$ref` points at, from `componentSchemas` when given, else\n * from the document being read: the component it names by key, or the\n * schema a pointer deeper into one lands on (`schemaRefTarget`; #539), so a\n * reader that follows a `$ref` to read what it declares follows\n * `#/components/schemas/Pet/properties/owner` to `Pet`'s `owner` schema.\n */\nexport function componentSchemaOf(\n  ref: string,\n  componentSchemas?: Record<string, SchemaObject>,\n): SchemaObject | undefined {\n  return schemaRefTarget(ref, componentSchemas ?? activeComponentSchemas);\n}\n\n/** The document's `components/schemas` while they are read (`activeComponentSchemas`), for a reader that merges an `allOf` as the extractors do. */\nexport function documentComponentSchemas(): Record<string, SchemaObject> | undefined {\n  return activeComponentSchemas;\n}\n\n/**\n * Module-level set of resolved schema names whose components/schemas entry is\n * an enum (`isEnumComponentSchema`: an `enum:` list, or a `oneOf`/`anyOf` of\n * string consts). Populated by extractSchemas() so schemaToTypeRef()\n * can classify a `$ref` to a top-level enum schema as `kind: 'enum'` instead of\n * `kind: 'model'`. Without this, every `$ref` was naively returned as a model\n * ref, even when the target was a shared enum like `PaginationOrder`.\n */\nlet activeEnumSchemaNames: Set<string> = new Set();\n\n/**\n * Subset of `activeEnumSchemaNames` whose component schema also admits\n * `null` — via an OAS 3.1 `type: [..., 'null']` array, the OAS 3.0\n * `nullable: true` flag, or a literal `null` member in `enum:`. A `$ref` to\n * one of these resolves to `nullable(enum)` so the component's own\n * nullability survives the reference, matching the shape an inline\n * `oneOf: [{ $ref }, { type: 'null' }]` already produces.\n */\nlet activeNullableEnumSchemaNames: Set<string> = new Set();\n\n/**\n * The `components/schemas` keys of the model components that admit `null`,\n * so that, as for a nullable enum, a `$ref` to one of these resolves to\n * `nullable(model)` (`componentTypeRef`): a named union with a `null`\n * variant, an OAS 3.1\n * `type` list with `'null'` or OAS 3.0 `nullable: true`\n * (`isNullableUnionSchema`) — the null variant is not a member\n * (`unionMembers` drops it), so the reference carries it and the IR says\n * what the inline form of the same union says (`nullable<union>`); and an\n * object component whose own schema `schemaToTypeRef` wraps in `nullable`\n * when it is written inline (`declaresNull`; #615) — `PetOwner: { type:\n * ['object', 'null'], properties }`, `{ type: 'object', nullable: true,\n * properties }`, `{ oneOf: [{ type: 'object', properties }, { type: 'null'\n * }] }`, a single-member `allOf` around one of these — whose model carries\n * its fields and no wrapper, so the reference carries it: `{ $ref: PetOwner\n * }` is `nullable<PetOwner>`, as `Pet.owner` written inline is and as the\n * JSON Pointer `#/components/schemas/Pet/properties/owner` to that inline\n * field is (#539); and an alias of either — an `allOf` read as its `$ref`\n * member (`PetOwnerAlias: { allOf: [{ $ref: PetOwner }] }`), as the same\n * `allOf` on a field is typed, or a bare `$ref` (`PetOwnerAlias: { $ref:\n * PetOwner }`; #618), at every hop of a chain — while an `allOf` that merges a typing\n * member beside the `$ref` (`Cat: { allOf: [{ $ref: PetOwner }, {\n * properties }] }`) is the object its merged fields describe, bare, as it\n * is on a field (`isNullableModelComponentEntry`). Keyed by the component\n * key the `$ref` names, as the array, primitive and alias components are,\n * never by the resolved name the reference is minted with: `Note: { type:\n * ['object', 'null'], properties }` and `note: { type: 'object', properties\n * }` resolve to one model `Note`, and only `{ $ref: Note }` admits `null`\n * — `{ $ref: note }` is the bare model (#641 review).\n */\nlet activeNullableModelComponentKeys: Set<string> = new Set();\n\n/**\n * What one extraction remembers about its named unions, so each is planned\n * once although the model (`namedUnionEntry`) and the extractor\n * (`extractNamedUnionVariantModels`) both read the plan, and so the\n * whole-document reads every plan makes — each component's shape and each\n * other union's variant names — are made once per document, not once per\n * union per read. Every entry is derived from the document being extracted\n * under `activeComponentSchemaKeys` and the active name transform, so the\n * memo is created where those are set (`extractSchemas`) and dropped with\n * them; outside an extraction nothing is memoized.\n */\ninterface NamedUnionMemo {\n  /** Each named union's plan, keyed by its schema; `name` and `schemas` are checked so a different read is never served a stale plan. */\n  plans: WeakMap<\n    SchemaObject,\n    { name: string; schemas: Record<string, SchemaObject> | undefined; plan: NamedUnionPlan | null }\n  >;\n  /** `schemaShapeKey` of every component schema and variant a plan compares, hashed once. */\n  shapes: WeakMap<SchemaObject, string>;\n  /** Each named union's inline variants named in isolation (`otherNamedUnionVariantEntries`), read by every other union's plan. */\n  variantEntries: WeakMap<SchemaObject, Map<SchemaObject, InlineVariantName>>;\n  /** `componentModelNames()`, resolved once. */\n  componentNames?: ReadonlySet<string>;\n}\nlet activeNamedUnionMemo: NamedUnionMemo | null = null;\n\n/**\n * What the parser decides about an array component (`isArrayComponentEntry`),\n * decided once per extraction and read by both sides: the reference\n * (`arrayComponentTypeRef`) and the extractor (`extractArrayComponentModels`),\n * so the items' TypeRef and the models and enums minted for them agree by\n * construction — the way a named union's plan serves `namedUnionEntry` and\n * `extractNamedUnionVariantModels`.\n */\ninterface ArrayComponentPlan {\n  /** The `components/schemas` key, as written: what a `$ref` names. */\n  key: string;\n  /** The key's IR name (`resolveSchemaName`): what the items are named from. */\n  name: string;\n  /** The component schema as written. */\n  schema: SchemaObject;\n  /**\n   * The synthetic property the schema is typed and extracted as, under the\n   * component's name: `item`, so the items mint `<Component>Item…`, or the\n   * context the tree stepped to (`item_item`, `item_array_item`, numbered)\n   * when a name it would mint anywhere — the item model, an object nested\n   * under it, an inline enum, a union variant — is already a component's,\n   * another array component's tree's, or another named union's inline\n   * variant's, of a different shape (`planArrayComponent`).\n   */\n  context: string;\n  /** `{ [context]: schema }`: the one-property object both sides read, as a named union's `memberProperties`. */\n  properties: ReadonlyMap<string, SchemaObject>;\n  /** Set once the self-reference warning has been printed, so it is printed once per component. */\n  warnedSelfReference: boolean;\n}\n\n/** Every model and inline enum an array component's item tree mints under one context (`arrayComponentMints`). */\ninterface ArrayComponentMints {\n  models: Model[];\n  /** Each inline enum the items are or hold, by name, with its members. */\n  enums: Map<string, EnumValue[]>;\n}\n\n/**\n * Every array component of the document being extracted, by its\n * `components/schemas` key as written — the key a `$ref` names, so `Notes:\n * { type: array, items: { $ref: Note } }` beside `Note: { type: object }`,\n * two keys `cleanSchemaName` resolves to one name, keep `Note` a model and\n * make `$ref: Notes` the array. Such a component becomes no `Model`; a\n * `$ref` to it resolves to the array itself, and what its items reference\n * is extracted under its resolved name. Planned in `extractSchemas` before\n * any TypeRef is built, because the component loop, the field pass, the\n * operations and the webhooks all resolve references to it, and dropped\n * with the other per-document state (`clearSchemaNameTransform`): outside\n * an extraction a `$ref` to such a key is a plain model reference, as a\n * `$ref` to an enum component is.\n */\nlet activeArrayComponentPlans: Map<string, ArrayComponentPlan> = new Map();\n\n/**\n * Every primitive component of the document being extracted\n * (`isPrimitiveComponentEntry`: a primitive, a `const`, a type list of\n * primitives or a schema that declares no type, or an alias of one), by its\n * `components/schemas` key as written, for the reason an array component is\n * keyed so. Such a component becomes no `Model`: a `$ref` to it resolves to\n * what it declares — the primitive, the literal, the union of primitives or\n * `unknown` (`schemaToTypeRef`; #512, #569). Decided in `extractSchemas`\n * before any TypeRef is built and dropped with the other per-document\n * state, so outside an extraction a `$ref` to such a key is a plain model\n * reference.\n */\nlet activePrimitiveComponentKeys: ReadonlySet<string> = new Set();\n\n/**\n * Every alias of an enum component in the document being extracted — a\n * `components/schemas` entry that is no enum itself but reads through a\n * `$ref` to one (`isEnumComponentAlias`: `PetKind: { $ref: Kind }`, `{\n * allOf: [{ $ref: Kind }, { description }] }`, `{ oneOf: [{ $ref: Kind },\n * { type: 'null' }] }`, an alias of an alias) — by its key as written, for\n * the reason an array component is keyed so. Such an entry becomes no\n * `Model` and no `Enum` of its own: a `$ref` to it resolves to the enum it\n * names, read through the alias as the same schema written inline is\n * (`schemaToTypeRef`; #560). A component that declares its enum inside the\n * `allOf` itself (`Kind: { allOf: [{ type: 'string', enum }], description\n * }`; #588 review), or inside a nullable `oneOf`/`anyOf` wrapper (`Kind: {\n * oneOf: [{ allOf: [{ type: 'string', enum }] }, { type: 'null' }] }`;\n * #606), names no enum component and is none: it is the enum `Kind`\n * (`isEnumComponentSchema`). Decided in `extractSchemas` before any TypeRef\n * is built and dropped with the other per-document state.\n */\nlet activeEnumAliasKeys: ReadonlySet<string> = new Set();\n\n/**\n * The names one discriminated union's variant models take\n * (`planDispatcherVariants`): each object variant's name, and the names in\n * its tree a component's model of the identical shape holds — the\n * component's model stands for the variant's, which is not built.\n */\ninterface DispatcherUnionPlan {\n  names: Map<SchemaObject, string>;\n  shared: Set<string>;\n}\n\n/**\n * The plans of the document's discriminated allOf + oneOf/anyOf components\n * (`planDispatcherVariants`), keyed by the union's variant list and the\n * component's name: what the dispatcher's mapping\n * (`detectAllOfVariantDiscriminator`) and the variant builder\n * (`extractDiscriminatedAllOfVariantModels`) both read, so the mapping names\n * the models built. Decided in `extractSchemas` before any model is built\n * and dropped with the other per-document state; empty while the plans are\n * decided and outside an extraction, when a variant takes the name its const\n * derives (`deriveDiscriminatedVariantName`).\n */\nlet activeDispatcherVariantPlans: Map<readonly SchemaObject[], Map<string, DispatcherUnionPlan>> = new Map();\n\n/** The array components whose reference is being built right now, so a cycle through their items is cut (`arrayComponentTypeRef`). */\nconst resolvingArrayComponents = new Set<string>();\n\n/** Drop `null` from an `enum:` list — it marks nullability, it is not a member. */\nfunction nonNullEnumValues(values: SchemaObject['enum']): (string | number)[] {\n  return (values ?? []).filter((v): v is string | number => v !== null);\n}\n\n/**\n * True when an enum schema admits `null` by any OAS 3.0 / 3.1 spelling: the\n * `nullable: true` flag, a `type` list naming `'null'`, a `null` member in\n * `enum:`, or — for an enum declared as a `oneOf`/`anyOf` of `const`\n * schemas — a `null` variant (`isNullSchema`) that an `enum:` list beside\n * the union does not forbid (`enumListAdmitsNull`).\n */\nfunction isNullableEnumSchema(schema: SchemaObject): boolean {\n  if (schema.nullable === true) return true;\n  if (Array.isArray(schema.type) && schema.type.includes('null')) return true;\n  if (Array.isArray(schema.enum) && schema.enum.includes(null)) return true;\n  return (schema.oneOf ?? schema.anyOf ?? []).some(isNullSchema) && enumListAdmitsNull(schema);\n}\n\n/**\n * Whether an `enum:` list written beside a `oneOf`/`anyOf` of consts lets a\n * `null` variant admit `null`. The keywords apply together, so a\n * list that leaves `null` out forbids it whatever the variant says; a schema\n * with no list admits it.\n */\nfunction enumListAdmitsNull(schema: SchemaObject): boolean {\n  return !Array.isArray(schema.enum) || schema.enum.includes(null);\n}\n\n/**\n * Whether a component schema is an enum: it declares an `enum:` list, or it\n * is a `oneOf`/`anyOf` whose every non-null variant is a string `const`\n * schema (`constUnionEnumMembers`) with no `allOf` that types the schema\n * (`allOfTypesSchema`: one whose members only annotate or limit it is part\n * of the wrapper, so `Kind: { allOf: [{ description }], oneOf: [{ const:\n * 'cat' }, { const: 'dog' }] }` is the enum `Kind` the same keys beside\n * the `oneOf` make it, as the same schema is inline; #613 review) and no\n * `properties` of its own — the OAS 3.1 spelling that documents and\n * deprecates values one by one — or it declares either inside an `allOf`\n * the type builder reads\n * as its one typing member (`enumComponentDeclaration`: `Kind: { allOf: [{\n * type: 'string', enum: ['cat', 'dog'] }], description }`, a lone member or\n * one beside members that only annotate or limit it, however nested), or\n * inside a nullable `oneOf`/`anyOf` wrapper the type builder collapses\n * (`nullableUnionBranch`: `Kind: { oneOf: [{ allOf: [{ type: 'string',\n * enum }] }, { type: 'null' }] }`, `Color: { oneOf: [{ type: 'string', enum\n * }, { type: 'null' }] }`, the one non-null variant beside `null` variants,\n * however nested; #606), which makes the enum nullable. All become an\n * `Enum` (`extractEnum`), and a `$ref` to any resolves to an `EnumRef`,\n * under `nullable` for the wrapper; the same schemas written inline\n * collapse to an inline enum (`schemaToTypeRef`), so the spellings have\n * one shape wherever they appear. The wrapper's OAS 3.0 form — `nullable:\n * true` beside a `oneOf`/`anyOf` of one variant, since a `null` variant\n * cannot be written there (`flaggedNullableUnionBranch`: `Color: { oneOf:\n * [{ type: 'string', enum }], nullable: true }`) — is the same nullable\n * enum: the flag is read beside a union, where every `$ref` to the\n * component is nullable as it is for a named union\n * (`isNullableUnionSchema`), so the two spellings of one document give\n * one IR and `oagen diff` between them reports nothing (#606 review). A\n * `oneOf` with any other variant — a `$ref`, an object, a number const —\n * is a named union, as before, and so is a `oneOf` of one variant with\n * neither a `null` variant nor the flag: the same schema inline is a\n * union of one. The `allOf` and\n * wrapper spellings name no enum component, so neither is an alias of one\n * (`isEnumComponentAlias`; #588 review and #606: each was read as an\n * alias, and its enum lifted as `UnknownEnum`).\n */\nfunction isEnumComponentSchema(schema: SchemaObject): boolean {\n  return enumComponentDeclaration(schema) !== undefined;\n}\n\n/**\n * The schema an enum component declares its members on, read as the\n * component's own, or `undefined` for a component that is no enum\n * (`isEnumComponentSchema`): the component itself when it declares an\n * `enum:` list or is a `oneOf`/`anyOf` of string consts\n * (`isConstUnionEnumSchema`), or — for a component written as an `allOf`\n * that `readInlineAllOf` reads as its one typing member (`'unwrapped'`: a\n * lone member, or one beside members that declare no type and only\n * annotate or limit it, #555) — that member read as the schema itself\n * (`unwrappedAllOfMember`), in turn, with the wrapper layer's own\n * declarations on it by the one wrapper rule a field written so follows:\n * its `description`, `externalDocs`, `example`, `examples` and `x-*` keys\n * over the member's (`withWrapperDocs`, the wrapper's own winning, then\n * the first annotating member's, the member's standing where the layer has\n * none), its `deprecated` in place of the member's\n * (`withWrapperDeprecation`), its `default` the same way, and its limits\n * conjoined with the member's (`extractConstraints`). So `Kind: { allOf:\n * [{ type: 'string', enum: ['cat', 'dog'] }], description: 'The kind of\n * pet.' }` is read as `Kind: { type: 'string', enum: ['cat', 'dog'],\n * description: 'The kind of pet.' }` is — the enum `Kind`, its text, flag\n * and default on the `Enum`, its limits read by a parameter that names it\n * — and the member's own nullability (a `null` member, a type list naming\n * `'null'`, OAS 3.0 `nullable: true` on the member) is the enum's, while\n * `nullable: true` beside the `allOf` declares nothing, as beside any\n * schema without a `type`. Or — for a component written as a nullable\n * `oneOf`/`anyOf` wrapper the type builder collapses (#606: one non-null\n * variant beside `null` variants, `nullableUnionBranch`) — the branch it\n * collapses to read in turn, carrying what the same wrapper hands a field\n * (`unwrapNullableField`'s layer, laid one level at a time): the wrapper's\n * text, link, examples and keys over the branch's (`withWrapperDocs`), its\n * `deprecated` in place of the branch's own (`withWrapperDeprecation`),\n * its limits conjoined (`extractConstraints`), its `default` over the\n * branch's as the `allOf` layer's is, and the wrapper's `null` variant as\n * the enum's own nullability (`nullable: true` on the declaration, the one\n * spelling that adds no member). A wrapper nested in a wrapper is read as\n * a wrapper of its own, so the nearest outer level's text, flag, key or\n * `default` wins and an inner level's stands where the outer declares\n * none (#606 review: every level was collapsed at once, and an inner\n * level's `default` was lost). A schema with a `$ref` declares no enum\n * whatever sits beside it: it is the reference, as the type builder reads\n * it first (#606 review: `{ $ref: Kind, oneOf: [{ enum }, { type: 'null'\n * }] }` unwrapped to itself and this reader recursed without end). So\n * `Kind: { oneOf: [{ allOf: [{ type: 'string', enum:\n * ['cat', 'dog'] }] }, { type: 'null' }] }`, `Size: { anyOf: [{ allOf: [{\n * type: 'string', enum }, { description: 'The size of the pet.' }] }, {\n * type: 'null' }] }` and `Color: { oneOf: [{ type: 'string', enum }, {\n * type: 'null' }] }` are the enums `Kind`, `Size` (with its text) and\n * `Color`, each nullable, as the same schemas inline are `nullable<enum>`.\n * The OAS 3.0 form of the wrapper, `nullable: true` beside a `oneOf` or\n * `anyOf` of one variant (`flaggedNullableUnionBranch`), is read the\n * same way, so `Color: { oneOf: [{ type: 'string', enum }], nullable: true\n * }` is the nullable enum `Color` in a 3.0.3 document as the `null`\n * variant makes it in a 3.1.0 one (#606 review). A `oneOf` of one variant\n * with neither a `null` variant nor the flag is no wrapper and stays the\n * named union of one it was. A component with `properties` beside the `allOf` or the\n * wrapper is a model, as it is everywhere. Read wherever an enum component\n * is read as a whole: `extractEnum`, the nullability pass of\n * `extractSchemas`, and what a bare `$ref` to it hands a field or\n * parameter (`buildFieldFromSchema`, `extractParams`, through an alias\n * `componentReference`). #588 review: such a component was an alias of\n * nothing — `componentEntries` read the lone member as the entry's own\n * declaration, `isEnumComponentEntry` accepted it, and `schemaToTypeRef`\n * lifted the inline enum under no name as `UnknownEnum`, the wrapper's\n * `deprecated` and limits lost; before #560 it was an empty model. #606:\n * the same through the nullable wrapper, which `componentEntries` unwraps\n * and this reader did not, so `Kind` and `Size` above were aliases of\n * nothing and `UnknownEnum`, `UnknownEnum2` again.\n */\n/**\n * The one variant of a `oneOf`/`anyOf` written with OAS 3.0 `nullable:\n * true` beside it and no `null` variant — `Color: { oneOf: [{ type:\n * 'string', enum }], nullable: true }` — or `undefined`: no union, a union\n * under an `allOf` that types the schema (`allOfTypesSchema`; one whose\n * members only annotate or limit it is part of the wrapper, as for\n * `nullableAxisBranch`, #613), no `nullable: true`, more than one variant,\n * or a `null` variant (`nullableUnionBranch` reads that wrapper). The OAS 3.0\n * form of the nullable wrapper `nullableUnionBranch` collapses, since a\n * `null` variant cannot be written there: beside a `oneOf`/`anyOf` the\n * flag is read — every `$ref` to the component is nullable, as it is for\n * a named union (`isNullableUnionSchema`) — unlike beside an `allOf` or\n * any other schema without a `type`, where it declares nothing. Read\n * where a component is read as an enum (`enumComponentDeclaration`; #606\n * review: the 3.1 spelling read as the enum `Color` while this one stayed\n * a `Color {}` model carrying `ColorVariant1`, so `oagen diff` from the\n * 3.0.3 document to the 3.1.0 one exited 2). A `oneOf` of one variant\n * with neither a `null` variant nor the flag is no wrapper: the union of\n * one it always was, as the same schema inline is.\n */\nfunction flaggedNullableUnionBranch(schema: SchemaObject): SchemaObject | undefined {\n  if (schema.nullable !== true || (schema.allOf !== undefined && allOfTypesSchema(schema.allOf))) return undefined;\n  const variants = schema.oneOf ?? schema.anyOf;\n  if (variants === undefined || variants.length !== 1 || isNullSchema(variants[0]!)) return undefined;\n  return variants[0];\n}\n\nexport function enumComponentDeclaration(schema: SchemaObject): SchemaObject | undefined {\n  // The members on the schema itself — an `enum:` list, or a union of\n  // string consts — beside no `allOf`, or one whose members only annotate\n  // or limit it: the schema with the wrapper layer's text, link, flag,\n  // examples and keys folded in (`allOfWrapperLayer`; the schema itself\n  // without such members) and the layer's `default`, so `Kind: { allOf: [{\n  // description: 'A kind.' }], oneOf: [{ const: 'cat' }, { const: 'dog' }]\n  // }` is the enum `Kind` described \"A kind.\", as `{ description: 'A\n  // kind.', oneOf: [...] }` is and as the same schema is inline (#613\n  // review: it was a model with no fields and no variants, and `oagen diff`\n  // between the two spellings exited 2).\n  if (Boolean(schema.enum) || isConstUnionEnumSchema(schema)) {\n    return withWrapperLayerDefault(allOfWrapperLayer(schema), schema);\n  }\n  // A `$ref` is the reference, whatever sits beside it — the type builder\n  // reads it first — so it declares no enum of its own; an alias is read\n  // through it (`componentEntries`). #606 review: `{ $ref: Kind, oneOf: [{\n  // enum }, { type: 'null' }] }` passed as a wrapper that unwrapped to\n  // itself, and this reader recursed without end.\n  if (schema.$ref || Object.keys(schema.properties ?? {}).length > 0) return undefined;\n  // A nullable wrapper — a `null` variant beside one branch, or the OAS\n  // 3.0 form, `nullable: true` beside a union of one variant\n  // (`flaggedNullableUnionBranch`) — read in turn with this level's layer\n  // on it as `unwrapNullableField` lays a wrapper's on what it unwraps to\n  // — the limits, the text, link, examples and keys, the `deprecated` in\n  // place of the branch's own — one level at a time, so a nested wrapper\n  // is read as a wrapper of its own and its `default` stands where this\n  // level declares none (#606 review); this level's `default` over the\n  // branch's, and its nullability as the enum's.\n  const branch = nullableUnionBranch(schema) ?? flaggedNullableUnionBranch(schema);\n  if (branch !== undefined) {\n    // This level's layer: its own keys, with an annotating `allOf` member's\n    // where it declares none (`allOfWrapperLayer`), so `{ allOf: [{\n    // description }], oneOf: [{ enum }, { type: 'null' }] }` — or with OAS\n    // 3.0 `nullable: true` in the `null` variant's place — is the nullable\n    // enum `{ description, oneOf: [...] }` is (#613 review).\n    const layer = allOfWrapperLayer(schema);\n    const limited = derivedCopy({ ...branch, ...extractConstraints(schema) }, branch);\n    const declaration = enumComponentDeclaration(withWrapperDeprecation(withWrapperDocs(limited, layer), layer));\n    if (declaration === undefined) return undefined;\n    return { ...withWrapperLayerDefault(declaration, schema), nullable: true };\n  }\n  if (!schema.allOf) return undefined;\n  if (classifyInlineSchema(schema) !== 'allOf' || readInlineAllOf(schema.allOf, schema) !== 'unwrapped') {\n    return undefined;\n  }\n  const declaration = enumComponentDeclaration(unwrappedAllOfMember(schema));\n  if (declaration === undefined) return undefined;\n  // The wrapper layer's `default` — the wrapper's own, then the first\n  // annotating member's — over the member's, as its text is.\n  return withWrapperLayerDefault(declaration, schema);\n}\n\n/**\n * The `oneOf`/`anyOf`-of-string-consts half of `isEnumComponentSchema`:\n * beside no `allOf` that types the schema (`allOfTypesSchema`; one whose\n * members only annotate or limit it is part of the wrapper, #613 review)\n * and no `properties` of its own.\n */\nfunction isConstUnionEnumSchema(schema: SchemaObject): boolean {\n  if (schema.allOf !== undefined && allOfTypesSchema(schema.allOf)) return false;\n  if (Object.keys(schema.properties ?? {}).length > 0) return false;\n  return constUnionEnumMembers(schema) !== null;\n}\n\n/**\n * `declaration` with the wrapper layer's `default` — `wrapper`'s own, then\n * the first annotating `allOf` member's (`annotatingAllOfMembers`) — over\n * its own, as the layer's text is (`allOfWrapperLayer`); `declaration`\n * itself when the layer declares none.\n */\nfunction withWrapperLayerDefault(declaration: SchemaObject, wrapper: SchemaObject): SchemaObject {\n  const layer = [wrapper, ...annotatingAllOfMembers(wrapper)].find((level) => level.default !== undefined);\n  return layer === undefined ? declaration : { ...declaration, default: layer.default };\n}\n\n/**\n * `{ description }` holding the first of `candidates` that is a string with\n * non-whitespace content, `{}` when none is — spread into an `EnumMember`.\n */\nfunction descriptionEntry(...candidates: unknown[]): { description?: string } {\n  const text = candidates.find((raw) => typeof raw === 'string' && raw.trim() !== '');\n  return typeof text === 'string' ? { description: text } : {};\n}\n\n/**\n * The members of an enum schema in document order, each with the\n * documentation the document attaches to that one value, from whichever\n * spelling declares them: a `oneOf`/`anyOf` of string `const` schemas\n * (`constUnionEnumMembers`, an `enum:` list beside it restricting the\n * members) first, else an `enum:` list alone (`enumListMembers`). Null when\n * the schema is neither.\n */\nexport function enumMembersOf(schema: SchemaObject): EnumMember[] | null {\n  return constUnionEnumMembers(schema) ?? enumListMembers(schema);\n}\n\n/**\n * The members an `enum:` list declares: each non-null entry (a `null` marks\n * nullability, `isNullableEnumSchema`), a number kept as one and anything\n * else as its string form, described by the schema's `x-enum-descriptions`\n * / `x-enumDescriptions` entry for it (`enumValueDescriptions`). No entry\n * is deprecated: an `enum:` list has no per-value keyword. Null when the\n * schema declares no `enum:`.\n */\nfunction enumListMembers(schema: SchemaObject): EnumMember[] | null {\n  if (!schema.enum) return null;\n  const describe = enumValueDescriptions(schema);\n  const members: EnumMember[] = [];\n  schema.enum.forEach((raw, index) => {\n    if (raw === null) return;\n    const value = typeof raw === 'number' ? raw : String(raw);\n    members.push({ value, ...descriptionEntry(describe(value, index)) });\n  });\n  return members;\n}\n\n/**\n * The members a `oneOf`/`anyOf` of string `const` schemas declares — a\n * single-member string `enum` is the same thing — once its `null` variants\n * are set aside: each variant's `const`, with the variant's own\n * `description` and, when it says `deprecated: true`, `deprecated` (the\n * literal `true` only, as `deprecatedEntry` reads it everywhere). A member\n * whose own `description` has no content takes the schema's\n * `x-enum-descriptions` / `x-enumDescriptions` entry for it\n * (`enumValueDescriptions`), the list form read at the variant's position as\n * written. An `enum:` list written beside the union applies together with\n * it, as JSON Schema keywords do: a member whose value the list leaves out\n * is dropped (so the list may leave no member at all), and the list decides\n * whether a `null` variant admits `null` (`enumListAdmitsNull`).\n * Null when the schema has no `oneOf`/`anyOf`, when every variant is a\n * `null` variant, or when any variant is anything but a string const — a\n * `$ref`, an object, a number const — since such a union is not an enum.\n */\nfunction constUnionEnumMembers(schema: SchemaObject): EnumMember[] | null {\n  const variants = (schema.oneOf ?? schema.anyOf)\n    ?.map((variant, index) => ({ variant, index }))\n    .filter(({ variant }) => !isNullSchema(variant));\n  if (!variants || variants.length === 0) return null;\n  const allowed = schema.enum\n    ? new Set(nonNullEnumValues(schema.enum).map((v) => (typeof v === 'number' ? v : String(v))))\n    : undefined;\n  const describe = enumValueDescriptions(schema);\n  const members: EnumMember[] = [];\n  for (const { variant, index } of variants) {\n    const value =\n      typeof variant.const === 'string'\n        ? variant.const\n        : Array.isArray(variant.enum) && variant.enum.length === 1 && typeof variant.enum[0] === 'string'\n          ? variant.enum[0]\n          : undefined;\n    if (value === undefined) return null;\n    if (allowed && !allowed.has(value)) continue;\n    members.push({\n      value,\n      ...descriptionEntry(variant.description, describe(value, index)),\n      ...deprecatedEntry(variant),\n    });\n  }\n  return members;\n}\n\n/**\n * The per-value descriptions an enum schema's `x-enum-descriptions` or\n * `x-enumDescriptions` extension declares, as a lookup by value and position.\n * Either key may hold an object mapping each value's text form (`\"5\"` for a\n * numeric `5`) to its description, or a list aligned with the members as\n * written — the `enum:` entries, or the `oneOf`/`anyOf` variants, a `null`\n * entry or `type: 'null'` variant counted in its place. `x-enum-descriptions`\n * is read when it holds an object or a list, `x-enumDescriptions` otherwise;\n * an entry that is not a string with non-whitespace content, or a value with\n * no entry, describes nothing (`descriptionEntry`).\n */\nfunction enumValueDescriptions(schema: SchemaObject): (value: string | number, index: number) => unknown {\n  const raw = [schema['x-enum-descriptions'], schema['x-enumDescriptions']].find(\n    (candidate) => typeof candidate === 'object' && candidate !== null,\n  );\n  if (raw === undefined) return () => undefined;\n  if (Array.isArray(raw)) return (_value, index) => raw[index];\n  const byValue = raw as Record<string, unknown>;\n  return (value) => (Object.hasOwn(byValue, String(value)) ? byValue[String(value)] : undefined);\n}\n\n/** Wrap `ref` in `nullable` unless it already is one, so a nullable enum `$ref` is never double-wrapped. */\nfunction asNullable(ref: TypeRef): TypeRef {\n  return ref.kind === 'nullable' ? ref : { kind: 'nullable', inner: ref };\n}\n\n/**\n * Apply cleanSchemaName + the active transform (if any) to a raw schema name.\n * When `rawName` is a `components.schemas` key the transform also receives it\n * as `originalName`, so a consumer can opt out of normalization by returning\n * the original spelling. Names oagen synthesises (request-body variant\n * models, title-derived names, ...) are not component keys and get no\n * `originalName`.\n */\nexport function resolveSchemaName(rawName: string): string {\n  let name = cleanSchemaName(toPascalCase(rawName));\n  if (activeSchemaNameTransform) {\n    const originalName = activeComponentSchemaKeys.has(rawName) ? rawName : undefined;\n    name = activeSchemaNameTransform(name, originalName);\n  }\n  return name;\n}\n\n/**\n * Signature of the `schemaNameTransform` hook. `name` is the cleaned\n * PascalCase name; `originalName` is the `components.schemas` key exactly\n * as spelled in the document, or `undefined` for names oagen synthesises.\n * See `SchemaExtractionOptions.schemaNameTransform`.\n */\nexport type SchemaNameTransform = (name: string, originalName?: string) => string;\n\nexport interface SchemaExtractionOptions {\n  /**\n   * Custom transform for schema (model/enum) names. Called with the cleaned\n   * PascalCase name and, for component schemas, the original name as spelled\n   * in the document (`originalName`). Returning `originalName` opts that\n   * schema out of the built-in normalization; only do so when it is a valid\n   * identifier, since keys like `user-profile` are otherwise fixed by\n   * cleanSchemaName. `originalName` is undefined for\n   * any name oagen synthesises (inline enums, request-body variant models,\n   * title-derived names).\n   */\n  schemaNameTransform?: SchemaNameTransform;\n  /**\n   * The whole OpenAPI document the schemas come from, read once up front for\n   * the rules that look at every inline schema of a root at a time: a\n   * title-mapped union variant keeps its bare title only when no variant of\n   * another shape takes the same title under the same root\n   * (`markContestedTitles`). Without it, the component schemas are the only\n   * root, so a title a request body, response, header, parameter or webhook\n   * payload repeats with another shape is not seen.\n   */\n  document?: unknown;\n}\n\nexport interface SchemaObject {\n  type?: string | string[];\n  format?: string;\n  description?: string;\n  properties?: Record<string, SchemaObject | undefined>;\n  required?: string[];\n  items?: SchemaObject;\n  /** OAS 3.1 allows a literal `null` member when `type` also admits null. */\n  enum?: (string | number | null)[];\n  allOf?: SchemaObject[];\n  oneOf?: SchemaObject[];\n  anyOf?: SchemaObject[];\n  discriminator?: { propertyName: string; mapping?: Record<string, string> };\n  readOnly?: boolean;\n  writeOnly?: boolean;\n  nullable?: boolean;\n  $ref?: string;\n  additionalProperties?: boolean | SchemaObject;\n  const?: unknown;\n  patternProperties?: Record<string, SchemaObject>;\n  deprecated?: boolean;\n  default?: unknown;\n  example?: unknown;\n  /** JSON Schema `examples` list; OAS 3.1 deprecates `example` in its favour. */\n  examples?: unknown[];\n  /** An External Documentation Object as written; `readExternalDocs` decides what reaches the IR. */\n  externalDocs?: RawExternalDocs;\n  // JSON Schema validation vocabulary. An exclusive bound is the bound itself\n  // in OAS 3.1 and, in OAS 3.0, a boolean that makes `minimum` / `maximum`\n  // exclusive; extractConstraints() normalizes both to the 3.1 shape.\n  minimum?: number;\n  maximum?: number;\n  exclusiveMinimum?: number | boolean;\n  exclusiveMaximum?: number | boolean;\n  multipleOf?: number;\n  minLength?: number;\n  maxLength?: number;\n  pattern?: string;\n  minItems?: number;\n  maxItems?: number;\n  uniqueItems?: boolean;\n  minContains?: number;\n  maxContains?: number;\n  minProperties?: number;\n  maxProperties?: number;\n  dependentRequired?: Record<string, string[]>;\n  [key: string]: unknown;\n}\n\n/** Validation keywords copied through unchanged when they hold a number. */\nconst NUMERIC_CONSTRAINT_KEYS = [\n  'multipleOf',\n  'minLength',\n  'maxLength',\n  'minItems',\n  'maxItems',\n  'minContains',\n  'maxContains',\n  'minProperties',\n  'maxProperties',\n] as const;\n\n/**\n * Collect the JSON Schema validation keywords declared directly on `schema`\n * into a `Constraints` object, or `undefined` when it declares none — so a\n * schema without limits yields no `constraints` key on its IR node at all.\n *\n * Numeric bounds are normalized to the OAS 3.1 shape. OAS 3.0 spells an\n * exclusive bound as `exclusiveMinimum: true` beside `minimum: n`; that pair\n * becomes `exclusiveMinimum: n` with no `minimum`. A boolean `false`, or a\n * `true` with no bound to apply to, is dropped. The 3.1 numeric form passes\n * through, including the legal-but-unusual case of both an inclusive and an\n * exclusive bound on the same side. `uniqueItems: false` restates the default\n * and is dropped too.\n *\n * Only the schema's own keywords are read: limits nested inside array `items`\n * or map values are not collected here — they are the items' or values'\n * own, carried on the type built for them (`schemaToTypeRef`; #545). The\n * one exception is a nullable wrapper — a `oneOf`/`anyOf` with a single\n * non-null, non-`$ref` branch — that declares none itself: it takes that\n * branch's keywords, since the IR collapses it to `nullable<T>`. Values of\n * the wrong type (a string `maxLength`, say) are ignored rather than\n * carried.\n */\nexport function extractConstraints(schema: SchemaObject): Constraints | undefined {\n  // The schema's own keywords conjoined with its `allOf` members' (recursively;\n  // a keyword declared at more than one level is combined by\n  // combineConstraints, so the stricter bound wins). schemaToTypeRef unwraps a\n  // single-member `allOf`, so `{ allOf: [{ type: 'string', maxLength: 3 }] }`\n  // is a string whose limit is the value's own; a `$ref` member contributes\n  // the keywords written beside the reference, but the target itself is not\n  // followed — its limits stay on the referenced model.\n  let out = ownConstraints(schema);\n  for (const member of schema.allOf ?? []) out = combineConstraints(out, extractConstraints(member));\n  // A nullable wrapper — `oneOf`/`anyOf` with exactly one non-null branch —\n  // collapses to `nullable<T>` in the IR, so that branch's keywords are the\n  // value's own too and conjoin with the rest. A `$ref` branch keeps its\n  // limits on the referenced model, and a genuine multi-variant union carries\n  // none.\n  const branch = singleNonNullBranch(schema);\n  return branch ? combineConstraints(out, extractConstraints(branch)) : out;\n}\n\n/** The keywords declared strictly on `schema`, normalized — without the nullable-branch fallback. */\nfunction ownConstraints(schema: SchemaObject): Constraints | undefined {\n  const out: Constraints = {};\n\n  const lower = normalizeBound(schema.minimum, schema.exclusiveMinimum);\n  if (lower.inclusive !== undefined) out.minimum = lower.inclusive;\n  if (lower.exclusive !== undefined) out.exclusiveMinimum = lower.exclusive;\n  const upper = normalizeBound(schema.maximum, schema.exclusiveMaximum);\n  if (upper.inclusive !== undefined) out.maximum = upper.inclusive;\n  if (upper.exclusive !== undefined) out.exclusiveMaximum = upper.exclusive;\n\n  for (const key of NUMERIC_CONSTRAINT_KEYS) {\n    const value = schema[key];\n    if (typeof value === 'number') out[key] = value;\n  }\n  if (typeof schema.pattern === 'string') out.pattern = schema.pattern;\n  if (schema.uniqueItems === true) out.uniqueItems = true;\n\n  const dependentRequired = readDependentRequired(schema.dependentRequired);\n  if (dependentRequired) out.dependentRequired = dependentRequired;\n  return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** The one non-null, non-`$ref` branch of a `oneOf`/`anyOf`, or `undefined` for anything else. */\nfunction singleNonNullBranch(schema: SchemaObject): SchemaObject | undefined {\n  const variants = schema.oneOf ?? schema.anyOf;\n  if (!variants) return undefined;\n  const nonNull = variants.filter((v) => !isNullSchema(v));\n  return nonNull.length === 1 && !nonNull[0].$ref ? nonNull[0] : undefined;\n}\n\n/**\n * True for the `null` variant of a `oneOf`/`anyOf` — the branch that makes a\n * union nullable, never a variant to type or name — in each spelling of a\n * schema that admits `null` alone: `{ type: 'null' }` / `{ type: ['null'] }`,\n * `{ const: null }`, and an `enum:` list of nothing but `null`\n * (`{ enum: [null] }`). A `const` or `enum:` counts only with no `type`\n * beside it and as the keyword that types the schema\n * (`classifyInlineSchema`), so `{ type: 'string', const: null }` and a\n * `$ref` or composition written beside one stay variants, as\n * `{ enum: [null, 'x'] }` does. The one test of every site that sets a\n * union's null variant aside.\n */\nexport function isNullSchema(schema: SchemaObject): boolean {\n  const { type } = schema;\n  if (type === 'null' || (Array.isArray(type) && type.length === 1 && type[0] === 'null')) return true;\n  if (type !== undefined) return false;\n  if (schema.const === null) return classifyInlineSchema(schema) === 'const';\n  const values = schema.enum;\n  return (\n    Array.isArray(values) &&\n    values.length > 0 &&\n    values.every((value) => value === null) &&\n    classifyInlineSchema(schema) === 'enum'\n  );\n}\n\n/**\n * `{ constraints }` when `schema` declares any validation keyword, `{}`\n * otherwise — spread into an IR node so the key stays absent rather than\n * present-but-undefined.\n */\nexport function constraintsEntry(schema: SchemaObject): { constraints?: Constraints } {\n  const constraints = extractConstraints(schema);\n  return constraints ? { constraints } : {};\n}\n\n/**\n * The limits a site that writes `schema` carries — what `Field.constraints`\n * is for a field written as `schema`, and what the type built from it\n * carries (`schemaToTypeRef`; #545): the keywords of the site's own level\n * — the schema, read by `extractConstraints`, which conjoins its `allOf`\n * members' with its own in document order and a nullable wrapper's with\n * its branch's; the `allOf` members that only annotate it\n * (`annotatingAllOfMembers`; #555) are no level of their own here, since\n * folded first a member's `pattern` or `multipleOf` would win over the\n * schema's own, which `combineConstraints` keeps (#587 review: `{ type:\n * 'string', pattern: '^a', allOf: [{ pattern: 'b$' }] }` carries `^a`) —\n * and, for a reference to an array or primitive component, or to an alias\n * of an enum component, of every entry the reference passes\n * (`componentReference`: the wrappers and the members beside the `$ref`\n * among `own`, then each alias and the component, each read once with its\n * annotating members' limits — `limitEntries`; #588 review: as levels of\n * their own, a member's `pattern` or `multipleOf` won over the alias's\n * own), conjoined from the component outward, as JSON Schema applies every\n * level at once and the wire enforces the component's limit whatever is\n * written beside the `$ref` (#512 review). A `$ref` to a model, named union or enum\n * contributes none of the target's: that node carries its own. A JSON\n * Pointer `$ref` deeper into a component (#539) contributes none here\n * either, since what it lands on is typed after the fact: once\n * `resolveSchemaPointers` settles that type, the pointed schema's limits\n * are conjoined with this reading on the type and on the field or\n * parameter alike, where the type can carry them (#545 review).\n * `undefined` when no level declares any.\n */\nexport function schemaConstraints(\n  schema: SchemaObject,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): Constraints | undefined {\n  const reference = componentReference(schema, componentSchemas);\n  return [...(reference?.own ?? [schema]), ...(reference?.limitEntries ?? [])].reduceRight<Constraints | undefined>(\n    (limits, level) => combineConstraints(limits, extractConstraints(level)),\n    undefined,\n  );\n}\n\n/**\n * `ref` carrying `constraints` on the node that can (#545): the\n * `primitive`, `literal`, `array`, `map` or `union` itself, or the `inner`\n * of a `nullable` wrapper, whose keywords are the value's; in place of any\n * it carried, since the limits of the site a type is built at account for\n * every level the type was built through. A `model` or `enum` reference is\n * returned as it is — the model carries its own, and what the site writes\n * around the `$ref` stays the field's or parameter's — and so is `ref`\n * when `constraints` is `undefined`, so a type stays as built. A reference\n * `resolveSchemaPointers` has yet to settle, for a JSON Pointer `$ref`\n * deeper into a component (#539), records them for that pass\n * (`recordPendingSiteLimits`), which conjoins them with the pointed\n * schema's on the type it settles the site into (#545 review) — conjoined\n * with what the reference already recorded, the branch's first, since a\n * wrapper's reading leaves its `$ref` branch out (`extractConstraints`)\n * where a component reference's levels would include it: `maxLength: 10`\n * on `oneOf: [{ $ref: …/code, maxLength: 3 }, { type: 'null' }]` keeps\n * the `3` (Greptile, #545 review round 3: the wrapper's `10` replaced it,\n * and the site settled to the target's `8`).\n */\nexport function withTypeConstraints(ref: TypeRef, constraints: Constraints | undefined): TypeRef {\n  if (!constraints) return ref;\n  switch (ref.kind) {\n    case 'primitive':\n    case 'literal':\n    case 'array':\n    case 'map':\n    case 'union':\n      ref.constraints = constraints;\n      return ref;\n    case 'nullable':\n      withTypeConstraints(ref.inner, constraints);\n      return ref;\n    case 'model':\n      if (isPendingSchemaRef(ref)) {\n        recordPendingSiteLimits(ref, combineConstraints(pendingSiteLimitsOf(ref), constraints));\n      }\n      return ref;\n    case 'enum':\n      return ref;\n  }\n  return assertNever(ref);\n}\n\n/**\n * `ref`, built for `schema` by hand where a site assembles a type instead of\n * asking `schemaToTypeRef` for it (a list response's data array, a `oneOf`\n * request body), carrying the limits that site has (`schemaConstraints`),\n * as `schemaToTypeRef` would have it carry them (#545).\n */\nexport function withSchemaConstraints(ref: TypeRef, schema: SchemaObject): TypeRef {\n  return withTypeConstraints(ref, schemaConstraints(schema, documentComponentSchemas()));\n}\n\n/**\n * `{ deprecated: true }` when `schema` says so, `{}` otherwise — spread into\n * a Model or Enum so the key stays absent rather than present-but-false. Read\n * the way `Field.deprecated` is: only the schema's own top-level keyword, and\n * only the literal `true` — `deprecated: \"yes\"` is not a declaration, as it\n * is not on a field, parameter, operation or header.\n */\nexport function deprecatedEntry(schema: SchemaObject): { deprecated?: boolean } {\n  return schema.deprecated === true ? { deprecated: true } : {};\n}\n\n/**\n * The declaration each copy a reader spreads from one stands for: a\n * nullable wrapper stripped (`unwrapNullableSchema`; the type builder's own\n * strips in `buildTypeRef`), a type list read one type at a time\n * (`buildTypeRef`, `inlineVariantTypeRef`), sibling properties folded into a composition\n * (`foldSiblingProperties`), a wrapper's documentation, `deprecated` or\n * limits carried onto the branch or member it collapses to\n * (`withWrapperDocs`, `withWrapperDeprecation`, `unwrapNullableField`,\n * `unwrappedAllOfMember`). A reader that must know whether two schemas are\n * one declaration — the guard on a merge already being built\n * (`materializingMergedAllOf`, `mintingMergedAllOf`; workos/oagen#566) —\n * compares what `sourceDeclaration` resolves each to, so the extractor and\n * the type builder meet the same key whichever wrapper each strips and\n * however many copies a strip makes. Keyed by the copies, which no reader\n * shares, so a document's own object and a conjunction\n * `combineDeclarations` memoizes — the declarations themselves — are never\n * entries and resolve to themselves.\n */\nconst derivedFrom = new WeakMap<SchemaObject, SchemaObject>();\n\n/**\n * `copy`, recorded as standing for the declaration `source` stands for\n * (`sourceDeclaration`; see `derivedFrom`): the one call a reader makes\n * where it spreads a schema into a copy, so the copy is read as that\n * declaration wherever identity decides. Nothing is recorded when `copy`\n * is `source` itself.\n */\nexport function derivedCopy(copy: SchemaObject, source: SchemaObject): SchemaObject {\n  if (copy !== source) derivedFrom.set(copy, sourceDeclaration(source));\n  return copy;\n}\n\n/**\n * The declaration `schema` stands for: the one it was spread from, through\n * every recorded copy (`derivedCopy`), else `schema` itself — a document's\n * own object, a conjunction `combineDeclarations` built, or a copy no\n * reader recorded. The key every reader that guards by identity compares\n * (`materializingMergedAllOf`, `mintingMergedAllOf`): a transform that\n * memoizes its copy per declaration composes with it, since one memoized\n * copy is itself a stable key, and one that records its copy resolves to\n * the declaration.\n */\nexport function sourceDeclaration(schema: SchemaObject): SchemaObject {\n  return derivedFrom.get(schema) ?? schema;\n}\n\n/**\n * Strip the nullable wrappers `schemaToTypeRef` unwraps before it names\n * anything — the OAS 3.1 `type: [X, 'null']` array, the OAS 3.0\n * `nullable: true` flag, and a `oneOf`/`anyOf` with a single non-null\n * variant (`nullableUnionBranch`: not one read as an enum, which the type\n * builder decides first and builds from the union itself) — so extraction\n * dispatches on the same shape the TypeRef was built from. The unwrap keeps\n * `contextName`/`parentModelName` semantics intact: `schemaToTypeRef`\n * passes both through each of these wrappers unchanged.\n *\n * `carry` is applied at each union level, to the branch with the wrapper\n * it collapses from, before the branch is unwrapped in turn — so a caller\n * that builds a model from the result (`unwrapNullableField`) composes the\n * wrappers' documentation outermost-first through every level\n * (`withWrapperDocs`). The default keeps the branch as written, which is\n * what every site that only dispatches on the unwrapped shape needs. The\n * type-array and `nullable: true` forms unwrap by spreading, so every\n * keyword of theirs survives without it. Every copy made here stands for\n * the schema it was spread from (`derivedCopy`), so a reader that guards by\n * identity reads it as that declaration (`sourceDeclaration`).\n */\nexport function unwrapNullableSchema(\n  schema: SchemaObject,\n  carry: (branch: SchemaObject, wrapper: SchemaObject) => SchemaObject = (branch) => branch,\n): SchemaObject {\n  if (schema.$ref) return schema;\n  // `properties` beside a typing composition are folded into it before any\n  // wrapper is stripped (`foldSiblingProperties`), so a nullable union\n  // written beside them collapses onto a variant that already carries them,\n  // and every site dispatches on the one shape `schemaToTypeRef` typed.\n  const folded = foldSiblingProperties(schema);\n  if (Array.isArray(folded.type)) {\n    const nonNullTypes = folded.type.filter((t) => t !== 'null');\n    if (nonNullTypes.length !== 1) return folded;\n    return unwrapNullableSchema(derivedCopy({ ...folded, type: nonNullTypes[0], nullable: false }, folded), carry);\n  }\n  if (folded.nullable && folded.type) {\n    return unwrapNullableSchema(derivedCopy({ ...folded, nullable: false }, folded), carry);\n  }\n  // A nullable union collapses onto its one non-null variant — decided by\n  // `nullableUnionBranch`, the same definition `collapsedNullableBranch`\n  // checks, so the check and the unwrap cannot disagree.\n  const branch = nullableUnionBranch(folded);\n  return branch ? unwrapNullableSchema(carry(branch, folded), carry) : folded;\n}\n\n/**\n * The one variant a nullable `oneOf`/`anyOf` wrapper collapses to: what is\n * left once every `null` variant (`isNullSchema` — `{ type: 'null' }`,\n * `{ const: null }` or `{ enum: [null] }`, however many) is discarded, when\n * at least one was and exactly one variant remains. The single definition of\n * a nullable union wrapper on the model side, shared by `unwrapNullableSchema`\n * and `collapsedNullableBranch`. `undefined` otherwise: no union, a union\n * under an `allOf` that types the schema (which `schemaToTypeRef` gives\n * precedence; one that only annotates or limits it is part of the wrapper,\n * `nullableAxisBranch`), no `null`\n * variant, more than one non-null variant, or a union of consts read as an\n * enum (`inlineEnumSpelling`) — here, one string const beside `null` and an\n * `enum:` list that makes it one. The type builder decides that enum before\n * it collapses a nullable union, so such a union is no wrapper: the enum is\n * built from the union itself, nullable or not, and the variant documents\n * that one value, not the schema (workos/oagen#535: collapsed to the lone\n * const, a request body's text reader gave the member's text to the body).\n * Reads the one keyword the schema writes, `oneOf` first; the readers of\n * a composed schema's members decide a member that writes both per axis\n * (`nullableAxisBranch`). Exported for the response path, which wraps an\n * array it builds itself in `nullable` exactly when `schemaToTypeRef`\n * would (`nullableIf`).\n */\nexport function nullableUnionBranch(schema: SchemaObject): SchemaObject | undefined {\n  const variants = schema.oneOf ?? schema.anyOf;\n  return variants ? nullableAxisBranch(schema, variants) : undefined;\n}\n\n/**\n * The one variant one union axis of `schema` — a `oneOf` or `anyOf` list\n * it carries (`unionAxesOf`) — collapses to when that axis is a nullable\n * wrapper: `nullableUnionBranch`'s definition, applied to the axis alone,\n * so a member that writes both keywords has each decided on its own. The\n * readers of a composed schema's members read every axis through it\n * (`mergeAllOfMembers`, `readComponentAllOfMember`, `declareVariant`,\n * `collectProperties`, `declaresInlineProperties`), so a member `{ oneOf:\n * [{ a }, { type: 'null' }], anyOf: [{ b }, { c }] }` is `a` read as one\n * more member and `b`, `c` flattened — exactly as the two keywords written\n * as two members are read, and as the union beside the `allOf` folds them\n * (#398 review: the member was read through `nullableUnionBranch`, which\n * reads one keyword, so the `oneOf`'s wrapper collapsed and the `anyOf`\n * was never read: `NewPet { name, a }` as one member, `{ name, a, b, c }`\n * as two). `undefined` for an axis under an `allOf` that types the schema\n * (`allOfTypesSchema`; one whose members only annotate or limit it is\n * part of the wrapper, #613), with no `null` variant, with more than one\n * non-null variant, or read as an enum — the enum spelling decided on the\n * axis alone (`axisAlone`) when the schema writes both keywords.\n */\nexport function nullableAxisBranch(schema: SchemaObject, variants: readonly SchemaObject[]): SchemaObject | undefined {\n  // An `allOf` that types the schema takes precedence over the union beside\n  // it (`classifyInlineSchema`), which folds in as a member\n  // (`foldSiblingUnions`); one whose members only annotate or limit the\n  // schema is part of the wrapper, and the axis collapses as it does with\n  // no `allOf` at all (#613: any `allOf` kept `{ allOf: [{ description }],\n  // oneOf: [{ $ref: Pet }, { type: 'null' }] }` from collapsing, so as a\n  // member of a composed model `Pet` was flattened as a branch, and as a\n  // component wrapping a `$ref` to an array component it was a union of\n  // one, where the description beside the `oneOf` gave `Pet`\n  // always-applying and an alias of the array). The branch keeps the\n  // wrapper's own keys, as it did: the members' are not carried onto it.\n  if (schema.allOf && allOfTypesSchema(schema.allOf)) return undefined;\n  const nonNull = variants.filter((v) => !isNullSchema(v));\n  if (nonNull.length !== 1 || nonNull.length === variants.length) return undefined;\n  return inlineEnumSpelling(axisAlone(schema, variants))?.spelling === 'const-union' ? undefined : nonNull[0];\n}\n\n/** `schema` carrying `variants` as its one union, for a decision made per axis (`nullableAxisBranch`); `schema` itself when it writes one keyword. */\nfunction axisAlone(schema: SchemaObject, variants: readonly SchemaObject[]): SchemaObject {\n  if (!schema.oneOf || !schema.anyOf) return schema;\n  const { oneOf: _oneOf, anyOf: _anyOf, ...rest } = schema;\n  return variants === schema.oneOf ? { ...rest, oneOf: schema.oneOf } : { ...rest, anyOf: schema.anyOf };\n}\n\n/**\n * The one variant of a single-member `oneOf`/`anyOf` — a union of exactly\n * one variant, and that one not `null` — which the type builder keeps as a\n * union of one variant but types by the wrapper rule, the union's\n * documentation carried onto it (`withWrapperDocs`, in `schemaToTypeRef`'s\n * union branch; workos/oagen#445). `undefined` otherwise: no union that\n * types the schema (`classifyInlineSchema` — none, one under an `allOf`,\n * which takes precedence, or one of bare limits), a `null` variant (a\n * nullable wrapper, `nullableUnionBranch`), several variants, or a `oneOf`\n * of consts read as an enum (`inlineEnumSpelling`), which is the schema\n * that declares the members and so keeps its own text. Decided on a schema\n * whose nullable wrappers are removed, as `schemaToTypeRef` decides it. The\n * one definition for the readers that follow the type builder without\n * typing (`unwrapCollapsedWrappers`).\n */\nfunction loneUnionVariant(schema: SchemaObject): SchemaObject | undefined {\n  if (classifyInlineSchema(schema) !== 'union' || inlineEnumSpelling(schema)?.spelling === 'const-union') {\n    return undefined;\n  }\n  const variants = schema.oneOf ?? schema.anyOf ?? [];\n  return variants.length === 1 && !isNullSchema(variants[0]) ? variants[0] : undefined;\n}\n\n/**\n * The array schema `schema` is, once a nullable wrapper of any spelling is\n * removed — an OAS 3.1 type list naming `null` (`type: ['array', 'null']`),\n * OAS 3.0 `nullable: true`, or a `oneOf`/`anyOf` with one non-null variant,\n * written with or without `items` beside it — and an `allOf` read as one\n * member (`allOfReadAsMember`: `allOf: [{ type: 'array', items }]`), the two\n * however they alternate, and `undefined` when it is not an array:\n * `unwrapNullableSchema`, the one definition the model side unwraps by, then\n * `isArraySchema`, the one test every site makes. So a list envelope's data\n * array, an array response body and an `allOf`-merged array property are\n * arrays here whatever wrapper they wear, as `schemaToTypeRef` types them\n * `nullable<array<…>>`. A `$ref` is a reference and is not looked through:\n * a `$ref` to an array component is typed as the array the component\n * declares by `schemaToTypeRef` itself, with the items the component pass\n * built (`isArrayComponentRef` says whether a property is one), a pointer\n * deeper into a component is settled to the array the schema it lands on\n * is typed as (`isArrayPointerRef` says whether a property is one; #609),\n * and the explicit `dataPath` walk (`resolveBareSchema`) is the one place\n * any other reference is followed.\n */\nexport function arraySchemaOf(schema: SchemaObject): SchemaObject | undefined {\n  const bare = unwrapNullableSchema(schema);\n  if (isArraySchema(bare)) return bare;\n  const member = allOfReadAsMember(bare);\n  return member && arraySchemaOf(member);\n}\n\n/**\n * The member `schemaToTypeRef` types an `allOf` as (`readInlineAllOf`): a\n * lone member with nothing added to it, or the one typing member beside\n * members that only annotate or limit it (`'unwrapped'`; #555), read as\n * the schema itself with the wrapper's limits, flag and documentation\n * (`unwrappedAllOfMember`), or the first `$ref` member of a plain reference\n * (`'reference'`). `undefined` for any other schema: no `allOf` that types\n * it (`classifyInlineSchema`), or one merged into a model. Read on a schema\n * whose nullable wrappers are removed and sibling `properties` folded in\n * (`unwrapNullableSchema`), as `schemaToTypeRef` reads it.\n */\nexport function allOfReadAsMember(schema: SchemaObject): SchemaObject | undefined {\n  if (!schema.allOf || classifyInlineSchema(schema) !== 'allOf') return undefined;\n  const reading = readInlineAllOf(schema.allOf, schema);\n  if (reading === 'unwrapped') return unwrappedAllOfMember(schema);\n  return reading === 'reference' ? schema.allOf.find((member) => member.$ref !== undefined) : undefined;\n}\n\n/**\n * `schema` with every wrapper the type builder collapses stripped — a\n * nullable wrapper of any spelling (`unwrapNullableSchema`) and a\n * single-member `allOf` read as its member (`unwrappedAllOfMember`) — and\n * every single-member `oneOf`/`anyOf` it keeps as a union of one variant\n * but types by the same rule (`loneUnionVariant`), however they nest — each\n * level's documentation carried onto what it unwraps to, outermost first\n * (`withWrapperDocs`). So its `description` is the text the enum lifted\n * from the branch takes: the outermost wrapper's with content, else the\n * next, else the branch's own — and the text the model built from it takes,\n * except under a single-member `oneOf`/`anyOf`, whose object variant's\n * model keeps the variant's own (workos/oagen#445). A `$ref` is never\n * followed, and a `$ref` member of an `allOf` is a reference rather than a\n * branch, so the wrapper's own text stands. A `oneOf`/`anyOf` of consts\n * read as an enum is the schema that declares the members, so it is where\n * the unwrap stops, nullable or not — `{ enum: ['draft', null], anyOf:\n * [{ const: 'draft', description }, { type: 'null' }] }` is a nullable enum\n * of `draft`, no wrapper around a lone const (`nullableUnionBranch`), and\n * the variant's text is the member's alone (workos/oagen#535), as a\n * single-member one's is (`loneUnionVariant`). An `allOf` member that\n * declares no type — `allOf: [{ $ref: Pet }, { description }]`, `allOf:\n * [{ type: 'string' }, { description }]` — is part of the wrapper, not a\n * branch (`annotatingAllOfMembers`), so its text is the wrapper's own,\n * after the wrapper's: carried onto the one typing member that is\n * unwrapped, and standing beside a `$ref` member or a merge as the\n * schema's where the schema has none (`allOfWrapperLayer`; #555). Read for\n * a request body's doc text (`requestBodyDescriptionOf`).\n */\nexport function unwrapCollapsedWrappers(schema: SchemaObject): SchemaObject {\n  const bare = unwrapNullableSchema(schema, withWrapperDocs);\n  const variant = loneUnionVariant(bare);\n  if (variant) return unwrapCollapsedWrappers(withWrapperDocs(variant, bare));\n  if (!bare.allOf || classifyInlineSchema(bare) !== 'allOf') return bare;\n  if (readInlineAllOf(bare.allOf, bare) !== 'unwrapped') return allOfWrapperLayer(bare);\n  return unwrapCollapsedWrappers(unwrappedAllOfMember(bare));\n}\n\n/**\n * Whether `schemaToTypeRef` wraps the schema's own type in `nullable`: an OAS\n * 3.1 type list naming `null` (`type: ['array', 'null']`), an OAS 3.0\n * `nullable: true` beside a `type`, a `oneOf`/`anyOf` that collapses to one\n * non-null variant (`nullableUnionBranch`), or an `allOf` read as a member\n * that does (`allOfReadAsMember`: `allOf: [{ type: ['array', 'null'] }]`).\n * The one test for the places the response path builds an array TypeRef\n * itself (`nullableIf`) or merges two array declarations\n * (`combineDeclarations`), which find the array through the same wrappers\n * (`arraySchemaOf`).\n */\nexport function declaresNull(schema: SchemaObject): boolean {\n  if (\n    (Array.isArray(schema.type) && schema.type.includes('null')) ||\n    (schema.nullable === true && schema.type !== undefined) ||\n    nullableUnionBranch(schema) !== undefined\n  ) {\n    return true;\n  }\n  const member = allOfReadAsMember(unwrapNullableSchema(schema));\n  return member !== undefined && declaresNull(member);\n}\n\n/**\n * `unwrapNullableSchema` for a schema a model is built from, carrying the\n * wrappers' limits, the outermost's `deprecated` and every collapsed\n * level's documentation onto the branch it unwraps to. The type-array and\n * `nullable: true` forms unwrap by spreading, so every keyword survives;\n * the union form swaps in the bare branch, which would drop a\n * `minProperties` or `deprecated: true` written beside\n * `anyOf: [{ type: 'object', … }, { type: 'null' }]`. `extractConstraints`\n * conjoins each wrapper's own keywords with its branch's as the field's\n * limits, and `Field.deprecated` is the outermost wrapper's, so the model\n * built from the branch must carry the same ones or it would disagree with\n * its field; the documentation — text, link, examples, extensions — rides\n * along level by level, outermost first, by the one wrapper rule\n * (`withWrapperDocs`, applied by `unwrapNullableSchema` at each level). Every\n * extractor that builds a model from a nullable wrapper's branch — the field\n * extractor, `extractNestedSchema`, `extractInlineModelDeep`, the request-body\n * and wrapped-response paths — goes through this one function, so the\n * copies they produce agree and the inline-model merges cannot keep a wrongly\n * flagged one. Returns `schema` itself when there is nothing to unwrap, and a\n * copy whenever a wrapper was stripped — a copy that still carries the union\n * when a multi-variant `oneOf`/`anyOf` sits beside `type: [X, 'null']`, so\n * identity with `schema` does not tell whether a union collapsed to one\n * branch; `collapsedNullableBranch` does. The copy stands for the branch it\n * was spread from (`derivedCopy`): the schema itself for the type-array and\n * `nullable: true` forms, the one variant for the union form — the object\n * that carries what the field is — so a reader that guards by identity\n * (`materializingMergedAllOf`) meets a merge under a nullable wrapper once,\n * however often the wrapper is stripped (workos/oagen#566 review: the\n * conjunction a typeless redeclaration annotates keeps the wrapper, and\n * every unwrap of it made a copy the guard had never seen).\n */\nexport function unwrapNullableField(schema: SchemaObject): SchemaObject {\n  // The documentation of every collapsed level rides onto the branch as it\n  // is unwrapped, outermost first (`withWrapperDocs` through\n  // `unwrapNullableSchema`), so an inner wrapper's text, link or key reaches\n  // the model wherever the outer has none; the limits conjoin through every\n  // level too (`extractConstraints`), and the flag is the outermost\n  // wrapper's alone, as `Field.deprecated` reads it.\n  const inner = unwrapNullableSchema(schema, withWrapperDocs);\n  if (inner === schema || schema.allOf || !(schema.oneOf ?? schema.anyOf)) return inner;\n  return withWrapperDeprecation(derivedCopy({ ...inner, ...extractConstraints(schema) }, inner), schema);\n}\n\n/**\n * The one branch a nullable `oneOf`/`anyOf` wrapper collapses to, carrying\n * the wrapper's `deprecated` and limits (`unwrapNullableField`), or\n * `undefined` when `schema` is not such a wrapper: not a union, or a union\n * with more than one non-null variant — nullable or not, including\n * `type: ['object', 'null']` beside a multi-variant `oneOf`. Decided at the\n * wrapper's level alone, by `nullableUnionBranch` — the very definition\n * `unwrapNullableSchema` collapses by, so the check and the unwrap cannot\n * disagree: the union collapses iff discarding every `null` variant, however\n * many and however spelled, leaves exactly one, whatever that variant\n * contains — a branch's own nested `oneOf`/`anyOf` (a union of constraint\n * sets beside its properties, say) is the branch's business and is built as\n * written, flag and limits carried. A multi-variant union is never\n * collapsed: each variant is its own schema, built as itself with its own\n * flag, and the wrapper's stays on the field. The sites that build a model\n * from a union's variants substitute the branch this returns for the one\n * variant it stands for, and otherwise build every variant as written.\n */\nexport function collapsedNullableBranch(schema: SchemaObject): SchemaObject | undefined {\n  return nullableUnionBranch(schema) ? unwrapNullableField(schema) : undefined;\n}\n\n/**\n * `inner` carrying the wrapper's `deprecated` in place of its own. A wrapper\n * the parser collapses — a nullable `oneOf`/`anyOf`, a single-member `allOf`\n * — is the field's schema, and `Field.deprecated` reads only that top-level\n * keyword, so the model built from what it unwraps to carries the same flag\n * the field does: the wrapper's, never the branch's or the member's own.\n */\nexport function withWrapperDeprecation(inner: SchemaObject, wrapper: SchemaObject): SchemaObject {\n  const result: SchemaObject = derivedCopy({ ...inner, ...deprecatedEntry(wrapper) }, inner);\n  if (wrapper.deprecated !== true) delete result.deprecated;\n  return result;\n}\n\n/**\n * `inner` carrying the wrapper's documentation layer — every keyword that\n * documents a schema without shaping it, the schema-side counterpart of a\n * Field's documentation (`FIELD_DOC_KEYS` in inline-models.ts): its\n * `description` when it has non-whitespace content (as `inlineEnumRef` and\n * `Model.description` read text), its `externalDocs` when usable\n * (`readExternalDocs`), its `example` when the key is present (an explicit\n * `null` is a value, as `Field.example` keeps it), its `examples` when a\n * non-empty list, and its `x-*` keys one by one (`extensionsOf`, the\n * consumed keys left where they are read). The wrapper's value wins\n * wherever both declare one; the branch keeps its own where the wrapper\n * has none; `inner` itself comes back when the wrapper carries nothing.\n *\n * The one rule for a wrapper the parser collapses — a nullable\n * `oneOf`/`anyOf`, a single-member `allOf` — which is the schema the\n * document wrote for the property, parameter, header or body, so what it\n * unwraps to must document itself by the wrapper first. Applied at every\n * collapse step, so nested wrappers compose outermost-first: an outer\n * wrapper's keys land on the inner wrapper before the inner wrapper's land\n * on the branch, and an inner wrapper's key survives wherever the outer has\n * none (workos/oagen#369 round 3: the model path restored the outermost\n * wrapper's keys after unwrapping every level at once, so an inner\n * wrapper's were lost). Read by the type builder's two wrapper sites\n * (`schemaToTypeRef`) and where it types the lone variant of a\n * single-member `oneOf`/`anyOf`, which stays a union (workos/oagen#445;\n * the request body's own `oneOf` likewise), by the model extractors\n * (`unwrapNullableField` through `unwrapNullableSchema`,\n * `unwrappedAllOfMember`), by the response path (`extractDirectResource`)\n * and by the request body's text reader, which strips the same wrappers\n * (`unwrapCollapsedWrappers`), so a model, an enum, a field and a body's\n * doc text built from one wrapper document themselves alike.\n */\nexport function withWrapperDocs(inner: SchemaObject, wrapper: SchemaObject): SchemaObject {\n  const carried: SchemaObject = {};\n  if (typeof wrapper.description === 'string' && wrapper.description.trim() !== '') {\n    carried.description = wrapper.description;\n  }\n  const externalDocs = readExternalDocs(wrapper.externalDocs);\n  if (externalDocs) carried.externalDocs = wrapper.externalDocs;\n  if (Object.hasOwn(wrapper, 'example')) carried.example = wrapper.example;\n  if (Array.isArray(wrapper.examples) && wrapper.examples.length > 0) carried.examples = wrapper.examples;\n  Object.assign(carried, extensionsOf(wrapper, SCHEMA_CONSUMED_EXTENSIONS));\n  return Object.keys(carried).length === 0 ? inner : derivedCopy({ ...inner, ...carried }, inner);\n}\n\n/** Keywords where the stricter of two declarations is the larger value. */\nconst MIN_KEYS = ['minimum', 'exclusiveMinimum', 'minLength', 'minItems', 'minContains', 'minProperties'] as const;\n/** Keywords where the stricter of two declarations is the smaller value. */\nconst MAX_KEYS = ['maximum', 'exclusiveMaximum', 'maxLength', 'maxItems', 'maxContains', 'maxProperties'] as const;\n\n/**\n * Conjoin two constraint sets the way `allOf` conjoins schemas: an instance\n * must satisfy both, so every `min*` takes the larger value, every `max*` the\n * smaller, `uniqueItems` holds if either side demands it, and\n * `dependentRequired` merges per property with the union of its names\n * (deduplicated, `a`'s order first). A keyword declared on one side only is\n * kept as is, and an absent side yields the other unchanged.\n *\n * `multipleOf` and `pattern` keep `a`'s value when the two differ: a true\n * conjunction would need the least common multiple, or a lookahead regex\n * joining both patterns, and neither is worth carrying into the IR.\n *\n * Not for the parameter `$ref` fallback in extractParams: keywords written\n * beside a `$ref` override the target's there, which is a different operation.\n */\nexport function combineConstraints(a: Constraints | undefined, b: Constraints | undefined): Constraints | undefined {\n  if (!a) return b;\n  if (!b) return a;\n  const out: Constraints = { ...a, ...b };\n  for (const key of MIN_KEYS) {\n    const [x, y] = [a[key], b[key]];\n    if (x !== undefined && y !== undefined) out[key] = Math.max(x, y);\n  }\n  for (const key of MAX_KEYS) {\n    const [x, y] = [a[key], b[key]];\n    if (x !== undefined && y !== undefined) out[key] = Math.min(x, y);\n  }\n  if (a.uniqueItems || b.uniqueItems) out.uniqueItems = true;\n  if (a.multipleOf !== undefined && b.multipleOf !== undefined) out.multipleOf = a.multipleOf;\n  if (a.pattern !== undefined && b.pattern !== undefined) out.pattern = a.pattern;\n  if (a.dependentRequired && b.dependentRequired) {\n    out.dependentRequired = unionDependentRequired(a.dependentRequired, b.dependentRequired);\n  }\n  return out;\n}\n\n/** Per-property union of two `dependentRequired` maps, deduplicated and keeping `a`'s order first. */\nfunction unionDependentRequired(a: Record<string, string[]>, b: Record<string, string[]>): Record<string, string[]> {\n  const merged = new Map<string, string[]>();\n  for (const [property, names] of Object.entries(a)) merged.set(property, [...names]);\n  for (const [property, names] of Object.entries(b)) {\n    const existing = merged.get(property);\n    if (!existing) {\n      merged.set(property, [...names]);\n      continue;\n    }\n    for (const name of names) if (!existing.includes(name)) existing.push(name);\n  }\n  return Object.fromEntries(merged);\n}\n\n/**\n * Resolve one side's bound from `minimum` / `maximum` plus its `exclusive*`\n * companion into the OAS 3.1 shape: a numeric companion is the exclusive\n * bound itself, `true` turns the inclusive bound into the exclusive one, and\n * `false` or absent leaves the inclusive bound as is.\n */\nfunction normalizeBound(inclusive: unknown, exclusive: unknown): { inclusive?: number; exclusive?: number } {\n  const bound = typeof inclusive === 'number' ? inclusive : undefined;\n  if (typeof exclusive === 'number') return { inclusive: bound, exclusive };\n  if (exclusive === true) return { exclusive: bound };\n  return { inclusive: bound };\n}\n\n/** Copy `dependentRequired` when it is an object whose values are string arrays; anything else is ignored. */\nfunction readDependentRequired(value: unknown): Record<string, string[]> | undefined {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n  const entries: [string, string[]][] = [];\n  for (const [property, deps] of Object.entries(value as Record<string, unknown>)) {\n    if (Array.isArray(deps) && deps.every((d): d is string => typeof d === 'string'))\n      entries.push([property, [...deps]]);\n  }\n  // Object.fromEntries creates an own property for every key. Assigning\n  // `out[property]` on a literal would instead set the prototype for a\n  // dependency named `__proto__` and silently drop it.\n  return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n}\n\n/**\n * Narrow a raw `examples` value to a non-empty list, or undefined. Guards\n * against documents that put an OAS Example Object map (or anything else)\n * where JSON Schema expects an array, and against an empty list, so the IR\n * carries `examples` only when there is at least one value.\n */\nexport function nonEmptyExamples(value: unknown): unknown[] | undefined {\n  return Array.isArray(value) && value.length > 0 ? value : undefined;\n}\n\n/**\n * Pick the single `example` the IR carries: the document's own `example`\n * when it is set (including an explicit `null`), otherwise the first entry\n * of the resolved `examples` list.\n */\nexport function pickExample(example: unknown, examples: unknown[] | undefined): unknown {\n  return example !== undefined ? example : examples?.[0];\n}\n\n/** One source of example values, e.g. a parameter's own declaration or its schema. */\nexport interface ExampleSource {\n  example: unknown;\n  examples: unknown[] | undefined;\n}\n\n/**\n * Resolve `example` and `examples` across ordered precedence levels: for a\n * parameter its own declaration, its inline schema, then the component its\n * `$ref` points at; for a field its own schema, then its `$ref` target.\n *\n * Each value walks the levels independently. `examples` is the first\n * non-empty list. `example` comes from the first level that has either an\n * `example` or a list, preferring that level's own `example` over its first\n * list entry — so a schema-level `example` can never mask the parameter's\n * own `examples` map. A level with neither falls through; an explicit\n * `null` is a value and stops the walk.\n */\nexport function resolveExamples(levels: ExampleSource[]): ExampleSource {\n  let example: unknown;\n  let examples: unknown[] | undefined;\n  for (const level of levels) {\n    if (examples === undefined) examples = level.examples;\n    if (example === undefined) example = pickExample(level.example, level.examples);\n  }\n  return { example, examples };\n}\n\n/**\n * If a schema is a `$ref` into `components/schemas`, return the schema it\n * points at — the component `#/components/schemas/X` names, or the schema a\n * pointer deeper into one lands on (`schemaRefTarget`; #539). Used to\n * surface schema-level metadata (default, example, examples, deprecated,\n * description) that would otherwise be invisible at the field or parameter\n * level.\n *\n * Refs are not pre-resolved by the bundler (`dereference: false` in refs.ts),\n * so without this, a param like `schema: { $ref: '.../PaginationOrder' }`\n * silently loses the target's `default: desc` and the SDK stops emitting the\n * spec-mandated default value in generated method signatures.\n */\nexport function resolveComponentSchemaRef(\n  schema: SchemaObject | undefined,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): SchemaObject | undefined {\n  if (!schema || !componentSchemas) return undefined;\n  return schemaRefTarget((schema as { $ref?: unknown }).$ref, componentSchemas);\n}\n\nexport interface ExtractedSchemas {\n  models: Model[];\n  enums: Enum[];\n}\n\nexport function extractSchemas(\n  schemas: Record<string, SchemaObject> | undefined,\n  options?: SchemaExtractionOptions,\n): ExtractedSchemas {\n  const enums: Enum[] = [];\n\n  if (!schemas) {\n    // No components, so no name transform is activated for this document;\n    // the titles are resolved here as they will be when the operations are\n    // typed, without one.\n    markContestedTitles(options?.document);\n    return { models: [], enums };\n  }\n\n  // Record the raw component keys first so every resolveSchemaName() call\n  // below (including the collision probe) can tell a real component key from\n  // a name oagen synthesised.\n  activeComponentSchemaKeys = new Set(Object.keys(schemas));\n  activeComponentSchemas = schemas;\n  // A new document: the references an `allOf` merge inherits from a\n  // component's property (`inheritedModelRefsOf`) are recorded per document,\n  // and so are the unions whose uncarried `properties` were reported; the\n  // declarations the merges combine (`combineDeclarations`) depend on these\n  // components, so they are combined afresh too.\n  resetInheritedModelRefs();\n  resetCombinedDeclarations();\n  resetFoldedSchemas();\n  resetFoldWarnings();\n\n  // Build collision-safe transform if provided. The transform is probed with\n  // the same (cleaned, raw) pair resolveSchemaName() will hand it, so a\n  // transform that keys off the original spelling is collision-checked on the\n  // names it will actually produce. Collisions are tracked by raw key: two raw\n  // keys may clean to the same name yet transform to different ones (e.g.\n  // `Users`/`User` with an originalName-based transform), and marking the\n  // shared cleaned name unsafe would wrongly disable the transform for both.\n  if (options?.schemaNameTransform) {\n    const transform = options.schemaNameTransform;\n    const transformedToRawKeys = new Map<string, string[]>();\n    for (const raw of Object.keys(schemas)) {\n      const transformed = transform(cleanSchemaName(toPascalCase(raw)), raw);\n      if (!transformedToRawKeys.has(transformed)) transformedToRawKeys.set(transformed, []);\n      transformedToRawKeys.get(transformed)!.push(raw);\n    }\n    // Raw keys whose transformed output is shared with another raw key, plus\n    // their cleaned names. Component keys are guarded by raw key; synthesised\n    // names (no originalName) keep the cleaned-name guard they always had.\n    const unsafeRawKeys = new Set<string>();\n    const unsafeCleanedNames = new Set<string>();\n    for (const [, rawKeys] of transformedToRawKeys) {\n      if (rawKeys.length > 1) {\n        for (const raw of rawKeys) {\n          unsafeRawKeys.add(raw);\n          unsafeCleanedNames.add(cleanSchemaName(toPascalCase(raw)));\n        }\n      }\n    }\n    activeSchemaNameTransform = (name: string, originalName?: string) => {\n      const unsafe = originalName !== undefined ? unsafeRawKeys.has(originalName) : unsafeCleanedNames.has(name);\n      return unsafe ? name : transform(name, originalName);\n    };\n  } else {\n    activeSchemaNameTransform = null;\n  }\n\n  // Before any field is typed: which title-mapped variants must not keep\n  // their title because another shape takes it under the same root. Decided\n  // with the name transform active, since the titles are compared by the\n  // names they resolve to. The component schemas are read as one root; every\n  // other inline schema of the document is a root of its own.\n  markContestedTitles(options?.document ?? { components: { schemas } });\n\n  // Pre-compute the set of resolved names whose component schema is an enum so\n  // schemaToTypeRef() can classify `$ref` targets correctly. Built in a separate\n  // pass because the per-schema loop mutates models/enums and we want this map\n  // available before any TypeRef is resolved (operations + nested fields both\n  // call schemaToTypeRef during extraction).\n  activeEnumSchemaNames = new Set();\n  activeNullableEnumSchemaNames = new Set();\n  activeNullableModelComponentKeys = new Set();\n  activeNamedUnionMemo = { plans: new WeakMap(), shapes: new WeakMap(), variantEntries: new WeakMap() };\n  // The primitive components, by key, before any TypeRef is built: a `$ref`\n  // to one is the primitive, literal, union of primitives or `unknown` it\n  // declares wherever it is typed, an array component's items included.\n  activePrimitiveComponentKeys = new Set(\n    Object.entries(schemas)\n      .filter(([, schema]) => !isEnumComponentSchema(schema) && isPrimitiveComponentEntry(schema, schemas))\n      .map(([key]) => key),\n  );\n  // The aliases of enum components, by key, before any TypeRef is built: a\n  // `$ref` to one is the enum it names wherever it is typed (#560). Only\n  // an entry whose chain passes a `$ref` (`isEnumComponentAlias`): one\n  // that declares its own enum, inside whatever wrapper, is the enum\n  // (#606), and one that declares none is a model.\n  activeEnumAliasKeys = new Set(\n    Object.entries(schemas)\n      .filter(([, schema]) => isEnumComponentAlias(schema, schemas))\n      .map(([key]) => key),\n  );\n  for (const [name, schema] of Object.entries(schemas)) {\n    const resolved = resolveSchemaName(name);\n    // An enum component is read on the schema it declares its members on\n    // (`enumComponentDeclaration`): through an `allOf` wrapper, the\n    // member's own nullability is the enum's, and the wrapper's OAS 3.0\n    // `nullable: true` declares nothing.\n    const declaration = enumComponentDeclaration(schema);\n    if (declaration) {\n      activeEnumSchemaNames.add(resolved);\n      if (isNullableEnumSchema(declaration)) activeNullableEnumSchemaNames.add(resolved);\n    } else if (\n      // A named union's `null` variant, or the `null` an object component\n      // declares on itself or on the component it is an alias of (#615),\n      // rides on every reference to the model (`componentTypeRef`), since\n      // the model built for it carries no wrapper.\n      isNullableModelComponentEntry(schema, schemas) &&\n      // A nullable wrapper around an array, a primitive or a `$ref` to an\n      // enum is no union but an array or primitive component, or an alias\n      // of the enum (#560), which a `$ref` names by its key and types with\n      // the component's own wrapper, as the schema written inline is typed.\n      !isArrayComponentEntry(schema, schemas) &&\n      !activePrimitiveComponentKeys.has(name) &&\n      !activeEnumAliasKeys.has(name)\n    ) {\n      activeNullableModelComponentKeys.add(name);\n    }\n  }\n\n  // The array components, planned once the sets above are complete, in\n  // rounds until the plans settle. Every tree starts under `item`. A round\n  // registers every tree under its current context — so a `$ref` to an\n  // array component resolves to its array in every rehearsal, the typing the\n  // real pass uses, which tells `{ value: { $ref: Notes } }` from `{ value:\n  // { $ref: Note } }` as `array<Note>` and `Note` — reads every name every\n  // other entry takes (`componentMints`) and every tree's names under its\n  // context (`arrayComponentMints`; the names a tree mints are read with\n  // none registered, so another component's items are never counted as its\n  // own), then decides the trees one at a time in the order of their keys\n  // sorted by code point — never the document's — each against every\n  // component and every other tree's current names (`planArrayComponent`),\n  // re-registering a tree that moves so the trees after it resolve its\n  // items under its new name. A round that moves nothing is the last: every\n  // shape was then compared under the names the plans settle on, so a tree\n  // whose items reference another tree is never shared on a provisional\n  // name (`array<PaletteItem>`) that the other tree then steps away from\n  // (`array<PaletteItemItem>`), and no two trees end on one name for\n  // different shapes, whatever the document's order. A `$ref` to an array\n  // component — from a component field, a named union's variant, an\n  // operation or a webhook — is then typed from its plan, by the key it\n  // names.\n  activeArrayComponentPlans = new Map();\n  // The discriminated variants' names, decided before the array components\n  // are planned: an array component's items step around them\n  // (`componentMints`), as they step around every other entry's names. They\n  // are decided with no plan in place, every variant read under the name\n  // its const derives.\n  activeDispatcherVariantPlans = new Map();\n  activeDispatcherVariantPlans = planDispatcherVariants(schemas);\n  const arrayComponents = Object.entries(schemas)\n    .filter(([, schema]) => !isEnumComponentSchema(schema) && isArrayComponentEntry(schema, schemas))\n    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n  if (arrayComponents.length > 0) {\n    const contexts = new Map(arrayComponents.map(([key]) => [key, 'item']));\n    const register = (): void => {\n      activeArrayComponentPlans = new Map(\n        arrayComponents.map(([key, schema]) => [key, arrayComponentPlan(key, schema, contexts.get(key)!)] as const),\n      );\n    };\n    let settled = false;\n    for (let round = 0; round < MAX_ARRAY_COMPONENT_ROUNDS && !settled; round++) {\n      register();\n      const minted = new Map(\n        Object.entries(schemas).map(([key, schema]) => [key, componentMints(key, schema, schemas)] as const),\n      );\n      const current = new Map(\n        arrayComponents.map(\n          ([key, schema]) =>\n            [key, arrayComponentMints(resolveSchemaName(key), schema, schemas, contexts.get(key)!)] as const,\n        ),\n      );\n      settled = true;\n      for (const [key, schema] of arrayComponents) {\n        const name = resolveSchemaName(key);\n        const own =\n          contexts.get(key) === 'item' ? current.get(key)! : arrayComponentMints(name, schema, schemas, 'item');\n        const others = new Map(current);\n        others.delete(key);\n        const context = planArrayComponent(name, schema, schemas, own, others, minted);\n        if (context === contexts.get(key)) continue;\n        settled = false;\n        contexts.set(key, context);\n        activeArrayComponentPlans.set(key, arrayComponentPlan(key, schema, context));\n        current.set(key, arrayComponentMints(name, schema, schemas, context));\n      }\n    }\n    if (!settled) {\n      console.warn(\n        `[oagen] Warning: The item names of the array components did not settle in ${MAX_ARRAY_COMPONENT_ROUNDS} rounds — keeping the last decision`,\n      );\n    }\n    register();\n  }\n\n  const modelsByCleanName = new Map<string, Model>();\n  // Keep the model with more fields when names collide after cleaning\n  // (two raw keys cleaning to one name), or when two inline models — a\n  // discriminated-allOf variant's, a named union's, an array component's\n  // items' — take one name.\n  const keepLarger = (model: Model): void => {\n    const existing = modelsByCleanName.get(model.name);\n    if (!existing || model.fields.length > existing.fields.length) modelsByCleanName.set(model.name, model);\n  };\n  // The key whose own model holds each name, so two keys that resolve to\n  // one name are told apart from a component and a variant of its own. Two\n  // such keys are one model only when their shapes agree\n  // (`modelFingerprint`: fields, types, limits); equal field counts say\n  // nothing, so a definition that differs is reported before it is dropped,\n  // as `keepLargestByName` reports one.\n  const componentKeysByName = new Map<string, string>();\n  const keepComponent = (key: string, model: Model): void => {\n    const other = componentKeysByName.get(model.name);\n    const existing = modelsByCleanName.get(model.name);\n    if (other !== undefined && existing && modelFingerprint(existing) !== modelFingerprint(model)) {\n      const kept =\n        model.fields.length > existing.fields.length\n          ? 'keeping the one with more fields'\n          : 'keeping the first definition';\n      console.warn(\n        `[oagen] Warning: Component schemas \"${other}\" and \"${key}\" both resolve to \"${model.name}\" with different fields or field types (${existing.fields.length} vs ${model.fields.length}) — ${kept}`,\n      );\n    }\n    if (other === undefined) componentKeysByName.set(model.name, key);\n    keepLarger(model);\n  };\n\n  for (const [name, schema] of Object.entries(schemas)) {\n    const pascalName = resolveSchemaName(name);\n\n    if (isEnumComponentSchema(schema)) {\n      enums.push(extractEnum(pascalName, schema));\n    } else if (activeArrayComponentPlans.has(name)) {\n      // No model of its own: a `$ref` to it is the array (`arrayComponentTypeRef`).\n      for (const inlineModel of extractArrayComponentModels(name, schemas)) keepLarger(inlineModel);\n    } else if (activePrimitiveComponentKeys.has(name)) {\n      // No model of its own either: a `$ref` to it is the primitive,\n      // literal, union of primitives or `unknown` it declares (#512, #569).\n    } else if (activeEnumAliasKeys.has(name)) {\n      // Nor an alias of an enum component (#560): a `$ref` to it is the\n      // enum it names, which keeps its own `Enum`.\n    } else {\n      // A bare `$ref` to a component that becomes a model is a model of its\n      // own carrying that component's fields, as `allOf: [{ $ref }]` is\n      // (`composesComponentModel`; #618). One whose chain of `$ref`s\n      // returns to itself, or names no component, carries nothing: it is\n      // the fieldless model it always was, reported once, here, in the one\n      // pass that is no rehearsal (`componentMints` runs `extractModel`\n      // under `rehearse`, which drops warnings).\n      if (bareRefNamesNothing(schema, schemas)) {\n        console.warn(\n          `[oagen] Warning: Component schema \"${name}\" is a $ref that resolves to no component (a chain of $refs that returns to itself, or a $ref no component answers) — reading it as a model with no fields`,\n        );\n      }\n      keepComponent(name, extractModel(pascalName, schema, schemas));\n\n      for (const inlineModel of [\n        ...extractDiscriminatedAllOfVariantModels(schema, pascalName, schemas),\n        ...extractNamedUnionVariantModels(schema, pascalName, schemas),\n      ]) {\n        keepLarger(inlineModel);\n      }\n    }\n  }\n\n  const models = [...modelsByCleanName.values()];\n\n  // Collect inline models from nested object/oneOf properties\n  // that schemaToTypeRef created model refs for but weren't extracted\n  const modelNames = new Set(models.map((m) => m.name));\n  const inlineQueue: Model[] = [...models];\n  while (inlineQueue.length > 0) {\n    const model = inlineQueue.pop()!;\n    for (const field of model.fields) {\n      collectNestedInlineModels(field.type, field.name, model.name, schemas ?? {}, models, modelNames, inlineQueue);\n    }\n  }\n\n  // Collect inline enums from model fields and named-union variants. One\n  // whose name a model extracted here owns (`Pet.kind` beside a `PetKind`\n  // object) is left on its ref: `collectInlineEnumsFromModels` promotes it\n  // under a distinct name once every model is known, as it does any clash.\n  for (const model of models) {\n    collectInlineEnums(model, enums, modelNames);\n  }\n  // ...and from every array component's items, which no model holds: the\n  // reference side types them, so an array of an inline enum lifts its enum\n  // whether or not anything refers to the component, as a named union's\n  // variant enum lifts through `variants`.\n  for (const name of activeArrayComponentPlans.keys()) {\n    const ref = arrayComponentTypeRef(name);\n    if (ref) collectInlineEnumFromRef(ref, enums, new Set(enums.map((e) => e.name)));\n  }\n\n  // NOTE: activeSchemaNameTransform is intentionally NOT cleared here.\n  // extractOperations() calls schemaToTypeRef() for $ref resolution and\n  // needs the same transform active. parseSpec() calls clearSchemaNameTransform()\n  // after all extraction is complete.\n  activeNamedUnionMemo = null;\n  return { models, enums };\n}\n\n/** Clear the module-level schemaNameTransform. Called by parseSpec() after all extraction phases. */\nexport function clearSchemaNameTransform(): void {\n  activeSchemaNameTransform = null;\n  activeEnumSchemaNames = new Set();\n  activeNullableEnumSchemaNames = new Set();\n  activeNullableModelComponentKeys = new Set();\n  activeComponentSchemaKeys = new Set();\n  activeComponentSchemas = undefined;\n  activeNamedUnionMemo = null;\n  activeArrayComponentPlans = new Map();\n  activePrimitiveComponentKeys = new Set();\n  activeEnumAliasKeys = new Set();\n  activeDispatcherVariantPlans = new Map();\n  resetCombinedDeclarations();\n  resetFoldedSchemas();\n  markContestedTitles(undefined);\n}\n\n/**\n * Walk a single TypeRef and extract inline enum refs as top-level enum definitions.\n * Shared by both schemas.ts (field-level) and parse.ts (model-level) collection passes.\n *\n * The lifted `Enum` carries the `description` and link its schema declared\n * and each value's own `description` and `deprecated` (recorded against the\n * ref by `inlineEnumRef`), like a component enum. This is the one place an\n * inline enum becomes an `Enum`, whatever declared it — a property, a\n * parameter, a response header, a request, response, error or secondary\n * body, a webhook parameter or payload — so every site documents its enum\n * by one rule. The first ref lifted under a name decides the enum, its\n * `description`, link and value documentation included — the same\n * first-wins rule `seen` applies to the values — so a key is absent when\n * that schema declared no text or usable link, even if a later same-named\n * one does.\n */\nexport function collectInlineEnumFromRef(ref: TypeRef, enums: Enum[], seen: Set<string>): void {\n  walkTypeRef(ref, {\n    enum: (r) => {\n      if (r.values && !seen.has(r.name)) {\n        seen.add(r.name);\n        const description = inlineEnumDescriptionOf(r);\n        const externalDocs = inlineEnumExternalDocsOf(r);\n        const extensions = inlineEnumExtensionsOf(r);\n        enums.push({\n          name: r.name,\n          ...(description !== undefined ? { description } : {}),\n          values: enumValuesOf(r),\n          ...(externalDocs ? { externalDocs } : {}),\n          ...(extensions ? { extensions } : {}),\n        });\n      }\n    },\n  });\n}\n\n/**\n * Walk a model's type refs (its fields' types and, for a named union, its\n * variants) and extract inline enum refs as top-level enum definitions,\n * skipping one whose name is in `modelNames`: a model and an enum must never\n * share a name, and the collision-aware model pass\n * (`collectInlineEnumsFromModels`) renames and promotes that one later.\n * This ensures type alias files are generated for inline enums.\n */\nfunction collectInlineEnums(model: Model, enums: Enum[], modelNames: ReadonlySet<string>): void {\n  const seen = new Set(enums.map((e) => e.name));\n  for (const ref of collectModelTypeRefs(model)) {\n    walkTypeRef(ref, {\n      enum: (r) => {\n        if (!modelNames.has(r.name)) collectInlineEnumFromRef(r, enums, seen);\n      },\n    });\n  }\n}\n\n/**\n * Walk a TypeRef tree and extract inline models for any model refs that point\n * to schemas with inline object properties (not in components/schemas).\n * This handles nested objects like `totp: { oneOf: [{ type: object, properties: {...} }] }`\n * that schemaToTypeRef turns into model refs but aren't extracted from components.\n */\nfunction collectNestedInlineModels(\n  ref: TypeRef,\n  fieldName: string,\n  parentModelName: string,\n  schemas: Record<string, SchemaObject>,\n  models: Model[],\n  modelNames: Set<string>,\n  queue: Model[],\n): void {\n  // `extractNestedSchema` names what it extracts from the ref it is handed, so\n  // it is only right for refs the field schema produces directly — its own\n  // object, its array items, or its union variants. A ref deeper in the tree\n  // (the items of a variant's array member, a nested union) is named from its\n  // enclosing variant; handing it over here would re-derive the variants'\n  // names from it and register them under the wrong names. Those models come\n  // from the field extractor, which names them by construction.\n  const directRefs = directModelRefNames(ref);\n  walkTypeRef(ref, {\n    model: (modelRef) => {\n      if (modelNames.has(modelRef.name)) return; // already extracted\n      if (!directRefs.has(modelRef.name)) return; // nested under a variant — field extractor's\n      // Check if this model name corresponds to a component schema\n      // by checking all possible original names that would map to this PascalCase name\n      const isComponent = Object.keys(schemas).some((k) => resolveSchemaName(k) === modelRef.name);\n      if (isComponent) return; // will be extracted from components\n\n      // This is a reference to a nested inline model that wasn't extracted.\n      // Look up the field schema in the parent model's component schema to extract it.\n      const parentSchema = findSchemaByName(parentModelName, schemas);\n      if (!parentSchema) return;\n\n      // The declaration the field was typed from, never another member's.\n      const fieldSchema = componentFieldSchema(fieldName, parentModelName, parentSchema, schemas);\n      if (!fieldSchema) return;\n\n      // Extract inline models from the field schema. A union's variants are\n      // named from the field's own qualified name — `extractModel` and\n      // `extractAllOfModel` type every field of a component, inherited ones\n      // included, under the component — which is also variant 0's name\n      // unless variant 0 took its title (`CircleDrawingShape`). Rebuild the\n      // base from the field rather than reading it off the ref, and keep the\n      // ref as the base only if the rebuilt one does not reproduce it. The\n      // variants also step around the names the component's other properties\n      // mint, as the field's TypeRef did, so derive that set from the same\n      // sibling set `extractModel` typed the field with.\n      const reserved = reservedInlineNames(fieldName, collectProperties(parentSchema, schemas), parentModelName);\n      const baseName = unionBaseName(modelRef.name, fieldName, fieldSchema, parentModelName, reserved);\n      if (baseName === null) return; // a union's non-object variant — field extractor's\n      const extracted = extractNestedSchema(baseName, fieldSchema, schemas, reserved);\n      for (const m of extracted) {\n        if (!modelNames.has(m.name)) {\n          models.push(m);\n          modelNames.add(m.name);\n          queue.push(m); // re-scan for deeper nesting\n          // Remembered by the field it was read from, so the field's site\n          // can claim it by origin rather than by name when the field\n          // extractor's copy of the same schema is settled\n          // (`fieldInlineModelBundles`): `Foo.barThing` and `FooBar.thing`\n          // both spell `FooBarThing`, and only one of them is lifted.\n          recordLiftedFieldModel(parentModelName, fieldName, m);\n        }\n      }\n    },\n  });\n}\n\n/**\n * The base name `extractNestedSchema` should name a field's `oneOf` variants\n * from: `refName` itself (the ref the walk is resolving) for every non-union\n * field, and for a union field the field's qualified inline name when naming\n * the inline object variants from it yields `refName`. Null for a union\n * field whose inline object variants are not named `refName`: the ref was\n * minted for one of the union's other variants — a nullable wrapper around\n * an object, an `allOf`, a nested union — which `schemaToTypeRef` typed under\n * a context of its own (`nonObjectVariantContexts`) and which only the field\n * extractor materializes; naming the union's object variants from such a ref\n * would register variant 0's fields under the other variant's name.\n */\nfunction unionBaseName(\n  refName: string,\n  fieldName: string,\n  fieldSchema: SchemaObject,\n  parentModelName: string,\n  reserved: ReadonlySet<string>,\n): string | null {\n  if (!fieldSchema.oneOf) return refName;\n  const fromField = qualifyInlineModelName(toPascalCase(fieldName), parentModelName);\n  const names = [...nameInlineVariants(fieldSchema, fromField, reserved).values()];\n  return names.includes(refName) ? fromField : null;\n}\n\n/**\n * The model refs a field's TypeRef produces directly: the ref itself, the\n * items of a (possibly nullable) array, or each (possibly nullable) variant of\n * a union — the shapes `extractNestedSchema` can name from a ref. Refs nested\n * any deeper are excluded.\n */\nfunction directModelRefNames(ref: TypeRef): Set<string> {\n  const names = new Set<string>();\n  let root = ref;\n  while (root.kind === 'nullable' || root.kind === 'array') {\n    root = root.kind === 'nullable' ? root.inner : root.items;\n  }\n  const leaves = root.kind === 'union' ? root.variants : [root];\n  for (const leaf of leaves) {\n    const inner = leaf.kind === 'nullable' ? leaf.inner : leaf;\n    if (inner.kind === 'model') names.add(inner.name);\n  }\n  return names;\n}\n\n/** Find a component schema by PascalCase name. */\nfunction findSchemaByName(pascalName: string, schemas: Record<string, SchemaObject>): SchemaObject | null {\n  for (const [k, v] of Object.entries(schemas)) {\n    if (resolveSchemaName(k) === pascalName) return v;\n  }\n  return null;\n}\n\n/**\n * Every property a component schema's model has a field for, each with the\n * declarations it received (`PropertyDeclarations`), in field order: the one\n * answer to \"which schema declares `x` for this component\". The field\n * builders (`extractModel`, `extractAllOfModel`), the nested-model lookup\n * (`componentFieldSchema`, for `collectNestedInlineModels`) and the\n * component field pass (`extractInlineModelsFromSchemas`) all read it, so a\n * field and every model nested under it — an inline object, array items,\n * map values, a union's variants — are built from the same declaration. An\n * `allOf` component is read by `readComponentAllOf`; any other component\n * declares its own `properties` as always-applying and, with none, a pure\n * `oneOf`/`anyOf`'s variants' properties as branch-only — the flattening\n * `extractModel` gives such a union. A composed component — an `allOf`, or\n * a typing union beside properties of its own (`composesComponentModel`)\n * — is read by `readComponentAllOf`. `name` is the model's, for the\n * dispatcher detection a variant axis needs.\n */\nexport function componentPropertyLedger(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): Map<string, PropertyDeclarations> {\n  const ledger = new Map<string, PropertyDeclarations>();\n  if (composesComponentModel(schema)) {\n    readComponentAllOf(name, schema, schemas, newComponentReading(ledger));\n    return ledger;\n  }\n  for (const [key, value] of Object.entries(schema.properties ?? {})) {\n    if (value) declareProperty(ledger, key, value, null, false);\n  }\n  if (ledger.size === 0) {\n    for (const variant of unionVariantsOf(schema) ?? []) {\n      for (const [key, value] of Object.entries(variant.properties ?? {})) {\n        if (value) declareProperty(ledger, key, value, null, true);\n      }\n    }\n  }\n  return ledger;\n}\n\n/**\n * The schema `fieldName` of the component `schema` (resolved to `name`) is\n * typed from — `declaredComponentProperty` over `componentPropertyLedger` —\n * or `null` when the component's model has no such field. The nested-model\n * pass builds a field's inline models from this very declaration, so a\n * model it builds (`OuterChild`) has the fields the field's type was built\n * from: a member's when one always declares the field, a branch's only when\n * no member does (workos/oagen#359 review: the lookup walked the schema and\n * returned the first declaration it met, a branch's before a later member's).\n */\nexport function componentFieldSchema(\n  fieldName: string,\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): SchemaObject | null {\n  const entry = componentPropertyLedger(name, schema, schemas).get(fieldName);\n  return entry ? declaredComponentProperty(entry) : null;\n}\n\n/**\n * Extract a model (and nested models) from an inline field schema. `reserved`\n * holds the inline names the field's sibling properties mint\n * (`reservedInlineNames`), which a `oneOf` variant must not take.\n */\nfunction extractNestedSchema(\n  name: string,\n  schema: SchemaObject,\n  schemas?: Record<string, SchemaObject>,\n  reserved: ReadonlySet<string> = NO_RESERVED,\n): Model[] {\n  // Handle oneOf: extract each object variant as its own model. `name` is the\n  // union's base name (the field's qualified inline name), and the variants\n  // are named from it by `nameInlineVariants` — the one place that decides a\n  // variant's name — so they match the union TypeRef and the field extractor\n  // (`UserApiKeyOwner`, `CircleDrawingShape`, `DrawingShapeWithSide`, ...).\n  // Same inline-object test as `schemaToTypeRef` and the field extractor, so\n  // a `type: ['object', 'null']` variant is counted here too instead of\n  // letting the next variant claim its name.\n  //\n  // One keyword types the schema (`classifyInlineSchema`, the order\n  // `schemaToTypeRef` follows), so exactly one branch below runs: a schema\n  // carrying both `items` and `properties` is an array here as it is there,\n  // and never also an object model under the same name. `properties` beside\n  // the composition that types the schema are folded into it first, as\n  // `schemaToTypeRef` folds them, so the variants built here carry them.\n  schema = foldSiblingProperties(schema);\n  const kind = classifyInlineSchema(schema);\n  if (kind === 'union' && schema.oneOf) {\n    const models: Model[] = [];\n    const variantNames = nameInlineVariants(schema, name, reserved);\n    // A nullable wrapper (one non-null branch beside `null`) is the field's\n    // schema: the model built from its branch takes the wrapper's `deprecated`,\n    // limits and link (`collapsedNullableBranch`), exactly as the field\n    // extractor builds the same model, so the two copies agree. A multi-variant\n    // union, nullable or not, is not collapsed: every variant is built as\n    // written.\n    const branch = collapsedNullableBranch(schema);\n\n    for (const variant of schema.oneOf) {\n      const variantName = variantNames.get(variant);\n      if (variantName === undefined) continue;\n      const source = branch ?? variant;\n      // Build the variant's fields under its own name: an inline object\n      // nested under variant N is then referenced as `<VariantN>Child`\n      // (`ThingShapeWithSideCenter`), which is the name the field extractor\n      // materializes it under — not `<Variant0>Child`.\n      const requiredSet = new Set(source.required ?? []);\n      const siblings = collectProperties(source);\n      const fields: Field[] = [];\n      for (const [fn, fs] of Object.entries(source.properties ?? {})) {\n        if (!fs) continue;\n        fields.push(buildFieldFromSchema(fn, fs, variantName, requiredSet, schemas, siblings));\n      }\n      models.push({\n        name: variantName,\n        description: source.description,\n        ...externalDocsEntry(source.externalDocs),\n        fields,\n        ...deprecatedEntry(source),\n        ...constraintsEntry(source),\n        ...schemaExtensionsEntry(source),\n      });\n    }\n    return models;\n  }\n\n  // Handle direct object\n  if (kind === 'object' && schema.properties && (schema.type === 'object' || !schema.type)) {\n    const requiredSet = new Set(schema.required ?? []);\n    const siblings = collectProperties(schema);\n    const fields: Field[] = [];\n    for (const [fn, fs] of Object.entries(schema.properties)) {\n      if (!fs) continue;\n      fields.push(buildFieldFromSchema(fn, fs, name, requiredSet, schemas, siblings));\n    }\n    return [\n      {\n        name,\n        description: schema.description,\n        ...externalDocsEntry(schema.externalDocs),\n        fields,\n        ...deprecatedEntry(schema),\n        ...constraintsEntry(schema),\n        ...schemaExtensionsEntry(schema),\n      },\n    ];\n  }\n\n  // Handle array with inline items — typed, nullable, or `items` with no\n  // `type`: `isArraySchema` is `classifyInlineSchema`'s answer once the\n  // nullable type list is unwrapped, the same test `schemaToTypeRef` applied\n  // when it named the ref. Only items it typed as an object are built here:\n  // `properties` beside a `oneOf`/`anyOf` or `allOf` that types the items are\n  // carried into that composition, whose models the field pass builds\n  // (`extractComponentFieldModels`) — a model of the properties alone would\n  // take their name.\n  if (isArraySchema(schema) && schema.items?.properties && classifyInlineSchema(schema.items) === 'object') {\n    const requiredSet = new Set(schema.items.required ?? []);\n    const siblings = collectProperties(schema.items);\n    const fields: Field[] = [];\n    for (const [fn, fs] of Object.entries(schema.items.properties)) {\n      if (!fs) continue;\n      fields.push(buildFieldFromSchema(fn, fs, name, requiredSet, schemas, siblings));\n    }\n    return [\n      {\n        name,\n        description: schema.items.description,\n        ...externalDocsEntry(schema.items.externalDocs),\n        fields,\n        ...deprecatedEntry(schema.items),\n        ...constraintsEntry(schema.items),\n        ...schemaExtensionsEntry(schema.items),\n      },\n    ];\n  }\n\n  return [];\n}\n\n/**\n * The prefix a variant's `title` contributes to its name: the title trimmed\n * and PascalCased, or null when there is no title or it PascalCases to\n * nothing.\n */\nfunction variantTitlePrefix(variant: SchemaObject): string | null {\n  const title = typeof variant['title'] === 'string' ? variant['title'].trim() : '';\n  return title ? toPascalCase(title) || null : null;\n}\n\n/** `<Prefix><Base>`, or `base` unchanged when it already starts with the prefix (no doubling). */\nfunction prefixedVariantName(prefix: string, base: string): string {\n  return base.startsWith(prefix) ? base : `${prefix}${base}`;\n}\n\n/**\n * The properties `variant` declares that no other inline object variant of\n * the same union declares, in the variant's own `properties` order.\n */\nfunction distinguishingProperties(variant: SchemaObject, siblings: readonly SchemaObject[]): string[] {\n  const declaredElsewhere = new Set<string>();\n  for (const sibling of siblings) {\n    if (sibling === variant) continue;\n    for (const property of Object.keys(sibling.properties ?? {})) declaredElsewhere.add(property);\n  }\n  return Object.keys(variant.properties ?? {}).filter((property) => !declaredElsewhere.has(property));\n}\n\n/**\n * Name an inline object variant of a `oneOf`/`anyOf` that has no better\n * signal: it is not variant 0 (which keeps the union's base name) and no\n * const discriminator gave it a prefix. The name is derived from the\n * variant's own content, never from where it sits in the document (beyond\n * its position among the variants, which only the final counter reads), so\n * an SDK user can tell the variants apart and reordering them changes nothing\n * but which one is variant 0. In order, taking the first candidate that is\n * neither the base name nor a name already given to an earlier variant of\n * the same union:\n *\n *   1. the variant's `title` (trimmed and PascalCased): `<Title><Base>`\n *      (`CircleDrawingShape`), the same prefix form a const discriminator\n *      produces, including the rule that a base already starting with the\n *      prefix is not doubled (that candidate equals the base, so it falls\n *      through); a title an earlier variant already took falls through too;\n *   2. a distinguishing property — the first property, in the variant's own\n *      order, that it declares and no other inline object variant declares:\n *      `<Base>With<Property>` (`DrawingShapeWithSide`); a property that\n *      PascalCases to nothing is skipped;\n *   3. the position counter, `<Base><position + 1>` (`DrawingShape2`; behind\n *      `No` after a base that ends in a digit, `PetShapeV2No2`, see\n *      numberedName), which now remains only for variants whose property\n *      sets are identical, and which keeps counting past a taken name\n *      (`DrawingShape3`).\n *\n * Every candidate is also checked against `reserved`: the inline names the\n * parent's other properties mint (`reservedInlineNames`), so a variant can\n * never take a name another field's model already has — beside a\n * `shape_with_side` object, the `{ side }` variant of `shape` is not\n * `DrawingShapeWithSide` but the next candidate. Read from sibling names and\n * content only, so document order plays no part.\n *\n * `siblings` are the inline object variants of the union, this one included;\n * `emitted` are the names already given to the earlier ones, in order. Every\n * site that names a variant — the union TypeRef, the component-field,\n * request-body and response extractors, and `mintedInlineNames` — goes\n * through this function (via `nameInlineVariant`), so they cannot drift.\n */\nexport function nameUndiscriminatedVariant(\n  variant: SchemaObject,\n  siblings: readonly SchemaObject[],\n  base: string,\n  emitted: readonly string[],\n  reserved: ReadonlySet<string> = NO_RESERVED,\n): string {\n  const taken = (candidate: string): boolean =>\n    candidate === base || emitted.includes(candidate) || reserved.has(candidate);\n\n  const titlePrefix = variantTitlePrefix(variant);\n  if (titlePrefix !== null) {\n    const candidate = prefixedVariantName(titlePrefix, base);\n    if (!taken(candidate)) return candidate;\n  }\n\n  for (const property of distinguishingProperties(variant, siblings)) {\n    const word = toPascalCase(property);\n    if (!word) continue;\n    const candidate = `${base}With${word}`;\n    if (!taken(candidate)) return candidate;\n  }\n\n  for (let position = emitted.length + 1; ; position++) {\n    const candidate = numberedName(base, position);\n    if (!taken(candidate)) return candidate;\n  }\n}\n\n/** No reserved names: for a union with no sibling properties (a request body or response that is itself a union). */\nconst NO_RESERVED: ReadonlySet<string> = new Set();\n\n/** No inline variant names: for a union read before its variants are named (`titleMappedVariantNames`). */\nconst NO_INLINE_NAMES: ReadonlyMap<SchemaObject, string> = new Map();\n\n/**\n * True when the union's inline object variants (two or more) each carry a\n * title and no two titles PascalCase to the same prefix: the one case in\n * which variant 0 is named from its title rather than keeping the base name.\n */\nfunction allDistinctlyTitled(siblings: readonly SchemaObject[]): boolean {\n  if (siblings.length < 2) return false;\n  const prefixes = siblings.map(variantTitlePrefix);\n  return prefixes.every((prefix) => prefix !== null) && new Set(prefixes).size === prefixes.length;\n}\n\n/**\n * The name of one inline object variant of a `oneOf`/`anyOf`, given the\n * union's base name (the field's qualified inline name, e.g. `ApiKeyOwner`),\n * the inline object variants of the union (`siblings`, this one included),\n * the names already given to the earlier variants (`emitted`, in order), and\n * the const-valued property that distinguishes the variants when there is\n * one (`deriveConstNamingDiscriminator`).\n *\n * Variant 0 keeps the bare base name: the union TypeRef and every extractor\n * reference it under that name, and a consumer's typed field keeps the name\n * it always had. Two exceptions: when the union has no const discriminator\n * and every variant carries a distinct title, variant 0 is named from its\n * title like the others (`CircleDrawingShape` beside `SquareDrawingShape`)\n * instead of being the only one left bare; and when the caller says the base\n * is already taken (`baseTaken`: a component schema that is itself the\n * union, whose own model holds the base name — `Model.variants`), variant 0\n * is named like every later variant (`CatPet`, `PetWithLivesLeft`, `Pet1`).\n * Whether the union is discriminated is read from the variants themselves\n * here, not from `discriminator`, so a caller forcing a property (an explicit\n * `discriminator:` without `mapping:`) still agrees with the extractors on\n * variant 0.\n *\n * A later variant takes `<ConstValue><Base>` from the discriminator\n * (`UserApiKeyOwner`) when the value PascalCases to something and the name is\n * neither the base, nor already emitted, nor minted by one of the parent's\n * other properties (`reserved`), and otherwise falls to\n * `nameUndiscriminatedVariant`: its title, a distinguishing property, then\n * the position counter, each checked the same way.\n */\nexport function nameInlineVariant(\n  variant: SchemaObject,\n  siblings: readonly SchemaObject[],\n  base: string,\n  emitted: readonly string[],\n  discriminator: { property: string } | null,\n  reserved: ReadonlySet<string> = NO_RESERVED,\n  baseTaken = false,\n): string {\n  if (emitted.length === 0 && !baseTaken) {\n    const undiscriminated = deriveConstNamingDiscriminator([...siblings]) === null;\n    const titlePrefix = undiscriminated && allDistinctlyTitled(siblings) ? variantTitlePrefix(variant) : null;\n    return titlePrefix === null ? base : prefixedVariantName(titlePrefix, base);\n  }\n\n  if (discriminator) {\n    const constValue = getConstPropertyValue(variant, discriminator.property);\n    const prefix = constValue ? toPascalCase(constValue) : '';\n    if (prefix) {\n      const candidate = prefixedVariantName(prefix, base);\n      if (candidate !== base && !emitted.includes(candidate) && !reserved.has(candidate)) return candidate;\n    }\n  }\n  return nameUndiscriminatedVariant(variant, siblings, base, emitted, reserved);\n}\n\n/**\n * Name every inline object variant of a `oneOf`/`anyOf` schema from the\n * union's base name, keyed by variant schema identity; null, non-object and\n * `$ref` variants get no entry. Positions are local to this variant list, so\n * the union's TypeRef entries and the extracted models agree no matter what\n * else has been extracted. `reserved` holds the inline names the parent's\n * other properties mint (`reservedInlineNames`); every site that has a\n * sibling set passes the same one, so the reference and the model step\n * around them identically.\n *\n * One union shape is named differently: a `oneOf` with no explicit\n * `discriminator:` whose every variant carries a `$ref` or a `title` and pins\n * the same const property, a `$ref` variant's read from its component\n * (`titleMappedDiscriminatorProperty`). Its\n * discriminator mapping has always named an inline variant by its title\n * (`resolveSchemaName(title)`: `Circle`, `Square`, run through the project's\n * schema-name transform like a component), and `schemaToTypeRef` references\n * the variant by that mapped name, so the title is the model name here too —\n * unless it is the base, already emitted, or reserved by a sibling, in which\n * case the variant takes a context-qualified name (its title as a prefix on\n * the base, `CircleDrawingMarker`, else a distinguishing property, else the\n * counter) and the mapping, which is read from this map, follows it. A kept\n * title is context-free: it is the same whatever field, array or map the\n * union sits under, so it names one shape wherever it appears, as a\n * component name would. A second union beside it using the same title for a\n * variant of the identical shape (`schemaShapeKey`) therefore shares the\n * model instead of stepping around it; a sibling giving the same title a\n * different shape reserves it (`reservedInlineNames`), and since both sides\n * read their siblings in isolation the decision is symmetric: when the\n * shapes differ, both unions fall back to their context-qualified names\n * (`CircleDrawingShape`, `CircleDrawingMarker`) and neither keeps the bare\n * `Circle`; when they are identical, both keep `Circle` and one model is\n * emitted. The same holds at any depth of one root, not only between\n * siblings: a title that two unions anywhere under the same root — a\n * component schema, a request body, a response, a header, a webhook payload\n * — give different shapes is contested (`markContestedTitles`, decided\n * before any union is named), and a contested variant takes its\n * context-qualified name exactly as a reserved one does\n * (`CircleDrawingShape` beside `CircleDrawingMarkerShape`), wherever in the\n * root it sits and whichever is declared first. `elementContextName` never\n * lets a context-free name drive an items/values step-aside, which no\n * context could satisfy. `nameInlineVariantEntries` reports which names are\n * context-free; a fallen-back title name is context-dependent.\n *\n * This is the list-level entry point every site uses: `schemaToTypeRef` (via\n * `nameInlineObjectVariants`), `extractNestedSchema`,\n * `extractInlineModelDeep`, `extractInlineModelsFromProperties` and\n * `mintedInlineNames`.\n */\nexport function nameInlineVariants(\n  union: SchemaObject,\n  base: string,\n  reserved: ReadonlySet<string> = NO_RESERVED,\n  baseTaken = false,\n): Map<SchemaObject, string> {\n  const names = new Map<SchemaObject, string>();\n  for (const [variant, entry] of nameInlineVariantEntries(union, base, reserved, baseTaken)) {\n    names.set(variant, entry.name);\n  }\n  return names;\n}\n\n/** A variant's model name, and whether it is context-free (a title-mapped union's title, see `nameInlineVariants`). */\nexport interface InlineVariantName {\n  name: string;\n  contextFree: boolean;\n}\n\n/**\n * `nameInlineVariants`, also telling for each name whether it is context-free.\n * `baseTaken` says the base name itself already belongs to another model (a\n * named union component's own), so variant 0 steps off it (`nameInlineVariant`).\n */\nexport function nameInlineVariantEntries(\n  union: SchemaObject,\n  base: string,\n  reserved: ReadonlySet<string> = NO_RESERVED,\n  baseTaken = false,\n): Map<SchemaObject, InlineVariantName> {\n  const nonNullVariants = (union.oneOf ?? union.anyOf ?? []).filter((v) => !isNullSchema(v));\n  const inlineObjectVariants = nonNullVariants.filter((v) => isInlineObjectSchema(v));\n  const discriminator = deriveConstNamingDiscriminator(inlineObjectVariants);\n  const titles = titleMappedVariantNames(union);\n  const emitted: string[] = [];\n  const entries = new Map<SchemaObject, InlineVariantName>();\n  for (const variant of inlineObjectVariants) {\n    let name: string | null = null;\n    let contextFree = false;\n    const titled = titles.get(variant);\n    if (titled !== undefined) {\n      if (titled !== base && !emitted.includes(titled) && !reserved.has(titled) && !isContestedTitle(variant)) {\n        name = titled;\n        contextFree = true;\n      } else {\n        // The title is taken (by a sibling's model, by a sibling's variant\n        // of a different shape, by an earlier variant of this union, or by a\n        // variant of another shape anywhere under the same root —\n        // `isContestedTitle`): the variant takes a context-qualified name\n        // instead — its title as a prefix on the base\n        // (`CircleDrawingMarker`), else a distinguishing property, else the\n        // counter — and the mapping, read from this map, follows.\n        name = nameUndiscriminatedVariant(variant, inlineObjectVariants, base, emitted, reserved);\n      }\n    }\n    name ??= nameInlineVariant(variant, inlineObjectVariants, base, emitted, discriminator, reserved, baseTaken);\n    emitted.push(name);\n    entries.set(variant, { name, contextFree });\n  }\n  return entries;\n}\n\n/**\n * The inline object variants of a title-mapped union — a `oneOf` with no\n * explicit `discriminator:` whose every non-null variant carries a `$ref` or\n * a `title` and pins the same const property, a `$ref` variant's read from\n * the component it points at (`titleMappedDiscriminatorProperty`; #568) —\n * each with the name its title resolves to (`resolveVariantModelName`: the\n * title run through the project's schema-name transform, like a component\n * name). Empty for any other union, so a caller can read \"is title-mapped\"\n * off the map's size. `nameInlineVariantEntries` names such a variant from\n * this map, and `markContestedTitles` reads the same map to find the\n * variants that give one title two shapes under one root, so the two cannot\n * disagree on which variants a title names. A `$ref` resolves against the\n * document's components (`documentComponentSchemas`) unless a map is handed in.\n */\nexport function titleMappedVariantNames(\n  union: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined = documentComponentSchemas(),\n): ReadonlyMap<SchemaObject, string> {\n  const names = new Map<SchemaObject, string>();\n  if (union.oneOf === undefined || union.discriminator) return names;\n  // Read before the variants are named, so an inline object variant is\n  // named by its title alone — the name `nameInlineVariantEntries` keeps.\n  const members = unionMembers(union, NO_INLINE_NAMES, schemas);\n  if (titleMappedDiscriminatorProperty(members, schemas) === null) return names;\n  for (const { raw, name } of members) {\n    if (isInlineObjectSchema(raw) && name !== null) names.set(raw, name);\n  }\n  return names;\n}\n\n/**\n * The property a title-mapped union pins: when every member is named — an\n * inline object by its title before naming, a `$ref` by its component, a\n * wrapper by the one model it wraps (`unionMembers`) — the first property\n * the first member pins that every member pins too, a `$ref` variant's\n * read from its component, through a `$ref` member of its `allOf` or a\n * `$ref` on the property (`getEffectiveConstPropertyValue`; #568); null\n * when a member is unnamed or no property is shared. The naming side's test (`titleMappedVariantNames`):\n * the titles are kept whether or not the values are distinct — a title\n * given twice within one union falls back through `emitted`\n * (`nameInlineVariantEntries`) — while the discriminator itself needs\n * values that tell the variants apart (`implicitUnionDiscriminator`), so a\n * union of two variants pinning one value keeps its titles and carries no\n * discriminator.\n */\nfunction titleMappedDiscriminatorProperty(\n  members: readonly UnionMember[],\n  schemas: Record<string, SchemaObject> | undefined,\n): string | null {\n  if (members.length < 2 || members.some((m) => m.name === null)) return null;\n  const first = members[0];\n  if (!first) return null;\n  for (const property of Object.keys(getEffectiveProperties(first.resolved, schemas))) {\n    if (members.every((m) => getEffectiveConstPropertyValue(m.resolved, property, schemas) !== null)) return property;\n  }\n  return null;\n}\n\n/**\n * Returns a discriminator descriptor when every inline object variant in a\n * oneOf has a string-const value on the same property — the signature of a\n * discriminated union without an explicit `discriminator:` keyword. Used by\n * `nameInlineVariant` to derive variant names from the const values.\n *\n * Distinct from `implicitUnionDiscriminator` (which reads every variant\n * once named — a `$ref` and a wrapper by their component — to build the\n * mapping): this pass operates on inline anonymous variants, where naming\n * is exactly what we're trying to derive.\n */\nfunction deriveConstNamingDiscriminator(variants: SchemaObject[]): { property: string } | null {\n  if (variants.length < 2) return null;\n  const candidates = Object.keys(variants[0]?.properties ?? {});\n  for (const propName of candidates) {\n    const values = variants.map((v) => getConstPropertyValue(v, propName));\n    if (values.some((v) => v === null)) continue;\n    if (new Set(values).size !== values.length) continue; // collisions = no signal\n    return { property: propName };\n  }\n  return null;\n}\n\n/**\n * True for a schema that `schemaToTypeRef` turns into an inline model reference:\n * it declares `properties` directly (no `$ref`) and is an object — whether by\n * `type: 'object'`, by omitting `type`, or by an OAS 3.1 nullable array such as\n * `type: ['object', 'null']`. Every inline-model extractor must use the same\n * test, or a field's reference points at a model nobody materializes.\n */\nexport function isInlineObjectSchema(schema: SchemaObject | undefined): schema is SchemaObject {\n  if (!schema || schema.$ref || !schema.properties) return false;\n  const { type } = schema;\n  return type === undefined || type === 'object' || (Array.isArray(type) && type.includes('object'));\n}\n\n/** True when a named union admits `null`: a `null` variant (`isNullSchema`), a `type` list with `'null'`, or OAS 3.0 `nullable: true`. */\nfunction isNullableUnionSchema(schema: SchemaObject): boolean {\n  if (schema.nullable === true) return true;\n  if (Array.isArray(schema.type) && schema.type.includes('null')) return true;\n  return (schema.oneOf ?? schema.anyOf ?? []).some(isNullSchema);\n}\n\n/**\n * Whether a `components/schemas` entry that becomes a `Model` admits\n * `null`, so that a `$ref` to it is wrapped in `nullable`\n * (`componentTypeRef`, through `activeNullableModelComponentKeys`): a named\n * union with a `null` variant (`isNullableUnionSchema`); an object\n * component whose own schema `schemaToTypeRef` wraps when it is written\n * inline (`declaresNull`: an OAS 3.1 `type` list naming `'null'`, OAS 3.0\n * `nullable: true` beside a `type`, a nullable `oneOf`/`anyOf` wrapper —\n * `properties` written beside it or not — or a single-member `allOf`\n * around one of these; #615), or a `null`-only schema in either spelling\n * (`isNullSchema`: `{ type: 'null' }`, `{ type: ['null'] }`), which keeps\n * the fieldless model it always became and admits nothing but `null`; or\n * an alias of either — an `allOf`\n * `readInlineAllOf` reads as its `$ref` member, alone or beside members\n * that only annotate or limit it (`allOfReadAsMember`), or a bare `$ref`\n * (`PetOwnerAlias: { $ref: PetOwner }`, with or without annotations beside\n * it; #618, MichaelDeBoey's #646 review: the bare spelling lost the\n * `null` the `allOf` spelling kept), followed through\n * aliases of aliases as an array or enum component's alias is\n * (`componentEntries`) — since the same `allOf` on a field is typed as the\n * reference, wrapper included. A bare `$ref` admits what its target admits\n * and nothing the keywords beside it say, as nothing but annotations is\n * read beside a `$ref`: `B: { $ref: Cat, type: ['object', 'null'] }` (OAS\n * 3.0: `type: 'object', nullable: true`) over a `Cat` that admits no `null`\n * is `B`, and `A: { $ref: B }` is `A`, as `{ $ref: Cat, type: ['object',\n * 'null'] }` on a field is `Cat` (Greptile, #646: the `type` beside the\n * `$ref` made both `nullable`). An `allOf` that merges — a typing member\n * beside the `$ref` (`Cat: { allOf: [{ $ref: PetOwner }, { properties }]\n * }`), a second `$ref`, a `required` that adds to the reference — is read\n * as none of its members: the composed model is the object its merged\n * fields describe, bare, as the same `allOf` on a field is, so a member's\n * nullability never wraps it. OAS 3.0 `nullable: true` beside an `allOf`\n * with no `type` declares nothing, as beside any schema without one. A\n * chain that returns to an entry it has visited admits nothing through\n * the loop.\n */\nfunction isNullableModelComponentEntry(\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  seen: Set<SchemaObject> = new Set(),\n): boolean {\n  if (seen.has(schema)) return false;\n  seen.add(schema);\n  // A bare `$ref` alias is its reference (#618), so it admits what the\n  // component it names admits, at every hop of a chain, as the `allOf`\n  // alias below does (#646 review) — and nothing more: the `$ref` is\n  // followed before any keyword beside it is read, since nothing but\n  // annotations is read beside a `$ref`, so a `type` list naming `'null'`\n  // or OAS 3.0 `nullable: true` beside a `type`, written beside the\n  // `$ref`, declares no `null` here, as it declares none on a field.\n  if (schema.$ref === undefined) {\n    if (isNamedUnionSchema(schema)) return isNullableUnionSchema(schema);\n    if (isNullSchema(schema) || declaresNull(schema)) return true;\n  }\n  const member = schema.$ref !== undefined ? schema : allOfReadAsMember(unwrapNullableSchema(schema));\n  if (member === undefined) return false;\n  if (member.$ref === undefined) return isNullableModelComponentEntry(member, schemas, seen);\n  const key = componentKeyOf(member.$ref);\n  const aliased = key !== undefined && Object.hasOwn(schemas, key) ? schemas[key] : undefined;\n  return aliased !== undefined && isNullableModelComponentEntry(aliased, schemas, seen);\n}\n\n/**\n * True for a schema that `schemaToTypeRef` types as an array: `type: 'array'`,\n * an OAS 3.1 type list whose only non-null member is `array` (`['array',\n * 'null']`, which it unwraps to a nullable array), or — since JSON Schema does\n * not require `type` beside `items` — `items` with no `type` at all. Every\n * site that decides whether to materialize an array's item model must ask\n * this same question, or the items reference a model nobody creates. The\n * answer is `classifyInlineSchema`'s, asked of the schema with its nullable\n * type list unwrapped the way `schemaToTypeRef` unwraps it first: a `$ref` is\n * a reference whatever else it carries; a type list naming another type\n * beside `array` is a union; and a schema that also composes — a `oneOf` /\n * `anyOf` with a typing variant, or an `allOf` with a `$ref` member, a\n * member declaring properties inline or a lone typing member — is that composition,\n * `type: 'array'` or not, since it is read before `items` and the item\n * extractor must not claim a variant's name first. An `allOf` or `oneOf` of\n * bare limits (`[{ minItems: 1 }, { maxItems: 10 }]`) types nothing there and\n * leaves the schema an array here. `items` is not required: a bare\n * `type: 'array'` types nothing to `classifyInlineSchema` and is still an\n * array (of unknown items) to `schemaToTypeRef`; a site that needs items\n * checks for them. A plain boolean rather than a type guard, because a guard\n * on a `SchemaObject` narrows the variable to `never` in the other branch.\n */\nexport function isArraySchema(schema: SchemaObject | undefined): boolean {\n  if (!schema) return false;\n  let bare = schema;\n  if (Array.isArray(schema.type)) {\n    const nonNull = schema.type.filter((t) => t !== 'null');\n    if (nonNull.length !== 1) return false;\n    bare = { ...schema, type: nonNull[0] };\n  }\n  const kind = classifyInlineSchema(bare);\n  return kind === 'array' || (kind === 'other' && bare.type === 'array');\n}\n\n/**\n * The context each variant of a `oneOf`/`anyOf` that is not an inline object\n * is typed and extracted under, keyed by the variant. An inline object\n * variant is named by `nameInlineVariants` (`objectVariantNames`) and is not\n * in the map; a `null` variant marks the union nullable and a `$ref` variant\n * mints nothing, so neither is either. Every other variant is read with its\n * nullable wrapper removed, whichever form it takes (`unwrapNullableSchema`),\n * as the extractor reads it, and gets a context by its kind:\n *\n *   - an array or map variant is typed under `<field>_item` / `<field>_value`,\n *     so what its items or values mint (`ReqShapesItem`, `ReqShapesValue`)\n *     can never take the name an object variant of the same union keeps\n *     (`ReqShape`, `ReqShapeWithX`);\n *   - a variant that would mint a model or enum name under the field's own\n *     context — a nested `oneOf`/`anyOf` with inline object variants (its\n *     variants are named from the field's name as the outer ones are, so its\n *     first one would take the outer variant 0's name), a nullable wrapper\n *     around an inline object, an `allOf`, an inline enum or a union of\n *     string consts — keeps the field's context when nothing it mints there is\n *     claimed (a nested union beside a primitive still names its variants\n *     `ReqShape`, `BReqShape`; an inline enum beside a primitive keeps\n *     `ReqShape`), and is otherwise typed under `<field>_variant_<n>`, n its\n *     1-based position among the non-null variants, as a named union's\n *     non-object variants are (`memberContext`): the nested union's variants\n *     become `ReqShapeVariant2`, `BReqShapeVariant2`, an enum beside an object\n *     variant `ReqShapeVariant2`. Only context-dependent names take part in\n *     the claim check: a nested title-mapped union (`nameInlineVariants`:\n *     every variant titled and pinning the same const) mints its titles,\n *     `A` and `B`, under every context alike, so it keeps the field's\n *     context — it is in the map, so the extractor builds `A` and `B` — and\n *     steps only for a variant of its own that fell back to a\n *     context-qualified name (`AReqShape` when `A` is already taken);\n *   - a variant that mints nothing under the field's context (a primitive, an\n *     `allOf` of `$ref`s alone) keeps the field's context and is not in the map.\n *\n * A name is claimed when a sibling property mints it (a real `shapes_item`\n * object), the caller reserved it (`reservedNames`: the set an enclosing\n * field handed down to its array items or map values, or the names a\n * deferred body's registry already gives another shape — the same set the\n * object variants step around through `reservedNamesFor`), an inline object\n * variant of the union takes it (`ReqShape` — the reason a nested union's\n * variants step), an object variant's own property mints it at any depth\n * (`item` under `ReqShape` is `ReqShapeItem`; a `variant` object holding a\n * `2` object under it mints `ReqShapeVariant2`, as a `variant_2` object\n * would), or an earlier variant of this map minted it, at any depth too.\n * When the context chosen by kind still mints a claimed name — a model of\n * the variant's own, or one at any depth under it (the `loc` of a nested\n * variant `ReqShapeVariant2` is `ReqShapeVariant2Loc`, which a\n * `variant_2_loc` object of `ReqShape` takes) — it steps on exactly as a\n * plain array's items do beside such a sibling\n * (`firstFreeElementContext`: `shapes_array_item`, `shapes_array_item2`, …\n * for an array; `shapes_variant_2_value`, `shapes_variant_2_member_value`, …\n * for the rest), so no two variants of one union share a model, and neither\n * do a variant's items and an object variant's child. The names minted this\n * way are what `mintedInlineNameEntries` reports for the union, so a sibling\n * steps around them in turn. Decided in variant order, from the siblings' and\n * the variants' content only, so both sides of the parser agree:\n * `schemaToTypeRef` types each variant under its context, the extractors\n * re-enter with the variant as a property of that name, and\n * `mintedInlineNameEntries` reads the names under it.\n *\n * Each entry also carries the names the variant must step around when it is\n * typed and extracted under its context (`reserved`): everything claimed at\n * that point — the sibling-minted and caller-reserved names, the object\n * variants and all they nest, every name an earlier variant minted — plus\n * the context-free title an earlier variant kept for a different shape. Both\n * sides hand that set down as `reservedNames`, the set the enclosing field's\n * own variants step around through `reservedNamesFor`, so a nested\n * title-mapped variant whose title is already a sibling's model (`HolderA`\n * beside the `a` object of `Holder`), an earlier variant's model\n * (`HolderShapeVariant2`) or an earlier nested variant's title of another\n * shape falls back to its context-qualified name (`HolderAHolderShape`,\n * `AHolderShape`) exactly as a field-level titled variant does beside the\n * same sibling (`nameInlineVariantEntries`); an earlier nested variant's\n * title of the identical shape is shared, as between sibling fields\n * (`reservedInlineNames`). Without the set, the nested variant would keep\n * the title and the extractor would skip it as already built, so the union\n * would expose the sibling's fields. The names a variant mints are read with\n * its own set (`mintedInlineNameEntries`), so the claims a later variant\n * sees are the names actually taken.\n *\n * `objectVariantNames` is the name each inline object variant's model takes\n * (`nameInlineVariants`), as the caller decided it; those names, and every\n * name the models' own properties mint at any depth\n * (`mintedChildNameEntries`), are claimed before any variant that mints a\n * name is decided. A variant is checked by every name it mints under a\n * context, at any depth too (`mintedInlineNameEntries`, `deep`): a name on\n * one side can equal one any number of levels down on the other, since\n * `variant` and `2` join into the name `variant_2` gives. What a kept\n * title's model nests is named from the title, so it is context-free like\n * the title and never makes a variant step.\n */\nexport function nonObjectVariantContexts(\n  contextName: string | undefined,\n  variants: readonly SchemaObject[],\n  siblings: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n  objectVariantNames: ReadonlyMap<SchemaObject, string>,\n  reservedNames?: ReadonlySet<string>,\n): Map<SchemaObject, VariantContext> {\n  const contexts = new Map<SchemaObject, VariantContext>();\n  if (contextName === undefined) return contexts;\n  const claimed = new Set<string>(reservedNames);\n  for (const [siblingName, siblingSchema] of siblings ?? []) {\n    if (siblingName === contextName) continue;\n    for (const minted of mintedInlineNames(siblingName, siblingSchema, parentModelName)) claimed.add(minted);\n  }\n  for (const variantName of objectVariantNames.values()) claimed.add(variantName);\n  // What the object variants' own properties mint, at any depth, is read\n  // once the first variant that mints a name is decided: a deep read walks\n  // the whole tree, which a union whose other variants mint nothing (an\n  // object beside `enum: ['']`) never needs.\n  let childrenClaimed = false;\n  // The context-free title each earlier variant kept, with the shape it\n  // gave it: reserved for a later variant unless that variant gives the same\n  // title the identical shape, which then shares the model.\n  const keptTitles = new Map<string, string>();\n  let position = 0;\n  for (const variant of variants) {\n    if (isNullSchema(variant)) continue;\n    position++;\n    if (objectVariantNames.has(variant)) continue;\n    const member = unwrapNullableSchema(variant);\n    const kind = classifyInlineSchema(member);\n    if (kind === 'ref') continue;\n    const ownEntries = mintedInlineNameEntries(contextName, member, parentModelName);\n    if (ownEntries.length > 0 && !childrenClaimed) {\n      childrenClaimed = true;\n      for (const [objectVariant, variantName] of objectVariantNames) {\n        for (const child of mintedChildNameEntries(unwrapNullableSchema(objectVariant).properties, variantName)) {\n          claimed.add(child.name);\n        }\n      }\n    }\n    const ownTitles = new Map<string, string>();\n    for (const entry of ownEntries) {\n      if (entry.contextFree && entry.schema) ownTitles.set(entry.name, schemaShapeKey(entry.schema));\n    }\n    const reserved = new Set(claimed);\n    for (const [title, shape] of keptTitles) if (ownTitles.get(title) !== shape) reserved.add(title);\n    // Read once per candidate: the check, the step and the claims below share it.\n    const mintedUnder = new Map<string, MintedInlineName[]>();\n    const minted = (candidate: string): MintedInlineName[] => {\n      let names = mintedUnder.get(candidate);\n      if (!names) {\n        names = mintedInlineNameEntries(candidate, member, parentModelName, reserved, true);\n        mintedUnder.set(candidate, names);\n      }\n      return names;\n    };\n    const dependentNames = (candidate: string): string[] =>\n      minted(candidate)\n        .filter((entry) => !entry.contextFree)\n        .map((entry) => entry.name);\n    const unclaimed = (names: readonly string[]): boolean => names.every((name) => !reserved.has(name));\n    let context: string;\n    if (kind === 'array' || kind === 'map') {\n      context = firstFreeElementContext(\n        contextName,\n        kind === 'array' ? 'item' : 'value',\n        reserved,\n        dependentNames,\n        [],\n      ).context;\n    } else {\n      // A variant that mints nothing (a primitive, an `allOf` of `$ref`s\n      // alone) needs no entry. One that mints only context-free names — a\n      // nested title-mapped union, whose variants are `A` and `B` under\n      // every context — needs one, so the extractor builds those models, but\n      // never a step: no context could move such a name; a taken title is\n      // stepped off through `reserved` instead.\n      if (minted(contextName).length === 0) continue;\n      const own = dependentNames(contextName);\n      const stepped = `${contextName}_variant_${position}`;\n      const under = dependentNames(stepped);\n      context = unclaimed(own)\n        ? contextName\n        : unclaimed(under)\n          ? stepped\n          : firstFreeElementContext(stepped, 'value', reserved, dependentNames, under).context;\n    }\n    contexts.set(variant, { context, reserved, minted: minted(context) });\n    for (const entry of minted(context)) {\n      if (entry.contextFree && entry.schema) keptTitles.set(entry.name, schemaShapeKey(entry.schema));\n      else claimed.add(entry.name);\n    }\n  }\n  return contexts;\n}\n\n/** How a non-object variant is typed and extracted: under `context`, stepping around `reserved` (see `nonObjectVariantContexts`). */\nexport interface VariantContext {\n  context: string;\n  reserved: ReadonlySet<string>;\n  /** Every name the variant mints under `context`, at any depth (`mintedInlineNameEntries`, `deep`). */\n  minted: readonly MintedInlineName[];\n}\n\n/** Which of its keywords types an inline schema; see `classifyInlineSchema`. */\nexport type InlineSchemaKind = 'ref' | 'allOf' | 'union' | 'const' | 'enum' | 'array' | 'object' | 'map' | 'other';\n\n/**\n * Decide which of a schema's keywords types it when several could, in the\n * one precedence every site follows: `$ref`; then `allOf`; then `oneOf` /\n * `anyOf`; then `const`; then `enum`; then `items` as an array (with\n * `type: 'array'` or no `type`); then `properties` as an object (with\n * `type: 'object'`, no `type`, or a type list naming `object`); then a\n * property-less `type: 'object'` as a map. Anything else — a primitive, a\n * type list without `object`, an empty schema — is `other`.\n *\n * `schemaToTypeRef` and every inline-model extractor\n * (`extractInlineModelsFromProperties`, `mintedInlineNameEntries`, and\n * through them the response header and secondary-body paths) dispatch on\n * this, so a schema carrying both `items` and `oneOf` is a union to all of\n * them and the models extracted are exactly the ones the type references.\n * Call it on a schema whose nullable wrappers are already removed.\n */\nexport function classifyInlineSchema(schema: SchemaObject): InlineSchemaKind {\n  if (schema.$ref) return 'ref';\n  if (schema.allOf && allOfTypesSchema(schema.allOf)) return 'allOf';\n  const variants = schema.oneOf ?? schema.anyOf;\n  if (variants && unionTypesSchema(variants)) return 'union';\n  if (schema.const !== undefined) return 'const';\n  if (schema.enum) return 'enum';\n  if (schema.items && (schema.type === 'array' || !schema.type)) return 'array';\n  // A plain boolean: the type guard would otherwise narrow `schema` to `never` below.\n  const inlineObject: boolean = isInlineObjectSchema(schema);\n  if (inlineObject) return 'object';\n  if (schema.type === 'object') return 'map';\n  return 'other';\n}\n\n/** Keywords that give a schema a type of its own; a member carrying none of them only adds limits or documentation. */\nconst TYPING_KEYWORDS: readonly string[] = [\n  '$ref',\n  'allOf',\n  'oneOf',\n  'anyOf',\n  'const',\n  'enum',\n  'items',\n  'properties',\n  'type',\n  'additionalProperties',\n  'patternProperties',\n];\n\n/**\n * Whether an `allOf` is what types the schema, i.e. the cases its branch in\n * `schemaToTypeRef` acts on: a `$ref` member (a reference, or an augmentation\n * model), a member declaring properties inline (a merged model —\n * `declaresInlineProperties`: its own `properties`, or those of a nested\n * `allOf` member or of a `oneOf`/`anyOf` variant, which `mergeAllOfMembers`\n * reads into the model), or exactly one member that types on its own\n * (`allOfTypingMember`, unwrapped) — alone, or beside members that declare\n * no type and only annotate or limit it: `allOf: [{ type: 'string', enum:\n * [...] }, { description }]` is the enum, as `allOf: [{ type: 'string',\n * enum: [...] }]` is (#555: it was not an `allOf` here, and the schema\n * was `unknown`). An `allOf` whose members only conjoin limits or\n * documentation — `allOf: [{ minProperties: 1 }, { maxProperties: 3 }]`\n * beside the schema's own `properties` — does not, nor one of several\n * typing members none of which declares properties — two primitives: the\n * schema is then typed from its own keywords, and `extractConstraints`\n * still conjoins the members' limits onto the field and the model it\n * builds. The one predicate for whether an `allOf` types a schema, at\n * every site that asks: `classifyInlineSchema`, `foldSiblingUnions` for a\n * union written beside an inline schema's `allOf`, and\n * `composesComponentModel` for one beside a component's (#613), so a union\n * beside an `allOf` that only annotates — `{ allOf: [{ description }],\n * oneOf: [...] }` — is the union inline and as a component alike.\n */\nfunction allOfTypesSchema(members: readonly SchemaObject[]): boolean {\n  if (members.some((member) => member.$ref !== undefined || declaresInlineProperties(member))) return true;\n  return allOfTypingMember(members) !== undefined;\n}\n\n/**\n * Whether a `oneOf`/`anyOf` is what types the schema: so when any variant\n * carries a typing keyword. A union of bare constraint sets —\n * `anyOf: [{ required: ['k'] }, { maxProperties: 1 }]` beside the schema's\n * own `properties` — does not, as such an `allOf` does not: the schema is typed from its own\n * keywords (the object, with its `k`), and the variants only limit it. The\n * stop-field test reads a declaration's variants by it too\n * (`endDeclarationFits`), so `total: { type: 'integer', anyOf: [{ maximum:\n * 100 }, { minimum: 200 }] }` stays the integer its `type` says.\n */\nexport function unionTypesSchema(variants: readonly SchemaObject[]): boolean {\n  return variants.some((variant) =>\n    TYPING_KEYWORDS.some((key) => (variant as Record<string, unknown>)[key] !== undefined),\n  );\n}\n\n/**\n * The schema `schemaToTypeRef` and every extractor dispatch on when a schema\n * writes `properties` beside a composition that types it: the composition,\n * carrying the properties. JSON Schema applies every keyword of one schema\n * at once, so `{ properties: { id }, allOf: [{ $ref: Pet }] }` is a `Pet`\n * that also has `id`, and `{ properties: { id }, oneOf: [pet, note] }` is\n * one of `pet` or `note` with `id` in either case. The parser reads a\n * composition before `properties` (`classifyInlineSchema`), so left as\n * written the properties would be dropped — while the response and\n * request-body paths, which read `properties` first, would drop the\n * composition instead and type the same schema two ways.\n *\n * An `allOf` gains the schema's own `properties` and `required` as its first\n * member, so the merge the parser already makes of such an `allOf` — the\n * augmentation of a `$ref` member, a model merged from inline members, a\n * single member unwrapped — carries them, the schema's own first. Each inline\n * object variant of a `oneOf`/`anyOf` (`isInlineObjectSchema`: `properties`\n * with `type: 'object'`, no `type`, or a type list naming `object`, so a\n * nullable or multi-typed object variant included) gains them, the schema's\n * own first and its own declaration kept where the variant declares the same\n * property unless the variant's is the narrower (`narrowsDeclaration`: a\n * variant's `kind: { const: 'cat' }` beside an own `kind: { type: 'string' }`\n * stays `'cat'`, while an own `kind: { $ref: Kind }` pins the enum's values\n * and stays over a variant's `enum` repeating them), so the union keeps\n * every variant, each carries the shared properties and a discriminated one\n * keeps its mapping. Every other variant\n * is typed as written: a `$ref` names a component the parser never merges\n * properties into (it may be an enum or a union it could not augment); a\n * primitive, an array or an enum is no object, so `properties` constrains\n * nothing in it; a nested composition or a nullable union wrapper is left to\n * its own variants. `schemaToTypeRef` reports the variants that may be\n * objects and did not take the properties (`warnOnUncarriedProperties`).\n *\n * Applies only when the schema's `type` admits an object (`object`, a type\n * list naming it, or none), it declares at least one property of its own\n * (`hasFoldableProperties`: an empty `properties: {}` leaves the schema as\n * written, so `{ properties: {}, allOf: [map] }` stays the map and\n * `{ properties: {}, oneOf: [...] }` the union as before) and the\n * composition is what types the schema — an `allOf` or `oneOf` of bare\n * limits beside `properties` leaves the schema the object it is. A property\n * is matched by its own name only (`Object.hasOwn`), so a field named\n * `constructor` or `toString` is a field. Returns the schema itself when nothing folds, else a\n * copy with no `properties` or `required` of its own, every other keyword —\n * `description`, `nullable`, limits, `discriminator`, `additionalProperties`\n * — kept; so folding a folded schema changes nothing. The copy is made\n * once per document schema (`foldedSchemas`) and stands for the schema it\n * was spread from (`derivedCopy`): the same schema folds to the same\n * object at every site that folds it, so a reader that guards by identity\n * meets the folded schema once, however often it is folded, and reads it\n * as that declaration (`sourceDeclaration`). A folded variant is a copy of\n * the document's, and `foldedVariantOrigin` gives the document's back, so\n * a decision recorded against it (a contested title, `isContestedTitle`)\n * reaches the copy. A component schema's own `properties` beside its\n * `allOf` are read the same way, as its first member, by\n * `componentAllOfMembers`.\n */\nexport function foldSiblingProperties(schema: SchemaObject): SchemaObject {\n  let folded = foldedSchemas.get(schema);\n  if (!folded) foldedSchemas.set(schema, (folded = foldAfresh(schema)));\n  return folded;\n}\n\n/**\n * The schema each document schema folds to (`foldSiblingProperties`), so\n * every site that folds one schema — the type builder, the extractors, the\n * request and response readers, the pagination walk, the title walk —\n * reads one object for it, however often it folds. The extractor guards\n * the merge it is materializing by the folded schema's identity\n * (`materializeMergedAllOf`, workos/oagen#566), and a field whose merge\n * reaches itself through a `$ref` variant — `Note.reply: { allOf: [{ depth\n * }], oneOf: [{ $ref: Note }, { other }] }` — is folded again on every\n * re-entry (#398 review: each fold built a new copy no guard had seen, so\n * the re-entry never ended, where the same union written as an `allOf`\n * member ended at once with `NoteReply { depth, id, reply, other }`; the\n * `properties`-beside-`allOf` fold, `{ allOf: [{ $ref: Note }],\n * properties: { reply: { depth } } }`, did the same). Forgotten per\n * document (`resetFoldedSchemas`), where the combined declarations are\n * (`resetCombinedDeclarations`). A schema that folds nothing maps to\n * itself.\n */\nlet foldedSchemas = new WeakMap<SchemaObject, SchemaObject>();\n\n/** Forget every folded schema: a document's components are being set (`extractSchemas`) or released (`clearSchemaNameTransform`). */\nfunction resetFoldedSchemas(): void {\n  foldedSchemas = new WeakMap();\n}\n\n/** What `foldSiblingProperties` returns for a schema not folded yet (see there). */\nfunction foldAfresh(schema: SchemaObject): SchemaObject {\n  const folded = foldSiblingUnions(schema);\n  if (!hasFoldableProperties(folded)) return folded;\n  const kind = classifyInlineSchema(folded);\n  if (kind !== 'allOf' && kind !== 'union') return folded;\n  const { properties, required, ...rest } = folded;\n  const own: SchemaObject = { type: 'object', properties, ...(required && required.length > 0 && { required }) };\n  // The fold stands for the schema it was spread from (`derivedCopy`), so a\n  // reader that guards by identity reads it as that declaration.\n  if (kind === 'allOf') return derivedCopy({ ...rest, allOf: [own, ...(folded.allOf ?? [])] }, folded);\n  const conjoin = (variant: SchemaObject): SchemaObject => conjoinSiblingProperties(variant, own);\n  return derivedCopy(\n    folded.oneOf\n      ? { ...rest, oneOf: folded.oneOf.map(conjoin) }\n      : { ...rest, anyOf: (folded.anyOf ?? []).map(conjoin) },\n    folded,\n  );\n}\n\n/**\n * The one reading of an `allOf` combined with a `oneOf`/`anyOf`, at every\n * site (#398, #429): a schema that writes a typing union beside an `allOf`\n * that types it (`allOfTypesSchema`, `unionTypesSchema`) is the `allOf`\n * with the union as one more member, the last — `{ allOf: [base], oneOf:\n * [{ ownerId }, { shelterId }] }` is `{ allOf: [base, { oneOf: [...] }] }`,\n * the base's fields plus each variant's properties as optional fields\n * (`mergeAllOfMembers`), exactly as the union written as a member is read\n * (#334) — since JSON Schema applies every keyword of one schema, so the\n * instance is the base and one (or any) of the variants. A `oneOf` and an\n * `anyOf` written together become two members, and a `discriminator`\n * written beside them goes with the first, so a component reading the\n * member finds it on the union it dispatches\n * (`detectAllOfVariantDiscriminator`). Before, the `allOf` was read alone\n * (`classifyInlineSchema` gives it precedence), so a field, a component\n * and a response body dropped the union while a request body built the\n * union from the variants alone, without the base. Read by\n * `foldSiblingProperties` before the schema's own `properties` are folded\n * in, and by `componentAllOfMembers` for a component schema — one\n * predicate, `allOfTypesSchema`, deciding at both sites whether the\n * `allOf` types the schema (`composesComponentModel`) — so the two agree.\n * A union of bare limits beside the `allOf`, or a union beside an `allOf`\n * whose members only annotate or limit the schema (`allOf: [{ description\n * }]`, `allOf: [{ minProperties: 1 }]`, `allOf: []`), is left as written:\n * the one keyword that types the schema is read as before, so `{ allOf:\n * [{ description: 'A new pet.' }], oneOf: [{ $ref: Pet }, { $ref: Toy }]\n * }` is the union of `Pet` and `Toy` inline and, as a component, the named\n * union `New` (#613: the component read the union as a member beside any\n * `allOf` and flattened it). The copy stands for the schema it was\n * spread from (`derivedCopy`), as every fold's does, so the fold of its\n * own properties that follows chains back to the document's declaration.\n */\nfunction foldSiblingUnions(schema: SchemaObject): SchemaObject {\n  if (schema.$ref || !schema.allOf || !allOfTypesSchema(schema.allOf)) return schema;\n  const unions = besideUnionMembers(schema);\n  if (unions.length === 0) return schema;\n  const { oneOf: _oneOf, anyOf: _anyOf, discriminator: _discriminator, ...rest } = schema;\n  return derivedCopy({ ...rest, allOf: [...schema.allOf, ...unions] }, schema);\n}\n\n/**\n * The `oneOf`/`anyOf` a schema writes beside the keywords that type it, as\n * the `allOf` members they are read as (`foldSiblingUnions`,\n * `componentAllOfMembers`): one member per typing union\n * (`unionTypesSchema`), `oneOf` first, the schema's own `discriminator`\n * carried on the first. Empty for a schema that writes no typing union.\n * The variant list is the document's own, not a copy, so a decision\n * recorded against it (a dispatcher's variant names, a reported union)\n * reaches every reading.\n */\nfunction besideUnionMembers(schema: SchemaObject): SchemaObject[] {\n  const members: SchemaObject[] = [];\n  for (const keyword of ['oneOf', 'anyOf'] as const) {\n    const variants = schema[keyword];\n    if (!variants || !unionTypesSchema(variants)) continue;\n    const discriminator = members.length === 0 && schema.discriminator ? { discriminator: schema.discriminator } : {};\n    members.push({ [keyword]: variants, ...discriminator });\n  }\n  return members;\n}\n\n/**\n * Whether a component schema's model is composed (`extractAllOfModel`,\n * reading `componentAllOfMembers`): it writes an `allOf` that types it\n * (`allOfTypesSchema`) or one beside properties of its own, or a typing\n * `oneOf`/`anyOf` beside properties of its own (#429: `Pet: { properties:\n * { id }, oneOf: [{ ownerId }, { shelterId }] }` is the object and one of\n * the variants, so its model flattens or dispatches the union as an\n * `allOf: [{ properties: { id } }, { oneOf: [...] }]` does; before, the\n * union was not read, and only a component that inherited `Pet` through an\n * `allOf` member carried the variants' properties), or it is a bare `$ref`\n * to another component (`CatAlias: { $ref: Cat }`, with or without text,\n * flags, limits or `x-*` keys beside the `$ref`), which composes the\n * component it names exactly as `CatAlias: { allOf: [{ $ref: Cat }] }`\n * does (#618: it was read from its own `properties`, which it has none of,\n * so it was a model with no fields, and every `$ref` to it was typed as\n * that empty model, while the `allOf` spelling carried `Cat`'s fields). A\n * bare `$ref` alias of an enum, array or primitive component never reaches\n * the model readers (`extractSchemas` reads it through to what it names;\n * #512, #560), so it is unchanged by this. A `oneOf`/`anyOf` with\n * no properties beside it is a named union (`isNamedUnionSchema`), an\n * enum, an array or a primitive component, never composed here; an empty\n * `properties: {}` declares nothing (`hasFoldableProperties`), so it leaves\n * the union a named union as before. So does an `allOf` whose members only\n * annotate or limit the schema — `New: { allOf: [{ description: 'A new\n * pet.' }], oneOf: [{ $ref: Pet }, { $ref: Toy }] }`, `allOf: [{\n * minProperties: 1 }]`, `allOf: []` — beside one typing union with no\n * properties of its own: such an `allOf` does not type the schema, by the\n * one predicate `foldSiblingUnions` reads an inline schema by\n * (`allOfTypesSchema`), so the union is the keyword that types it, and the\n * component is the named union `New` of `Pet` and `Toy` that `{\n * description: 'A new pet.', oneOf: [...] }` is, the members part of its\n * wrapper (#613: any `allOf` made the component composed, and the union\n * was flattened into `New { name?, toy? }`, the variants' properties as\n * optional fields with no variants, while the same schema inline was the\n * union). An `allOf` that only annotates or limits with no typing union\n * beside it still composes, as it did — a fieldless model, unless the\n * component is read as a primitive (`isPrimitiveComponentSchema`) — and so\n * does one beside both a typing `oneOf` and a typing `anyOf`: two axes a\n * named union cannot carry (`compositionKind` names one), read as two\n * members, each flattened or dispatched on its own, as they were (#613\n * review: read as a named union, the component kept the `oneOf` alone).\n */\nfunction composesComponentModel(schema: SchemaObject): boolean {\n  // A component written as a bare `$ref` composes one member, the reference (#618).\n  if (schema.$ref !== undefined) return true;\n  const unions = besideUnionMembers(schema).length;\n  if (schema.allOf === undefined) return hasFoldableProperties(schema) && unions > 0;\n  // One typing union beside an `allOf` that only annotates or limits the\n  // schema, with no properties of its own, is the named union; a `oneOf`\n  // and an `anyOf` written together are two axes a named union cannot\n  // carry, so they stay two members, as they were (#613 review).\n  return allOfTypesSchema(schema.allOf) || hasFoldableProperties(schema) || unions !== 1;\n}\n\n/**\n * Whether `schema` declares at least one property of its own that a\n * composition beside them could carry (see `foldSiblingProperties`). An\n * empty `properties: {}` declares none: folded, it would add an empty object\n * member that types the schema as a model the extractor builds nothing for\n * (`{ properties: {}, allOf: [map] }` is the map, as written).\n */\nfunction hasFoldableProperties(schema: SchemaObject): boolean {\n  if (schema.$ref || schema.properties === undefined || Object.keys(schema.properties).length === 0) return false;\n  const { type } = schema;\n  return type === undefined || type === 'object' || (Array.isArray(type) && type.includes('object'));\n}\n\n/**\n * The members a component schema's `allOf` model is built from: the schema's\n * own `properties` and `required`, when it declares a property\n * (`hasFoldableProperties`), as one more member — the first — then the\n * members as written. JSON Schema applies both at once, so\n * `Dog: { allOf: [{ $ref: Pet }], properties: { breed }, required: [breed] }`\n * has `Pet`'s properties and `breed`: the own keywords are read here exactly\n * as `foldSiblingProperties` folds them for an inline schema, and as\n * `mergeAllOfMembers` reads this component when a `$ref` member names it\n * (its own properties, then its members), so the component's model and an\n * inline merge that names it carry its own and inherited properties in the\n * same order (workos/oagen#307: the component's own properties were not\n * read, and `Dog` was `{ name }`). Then a typing `oneOf`/`anyOf` written\n * beside them (`besideUnionMembers`), as the last member, exactly as\n * `foldSiblingUnions` folds it for an inline schema (#398, #429): the\n * component is the base and one of the variants, dispatched or flattened\n * after every always-applying member, whether the union sits beside an\n * `allOf` that types the schema (`NewPet: { allOf: [base], oneOf: [...]\n * }`) or beside the component's own `properties` alone (`Pet: {\n * properties: { id }, oneOf: [...] }`, read as a composed model by\n * `composesComponentModel`) — and by the predicate `foldSiblingUnions`\n * folds by, `allOfTypesSchema`: a union beside an `allOf` whose members\n * only annotate or limit the schema, with no properties of its own, is\n * no member here but the named union the component is\n * (`isNamedUnionSchema`), so `New: { allOf: [{ description: 'A new pet.'\n * }], oneOf: [{ $ref: Pet }, { $ref: Toy }] }` composes nothing and is the\n * union of `Pet` and `Toy` inline and as the component alike (#613: the\n * union was appended beside any `allOf`, and the component flattened to\n * `New { name?, toy? }`). A\n * component written as a bare `$ref` composes one member and nothing\n * else: the reference as written — `CatAlias: { $ref: Cat, description }`\n * is read as `{ allOf: [{ $ref: Cat }], description }` is (#618) — which\n * every reader follows to the component it names through a chain of\n * aliases (`followMemberRefs`), so the readers key nothing on the member\n * itself. The text, flag, limits and keys written beside the `$ref` are\n * the wrapper's own (`allOfWrapperLayer`, `constraintsEntry`), never a\n * member; `properties`, `required`, an `allOf`, a union or a\n * `discriminator` beside it are not read, here or anywhere a `$ref` is\n * followed (#618 review, #622: nothing but annotations is read beside a\n * `$ref`), so only the `allOf: [{ $ref }]` spelling composes them. Shared\n * by `extractAllOfModel`, at every level of a `$ref` chain, and by\n * `extractDiscriminatedAllOfVariantModels`, whose dispatcher base carries\n * them into every variant. Empty for a component that composes nothing.\n */\nfunction componentAllOfMembers(schema: SchemaObject): readonly SchemaObject[] {\n  if (!composesComponentModel(schema)) return [];\n  if (schema.$ref !== undefined) return [{ $ref: schema.$ref }];\n  const members = [...(schema.allOf ?? []), ...besideUnionMembers(schema)];\n  if (!hasFoldableProperties(schema)) return members;\n  const { properties, required } = schema;\n  return [{ type: 'object', properties, ...(required && required.length > 0 && { required }) }, ...members];\n}\n\n/**\n * `variant` carrying `own`'s properties and required names when it is an\n * inline object (`isInlineObjectSchema`), itself otherwise. The schema's own\n * properties come first and win where both declare a name, unless the\n * variant's declaration is the narrower (`narrowsDeclaration`): JSON Schema\n * applies both, so a variant's `kind: { const: 'cat' }` beside an own\n * `kind: { type: 'string', readOnly: true }` is a read-only `'cat'`, and a\n * discriminated union keeps its mapping. A `$ref` to an enum component pins\n * that enum's values (`pinnedValues`), so an own `kind: { $ref: Kind }`\n * stays `Kind` over a variant's `enum` that repeats its values, as an own\n * `enum` of them does. The own declaration's flags, documentation, limits\n * and extensions (`declarationKeywords`) stay the field's wherever the\n * variant's sets none. The required names are the union of both lists.\n */\nfunction conjoinSiblingProperties(variant: SchemaObject, own: SchemaObject): SchemaObject {\n  if (!isInlineObjectSchema(variant)) return variant;\n  const properties: Record<string, SchemaObject | undefined> = { ...own.properties };\n  for (const [name, property] of Object.entries(variant.properties ?? {})) {\n    const held = properties[name];\n    if (!Object.hasOwn(properties, name)) properties[name] = property;\n    else if (held && property && narrowsDeclaration(property, held)) {\n      properties[name] = { ...declarationKeywords(held), ...property };\n    }\n  }\n  const required = [...new Set([...(own.required ?? []), ...(variant.required ?? [])])];\n  const folded: SchemaObject = { ...variant, properties, ...(required.length > 0 && { required }) };\n  foldedVariantOrigins.set(folded, foldedVariantOrigin(variant) ?? variant);\n  return folded;\n}\n\n/**\n * Whether a variant's declaration of a property is narrower than the\n * schema's own (`conjoinSiblingProperties`): it is typed by the values it\n * pins (`pinnedValues`: a `const`, an `enum`, or a `$ref` to an enum\n * component, `null` among them when it admits `null`), and the own\n * declaration pins none — and does not forbid a `null` the variant admits\n * (`forbidsNull`) — or pins every one of them and more. Any other pair —\n * the same values, values the own does not all admit (`null` included, so\n * a nullable variant beside an own that forbids `null` keeps the own), a\n * variant that pins none — is not, and the own declaration stays.\n */\nfunction narrowsDeclaration(variant: SchemaObject, own: SchemaObject): boolean {\n  const narrow = pinnedValues(variant);\n  if (narrow === undefined) return false;\n  const wide = pinnedValues(own);\n  if (wide === undefined) return !narrow.includes(null) || !forbidsNull(own);\n  return narrow.every((value) => wide.includes(value)) && wide.some((value) => !narrow.includes(value));\n}\n\n/**\n * Whether a declaration that pins no values forbids `null`: it names a\n * type (`type`) that is not `null` and admits `null` by no spelling the\n * parser reads (`isNullableEnumSchema`). A typeless declaration, or a\n * `$ref`, constrains nothing here.\n */\nfunction forbidsNull(schema: SchemaObject): boolean {\n  return schema.type !== undefined && !isNullSchema(schema) && !isNullableEnumSchema(schema);\n}\n\n/**\n * The values a declaration pins a property to, when that is what types it,\n * `null` among them when the declaration admits it: its own `const`,\n * `enum` or `oneOf`/`anyOf` of string consts (`ownPinnedValues`), or those\n * of the schema it reaches (`referencedPinnedValues`) — the enum component\n * its `$ref`, or an `allOf` read as that reference (the spellings that\n * annotate one: a lone `allOf: [{ $ref }]`, or one whose other members add\n * nothing to it, `allOf: [{ $ref }, { description }]`), names, read through\n * a chain of references. So an own\n * `kind: { $ref: Kind }`, `Kind` the enum `[cat, dog]`, pins `cat` and\n * `dog` exactly as an own `kind: { enum: [cat, dog] }` does: it stays over\n * a variant that repeats those values, or names more, and gives way to a\n * variant's `const: cat`. `null` is one more value, admitted by any\n * spelling the parser reads as nullable (`isNullableEnumSchema`: a type\n * list naming `null`, `nullable: true`, a `null` value or variant), so a\n * variant's `{ type: ['string', 'null'], enum: [cat] }` pins `cat` and\n * `null` and is not narrower than an own `enum: [cat, dog]`, which forbids\n * `null`. `undefined` for a declaration that pins none — a plain type, an\n * object, a `$ref` to anything but an enum.\n */\nfunction pinnedValues(\n  schema: SchemaObject,\n  seen: ReadonlySet<SchemaObject> = new Set(),\n): readonly unknown[] | undefined {\n  const values = ownPinnedValues(schema) ?? referencedPinnedValues(schema, seen);\n  if (values === undefined) return undefined;\n  return isNullableEnumSchema(schema) && !values.includes(null) ? [...values, null] : values;\n}\n\n/** The values `schema` pins by its own `const`, `enum` or `oneOf`/`anyOf` of string consts; `undefined` when it pins none that way. */\nfunction ownPinnedValues(schema: SchemaObject): readonly unknown[] | undefined {\n  const kind = classifyInlineSchema(schema);\n  if (kind === 'const') return [schema.const];\n  if (kind === 'enum') return schema.enum;\n  return isConstUnionEnumSchema(schema) ? (constUnionEnumMembers(schema) ?? undefined)?.map((m) => m.value) : undefined;\n}\n\n/**\n * The values the one schema a declaration reaches pins (`pinnedValues`):\n * the component its `$ref` names (`componentSchemaOf`), the member its\n * `allOf` is typed as (`allOfReadAsMember`: a lone member, or the `$ref`\n * member beside members that add nothing to it), or the variant its\n * nullable union wrapper collapses to (`nullableUnionBranch`). `undefined`\n * when it reaches none — an `allOf` merged into a model among them — or one\n * already read (a cycle of references, which runs through a `$ref`: the\n * copy `allOfReadAsMember` makes of a lone inline member is never reached\n * twice).\n */\nfunction referencedPinnedValues(schema: SchemaObject, seen: ReadonlySet<SchemaObject>): readonly unknown[] | undefined {\n  const kind = classifyInlineSchema(schema);\n  const reached =\n    kind === 'ref'\n      ? schema\n      : kind === 'allOf'\n        ? allOfReadAsMember(schema)\n        : kind === 'union'\n          ? nullableUnionBranch(schema)\n          : undefined;\n  const next = reached?.$ref ? componentSchemaOf(reached.$ref) : reached;\n  if (next === undefined || seen.has(next)) return undefined;\n  return pinnedValues(next, new Set([...seen, next]));\n}\n\n/** The document's variant each folded copy was made from (`conjoinSiblingProperties`). */\nconst foldedVariantOrigins = new WeakMap<SchemaObject, SchemaObject>();\n\n/** The document's variant `variant` is a folded copy of, or `undefined` when it is the document's own. */\nexport function foldedVariantOrigin(variant: SchemaObject): SchemaObject | undefined {\n  return foldedVariantOrigins.get(variant);\n}\n\n/**\n * The `oneOf`/`anyOf` lists `warnOnUncarriedProperties` has reported, so a\n * union is reported once however many times it is typed. Keyed by the list,\n * which every nullable unwrap keeps while it copies the schema around it.\n * Replaced per document (`resetFoldWarnings`).\n */\nlet reportedUncarriedProperties = new WeakSet<readonly SchemaObject[]>();\n\n/** Forget which unions `warnOnUncarriedProperties` has reported; called once per document (`extractSchemas`). */\nexport function resetFoldWarnings(): void {\n  reportedUncarriedProperties = new WeakSet();\n}\n\n/**\n * Warn, once per union, when `properties` written beside a typing\n * `oneOf`/`anyOf` are not carried into a variant that may be an object — a\n * `$ref`, an `allOf`, a nested union, a map, or a nullable union wrapper\n * around an object — because only an inline object variant takes them\n * (`foldSiblingProperties`). A primitive, array or enum variant is no object\n * and is not reported. Called by `schemaToTypeRef` with the context it types\n * the schema under, before the fold, on the schema as written — and by the\n * response and request-body paths, which fold a body before anything types\n * it, on the body as written under the body's name.\n */\nexport function warnOnUncarriedProperties(\n  schema: SchemaObject,\n  contextName: string | undefined,\n  parentModelName: string | undefined,\n): void {\n  const variants = schema.oneOf ?? schema.anyOf;\n  if (!variants || !hasFoldableProperties(schema) || classifyInlineSchema(schema) !== 'union') return;\n  if (reportedUncarriedProperties.has(variants)) return;\n  const uncarried: number[] = [];\n  variants.forEach((variant, index) => {\n    if (isNullSchema(variant) || isInlineObjectSchema(variant)) return;\n    const kind = classifyInlineSchema(unwrapNullableSchema(variant));\n    if (kind === 'ref' || kind === 'allOf' || kind === 'union' || kind === 'map' || kind === 'object') {\n      uncarried.push(index + 1);\n    }\n  });\n  if (uncarried.length === 0) return;\n  reportedUncarriedProperties.add(variants);\n  const keyword = schema.oneOf ? 'oneOf' : 'anyOf';\n  const which = uncarried.length === 1 ? `variant ${uncarried[0]} is` : `variants ${uncarried.join(', ')} are`;\n  const context =\n    contextName === undefined ? '' : ` (context: ${parentModelName ? `${parentModelName}.` : ''}${contextName})`;\n  console.warn(\n    `[oagen] Warning: \\`properties\\` beside \\`${keyword}\\` are carried into its inline object variants only; ${which} typed as written, without them${context}`,\n  );\n}\n\n/**\n * The synthetic context names a multi-type inline variant's non-object\n * members are typed and extracted under, chosen so the models they name can\n * never collide with a model named from one of the variant's own properties.\n * An `array` member's items go under `item` (`<Variant>Item`), falling back\n * to `array_item` (`<Variant>ArrayItem`) and then `array_item2`,\n * `array_item3`, ... when a property already claims that name; any other\n * member goes under `value` (`<Variant>Value`), then `member_value`,\n * `member_value2`, .... A candidate is skipped when the model name\n * `qualifyInlineModelName` derives from it equals one derived from a\n * property — compared after qualification, so a property `items`, whose\n * name singularizes to `<Variant>Item`, blocks `item` as well.\n * This is the single source of these names for the TypeRef builder\n * (`inlineVariantTypeRef`) and the extractors (`variantMemberSchemas`).\n */\nexport function variantMemberKeys(variant: SchemaObject, variantName: string): { item: string; value: string } {\n  const modelNameFor = (key: string): string => qualifyInlineModelName(toPascalCase(key), variantName);\n  const claimed = new Set(Object.keys(variant.properties ?? {}).map(modelNameFor));\n  const pick = (preferred: string, fallback: string): string => {\n    for (let i = 0; ; i++) {\n      const candidate = i === 0 ? preferred : i === 1 ? fallback : `${fallback}${i}`;\n      if (!claimed.has(modelNameFor(candidate))) return candidate;\n    }\n  };\n  return { item: pick('item', 'array_item'), value: pick('value', 'member_value') };\n}\n\n/**\n * The schemas carried by the non-object members of a multi-type inline\n * variant (`type: ['object', 'array']` with `items`), keyed by the synthetic\n * context name from `variantMemberKeys` that `schemaToTypeRef` types them\n * under, so an inline object item is `<Variant>Item` (or `<Variant>ArrayItem`\n * when `item` is taken) and its own nested objects `<Variant>ItemChild`.\n * Every extractor re-enters with these under the variant's name so the\n * models line up with the refs by construction. A map member cannot occur\n * here: a variant with `properties` is typed as a model, never as a map.\n */\nexport function variantMemberSchemas(variant: SchemaObject, variantName: string): Record<string, SchemaObject> {\n  const members: Record<string, SchemaObject> = {};\n  if (Array.isArray(variant.type) && variant.type.includes('array') && variant.items) {\n    members[variantMemberKeys(variant, variantName).item] = variant.items;\n  }\n  return members;\n}\n\n/**\n * The `$ref` a field's schema is typed as, read through the wrappers\n * `schemaToTypeRef` reads through — a nullable wrapper of any spelling\n * (`unwrapNullableSchema`) and an `allOf` read as its one typing member or\n * as a plain reference (`allOfReadAsMember`), however they nest — with\n * every schema on the way that documents or limits the field, nearest\n * first: the field's own, each wrapper it unwraps to, the members written\n * beside the `$ref` in an `allOf` (`{ allOf: [{ $ref: PetId }, {\n * description }] }`, the usual OAS 3.0 way to document a reference) or\n * beside the member it unwraps to (`{ allOf: [{ oneOf: [{ $ref: PetId },\n * { type: 'null' }] }, { description }] }`; #555) and the `$ref` schema\n * itself, with whatever is written beside it. A bare `$ref` is itself, with\n * the field's schema as its one level. `undefined` when the schema is typed\n * as no reference: an inline schema, or an `allOf` merged into a model.\n */\nfunction wrappedReference(schema: SchemaObject): { reference: SchemaObject; levels: SchemaObject[] } | undefined {\n  const levels: SchemaObject[] = [];\n  let current = schema;\n  for (;;) {\n    if (current.$ref !== undefined) {\n      levels.push(current);\n      return { reference: current, levels };\n    }\n    levels.push(current);\n    const bare = unwrapNullableSchema(current);\n    if (bare.$ref !== undefined) {\n      levels.push(bare);\n      return { reference: bare, levels };\n    }\n    if (bare !== current) levels.push(bare);\n    const member = allOfReadAsMember(bare);\n    if (member === undefined) return undefined;\n    // The other members annotate or limit the field: those beside a plain\n    // reference's `$ref`, and those that declare no type beside the one\n    // member unwrapped (`annotatingAllOfMembers`), which is read as a copy.\n    levels.push(\n      ...(member.$ref !== undefined ? (bare.allOf ?? []) : annotatingAllOfMembers(bare)).filter(\n        (other) => other !== member,\n      ),\n    );\n    current = member;\n  }\n}\n\n/**\n * The levels an entry the reference passes declares on, nearest first: the\n * entry's own schema, then each `allOf` member of its that declares no type\n * and so only annotates or limits it (`annotatingAllOfMembers`) — part of\n * the entry's own declaration, as such a member is part of a field's (#555)\n * — so an alias documented that way (`PetKind: { allOf: [{ $ref: Kind }, {\n * description }] }`; #560) documents the site that names it, as the same\n * `allOf` written on the site does. The member the entry is read as — a\n * lone one, the `$ref` itself — is no level: what is written on it is its\n * own, as a component model built from one does not read it (#399), while\n * its limits are conjoined by `extractConstraints` as an `allOf`'s always\n * are.\n */\nfunction aliasEntryLevels(entry: SchemaObject): SchemaObject[] {\n  return [entry, ...annotatingAllOfMembers(entry)];\n}\n\n/**\n * What a field or parameter schema that references an array or primitive\n * component, or an alias of an enum component, reads the component's\n * declarations through (#399, #512, #560). Such a component, or alias,\n * names no model that could carry what it declares beside its items, its\n * type or its `$ref`, so the site reads that from every entry the reference\n * passes on its way to the declaration — the entry it names, each alias in\n * turn, the array or primitive component itself (`componentEntries`,\n * nearest first), each through the levels it declares the reference on\n * (`aliasEntryLevels`) for its documentation, and once, as one schema, for\n * its limits (`limitEntries`: `extractConstraints` conjoins an entry's\n * annotating members' limits with its own, the entry's `pattern` or\n * `multipleOf` standing where a member's conflicts, as it reads a field's\n * schema; #588 review: folded as levels, a member's `pattern: 'b$'` won\n * over the alias's own `'^a'`) — under its own. An enum component is no entry: the\n * `Enum` carries what it declares, as it does for a bare `$ref` to it, so\n * the site reads the aliases alone and the enum's `example` as that `$ref`\n * reads it (`enumComponent`). A bare `$ref` reads all of it: text, flags,\n * default, examples, `x-*` keys and limits, as the same schema written\n * inline carries them. Under a wrapper the type builder reads through — a\n * nullable one, an `allOf` read as the reference (`wrappedReference`) — the\n * site documents itself: its text, flags, default, examples and keys come\n * from the wrapper and the members written beside the `$ref`, and none from\n * the component (#335 review). Its limits are another matter: the wire\n * enforces the component's whether or not the `$ref` is wrapped, and no\n * model carries them, so they conjoin with the site's own exactly as a bare\n * `$ref`'s do (#512 review). `undefined` for a schema that is no such\n * reference — an inline schema, or a `$ref` to a model, named union or enum,\n * which leaves all of it on that node — and outside an extraction, as\n * `isArrayComponentRef` is.\n */\nexport interface ComponentReference {\n  /** The schemas on the way to the `$ref`, nearest first: the site's own and, under a wrapper, each wrapper, the members beside the `$ref` and the `$ref` schema with whatever is written beside it (`wrappedReference`). */\n  own: SchemaObject[];\n  /** The levels of every entry the reference passes on its way to the array or primitive, nearest first (`componentEntries`, each entry with its annotating `allOf` members, `aliasEntryLevels`), which the site documents itself from; for an alias of an enum, the aliases' alone. */\n  entries: SchemaObject[];\n  /** The entries themselves, nearest first, each once: what the site conjoins limits from, an entry's annotating members' read with its own by `extractConstraints` (#588 review: as levels of `entries`, a member's `pattern` or `multipleOf` won over the entry's own, which `combineConstraints` keeps); for an alias of an enum, the aliases alone. */\n  limitEntries: SchemaObject[];\n  /** The enum component an alias chain ends at (#560), on the schema it declares its members on (`enumComponentDeclaration`), read for its `example`/`examples` as a bare `$ref` to it is, and by a parameter for the fallbacks it reads from any component a bare `$ref` names; absent for an array or primitive component, whose own declarations are among `entries`. */\n  enumComponent?: SchemaObject;\n  /** Whether the schema is the bare `$ref`, which reads the entries' documentation as well as their limits. */\n  bare: boolean;\n}\n\nexport function componentReference(\n  schema: SchemaObject,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): ComponentReference | undefined {\n  const wrapped = wrappedReference(schema);\n  if (!wrapped || !componentSchemas) return undefined;\n  const { reference } = wrapped;\n  const declares = isArrayComponentRef(reference)\n    ? isArrayComponentSchema\n    : isPrimitiveComponentRef(reference)\n      ? isPrimitiveComponentSchema\n      : isEnumAliasRef(reference)\n        ? isEnumComponentSchema\n        : undefined;\n  const target = declares && resolveComponentSchemaRef(reference, componentSchemas);\n  if (!declares || !target) return undefined;\n  const entries = componentEntries(target, componentSchemas, declares) ?? [target];\n  // The enum an alias chain ends at, read on the schema it declares its\n  // members on (`enumComponentDeclaration`), as a bare `$ref` to it reads it.\n  const last = entries[entries.length - 1];\n  const enumComponent = declares === isEnumComponentSchema ? (enumComponentDeclaration(last) ?? last) : undefined;\n  const aliases = enumComponent ? entries.slice(0, -1) : entries;\n  return {\n    own: wrapped.levels,\n    entries: aliases.flatMap(aliasEntryLevels),\n    limitEntries: aliases,\n    ...(enumComponent ? { enumComponent } : {}),\n    bare: schema.$ref !== undefined,\n  };\n}\n\n/**\n * Build a single Field from a schema property entry. Shared across all\n * extraction sites. Pass `componentSchemas` where they are at hand so a\n * field whose schema is a bare `$ref` can take `example`/`examples` from the\n * component it points at, as a parameter does, and what an array or\n * primitive component declares beside its items or its type through its\n * aliases (`componentReference`). `siblingProperties` are the\n * other properties of the object the field belongs to (`collectProperties`);\n * array items and map values use them to step aside from a sibling that\n * would take their singular name (`elementContextName`).\n */\nexport function buildFieldFromSchema(\n  fieldName: string,\n  fieldSchema: SchemaObject,\n  contextName: string,\n  requiredSet: Set<string>,\n  componentSchemas?: Record<string, SchemaObject>,\n  siblingProperties?: ReadonlyMap<string, SchemaObject>,\n): Field {\n  // What the field reads from an array or primitive component, or an alias\n  // of an enum component, it references (`componentReference`): every\n  // entry's limits, and a bare `$ref`'s documentation too. A `$ref` to a\n  // model, named union or enum leaves all of it on that node but the\n  // `example` and `examples` a field takes from any component a bare `$ref`\n  // names — the enum an alias resolves to included (#560). An enum\n  // component is read on the schema it declares its members on\n  // (`enumComponentDeclaration`), its `allOf` wrapper's examples included.\n  const { settings, constraints } = fieldReading(fieldSchema, componentSchemas);\n  const externalDocs = readExternalDocs(settings.externalDocs);\n  const extensions = extensionsOf(settings, SCHEMA_CONSUMED_EXTENSIONS);\n  return {\n    name: fieldName,\n    type: schemaToTypeRef(fieldSchema, fieldName, contextName, siblingProperties),\n    required: requiredSet.has(fieldName),\n    description: settings.description,\n    // The field schema's own link, read like `description`: a sibling of a\n    // `$ref` is the field's, and a bare `$ref` gives none — the referenced\n    // model carries its own — unless the `$ref` names an array component.\n    ...(externalDocs ? { externalDocs } : {}),\n    readOnly: settings.readOnly || undefined,\n    writeOnly: settings.writeOnly || undefined,\n    deprecated: settings.deprecated || undefined,\n    default: settings.default,\n    example: settings.example,\n    // Only materialise the key when there is something to carry so existing\n    // inline snapshots of fields without examples stay byte-identical.\n    ...(settings.examples ? { examples: settings.examples } : {}),\n    // Keywords written beside a `$ref` (legal in OAS 3.1) are the field's own;\n    // a bare `$ref` to a model declares none, and the model carries its limits.\n    ...(constraints ? { constraints } : {}),\n    ...(extensions ? { extensions } : {}),\n  };\n}\n\n/**\n * What a field written as `fieldSchema` reads off its levels, as one\n * declaration — `settings`: its `description`, `externalDocs`, `readOnly`,\n * `writeOnly`, `deprecated`, `default`, `example`, `examples` and `x-*`\n * keys, each as `buildFieldFromSchema` carries it — with the limits it\n * conjoins (`constraints`: `schemaConstraints`). The levels are the field's\n * schema and, under it, each `allOf` member that declares no type and so\n * only annotates or limits the field (`annotatingAllOfMembers`; #555:\n * `allOf: [{ $ref: Kind }, { description }]` and `allOf: [{ type: 'string'\n * }, { deprecated: true }]` read neither the text nor the flag) — nearest\n * first, as `wrappedReference` orders them for a reference to an array or\n * primitive component — and, for a bare `$ref` alone, the entries the\n * reference passes (`componentReference`): under a wrapper the field\n * documents itself, from the wrapper and the members beside the `$ref`,\n * and takes none of the component's text, flags, default, examples or keys\n * (#335 review), while its limits conjoin from every entry either way\n * (#512 review). The one reading of a field's settings, shared with the\n * request-body fold (`fieldSettings`), so a folded discriminator carries\n * exactly what the variants' own fields carry (#607 review: the fold read\n * its settings through every hop of the pin walk, a `$ref` under a wrapper\n * included, so two variants writing `kind: { allOf: [{ $ref: CatKind }] }`\n * with `CatKind: { const: 'cat', readOnly: true }` folded to a read-only\n * `kind` where each variant's own field is not).\n */\nfunction fieldReading(\n  fieldSchema: SchemaObject,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): { settings: SchemaObject; constraints: Constraints | undefined } {\n  // What the field reads from an array or primitive component, or an alias\n  // of an enum component, it references (`componentReference`): every\n  // entry's limits, and a bare `$ref`'s documentation too. A `$ref` to a\n  // model, named union or enum leaves all of it on that node but the\n  // `example` and `examples` a field takes from any component a bare `$ref`\n  // names — the enum an alias resolves to included (#560). An enum\n  // component is read on the schema it declares its members on\n  // (`enumComponentDeclaration`), its `allOf` wrapper's examples included.\n  const reference = componentReference(fieldSchema, componentSchemas);\n  const target = resolveComponentSchemaRef(fieldSchema, componentSchemas);\n  const refTarget = reference ? reference.enumComponent : target && (enumComponentDeclaration(target) ?? target);\n  const aliases = reference?.entries ?? [];\n  const bare = fieldSchema.$ref !== undefined;\n  const own = reference?.own ?? [fieldSchema, ...annotatingAllOfMembers(fieldSchema)];\n  const levels = bare ? [...own, ...aliases] : own;\n  const { example, examples } = resolveExamples(\n    [...own, ...(bare ? [...aliases, ...(refTarget ? [refTarget] : [])] : [])].map((level) => ({\n      example: level.example,\n      examples: nonEmptyExamples(level.examples),\n    })),\n  );\n  // The first level whose link is usable (`readExternalDocs`) gives the field its link.\n  const linked = levels.find((level) => readExternalDocs(level.externalDocs));\n  // Limits conjoin, as JSON Schema applies every level at once\n  // (`schemaConstraints`: the same reading the field's type carries, #545);\n  // an `x-*` key the nearer level declares wins, as a collapsed wrapper's\n  // does (`withWrapperDocs`). Both start from the component, so its keys\n  // come first.\n  const constraints = schemaConstraints(fieldSchema, componentSchemas);\n  const extensions = levels.reduceRight<Extensions | undefined>((keys, level) => {\n    const own = extensionsOf(level, SCHEMA_CONSUMED_EXTENSIONS);\n    return own ? { ...keys, ...own } : keys;\n  }, undefined);\n  const description = levels.map((level) => level.description).find((text) => text !== undefined && text !== null);\n  const defaulted = levels.find((level) => level.default !== undefined);\n  const settings: SchemaObject = {\n    ...(description !== undefined ? { description } : {}),\n    ...(linked ? { externalDocs: linked.externalDocs } : {}),\n    ...(levels.some((level) => level.readOnly) ? { readOnly: true } : {}),\n    ...(levels.some((level) => level.writeOnly) ? { writeOnly: true } : {}),\n    ...(levels.some((level) => level.deprecated === true) ? { deprecated: true } : {}),\n    ...(defaulted ? { default: defaulted.default } : {}),\n    ...(example !== undefined ? { example } : {}),\n    ...(examples ? { examples } : {}),\n    ...extensions,\n  };\n  return { settings, constraints };\n}\n\n/**\n * The settings a field written as `schema` carries, as the keywords of one\n * declaration — `fieldReading`'s settings with the limits it conjoins\n * beside them — so declarations written through different wrappers and\n * references compare as written ones do (`agreedDeclarationKeys`,\n * `agreedExtensions`): the request-body fold reads each variant's\n * discriminator declaration this way and carries onto the discriminator it\n * rebuilds the settings every variant agrees on\n * (`flattenDiscriminatedUnionBody`; #607 review).\n */\nexport function fieldSettings(\n  schema: SchemaObject,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n): SchemaObject {\n  const { settings, constraints } = fieldReading(schema, componentSchemas);\n  return { ...settings, ...constraints };\n}\n\n/**\n * Build an EnumRef the same way the regular enum path does for naming. The\n * `oneOf`/`anyOf` wrapper is the schema that declares this enum, so its\n * `description` and link are the enum's (`rawDescription`,\n * `rawExternalDocs`), as an inline `enum:` schema's are; the members carry\n * each variant's own documentation (`constUnionEnumMembers`).\n */\nfunction buildSyntheticEnumRef(\n  members: readonly EnumMember[],\n  contextName: string | undefined,\n  parentModelName: string | undefined,\n  rawExternalDocs: unknown,\n  rawDescription: unknown,\n  extensions: Extensions | undefined,\n): TypeRef {\n  return inlineEnumRef(\n    inlineEnumName(contextName, parentModelName),\n    members,\n    rawExternalDocs,\n    rawDescription,\n    extensions,\n  );\n}\n\n/**\n * The name `schemaToTypeRef` gives an inline enum typed under `contextName`\n * (`GetPetError404`; `status` → `Status`): qualified by `parentModelName`\n * with its list-item markers stripped (`DirectoryListItem` + `State` →\n * `DirectoryState`) unless the name already starts with it and adds\n * something after it (`extendsParentName`: `Connection` + `ConnectionType` →\n * `ConnectionType`; `Reply` + `Reply` → `ReplyReply`, never the model's own\n * name, workos/oagen#621), then passed through the active\n * `schemaNameTransform` as a component's name is, so a project's rename map\n * (`RadarAction` → `RadarListAction` in `oagen.config.ts`) reaches inline\n * enums too. One rule for every inline enum: an `enum:` list and a `oneOf`\n * of consts (`buildSyntheticEnumRef`) alike.\n */\nexport function inlineEnumName(contextName: string | undefined, parentModelName: string | undefined): string {\n  const baseName = toPascalCase(contextName ?? 'UnknownEnum');\n  const cleanParent = parentModelName ? stripListItemMarkers(parentModelName) : undefined;\n  const qualifiedName =\n    cleanParent && !extendsParentName(baseName, cleanParent) ? `${cleanParent}${baseName}` : baseName;\n  return activeSchemaNameTransform ? activeSchemaNameTransform(qualifiedName) : qualifiedName;\n}\n\n/**\n * How `schemaToTypeRef` types a schema as an inline enum, when it does: the\n * one decision the typer's enum branches read. Decided on the schema as\n * the typer sees it at those branches — its nullable wrappers removed, so\n * callers unwrap first (`unwrapNullableSchema`): a `oneOf`/`anyOf` whose\n * non-null variants are string `const` schemas (`constUnionEnumMembers`)\n * with two or more members, or any number beside an `enum:` list that\n * restricts them, is a `const-union` enum of those members; an `enum:` list\n * of any count of non-null members but one is an `enum-list` enum, one\n * alone being a literal; every other shape — a `$ref`, an `allOf`, a union\n * of other variants, an object, an array — is not an enum here (an array's\n * items are typed on their own).\n */\nexport function inlineEnumSpelling(schema: SchemaObject): InlineEnumSpelling | undefined {\n  const kind = classifyInlineSchema(schema);\n  if (kind === 'union') {\n    const members = constUnionEnumMembers(schema);\n    if (members !== null && (members.length >= 2 || Array.isArray(schema.enum))) {\n      return { spelling: 'const-union', members };\n    }\n    return undefined;\n  }\n  if (kind === 'enum' && nonNullEnumValues(schema.enum).length !== 1) return { spelling: 'enum-list' };\n  return undefined;\n}\n\n/** The two spellings of an inline enum `schemaToTypeRef` lifts (`inlineEnumSpelling`), with the const union's members. */\nexport type InlineEnumSpelling = { spelling: 'const-union'; members: EnumMember[] } | { spelling: 'enum-list' };\n\n/**\n * The string const a schema pins `property` to in its own `properties`, in\n * either spelling:\n *   { properties: { event: { const: \"x\" } }, required: [\"event\"] }\n *   { properties: { event: { type: \"string\", enum: [\"x\"] } } }\n * read as the declaration pins it (`pinnedDeclarationValue`): as written,\n * or behind the wrappers the type builder reads the declaration through —\n * `{ allOf: [{ const: \"x\" }] }`, a nullable wrapper, and, with `schemas`,\n * a `$ref` to a component pinning one value or to an alias of one (#607).\n * Null when it pins none there (`getEffectiveConstPropertyValue` reads\n * through `allOf` wrappers too), and for a schema written as a `$ref`,\n * which pins nothing of its own: nothing but annotations is read beside a\n * `$ref`, so `properties` beside an alias's reference are no declaration\n * here, as they are none for its model (`getEffectiveProperties`,\n * `componentAllOfMembers`; Greptile, #618 review: `CatAlias: { $ref: Cat,\n * properties: { kind: { const: 'other' } } }` had `kind: 'cat'` as a field\n * while a union mapped `'other'` to it).\n */\nfunction getConstPropertyValue(\n  schema: SchemaObject,\n  property: string,\n  schemas?: Record<string, SchemaObject>,\n): string | null {\n  if (schema.$ref !== undefined) return null;\n  const prop = schema.properties?.[property];\n  return prop ? pinnedDeclarationValue(prop, schemas) : null;\n}\n\n/**\n * The one string a schema pins as written — a string `const`, or an `enum:`\n * of exactly one string; null otherwise. The leaf `pinnedDeclarationValue`\n * reads once every wrapper is read through; no other site reads a\n * declaration as written.\n */\nfunction pinnedStringValue(schema: SchemaObject): string | null {\n  if (typeof schema.const === 'string') return schema.const;\n  if (Array.isArray(schema.enum) && schema.enum.length === 1 && typeof schema.enum[0] === 'string') {\n    return schema.enum[0];\n  }\n  return null;\n}\n\nfunction resolveVariantModelName(schema: SchemaObject): string | null {\n  if (schema.$ref) {\n    // A `$ref` names a model by the component it names; a pointer deeper\n    // into one names a schema, not a model, and so names nothing here (#539).\n    const key = componentKeyOf(schema.$ref);\n    return key === undefined ? null : resolveSchemaName(key);\n  }\n  const title = typeof schema['title'] === 'string' ? (schema['title'] as string) : null;\n  if (title) return resolveSchemaName(title);\n  return null;\n}\n\n/** Look up the discriminator's mapped variant name for an inline object\n *  variant by reading its const-valued discriminator property. Returns null\n *  when the variant doesn't pin the property to a string const, or when\n *  the value isn't in the mapping. */\nfunction mapVariantToDiscriminatorEntry(\n  variant: SchemaObject,\n  discriminator: { property: string; mapping: Record<string, string> },\n): string | null {\n  const value = getConstPropertyValue(variant, discriminator.property);\n  if (value === null) return null;\n  // Own keys only: a const spelled like an inherited property (`constructor`)\n  // must not resolve to `Object.prototype`'s.\n  return Object.hasOwn(discriminator.mapping, value) ? (discriminator.mapping[value] ?? null) : null;\n}\n\n/**\n * The spec's own `discriminator.mapping` as an inline union carries it: each\n * target with a leading `#/components/schemas/` stripped and otherwise as the\n * document spelled it (`cat_dto` stays `cat_dto`; a target in another section\n * stays whole) — unlike a named union's, whose targets are resolved to IR\n * model names (`namedUnionDiscriminator`) — except an entry whose target is\n * a pointer deeper into a component, which is settled to the model the\n * schema it points at is built as (`deferPointerMappingEntries`; #539,\n * #619): a pointer (`Zoo/properties/dog`) names no model, cleaned or not. The one reader for every site\n * that builds an inline union, a field or a response (`schemaToTypeRef`) and\n * a request body (`typePickedRequestBody`) alike, so the same union reads the\n * same wherever it is written and the differ can tell a key a new variant\n * brings from one that names no variant (#458 review).\n */\nexport function inlineMappingTargets(mapping: Record<string, string> | undefined): Record<string, string> {\n  return Object.fromEntries(Object.entries(mapping ?? {}).map(([k, v]) => [k, inlineMappingTarget(v)]));\n}\n\n/** One target as an inline union's mapping spells it (`inlineMappingTargets`): a leading `#/components/schemas/` stripped, the rest as written. */\nfunction inlineMappingTarget(target: string): string {\n  return target.replace(/^#\\/components\\/schemas\\//, '');\n}\n\n/**\n * The names reserved for a union typed under `contextName`: the set an\n * enclosing field handed down (`reservedNames`, for a union among a field's\n * array items or map values), else the inline names the field's own sibling\n * properties mint (`reservedInlineNames`), else nothing. The extractor\n * derives the same set at each of those levels, so the reference and the\n * model step around a sibling's name identically.\n */\nfunction reservedNamesFor(\n  contextName: string | undefined,\n  siblingProperties: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n  reservedNames: ReadonlySet<string> | undefined,\n): ReadonlySet<string> {\n  if (reservedNames) return reservedNames;\n  if (contextName === undefined) return NO_RESERVED;\n  return reservedInlineNames(contextName, siblingProperties, parentModelName);\n}\n\n/**\n * Name the inline object variants of a field's `oneOf`/`anyOf` exactly as the\n * inline-model extractors do (`extractInlineModelsFromProperties` in\n * inline-models.ts, and `extractNestedSchema` / `extractInlineModelDeep`\n * here): the union's base name is the field's qualified inline name, the\n * names the field's sibling properties mint — or the set handed down from an\n * enclosing field — are reserved (`reservedNamesFor`), and\n * `nameInlineVariants` hands out the variant names from there. Returned keyed\n * by variant schema identity.\n */\nfunction nameInlineObjectVariants(\n  union: SchemaObject,\n  contextName: string | undefined,\n  parentModelName: string | undefined,\n  siblingProperties: ReadonlyMap<string, SchemaObject> | undefined,\n  reservedNames: ReadonlySet<string> | undefined,\n): Map<SchemaObject, string> {\n  const baseInlineName = qualifyInlineModelName(toPascalCase(contextName ?? 'UnknownModel'), parentModelName);\n  return nameInlineVariants(\n    union,\n    baseInlineName,\n    reservedNamesFor(contextName, siblingProperties, parentModelName, reservedNames),\n  );\n}\n\n/**\n * The TypeRef for an inline object variant whose extracted model is\n * `modelName`, keeping every other type the variant allows. Mirrors what\n * `schemaToTypeRef` builds for the same schema — one member per non-null\n * entry of a `type` array, `union`-wrapped when there is more than one,\n * `nullable`-wrapped when `null` or OAS 3.0 `nullable: true` is present —\n * with the `object` member swapped for a ref to `refName`: the model's own\n * name, or the component the spec's `discriminator.mapping` points the\n * variant's const at, which substitutes for the model exactly as it does\n * inline (`mapVariantToDiscriminatorEntry`).\n * `type: ['object', 'string']` → `union[model, string]`,\n * `['object', 'integer', 'null']` → `nullable<union[model, integer]>`,\n * `['object', 'null']` / `nullable: true` → `nullable<model>`.\n * A `oneOf: [X, { type: 'null' }]` variant has no `properties` of its own\n * and never reaches this path; `schemaToTypeRef` types it directly.\n *\n * Anything inline under a non-object member is named from the variant's\n * model — never from the union's field, and never from the mapping: an\n * `array` member types its items under `modelName` as parent with the\n * context `variantMemberKeys` picks (`item` → `<Variant>Item`, or\n * `array_item` → `<Variant>ArrayItem` when a property claims `item`), and\n * any other member under its `value` key (`<Variant>Value` for an inline\n * enum, else `<Variant>MemberValue`). The extractor materializes those\n * members under the same model (`variantMemberSchemas`), which it builds\n * whether or not the mapping redirects the object member; naming them from\n * the mapped component would reference `CatItem`, which nothing extracts,\n * and naming them from the field would hand variant 0's model name to every\n * variant's items.\n *\n * The variant's own limits ride on what it is typed as, where that can\n * carry them (#545): the union of a multi-type variant, under its nullable\n * wrapper — `{ type: ['object', 'string'], properties, maxLength: 5 }` is\n * `union<Model | string>` with `{ maxLength: 5 }` — as a type list's are\n * the union's; a model reference carries none, the model its own. Attached\n * here, so a named union's variant (`namedUnionEntry`) carries them as an\n * inline union's does (Greptile, #545 review round 3: the inline caller\n * attached them and the named one did not). Each per-type copy of the\n * variant stands for the variant (`derivedCopy`), so a merge the variant\n * carries is the one the extractor builds for it, whichever type it is read\n * as (`materializingMergedAllOfName`; #566 review), and keeps the keywords\n * that apply to an instance of its type, as a type list's copies do\n * everywhere (`typeListCopy`; #616): the `string` member of `{ type:\n * ['object', 'string'], properties }` is `{ type: 'string' }`. A type two\n * members are typed alike as is one member (`dedupeTypeRefs`).\n */\nfunction inlineVariantTypeRef(variant: SchemaObject, modelName: string, refName: string = modelName): TypeRef {\n  const modelRef: ModelRef = { kind: 'model', name: refName };\n  if (refName !== modelName) redirectedVariantModelRefs.add(modelRef);\n  const typeList = Array.isArray(variant.type) ? variant.type : [];\n  const nullable = variant.nullable === true || typeList.includes('null');\n  const keys = variantMemberKeys(variant, modelName);\n  // The variant's limits are the union's, as a type list's are\n  // (`schemaToTypeRef`; #545), so the other members are built without them.\n  const members = dedupeTypeRefs(\n    typeList\n      .filter((t) => t !== 'null')\n      .flatMap((t) => {\n        if (t === 'object') return [modelRef];\n        const copy = typeListCopy(variant, t, { nullable: false });\n        return copy === undefined ? [] : [buildTypeRef(copy, t === 'array' ? keys.item : keys.value, modelName)];\n      }),\n  );\n  const ref: TypeRef = members.length > 1 ? { kind: 'union', variants: members } : modelRef;\n  return withSchemaConstraints(nullable ? asNullable(ref) : ref, variant);\n}\n\nfunction extractEnum(name: string, schema: SchemaObject): Enum {\n  // The schema the component declares its members on: itself, or — for a\n  // component written as an `allOf` read as its one typing member — that\n  // member with the wrapper layer's text, link, flag, default, examples\n  // and keys on it (`enumComponentDeclaration`), so `{ allOf: [{ type:\n  // 'string', enum }], description }` is read as `{ type: 'string', enum,\n  // description }` is.\n  const declaration = enumComponentDeclaration(schema) ?? schema;\n  // The members of either spelling (`enumMembersOf`), each with its own\n  // `description` and `deprecated`. A `null` member or `type: 'null'`\n  // variant marks the schema as nullable (OAS 3.1); it is not a value.\n  // Nullability is carried on the `$ref` side via\n  // `activeNullableEnumSchemaNames`, so it is dropped here instead of\n  // emitting a bogus `NULL = \"null\"` member.\n  const values: EnumValue[] = (enumMembersOf(declaration) ?? []).map(toEnumValue);\n\n  const rawDefault = declaration.default;\n  const def =\n    rawDefault !== undefined && values.some((v) => v.value === rawDefault)\n      ? (rawDefault as string | number)\n      : undefined;\n\n  // The component's own `description` is the enum's, as a model's is its\n  // model's; a lifted inline enum takes its schema's the same way\n  // (`collectInlineEnumFromRef`). Present only when it has content.\n  return {\n    name,\n    ...descriptionEntry(declaration.description),\n    values,\n    default: def,\n    ...externalDocsEntry(declaration.externalDocs),\n    ...deprecatedEntry(declaration),\n    ...schemaExtensionsEntry(declaration),\n  };\n}\n/**\n * The model of a `components/schemas` entry that becomes one (resolved to\n * `name`): a composed component — an `allOf`, a typing union beside\n * properties of its own, or a bare `$ref` to another component, read as\n * `allOf: [{ $ref }]` is (`composesComponentModel`; #618) — through\n * `extractAllOfModel`; any other from its own `properties`, or, with none,\n * the variants of a pure `oneOf`/`anyOf` flattened as optional fields. A\n * bare `$ref` whose chain returns to itself or names no component composes\n * nothing (`bareRefNamesNothing`, which `extractSchemas` reports once), so\n * its model has no fields.\n */\nfunction extractModel(name: string, schema: SchemaObject, schemas?: Record<string, SchemaObject>): Model {\n  // A composed component: an `allOf`, its own `properties` beside it read\n  // as its first member and a typing union beside either as its last, or a\n  // bare `$ref` read as its one member (`componentAllOfMembers`,\n  // `composesComponentModel`).\n  if (composesComponentModel(schema)) {\n    return extractAllOfModel(name, schema, schemas);\n  }\n\n  const requiredSet = new Set(schema.required ?? []);\n  // The sibling set the field extractor derives for this component too, so\n  // array items and map values are named the same on both sides.\n  const siblings = collectProperties(schema, schemas);\n\n  // Its own `properties`, or — with none — the variants of a pure\n  // `oneOf`/`anyOf` flattened as optional fields (`componentPropertyLedger`,\n  // the ledger the nested-model lookup and the field pass read too). This\n  // handles schemas like UpdateOrganizationMembership which is a oneOf with\n  // mutually exclusive field groups (role_slug vs role_slugs); a variant's\n  // field is optional whatever the schema's own `required` says, as it was.\n  const emptyRequired = new Set<string>();\n  const fields: Field[] = [...componentPropertyLedger(name, schema, schemas).values()].map((entry) =>\n    buildFieldFromSchema(\n      entry.name,\n      declaredComponentProperty(entry),\n      name,\n      entry.unconditional ? requiredSet : emptyRequired,\n      schemas,\n      siblings,\n    ),\n  );\n\n  // When additionalProperties is an object schema alongside properties,\n  // surface it as a catch-all map field so emitters can generate Map<string, T>.\n  if (schema.additionalProperties && typeof schema.additionalProperties === 'object' && schema.properties) {\n    const apKeys = Object.keys(schema.additionalProperties);\n    if (apKeys.length > 0) {\n      const valueType = schemaToTypeRef(schema.additionalProperties as SchemaObject, 'additionalProperties', name);\n      fields.push({\n        name: 'additionalProperties',\n        type: { kind: 'map', valueType },\n        required: false,\n        description: 'Additional properties not captured by named fields',\n      });\n    }\n  }\n\n  // A named union keeps its variants and discriminator beside the merged\n  // fields, the way the same schema written inline keeps them on its union\n  // TypeRef (`namedUnionEntry`). `fields` is untouched, so a consumer that\n  // does not read `variants` sees the model it always did.\n  // The text, link, flag and extensions are the wrapper layer's: the\n  // component's own, with an annotating `allOf` member's where it declares\n  // none (`allOfWrapperLayer`), as a composed model's are\n  // (`extractAllOfModel`). The one `allOf` a component read here can carry\n  // is one whose members only annotate or limit it, beside a typing union\n  // (`composesComponentModel`; #613): `New: { allOf: [{ description: 'A new\n  // pet.' }], oneOf: [...] }` is described \"A new pet.\" as `{ description:\n  // 'A new pet.', oneOf: [...] }` is, and the members' limits conjoin with\n  // the component's own (`extractConstraints`).\n  const layer = allOfWrapperLayer(schema);\n  return {\n    name,\n    description: layer.description,\n    ...externalDocsEntry(layer.externalDocs),\n    fields,\n    ...deprecatedEntry(layer),\n    ...namedUnionEntry(name, schema, schemas),\n    ...constraintsEntry(schema),\n    ...schemaExtensionsEntry(layer),\n  };\n}\n\n/** One non-null variant of a `oneOf`/`anyOf`, a named union component's or an inline union's alike (see `unionMembers`). */\ninterface UnionMember {\n  /** The variant as written. */\n  raw: SchemaObject;\n  /**\n   * The component schema a `$ref` variant points at (as `extractAllOfModel`\n   * resolves its members), or the one a wrapper variant wraps\n   * (`wrappedVariantReference`); `raw` otherwise. Its consts are read\n   * through its `allOf` members, a `$ref` member or a `$ref` on the\n   * property followed to the component it names\n   * (`getEffectiveConstPropertyValue`).\n   */\n  resolved: SchemaObject;\n  /**\n   * The model name the variant is referenced by: an inline object variant's\n   * extracted model (`nameNamedUnionVariants`, `nameInlineObjectVariants`)\n   * — its title alone before the variants are named — a `$ref` variant's\n   * component, a wrapper variant's one wrapped component (`nullable<Bird>`,\n   * `union<Bird|string>`). `null` for a variant that is none of those (a\n   * primitive, an inline enum, an array, an `allOf` merged into a model of\n   * its own — titled or not, since no model is extracted under such a\n   * variant's title), which a derived discriminator cannot map.\n   */\n  name: string | null;\n}\n\n/**\n * Everything the parser decides about a named union, decided once and read by\n * both the model (`namedUnionEntry`) and the extractor\n * (`extractNamedUnionVariantModels`), so the variant TypeRefs and the models\n * and enums minted for them agree by construction.\n */\ninterface NamedUnionPlan {\n  compositionKind: 'oneOf' | 'anyOf';\n  /** The non-null variants, in document order; `variants[i]` is built from `members[i]`. */\n  members: UnionMember[];\n  /** The inline object variants' model names (`nameNamedUnionVariants`). */\n  inlineNames: ReadonlyMap<SchemaObject, string>;\n  /**\n   * Every other non-`$ref` variant (a primitive, an inline enum, an array, a\n   * map, an `allOf`, a nested union) as a property of one synthetic object:\n   * `variant_<n>` → schema, where n is the variant's 1-based position among\n   * the non-null variants. Both sides type and extract that object as a\n   * field's parent (`schemaToTypeRef` / `extractInlineModelsFromProperties`\n   * under the union's name), so whatever a variant mints — an enum, an\n   * array's inline items, a map's values, a nested union's variants — is\n   * named `<Union>Variant<n>…` by the one rule the field path uses, and two\n   * variants of the same kind can never share a name.\n   */\n  memberProperties: ReadonlyMap<string, SchemaObject>;\n  /** The same, keyed by variant. */\n  memberContexts: ReadonlyMap<SchemaObject, string>;\n  discriminator?: { property: string; mapping: Record<string, string> };\n}\n\n/**\n * True when a component schema is a named union: a `oneOf`/`anyOf` with no\n * `allOf` that types the schema and no `properties` of its own. A `oneOf`\n * beside `properties` is a composed model instead\n * (`composesComponentModel`): the properties are its base and the union is\n * flattened or dispatched after them, as it is beside an `allOf` that\n * types the schema (#429). An `allOf` whose members only annotate or limit\n * the schema (`allOfTypesSchema`: `allOf: [{ description }]`, `allOf: [{\n * minProperties: 1 }]`, `allOf: []`) composes nothing, so a union beside\n * it is a named union, the members part of its wrapper — `New: { allOf:\n * [{ description: 'A new pet.' }], oneOf: [{ $ref: Pet }, { $ref: Toy }]\n * }` is the union of `Pet` and `Toy` that `{ description: 'A new pet.',\n * oneOf: [...] }` is, and that the same schema is inline (#613: it was a\n * composed model, flattened). A component that is only a nullable wrapper\n * around one plain inline object — `oneOf: [{ type: object, … }, { type:\n * 'null' }]` — is not a named union either: its merged fields already are\n * the object (an inline wrapper collapses to `nullable<model>`, not to a\n * union). Nor is a nullable wrapper around one enum declaration — `oneOf:\n * [{ type: 'string', enum }, { type: 'null' }]`, `oneOf: [{ allOf: [{\n * type: 'string', enum }] }, { type: 'null' }]` — which is the enum\n * component itself, nullable (`isEnumComponentSchema`; #606). A wrapper\n * around one `$ref`, one primitive, or one object that also admits\n * another type (`type: ['object', 'string']`) is a union of one: the\n * model has nothing else to say about it, and the other type would be\n * lost.\n */\nfunction isNamedUnionSchema(schema: SchemaObject): boolean {\n  // A composed component is never a named union: one whose `allOf` types it\n  // or sits beside its own properties, and a `$ref` with a union beside it,\n  // which is the alias of its reference (`composesComponentModel`), the\n  // union unread as anything beside a `$ref` is (#618 review): never a named\n  // union minting variants of its own.\n  if (composesComponentModel(schema) || (!schema.oneOf && !schema.anyOf)) return false;\n  if (Object.keys(schema.properties ?? {}).length > 0) return false;\n  // A `oneOf`/`anyOf` of string consts, or a nullable wrapper around one\n  // enum declaration, is an enum (`isEnumComponentSchema`), not a union —\n  // beside an `allOf` that only annotates or limits it too (#613 review).\n  if (isEnumComponentSchema(schema)) return false;\n  const nonNull = (schema.oneOf ?? schema.anyOf ?? []).filter((v) => !isNullSchema(v));\n  return !(nonNull.length === 1 && isPlainObjectSchema(nonNull[0]));\n}\n\n/**\n * An inline object that admits nothing but an object (and null): `type:\n * 'object'`, no `type`, `type: ['object', 'null']`, or OAS 3.0 `nullable:\n * true` on one of those. A type list with another member\n * (`['object', 'string']`) is not plain.\n */\nfunction isPlainObjectSchema(schema: SchemaObject | undefined): boolean {\n  if (!isInlineObjectSchema(schema)) return false;\n  const { type } = schema;\n  return !Array.isArray(type) || type.every((t) => t === 'object' || t === 'null');\n}\n\n/**\n * The plan for a named union component, or null for any other schema (see\n * `NamedUnionPlan`). Planned once per extraction (`activeNamedUnionMemo`):\n * the model and the extractor both read it, and building it reads every\n * component and every other union (`namedUnionClaimedShapes`).\n */\nfunction planNamedUnion(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): NamedUnionPlan | null {\n  const memo = activeNamedUnionMemo?.plans.get(schema);\n  if (memo && memo.name === name && memo.schemas === schemas) return memo.plan;\n  const plan = buildNamedUnionPlan(name, schema, schemas);\n  activeNamedUnionMemo?.plans.set(schema, { name, schemas, plan });\n  return plan;\n}\n\nfunction buildNamedUnionPlan(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): NamedUnionPlan | null {\n  if (!isNamedUnionSchema(schema)) return null;\n  const compositionKind: 'oneOf' | 'anyOf' = schema.oneOf ? 'oneOf' : 'anyOf';\n  const inlineNames = nameNamedUnionVariants(name, schema, schemas);\n  const members = unionMembers(schema, inlineNames, schemas);\n  const memberProperties = new Map<string, SchemaObject>();\n  const memberContexts = new Map<SchemaObject, string>();\n  const claimed = namedUnionClaimedShapes(name, schema, schemas);\n  members.forEach(({ raw }, index) => {\n    if (raw.$ref || inlineNames.has(raw)) return;\n    const key = memberContext(`variant_${index + 1}`, raw, name, claimed);\n    memberProperties.set(key, raw);\n    memberContexts.set(raw, key);\n  });\n  const discriminator = namedUnionDiscriminator(schema, compositionKind, members, schemas);\n  return {\n    compositionKind,\n    members,\n    inlineNames,\n    memberProperties,\n    memberContexts,\n    ...(discriminator ? { discriminator } : {}),\n  };\n}\n\n/**\n * The `variants`, `compositionKind` and `discriminator` of a named union\n * component (`Model.variants`), or nothing for any other schema. Built the\n * way `schemaToTypeRef` builds the same union inline: a `$ref` variant is a\n * model/enum ref; an inline object variant is referenced by the model\n * extracted for it, a nullable or multi-type one keeping its wrapper\n * (`inlineVariantTypeRef`); a `type: 'null'` variant is dropped; and every\n * other variant is typed as the `variant_<n>` property of the plan's\n * synthetic object, under the union's name, exactly as the extractor\n * materializes it. The spec's own `mapping:` substitutes for an inline\n * variant's name exactly as it does inline (`mapVariantToDiscriminatorEntry`)\n * — on the object member only: the items or values of a multi-type variant's\n * other members are named from the model the plan extracts for it\n * (`inlineNames`, the name `extractNamedUnionVariantModels` builds them\n * under), so the reference and the model agree whatever the mapping says.\n * Derived mappings are read from the same names, so they can only point at\n * models that exist.\n */\nfunction namedUnionEntry(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): Pick<Model, 'variants' | 'compositionKind' | 'discriminator'> {\n  const plan = planNamedUnion(name, schema, schemas);\n  if (!plan) return {};\n  const { inlineNames, memberContexts, memberProperties, discriminator } = plan;\n\n  const variants: TypeRef[] = plan.members.map(({ raw }) => {\n    const inlineName = inlineNames.get(raw);\n    if (inlineName !== undefined) {\n      const mappedName = discriminator ? mapVariantToDiscriminatorEntry(raw, discriminator) : null;\n      return inlineVariantTypeRef(raw, inlineName, mappedName ?? inlineName);\n    }\n    if (raw.$ref) return schemaToTypeRef(raw);\n    return schemaToTypeRef(raw, memberContexts.get(raw), name, memberProperties);\n  });\n  // An explicit entry written as a pointer is settled to the model the pointed schema is built as (#539, #619).\n  const written = schema.discriminator?.mapping;\n  if (discriminator && written)\n    deferPointerMappingEntries(written, plan.members, variants, discriminator.mapping, schemas, mappingTargetModelName);\n\n  return { variants, compositionKind: plan.compositionKind, ...(discriminator ? { discriminator } : {}) };\n}\n\n/**\n * The non-null variants of a union — a named union component's, or one\n * written inline as a field's, a body's or an item's — each with the schema\n * its const values and properties are read from (a `$ref` resolved against\n * the components, so a discriminator pinned inside the referenced schema is\n * seen — in its own `properties`, under a `$ref` member of its `allOf`, or\n * as a `$ref` on the property to a const component) and the model name it\n * is referenced by. A variant that wraps one\n * reference to a model (`wrappedVariantReference`) is read as that reference,\n * so its const reaches a derived mapping as a bare `$ref` variant's does (#427).\n * The one reader both derivations share, so a union carries the same\n * mapping inline as it does as a component (#568): `inlineNames` is the\n * name each inline object variant's model takes, as the site decided it\n * (`nameNamedUnionVariants`, `nameInlineObjectVariants`); before the\n * variants are named (`titleMappedVariantNames`) an inline object variant\n * is named by its title alone. A title on any other variant names nothing,\n * since no model is extracted under it.\n */\nfunction unionMembers(\n  schema: SchemaObject,\n  inlineNames: ReadonlyMap<SchemaObject, string>,\n  schemas: Record<string, SchemaObject> | undefined,\n): UnionMember[] {\n  const members: UnionMember[] = [];\n  for (const raw of schema.oneOf ?? schema.anyOf ?? []) {\n    if (isNullSchema(raw)) continue;\n    const named = raw.$ref || inlineNames.has(raw) ? raw : (wrappedVariantReference(raw, schemas) ?? raw);\n    const resolved = named.$ref ? (componentSchemaOf(named.$ref, schemas) ?? raw) : raw;\n    let name = inlineNames.get(raw) ?? null;\n    if (name === null && (named.$ref || isInlineObjectSchema(raw))) name = resolveVariantModelName(named);\n    members.push({ raw, resolved, name });\n  }\n  return members;\n}\n\n/**\n * The one `$ref` to a model a union's variant wraps, named or inline, read\n * through the wrappers the differ reads a variant's models through\n * (`variantModelNames`):\n * a nullable wrapper (`unwrapNullableSchema`: `anyOf: [{ $ref: Bird }, { type:\n * 'null' }]`), an `allOf` read as its reference (`allOfReadAsMember`), and a\n * nested `oneOf`/`anyOf`, whose primitive, enum, array or map members name no\n * model (`oneOf: [{ $ref: Bird }, { type: 'string' }]`) — nor does a `$ref` to\n * an enum component or an alias of one (#560), or to an array or primitive\n * component, which `extractSchemas` builds no model for (`oneOf: [{ $ref:\n * Bird }, { $ref: Song }]`, typed `union<Bird|Song>`).\n * `undefined` when it wraps no reference to a model, two, or one beside a\n * model the extractor names (an inline object, a merged `allOf`): a mapping\n * key read off that one reference would leave the other model out.\n */\nfunction wrappedVariantReference(\n  variant: SchemaObject,\n  schemas: Record<string, SchemaObject> = {},\n): SchemaObject | undefined {\n  const refs: SchemaObject[] = [];\n  const visit = (schema: SchemaObject): boolean => {\n    const bare = unwrapNullableSchema(schema);\n    switch (classifyInlineSchema(bare)) {\n      case 'ref': {\n        // The component itself, not `activeArrayComponentPlans`, which is\n        // empty when `planDispatcherVariants` rehearses (and memoizes) this plan.\n        const target = componentSchemaOf(bare.$ref ?? '', schemas);\n        const modelless =\n          target !== undefined &&\n          (isEnumComponentEntry(target, schemas) ||\n            isArrayComponentEntry(target, schemas) ||\n            isPrimitiveComponentEntry(target, schemas));\n        if (!modelless) refs.push(bare);\n        return true;\n      }\n      case 'allOf': {\n        const member = allOfReadAsMember(bare);\n        return member !== undefined && visit(member);\n      }\n      case 'union':\n        return (bare.oneOf ?? bare.anyOf ?? []).every((member) => isNullSchema(member) || visit(member));\n      case 'object':\n        return false;\n      default:\n        return true;\n    }\n  };\n  return visit(variant) && refs.length === 1 ? refs[0] : undefined;\n}\n\n/**\n * Name the inline object variants of a named union component the way a\n * field's union names its own (`nameInlineVariants`), with the union's model\n * name as the base. The base is taken — the union's own model holds it — so\n * variant 0 steps off it like any later variant (`CatPet`, `PetWithLivesLeft`,\n * `Pet1`), and the names in `namedUnionReservedNames` are stepped around.\n */\nfunction nameNamedUnionVariants(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): Map<SchemaObject, string> {\n  return nameInlineVariants(schema, name, namedUnionReservedNames(name, schema, schemas), true);\n}\n\n/** The IR name of every component schema being extracted, resolved once per extraction. */\nfunction componentModelNames(): ReadonlySet<string> {\n  if (activeNamedUnionMemo?.componentNames) return activeNamedUnionMemo.componentNames;\n  const names = new Set<string>();\n  for (const key of activeComponentSchemaKeys) names.add(resolveSchemaName(key));\n  if (activeNamedUnionMemo) activeNamedUnionMemo.componentNames = names;\n  return names;\n}\n\n/** `schemaShapeKey`, hashed once per extraction for the schemas the named-union plans compare. */\nfunction namedUnionShapeKey(schema: SchemaObject): string {\n  const cached = activeNamedUnionMemo?.shapes.get(schema);\n  if (cached !== undefined) return cached;\n  const key = schemaShapeKey(schema);\n  activeNamedUnionMemo?.shapes.set(schema, key);\n  return key;\n}\n\n/**\n * The names a named union's inline variants must not take: every component\n * schema's name, so a variant titled like a component never shadows it, and\n * every context-free title another named union component keeps for a variant\n * whose shape differs from the one this union gives the same title — the\n * comparison the field path makes between sibling unions\n * (`reservedInlineNames`, `schemaShapeKey`). Each union is read in isolation\n * against the component names alone, so the decision is symmetric: when\n * `Circle` is `{ radius }` on `Shape` and `{ diameter }` on `Marker`, both\n * fall back to their context-qualified names (`CircleShape`, `CircleMarker`)\n * and neither keeps the bare title; when the shapes are identical, both keep\n * `Circle` and one model is emitted. Context-qualified names carry their own\n * union's name and cannot collide across unions.\n */\nfunction namedUnionReservedNames(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): ReadonlySet<string> {\n  const componentNames = componentModelNames();\n  const reserved = new Set(componentNames);\n  if (!schemas) return reserved;\n\n  const ownShapes = new Map<string, string>();\n  for (const [variant, entry] of nameInlineVariantEntries(schema, name, componentNames, true)) {\n    if (entry.contextFree) ownShapes.set(entry.name, namedUnionShapeKey(variant));\n  }\n  for (const { variant, entry } of otherNamedUnionVariantEntries(name, schema, schemas, componentNames)) {\n    if (entry.contextFree && ownShapes.get(entry.name) !== namedUnionShapeKey(variant)) reserved.add(entry.name);\n  }\n  return reserved;\n}\n\n/**\n * The inline object variants of every other named union component, each\n * with the name it would keep, read in isolation against the component names\n * alone (no cross-union reservations), so every union sees the others the\n * same way and no two can chase each other's names. Each union's entries are\n * named once per extraction (`activeNamedUnionMemo`): every other union's\n * plan reads them, twice.\n */\nfunction otherNamedUnionVariantEntries(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  componentNames: ReadonlySet<string>,\n): Array<{ variant: SchemaObject; entry: InlineVariantName }> {\n  const entries: Array<{ variant: SchemaObject; entry: InlineVariantName }> = [];\n  for (const [key, other] of Object.entries(schemas)) {\n    if (other === schema || !isNamedUnionSchema(other)) continue;\n    const otherName = resolveSchemaName(key);\n    if (otherName === name) continue;\n    let otherEntries = activeNamedUnionMemo?.variantEntries.get(other);\n    if (!otherEntries) {\n      otherEntries = nameInlineVariantEntries(other, otherName, componentNames, true);\n      activeNamedUnionMemo?.variantEntries.set(other, otherEntries);\n    }\n    for (const [variant, entry] of otherEntries) entries.push({ variant, entry });\n  }\n  return entries;\n}\n\n/**\n * Every model or enum name already spoken for when a named union's\n * `variant_<n>` members mint theirs, with the shape of each claimant: every\n * component schema (its own shape), and every inline object variant of every\n * other named union (`otherNamedUnionVariantEntries`). A claimant whose\n * shape is unknown (no component map) is recorded as `null`, which never\n * counts as identical.\n */\nfunction namedUnionClaimedShapes(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): Map<string, Array<string | null>> {\n  const claimed = new Map<string, Array<string | null>>();\n  const claim = (claimant: string, shape: string | null): void => {\n    if (claimant === name) return;\n    claimed.set(claimant, [...(claimed.get(claimant) ?? []), shape]);\n  };\n  if (!schemas) {\n    for (const claimant of componentModelNames()) claim(claimant, null);\n    return claimed;\n  }\n  for (const [key, other] of Object.entries(schemas)) claim(resolveSchemaName(key), namedUnionShapeKey(other));\n  for (const { variant, entry } of otherNamedUnionVariantEntries(name, schema, schemas, componentModelNames())) {\n    claim(entry.name, namedUnionShapeKey(variant));\n  }\n  return claimed;\n}\n\n/**\n * The synthetic property name a non-object variant of a named union is typed\n * and extracted under: `base` (`variant_<n>`) unless a name it would mint\n * under it (`mintedInlineNameEntries`: `PetVariant1` for an inline enum, an\n * array's inline items or a map's inline values, a nested union's variants)\n * is already claimed by a component or by another union's variant of a\n * different shape (`claimed`). An identical shape is shared, as array items\n * share a same-shaped sibling's model; otherwise the context steps exactly as\n * an array's or map's does beside a claiming sibling\n * (`firstFreeElementContext`): `variant_1_item` / `variant_1_value`\n * (`PetVariant1Item`, `PetVariant1Value`), then `variant_1_array_item` /\n * `variant_1_member_value`, then numbered — stopping as soon as a candidate\n * mints the same names as the one before it (a context-free name no context\n * can escape) and at the attempt cap. Both sides read the chosen context\n * from the plan, so every name nested under a stepped variant moves with it.\n */\nfunction memberContext(\n  base: string,\n  variant: SchemaObject,\n  unionName: string,\n  claimed: ReadonlyMap<string, ReadonlyArray<string | null>>,\n): string {\n  const mint = (candidate: string): string[] =>\n    mintedInlineNameEntries(candidate, variant, unionName)\n      .filter((entry) => !entry.contextFree)\n      .map((entry) => entry.name);\n  const own = mint(base);\n  if (own.length === 0) return base;\n  const rivals = own.flatMap((minted) => claimed.get(minted) ?? []);\n  if (rivals.length === 0) return base;\n  const shape = namedUnionShapeKey(mintingSchema(variant));\n  if (rivals.every((rival) => rival === shape)) return base;\n  // An array in any spelling (`isArraySchema`: a bare `items`, a nullable\n  // type list) steps with `_item`, as the doc says it does; a map with `_value`.\n  const kind = isArraySchema(variant) ? 'item' : 'value';\n  return firstFreeElementContext(base, kind, new Set(claimed.keys()), mint, own).context;\n}\n\n/**\n * The schema whose shape a non-object variant's minted name stands for: an\n * array's items, a map's values, else the variant itself — read with its\n * nullable wrapper removed, as `elementContextDecision` reads an array's\n * items against a claiming sibling, so a nullable array of the claimant's\n * shape shares the claimant's model instead of stepping around it.\n */\nfunction mintingSchema(variant: SchemaObject): SchemaObject {\n  const bare = unwrapNullableSchema(variant);\n  if (bare.items && isArraySchema(bare)) return mintingSchema(bare.items);\n  if (bare.type === 'object' && !bare.properties) {\n    const value = mapValueSchema(bare);\n    if (value) return mintingSchema(value);\n  }\n  return bare;\n}\n\n/**\n * True for a `components/schemas` entry the parser reads as an array\n * component: a schema `isArraySchema` accepts — `type: 'array'`, an OAS 3.1\n * type list `['array', 'null']`, OAS 3.0 `nullable: true` beside `type:\n * 'array'`, or `items` with no `type` — that declares `items`, read with a\n * nullable `oneOf`/`anyOf` wrapper removed (`unwrapNullableComponent`):\n * `oneOf: [{ type: 'array', items }, { type: 'null' }]` is the nullable\n * array everywhere else, so it is one here (#399). An `enum:` list or a\n * `oneOf`/`anyOf` of other variants beside the array is read first by\n * `classifyInlineSchema`, so such a schema is an enum or a named union here\n * as it is everywhere else. A `type: 'array'` with no `items` is not an\n * array component: `schemaToTypeRef` types it as unknown, with a warning, so\n * it keeps the fieldless model it always became rather than warning at\n * every reference.\n */\nexport function isArrayComponentSchema(schema: SchemaObject): boolean {\n  const bare = unwrapNullableComponent(schema);\n  return isArraySchema(bare) && bare.items !== undefined;\n}\n\n/**\n * True for a `components/schemas` entry the parser reads as a primitive\n * component: a schema `schemaToTypeRef` types from its own keywords alone,\n * with no model, enum, array or map — once a nullable wrapper is removed as\n * it is from an array component (`unwrapNullableComponent`: an OAS 3.1 type\n * list naming `null`, OAS 3.0 `nullable: true`, or a `oneOf`/`anyOf` whose\n * one variant beside a `null` one is such a schema). Four shapes: a\n * primitive — `type: 'string'`, `'integer'`, `'number'` or `'boolean'`, and\n * no keyword beside it that types the schema otherwise\n * (`classifyInlineSchema` reads it as `other`, so an `enum:` list or a\n * composition is read as it is everywhere else); a literal — a `const` of\n * any value, which `classifyInlineSchema` reads before anything but a `$ref`\n * or a composition (`Kind: { type: 'string', const: 'cat' }`); a union of\n * primitives — a type list of several such types, `null` among them or not\n * (`Tag: { type: ['string', 'integer'] }`, `isPrimitiveTypeList`); and\n * `unknown` — a schema that declares no type at all (`declaresNoType`:\n * `Anything: { description: 'Any value.' }`, `{}`, `{ format: 'uuid' }`,\n * and the same written inside an `allOf` whose members each declare none,\n * `Metadata: { allOf: [{ description: 'Free-form metadata.' }] }`, `{\n * allOf: [{}] }`, `{ allOf: [{ description }, { maxLength: 3 }] }`, which\n * `classifyInlineSchema` reads as `other` since no member types it). The\n * last three became fieldless models before #569, while the same schema\n * inline was the literal, the union or `unknown`; so did the lone-`allOf`\n * spelling of an untyped schema until the #569 review, while the lone-`allOf`\n * spelling of a `const`, a type list or a primitive was read through\n * (`componentEntries`). A type list naming `object` or `array`, a `type` no\n * rule knows, `type: 'null'` alone in either spelling, `type: 'array'`\n * without `items`, and an `allOf` of several typing members\n * (`allOfTypesSchema` reads it as none of them) are none of these: each\n * keeps the fieldless model it always became.\n */\nfunction isPrimitiveComponentSchema(schema: SchemaObject): boolean {\n  const bare = unwrapNullableComponent(schema);\n  switch (classifyInlineSchema(bare)) {\n    case 'const':\n      return true;\n    case 'other':\n      return bare.type === undefined ? declaresNoType(bare) : isPrimitiveTypeList(bare.type);\n    default:\n      return false;\n  }\n}\n\n/**\n * Whether a schema declares no type at all, so that `schemaToTypeRef` types\n * it as `unknown` from its own keywords: none of the keywords `declaresType`\n * reads (`{ description: 'Any value.' }`, `{}`), or an `allOf` alone among\n * them whose members each declare none (`{ allOf: [{ description:\n * 'Free-form metadata.' }] }`, `{ allOf: [{}] }`, `{ allOf: [{ description:\n * 'a' }, { maxLength: 3 }] }`; #569 review) — members that only annotate\n * or limit the schema (`annotatingAllOfMembers`), which `allOfTypesSchema`\n * leaves to the schema's own keywords, so `classifyInlineSchema` reads the\n * schema as `other` and `typesAsUnknown` holds. An `allOf` with a member\n * that declares a type is not read here: one typing member is the schema\n * (`readInlineAllOf`), and several are a shape no site reads as unknown\n * on purpose.\n */\nfunction declaresNoType(schema: SchemaObject): boolean {\n  if (!declaresType(schema)) return true;\n  if (schema.allOf === undefined || declaresType({ ...schema, allOf: undefined })) return false;\n  return schema.allOf.every((member) => !declaresType(member));\n}\n\n/**\n * Whether a `type` keyword names nothing but primitives: one primitive\n * (`'string'`), or a list of primitives with or without `null`\n * (`['string', 'integer']`, `['string', 'integer', 'null']`), at least one\n * primitive among them — the lists `schemaToTypeRef` types as a primitive,\n * a union of primitives, or either under `nullable` (#569). A list of\n * `null` alone names no primitive, and a list naming `object` or `array`\n * types a map, a model or an array beside the primitives.\n */\nfunction isPrimitiveTypeList(type: string | string[]): boolean {\n  const types = Array.isArray(type) ? type : [type];\n  const nonNull = types.filter((t) => t !== 'null');\n  return nonNull.length > 0 && nonNull.every((t) => Object.hasOwn(PRIMITIVE_TYPES, t));\n}\n\n/**\n * A component schema with a nullable `oneOf`/`anyOf` wrapper removed, as\n * `schemaToTypeRef` removes it (`unwrapNullableSchema`) — unless the\n * component declares `properties` of its own: those keep the object model a\n * component with `properties` beside a `oneOf`/`anyOf` always is\n * (`isNamedUnionSchema`), and are only folded in (`foldSiblingProperties`).\n */\nfunction unwrapNullableComponent(schema: SchemaObject): SchemaObject {\n  if (Object.keys(schema.properties ?? {}).length > 0) return foldSiblingProperties(schema);\n  return unwrapNullableSchema(schema);\n}\n\n/**\n * Whether a `components/schemas` entry is read as an array component: an\n * array schema itself (`isArrayComponentSchema`), or one `schemaToTypeRef`\n * types as an array through the readings it makes of a nullable wrapper, a\n * `$ref` and an `allOf` — a bare `$ref` to one; a nullable `oneOf`/`anyOf`\n * around one (`unwrapNullableComponent`: `oneOf: [{ $ref: Pets }, { type:\n * 'null' }]`); an `allOf` read as a plain reference (`readInlineAllOf`:\n * `$ref` members with nothing inline beside them — `allOf: [{ $ref: Pets }]`,\n * `allOf: [{ $ref: Pets }, { maxItems: 10 }]`), read as its first `$ref`\n * member; an `allOf` of one member, read as that member\n * (`unwrappedAllOfMember`) — followed through aliases of aliases, so a\n * `$ref` to the alias resolves to the array exactly as the same schema\n * written on a field does (`componentEntries`).\n */\nexport function isArrayComponentEntry(schema: SchemaObject, schemas: Record<string, SchemaObject>): boolean {\n  return componentEntries(schema, schemas, isArrayComponentSchema) !== undefined;\n}\n\n/**\n * Whether a `components/schemas` entry is read as a primitive component: a\n * primitive, `const`, primitive-type-list or typeless schema itself\n * (`isPrimitiveComponentSchema`), or an alias of one, read through the\n * nullable wrappers, `$ref`s and `allOf`s an array component's alias is\n * read through (`componentEntries`).\n */\nfunction isPrimitiveComponentEntry(schema: SchemaObject, schemas: Record<string, SchemaObject>): boolean {\n  return componentEntries(schema, schemas, isPrimitiveComponentSchema) !== undefined;\n}\n\n/**\n * Whether a `components/schemas` entry is read as an enum component: an\n * enum schema itself (`isEnumComponentSchema`), or an alias of one — a bare\n * `$ref` to it, with or without text beside it; a nullable `oneOf`/`anyOf`\n * around that `$ref`; an `allOf` read as the reference, alone or beside\n * members that only annotate or limit it (`allOf: [{ $ref: Kind }, {\n * description }]`); an alias of an alias — read through the nullable\n * wrappers, `$ref`s and `allOf`s an array component's alias is read\n * through (`componentEntries`). An alias becomes no `Model` and no `Enum`\n * of its own: a `$ref` to it is the enum it names (`schemaToTypeRef`),\n * exactly as the same schema written inline is typed (#560: it was an\n * empty model, and the field typed as that model instead of the enum).\n * An alias is only a chain that ends at a `$ref` to an enum component\n * (`isEnumComponentAlias`): a component that declares its enum inside a\n * wrapper `componentEntries` reads through, with no `$ref` — the lone\n * `allOf` member (`Kind: { allOf: [{ type: 'string', enum: ['cat', 'dog']\n * }], description }`, alone or beside annotating members; #588 review),\n * the nullable `oneOf`/`anyOf` around it or around the enum itself (`Kind:\n * { oneOf: [{ allOf: [{ type: 'string', enum }] }, { type: 'null' }] }`;\n * #606) — is the enum component itself (`isEnumComponentSchema`, which\n * reads the member and the branch as the component's own declaration,\n * `enumComponentDeclaration`), so it is true here as any enum component is\n * and is no alias.\n */\nfunction isEnumComponentEntry(schema: SchemaObject, schemas: Record<string, SchemaObject>): boolean {\n  return componentEntries(schema, schemas, isEnumComponentSchema) !== undefined;\n}\n\n/**\n * Whether a `components/schemas` entry is an alias of an enum component:\n * a chain `componentEntries` follows through at least one `$ref` to an\n * enum component — `PetKind: { $ref: Kind }`, `{ allOf: [{ $ref: Kind }, {\n * description }] }`, `{ oneOf: [{ $ref: Kind }, { type: 'null' }] }`, `{\n * oneOf: [{ allOf: [{ $ref: Kind }] }, { type: 'null' }] }`, an alias of an\n * alias — never the enum component itself, which the chain lists alone.\n * An alias is only a chain that ends at a `$ref` to an enum component, so\n * a chain of one entry, which passed none, is never one, whatever the\n * parser reads at its end: an entry that declares its enum inside a\n * wrapper `componentEntries` reads through is the enum component\n * (`isEnumComponentSchema`), and one it does not read as an enum keeps\n * the model it always became. What `extractSchemas` records as the\n * aliases (`activeEnumAliasKeys`). #606: `Kind: { oneOf: [{ allOf: [{\n * type: 'string', enum }] }, { type: 'null' }] }` was recorded as an alias\n * — `isEnumComponentEntry` accepted the chain of one and\n * `isEnumComponentSchema` did not read the wrapper — so its model was\n * skipped and `schemaToTypeRef` lifted the inline enum under no name as\n * `UnknownEnum`, `UnknownEnum2`, the component's name lost; #588 review:\n * the same for the lone `allOf` member.\n */\nfunction isEnumComponentAlias(schema: SchemaObject, schemas: Record<string, SchemaObject>): boolean {\n  const entries = componentEntries(schema, schemas, isEnumComponentSchema);\n  return entries !== undefined && entries.length > 1;\n}\n\n/**\n * The `components/schemas` entries a reference to `schema` reads through to\n * the array, primitive or enum it is — the schema `declares` accepts\n * (`isArrayComponentSchema`, `isPrimitiveComponentSchema`,\n * `isEnumComponentSchema`) — nearest first: `schema` itself, each alias it\n * names in turn, and last the entry that declares it — `[PetsList, Pets]`\n * for `PetsList: { allOf: [{ $ref: Pets }] }` — or `undefined` when `schema`\n * is no such component (see `isArrayComponentEntry`). A field that names one\n * with a bare `$ref` reads what each entry declares beside the array,\n * primitive or `$ref`, since none of them is a model that could carry it\n * (`buildFieldFromSchema`; an enum carries its own).\n * `properties` written beside the composition are folded in first\n * (`unwrapNullableComponent`), as `schemaToTypeRef` folds them. The lone\n * member of an `allOf` is the entry's own declaration, not an entry of its\n * own, and so is the branch of a nullable wrapper: the chain lists\n * `schema` and then one entry per `$ref` followed, so a chain of one entry\n * passed no `$ref` (`isEnumComponentAlias`; #606). A chain that returns to\n * an entry it has visited names no array, primitive or enum: such an entry\n * is left to the model readers, as an alias of an object component is —\n * that one a model carrying the component's fields (`extractModel`,\n * `composesComponentModel`; #618), a chain that repeats a model with none,\n * reported once (`bareRefNamesNothing`).\n */\nfunction componentEntries(\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  declares: (schema: SchemaObject) => boolean,\n  seen: Set<SchemaObject> = new Set(),\n): SchemaObject[] | undefined {\n  if (declares(schema)) return [schema];\n  if (seen.has(schema)) return undefined;\n  seen.add(schema);\n  const bare = unwrapNullableComponent(schema);\n  const aliasOf = (ref: string | undefined): SchemaObject[] | undefined => {\n    const key = ref === undefined ? undefined : componentKeyOf(ref);\n    const aliased = key === undefined ? undefined : schemas[key];\n    const entries = aliased === undefined ? undefined : componentEntries(aliased, schemas, declares, seen);\n    return entries && [schema, ...entries];\n  };\n  if (bare.$ref) return aliasOf(bare.$ref);\n  if (classifyInlineSchema(bare) !== 'allOf' || !bare.allOf) return undefined;\n  const reading = readInlineAllOf(bare.allOf, bare, schemas);\n  if (reading === 'reference') return aliasOf(bare.allOf.find((member) => member.$ref)?.$ref);\n  if (reading !== 'unwrapped') return undefined;\n  const entries = componentEntries(unwrappedAllOfMember(bare), schemas, declares, seen);\n  return entries && [schema, ...entries.slice(1)];\n}\n\n/**\n * The plan for an array component (`ArrayComponentPlan`): the synthetic\n * property its schema is typed and extracted as, under the component's\n * resolved name. The base is `item`, so inline object items are\n * `<Component>Item`, an inline enum `<Component>Item`, the objects of a\n * nested array or map `<Component>Item` as well, and whatever those hold\n * `<Component>Item…`, by the one rule a field's inline models follow. Every\n * name the whole tree mints under a context is read off a rehearsal of the\n * extraction itself (`arrayComponentMints`), so an object nested under the\n * item model (`PetsItemOwner`) or an enum a nested field holds counts\n * exactly as the item model does. When any of them is already claimed for a\n * different shape (`arrayComponentClaims`: any name any extraction pass\n * takes from another entry — its model, enum or array, a discriminated or\n * named-union variant, an object its fields mint, their nested objects and\n * lifted enums — or another array component's tree), the context steps\n * exactly as a named union's `variant_<n>` does\n * (`firstFreeElementContext`): `item_item` (`<Component>ItemItem…`), then\n * `item_array_item`, then numbered, until no name under it is claimed, and\n * every name nested under the tree moves with it. A claimant of the\n * identical shape — the same fields and limits for a model, the same\n * members for an enum — is shared instead, and the tree references it.\n * `own` is the tree's names under `item`; `others` the names every other\n * tree claims — what the plans decided before this one settled on, what the\n * plans after it would mint under `item` — so a stepped tree never lands on\n * a name another tree keeps or steps to, in either direction.\n */\nfunction planArrayComponent(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  own: ArrayComponentMints,\n  others: ReadonlyMap<string, ArrayComponentMints>,\n  minted: ReadonlyMap<string, ReadonlyMap<string, readonly string[]>>,\n): string {\n  const claims = arrayComponentClaims(others, minted);\n  const contested = [...mintedShapes(own)].some(([minted, shape]) =>\n    (claims.get(minted) ?? []).some((rival) => rival !== shape),\n  );\n  if (!contested) return 'item';\n  const names = (mints: ArrayComponentMints): string[] => [...mintedShapes(mints).keys()];\n  return firstFreeElementContext(\n    'item',\n    'item',\n    new Set(claims.keys()),\n    (candidate) => names(arrayComponentMints(name, schema, schemas, candidate)),\n    names(own),\n  ).context;\n}\n\n/** The rounds `extractSchemas` gives the array components' plans to settle; two suffice unless trees chase each other's names. */\nconst MAX_ARRAY_COMPONENT_ROUNDS = 8;\n\n/** The shape key of every name a tree mints: a model's fingerprint, an inline enum's members. */\nfunction mintedShapes(mints: ArrayComponentMints): Map<string, string> {\n  const shapes = new Map<string, string>();\n  for (const model of mints.models) shapes.set(model.name, modelShapeKey(model));\n  for (const [enumName, values] of mints.enums) shapes.set(enumName, enumShapeOf(values));\n  return shapes;\n}\n\n/** The shape a model stands for when a name is contested: its fingerprint, the key every clash check in the parser reads. */\nfunction modelShapeKey(model: Model): string {\n  return `model:${modelFingerprint(model)}`;\n}\n\n/** The shape an enum stands for when a name is contested: its members, each with its deprecation. */\nfunction enumShapeOf(values: readonly EnumValue[]): string {\n  return `enum:${enumShapeKey(values)}`;\n}\n\n/**\n * Every model and inline enum an array component's items would mint under\n * `context`: a rehearsal of both sides — the extractor\n * (`extractInlineModelsFromProperties`) for the models, `schemaToTypeRef`\n * for the inline enums the items are or hold, read off the TypeRef it builds\n * and the fields of the models built — so the names are the ones the real\n * extraction produces, with no second copy of the naming rules to keep in\n * step. The models are built with every array component provisionally\n * registered (`extractSchemas`), so their fingerprints read a `$ref` to one\n * as the array the real pass types; the enums are read with none registered\n * (`withoutArrayComponents`), so an enum another component's items hold is\n * never counted as this tree's own. The rehearsal is silent and leaves no\n * trace (`rehearse`).\n */\nfunction arrayComponentMints(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  context: string,\n): ArrayComponentMints {\n  return rehearse(() => {\n    const extract = (): Model[] => {\n      const models: Model[] = [];\n      extractInlineModelsFromProperties({ properties: { [context]: schema } }, models, name, schemas);\n      return models;\n    };\n    const models = extract();\n    const enums = withoutArrayComponents(() =>\n      liftedEnums([\n        schemaToTypeRef(schema, context, name, new Map([[context, schema]])),\n        ...extract().flatMap((model) => collectModelTypeRefs(model)),\n      ]),\n    );\n    return { models, enums };\n  });\n}\n\n/** Every inline enum `refs` hold — an `EnumRef` carrying `values` — by name, with its members; the first occurrence of a name decides, as the lift does. */\nfunction liftedEnums(refs: readonly TypeRef[]): Map<string, EnumValue[]> {\n  const enums = new Map<string, EnumValue[]>();\n  for (const ref of refs) {\n    walkTypeRef(ref, {\n      enum: (r) => {\n        if (r.values && !enums.has(r.name)) enums.set(r.name, enumValuesOf(r));\n      },\n    });\n  }\n  return enums;\n}\n\n/**\n * The plan of an array component under `context`: what `extractSchemas`\n * registers for a tree while the plans are decided — so a `$ref` to it\n * resolves to its array in every rehearsal, as the real pass types it, under\n * the names the tree carries at that point — and, once a round moves\n * nothing, for good.\n */\nfunction arrayComponentPlan(key: string, schema: SchemaObject, context: string): ArrayComponentPlan {\n  return {\n    key,\n    name: resolveSchemaName(key),\n    schema,\n    context,\n    properties: new Map([[context, schema]]),\n    warnedSelfReference: false,\n  };\n}\n\n/**\n * Run `fn` with no array component registered, so a `$ref` to one is a\n * plain model reference that mints nothing: the way the names a tree mints\n * are read, so another component's items are never counted among them.\n */\nfunction withoutArrayComponents<T>(fn: () => T): T {\n  const plans = activeArrayComponentPlans;\n  activeArrayComponentPlans = new Map();\n  try {\n    return fn();\n  } finally {\n    activeArrayComponentPlans = plans;\n  }\n}\n\n/**\n * Run `fn` as a rehearsal whose output is discarded: `console.warn` is\n * silenced, and the memory of which unions' fold warnings were already\n * reported is set aside and restored, so every warning the schema deserves\n * is printed once, by the extraction that keeps the models.\n */\nexport function rehearse<T>(fn: () => T): T {\n  const warn = console.warn;\n  const reported = reportedUncarriedProperties;\n  console.warn = () => {};\n  reportedUncarriedProperties = new WeakSet();\n  try {\n    return fn();\n  } finally {\n    console.warn = warn;\n    reportedUncarriedProperties = reported;\n  }\n}\n\n/**\n * Every name a `components/schemas` entry takes when it is extracted, each\n * with the shape(s) it stands for, read off a rehearsal of the passes that\n * take them rather than a list of those passes kept in step by hand: the\n * entry's own name — a model's fingerprint (`extractModel`), an enum's\n * members (`extractEnum`), or `'array'` for an array component,\n * `'primitive'` for a primitive one and `'alias'` for an alias of an enum\n * component, shapes no model or enum can share — its\n * discriminated allOf+oneOf variants\n * (`extractDiscriminatedAllOfVariantModels`), its named-union variants and\n * `variant_<n>` members (`extractNamedUnionVariantModels`), the inline\n * models its fields mint (`extractInlineModelsFromSchemas`, the field pass),\n * everything nested under any of those, and every inline enum those\n * models' fields hold — so an array component's plan steps around exactly\n * the names the real passes will take, and an `Event` whose variant pins\n * `type: 'pets_item'` keeps its `PetsItem` while `Pets`'s items step. A name\n * two passes mint for one entry carries both shapes. The models are built\n * with every array component provisionally registered, so a field that is a\n * `$ref` to one is fingerprinted as the array the real pass types; the\n * enums are read with none registered (`withoutArrayComponents`), so an\n * enum another component's items hold is never claimed for this entry. An\n * array component's items are not read here: their names come from its plan\n * (`others`), under the context it settles on. With `dispatcherVariants`\n * false the discriminated variants are left out: the names they are\n * planned around (`planDispatcherVariants`).\n */\nfunction componentMints(\n  key: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  dispatcherVariants = true,\n): ReadonlyMap<string, readonly string[]> {\n  const name = resolveSchemaName(key);\n  return rehearse(() => {\n    const shapes = new Map<string, string[]>();\n    const claim = (minted: string, shape: string): void => {\n      shapes.set(minted, [...(shapes.get(minted) ?? []), shape]);\n    };\n    if (isEnumComponentSchema(schema)) {\n      claim(name, enumShapeOf(extractEnum(name, schema).values));\n      return shapes;\n    }\n    if (isArrayComponentEntry(schema, schemas)) {\n      claim(name, 'array');\n      return shapes;\n    }\n    if (activePrimitiveComponentKeys.has(key)) {\n      claim(name, 'primitive');\n      return shapes;\n    }\n    if (activeEnumAliasKeys.has(key)) {\n      // The alias emits nothing under its name, so no shape can share it (#560).\n      claim(name, 'alias');\n      return shapes;\n    }\n    const extract = (): Model[] => [\n      extractModel(name, schema, schemas),\n      ...(dispatcherVariants ? extractDiscriminatedAllOfVariantModels(schema, name, schemas) : []),\n      ...extractNamedUnionVariantModels(schema, name, schemas),\n      ...extractInlineModelsFromSchemas({ [key]: schema }),\n    ];\n    for (const model of extract()) claim(model.name, modelShapeKey(model));\n    const enums = withoutArrayComponents(() => liftedEnums(extract().flatMap((model) => collectModelTypeRefs(model))));\n    for (const [enumName, values] of enums) claim(enumName, enumShapeOf(values));\n    return shapes;\n  });\n}\n\n/**\n * Every name an array component's item tree must not take for a shape of\n * its own, each with the shape(s) it stands for: every name every other\n * entry takes (`minted`, see `componentMints`) and every model and enum\n * every other array component's tree mints (`others`: settled or isolated,\n * as `planArrayComponent` says). A claimant of the identical shape is\n * shared, so two trees that mint one name for one shape keep it and one\n * model is emitted.\n */\nfunction arrayComponentClaims(\n  others: ReadonlyMap<string, ArrayComponentMints>,\n  minted: ReadonlyMap<string, ReadonlyMap<string, readonly string[]>>,\n): Map<string, string[]> {\n  const claims = new Map<string, string[]>();\n  const claim = (claimant: string, shape: string): void => {\n    claims.set(claimant, [...(claims.get(claimant) ?? []), shape]);\n  };\n  for (const names of minted.values()) {\n    for (const [name, shapes] of names) for (const shape of shapes) claim(name, shape);\n  }\n  for (const mints of others.values()) {\n    for (const [name, shape] of mintedShapes(mints)) claim(name, shape);\n  }\n  return claims;\n}\n\n/**\n * The models an array component's items reference that nothing else\n * materializes — an inline object item, the object variants of an\n * `items.oneOf`, the objects of a nested array or map, an `allOf`, and\n * everything nested under them — extracted by the field extractor from the\n * plan's synthetic property under the component's resolved name, exactly as\n * `arrayComponentTypeRef` types it. Nothing for an alias of another array\n * component, whose `$ref` mints nothing.\n */\nfunction extractArrayComponentModels(key: string, schemas: Record<string, SchemaObject>): Model[] {\n  const plan = activeArrayComponentPlans.get(key);\n  if (!plan) return [];\n  const models: Model[] = [];\n  extractInlineModelsFromProperties({ properties: Object.fromEntries(plan.properties) }, models, plan.name, schemas);\n  return models;\n}\n\n/**\n * The TypeRef a `$ref` to the array component under `key` resolves to: the\n * array the component declares, built by `schemaToTypeRef` from the plan's\n * synthetic property under the component's resolved name — so a nullable\n * type list or OAS 3.0 flag on the component wraps it in `nullable`, an\n * alias (`isArrayComponentEntry`) resolves to the component it names, `$ref`\n * items stay the references they are (to a model, an enum, or another array\n * component, which resolves in turn), and inline items are named\n * `<Component>Item…` as `extractArrayComponentModels` builds them. A fresh\n * TypeRef per reference, since later passes rename references in place. A\n * component reached again while its own reference is being built — `Tree:\n * { type: 'array', items: { $ref: Tree } }`, directly or through another\n * array component or an alias — has no finite type in the IR: that inner\n * reference is typed as unknown, with one warning per component, naming the\n * key as the document writes it. `undefined` for any other key.\n */\nfunction arrayComponentTypeRef(key: string): TypeRef | undefined {\n  const plan = activeArrayComponentPlans.get(key);\n  if (!plan) return undefined;\n  if (resolvingArrayComponents.has(key)) {\n    if (!plan.warnedSelfReference) {\n      plan.warnedSelfReference = true;\n      console.warn(\n        `[oagen] Warning: Array component \"${key}\" refers to itself through its items — the inner reference is typed as unknown`,\n      );\n    }\n    return { kind: 'primitive', type: 'unknown' };\n  }\n  resolvingArrayComponents.add(key);\n  try {\n    return schemaToTypeRef(plan.schema, plan.context, plan.name, plan.properties);\n  } finally {\n    resolvingArrayComponents.delete(key);\n  }\n}\n\n/**\n * Whether `schema` is a `$ref` to an array component — by the key the `$ref`\n * names, as `schemaToTypeRef` resolves it — under any nullable wrapper\n * `unwrapNullableSchema` strips and any `allOf` read as the reference\n * (`allOfReadAsMember`: `allOf: [{ $ref: Pets }]`), so a reader that asks\n * whether a property is an array from the document (`detectListEnvelope`,\n * `buildFieldFromSchema`) answers for a reference as `schemaToTypeRef`\n * types it. False outside an extraction, as a `$ref` to an enum component\n * is a model reference there, and for a `$ref` that names no component — a\n * pointer deeper into one, which `isArrayPointerRef` answers for.\n */\nexport function isArrayComponentRef(schema: SchemaObject | undefined): boolean {\n  if (!schema) return false;\n  const bare = unwrapNullableSchema(schema);\n  if (!bare.$ref) return isArrayComponentRef(allOfReadAsMember(bare));\n  const key = componentKeyOf(bare.$ref);\n  return key !== undefined && activeArrayComponentPlans.has(key);\n}\n\n/**\n * Whether `schema` is a `$ref` that settles to an array (#609): a JSON\n * Pointer deeper into a component (`#/components/schemas/Holder/properties/\n * owners`) — under any nullable wrapper `unwrapNullableSchema` strips and\n * any `allOf` read as the reference (`allOfReadAsMember`), as\n * `isArrayComponentRef` reads a `$ref` to an array component — that lands\n * on a schema typed as an array where it stands: an array in any spelling,\n * a `$ref` to an array component, or another such pointer, under the same\n * wrappers. Read ahead from the document (`pointerTypesAsArray`), as\n * `referenceTypesAsUnknown` reads what a pointer settles to, so a reader\n * that asks whether a property is an array before any model is built\n * (`detectListEnvelope`) answers for a pointer as the settle\n * (`resolveSchemaPointers`) will type it. The pointer is read in `schemas`\n * — the document being read, unless the caller hands over the map it walks\n * (`pointerTypesAsArray`, following a pointer that lands on another). False\n * for a `$ref` that names a component, which `isArrayComponentRef` answers\n * for, for a pointer that leads nowhere or to no array, and outside an\n * extraction, as `isArrayComponentRef` is.\n */\nexport function isArrayPointerRef(\n  schema: SchemaObject | undefined,\n  schemas: Record<string, SchemaObject> | undefined = documentComponentSchemas(),\n): boolean {\n  if (!schema) return false;\n  const bare = unwrapNullableSchema(schema);\n  if (!bare.$ref) return isArrayPointerRef(allOfReadAsMember(bare), schemas);\n  if (componentKeyOf(bare.$ref) !== undefined) return false;\n  return schemas !== undefined && pointerTypesAsArray(String(bare.$ref), schemas);\n}\n\n/**\n * Whether `schema` is a bare `$ref` to a primitive component, by the key the\n * `$ref` names, as `schemaToTypeRef` resolves it. False outside an\n * extraction, as `isArrayComponentRef` is.\n */\nfunction isPrimitiveComponentRef(schema: SchemaObject): boolean {\n  const key = componentKeyOf(schema.$ref);\n  return key !== undefined && activePrimitiveComponentKeys.has(key);\n}\n\n/**\n * Whether `schemaToTypeRef` types `schema` as the bare `unknown` primitive\n * through a `$ref` — decided without typing it, as `typesAsUnknown` decides\n * an inline schema, and for the same reader: the one that must know before\n * a body is typed (`bodyTypesAsUnknown`, choosing the primary response).\n * `typesAsUnknown` holds for no `$ref`, since a `$ref` to a model, enum,\n * named union, array component or primitive component with a type is never\n * unknown; but a `$ref` to a primitive component that declares no type\n * (`Anything: { description: 'Any value.' }`; #569), or to an alias of one,\n * is typed as that schema written inline, so it is `unknown` exactly when\n * the component is — read as the reference is typed: a nullable wrapper on\n * the way makes it `nullable<unknown>`, not bare unknown; an `allOf` read as\n * the reference takes its `$ref` member's answer, one read as its lone\n * typing member that member's; an alias of an alias resolves in turn. So\n * for a `$ref` to a component: whether it names a primitive component (by\n * key, as `schemaToTypeRef` resolves it; false outside an extraction) whose\n * schema answers so here. For a `$ref` that names no component — a pointer\n * deeper into one, or a `$ref` into another section (#539) — the site is\n * settled once every model is built, to the type of the schema the pointer\n * lands on where it stands, or to `unknown` when it leads nowhere; what it\n * settles to is read ahead from the document (`pointerTypesAsUnknown`,\n * false outside an extraction likewise), so a `200` body pointing at an\n * untyped schema (`Pet/properties/anything`, `anything: {}`) loses to a\n * typed `201` as the same schema written inline would, and never selects\n * the operation's primary response only to settle to `unknown`. For any\n * other schema: `typesAsUnknown`, then — for an `allOf` that predicate\n * leaves because the member it is read as is a `$ref` (`readInlineAllOf`)\n * — that member's answer here. A type list is read\n * as `typesAsUnknown` reads it: one naming a single type without\n * `null` is that type, so the `allOf` beside it is still followed (`Alias:\n * { type: ['string'], allOf: [{ $ref: Anything }] }` is the reference, and\n * `unknown`, as `schemaToTypeRef` types it; #569 review: the list stopped\n * the walk, and a `200` naming `Alias` beside a `201` naming `Pet` kept\n * the pick and exposed `unknown`); an empty list or one naming `null`\n * beside a type is `nullable<unknown>` or nullable, never the bare unknown,\n * as `nullable: true` beside a `type` is; one of several types is the\n * union of its per-type copies, each read here in turn, so it is the bare\n * unknown exactly when every copy is (`typeListCopies`; #616).\n */\nexport function referenceTypesAsUnknown(schema: SchemaObject): boolean {\n  if (schema.$ref) {\n    if (componentKeyOf(schema.$ref) === undefined) {\n      const schemas = documentComponentSchemas();\n      return schemas !== undefined && pointerTypesAsUnknown(String(schema.$ref), schemas);\n    }\n    const component = isPrimitiveComponentRef(schema) ? componentSchemaOf(schema.$ref) : undefined;\n    return component !== undefined && referenceTypesAsUnknown(component);\n  }\n  if (typesAsUnknown(schema)) return true;\n  if (Array.isArray(schema.type)) {\n    const nonNullTypes = schema.type.filter((t: string) => t !== 'null');\n    if (nonNullTypes.length === 0 || schema.type.includes('null')) return false;\n    if (nonNullTypes.length > 1) return typeListCopies(schema).every((copy) => referenceTypesAsUnknown(copy));\n  }\n  if (schema.nullable && schema.type) return false;\n  const folded = foldSiblingProperties(schema);\n  if (classifyInlineSchema(folded) !== 'allOf' || !folded.allOf) return false;\n  const reading = readInlineAllOf(folded.allOf, folded);\n  if (reading === 'reference') {\n    const member = folded.allOf.find((candidate) => candidate.$ref);\n    return member !== undefined && referenceTypesAsUnknown(member);\n  }\n  return reading === 'unwrapped' && referenceTypesAsUnknown(allOfTypingMember(folded.allOf) ?? folded.allOf[0]);\n}\n\n/**\n * Whether `schema` is a bare `$ref` to an alias of an enum component\n * (`activeEnumAliasKeys`; #560), by the key the `$ref` names, as\n * `schemaToTypeRef` resolves it. False for a `$ref` to the enum itself,\n * whose `Enum` carries what it declares, and outside an extraction, as\n * `isArrayComponentRef` is.\n */\nfunction isEnumAliasRef(schema: SchemaObject): boolean {\n  const key = componentKeyOf(schema.$ref);\n  return key !== undefined && activeEnumAliasKeys.has(key);\n}\n\n/**\n * The discriminator of a named union, resolved from the same sources\n * `schemaToTypeRef` reads for an inline union, in the same order, from the\n * same members (`unionMembers`: a `$ref` variant's const read from the\n * component it points at), differing only in how the spec's own targets are\n * spelled:\n *   1. An explicit `discriminator:` with a `mapping:` — the spec's own, each\n *      target reduced to the IR model name it refers to (the component the\n *      `$ref` names, or a bare schema name, through `resolveSchemaName`, so\n *      `schemaNameTransform` applies, as it does to every mapping value\n *      `Model.discriminator` carries; `mappingTargetModelName`). An entry\n *      naming a schema outside the variant list is kept as written. An\n *      entry whose target is a pointer deeper into a component is settled\n *      to the model the schema it points at is built as — with the\n *      variant written as that pointer, or on its own\n *      (`deferPointerMappingEntries`; #539, #619).\n *   2. An explicit `discriminator:` without `mapping:` — each variant's const\n *      on the property paired with its model name (`unionConstMapping`); `{}`\n *      when any variant pins none or is unnamed, as it is inline.\n *   3. No keyword, `oneOf` only — the implicit discriminator\n *      (`implicitUnionDiscriminator`), as inline; an `anyOf` is never\n *      discriminated implicitly.\n */\nfunction namedUnionDiscriminator(\n  schema: SchemaObject,\n  compositionKind: 'oneOf' | 'anyOf',\n  members: readonly UnionMember[],\n  schemas: Record<string, SchemaObject> | undefined,\n): { property: string; mapping: Record<string, string> } | undefined {\n  if (schema.discriminator) {\n    const property = schema.discriminator.propertyName;\n    const explicit = Object.entries(schema.discriminator.mapping ?? {});\n    const mapping: Record<string, string> =\n      explicit.length > 0\n        ? Object.fromEntries(explicit.map(([value, target]) => [value, mappingTargetModelName(target)]))\n        : (unionConstMapping(members, property, schemas) ?? {});\n    return { property, mapping };\n  }\n  return compositionKind === 'oneOf' ? implicitUnionDiscriminator(members, schemas) : undefined;\n}\n\n/**\n * The IR model name a named union's explicit mapping target refers to: a\n * `$ref` to a component by the component it names, a bare schema name\n * (`Cat`, which OpenAPI allows in place of the `$ref`) as that name, each\n * through `resolveSchemaName` so `schemaNameTransform` applies. A target\n * that names no component — a `$ref` into another section, or a pointer\n * deeper into a component (#539), which the parser reads as written\n * whether the document or `transformSpec` wrote it (`loadAndBundleSpec`\n * undoes the bundler's rewrite of one) and settles later to the model the\n * pointed schema is built as (`deferPointerMappingEntries`) — is kept as\n * written, as an entry naming a schema outside the variant list is.\n */\nfunction mappingTargetModelName(target: string): string {\n  const key = componentKeyOf(target) ?? (target.startsWith('#') || target.includes('/') ? undefined : target);\n  return key === undefined ? target : resolveSchemaName(key);\n}\n\n/**\n * Defer every entry of a union's explicit `mapping:` whose target stands\n * for a schema that is no component of its own — a pointer deeper into a\n * component (`#/components/schemas/Zoo/properties/dog`; #539 review,\n * #619), or a component that is an alias of one (`Hound: { $ref:\n * '#/components/schemas/Shelter/properties/dog' }`; #619 review) — to the\n * settle of the reference it follows (`deferMappingEntry`), for a named\n * union, an inline one and an allOf+oneOf dispatcher alike. Such a target\n * names no model by its key — the bundler rewrites one to a component it\n * hoists the schema into, and the rewrite is undone before the parser\n * reads the document (`loadAndBundleSpec`), so the target reaches here as\n * written, as one `transformSpec` writes does — and the model it names is\n * the one the schema it stands for is built as, which no reader knows\n * until every model is. Each target is read through its alias chain\n * (`aliasChainOf`) and every hop matched by identity against the members'\n * schemas, read through their own aliases (`schemasAlong`), the nearest hop\n * first and, at a hop, the member reached through the fewest aliases of\n * its own, so `dog: Hound` beside `$ref: Mutt` and `$ref: Hound`, with\n * `Mutt` an alias of `Hound`, is `Hound` in either order: a hop that is\n * a pointer variant's — an unnamed member, pending until settled — follows\n * the variant, to the model it settles to (`ZooDog`; `ShelterDog` for\n * `dog: Hound` beside the variant `Shelter/properties/dog`, as the pointer\n * spelling gives), or, where the site holds no variants (a dispatcher), a\n * pending reference of that pointer's own, settled at the mapping site; a\n * hop that is a named member's names that member's model now, spelled as\n * the site spells the member's own `$ref` (`memberSpelling`: `Hound` when\n * `$ref: Hound` is the variant, for the target `Hound` and for the pointer\n * `Shelter/properties/dog` it aliases alike; `Cat` for an alias of `Cat`\n * beside `$ref: Cat`); a chain no member holds ends at a pointer,\n * followed by a pending reference of the target's own (`pendingSchemaRef`),\n * settled at the mapping site to the model the pointed schema is built as\n * (`ShelterDog`), or left as written after a warning when it names no\n * model (`settleDeferredMappingEntries`), or at a component, which names\n * the entry now (`Wolf` for `Hound: { $ref: Wolf }`, as the bundler's\n * rewrite made it before). A target that names a component of its own is\n * read by key (`mappingTargetModelName`, `inlineMappingTargets`) and never\n * deferred. An inline object variant pinning the entry's value was\n * redirected to the entry's target as the IR spells it\n * (`mapVariantToDiscriminatorEntry`, `inlineVariantTypeRef`), as a\n * component target redirects it to the component's model; a pointer so\n * spelled names no model, so the redirected reference is made the\n * pointer's own — named by the `$ref` as written and marked pending — and\n * settled by the walk as a pointer variant's is, to the model the pointed\n * schema is built as, the entry following it (#619 review: the reference\n * kept the pointer for a name no model has) — whether or not the target\n * is a pointer variant's schema as well, since the entry's value may be\n * pinned by an inline variant beside that pointer variant; one redirected\n * to a named member's model, or to the component a chain ends at, is named\n * so now. `written` is the document's mapping, `mapping` the one the IR\n * carries, `spell` how the site writes a `$ref` target into it (an IR\n * model name for a named union or a dispatcher, the stripped spelling for\n * an inline union); `variants[i]` is built from `members[i]`, and a\n * dispatcher, which holds no variants, passes none.\n */\nfunction deferPointerMappingEntries(\n  written: Record<string, unknown>,\n  members: readonly UnionMember[],\n  variants: readonly TypeRef[],\n  mapping: Record<string, string>,\n  schemas: Record<string, SchemaObject> | undefined,\n  spell: (target: string) => string,\n): void {\n  const memberSchemas = members.map((member) => schemasAlong(member.resolved, schemas));\n  for (const [value, target] of Object.entries(written)) {\n    if (typeof target !== 'string' || schemaRefTokens(target) === undefined) continue;\n    const chain = aliasChainOf(target, schemas);\n    const last = chain[chain.length - 1]!;\n    const endsAtPointer = (schemaRefTokens(last.ref)?.length ?? 0) > 1;\n    if (chain.length === 1 && !endsAtPointer) continue;\n    const redirected = redirectedVariantRefs(variants, mapping[value]);\n    /** Make every redirected reference the pointer `ref`'s own, settled by the walk. */\n    const redirectToPointer = (ref: string): void => {\n      for (const redirect of redirected) {\n        redirect.name = ref;\n        markPendingSchemaRef(redirect);\n      }\n    };\n    /** Name the entry, and every redirected reference, `name` now. */\n    const nameNow = (name: string): void => {\n      for (const redirect of redirected) redirect.name = name;\n      if (Object.hasOwn(mapping, value)) mapping[value] = name;\n    };\n    // The nearest hop of the chain that is a member's schema names that\n    // member's model — the member reached through the fewest aliases of its\n    // own first (its own schema, then one alias away, …), so an entry naming\n    // a variant outright is that variant's whatever is declared around it\n    // (Greptile, #619 review round 7: with `$ref: Mutt` declared before\n    // `$ref: Hound` and `Mutt` an alias of `Hound`, `dog: Hound` went to\n    // `Mutt`), and never the order the variants are declared in.\n    let hop = -1;\n    let index = -1;\n    const deepest = Math.max(0, ...memberSchemas.map((along) => along.length));\n    outer: for (let at = 0; at < chain.length; at++) {\n      const schema = chain[at]!.schema;\n      if (schema === undefined) continue;\n      for (let depth = 0; depth < deepest; depth++) {\n        for (let position = 0; position < members.length; position++) {\n          if (memberSchemas[position]![depth] === schema) {\n            hop = at;\n            index = position;\n            break outer;\n          }\n        }\n      }\n    }\n    if (index >= 0) {\n      const member = members[index]!;\n      const variant = variants[index];\n      if (member.name === null) {\n        // An unnamed member is a pointer's: the entry follows the pending\n        // variant built for it, or, where the site holds no variants (a\n        // dispatcher), a pending reference of that pointer's own (Greptile,\n        // #619 review round 5: the hop was written as a name instead).\n        redirectToPointer(chain[hop]!.ref);\n        deferMappingEntry(\n          mapping,\n          value,\n          variant !== undefined && isPendingVariant(variant)\n            ? variant\n            : (redirected[0] ?? pendingSchemaRef(chain[hop]!.ref)),\n        );\n      } else {\n        // A named member: the entry names its model, spelled as the site\n        // spells the member's own `$ref` — never the hop's, which may be a\n        // pointer the member aliases (`$ref: Hound` for `Shelter/properties/dog`).\n        nameNow(memberSpelling(member, member.name, schemas, spell));\n      }\n      continue;\n    }\n    if (endsAtPointer) {\n      redirectToPointer(last.ref);\n      deferMappingEntry(mapping, value, redirected[0] ?? pendingSchemaRef(last.ref));\n      continue;\n    }\n    nameNow(spell(last.ref));\n  }\n}\n\n/**\n * `deferPointerMappingEntries` for a site that builds an inline union's\n * variants itself instead of through `schemaToTypeRef` — a request body\n * written as a `oneOf` (`typePickedRequestBody`) — so the body's union\n * settles a pointer entry exactly as a field's or a response's does:\n * `dog: '#/components/schemas/Zoo/properties/dog'` beside the variant\n * written as that pointer is `ZooDog`, the model the variant settles to,\n * at all three sites (Greptile, #660 review: the body's variant settled\n * to `ZooDog` while its entry stayed `Zoo/properties/dog`, a name no model\n * has). `schema` is the union as written, `inlineNames` the name each\n * inline object variant's model takes at the site, `variants` the\n * references built for its non-null variants, in order, and `mapping` the\n * object the union's discriminator carries (`inlineMappingTargets`), which\n * the settle writes into.\n */\nexport function deferInlineUnionMappingEntries(\n  schema: SchemaObject,\n  inlineNames: ReadonlyMap<SchemaObject, string>,\n  variants: readonly TypeRef[],\n  mapping: Record<string, string>,\n): void {\n  const written = schema.discriminator?.mapping;\n  if (!written) return;\n  const schemas = documentComponentSchemas();\n  deferPointerMappingEntries(\n    written,\n    unionMembers(schema, inlineNames, schemas),\n    variants,\n    mapping,\n    schemas,\n    inlineMappingTarget,\n  );\n}\n\n/**\n * How `spell` writes a named member's model into the mapping: as the\n * member's own `$ref` to a component — written on the member, or wrapped\n * by it (`wrappedVariantReference`) — else as `name`, the model name it\n * carries (an inline variant's, or a title's).\n */\nfunction memberSpelling(\n  member: UnionMember,\n  name: string,\n  schemas: Record<string, SchemaObject> | undefined,\n  spell: (target: string) => string,\n): string {\n  const ref = member.raw.$ref ?? wrappedVariantReference(member.raw, schemas)?.$ref;\n  return typeof ref === 'string' && componentKeyOf(ref) !== undefined ? spell(ref) : name;\n}\n\n/**\n * The `$ref`s a schema `$ref` stands for, from the `$ref` itself through\n * every bare `$ref` it lands on — a component that is an alias (`Hound: {\n * $ref: … }`), or a pointer landing on a `$ref` schema — each with the\n * schema it names (`schemaRefTarget`), `undefined` for one that names none,\n * which ends the chain, as does a `$ref` into another section, which the\n * parser does not follow, and a `$ref` met again. What is written beside\n * a `$ref` is not read, as beside any `$ref` (#618).\n */\nfunction aliasChainOf(\n  ref: string,\n  schemas: Record<string, SchemaObject> | undefined,\n): Array<{ ref: string; schema: SchemaObject | undefined }> {\n  const chain: Array<{ ref: string; schema: SchemaObject | undefined }> = [];\n  const seen = new Set<string>();\n  let current: string | undefined = ref;\n  while (current !== undefined && !seen.has(current)) {\n    seen.add(current);\n    const schema = schemaRefTarget(current, schemas);\n    chain.push({ ref: current, schema });\n    const next = schema?.$ref;\n    current = typeof next === 'string' && schemaRefTokens(next) !== undefined ? next : undefined;\n  }\n  return chain;\n}\n\n/** `schema` and every schema its `$ref` chain lands on (`aliasChainOf`, from a schema rather than a `$ref`): a member's, so a target is matched against the member through the member's own aliases. */\nfunction schemasAlong(schema: SchemaObject, schemas: Record<string, SchemaObject> | undefined): SchemaObject[] {\n  const along = [schema];\n  if (typeof schema.$ref === 'string') {\n    for (const hop of aliasChainOf(schema.$ref, schemas)) if (hop.schema !== undefined) along.push(hop.schema);\n  }\n  return along;\n}\n\n/**\n * The model references `inlineVariantTypeRef` built for an inline object\n * variant redirected to a mapping entry's target — a name other than the\n * variant's own model's — by identity, so a pointer entry finds the\n * references it redirected and no other: a reference an array variant's\n * items or a map variant's values make to a component of the same name is\n * the document's own and stays (Greptile, #619 review round 6: it was\n * found by name and sent to the pointer too).\n */\nconst redirectedVariantModelRefs = new WeakSet<ModelRef>();\n\n/**\n * The references among `variants` an inline object variant was redirected\n * to under `name` — a mapping entry's target as the IR spells it, which for\n * a pointer names no model — the variant itself, or the object member of a\n * multi-type variant's union, each one `inlineVariantTypeRef` built for the\n * redirect (`redirectedVariantModelRefs`); none when `name` is no entry's\n * spelling. A reference already pending is a pointer's own and is passed\n * over.\n */\nfunction redirectedVariantRefs(variants: readonly TypeRef[], name: string | undefined): ModelRef[] {\n  const refs: ModelRef[] = [];\n  if (name === undefined) return refs;\n  for (const variant of variants) {\n    walkTypeRef(variant, {\n      model: (ref) => {\n        if (ref.name === name && redirectedVariantModelRefs.has(ref) && !isPendingSchemaRef(ref)) refs.push(ref);\n      },\n    });\n  }\n  return refs;\n}\n\n/**\n * The implicit discriminator of a `oneOf` with no `discriminator:` keyword,\n * named or inline: when every member is named — an inline object by its\n * model or its title, a `$ref` by its component, a wrapper by the one model\n * it wraps (`unionMembers`) — the first property the first member pins whose\n * values are distinct across all of them, with that mapping\n * (`unionConstMapping`). A constant every variant shares (`version: 'v1'`)\n * is passed over, not taken as proof there is no discriminator; an unnamed\n * variant is no signal, nor is a union of one variant; and the OpenAPI\n * default of \"the discriminator value is the schema name\" is not synthesized.\n */\nfunction implicitUnionDiscriminator(\n  members: readonly UnionMember[],\n  schemas: Record<string, SchemaObject> | undefined,\n): { property: string; mapping: Record<string, string> } | undefined {\n  if (members.length < 2 || members.some((m) => m.name === null)) return undefined;\n  const first = members[0];\n  if (!first) return undefined;\n  for (const property of Object.keys(getEffectiveProperties(first.resolved, schemas))) {\n    const mapping = unionConstMapping(members, property, schemas);\n    if (mapping) return { property, mapping };\n  }\n  return undefined;\n}\n\n/**\n * `property`'s const value on every member paired with the member's model\n * name, or null when any member is unnamed, pins no string const on the\n * property (through its `allOf` wrappers, a `$ref` member or a `$ref` on\n * the property followed to the component it names —\n * `getEffectiveConstPropertyValue`; #568 review), or repeats another\n * member's value. Collected in a Map, so a value spelled like\n * an inherited property (`constructor`, `toString`) is neither mistaken for a\n * duplicate nor lost; the result has every value as an own key.\n */\nfunction unionConstMapping(\n  members: readonly UnionMember[],\n  property: string,\n  schemas: Record<string, SchemaObject> | undefined,\n): Record<string, string> | null {\n  if (members.length === 0) return null;\n  const mapping = new Map<string, string>();\n  for (const member of members) {\n    if (member.name === null) return null;\n    const value = getEffectiveConstPropertyValue(member.resolved, property, schemas);\n    if (value === null || mapping.has(value)) return null;\n    mapping.set(value, member.name);\n  }\n  return Object.fromEntries(mapping);\n}\n\n/**\n * The models a named union component's variants reference that nothing else\n * materializes, extracted by the field extractor so every object shape\n * `schemaToTypeRef` references — a nested object with or without `type`, an\n * array's or map's inline items, an `allOf`, a nested union — is\n * materialized under the name the reference uses: each inline object variant\n * under the name `nameNamedUnionVariants` gave it, with everything nested\n * under it and, for a multi-type variant, the members of its other types,\n * exactly as the extractor's own union branch does; and the plan's synthetic\n * object of every other variant (`variant_<n>`), extracted under the union's\n * name as the TypeRefs were typed. Nothing for a schema that is not a named\n * union.\n */\nfunction extractNamedUnionVariantModels(\n  schema: SchemaObject,\n  name: string,\n  schemas?: Record<string, SchemaObject>,\n): Model[] {\n  const plan = planNamedUnion(name, schema, schemas);\n  if (!plan) return [];\n  const models: Model[] = [];\n  for (const [variant, variantName] of plan.inlineNames) {\n    models.push(buildInlineModel(variantName, variant, schemas));\n    extractInlineModelsFromProperties(variant, models, variantName, schemas);\n    extractInlineModelsFromProperties(\n      { properties: variantMemberSchemas(variant, variantName) },\n      models,\n      variantName,\n      schemas,\n    );\n  }\n  if (plan.memberProperties.size > 0) {\n    extractInlineModelsFromProperties({ properties: Object.fromEntries(plan.memberProperties) }, models, name, schemas);\n  }\n  return models;\n}\n\n/** A dispatcher's discriminator: the property every variant pins, and the model each value selects. */\ntype AllOfDiscriminator = { property: string; mapping: Record<string, string> };\n\n/** The `discriminator` keyword as the document writes it, on a union's carrier or on the `allOf` wrapper around it. */\ntype DiscriminatorKeyword = NonNullable<SchemaObject['discriminator']>;\n\n/**\n * The variants of the union a schema carries — `oneOf`, else `anyOf` — or\n * `undefined` for a schema carrying none: the one axis a pure union\n * component is flattened by (`componentPropertyLedger`). A schema that\n * composes with `allOf` reads every union it carries (`unionAxesOf`).\n */\nexport function unionVariantsOf(schema: SchemaObject): SchemaObject[] | undefined {\n  return schema.oneOf ?? schema.anyOf;\n}\n\n/**\n * Every union a schema carries, `oneOf` then `anyOf`, each as the variant\n * list the document wrote — or none. JSON Schema applies both keywords, so\n * a member written `{ oneOf: [...], anyOf: [...] }` is one of the first and\n * any of the second: each list is one variant axis, dispatched or flattened\n * on its own (#398: only the `oneOf` was read, and the `anyOf`'s properties\n * were lost without a word). The one keyword test every reader of a\n * composed schema's unions applies — the member reader that detects a\n * dispatcher or flattens the variants (`readComponentAllOfMember`), the\n * variant builder (`extractDiscriminatedAllOfVariantModels`, its axis and\n * its variant loop), the inline merge and the branch reader it shares with\n * the member reader (`mergeAllOfMembers`, `declareVariant`) and a\n * dispatched variant's nested unions (`flattenVariantForExtraction`) — so a\n * union detected as a dispatcher is the union whose variant models are\n * built, whichever keyword spells it (workos/oagen#359 review: an `anyOf`\n * axis was dispatched but its variants were not built, and the mapping\n * named a model nothing created).\n */\nexport function unionAxesOf(schema: SchemaObject): SchemaObject[][] {\n  const axes: SchemaObject[][] = [];\n  if (schema.oneOf) axes.push(schema.oneOf);\n  if (schema.anyOf) axes.push(schema.anyOf);\n  return axes;\n}\n\n/**\n * What one reading of a composed component collects (`readComponentAllOf`,\n * `readComponentAllOfMember`): every declaration with its provenance\n * (`declareProperty`), the names every always-applying member requires, and\n * the schemas read so far as always-applying (`seen`: a component met\n * again on the chain declares nothing more). A variant is read as a\n * conjunction of its own, with a guard of its own (`declareVariant`), so\n * a component two variants name declares into each.\n */\ninterface ComponentReading {\n  ledger: Map<string, PropertyDeclarations>;\n  required: Set<string>;\n  /**\n   * Who requires each name in `required`: the origin of every\n   * always-applying `required` list that names it — a base, by name, or\n   * `null` for the component's own list and an inline member's — read\n   * beside a declaration's origin to tell a field left as its base\n   * declares it (`Field.inheritedFrom`) from one the model requires on its\n   * own (`inheritedBase`; #591).\n   */\n  requiredBy: Map<string, Set<string | null>>;\n  /**\n   * The bases the reading lands on (`Model.bases`): one `model` reference\n   * per component a `$ref` member's declarations are recorded under\n   * (`noteBase`), each once, in the order first met.\n   */\n  bases: ModelRef[];\n  /** The schema the reading started on (the component's own), so a member that reaches it again — the component naming itself, or an alias of it — is told from one naming another component already read (`followMemberRefChain`). */\n  root?: SchemaObject;\n  seen: Set<SchemaObject>;\n}\n\n/** A fresh `ComponentReading`, into `ledger` when given. */\nfunction newComponentReading(ledger = new Map<string, PropertyDeclarations>()): ComponentReading {\n  return { ledger, required: new Set(), requiredBy: new Map(), bases: [], seen: new Set() };\n}\n\n/**\n * The component a declaration is recorded under — the `{ name, schema }`\n * `declareProperty` keeps as a declaration's origin, with the\n * `components/schemas` key it was reached by, which `componentTypeRef`\n * resolves (`noteBase`). `schema` is the component's own — a bare alias's\n * `{ $ref }` when the member names one — whose own keywords keep the\n * origin through everything read inside it (`memberOrigin`), as the inline\n * merge keeps an origin whose schema writes an `allOf` or a `$ref`.\n */\ninterface ComponentOrigin {\n  key: string;\n  name: string;\n  schema: SchemaObject;\n}\n\n/**\n * How a member is read: the one variant axis not to read (the dispatcher\n * base reads its axis for its own properties only), the `discriminator`\n * written for a union among the members outside the member that carries it\n * — on the `allOf` wrapper, or on a nullable wrapper around the union —\n * and the component whose own chain the member is read inside (`origin`:\n * a `$ref` member's component, handed down to that component's members\n * and nullable branches), under which its declarations are recorded\n * (`memberOrigin`); absent at the top level, where a `$ref` member's\n * declarations are its own component's and an inline member's are the\n * model's own.\n */\ninterface MemberReadingOptions {\n  skipAxis?: readonly SchemaObject[];\n  wrapperDiscriminator?: DiscriminatorKeyword;\n  origin?: ComponentOrigin;\n}\n\n/**\n * The component a member's declarations are recorded under — the origin\n * `declareProperty` keeps per declaration, decided as the inline merge\n * decides it (`mergeAllOfMembers`; #591): the first component a `$ref`\n * member's chain resolves through (`landing.key`) — a bare alias (`Hop: {\n * $ref: Animal }`) is a model of its own, read as `allOf: [{ $ref: Animal\n * }]` (#618), so it is the origin and `Animal` is its own base in turn;\n * the enclosing base (`enclosing`) for a member of a base's own `allOf`\n * chain — the base's model carries everything reached inside it, a `$ref`\n * member of its included, so `Living`'s `born` under `Animal: { allOf: [{\n * $ref: Living }] }` is `Animal`'s — and for an inline member or branch\n * read inside any base, a bare alias of a nullable wrapper included\n * (`Hop: { $ref: Alias }`: what `Alias`'s one variant names is `Hop`'s,\n * as the inline merge keeps an origin whose schema writes a `$ref`;\n * Greptile on #591); a nullable alias (`Alias: { oneOf: [{ $ref: Animal\n * }, { type: 'null' }] }`) is no `allOf` component and declares nothing\n * of its own, so the `$ref` its branch names starts an origin of its own.\n * `null` for an inline member at the top level: the model's own.\n */\nfunction memberOrigin(landing: MemberLanding, enclosing: ComponentOrigin | undefined): ComponentOrigin | null {\n  if (enclosing && (enclosing.schema.allOf || enclosing.schema.$ref !== undefined)) return enclosing;\n  if (landing.key !== undefined && landing.named) {\n    return { key: landing.key, name: resolveSchemaName(landing.key), schema: landing.named };\n  }\n  return enclosing ?? null;\n}\n\n/**\n * Record `origin` among the reading's bases (`Model.bases`), once, when it\n * is a model component: a `$ref` to it is typed as a model\n * (`componentTypeRef`, read through the nullability a component carries),\n * not as an enum, an array or a primitive, which build no model and\n * contribute nothing to the fields. Called where a `$ref` member lands on\n * a component that is more than a nullable wrapper\n * (`declaresOnlyNullable`), so a base that declares nothing is still\n * named, and wherever a declaration or a `required` name is recorded under\n * an origin (`declareUnder`, `noteRequired`), so the origin every\n * `inheritedFrom` names is a base.\n */\nfunction noteBase(reading: ComponentReading, origin: ComponentOrigin): void {\n  if (reading.bases.some((base) => base.name === origin.name)) return;\n  const ref = componentTypeRef(origin.key);\n  const inner = ref.kind === 'nullable' ? ref.inner : ref;\n  if (inner.kind === 'model') reading.bases.push(inner);\n}\n\n/** Record `name` as required by `origin`'s list (`required`, `requiredBy`), the base noted (`noteBase`). */\nfunction noteRequired(reading: ComponentReading, name: string, origin: ComponentOrigin | null): void {\n  reading.required.add(name);\n  let by = reading.requiredBy.get(name);\n  if (!by) reading.requiredBy.set(name, (by = new Set()));\n  by.add(origin?.name ?? null);\n  if (origin) noteBase(reading, origin);\n}\n\n/** Declare `name` as always-applying under `origin` (`declareProperty`), the base noted (`noteBase`). */\nfunction declareUnder(\n  reading: ComponentReading,\n  name: string,\n  schema: SchemaObject,\n  origin: ComponentOrigin | null,\n): void {\n  declareProperty(reading.ledger, name, schema, origin, false);\n  if (origin) noteBase(reading, origin);\n}\n\n/**\n * Whether a schema is only a nullable wrapper — every union it writes a\n * `null` variant beside one other (`nullableAxisBranch`), with no `allOf`,\n * no property and no `required` of its own — which declares nothing\n * itself: its one variant is read in its place (`readComponentAllOfMember`)\n * and names the base when it is a `$ref` (`memberOrigin`), so the wrapper\n * is not noted as one on landing (`noteBase`).\n */\nfunction declaresOnlyNullable(schema: SchemaObject): boolean {\n  if (schema.allOf || hasFoldableProperties(schema) || (schema.required?.length ?? 0) > 0) return false;\n  const axes = unionAxesOf(schema);\n  return axes.length > 0 && axes.every((variants) => nullableAxisBranch(schema, variants) !== undefined);\n}\n\n/**\n * The base an entry's field is taken from unchanged (`Field.inheritedFrom`),\n * or none: the origin of the always-applying declaration the entry settled\n * on — a declaration of the model's own that changes it, before or after\n * the base's, makes the entry the model's own (`declareProperty`) — when it\n * is among the model's bases and the model requires the field only as that\n * base does (`requiredBy`): a field the model requires on its own, which\n * the base leaves optional, is changed.\n */\nfunction inheritedBase(entry: PropertyDeclarations, reading: ComponentReading): ModelRef | undefined {\n  const origin = entry.unconditional?.origin;\n  if (!origin || !reading.bases.some((base) => base.name === origin.name)) return undefined;\n  if (reading.required.has(entry.name) && !reading.requiredBy.get(entry.name)?.has(origin.name)) return undefined;\n  return inheritedRef(origin.name);\n}\n\n/** A `model` reference to the base `name`, marked as a component's (`markComponentModelRef`) so a pass that renames inline models leaves it as written. */\nfunction inheritedRef(name: string): ModelRef {\n  const ref: ModelRef = { kind: 'model', name };\n  markComponentModelRef(ref);\n  return ref;\n}\n\n/**\n * Read one member of a component's `allOf` into `reading`, each\n * declaration with its provenance (`declareProperty`): the component the\n * member's chain lands on for a `$ref` member, the base for a member read\n * inside a base's own chain, the model's own for an inline member\n * (`memberOrigin`, `options.origin`; #591) — the components landed on\n * noted as the model's bases (`noteBase`) and each `required` name by the\n * origin that lists it (`noteRequired`), so `extractAllOfModel` can tell\n * a field taken from a base unchanged. A `$ref` member is\n * resolved to its component, through a chain of references; a component\n * met again on the chain declares nothing more. An `allOf` member — a\n * component composed with `allOf`, or an inline wrapper — is read by\n * `readComponentAllOf`, so a declaration it makes under a `oneOf`/`anyOf`\n * variant stays branch-only however deep it sits; its own discriminator,\n * if any, is its own model's and is not returned (the model reading it\n * carries the base fields only, as the inline merge of a reference to it\n * does). Every member contributes its own `properties` as always-applying\n * and its own `required` — beside a `oneOf`/`anyOf` too, an inline\n * member's or those of the component a `$ref` member names (`Pet: {\n * properties: { id }, oneOf: [...] }`, whose union is then this model's to\n * dispatch or flatten, as it is `Pet`'s own; #429). A\n * member's `oneOf`/`anyOf` with exactly one non-null variant beside `null`\n * is a nullable wrapper, not a union — decided per keyword by\n * `nullableAxisBranch`, `nullableUnionBranch`'s definition, the one\n * `unwrapNullableSchema` collapses by, which `mergeAllOfMembers` reads an\n * inline member through and the envelope collector reads every member\n * through (`resolveBareSchema`) — and that variant is read as one more\n * member, in this member's own capacity: `{ oneOf: [{ $ref: Base }, {\n * type: 'null' }] }` applies `Base` whole, its `$ref` followed and its\n * `required` read, since an instance that is not null is a `Base` and\n * beside an object member it is never null (workos/oagen#308: read as a\n * union, `Base`'s `has_more` ended the operation's iteration but was\n * missing from the model); the wrapper itself is recorded as read, so a\n * component that wraps a reference to itself ends there. A member writing\n * a nullable `oneOf` beside an `anyOf` has the `anyOf` read as below, as\n * two members would be (#398 review: the wrapper was decided on the\n * member, which reads one keyword, and the `anyOf` was lost). Each union\n * the member carries (`unionAxesOf`: a `oneOf` and an `anyOf` written\n * together are two) is a dispatcher when its variants pin one property to distinct\n * consts, or the document declares a `discriminator` for it — on the\n * member, on a nullable wrapper the member writes around the union (handed\n * down with the wrapper's one variant), or on the wrapper whose `allOf` the\n * member sits in\n * (`wrapperDiscriminator`; `detectAllOfVariantDiscriminator`, which reads a\n * `$ref` variant's const from its component): its variants' properties are\n * not read, and the discriminator is returned (the first, when two axes\n * dispatch); otherwise every variant is flattened in as branch-only\n * declarations — its properties, those of its `allOf` wrappers and of the\n * unions nested in them, and those of the component a `$ref` variant names\n * (`declareVariant`, the one branch reader the inline merge flattens a\n * variant with, so the two read a variant alike; #398: a `$ref` variant and\n * a nested union's variants declared nothing here) — and a variant's\n * `required` is not read, since its properties are present only on that\n * branch. With `skipAxis` the dispatcher base reads the variant axis for\n * its own properties only, while a nullable wrapper, never a variant axis,\n * and any other union the member carries are still read. Shared by\n * `extractAllOfModel` and the dispatcher base of\n * `extractDiscriminatedAllOfVariantModels`, so the two read a member alike.\n */\nfunction readComponentAllOfMember(\n  name: string,\n  member: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n  reading: ComponentReading,\n  options: MemberReadingOptions = {},\n): AllOfDiscriminator | undefined {\n  const { ledger, seen } = reading;\n  const landing = followMemberRefChain(member, schemas, seen);\n  const { resolved } = landing;\n  // The component the member's declarations are recorded under\n  // (`memberOrigin`); a landing that sets it is a base of the model, unless\n  // the component is only a nullable wrapper, whose one variant names the\n  // base (a bare alias of one is a model of its own, and the base). A\n  // member whose component another member's chain already read declares\n  // nothing more but is a direct base all the same, in either order\n  // (Greptile on #591: `allOf: [{ $ref: Animal }, { $ref: Living }]` over\n  // `Animal: { allOf: [{ $ref: Living }] }` named `Animal` alone, and\n  // reordered both); one that reaches the model itself (`reading.root`) —\n  // a component naming itself, or an alias of it — is no base of its own.\n  const origin = landing.stoppedAt === reading.root ? null : memberOrigin(landing, options.origin);\n  if (origin !== null && origin !== options.origin && !declaresOnlyNullable(origin.schema)) noteBase(reading, origin);\n  if (!landing.read) return undefined;\n  // A member that writes an `allOf` composing it — one that types it, one\n  // beside properties of its own, or one with no typing union beside it —\n  // is read as a component is; a typing union beside an `allOf` whose\n  // members only annotate or limit it is the union, read below as a member\n  // writing the union alone is (#613: any `allOf` sent the member here,\n  // where `componentAllOfMembers` now composes nothing of it, so `{ allOf:\n  // [{ description }], oneOf: [...] }`, inline or a `$ref` to such a\n  // component, would have declared nothing). A member with no `allOf` is\n  // read below whatever else it writes, as it was: a dispatcher it carries\n  // beside its own properties is the model's (#429).\n  if (resolved.allOf !== undefined && composesComponentModel(resolved)) {\n    readComponentAllOf(name, resolved, schemas, reading, origin ?? undefined);\n    return undefined;\n  }\n  // The member's own `properties` and `required` always apply, whether or\n  // not a `oneOf`/`anyOf` sits beside them (workos/oagen#359 review: a\n  // member `{ properties: { x }, oneOf: […] }`, inline or a `$ref` to such a\n  // component, lost `x`, while the same schema as a body kept it), and so\n  // does the `required` list of an `allOf` member that only annotates or\n  // limits the member (`annotatingAllOfMembers`) — the one `allOf` a member\n  // read here can carry, beside its union (#613 review: `{ allOf: [{\n  // required: ['id'] }], oneOf: [...] }` read here lost `id` from the\n  // required set, which the composed reading had kept).\n  for (const level of [resolved, ...annotatingAllOfMembers(resolved)]) {\n    for (const r of level.required ?? []) noteRequired(reading, r, origin);\n  }\n  for (const [key, value] of Object.entries(resolved.properties ?? {})) {\n    if (value) declareUnder(reading, key, value, origin);\n  }\n  // A nullable wrapper is its one non-null variant, read as one more member\n  // in this member's own capacity — decided per axis (`nullableAxisBranch`),\n  // so a member writing a nullable `oneOf` beside an `anyOf` has the `anyOf`\n  // read too; the wrapper is recorded so a component that wraps a reference\n  // to itself ends here.\n  const axes = unionAxesOf(resolved).filter((variants) => variants !== options.skipAxis);\n  const branches = axes.map((variants) => nullableAxisBranch(resolved, variants));\n  if (branches.some((branch) => branch !== undefined)) {\n    if (seen.has(resolved)) return undefined;\n    seen.add(resolved);\n  }\n  let discriminator: AllOfDiscriminator | undefined;\n  for (const [index, variants] of axes.entries()) {\n    const branch = branches[index];\n    if (branch) {\n      // The member's own `discriminator`, written on the wrapper, goes with\n      // the variant (#398 review round 6: the recursion passed the options\n      // unchanged, so a mapping on the wrapper never reached the union under\n      // it, which was flattened instead of dispatched).\n      const wrapperDiscriminator = resolved.discriminator ?? options.wrapperDiscriminator;\n      const wrapped = readComponentAllOfMember(name, branch, schemas, reading, {\n        ...options,\n        wrapperDiscriminator,\n        origin: origin ?? undefined,\n      });\n      discriminator ??= wrapped;\n      continue;\n    }\n    // A dispatcher: the discriminator is kept instead of the variants'\n    // fields — the base members already carry the fields every variant\n    // shares (e.g. EventSchema, where each variant pins `event`).\n    const detected = detectAllOfVariantDiscriminator(\n      variants,\n      name,\n      schemas,\n      resolved.discriminator ?? options.wrapperDiscriminator,\n    );\n    if (detected) {\n      discriminator ??= detected;\n      continue;\n    }\n    // Flatten the variants' fields into the model as optional fields: the\n    // common allOf + oneOf pattern of mutually exclusive field groups (e.g.\n    // password vs password_hash), each variant read as the inline merge\n    // reads it (workos/oagen#430 review: a wrapped `{ kind: '-', meow }` lost\n    // `meow` once its nameless const sent the union here).\n    for (const variant of variants) declareVariant(ledger, variant, schemas);\n  }\n  return discriminator;\n}\n\n/**\n * Read a composed component schema — its own `properties` and `required`\n * first, then its `allOf` members, or the one `$ref` member a bare `$ref`\n * component composes (#618), then a typing union written beside them\n * (`componentAllOfMembers`), each through `readComponentAllOfMember` — into\n * `reading`, under `origin` when the schema is a base's read inside the\n * model's chain (its members' declarations and its `required` are then\n * that base's; #591), and return the discriminator a direct member's\n * `oneOf`/`anyOf` declares, if any. A `discriminator` the schema writes\n * beside its `allOf` with no union beside it is the one a union among its\n * members dispatches by (`Pet: { allOf: [{ $ref: Base }, { oneOf: [...] }],\n * discriminator: { propertyName: 'kind' } }`), so it is handed to each\n * member as the wrapper's; one written beside a union goes with that union\n * (`besideUnionMembers`). A schema reached again on the chain declares\n * nothing more (`seen`), so a component that names itself, or two members\n * naming one component, terminate. A component written as a bare `$ref`\n * composes its reference alone (`componentAllOfMembers`): a `required` or\n * a `discriminator` beside the `$ref` is not read, as nothing but\n * annotations is beside any `$ref` (#618 review).\n */\nfunction readComponentAllOf(\n  name: string,\n  schema: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n  reading: ComponentReading = newComponentReading(),\n  origin?: ComponentOrigin,\n): AllOfDiscriminator | undefined {\n  if (reading.seen.has(schema)) return undefined;\n  reading.seen.add(schema);\n  reading.root ??= schema;\n  let discriminator: AllOfDiscriminator | undefined;\n  const wrapperDiscriminator = wrapperDiscriminatorOf(schema);\n  for (const member of componentAllOfMembers(schema)) {\n    discriminator =\n      readComponentAllOfMember(name, member, schemas, reading, { wrapperDiscriminator, origin }) ?? discriminator;\n  }\n  // The component's own `required`: carried by its own member when it\n  // declares properties, and read here when it only names inherited ones\n  // (`Pup: { allOf: [{ $ref: Dog }], required: [breed] }`) — never beside\n  // a bare `$ref`, which composes its reference alone — the model's own\n  // list at the top level, a base's inside its chain (`origin`).\n  for (const r of ownRequired(schema)) noteRequired(reading, r, origin ?? null);\n  return discriminator;\n}\n\n/**\n * The `required` names a composed component declares as its own\n * (`readComponentAllOf`, `discriminatedVariantSchemas`): its `required`\n * list, unless the component is written as a bare `$ref`, beside which\n * nothing but annotations is read (#618 review: `B: { $ref: Cat,\n * required: [name] }` is `Cat`'s `name` as optional as `Cat` declares it,\n * at `B`, at every hop of a chain naming `B` and in a merge naming it,\n * where `B: { allOf: [{ $ref: Cat }], required: [name] }` requires it).\n */\nfunction ownRequired(schema: SchemaObject): readonly string[] {\n  return schema.$ref === undefined ? (schema.required ?? []) : [];\n}\n\n/**\n * The `discriminator` a schema writes beside an `allOf` for a union among\n * the members, when it writes no union of its own beside it — one written\n * beside a union is that union's (`besideUnionMembers`), never another\n * member's. Read by the component readers and the inline merge alike, so a\n * reference to the component and the component itself dispatch by it.\n */\nexport function wrapperDiscriminatorOf(schema: SchemaObject): DiscriminatorKeyword | undefined {\n  // A `discriminator` beside a `$ref` is not read, as nothing but\n  // annotations is beside any `$ref` (#618 review): a bare `$ref` alias\n  // dispatches as the component it names does.\n  if (schema.$ref !== undefined) return undefined;\n  return besideUnionMembers(schema).length === 0 ? schema.discriminator : undefined;\n}\n\n/**\n * The schema that types a property a component declares: the always-applying\n * declaration `declareProperty` settles on — the first that declares a type,\n * a typeless one only annotating it (`combineDeclarations`) — else the\n * union of the distinct branch declarations, built exactly as the inline\n * merge builds it (`unionOfDeclarations`): one shape is its first\n * declaration, carrying the flags, documentation, limits and extensions\n * every branch agrees on (`agreedExtensions`; workos/oagen#369 review: a\n * component's `kind` took the first variant's `x-since` while the inline\n * twin left a disputed key off), several shapes are a `oneOf` of them,\n * whose inline variants the component field pass materializes under the\n * component as it does any union a field carries (#398: a component took\n * the first branch's declaration, so `kind` declared `string` by one\n * variant and `integer` by another was a `string`, while the same schema\n * inline was `(string | integer)`). Read over `componentPropertyLedger` by\n * every pass that builds a field or a model nested under one, so they\n * agree on the declaration.\n */\nexport function declaredComponentProperty(entry: PropertyDeclarations): SchemaObject {\n  if (entry.unconditional) return entry.unconditional.schema;\n  return unionOfDeclarations(entry.conditional);\n}\n\n/**\n * The model of a composed component schema (`extractModel`,\n * `composesComponentModel`). The members are read in document order\n * (`readComponentAllOf`), the component's own `properties` and `required`\n * first as one more member and a typing union written beside them last\n * (`componentAllOfMembers`); a `$ref` member's component is read the same\n * way, its own properties and then its members, so a chain\n * (`Puppy → Dog → Pet`) carries every level's own properties. A component\n * written as a bare `$ref` is read as the `allOf` of that one member\n * (#618): `CatAlias: { $ref: Cat }` is `CatAlias: { allOf: [{ $ref: Cat }]\n * }`, a model carrying `Cat`'s fields, `required` and dispatcher, through\n * a chain of such aliases (`A: { $ref: B }`, `B: { $ref: Cat }`) and into a\n * component that itself composes (`Puppy: { $ref: Dog }`), with what is\n * written beside the `$ref` as its own text, flag, limits and keys, as\n * beside an `allOf`. The\n * components the `$ref` members land on are the model's `bases`, in\n * document order, each once (`noteBase`: a model component — a bare alias\n * being a model of its own, read as the `allOf` of its reference (#618) —\n * read through a nullable alias; an enum, array or primitive component is\n * none; a `$ref` member whose component an earlier member's chain read\n * declares nothing more but is a base all the same, while the model\n * itself, or an alias of it, is none),\n * and a field whose declaration is a base's as written, which the model\n * requires only as that base does, carries that base as `inheritedFrom`\n * (`inheritedBase`; #591) — `fields` complete and in order either way,\n * so a reader of neither key sees the model it always saw. Every field is\n * typed under the component's own name with one sibling set\n * (`collectProperties`), from the one declaration\n * `declaredComponentProperty` picks: the always-applying declaration\n * `declareProperty` settles on — the first that declares a type, the\n * component's own first, a typeless one only annotating it — whatever a\n * `oneOf`/`anyOf` variant declares\n * before or after it and at whatever depth — the precedence\n * `declareProperty` gives `mergeAllOfMembers` too — and `required` is the\n * union of every always-applying member's list and the component's own; a\n * variant's `required` is not read. A `oneOf`/`anyOf` member whose variants\n * pin one property to distinct consts, or that the document declares a\n * `discriminator` for, makes the model a dispatcher\n * (`detectAllOfVariantDiscriminator`; its inline variants are built by\n * `extractDiscriminatedAllOfVariantModels`, a `$ref` variant's component\n * standing for it); otherwise the variants' properties — read through\n * their `allOf` wrappers, their nested unions and the component a `$ref`\n * variant names (`declareVariant`) — are flattened in as optional fields,\n * a property several variants declare typed as their union.\n */\nfunction extractAllOfModel(name: string, schema: SchemaObject, schemas?: Record<string, SchemaObject>): Model {\n  // One sibling set for every field of the composed model, nested `allOf`\n  // levels included, matching what the field extractor derives for it.\n  const siblings = collectProperties(schema, schemas);\n  const reading = newComponentReading();\n  const discriminator = readComponentAllOf(name, schema, schemas, reading);\n  const requiredSet = reading.required;\n  const fields = [...reading.ledger.values()].map((entry) => {\n    const field = buildFieldFromSchema(\n      entry.name,\n      declaredComponentProperty(entry),\n      name,\n      requiredSet,\n      schemas,\n      siblings,\n    );\n    const base = inheritedBase(entry, reading);\n    return base ? { ...field, inheritedFrom: base } : field;\n  });\n\n  // The text, link, flag and extensions are the wrapper layer's: the\n  // component's own, with an annotating member's — one that declares no\n  // type — where it declares none (`allOfWrapperLayer`), as the merged\n  // model's are (`mergeAllOfMembers`; #555 review: `Owner: { allOf: [{ $ref:\n  // Base }, { properties: { name } }, { description: 'An owner.',\n  // deprecated: true }] }` was a model with neither, while the same keys\n  // beside the `allOf` were its own, and `oagen diff` between the two\n  // reported `deprecatedChanged`). A typing member's stay on that member —\n  // a `$ref` member's flag on the referenced model, as `Field.deprecated`\n  // leaves it there on an allOf field.\n  const layer = allOfWrapperLayer(schema);\n  return {\n    name,\n    description: layer.description,\n    ...externalDocsEntry(layer.externalDocs),\n    fields,\n    ...(reading.bases.length > 0 ? { bases: reading.bases } : {}),\n    ...(discriminator ? { discriminator } : {}),\n    ...deprecatedEntry(layer),\n    // The wrapper's own keywords conjoined with its inline members'; `$ref`\n    // members keep theirs on the referenced model.\n    ...constraintsEntry(schema),\n    ...schemaExtensionsEntry(layer),\n  };\n}\n\n/**\n * Walk through `allOf` wrappers to collect the effective top-level properties\n * of a schema. Stops at `oneOf` / `anyOf` boundaries — those are different\n * variant axes, not part of the same flat object.\n *\n * Used by `detectAllOfVariantDiscriminator` and `deriveDiscriminatedVariantName`\n * so a oneOf variant of the form `{ allOf: [{ properties: { … } }, { oneOf: […] }] }`\n * still surfaces its top-level `properties` (in particular its discriminator\n * `const`) instead of being treated as having none.\n *\n * A `$ref` member of an `allOf` is followed to the component it names when\n * the document's components are handed in (`schemas`), through a chain of\n * aliases (`followMemberRefs`), so a union member's const that its base\n * component pins is seen (#568 review): `Cat: { allOf: [{ $ref: CatBase },\n * { properties: { lives } }] }` pins what `CatBase` pins, and `Puppy: {\n * allOf: [{ $ref: Dog }] }` what `Dog` pins, as the models built for them\n * carry `kind`. A component reached again on one walk is read once, so a\n * cycle (`Loop: { allOf: [{ $ref: Loop }] }`) declares nothing more.\n * Without the map a `$ref` member declares nothing, as the allOf+oneOf\n * readers read a variant's inline members only. A schema that is itself a\n * `$ref` — a component alias (`CatAlias: { $ref: Cat }`), which the model\n * readers read as `allOf: [{ $ref: Cat }]` (#618) — is followed too, one\n * hop at a time, and nothing written beside its `$ref` is read, as beside\n * any `$ref` (#618 review), so a union variant naming the alias pins what\n * `Cat` pins, and `Pet: { oneOf: [{ $ref: CatAlias }, { $ref: Dog }] }`\n * dispatches by `kind` as it does with the `allOf` spelling.\n *\n * A property several members declare keeps its first declaration, unless a\n * later one pins it to one value the earlier left open — a const narrows\n * and never widens — so `Base.kind: { type: 'string' }` under a `$ref`\n * member read before the variant's own `kind: { const: 'cat' }` (`Cat: {\n * allOf: [{ $ref: Base }, { properties: { kind } }] }`) leaves the variant\n * pinned, in either member order, as it was when the `$ref` member was not\n * followed (#590 review). A pin behind a `$ref`, a nullable wrapper or an\n * `allOf` read as one member on the declaration counts\n * (`pinnedDeclarationValue`; #607).\n */\nfunction getEffectiveProperties(\n  schema: SchemaObject,\n  schemas?: Record<string, SchemaObject>,\n): Record<string, SchemaObject> {\n  // Collected in a `Map` and returned through `Object.fromEntries`, so a\n  // property named `__proto__` is an own entry rather than the prototype.\n  const props = new Map<string, SchemaObject>();\n  const seen = new Set<SchemaObject>();\n  const visit = (s: SchemaObject): void => {\n    if (seen.has(s)) return;\n    seen.add(s);\n    // A `$ref` composes the component it names and nothing beside it\n    // (#618): followed one hop at a time, so a chain of aliases is read\n    // through, a cycle ends on `seen`, and a `$ref` no component answers\n    // declares nothing; what is written beside the `$ref` is not read, as\n    // beside any `$ref` (#618 review).\n    if (s.$ref !== undefined) {\n      const target = schemaRefTarget(s.$ref, schemas);\n      if (target) visit(target);\n      return;\n    }\n    for (const [k, v] of Object.entries(s.properties ?? {})) {\n      if (!v) continue;\n      const held = props.get(k);\n      // A later pin replaces an open declaration; `set` keeps the key's\n      // position, so the property order is still the order first declared.\n      if (\n        held === undefined ||\n        (pinnedDeclarationValue(held, schemas) === null && pinnedDeclarationValue(v, schemas) !== null)\n      ) {\n        props.set(k, v);\n      }\n    }\n    for (const sub of s.allOf ?? []) {\n      const member = followMemberRefs(sub, schemas, seen);\n      if (member) visit(member);\n    }\n    // Do NOT walk into oneOf / anyOf — those are alternatives, not\n    // simultaneously-present properties.\n  };\n  visit(schema);\n  return Object.fromEntries(props);\n}\n\n/**\n * The string const `schema` pins `property` to: in its own `properties`\n * (`getConstPropertyValue`), else through its `allOf` wrappers\n * (`getEffectiveProperties`, a `$ref` member followed to its component when\n * `schemas` is handed in). The declaration found — the own one too — is\n * read as the type builder reads it (`pinnedDeclarationValue`): a `$ref`\n * to a component pinning one value — `kind: { $ref: HamsterKind }` with\n * `HamsterKind: { const: 'hamster' }`, or `{ enum: ['hamster'] }` in OAS\n * 3.0 — or to an alias chain ending in one is followed with the map (#568\n * review), a nullable wrapper and an `allOf` read as one member are read\n * through at every hop (`kind: { allOf: [{ const: 'cat' }] }`; #607), and\n * a chain that repeats pins nothing. Null when the property is undeclared\n * or pins no one string (an enum of several values, a plain `type:\n * string`).\n */\nfunction getEffectiveConstPropertyValue(\n  schema: SchemaObject,\n  property: string,\n  schemas?: Record<string, SchemaObject>,\n): string | null {\n  const direct = getConstPropertyValue(schema, property, schemas);\n  if (direct !== null) return direct;\n  const effective = getEffectiveProperties(schema, schemas)[property];\n  return effective ? pinnedDeclarationValue(effective, schemas) : null;\n}\n\n/**\n * The one string a property declaration pins, read as the type builder\n * reads the declaration (`schemaToTypeRef`): through every wrapper that\n * reads as what it wraps, at every hop, in the builder's order — a `$ref`\n * to its component, followed when `schemas` is handed in\n * (`schemaRefTarget`; without the map a `$ref` declares nothing beyond\n * what is written beside it, as a `$ref` member of an `allOf` declares\n * nothing without it); a nullable wrapper of any spelling to its one\n * variant (`unwrapNullableSchema`); an `allOf` read as one member\n * (`allOfReadAsMember`: a lone member, one typing member beside members\n * that only annotate or limit it, or a lone `$ref` member beside such\n * members) to that member — then the `const` or one-value `enum:` written\n * on what it lands on (`pinnedStringValue`). So `kind: { allOf: [{ const:\n * 'cat' }] }`, `kind: { allOf: [{ $ref: HamsterKind }], description: 'The\n * kind of pet.' }` with `HamsterKind: { const: 'hamster' }`, and `kind: {\n * $ref: RabbitKind }` with `RabbitKind: { allOf: [{ $ref: RabbitConst }] }`\n * and `RabbitConst: { const: 'rabbit' }` pin `cat`, `hamster` and `rabbit`\n * — the literal each model's `kind` field carries — in OAS 3.0 (`enum:\n * ['cat']`) and 3.1 alike (#607: the bare `$ref` chain alone was followed\n * and what it landed on read as written, so each pinned nothing and the\n * union mapped `{}`). Null for a declaration that pins no one string — a\n * plain type, an enum of several values, an `allOf` of two typing members\n * (`{ allOf: [{ const: 'cat' }, { const: 'dog' }] }`, which the type\n * builder reads as neither, so it pins nothing even when the two agree) —\n * and for a chain that repeats: every schema read is recorded by identity,\n * and a hop that reaches one again pins nothing. The one reading of a\n * pinned value, shared by `getConstPropertyValue` (an inline variant's own\n * property, which the naming reads without the map), by\n * `getEffectiveProperties`, by the request-body fold\n * (`flattenDiscriminatedUnionBody`) and by the const-prefix reservation\n * (`collectOperationConstPrefixes`), so no two sites read a declaration\n * differently.\n */\nexport function pinnedDeclarationValue(\n  declaration: SchemaObject,\n  schemas?: Record<string, SchemaObject>,\n): string | null {\n  const hops = pinnedDeclarationHops(declaration, schemas);\n  return hops ? pinnedStringValue(hops[hops.length - 1]!) : null;\n}\n\n/**\n * Whether a property declaration admits `null` beside the value it pins, at\n * any hop `pinnedDeclarationValue` reads it through (`declaresNull` at each:\n * a type list naming `null`, OAS 3.0 `nullable: true` beside a `type`, a\n * nullable union wrapper, or an `allOf` read as a member that does; a\n * `nullable: true` beside an `allOf` declares nothing, as the type builder\n * reads it, and nothing beside a `$ref` is read, since the type builder\n * gives the `$ref` precedence over every sibling — `kind: { $ref:\n * EmailKind, type: ['string', 'null'] }` is the non-null field `EmailKind`\n * types; #607 review round 2) — so `kind: { oneOf: [{ const: 'email' }, {\n * type: 'null' }] }`, `kind: { type: ['string', 'null'], const: 'email' }`,\n * `kind: { type: 'string', enum: ['email'], nullable: true }` and a `$ref`\n * to a component written so admit `null` as the field built from them is\n * `nullable<literal>`. Read by the request-body fold\n * (`flattenDiscriminatedUnionBody`), so the discriminator it rebuilds from\n * the pinned values admits `null` exactly when a variant's does (#607\n * review: the fold dropped the admission). False for a chain that repeats.\n */\nexport function pinnedDeclarationAdmitsNull(\n  declaration: SchemaObject,\n  schemas?: Record<string, SchemaObject>,\n): boolean {\n  return (pinnedDeclarationHops(declaration, schemas) ?? []).some((hop) => hop.$ref === undefined && declaresNull(hop));\n}\n\n/**\n * The schemas a property declaration is read through to its pinned value\n * (`pinnedDeclarationValue`), in order — the declaration, then each hop's\n * target — ending with the one read as written; `undefined` for a chain\n * that repeats (every schema read is recorded by identity, and a hop that\n * reaches one again ends the walk pinning nothing).\n */\nfunction pinnedDeclarationHops(\n  declaration: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n): SchemaObject[] | undefined {\n  const hops: SchemaObject[] = [];\n  const seen = new Set<SchemaObject>();\n  let current = declaration;\n  while (!seen.has(current)) {\n    seen.add(current);\n    hops.push(current);\n    const next = current.$ref !== undefined ? schemaRefTarget(current.$ref, schemas) : readAsWrapped(current);\n    if (next === undefined) return hops;\n    current = next;\n  }\n  return undefined;\n}\n\n/**\n * The schema a wrapper reads as, by the type builder's rule: a nullable\n * wrapper's one variant (`unwrapNullableSchema`, which also strips a\n * `null` type-list entry or `nullable: true` to a copy), else the member\n * an `allOf` is read as (`allOfReadAsMember`); `undefined` for a schema\n * that wraps nothing, which is then read as written.\n */\nfunction readAsWrapped(schema: SchemaObject): SchemaObject | undefined {\n  const bare = unwrapNullableSchema(schema);\n  return bare !== schema ? bare : allOfReadAsMember(schema);\n}\n\n/**\n * The discriminator one variant axis of a composed component dispatches by,\n * or null for an axis that is flattened instead — the one decision the\n * member reader (`readComponentAllOfMember`), the variant builder\n * (`discriminatedVariantSchemas`) and the inline merge of a reference to\n * the component (`mergeAllOfMembers`, through `componentUnionDispatches`)\n * share, so a variant model is built exactly when the model dispatches to\n * it, and a reference reads the union as the model does.\n *\n * The variants are read as a union's members are (`unionMembers`): a `$ref`\n * variant, bare or wrapping one model reference, is resolved to its\n * component and named by it — its const read from the component, its\n * model the component's own, which the mapping names (`{ cat: 'Cat', dog:\n * 'Dog' }`) and nothing builds again (#398: a `$ref` variant surfaced no\n * const, so `Pet: { allOf: [{ $ref: Base }, { oneOf: [{ $ref: Cat }, {\n * $ref: Dog }] }], discriminator }` was a plain `{ id }`, and `oagen diff`\n * saw no variant added or removed); an inline object variant is named for\n * its const (`deriveDiscriminatedVariantName`, read through its `allOf`\n * wrappers so `{ allOf: [{ properties: { type: { const: 'oauth' } } }, {\n * oneOf: […] }] }` surfaces `type`), or the name its model settled on\n * (`planDispatcherVariants`), the one\n * `extractDiscriminatedAllOfVariantModels` builds it under; a `null`\n * variant is set aside, as an inline union sets it aside.\n *\n * The property is the document's `discriminator.propertyName` when it\n * declares one — on the union's carrier, or on the `allOf` wrapper around\n * it (`explicit`) — else the first property the first variant pins that\n * every variant pins. With a `mapping` written beside the keyword, the\n * mapping is the document's, each target resolved to the model it names\n * (`mappingTargetModelName`), as a named union reads it. Otherwise every\n * variant must pin the property to a distinct string const and name a\n * distinct model — two variants of one name, one named as the component\n * (a const that gives no name, `''` or `'-'`; workos/oagen#430), or two\n * pinning one value make the union no axis — and the mapping pairs each\n * value with its model. A single const-pinned variant dispatches too.\n */\nfunction detectAllOfVariantDiscriminator(\n  variants: readonly SchemaObject[],\n  fallbackName: string,\n  schemas: Record<string, SchemaObject> | undefined,\n  explicit?: DiscriminatorKeyword,\n): AllOfDiscriminator | null {\n  const members = unionMembers({ oneOf: [...variants] }, NO_INLINE_NAMES, schemas);\n  if (members.length === 0) return null;\n  const writtenMapping = explicit?.mapping ?? {};\n  const written = Object.entries(writtenMapping);\n  if (explicit && written.length > 0) {\n    const mapping = Object.fromEntries(written.map(([value, target]) => [value, mappingTargetModelName(target)]));\n    // An entry written as a pointer is settled to the model the pointed\n    // schema is built as (#619); a dispatcher holds no variants for one to\n    // follow, so every such entry is settled on its own.\n    deferPointerMappingEntries(writtenMapping, members, [], mapping, schemas, mappingTargetModelName);\n    return { property: explicit.propertyName, mapping };\n  }\n  // The tags are read through the component map (#568 review): one a\n  // variant inherits through an `allOf` `$ref` member, or declares as a\n  // `$ref` to a const schema, pins as one written on the variant does.\n  const pinnedBy = (property: string): boolean =>\n    members.every((member) => getEffectiveConstPropertyValue(member.resolved, property, schemas) !== null);\n  const candidates = explicit\n    ? [explicit.propertyName]\n    : Object.keys(getEffectiveProperties(members[0]!.resolved, schemas));\n  const property = candidates.find(pinnedBy);\n  if (property === undefined) return null;\n\n  // Collected in a `Map`, so a value spelled like an inherited property\n  // (`constructor`) is an own key of the mapping.\n  const mapping = new Map<string, string>();\n  // The component's own name is the dispatcher's: a variant named so is as\n  // ambiguous as two variants of one name.\n  const seenModelNames = new Set<string>([fallbackName]);\n  const plan = activeDispatcherVariantPlans.get(variants)?.get(fallbackName);\n  for (const member of members) {\n    const value = getEffectiveConstPropertyValue(member.resolved, property, schemas);\n    if (value === null || mapping.has(value)) return null;\n    const reference = member.raw.$ref !== undefined || member.resolved !== member.raw;\n    const modelName = reference ? member.name : deriveDiscriminatedVariantName(member.raw, fallbackName, schemas);\n    if (modelName === null || seenModelNames.has(modelName)) return null;\n    seenModelNames.add(modelName);\n    mapping.set(value, reference ? modelName : (plan?.names.get(member.raw) ?? modelName));\n  }\n  return { property, mapping: Object.fromEntries(mapping) };\n}\n\n/**\n * Whether a composed component dispatches one of its unions rather than\n * flattening it (`detectAllOfVariantDiscriminator`), for the inline merge\n * of a reference to it (`mergeAllOfMembers`): a union the component's own\n * model dispatches is the component's to dispatch, and its variants'\n * properties are on neither model; one the model flattens is flattened\n * into the merge too (#429), so the component's model and every merge that\n * names it carry the same fields.\n */\nexport function componentUnionDispatches(\n  variants: readonly SchemaObject[],\n  name: string,\n  schemas: Record<string, SchemaObject> | undefined,\n  explicit?: DiscriminatorKeyword,\n): boolean {\n  return detectAllOfVariantDiscriminator(variants, name, schemas, explicit) !== null;\n}\n\n/**\n * Whether a component written as a bare `$ref` names no component its\n * model could carry: its chain of `$ref`s returns to itself (`Loop: { $ref:\n * Loop }`; `A: { $ref: B }` beside `B: { $ref: A }`), or ends at a `$ref` no\n * component answers — followed through every `$ref` on the chain, whatever\n * is written beside it. Such a component is read as any bare `$ref` alias\n * is (`extractAllOfModel`; #618) and the chain declares nothing, so its\n * model has no fields but what the aliases write beside their `$ref`s;\n * `extractSchemas` reports it once. False for a schema that is no bare\n * `$ref`, and for one whose chain ends at a component.\n */\nfunction bareRefNamesNothing(schema: SchemaObject, schemas: Record<string, SchemaObject> | undefined): boolean {\n  if (schema.$ref === undefined) return false;\n  const chain = new Set<SchemaObject>([schema]);\n  let hop: SchemaObject = schema;\n  while (hop.$ref !== undefined) {\n    const target = schemaRefTarget(hop.$ref, schemas);\n    if (target === undefined || chain.has(target)) return true;\n    chain.add(target);\n    hop = target;\n  }\n  return false;\n}\n\n/**\n * The component an `allOf` member names, followed through a chain of\n * references (`Hop: { $ref: Alias }`), or the member itself when it is no\n * reference; `undefined` when the chain repeats or reaches a component\n * already read on this walk (`seen`), which then declares nothing more.\n * Every `$ref` on the chain is followed through, whatever is written\n * beside it: nothing but annotations is read beside a `$ref` (#618\n * review), so `B: { $ref: Cat, required: [name] }` under `A: { $ref: B }`\n * is `Cat` at `A` and at `B` alike. The one reference-following every\n * reader of a component's member shares: `readComponentAllOfMember` reads\n * the member it lands on, `memberUnion` finds the union it carries. A\n * `$ref` no component answers ends the chain on the schema that writes\n * it, which the caller sees by its `$ref`.\n */\nfunction followMemberRefs(\n  member: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n  seen: Set<SchemaObject>,\n): SchemaObject | undefined {\n  const landing = followMemberRefChain(member, schemas, seen);\n  return landing.read ? landing.resolved : undefined;\n}\n\n/**\n * Where a member's reference chain lands (`followMemberRefs`), with the key\n * and the own schema of the first component it resolves through — the one\n * whose model carries what the member declares (`memberOrigin`): a bare\n * alias on the way (`Hop: { $ref: Animal }`, `Hop: { $ref: Alias }` over a\n * nullable `Alias`) is read as `allOf: [{ $ref: … }]`, a model of its own\n * (#618), so the member's declarations are its. No key for an inline\n * member, or a chain of pointers into components alone (#539).\n */\ninterface MemberLanding {\n  resolved: SchemaObject;\n  key?: string;\n  named?: SchemaObject;\n  /** Whether the landing is to be read: `false` when the chain reaches a schema already read on this walk (`seen`), or one of its own again, which then declares nothing more — `stoppedAt` names it, so a member that only names the model itself, or an alias of it, is told from one naming a component another member's chain read. */\n  read: boolean;\n  stoppedAt?: SchemaObject;\n}\n\n/** `followMemberRefs` with the landing's component key (`MemberLanding`). */\nfunction followMemberRefChain(\n  member: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n  seen: Set<SchemaObject>,\n): MemberLanding {\n  let resolved = member;\n  let key: string | undefined;\n  let named: SchemaObject | undefined;\n  const chain = new Set<SchemaObject>();\n  while (resolved.$ref) {\n    const target = schemaRefTarget(resolved.$ref, schemas);\n    if (!target) break;\n    if (key === undefined) {\n      key = componentKeyOf(resolved.$ref);\n      if (key !== undefined) named = target;\n    }\n    if (seen.has(target) || chain.has(target)) return { resolved: target, key, named, read: false, stoppedAt: target };\n    chain.add(target);\n    resolved = target;\n  }\n  return { resolved, key, named, read: true };\n}\n\n/** One union a component's `allOf` member carries: the schema that writes it, its variants, and the `discriminator` declared for it on the way — the carrier's own, else a nullable wrapper's around it. */\ninterface MemberUnion {\n  carrier: SchemaObject;\n  variants: SchemaObject[];\n  discriminator?: DiscriminatorKeyword;\n}\n\n/**\n * The unions a component's `allOf` member carries (`unionAxesOf`), read\n * through every wrapper `readComponentAllOfMember` reads the member through\n * — a chain of references (`followMemberRefs`), then, per keyword, a\n * nullable union wrapper (`nullableAxisBranch`) to its one non-null\n * variant, the two alternating — in the order the member reader reads\n * them: an axis that is no wrapper as it stands, a nullable axis as the\n * unions its one variant carries, each with the `discriminator` declared\n * for it on the way (the carrier's own, else the wrapper's around it, as\n * the member reader hands a wrapper's down; #398 review round 6: a mapping\n * on the wrapper was forgotten, and the builder flattened what the reader\n * dispatched). None for a member that carries none, or a member whose\n * `allOf` composes it (`composesComponentModel`: read as a component\n * composed with `allOf`, never as a variant axis — a union beside an\n * `allOf` that only annotates or limits the member is an axis, as the\n * member reader reads it; #613).\n * The one way the variant builder\n * (`extractDiscriminatedAllOfVariantModels`) finds a variant axis, so a\n * union the member reader detects as a dispatcher is the union whose\n * variant models are built, whichever wrapper it sits under\n * (workos/oagen#308 merge review: a dispatcher detected through `{ oneOf:\n * [{ oneOf: [A, B] }, { type: 'null' }] }` mapped its tags to models\n * nothing built, since the builder looked at each direct member's union\n * only) and whatever is written beside it (#398 review round 2: a member\n * `{ oneOf: [{ a }, { type: 'null' }], anyOf: [cat, dog] }` was collapsed\n * to `{ a }` for the whole member once the reader decided its wrappers\n * per keyword, so `Pet` mapped `cat` and `dog` to `PetCat` and `PetDog`\n * and neither was built).\n */\nfunction memberUnions(\n  member: SchemaObject,\n  schemas: Record<string, SchemaObject> | undefined,\n  seen = new Set<SchemaObject>(),\n  wrapper?: DiscriminatorKeyword,\n): MemberUnion[] {\n  const carrier = followMemberRefs(member, schemas, seen);\n  // A carrier whose `allOf` composes it is read as a component\n  // (`readComponentAllOfMember`, by the same predicate), never as a variant\n  // axis; a union beside an `allOf` that only annotates it is the axis it\n  // is written alone (#613).\n  if (!carrier || (carrier.allOf !== undefined && composesComponentModel(carrier))) return [];\n  const axes = unionAxesOf(carrier);\n  const branches = axes.map((variants) => nullableAxisBranch(carrier, variants));\n  // The wrapper is recorded as read, as the member reader records it, so a\n  // component that wraps a reference to itself ends here.\n  if (branches.some((branch) => branch !== undefined)) {\n    if (seen.has(carrier)) return [];\n    seen.add(carrier);\n  }\n  const discriminator = carrier.discriminator ?? wrapper;\n  const unions: MemberUnion[] = [];\n  for (const [index, variants] of axes.entries()) {\n    const branch = branches[index];\n    if (branch) unions.push(...memberUnions(branch, schemas, seen, discriminator));\n    else unions.push({ carrier, variants, discriminator });\n  }\n  return unions;\n}\n\n/**\n * The variant models of a discriminated allOf + oneOf/anyOf component: each\n * object variant's rebuilt schema (`discriminatedVariantSchemas`) extracted\n * with everything nested under it (`extractInlineModelDeep`) under the name\n * the variant settled on (`planDispatcherVariants`), the one the\n * dispatcher's mapping names. A model another entry builds for the\n * identical shape is that entry's to build, so it is left out here.\n */\nfunction extractDiscriminatedAllOfVariantModels(\n  schema: SchemaObject,\n  fallbackName: string,\n  schemas?: Record<string, SchemaObject>,\n): Model[] {\n  const models: Model[] = [];\n  const seenNames = new Set<string>();\n  for (const { variants, rebuilt } of discriminatedVariantSchemas(schema, fallbackName, schemas)) {\n    const plan = activeDispatcherVariantPlans.get(variants)?.get(fallbackName);\n    for (const { variant, merged } of rebuilt) {\n      const variantName = plan?.names.get(variant) ?? deriveDiscriminatedVariantName(variant, fallbackName, schemas);\n      for (const model of extractInlineModelDeep(variantName, merged, schemas)) {\n        if (seenNames.has(model.name) || plan?.shared.has(model.name)) continue;\n        seenNames.add(model.name);\n        models.push(model);\n      }\n    }\n  }\n  return models;\n}\n\n/** A discriminated component's variant axis: its union's variants, and each object variant with the schema its model is built from. */\ninterface DiscriminatedAxis {\n  variants: readonly SchemaObject[];\n  rebuilt: Array<{ variant: SchemaObject; merged: SchemaObject }>;\n}\n\n/**\n * Every variant axis of a discriminated allOf + oneOf/anyOf component, each\n * object variant rebuilt as the complete object its model is built from: the\n * base every variant carries, then the variant's own declarations. Nothing\n * for a component no union of which dispatches.\n */\nfunction discriminatedVariantSchemas(\n  schema: SchemaObject,\n  fallbackName: string,\n  schemas?: Record<string, SchemaObject>,\n): DiscriminatedAxis[] {\n  const axesFound: DiscriminatedAxis[] = [];\n\n  // Collect base-object properties + required from the allOf wrapper so each\n  // variant can be emitted as a complete, self-contained type. Schemas like\n  // `EventSchema` repeat the base fields inside every variant in the spec\n  // (so this merge is a no-op there), but `ConnectApplication`'s OAuth /\n  // M2M variants don't — without this, dispatcher consumers would get a\n  // variant that's missing the shared `id` / `name` / `object` etc.\n  // The base: every declaration the members other than the variant axis\n  // make, read exactly as `extractAllOfModel` reads them\n  // (`readComponentAllOfMember`, with the component's own `properties` and\n  // `required` first — `componentAllOfMembers` — so what the component\n  // declares beside its `allOf` is a base field every variant carries, as a\n  // member's is) and resolved by the same precedence: the first\n  // always-applying declaration; a declaration a nested union's branch makes\n  // is a fallback the base carries as optional. Names are matched by own\n  // name (`Map`, `Object.fromEntries`), so a base property named\n  // `constructor`, `toString` or `__proto__` reaches every variant.\n  const members = componentAllOfMembers(schema);\n  const wrapperDiscriminator = wrapperDiscriminatorOf(schema);\n  // The variant axis: a member carrying a `oneOf`/`anyOf` — read through a\n  // reference chain and a nullable wrapper exactly as `readComponentAllOfMember`\n  // reads it (`memberUnions`) — whose variants pin one property to distinct\n  // consts, or that the document declares a `discriminator` for — the\n  // reading `extractAllOfModel` makes of it\n  // (`detectAllOfVariantDiscriminator`) — so a variant model exists exactly\n  // when the component's model dispatches to it; the first such union of a\n  // member, as the member reader keeps the first. A union that is not an\n  // axis is flattened into the model and builds no variant model here\n  // (workos/oagen#359 review: it did, and a model nested under such a\n  // variant took the name of the flattened field's own model).\n  const axisVariants = new Map<SchemaObject, SchemaObject[]>();\n  for (const m of members) {\n    for (const { variants, discriminator } of memberUnions(m, schemas)) {\n      const explicit = discriminator ?? wrapperDiscriminator;\n      if (detectAllOfVariantDiscriminator(variants, fallbackName, schemas, explicit) === null) continue;\n      axisVariants.set(m, variants);\n      break;\n    }\n  }\n  if (axisVariants.size === 0) return axesFound;\n  const reading = newComponentReading();\n  reading.seen.add(schema);\n  reading.root = schema;\n  // Shared limits every variant instance must satisfy under allOf semantics:\n  // the outer wrapper's own keywords, each base member's (through its allOf\n  // wrappers), and any written beside the `oneOf` itself — everything except\n  // the branches. They ride along with the base properties and are conjoined\n  // with each variant's own below, so on a shared keyword the stricter bound\n  // wins.\n  let baseConstraints = ownConstraints(schema);\n  for (const subSchema of members) {\n    const skipAxis = axisVariants.get(subSchema);\n    if (skipAxis) {\n      // The axis: its branches are handled below, its own keywords bind all\n      // of them — the keywords of its own level, an `allOf` member that only\n      // annotates or limits it included (`annotatingAllOfMembers`; #613\n      // review: `{ allOf: [{ maxProperties: 3 }], oneOf: [cat, dog] }` as a\n      // member built `HolderCat` and `HolderDog` without the limit, where\n      // `{ maxProperties: 3, oneOf: [...] }` carried it onto both) — and its\n      // own `properties` and `required` are base fields every variant\n      // carries (read without its variants).\n      readComponentAllOfMember(fallbackName, subSchema, schemas, reading, { skipAxis, wrapperDiscriminator });\n      for (const level of [subSchema, ...annotatingAllOfMembers(subSchema)]) {\n        baseConstraints = combineConstraints(baseConstraints, ownConstraints(level));\n      }\n      continue;\n    }\n    // Any other member, a union that is not an axis included: read as the\n    // model reads it, its variants' properties as branch-only fallbacks.\n    readComponentAllOfMember(fallbackName, subSchema, schemas, reading, { wrapperDiscriminator });\n    baseConstraints = combineConstraints(baseConstraints, extractConstraints(subSchema));\n  }\n  // The component's own `required` naming an inherited property only, as\n  // `readComponentAllOf` reads it for the dispatcher model.\n  for (const r of ownRequired(schema)) reading.required.add(r);\n  const baseRequired = reading.required;\n  const baseProperties: Record<string, SchemaObject> = Object.fromEntries(\n    [...reading.ledger.values()].map((entry) => [entry.name, declaredComponentProperty(entry)]),\n  );\n\n  for (const variants of axisVariants.values()) {\n    const rebuilt: DiscriminatedAxis['rebuilt'] = [];\n    for (const variant of variants) {\n      // Flatten any allOf wrapper on the variant (e.g. `ConnectApplication`'s\n      // OAuth branch is `allOf: [{ properties: {…} }, { oneOf: [first-party\n      // sub-variants] }]`). The flattened object has merged properties and\n      // an inlined sub-variant `oneOf` so `extractInlineModelDeep` can pull\n      // out a complete variant model.\n      const flat = flattenVariantForExtraction(variant);\n      if (!flat.properties || (flat.type !== undefined && flat.type !== 'object')) continue;\n\n      // Merge base fields into the variant. Variant-specific properties win\n      // on name collisions because the spec may pin a base field to a more\n      // specific shape inside a variant. Built through a `Map`, so a property\n      // named `__proto__` is set rather than taken for the prototype.\n      const mergedProperties = new Map<string, SchemaObject>(Object.entries(baseProperties));\n      for (const [k, v] of Object.entries(flat.properties)) {\n        if (v) mergedProperties.set(k, v);\n      }\n      const mergedRequired = new Set<string>([...baseRequired, ...(flat.required ?? [])]);\n      // The variant's own keywords (read through its allOf wrappers, like its\n      // properties) conjoined with the base members'. They are already in the\n      // 3.1 shape, so spreading them into the rebuilt schema lets\n      // extractInlineModelDeep's constraintsEntry read them back unchanged.\n      const merged: SchemaObject = {\n        type: 'object',\n        properties: Object.fromEntries(mergedProperties),\n        required: [...mergedRequired],\n        // The variant's own flag only: the union's wrapper deprecates the\n        // dispatcher model, not the variants it dispatches to.\n        ...deprecatedEntry(variant),\n        ...combineConstraints(baseConstraints, extractConstraints(variant)),\n        // The variant's own link rides along like its keywords, so the model\n        // built from the rebuilt schema carries it; so do its own extensions.\n        ...externalDocsEntry(variant.externalDocs),\n        ...extensionsOf(variant, SCHEMA_CONSUMED_EXTENSIONS),\n      };\n      rebuilt.push({ variant, merged });\n    }\n    axesFound.push({ variants, rebuilt });\n  }\n\n  return axesFound;\n}\n\n/**\n * The name of every discriminated allOf + oneOf/anyOf component's variant\n * models, decided once per document, the components in document order, so\n * no variant folds onto a model of another shape (workos/oagen#430 review:\n * `CatEvent`'s `cat` variant, `CatEventCat`, was dropped for a component\n * `CatEventCat` with more fields, and the dispatcher mapped `cat` to that\n * component). A variant takes the name its const derives\n * (`deriveDiscriminatedVariantName`) unless a name its tree mints there —\n * the variant's model or one nested under it (`extractInlineModelDeep`,\n * rehearsed) — is held with another shape: by another entry\n * (`componentMints`: its model, enum or array, its named-union variants, the\n * objects and enums its fields mint), by a variant an earlier dispatcher or\n * an earlier variant of the union settled on, or, whatever its shape, by the\n * component itself or the union's other variants. It then steps by number\n * (`CatEventCat2`, `CatEventCat3`, …), the number spelled as `numberedName`\n * spells every numbered name, behind `No` after a digit (`PetEvent`'s\n * `pet.v2` beside a component `PetV2` of another shape is `PetV2No2`, then\n * `PetV2No3`, never `PetV22`, which reads as version 22; #602), everything\n * nested under it moving with it (`CatEventCat2Owner`, `PetV2No2Owner`) and\n * the mapping naming it there. A holder of the identical shape is shared. A\n * component's model stands for the variant's, which is not built, so the\n * component keeps its own documentation; any other holder's copy is built\n * as before and folds onto the other (`keepLarger`,\n * `settleFieldInlineModels`), so the mapping never names a model a later\n * pass may rename through another site, such as a field's object. A name\n * that does not start with the variant's (a nested variant's title) does\n * not move with it and is left to the rules that name it.\n */\nfunction planDispatcherVariants(\n  schemas: Record<string, SchemaObject>,\n): Map<readonly SchemaObject[], Map<string, DispatcherUnionPlan>> {\n  const plans = new Map<readonly SchemaObject[], Map<string, DispatcherUnionPlan>>();\n  const dispatchers = Object.entries(schemas).flatMap(([key, schema]) => {\n    if (isEnumComponentSchema(schema) || isArrayComponentEntry(schema, schemas)) return [];\n    const name = resolveSchemaName(key);\n    const axes = discriminatedVariantSchemas(schema, name, schemas);\n    return axes.length > 0 ? [{ key, name, axes }] : [];\n  });\n  if (dispatchers.length === 0) return plans;\n  const components = componentModelNames();\n  const minted = new Map(\n    Object.entries(schemas).map(([key, schema]) => [key, componentMints(key, schema, schemas, false)] as const),\n  );\n  // Every name a variant tree settled on, with its shape, for the dispatchers after it.\n  const settled = new Map<string, string[]>();\n  for (const { key, name, axes } of dispatchers) {\n    const held = new Map<string, string[]>();\n    const hold = (holder: string, shape: string): void => {\n      held.set(holder, [...(held.get(holder) ?? []), shape]);\n    };\n    for (const [other, names] of minted) {\n      if (other !== key) for (const [holder, shapes] of names) for (const shape of shapes) hold(holder, shape);\n    }\n    for (const [holder, shapes] of settled) for (const shape of shapes) hold(holder, shape);\n    for (const { variants, rebuilt } of axes) {\n      const taken = new Set([\n        name,\n        ...variants.map((variant) => deriveDiscriminatedVariantName(variant, name, schemas)),\n      ]);\n      const plan: DispatcherUnionPlan = { names: new Map(), shared: new Set() };\n      for (const { variant, merged } of rebuilt) {\n        const own = deriveDiscriminatedVariantName(variant, name, schemas);\n        taken.delete(own);\n        const { variantName, tree } = firstFreeVariantName(own, merged, schemas, taken, held);\n        plan.names.set(variant, variantName);\n        taken.add(variantName);\n        for (const model of tree) {\n          if (!model.name.startsWith(variantName)) continue;\n          if (held.has(model.name)) {\n            if (components.has(model.name)) plan.shared.add(model.name);\n            continue;\n          }\n          const shape = modelShapeKey(model);\n          hold(model.name, shape);\n          settled.set(model.name, [shape]);\n        }\n      }\n      plans.set(variants, new Map([...(plans.get(variants) ?? []), [name, plan]]));\n    }\n  }\n  return plans;\n}\n\n/**\n * The first of `base`, then `base` numbered 2, 3, … as `numberedName`\n * spells every numbered model and enum name — bare after a letter\n * (`CatEventCat2`), behind `No` after a digit (`PetV2No2`, never `PetV22`,\n * which reads as version 22; #602) — under which a variant's tree — its\n * rebuilt schema `merged`, extracted with everything nested under it —\n * mints no name starting with the candidate that is `taken`, or `held`\n * with a shape other than the one it mints; with that tree. It ends: each\n * candidate's names start with the candidate, and a held or taken name\n * starts with finitely many of them.\n */\nfunction firstFreeVariantName(\n  base: string,\n  merged: SchemaObject,\n  schemas: Record<string, SchemaObject>,\n  taken: ReadonlySet<string>,\n  held: ReadonlyMap<string, readonly string[]>,\n): { variantName: string; tree: Model[] } {\n  for (let n = 1; ; n++) {\n    const variantName = n === 1 ? base : numberedName(base, n);\n    if (taken.has(variantName)) continue;\n    const tree = rehearse(() => extractInlineModelDeep(variantName, merged, schemas));\n    const free = tree.every(\n      (model) =>\n        !model.name.startsWith(variantName) ||\n        (!taken.has(model.name) && (held.get(model.name) ?? []).every((shape) => shape === modelShapeKey(model))),\n    );\n    if (free) return { variantName, tree };\n  }\n}\n\n/**\n * Flatten a oneOf variant schema into a single object-shaped schema for\n * variant-model extraction, and for a union no discriminator dispatches,\n * whose variants a component's model flattens in\n * (`readComponentAllOfMember`), so a variant declares the same properties\n * either way. Recursively merges `allOf` members and folds\n * any nested `oneOf` into an inline-oneOf field group whose properties are\n * the union across sub-branches (required only when present in every\n * sub-branch). Returns the schema unchanged when no flattening is needed.\n */\nfunction flattenVariantForExtraction(variant: SchemaObject): SchemaObject {\n  if (!variant.allOf) return variant;\n\n  // A `Map`, returned through `Object.fromEntries`, so a property named\n  // `__proto__` is kept as an own entry.\n  const mergedProperties = new Map<string, SchemaObject>();\n  const mergedRequired = new Set<string>();\n  const nestedOneOfs: SchemaObject[][] = [];\n\n  const collect = (s: SchemaObject): void => {\n    if (s.properties) {\n      for (const [k, v] of Object.entries(s.properties)) {\n        if (!mergedProperties.has(k) && v) mergedProperties.set(k, v);\n      }\n    }\n    if (s.required) {\n      for (const r of s.required) mergedRequired.add(r);\n    }\n    if (s.allOf) {\n      for (const sub of s.allOf) collect(sub);\n    }\n    nestedOneOfs.push(...unionAxesOf(s));\n  };\n  collect(variant);\n\n  // Fold each nested oneOf into the merged shape: any field appearing in any\n  // sub-branch is included as optional (or required iff present-and-required\n  // in every sub-branch). Conflicting literal types widen to their primitive\n  // base. This handles the `is_first_party: true | false` widening on the\n  // OAuth variant's first-party sub-oneOf.\n  for (const branches of nestedOneOfs) {\n    const flatBranches = branches.map(flattenVariantForExtraction);\n    const branchKeys = new Set<string>();\n    for (const b of flatBranches) {\n      for (const k of Object.keys(b.properties ?? {})) branchKeys.add(k);\n    }\n    for (const key of branchKeys) {\n      const schemas: SchemaObject[] = [];\n      for (const b of flatBranches) {\n        const s = b.properties?.[key];\n        if (s) schemas.push(s);\n      }\n      const merged = mergeBranchPropertySchemas(schemas);\n      if (!mergedProperties.has(key)) mergedProperties.set(key, merged);\n      const inAllBranches = flatBranches.every((b) => b.properties !== undefined && Object.hasOwn(b.properties, key));\n      const requiredInAll = inAllBranches && flatBranches.every((b) => (b.required ?? []).includes(key));\n      if (requiredInAll) mergedRequired.add(key);\n    }\n  }\n\n  return {\n    type: 'object',\n    properties: Object.fromEntries(mergedProperties),\n    required: [...mergedRequired],\n  };\n}\n\n/**\n * Merge same-named property schemas from across sub-variants. If every\n * occurrence is a boolean const, widen to plain boolean; if every occurrence\n * is a distinct string const, widen to plain string. Otherwise return the\n * first occurrence — emitters that build their own widened types (e.g. the\n * Node discriminated-models module) re-derive from the raw spec. Whichever\n * way, the result carries exactly the extensions every occurrence agrees on\n * (`agreedExtensions`, the one rule for a property several declarations\n * give; workos/oagen#369 review: a widened field kept `type` and\n * `description` alone, so a shared `x-since` was lost, and the first\n * occurrence was returned with its own keys, disputed or not).\n */\nfunction mergeBranchPropertySchemas(schemas: SchemaObject[]): SchemaObject {\n  if (schemas.length === 0) return {};\n  if (schemas.length === 1) return schemas[0];\n  const extensions = agreedExtensions(schemas);\n\n  const allBoolConst = schemas.every((s) => s.type === 'boolean' && typeof s.const === 'boolean');\n  if (allBoolConst) {\n    return { type: 'boolean', description: schemas[0].description, ...extensions };\n  }\n  const allStringConst = schemas.every((s) => s.type === 'string' && typeof s.const === 'string');\n  if (allStringConst) {\n    const values = schemas.map((s) => s.const as string);\n    if (new Set(values).size === 1) return withAgreedExtensions(schemas[0], extensions);\n    return { type: 'string', description: schemas[0].description, ...extensions };\n  }\n  return withAgreedExtensions(schemas[0], extensions);\n}\n\n/**\n * The name an inline variant of a composed component's union settles on\n * from the const it pins — `<component><Const>` — or `fallbackName` when\n * it pins none. The const is read through the variant's `allOf` wrappers\n * and, with the component map (`schemas`), through a `$ref` member among\n * them and a `$ref` to a const schema, as the dispatcher detection reads\n * it (`detectAllOfVariantDiscriminator`, `getEffectiveProperties`), so a\n * variant named by an inherited tag dispatches as one tagged directly does\n * (#398 review round 3) — and the declaration found is read as the\n * detection reads it (`pinnedDeclarationValue`), through a nullable\n * wrapper and an `allOf` read as one member, so a variant pinning `kind:\n * { allOf: [{ const: 'cat' }] }` is `<component>Cat` as one pinning `kind:\n * { const: 'cat' }` is (#607: the declaration was read as written, so the\n * variant was named as the component, and the detection — which had read\n * the value through the wrapper — rejected the clash and flattened the\n * union). Every reader of a variant's name hands the map in, so detection,\n * the variant plan and the builder settle on one name.\n */\nfunction deriveDiscriminatedVariantName(\n  schema: SchemaObject,\n  fallbackName: string,\n  schemas?: Record<string, SchemaObject>,\n): string {\n  // Walk through allOf wrappers so a variant of the form\n  // `{ allOf: [{ properties: { type: const: 'oauth' } }, { oneOf: […] }] }`\n  // still surfaces its discriminator const value for naming.\n  const effective = getEffectiveProperties(schema, schemas);\n  if (Object.keys(effective).length === 0) return fallbackName;\n\n  const pickConst = (name: string): string | null => {\n    const field = effective[name];\n    return field ? pinnedDeclarationValue(field, schemas) : null;\n  };\n\n  let constValue: string | null = null;\n  for (const preferred of ['event', 'type', 'object']) {\n    constValue = pickConst(preferred);\n    if (constValue) break;\n  }\n  if (constValue === null) {\n    for (const name of Object.keys(effective)) {\n      constValue = pickConst(name);\n      if (constValue) break;\n    }\n  }\n  if (constValue === null) return fallbackName;\n\n  const pascal = toPascalCase(constValue);\n  if (!pascal) return fallbackName;\n\n  // A single-word const like `oauth` or `m2m` is too generic to stand alone\n  // as a top-level model name — it would collide with unrelated schemas. Pair\n  // it with the parent name so the variant resolves to e.g. `ConnectApplicationOAuth`\n  // / `ConnectApplicationM2M`. Multi-word consts like `action.authentication.denied`\n  // are already specific enough on their own, matching the established\n  // EventSchema variant naming. Either way a const never names the variant as\n  // the parent itself, whose name is the dispatcher's: `CatEvent`'s `cat` is\n  // `CatEventCat` as `PetEvent`'s is `PetEventCat`, and `Cat`'s is `CatCat`\n  // (workos/oagen#430).\n  const wordCount = splitWords(constValue).length;\n  if (pascal === fallbackName) return `${fallbackName}${pascal}`;\n  if (wordCount >= 2) return pascal;\n  if (pascal.endsWith(fallbackName)) return pascal;\n  return `${fallbackName}${pascal}`;\n}\n\n/**\n * The model for a discriminated variant's rebuilt object schema, and every\n * inline model its fields reference: the variant's own model\n * (`buildInlineModel`, its properties typed under `name`) followed by\n * whatever its properties mint, extracted by the field extractor\n * (`extractInlineModelsFromProperties`) under `name` as parent — so a\n * nested object, typed or not, nullable or not; array items and map values\n * of any shape (an inline object, an `allOf` merge, a union); every\n * `oneOf`/`anyOf` variant and its members; an `allOf` field read as\n * `readInlineAllOf` reads it; an inline enum — is materialized under exactly\n * the name `buildFieldFromSchema` typed it with, since the extractor and the\n * type builder name by the same rules. A variant's fields are built here\n * the one way every inline object's are, so typing and extraction cannot\n * disagree for any shape under a discriminated variant.\n */\nfunction extractInlineModelDeep(name: string, schema: SchemaObject, schemas?: Record<string, SchemaObject>): Model[] {\n  const nestedModels: Model[] = [];\n  extractInlineModelsFromProperties(schema, nestedModels, name, schemas);\n  return [buildInlineModel(name, schema, schemas), ...nestedModels];\n}\n\n/**\n * `elementContextName` for an optional context: with no field name there is\n * nothing to decide, and the items / values keep an undefined context.\n */\nfunction elementContext(\n  contextName: string | undefined,\n  kind: 'item' | 'value',\n  siblingProperties: ReadonlyMap<string, SchemaObject> | undefined,\n  parentModelName: string | undefined,\n  elementSchema: SchemaObject,\n): string | undefined {\n  return contextName === undefined\n    ? undefined\n    : elementContextName(contextName, kind, siblingProperties, parentModelName, elementSchema);\n}\n\n/**\n * Every `ModelRef` built from a `$ref` — an explicit reference to a component\n * schema, as opposed to one minted for an inline object. The two kinds carry\n * the same `{ kind: 'model', name }` shape, so the identity is kept here: a\n * pass that renames an inline model repoints the references minted for it and\n * must leave an explicit reference to a same-named component as written\n * (`isComponentModelRef`). The set is keyed by object identity and every\n * pass between building and emitting mutates refs in place, so it holds.\n */\nconst componentModelRefs = new WeakSet<ModelRef>();\n\n/** Whether `ref` was built from a `$ref` to a component schema rather than minted for an inline object. */\nexport function isComponentModelRef(ref: ModelRef): boolean {\n  return componentModelRefs.has(ref);\n}\n\n/** Record `ref` as built from a `$ref` to a component: for a copy of a marked reference (`cloneTypeRef`), which a structural clone would leave unmarked. */\nexport function markComponentModelRef(ref: ModelRef): void {\n  componentModelRefs.add(ref);\n}\n\n/**\n * The type a `$ref` to the `components/schemas` entry under `key` resolves\n * to, as every site that names the component with a bare `$ref` is typed:\n * a top-level component schema needs to preserve whether the target is a\n * model or an enum, because emitters route imports differently for the two\n * kinds (e.g. com.example.models.X vs com.example.types.X). The set of enum\n * names is precomputed by extractSchemas() in a first pass so it's\n * available even when called recursively for nested $refs. Read by\n * `schemaToTypeRef` for the `$ref` itself and by `resolveSchemaPointers`\n * for the component a pointer enters (#539).\n *\n * Every kind of component carries its own nullability through the\n * reference, so the two spellings of one schema — written inline, or\n * extracted into a component and named by a `$ref` — are typed alike. An\n * array or primitive component is typed from its schema, wrapper included.\n * An enum, a named union or an object component that admits `null` — an\n * OAS 3.1 `type` list naming `'null'`, OAS 3.0 `nullable: true`, a nullable\n * `oneOf`/`anyOf` wrapper, a single-member `allOf` around one of these —\n * is wrapped in `nullable` here, since the enum or model built for it\n * carries no wrapper (`activeNullableEnumSchemaNames`,\n * `activeNullableModelComponentKeys`; #615: `PetOwner: { type: ['object',\n * 'null'], properties }` named by a bare `$ref` was `PetOwner`, while\n * `Pet.owner` written inline, and the JSON Pointer `#/components/schemas/\n * Pet/properties/owner` to it, were `nullable<PetOwner>`). An alias of\n * such a component — an `allOf` read as its `$ref` member, `PetOwnerAlias:\n * { allOf: [{ $ref: PetOwner }] }` — is wrapped as the component is, as the\n * same `allOf` on a field is typed; an `allOf` that merges a typing member\n * beside the `$ref` (`Cat: { allOf: [{ $ref: PetOwner }, { properties }]\n * }`) is the object its fields describe, bare, as it is on a field\n * (`isNullableModelComponentEntry`). This holds at every site typed\n * through `schemaToTypeRef` — a field, array items, map\n * values, a union variant, a body, a parameter, a header, a webhook or\n * callback payload — and a site that wraps the `$ref` itself (`oneOf: [{\n * $ref: PetOwner }, { type: 'null' }]`) is wrapped once (`asNullable`).\n */\nexport function componentTypeRef(key: string): TypeRef {\n  const component =\n    activeComponentSchemas && Object.hasOwn(activeComponentSchemas, key) ? activeComponentSchemas[key] : undefined;\n  // An array component is no model: the reference is the array it\n  // declares, its items typed under the component's name exactly as the\n  // component pass materializes them (`arrayComponentTypeRef`). Looked up\n  // by the key the `$ref` names, before any name-based test: `Notes` is\n  // the array whatever another key resolving to `Note` is.\n  const arrayAlias = arrayComponentTypeRef(key);\n  if (arrayAlias) return arrayAlias;\n  // A primitive component is no model either: the reference is what it\n  // declares, typed as the same schema written inline (an alias resolving\n  // in turn) — the primitive, `format` and nullability included (#512);\n  // the literal of its `const`, the union of its type list, or `unknown`\n  // for a schema that declares no type (#569: `Kind: { type: 'string',\n  // const: 'cat' }`, `Tag: { type: ['string', 'integer'] }` and `Anything:\n  // { description }` were fieldless models, and a `$ref` to each typed as\n  // that model while the same schema inline was `'cat'`, `string |\n  // integer` and `unknown`).\n  const primitive = activePrimitiveComponentKeys.has(key) ? component : undefined;\n  if (primitive) return schemaToTypeRef(primitive);\n  // An alias of an enum component is no model either (#560): the\n  // reference is the enum it names, read through the alias as the same\n  // schema written inline is — `PetKind: { allOf: [{ $ref: Kind }, {\n  // description }] }` is `Kind`, a nullable wrapper around the `$ref` is\n  // `nullable<Kind>`, an alias of an alias resolves in turn — so `{ $ref:\n  // PetKind }` on a field is typed as `{ allOf: [{ $ref: Kind }, {\n  // description }] }` there is.\n  const alias = activeEnumAliasKeys.has(key) ? component : undefined;\n  if (alias) return schemaToTypeRef(alias);\n  const resolved = resolveSchemaName(key);\n  if (activeEnumSchemaNames.has(resolved)) {\n    const enumRef: TypeRef = { kind: 'enum', name: resolved };\n    // Carry the component's own nullability through the reference so\n    // `field: { $ref: NullableEnum }` has the same shape as the inline\n    // `oneOf: [{ $ref }, { type: 'null' }]` form.\n    return activeNullableEnumSchemaNames.has(resolved) ? { kind: 'nullable', inner: enumRef } : enumRef;\n  }\n  // Likewise a model component that admits `null` — a named union with a\n  // `null` variant, or an object component that declares it (#615): neither\n  // the variant nor the declaration is a member of the model, so the\n  // reference carries the nullability — read by the key the `$ref` names,\n  // since two keys can resolve to one model and only the one that admits\n  // `null` wraps its references. The model reference itself is recorded as\n  // a component's (`componentModelRefs`) whether or not it is wrapped.\n  const modelRef: ModelRef = { kind: 'model', name: resolved };\n  componentModelRefs.add(modelRef);\n  return activeNullableModelComponentKeys.has(key) ? { kind: 'nullable', inner: modelRef } : modelRef;\n}\n\n/**\n * The type `schema` is read as (`buildTypeRef`), carrying the limits of the\n * site that writes it (#545): every `primitive`, `literal`, `array`, `map`\n * or `union` the parser builds from a schema carries that schema's\n * validation keywords as `constraints`, read as a field's are\n * (`schemaConstraints`) — a field's own schema, an array's items, a union's\n * variant, a map's values, a parameter's or header's schema, a body, a\n * primitive or array component a `$ref` resolves to — under a nullable\n * wrapper onto its `inner` (`withTypeConstraints`). A `model` or `enum`\n * reference carries none. The builder re-enters here for every nested\n * schema, so each node carries its own site's limits; where it re-enters\n * for a wrapper's branch or an `allOf`'s member — the same site, read one\n * level down — the outer level's reading replaces the branch's, which it\n * accounts for (a wrapper's keywords conjoin with its branch's, a `$ref`\n * site's with its component's, in the one order `Field.constraints` reads\n * them). So a field's `constraints` and its type's are one reading — for a\n * JSON Pointer `$ref` deeper into a component (#539) once\n * `resolveSchemaPointers` settles the site, which conjoins the pointed\n * schema's limits with the site's on the type and the field or parameter\n * alike (#545 review).\n */\nexport function schemaToTypeRef(\n  schema: SchemaObject,\n  contextName?: string,\n  parentModelName?: string,\n  siblingProperties?: ReadonlyMap<string, SchemaObject>,\n  // The inline names an enclosing field's siblings mint, handed down to the\n  // field's array items and map values so a union among them steps around a\n  // sibling's model like a union at field level (`reservedNamesFor`).\n  reservedNames?: ReadonlySet<string>,\n): TypeRef {\n  return withTypeConstraints(\n    buildTypeRef(schema, contextName, parentModelName, siblingProperties, reservedNames),\n    schemaConstraints(schema, documentComponentSchemas()),\n  );\n}\n\n/**\n * The keywords JSON Schema applies to an instance of one type alone, by\n * that type (Validation §6.2–6.5 and the applicators of Core §10.3;\n * `format`, for the three primitives OAS defines formats for): what a\n * per-type copy of a type list keeps for its own type and sheds for every\n * other (`typeListCopy`). A keyword of no family — `const`, `enum`, a\n * composition, `discriminator`, `not`, an annotation, an `x-*` key —\n * applies whatever the instance's type and stays on every copy.\n */\nconst TYPE_FAMILY_KEYWORDS: Readonly<Record<string, readonly string[]>> = {\n  object: [\n    'properties',\n    'required',\n    'additionalProperties',\n    'patternProperties',\n    'propertyNames',\n    'minProperties',\n    'maxProperties',\n    'dependentRequired',\n    'dependentSchemas',\n    'unevaluatedProperties',\n  ],\n  array: [\n    'items',\n    'prefixItems',\n    'additionalItems',\n    'contains',\n    'minContains',\n    'maxContains',\n    'minItems',\n    'maxItems',\n    'uniqueItems',\n    'unevaluatedItems',\n  ],\n  string: ['format', 'pattern', 'minLength', 'maxLength', 'contentEncoding', 'contentMediaType', 'contentSchema'],\n  number: ['format', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'],\n  integer: ['format', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'],\n  boolean: [],\n};\n\n/** The types a `type` keyword names, as a set; `number` admits an `integer` (`admits`). */\nfunction typesNamed(type: string | string[]): ReadonlySet<string> {\n  return new Set(Array.isArray(type) ? type : [type]);\n}\n\n/** Whether `declared` admits an instance of `type`: names it, or names `number` for an `integer`. */\nexport function admits(declared: ReadonlySet<string>, type: string): boolean {\n  return declared.has(type) || (type === 'integer' && declared.has('number'));\n}\n\n/**\n * The JSON types `schema` declares an instance may have: its `type`; a\n * `$ref`'d component's, through a chain of `$ref`s (a cycle, or a `$ref`\n * no component answers, declares none); a `null` schema's `null`\n * (`isNullSchema`); what every member of its `allOf` admits (`Puppy: {\n * allOf: [{ $ref: Dog }] }` declares what `Dog` does, and two members\n * naming different types nothing at all); or what any variant of its\n * `oneOf`/`anyOf` does, when each declares some. `undefined` when it\n * declares none — `{ properties }`, `{ enum: ['a'] }`, `{ description }` —\n * and so admits an instance of every type, as JSON Schema reads it:\n * `properties` constrains an object and says nothing of a string, which\n * is why `Owner: { properties }` beside `type: ['object', 'string']` keeps\n * the `string` (#616) and `Owner: { type: 'object', properties }` excludes\n * it (`typeListCopy`).\n */\nfunction declaredTypes(schema: SchemaObject, seen: Set<SchemaObject> = new Set()): ReadonlySet<string> | undefined {\n  if (seen.has(schema)) return undefined;\n  seen.add(schema);\n  try {\n    if (schema.$ref !== undefined) {\n      const target = componentSchemaOf(schema.$ref);\n      return target === undefined ? undefined : declaredTypes(target, seen);\n    }\n    if (schema.type !== undefined) return typesNamed(schema.type);\n    if (isNullSchema(schema)) return typesNamed('null');\n    if (schema.allOf !== undefined) {\n      let admitted: ReadonlySet<string> | undefined;\n      for (const member of schema.allOf) {\n        const declared = declaredTypes(member, seen);\n        if (declared === undefined) continue;\n        const both = admitted;\n        admitted =\n          both === undefined\n            ? declared\n            : new Set([...both, ...declared].filter((type) => admits(both, type) && admits(declared, type)));\n      }\n      if (admitted !== undefined) return admitted;\n    }\n    const variants = schema.oneOf ?? schema.anyOf;\n    if (variants !== undefined && variants.length > 0) {\n      const admitted = new Set<string>();\n      for (const variant of variants) {\n        const declared = declaredTypes(variant, seen);\n        if (declared === undefined) return undefined;\n        for (const type of declared) admitted.add(type);\n      }\n      return admitted;\n    }\n    return undefined;\n  } finally {\n    seen.delete(schema);\n  }\n}\n\n/** Whether `schema` admits an instance of `type`: it declares no type (`declaredTypes`), or one that admits it. */\nfunction admitsType(schema: SchemaObject, type: string): boolean {\n  const declared = declaredTypes(schema);\n  return declared === undefined || admits(declared, type);\n}\n\n/**\n * Whether `schema` says anything about an instance of `type`: it declares\n * a type admitting it, pins the value (`const`, `enum`), writes a keyword\n * of the type's family (`TYPE_FAMILY_KEYWORDS`: `properties` for an\n * object, `items` for an array, `pattern` for a string), or composes\n * members one of which does — a `$ref` followed to its component, and\n * taken to apply when no component answers it. A `null` schema says\n * nothing of any other type. A member that does not — `{ properties }` or\n * `{ $ref: Owner }` beside a `string` copy, `{ description }` beside any —\n * annotates or constrains an instance of another type and is left off the\n * copy (`typeListCopy`; #616).\n */\nfunction appliesToType(schema: SchemaObject, type: string, seen: Set<SchemaObject> = new Set()): boolean {\n  if (seen.has(schema)) return false;\n  seen.add(schema);\n  try {\n    if (schema.$ref !== undefined) {\n      const target = componentSchemaOf(schema.$ref);\n      return target === undefined || appliesToType(target, type, seen);\n    }\n    if (isNullSchema(schema)) return false;\n    if (schema.type !== undefined) return admits(typesNamed(schema.type), type);\n    if (schema.const !== undefined || schema.enum !== undefined) return true;\n    if ((TYPE_FAMILY_KEYWORDS[type] ?? []).some((keyword) => schema[keyword] !== undefined)) return true;\n    return [schema.allOf, schema.oneOf, schema.anyOf].some(\n      (members) => members?.some((member) => appliesToType(member, type, seen)) ?? false,\n    );\n  } finally {\n    seen.delete(schema);\n  }\n}\n\n/**\n * `schema` read as `type`, one entry of its type list (#616): a copy with\n * `type` set to that entry, carrying the keywords that apply to an instance\n * of it. A type list says the instance is one of the types named, and JSON\n * Schema applies each keyword to the instances of its own type alone\n * (`TYPE_FAMILY_KEYWORDS`), so the `object` copy of `{ type: ['object',\n * 'string'], properties }` is the object with those properties and the\n * `string` copy is `{ type: 'string' }` — `NoteAuthor | string` for the\n * issue's `inline.json`. A composition is read against `type` member by\n * member, and kept or left off whole: a member that declares a type\n * excluding `type` (`declaredTypes`: its own, its component's, its own\n * composition's) admits no instance of it, so an `allOf` with such a\n * member leaves no copy at all (`undefined`), as does a `oneOf`/`anyOf`\n * whose every variant is one. On an `object` or `array` copy — one the\n * extractor builds models for (`buildsModels`), from the schema's\n * composition read whole as a merge or a reference — a composition some\n * member of which says something about an instance of `type`\n * (`appliesToType`) stays as written, never trimmed to those members,\n * since a copy reading a composition of its own would reference a model\n * nobody builds (Greptile, #616 review: `allOf: [{ properties: { name } },\n * { items }]` beside `['array', 'string']` was `array<NoteAuthor>` for an\n * array copy keeping the `items` member alone, while the extractor merged\n * `NoteAuthor { name }`); one no member of which says anything about an\n * instance of `type` is left off when the copy is then a bare type — an\n * object or array declaring no schema of its own (`declaresOwnSchemas`) —\n * and kept otherwise, so `{ type: ['array', 'string'], items, allOf: [{\n * $ref: Owner }] }` is `Owner | string`, the reference the `allOf` beside\n * the items is, not an array of items no extractor builds. A primitive\n * copy, which nothing of reaches the extractor, keeps of an `allOf` the\n * members that say something about its type alone (#616 review): `{ type:\n * ['object', 'string'], allOf: [{ $ref: Owner }, { minLength: 1 }] }` with\n * `Owner` untyped is `Owner | string`, the `string` copy keeping `{\n * minLength: 1 }` and shedding the `$ref` as it does when the keyword sits\n * beside the list, and `['string', 'integer']` beside the same `allOf` is\n * `string | integer` — not `Owner` and `Owner | integer`, the `$ref`\n * typing the `string` copy because a member beside it applied. A\n * `oneOf`/`anyOf` is kept whole while any variant applies, so the union\n * it types keeps the shape the document wrote. So `Note.author: { type: ['object',\n * 'string'], allOf: [{ $ref: Owner }] }` is `Owner | string` when `Owner`\n * declares `properties` and no `type` — its `properties` say nothing of a\n * string — and `Owner` alone when `Owner` is `type: 'object'`, which no\n * string satisfies. Before, every copy kept every keyword, so the `string`\n * copy was typed by the `allOf` as the `object` copy was, and the field\n * was `Owner | Owner`. `overrides` are spread over the copy before `type`\n * is set; the copy stands for `schema` (`derivedCopy`), so a merge the\n * schema carries is the one the extractor is building for the schema\n * itself (`materializingMergedAllOfName`; #566 review).\n */\nfunction typeListCopy(\n  schema: SchemaObject,\n  type: string,\n  overrides: Partial<SchemaObject> = {},\n): SchemaObject | undefined {\n  const copy: SchemaObject = { ...schema, ...overrides, type };\n  const own = TYPE_FAMILY_KEYWORDS[type] ?? [];\n  for (const [family, keywords] of Object.entries(TYPE_FAMILY_KEYWORDS)) {\n    if (family === type) continue;\n    for (const keyword of keywords) if (!own.includes(keyword)) delete copy[keyword];\n  }\n  for (const keyword of ['allOf', 'oneOf', 'anyOf'] as const) {\n    const members = schema[keyword];\n    if (members === undefined || members.length === 0) continue;\n    const excluding = members.filter((member) => !admitsType(member, type)).length;\n    if (keyword === 'allOf' ? excluding > 0 : excluding === members.length) return undefined;\n    const applying = members.filter((member) => appliesToType(member, type));\n    if (keyword === 'allOf' && !buildsModels(type)) {\n      // A primitive copy keeps the members that say something about its\n      // type alone: nothing of it reaches the extractor, so nothing can\n      // disagree with what it builds.\n      if (applying.length === 0) delete copy.allOf;\n      else if (applying.length < members.length) copy.allOf = applying;\n    } else if (applying.length === 0 && !declaresOwnSchemas(copy)) {\n      // Kept or left off whole, never trimmed to the members that apply.\n      delete copy[keyword];\n    }\n  }\n  return derivedCopy(copy, schema);\n}\n\n/** Whether the extractor builds models for a copy of `type` — an object's, or an array's items — so its composition must stay the one the extractor reads. */\nfunction buildsModels(type: string): boolean {\n  return type === 'object' || type === 'array';\n}\n\n/** The keywords under which a schema declares schemas of its own — an inline object, items, values — that an extractor builds models for. */\nconst OWN_SCHEMA_KEYWORDS: readonly string[] = [\n  'properties',\n  'additionalProperties',\n  'patternProperties',\n  'items',\n  'prefixItems',\n  'contains',\n];\n\n/**\n * Whether `copy` declares a schema of its own (`OWN_SCHEMA_KEYWORDS`), so\n * that a composition left off it would leave the copy typed by those\n * schemas alone — items, values, properties the extractor, reading the\n * composition beside them, never builds a model for (`typeListCopy`).\n */\nfunction declaresOwnSchemas(copy: SchemaObject): boolean {\n  return OWN_SCHEMA_KEYWORDS.some((keyword) => copy[keyword] !== undefined);\n}\n\n/** Whether `schema`'s `type` is a list naming several types besides `null` — the lists `buildTypeRef` reads as a union of per-type copies (`typeListCopies`; #616). */\nexport function namesSeveralTypes(schema: SchemaObject): boolean {\n  return Array.isArray(schema.type) && schema.type.filter((type) => type !== 'null').length > 1;\n}\n\n/**\n * The per-type copies a type list naming several types is read as: one per\n * non-null entry, in the list's order (`typeListCopy`), less the entries\n * the schema's composition excludes. A list no entry of which survives —\n * `type: ['string', 'integer']` beside `allOf: [{ $ref: Owner }]` with\n * `Owner` an object — contradicts itself and is read as written: every\n * entry, every keyword on each, so the `allOf` types each copy and the\n * union holds `Owner` once (`dedupeTypeRefs`). Read by `buildTypeRef` to\n * type the list and by `typesAsUnknown` to answer for it without typing.\n */\nfunction typeListCopies(schema: SchemaObject): SchemaObject[] {\n  const types = (Array.isArray(schema.type) ? schema.type : []).filter((type) => type !== 'null');\n  const copies = types\n    .map((type) => typeListCopy(schema, type))\n    .filter((copy): copy is SchemaObject => copy !== undefined);\n  return copies.length > 0 ? copies : types.map((type) => derivedCopy({ ...schema, type }, schema));\n}\n\n/**\n * `variants` with each repeat of an earlier one dropped — a model or enum\n * reference repeated by name, any other type by shape (`stableStringify`,\n * limits and all) — so a union never holds one type twice: the copies of a\n * type list one keyword types alike (`{ type: ['string', 'integer'], enum:\n * ['a', 1] }` is the one enum, not that enum twice; #616).\n */\nfunction dedupeTypeRefs(variants: readonly TypeRef[]): TypeRef[] {\n  const seen = new Set<string>();\n  return variants.filter((variant) => {\n    const key =\n      variant.kind === 'model' || variant.kind === 'enum'\n        ? `${variant.kind}:${variant.name}`\n        : stableStringify(variant);\n    if (seen.has(key)) return false;\n    seen.add(key);\n    return true;\n  });\n}\n\n/**\n * `schemaToTypeRef` without the site's limits: the shape of the type, every\n * nested schema typed through `schemaToTypeRef` itself. A type list naming\n * several types is the union of its per-type copies (`typeListCopies`),\n * never one type twice, a lone copy the type itself (`dedupeTypeRefs`;\n * #616).\n */\nfunction buildTypeRef(\n  schema: SchemaObject,\n  contextName?: string,\n  parentModelName?: string,\n  siblingProperties?: ReadonlyMap<string, SchemaObject>,\n  reservedNames?: ReadonlySet<string>,\n): TypeRef {\n  // Handle $ref → ModelRef or EnumRef.\n  // A `$ref` that names a component — exactly `#/components/schemas/<key>`\n  // — is typed by that key (`componentTypeRef`). One that names no\n  // component is typed as the schema it points at is typed where it stands,\n  // which no reader knows until every model is built, so it is a reference\n  // settled in place once they are (`resolveSchemaPointers`; #539): a\n  // pointer deeper into a component (`#/components/schemas/Pet/properties/\n  // owner`, `PetOwner`, the model `Pet.owner` is built as; `Pets/items`,\n  // the array component's items; `Pet/properties/id`, `string`), or a\n  // `$ref` into another section, which that pass reports and types\n  // `unknown`. Before, the last token was taken for a component's key, so\n  // `Pet/properties/owner` named a model `Owner` that nothing declared, or\n  // an unrelated component `Owner`, without a word.\n  if (schema.$ref) {\n    const key = componentKeyOf(schema.$ref);\n    return key === undefined ? pendingSchemaRef(String(schema.$ref)) : componentTypeRef(key);\n  }\n\n  // Handle OAS 3.1 nullable type arrays: type: [string, null]\n  if (Array.isArray(schema.type)) {\n    const nonNullTypes = schema.type.filter((t: string) => t !== 'null');\n    // type: ['null'] — only null, no real type\n    if (nonNullTypes.length === 0) {\n      return { kind: 'nullable', inner: { kind: 'primitive', type: 'unknown' } };\n    }\n    // Keep `parentModelName` through the unwrap so an inline object, map\n    // value, or enum under a nullable field is qualified exactly like its\n    // non-nullable twin — the inline-model extractor names it that way.\n    if (schema.type.includes('null') && nonNullTypes.length === 1) {\n      return asNullable(\n        schemaToTypeRef(\n          derivedCopy({ ...schema, type: nonNullTypes[0], nullable: false }, schema),\n          contextName,\n          parentModelName,\n          siblingProperties,\n          reservedNames,\n        ),\n      );\n    }\n    // Multiple non-null types → union of one variant per type the schema is\n    // read as (`typeListCopies`): each per-type copy keeps the keywords that\n    // apply to an instance of its type and is left out when the schema's\n    // composition admits none of it (`typeListCopy`; #616), a type two\n    // copies are typed alike as is one variant (`dedupeTypeRefs`), and a\n    // single variant is the type itself: `{ type: ['object', 'string'],\n    // allOf: [{ $ref: Owner }] }` is `Owner | string`, or `Owner` when\n    // `Owner` is `type: 'object'` — not `Owner | Owner`. The schema's\n    // limits are the union's (`schemaToTypeRef` attaches them to it), not\n    // each variant's: a variant is the same schema read as one of its\n    // types, so the limits are read from the union, once, for whichever\n    // type the value takes (#545) — or, once the list collapses to one\n    // variant, from that type where it can carry them: a model or enum\n    // reference carries none, as the same limits beside a bare `$ref` carry\n    // none (Greptile, #616 review: `items: { type: ['object', 'string'],\n    // allOf: [{ $ref: Owner }], minProperties: 2 }` is `Owner[]`, as\n    // `items: { allOf: [{ $ref: Owner }], minProperties: 2 }` is). The\n    // variants are built without them\n    // (`buildTypeRef`); what they nest — items, values — carries its own.\n    // Each per-type copy stands for the schema it was spread from\n    // (`derivedCopy`), so a merge the schema carries (`allOf` beside `type:\n    // ['object', 'string']`) is the one the extractor is building for the\n    // schema itself (`materializingMergedAllOfName`; #566 review).\n    if (nonNullTypes.length > 1) {\n      const variants = dedupeTypeRefs(\n        typeListCopies(schema).map((copy) =>\n          buildTypeRef(copy, contextName, parentModelName, siblingProperties, reservedNames),\n        ),\n      );\n      const ref: TypeRef = variants.length === 1 ? variants[0]! : { kind: 'union', variants };\n      return schema.type.includes('null') ? asNullable(ref) : ref;\n    }\n  }\n\n  // Handle OAS 3.0 nullable flag. The copy stands for the schema it was\n  // spread from (`derivedCopy`), as the extractor's strip of the same\n  // wrapper does, so both meet one key for a merge under it.\n  if (schema.nullable && schema.type) {\n    return asNullable(\n      schemaToTypeRef(\n        derivedCopy({ ...schema, nullable: false }, schema),\n        contextName,\n        parentModelName,\n        siblingProperties,\n        reservedNames,\n      ),\n    );\n  }\n\n  // From here on the nullable wrappers are gone. `properties` written beside\n  // a typing `allOf`/`oneOf`/`anyOf` are folded into it (the extractors\n  // dispatch on the same fold, through `unwrapNullableSchema`), the variants\n  // that cannot take them reported, and then one classification decides\n  // which keyword types the schema — the same one the inline-model\n  // extractors dispatch on, so the models they build are the ones referenced.\n  // A schema no branch below types is `unknown` — decided by\n  // `typesAsUnknown`, the one answer a reader that must know before typing\n  // asks (`bodyTypesAsUnknown`, for the primary response) — with a warning for a\n  // shape the parser does not read; an empty `{}` describes nothing on\n  // purpose and is not reported.\n  if (typesAsUnknown(schema)) {\n    if (contextName && !describesNothing(schema)) {\n      console.warn(`[oagen] Warning: Unknown schema shape treated as unknown (context: ${contextName})`);\n    }\n    return { kind: 'primitive', type: 'unknown' };\n  }\n\n  warnOnUncarriedProperties(schema, contextName, parentModelName);\n  schema = foldSiblingProperties(schema);\n  const inlineKind = classifyInlineSchema(schema);\n\n  // Handle allOf, read the one way every site reads it (`readInlineAllOf`):\n  // a merged model — a `$ref` member augmented by an inline object member,\n  // or inline members one of which declares properties, a `oneOf`/`anyOf`\n  // member's inline object variants included — which `materializeMergedAllOf`\n  // builds under this very name; a lone member unwrapped; or a plain\n  // reference to the first `$ref` member.\n  if (inlineKind === 'allOf' && schema.allOf) {\n    const reading = readInlineAllOf(schema.allOf, schema);\n    if (reading === 'merged') {\n      // A merge the extractor is building a model for on the path to this\n      // one — the conjunction a component that extends itself through a\n      // field its inline member redeclares owns in every merge — is that\n      // model: the re-entry under this name would build nothing (#566).\n      const building = materializingMergedAllOfName(schema);\n      if (building !== undefined) return { kind: 'model', name: building };\n      const baseName = toPascalCase(contextName ?? 'UnknownModel');\n      return { kind: 'model', name: qualifyInlineModelName(baseName, parentModelName) };\n    }\n    if (reading === 'reference') {\n      const refItem = schema.allOf.find((s: SchemaObject) => s.$ref);\n      // `'reference'` is only read with a `$ref` member among the members an\n      // `allOfTypesSchema` admits, so one is found here.\n      if (refItem) return schemaToTypeRef(refItem, contextName, parentModelName);\n    } else {\n      // A single member, or the one member that types the schema beside\n      // members that only annotate or limit it, its items documented by a\n      // member's `items` that declare no type (`annotatedTypingMember`;\n      // #555), unwrapped. The wrapper is the schema the document wrote, and\n      // those members are part of it (`allOfWrapperLayer`), so its\n      // documentation rides onto the member — an inline enum lifted from it\n      // carries the wrapper's `description` and link (`withWrapperDocs`),\n      // and a model built from it the wrapper's link (`unwrappedAllOfMember`).\n      return schemaToTypeRef(\n        withWrapperDocs(annotatedTypingMember(schema), allOfWrapperLayer(schema)),\n        contextName,\n        parentModelName,\n        siblingProperties,\n        reservedNames,\n      );\n    }\n    // Unreachable: `allOfTypesSchema` admits only the three readings above.\n    // An `allOf` of bare limits is classified from the schema's own keywords.\n  }\n\n  // Handle oneOf / anyOf → Union or Nullable\n  // Valid OAS 3.1: properties can have { oneOf: [{ type: object }, { type: 'null' }] }\n  // without a wrapping `type` field.\n  if (inlineKind === 'union') {\n    const compositionKind: 'oneOf' | 'anyOf' = schema.oneOf ? 'oneOf' : 'anyOf';\n    const rawVariants: SchemaObject[] = schema.oneOf ?? schema.anyOf ?? [];\n\n    // Check for nullable pattern: oneOf: [realType, { type: 'null' }]. Every\n    // `null` variant is set aside, however many and however spelled\n    // (`isNullSchema`), as `nullableUnionBranch` sets them aside.\n    const nonNullVariants = rawVariants.filter((v) => !isNullSchema(v));\n    const hasNull = nonNullVariants.length < rawVariants.length;\n\n    // Collapse an oneOf/anyOf whose non-null variants are all string-const\n    // schemas into a single enum. This turns patterns like\n    //   provider: { oneOf: [{ const: \"AppleOAuth\" }, { const: \"GitHubOAuth\" }, ...] }\n    // into a proper enum type with one member per variant instead of a\n    // structurally-opaque union of literal refs. Each member keeps its\n    // variant's `description` and `deprecated` (`constUnionEnumMembers`), the\n    // way the same `oneOf` under `components.schemas` does (`extractEnum`).\n    // An `enum:` list beside the union restricts the members and `null`\n    // alike, through the two helpers the component path reads\n    // (`constUnionEnumMembers`, `enumListAdmitsNull`), whatever it leaves:\n    // one member is an enum of that member, none an enum with no members —\n    // the component's answers — never the union of every const the list\n    // forbade, nor the nullable literal the single-variant unwrap below would\n    // make of `oneOf: [a, null]` when the list forbids `null`; so this is\n    // decided first. Without a list, a union of fewer than two consts keeps\n    // the shape the branches below give it (a lone const beside\n    // `type: 'null'` is a nullable literal).\n    // Whether this union is such an enum is the one decision the predictor\n    // that reserves enum names before typing reads too (`inlineEnumSpelling`).\n    const constUnion = inlineEnumSpelling(schema);\n    if (constUnion?.spelling === 'const-union') {\n      const enumRef = buildSyntheticEnumRef(\n        constUnion.members,\n        contextName,\n        parentModelName,\n        schema.externalDocs,\n        schema.description,\n        extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS),\n      );\n      // An `enum:` list beside the union that leaves `null` out forbids it,\n      // whatever the `type: 'null'` variant says (`enumListAdmitsNull`).\n      return hasNull && enumListAdmitsNull(schema) ? { kind: 'nullable', inner: enumRef } : enumRef;\n    }\n\n    if (hasNull && nonNullVariants.length === 1) {\n      // Nullable single type — unwrap as nullable. `asNullable` keeps a\n      // `$ref` to an already-nullable enum component from double-wrapping.\n      // The wrapper's `description` and link ride onto the branch\n      // (`withWrapperDocs`), so an inline enum under a nullable wrapper lifts\n      // with the wrapper's text and link; the model the extractor builds from\n      // the same branch takes the wrapper's link (`unwrapNullableField`).\n      return asNullable(\n        schemaToTypeRef(\n          withWrapperDocs(nonNullVariants[0], schema),\n          contextName,\n          parentModelName,\n          siblingProperties,\n          reservedNames,\n        ),\n      );\n    }\n\n    // The inline object variants' model names, decided once for this TypeRef\n    // and every extractor (`nameInlineVariants`): variant 0's bare qualified\n    // field name, a const prefix, a title, a distinguishing property or a\n    // counter — or, for a title-mapped `oneOf` (3. below), the title itself\n    // — never a name a sibling property mints. Computed first because the\n    // derived discriminator mappings below are read from it, so a mapping\n    // can only point at a model that exists.\n    const inlineVariantNames = nameInlineObjectVariants(\n      schema,\n      contextName,\n      parentModelName,\n      siblingProperties,\n      reservedNames,\n    );\n\n    // The variants as a named union reads them (`unionMembers`): an inline\n    // object variant named by its model, a `$ref` variant by its component,\n    // with its const read from that component, and a variant wrapping one\n    // model `$ref` (`oneOf: [{ $ref: Bird }, { $ref: Song }]`, `Song` an\n    // enum) through that reference (#568). Without a context name nothing is\n    // extracted for an inline object variant (`nonObjectVariantContexts`),\n    // so it is named by its title alone, as before naming.\n    const componentSchemas = documentComponentSchemas();\n    const members = unionMembers(\n      schema,\n      contextName === undefined ? NO_INLINE_NAMES : inlineVariantNames,\n      componentSchemas,\n    );\n\n    // Resolve the discriminator. Three sources, in order — the ones a named\n    // union reads (`namedUnionDiscriminator`), from the same members:\n    //   1. Explicit `discriminator:` with explicit `mapping:` — trust the\n    //      spec, each target as the document spelled it (`inlineMappingTargets`).\n    //   2. Explicit `discriminator:` with no `mapping:` — pair each variant's\n    //      const value on the property with its model name\n    //      (`unionConstMapping`); `{}` when any variant pins none or is\n    //      unnamed. This covers `ApiKey.owner`-shaped schemas where the spec\n    //      uses `discriminator: { propertyName: type }` but lists inline\n    //      anonymous `oneOf` variants instead of `$ref` links, and a\n    //      `oneOf: [{ $ref: Cat }, { $ref: Dog }]` under the keyword alike.\n    //   3. No explicit discriminator, `oneOf` only — when every variant is\n    //      named and one const property tells them all apart\n    //      (`implicitUnionDiscriminator`): the mapping names a `$ref` variant\n    //      by its component and an inline variant by the name\n    //      `nameInlineVariants` gave it — its title (`Circle`, `Square`)\n    //      unless that is taken, else a const prefix\n    //      (`ApiKeyCreatedData.owner`: `ApiKeyCreatedDataOwner`,\n    //      `UserApiKeyCreatedDataOwner`) — so the extracted model and the\n    //      mapping agree.\n    let resolvedDiscriminator: { property: string; mapping: Record<string, string> } | undefined;\n    if (schema.discriminator) {\n      const property = schema.discriminator.propertyName;\n      const explicit = inlineMappingTargets(schema.discriminator.mapping);\n      const mapping =\n        Object.keys(explicit).length > 0 ? explicit : (unionConstMapping(members, property, componentSchemas) ?? {});\n      resolvedDiscriminator = { property, mapping };\n    } else if (compositionKind === 'oneOf') {\n      resolvedDiscriminator = implicitUnionDiscriminator(members, componentSchemas);\n    }\n\n    // Build variants. An inline object variant is referenced by the name its\n    // extracted model carries (`inlineVariantNames`); a discriminator mapping\n    // entry substitutes for it only when the spec's own `mapping:` (1.) names\n    // the variant, since the derived mappings (2.–3.) are read from the same\n    // names. Falling back to `schemaToTypeRef` instead would hand every\n    // inline variant the same parent-derived name (e.g. `ApiKeyOwner`),\n    // collapsing the union onto one repeated model ref while the extractor\n    // emits `ApiKeyOwner`, `UserApiKeyOwner`, ... for them.\n    // The named ref replaces only the `object` member of what `schemaToTypeRef`\n    // would build for the variant: a nullable variant (`['object', 'null']`,\n    // OAS 3.0 `nullable: true`) keeps its wrapper, and a multi-type variant\n    // (`['object', 'string']`) keeps its other alternatives in a union — see\n    // `inlineVariantTypeRef`. The extractor emits the model under the same\n    // name in every case, and a multi-type variant's other members are named\n    // from that model, not from the mapping, so their items resolve.\n    const variants: TypeRef[] = [];\n    // Every other variant that mints a name — an array or map, a nested\n    // union, a nullable wrapper around an object, an `allOf`, an inline enum\n    // — is typed under the context `nonObjectVariantContexts` gives it, so\n    // the models and enums it mints never share a name with an object\n    // variant of the same union, which keeps the field's own name, nor with\n    // another such variant's. The extractors re-enter with the same contexts.\n    const variantContexts = nonObjectVariantContexts(\n      contextName,\n      rawVariants,\n      siblingProperties,\n      parentModelName,\n      inlineVariantNames,\n      reservedNames,\n    );\n    for (const v of nonNullVariants) {\n      const inlineName = inlineVariantNames.get(v);\n      if (inlineName) {\n        const mappedName = resolvedDiscriminator ? mapVariantToDiscriminatorEntry(v, resolvedDiscriminator) : null;\n        // The variant's own limits ride on the union of a multi-type variant\n        // (#545), attached by `inlineVariantTypeRef` for every site.\n        variants.push(inlineVariantTypeRef(v, inlineName, mappedName ?? inlineName));\n      } else {\n        // A union of one variant stays a union, but it is the schema the\n        // document wrote for its variant: the variant is typed with the\n        // union's documentation by the one wrapper rule (`withWrapperDocs`),\n        // so an inline enum it lifts to documents itself as under a nullable\n        // wrapper. The lookups read the variant as written. A reader that\n        // follows this decision without typing — a request body's doc text —\n        // takes it from `loneUnionVariant`.\n        const typed = nonNullVariants.length === 1 ? withWrapperDocs(v, schema) : v;\n        const entry = variantContexts.get(v);\n        variants.push(\n          entry\n            ? schemaToTypeRef(typed, entry.context, parentModelName, undefined, entry.reserved)\n            : schemaToTypeRef(typed, contextName, parentModelName),\n        );\n      }\n    }\n    // An explicit entry written as a pointer is settled to the model the\n    // pointed schema is built as — with the variant written as that\n    // pointer, or on its own (`deferPointerMappingEntries`; #539, #619):\n    // its stripped target names no variant.\n    const written = schema.discriminator?.mapping;\n    if (resolvedDiscriminator && written) {\n      deferPointerMappingEntries(\n        written,\n        members,\n        variants,\n        resolvedDiscriminator.mapping,\n        documentComponentSchemas(),\n        inlineMappingTarget,\n      );\n    }\n    const union: TypeRef = {\n      kind: 'union',\n      variants,\n      compositionKind,\n      ...(resolvedDiscriminator ? { discriminator: resolvedDiscriminator } : {}),\n    };\n    return hasNull ? { kind: 'nullable', inner: union } : union;\n  }\n\n  // Handle const → LiteralType (supports string, number, boolean)\n  if (inlineKind === 'const') {\n    if (typeof schema.const === 'string' || typeof schema.const === 'number' || typeof schema.const === 'boolean') {\n      return { kind: 'literal', value: schema.const };\n    }\n    // null const → nullable unknown\n    if (schema.const === null) {\n      return { kind: 'nullable', inner: { kind: 'primitive', type: 'unknown' } };\n    }\n    // const of object/array → map or array with unknown values\n    if (typeof schema.const === 'object') {\n      if (Array.isArray(schema.const)) {\n        return { kind: 'array', items: { kind: 'primitive', type: 'unknown' } };\n      }\n      return { kind: 'map', valueType: { kind: 'primitive', type: 'unknown' } };\n    }\n  }\n  // A `null` member of an inline `enum:` marks nullability, not a value.\n  // Strip it before deciding literal-vs-enum, and wrap the result so a\n  // bare `type: 'string', enum: ['a', null]` is nullable even without a\n  // `type: [..., 'null']` array (the array branch above already wrapped\n  // us when present; `asNullable` keeps that from doubling up).\n  const enumValues = nonNullEnumValues(schema.enum);\n  const enumAdmitsNull = schema.enum !== undefined && enumValues.length !== schema.enum.length;\n  if (inlineKind === 'enum' && enumValues.length === 1) {\n    const v = enumValues[0];\n    const literal: TypeRef = { kind: 'literal', value: typeof v === 'number' ? v : String(v) };\n    return enumAdmitsNull ? asNullable(literal) : literal;\n  }\n\n  // Handle enum — the `enum-list` spelling of the one decision the predictor\n  // that reserves enum names before typing reads too (`inlineEnumSpelling`);\n  // the single-member list was returned as a literal above.\n  if (inlineEnumSpelling(schema)?.spelling === 'enum-list') {\n    // Named by the one rule every inline enum follows (`inlineEnumName`):\n    // qualified by the parent with its list-item markers stripped, no\n    // redundant prefix, the project's `schemaNameTransform` applied. The\n    // schema's `description`, link and extensions and each value's\n    // `x-enum-descriptions` / `x-enumDescriptions` entry are recorded against\n    // the ref so the lifted `Enum` carries them (`collectInlineEnumFromRef`);\n    // the nullable unwraps above spread the schema, so a wrapped enum's text,\n    // link and keys reach here too.\n    const enumRef = inlineEnumRef(\n      inlineEnumName(contextName, parentModelName),\n      enumListMembers(schema) ?? [],\n      schema.externalDocs,\n      schema.description,\n      extensionsOf(schema, SCHEMA_CONSUMED_EXTENSIONS),\n    );\n    return enumAdmitsNull ? asNullable(enumRef) : enumRef;\n  }\n\n  // Handle array — pass parentModelName through to qualify inline items. The\n  // items' context is the field itself, or `<field>_item` when a sibling\n  // property would take the singular name (`elementContextName`), so an\n  // inline object item is `<Parent><Field>` or `<Parent><Field>Item`. The\n  // items get no sibling set of their own (they are not a property), but a\n  // union among them must still step around the models the field's siblings\n  // mint, so that set is handed down (`reservedNamesFor`), exactly as the\n  // extractor passes it into its items re-entry.\n  if (inlineKind === 'array' && schema.items) {\n    return {\n      kind: 'array',\n      items: schemaToTypeRef(\n        schema.items,\n        elementContext(contextName, 'item', siblingProperties, parentModelName, schema.items),\n        parentModelName,\n        undefined,\n        reservedNamesFor(contextName, siblingProperties, parentModelName, reservedNames),\n      ),\n    };\n  }\n\n  // Handle object → ModelRef (if it has properties, it's a named model reference,\n  // with `type: 'object'`, no `type`, or a type list naming `object`).\n  // When additionalProperties is also present, we still return a ModelRef so the\n  // named properties are preserved. The extractModel path will pick up the extra\n  // properties as a catch-all map field named `additionalProperties`.\n  if (inlineKind === 'object') {\n    const baseName = toPascalCase(contextName ?? 'UnknownModel');\n    return {\n      kind: 'model',\n      name: qualifyInlineModelName(baseName, parentModelName),\n    };\n  }\n\n  // Handle freeform object with additionalProperties or patternProperties → Map<string, T>\n  // The value schema is typed with the field's own `contextName` and\n  // `parentModelName`, exactly like array items, so an inline object value is\n  // referenced as `${Parent}${SingularField}` (`layers` on\n  // `CreateDrawingRequest` → `CreateDrawingRequestLayer`) and the inline-model\n  // extractor (`extractInlineModelsFromProperties`) emits a model of that name.\n  // When a sibling property would take that singular name the values use\n  // `<field>_value` instead (`<Parent><Field>Value`, see `elementContextName`).\n  if (inlineKind === 'map') {\n    // `mapValueSchema` picks the value schema in this branch's precedence: a\n    // non-empty `additionalProperties` object, else the first\n    // `patternProperties` entry; `additionalProperties: {}` or `true` means\n    // \"any value\" and stays unknown.\n    let valueType: TypeRef = { kind: 'primitive', type: 'unknown' };\n    const valueSchema = mapValueSchema(schema);\n    if (valueSchema) {\n      const valueContext = elementContext(contextName, 'value', siblingProperties, parentModelName, valueSchema);\n      // Like array items: the field's sibling reservations reach the values.\n      valueType = schemaToTypeRef(\n        valueSchema,\n        valueContext,\n        parentModelName,\n        undefined,\n        reservedNamesFor(contextName, siblingProperties, parentModelName, reservedNames),\n      );\n    }\n    return {\n      kind: 'map',\n      valueType,\n    };\n  }\n\n  // Handle primitives\n  const typeStr = Array.isArray(schema.type) ? schema.type[0] : schema.type;\n  if (typeStr && PRIMITIVE_TYPES[typeStr]) {\n    return {\n      kind: 'primitive',\n      type: PRIMITIVE_TYPES[typeStr],\n      ...(schema.format ? { format: schema.format } : {}),\n    };\n  }\n\n  // Unreachable: every shape no branch above types was answered at the top\n  // (`typesAsUnknown` holds exactly for those).\n  return { kind: 'primitive', type: 'unknown' };\n}\n\n/** The `type` keywords `schemaToTypeRef` reads as a primitive, and the primitive each becomes. */\nconst PRIMITIVE_TYPES: Record<string, 'string' | 'integer' | 'number' | 'boolean'> = {\n  string: 'string',\n  integer: 'integer',\n  number: 'number',\n  boolean: 'boolean',\n};\n\n/** An empty schema — `{}`, or one with annotations only: none of the keywords that type a schema. */\nfunction describesNothing(schema: SchemaObject): boolean {\n  return (\n    !schema.type &&\n    !schema.$ref &&\n    !schema.oneOf &&\n    !schema.anyOf &&\n    !schema.allOf &&\n    !schema.enum &&\n    !schema.properties &&\n    !schema.items\n  );\n}\n\n/**\n * Whether `schemaToTypeRef` types `schema` as the bare `unknown` primitive,\n * decided without typing it — the one answer, which `schemaToTypeRef`\n * itself returns on, so a reader that must know before a body is typed\n * (`bodyTypesAsUnknown`, choosing the primary response, which asks here\n * only where classification ends on `schemaToTypeRef`) never disagrees\n * with the type it then gets. It holds for a schema no branch of `schemaToTypeRef`\n * types: no `$ref`; no type list except one naming a single type without\n * `null` (an empty list is `nullable<unknown>`, `null` beside one type is\n * nullable) or several types each of whose per-type copies is such a\n * schema (`typeListCopies`: the copies the list's composition admits,\n * typed alike as one, so `['weird', 'weirder']` is `unknown` and\n * `['string', 'integer']` a union; #616); no `nullable: true` beside a\n * `type`; then, once sibling properties are folded into a typing\n * composition (`foldSiblingProperties`), a classification of `other`\n * (`classifyInlineSchema`: no composition, union, `const`, `enum`, array,\n * object or map) with no primitive `type` — `{}`, `{ nullable: true }`, a\n * `type` no rule knows, `type: 'array'` without `items`, a bare\n * `additionalProperties` without `type: 'object'` — or an `allOf` member\n * read as the schema itself (`readInlineAllOf`: `'unwrapped'` — a lone\n * member, or the one typing member beside annotating ones:\n * `allOfTypingMember`) that is such a schema. Warns about nothing.\n */\nexport function typesAsUnknown(schema: SchemaObject): boolean {\n  if (schema.$ref) return false;\n  if (Array.isArray(schema.type)) {\n    const nonNullTypes = schema.type.filter((t: string) => t !== 'null');\n    if (nonNullTypes.length === 0 || schema.type.includes('null')) return false;\n    // Several types: the union of their copies, bare `unknown` exactly when\n    // every copy is — the copies the composition admits, one of each type\n    // (`typeListCopies`; #616).\n    if (nonNullTypes.length > 1) return typeListCopies(schema).every((copy) => typesAsUnknown(copy));\n  }\n  if (schema.nullable && schema.type) return false;\n  const folded = foldSiblingProperties(schema);\n  const kind = classifyInlineSchema(folded);\n  if (kind === 'allOf' && folded.allOf) {\n    return readInlineAllOf(folded.allOf, folded) === 'unwrapped' && typesAsUnknown(annotatedTypingMember(folded));\n  }\n  if (kind !== 'other') return false;\n  const typeStr = Array.isArray(folded.type) ? folded.type[0] : folded.type;\n  return !(typeStr && PRIMITIVE_TYPES[typeStr]);\n}\n\nimport {\n  allOfTypingMember,\n  allOfWrapperLayer,\n  annotatedTypingMember,\n  annotatingAllOfMembers,\n  buildInlineModel,\n  collectProperties,\n  declarationKeywords,\n  declareProperty,\n  declareVariant,\n  declaresInlineProperties,\n  declaresType,\n  elementContextName,\n  extractInlineModelsFromProperties,\n  extractInlineModelsFromSchemas,\n  firstFreeElementContext,\n  isContestedTitle,\n  mapValueSchema,\n  markContestedTitles,\n  materializingMergedAllOfName,\n  readInlineAllOf,\n  unionOfDeclarations,\n  unwrappedAllOfMember,\n  agreedExtensions,\n  withAgreedExtensions,\n  type MintedInlineName,\n  mintedChildNameEntries,\n  mintedInlineNameEntries,\n  mintedInlineNames,\n  modelFingerprint,\n  type PropertyDeclarations,\n  extendsParentName,\n  qualifyInlineModelName,\n  recordLiftedFieldModel,\n  reservedInlineNames,\n  resetCombinedDeclarations,\n  resetInheritedModelRefs,\n  schemaShapeKey,\n  stableStringify,\n} from './inline-models.js';\n\nexport { qualifyInlineModelName, extractInlineModelsFromSchemas } from './inline-models.js';\n","import { createHash } from 'node:crypto';\nimport type {\n  Enum,\n  HttpMethod,\n  Model,\n  ModelRef,\n  Parameter,\n  RequestBodyContent,\n  Service,\n  TypeRef,\n  Webhook,\n  WebhookResponse,\n} from '../ir/types.js';\nimport {\n  collectModelTypeRefs,\n  collectOperationTypeRefs,\n  collectWebhookTypeRefs,\n  renameTypeRefModels,\n  walkTypeRef,\n} from '../ir/types.js';\nimport { foldParameterName, parameterKey } from '../ir/parameter-key.js';\nimport { numberedName, numberedProperty, toPascalCase } from '../utils/naming.js';\nimport { mediaTypeNameFragment, mediaTypeNamingOrder } from '../utils/media-type.js';\nimport type { SchemaObject } from './schemas.js';\nimport { isComponentModelRef, schemaToTypeRef } from './schemas.js';\nimport {\n  cloneTypeRef,\n  extractInlineModelsFromProperties,\n  modelFingerprint,\n  qualifyInlineModelName,\n  shapeFingerprint,\n  type InlineModelBundle,\n} from './inline-models.js';\nimport {\n  HTTP_METHODS,\n  extractParams,\n  extractTags,\n  isIgnoredHeaderParameter,\n  namesNothing,\n  operationIdModelBase,\n  parameterSchema,\n  presentText,\n  requestBodyDescriptionOf,\n  resolveOperationDocs,\n  resolveParameterRef,\n  resolveRequestBodyRef,\n  schemalessRequestBodyType,\n  schemalessRequestContentType,\n  selectRequestBodyContent,\n  warnUnreadParameterContent,\n  warnUnreadRequestBody,\n  type DeclaredCallbacks,\n  type OperationObject,\n  type ParameterObject,\n  type PathItem,\n  type RequestBodyObject,\n} from './operations.js';\nimport { externalDocsEntry } from './external-docs.js';\nimport { resolvePathItemRef } from './path-item-refs.js';\nimport { followReference, type SiblingDocs } from './reference-objects.js';\nimport { isResponseEntry, isResponsesObject } from './response-refs.js';\nimport { classifyResponseKey, warnUnrecognizedResponseKey } from './responses.js';\nimport { extractSecurityRequirements } from './security.js';\n\n/** The `components` sections webhook extraction resolves references against. */\nexport interface WebhookComponents {\n  schemas?: Record<string, SchemaObject>;\n  parameters?: Record<string, Record<string, unknown>>;\n  requestBodies?: Record<string, Record<string, unknown>>;\n  responses?: Record<string, Record<string, unknown>>;\n  examples?: Record<string, Record<string, unknown>>;\n  /**\n   * `components.pathItems` (OpenAPI 3.1), which a webhook entry's `$ref` may\n   * point into, as it may name another `webhooks` or `paths` entry.\n   */\n  pathItems?: Record<string, Record<string, unknown>>;\n  /** `components.callbacks`, which a `callbacks` entry's `$ref` may point into (`extractCallbacks`; #382). */\n  callbacks?: Record<string, Record<string, unknown>>;\n}\n\nexport interface WebhookExtractionResult {\n  /** One entry per (webhook key, HTTP method), in document order. */\n  webhooks: Webhook[];\n  /** Models materialized from inline payload and parameter schemas, to merge into `ApiSpec.models`. */\n  inlineModels: Model[];\n  /**\n   * Where those models came from: one site per group of entries that share\n   * a minting, qualified by the group's stem and owning every reference of\n   * every webhook in the group — its payload and its parameters\n   * (`collectWebhookTypeRefs`) — so a merge pass that must rename one of the\n   * models (a payload variant titled like a component of another shape)\n   * repoints exactly those, as it does an operation's (`InlineModelBundle`).\n   */\n  inlineModelBundles: InlineModelBundle[];\n  /**\n   * Every `callbacks` map a webhook's operation declares, in webhook order,\n   * for `extractCallbacks` to read once every webhook is named (#382).\n   */\n  declaredCallbacks: DeclaredCallbacks[];\n}\n\n/**\n * What a received request is read from: a (key, method) of the `webhooks`\n * map, or a (key, expression, method) of a `callbacks` map (#382). Names\n * the noun in diagnostics (`a webhook has no path`, `callback operation`)\n * and the word put in front of a stem that would be empty or start with a\n * digit (`Webhook2FaEnabledPayload`, `Callback2FaEnabledPayload`).\n */\nexport type ReceivedRequestKind = 'webhook' | 'callback';\n\n/**\n * One (key, method) pair of the `webhooks` map — or, for a callback, one\n * (key, expression, method) of a `callbacks` map — with its references\n * resolved. Every reader below takes one of these, so a webhook and a\n * callback are typed, named and built by one code path.\n */\nexport interface WebhookEntry {\n  kind: ReceivedRequestKind;\n  /** The `webhooks` key, or the `callbacks` key, verbatim. */\n  name: string;\n  method: HttpMethod;\n  op: OperationObject;\n  /**\n   * The path item the operation sits on — the entry itself, or the\n   * Path Item its `$ref` leads to — whose `summary` and\n   * `description` apply to the operation (`resolveOperationDocs`).\n   */\n  pathItem: PathItem;\n  /** The webhook's own parameters after path-item-level ones, deduplicated by (in, name). */\n  params: ParameterObject[];\n  body: RequestBodyObject | undefined;\n  /** `webhooks.<name>.<method>`, or `<owner label>.callbacks.<name>.<expression>.<method>`, for diagnostics. */\n  label: string;\n  /** How many methods the entry's path item declares; a second one qualifies a key-derived stem. */\n  methodCount: number;\n  /**\n   * The operationId the stem is named from: the operation's own, when it\n   * names something (`namesNothing`; #564) and no different operation\n   * object among the entries read together declares the same one (see\n   * `settleStemOperationIds`). Absent, the stem comes from the key.\n   */\n  stemOperationId?: string;\n  /** A callback's runtime expression, verbatim (`{$request.body#/callbackUrl}`); absent on a webhook. */\n  expression?: string;\n  /**\n   * How many expressions the Callback Object declares; a second one\n   * qualifies a key-derived stem with the expression PascalCased, as a\n   * second method qualifies it with the method. Absent on a webhook.\n   */\n  expressionCount?: number;\n  /**\n   * The stem of the operation, webhook or callback that declares the\n   * callback, which a key-derived stem is prefixed with: `CreatePet` +\n   * `petAdopted` → `CreatePetPetAdopted`. An operation's or webhook's\n   * settled stem (`DeclaredCallbacks.stem`); a parent callback's plain stem\n   * before any collision hash (`plainStemOf`), since every callback of the\n   * document is named in one batch. Absent on a webhook, whose key stands\n   * alone.\n   */\n  parentStem?: string;\n  /**\n   * What a key-named callback's collision hash is taken from\n   * (`stemIdentity`): its owner's identity — an operation's operationId,\n   * else `METHOD /path`; a webhook's or a callback's operationId when its\n   * stem is named from one, else that node's own identity — followed by\n   * `.callbacks.<key>.<expression>.<method>`, the shape of `label`. The\n   * label itself names the site the entry was read at, which for a shared\n   * callback operation differs per site; the identity does not, so a group\n   * read at several sites hashes alike whichever site comes first (#382).\n   * Absent on a webhook, and on a callback read outside `extractCallbacks`,\n   * where the label stands in.\n   */\n  identity?: string;\n  /**\n   * The callback entry whose operation declares this one; absent on a\n   * webhook and on an operation's or webhook's own callback. The chain of\n   * parents is the entry's depth (`depthOf`) and its ancestry: a name a\n   * descendant mints under a stem of its own never moves an ancestor's\n   * stem, and a group is minted at its shallowest member's depth, after\n   * every group shallower than it (`buildReceivedRequests`).\n   */\n  parent?: WebhookEntry;\n}\n\n/** How many callbacks sit between the declaring operation or webhook and `entry`: 0 for a webhook or a direct callback. */\nfunction depthOf(entry: WebhookEntry): number {\n  let depth = 0;\n  for (let parent = entry.parent; parent !== undefined; parent = parent.parent) depth++;\n  return depth;\n}\n\n/** What one stem mints for a webhook: its typed parameters and payload, and the models behind them. */\ninterface MintedWebhook {\n  headerParams: Parameter[];\n  queryParams: Parameter[];\n  cookieParams: Parameter[];\n  requestBody?: TypeRef;\n  requestBodyEncoding?: Webhook['requestBodyEncoding'];\n  requestBodyContentType?: string;\n  requestBodyContentTypes?: string[];\n  requestBodyContents?: RequestBodyContent[];\n  inlineModels: Model[];\n  /** Every model and inline-enum name the webhook minted (see `mintSchema`). */\n  names: Set<string>;\n}\n\n/** The part of a minting a `Webhook` carries: its typed parameters and payload. */\ntype MintedShape = Pick<\n  MintedWebhook,\n  | 'headerParams'\n  | 'queryParams'\n  | 'cookieParams'\n  | 'requestBody'\n  | 'requestBodyEncoding'\n  | 'requestBodyContentType'\n  | 'requestBodyContentTypes'\n  | 'requestBodyContents'\n>;\n\n/**\n * Read the document's top-level `webhooks` map (OpenAPI 3.1) into the IR.\n *\n * Each key names a path item, and each HTTP method on it is one `Webhook`,\n * in document order. The key is kept verbatim as `Webhook.name`, one\n * starting with `x-` included: OpenAPI gives the `webhooks` map no\n * specification extensions, unlike `paths`, so `x-pet-returned` is a webhook\n * like any other (#421). An entry that is a `$ref` into\n * `components/pathItems`, or to another `webhooks` or `paths` entry\n * (`#/webhooks/petAdopted`, `#/paths/~1pets`; #422), is resolved (chains\n * included, with a cycle guard) by `resolvePathItemRef`, the resolver a\n * `paths` entry goes through too; one that points anywhere else, or that\n * cannot be resolved, is warned about and skipped rather than failing the\n * parse, as is an entry that is not an object. A `webhooks` value that is not an object\n * at all is warned about and ignored. Nothing is read from `x-webhooks`, the\n * pre-3.1 convention: the parser reads the standard key only.\n *\n * Parameters and request bodies go through the same resolvers and extractors\n * as operations (`components/parameters` and `components/requestBodies` refs\n * resolved, path-item-level parameters overridden by operation-level ones of\n * the same identity), so a malformed reference fails the parse the way it\n * does on an operation. A `path` parameter has nowhere to go — a webhook has\n * no path — and is dropped with a warning; an `Accept`, `Content-Type` or\n * `Authorization` header is ignored, as OpenAPI requires and as on an\n * operation (`isIgnoredHeaderParameter`). A response that is a `$ref` into\n * `components/responses` is followed for its description.\n *\n * The payload schema is typed and materialized as the `payload` property of a\n * synthetic object named by the webhook's stem (see\n * `resolveWebhookModelStems`), through the same `schemaToTypeRef` /\n * `extractInlineModelsFromProperties` pair that names component fields and\n * response unions. An inline object therefore becomes `<Stem>Payload` with\n * its nested objects under it (`<Stem>PayloadPet`); a `oneOf` of inline\n * objects stays a union whose variants are named as any field-level union's\n * are, discriminator intact, because an event handler switches on it; a\n * `$ref` stays a reference; an inline enum takes the same name and is\n * promoted by `collectInlineEnumsFromWebhooks`. Nothing is flattened. An\n * inline object on a parameter is materialized the same way, under the name\n * `extractParams` references it by (`<Stem>XMeta`).\n *\n * `reservedNames` is every model and enum name already decided — see\n * `collectExistingNames` — so a webhook never mints a name one of them owns,\n * and `reservedEnumNames` the enums among them (`collectExistingEnumNames`),\n * which no webhook model may take even where the stem cannot move it.\n *\n * A webhook operation's `callbacks` are not read here: each map is\n * recorded (`declaredCallbacks`) with the webhook's label and stem for\n * `extractCallbacks` to read once every webhook is named, so a callback's\n * models step around the webhooks' too (#382).\n */\nexport function extractWebhooks(\n  webhooks: unknown,\n  components: WebhookComponents = {},\n  reservedNames: Iterable<string> = [],\n  reservedEnumNames: Iterable<string> = [],\n  // Whether text written beside a `$ref` into `components/parameters`,\n  // `requestBodies`, `responses` or `examples` overrides the component's\n  // (OAS 3.1) or is ignored (OAS 3.0): the document's mode, as the operations\n  // read it (`siblingDocsMode`), applied to every Reference Object here.\n  siblingDocs: SiblingDocs = 'override',\n  // The document's `paths` map, as written, whose entries a webhook entry's\n  // `$ref` may name (`resolvePathItemRef`), as it may name another webhook's.\n  paths?: unknown,\n): WebhookExtractionResult {\n  if (webhooks === undefined) return { webhooks: [], inlineModels: [], inlineModelBundles: [], declaredCallbacks: [] };\n  if (!isRecord(webhooks)) {\n    console.warn('[oagen] Warning: Top-level `webhooks` is not an object; ignoring it.');\n    return { webhooks: [], inlineModels: [], inlineModelBundles: [], declaredCallbacks: [] };\n  }\n\n  const entries = collectWebhookEntries(webhooks, components, siblingDocs, paths);\n  const reserved: ReservedNames = { all: new Set(reservedNames), enums: new Set(reservedEnumNames) };\n  const { built, inlineModels, inlineModelBundles } = buildReceivedRequests(entries, components, reserved, siblingDocs);\n  // Each webhook's `callbacks`, read after every webhook is named, under\n  // the webhook's label and the stem its own models took.\n  const declaredCallbacks: DeclaredCallbacks[] = built\n    .filter(({ entry }) => entry.op.callbacks !== undefined)\n    .map(({ entry, node, stem }) => ({\n      owner: node,\n      callbacks: entry.op.callbacks,\n      label: entry.label,\n      stem,\n      // Two keys sharing one path item with an operationId are one identity.\n      identity: entry.stemOperationId ?? entry.label,\n    }));\n  return { webhooks: built.map(({ node }) => node), inlineModels, inlineModelBundles, declaredCallbacks };\n}\n\n/** What `buildReceivedRequests` made of a batch of entries. */\nexport interface BuiltReceivedRequests {\n  /** One node per entry, in entry order, with the entry and the stem its models were named from. */\n  built: Array<{ entry: WebhookEntry; node: Webhook; stem: string }>;\n  /** The models the batch minted, to merge into `ApiSpec.models`. */\n  inlineModels: Model[];\n  /** Where those models came from (see `WebhookExtractionResult.inlineModelBundles`). */\n  inlineModelBundles: InlineModelBundle[];\n  /** Every model and inline-enum name the batch minted, for a later batch to reserve. */\n  names: Set<string>;\n}\n\n/**\n * Name, mint and build one batch of entries — the `webhooks` map's, or\n * every callback of the document (`extractCallbacks`) — against `reserved`,\n * in three phases. The entries are grouped first (`groupEntries`): those\n * that resolve to one operation object and are named from its operationId,\n * and key-named callbacks reading one object under one plain stem, mint\n * once and share the minting, whatever depths their members sit at; every\n * other entry mints on its own. The stems are then settled once, in one\n * resolution over every group at every depth (`resolveWebhookModelStems`),\n * exactly as the `webhooks` map's are: a name a group would mint that the\n * document already holds, or that another group also mints, hashes its\n * stem from its identity, the reserved-name hits and the collisions decided\n * together, so both of a colliding pair move and a group's stem never\n * depends on which depths reference it, nor on how the groups nest: a\n * group of one plain stem with another is its peer, referenced directly,\n * nested inside it, or both, and both hash. The one rule the `webhooks`\n * map never exercises: a name a descendant mints under a stem of its own\n * never moves an ancestor's stem — a nested callback's payload landing on\n * its parent's parameter model moves the nested stem alone — so a nested\n * callback added renames nothing above it. (The resolution compares the\n * names minted, not the stems, so without that rule the parent's parameter\n * model would move the nested payload and the nested payload the parent's\n * stem alike.) Two groups that each nest a reference to the other are\n * peers again, neither protected. Minting then proceeds ancestors first, in waves by each group's\n * shallowest member's depth (`depthOf`, 0 for a webhook): every group with\n * a member at depth 0, then those at depth 1, and so on, each wave minted\n * against the reserved names and every name the waves before minted, where\n * a name still taken — a spent hash, an enum an earlier wave minted —\n * steps aside at mint time; a group that spans depths is one minting,\n * named at its shallowest depth and reused by its deeper members (#382).\n * Last, for a callback batch, whatever let two groups mint one name for\n * two shapes past all that moves every group minting it, each on its own\n * stem (`separateMintedNames`); one shape under one name is the merge's to\n * share. The\n * outcome depends only on the document, never on the order its entries\n * are read in, and a document without callbacks names its webhooks as it\n * always has.\n *\n * The nodes come back in entry order, not group order: a shared\n * operation's second key keeps its own place. A group's owner takes the\n * minted parameters and payload as they are; every other member gets its\n * own copy, so no two nodes share IR nodes — a copy that keeps each\n * reference's provenance (`cloneMintedShape`), so a `$ref` to a component\n * stays one on every member when a merge pass renames the group's models.\n * Each group's models are one site (`inlineModelBundles`): every member's\n * references, the copies included, so a rename reaches every node that\n * shares the minting and nothing else. The bundle is recorded before any\n * callback is attached to a node, so it owns the node's own references and\n * not a nested callback's, which has a bundle of its own.\n */\nexport function buildReceivedRequests(\n  entries: WebhookEntry[],\n  components: WebhookComponents,\n  reserved: ReservedNames,\n  siblingDocs: SiblingDocs,\n): BuiltReceivedRequests {\n  const { groups, groupOf } = groupEntries(entries);\n  // The groups a group descends from: those of its members' parents, at\n  // every remove. None for the `webhooks` map.\n  const ancestorsOf = new Map<WebhookGroup, Set<WebhookGroup>>();\n  for (const group of groups) {\n    const ancestors = new Set<WebhookGroup>();\n    for (const entry of group.entries) {\n      for (let parent = entry.parent; parent !== undefined; parent = parent.parent) {\n        const ancestor = groupOf.get(parent);\n        if (ancestor !== undefined && ancestor !== group) ancestors.add(ancestor);\n      }\n    }\n    ancestorsOf.set(group, ancestors);\n  }\n  // The stems, settled once over every group at every depth, reserved-name\n  // hits and collisions decided together as the `webhooks` map's are: both\n  // of a colliding pair move, whichever depths reference them and however\n  // they nest — a group of one plain stem with another is its peer, direct\n  // or nested or both. The one rule the `webhooks` map never exercises: a\n  // name a descendant mints under a stem of its own never moves an\n  // ancestor's stem, so the descendant is the one that hashes.\n  const plainStems = new Map(groups.map((group) => [group, plainStem(group.owner, '')]));\n  // What each group's collision hash is taken from: one record per group\n  // the settling, every wave and the catch-all share and raise together.\n  const identities = groupIdentities(groups);\n  /**\n   * Whether a name `other` mints may move `group`'s stem: it may when the\n   * plain stems agree, when neither group is a strict descendant of the\n   * other, or when each descends from the other — mutual ancestry makes\n   * them peers, neither protected: `petEvent`, whose union mints\n   * `ReturnedPetEventPayload`, and `returnedPetEvent`, whose body wants\n   * that name, each nesting a reference to the other (the cycle guard\n   * stops each walk one level down), both hash as two `webhooks` keys\n   * would. Only a name a strict descendant mints under a stem of its own\n   * never moves its ancestor's stem.\n   */\n  const contends = (group: WebhookGroup, other: WebhookGroup): boolean =>\n    plainStems.get(other) === plainStems.get(group) ||\n    !ancestorsOf.get(other)!.has(group) ||\n    ancestorsOf.get(group)!.has(other);\n  const settled = resolveWebhookModelStems(groups, reserved, components, siblingDocs, identities, undefined, contends);\n  // Each group's wave: its shallowest member's depth.\n  const waveOf = new Map(groups.map((group) => [group, Math.min(...group.entries.map(depthOf))] as const));\n  const waves = [...new Set(waveOf.values())].sort((a, b) => a - b);\n  // What every wave steps around at mint time: the reserved names, and the\n  // names and enums the waves before minted.\n  const all = new Set(reserved.all);\n  const enums = new Set(reserved.enums);\n  const stems = new Map<WebhookGroup, string>();\n  const hashLength = new Map<WebhookGroup, number>();\n  const reservedOf = new Map<WebhookGroup, ReservedNames>();\n  const mintedByGroup = new Map<WebhookGroup, MintedWebhook>();\n  for (const wave of waves) {\n    const waveGroups = groups.filter((group) => waveOf.get(group) === wave);\n    // One reserved set for the wave's step-around and its minting, so what\n    // the step-around minted is what is kept; the next wave reserves it.\n    const waveReserved: ReservedNames = { all: new Set(all), enums: new Set(enums) };\n    const resolved = resolveWebhookModelStems(\n      waveGroups,\n      waveReserved,\n      components,\n      siblingDocs,\n      identities,\n      settled,\n      contends,\n    );\n    for (const group of waveGroups) {\n      const stem = resolved.stems.get(group)!;\n      const minted = mintWebhook(group.owner, stem, components, waveReserved, siblingDocs);\n      stems.set(group, stem);\n      hashLength.set(group, resolved.hashLength.get(group) ?? 0);\n      reservedOf.set(group, waveReserved);\n      mintedByGroup.set(group, minted);\n      for (const name of minted.names) all.add(name);\n      for (const name of mintedEnumNames(minted)) enums.add(name);\n    }\n  }\n  // The groups in minting order: by wave, then as the document declares them.\n  const order = waves.flatMap((wave) => groups.filter((group) => waveOf.get(group) === wave));\n  if (entries[0]?.kind === 'callback') {\n    separateMintedNames(\n      order,\n      stems,\n      hashLength,\n      mintedByGroup,\n      reservedOf,\n      reserved,\n      identities,\n      components,\n      siblingDocs,\n    );\n  }\n  const inlineModels = order.flatMap((group) => mintedByGroup.get(group)!.inlineModels);\n  const names = new Set(order.flatMap((group) => [...mintedByGroup.get(group)!.names]));\n\n  const built: BuiltReceivedRequests['built'] = [];\n  const nodesByGroup = new Map<WebhookGroup, Webhook[]>();\n  for (const entry of entries) {\n    const group = groupOf.get(entry)!;\n    const minted = mintedByGroup.get(group)!;\n    const shape: MintedShape = {\n      headerParams: minted.headerParams,\n      queryParams: minted.queryParams,\n      cookieParams: minted.cookieParams,\n      requestBody: minted.requestBody,\n      requestBodyEncoding: minted.requestBodyEncoding,\n      requestBodyContentType: minted.requestBodyContentType,\n      requestBodyContentTypes: minted.requestBodyContentTypes,\n      requestBodyContents: minted.requestBodyContents,\n    };\n    const node = buildWebhook(entry, entry === group.owner ? shape : cloneMintedShape(shape), components, siblingDocs);\n    built.push({ entry, node, stem: stems.get(group)! });\n    nodesByGroup.set(group, [...(nodesByGroup.get(group) ?? []), node]);\n  }\n\n  const inlineModelBundles: InlineModelBundle[] = [];\n  for (const group of groups) {\n    const minted = mintedByGroup.get(group)!;\n    if (minted.inlineModels.length === 0) continue;\n    inlineModelBundles.push({\n      qualifier: toPascalCase(stems.get(group)!),\n      roots: (nodesByGroup.get(group) ?? []).flatMap((node) => collectWebhookTypeRefs(node)),\n      models: minted.inlineModels,\n    });\n  }\n\n  return { built, inlineModels, inlineModelBundles, names };\n}\n\n/**\n * The catch-all after a callback batch is minted, independent of what the\n * resolution counted: no two groups may mint one model or enum name for\n * two shapes, whatever let the collision through — a title-mapped union\n * variant, which embeds no stem and so no stem hash moves\n * (`resolveWebhookModelStems`), a hash coincidence, a spent hash. A name\n * two groups mint for one shape — the model's with `deprecated` read\n * apart, an enum's values (`mintedShape`), the way the merge decides a\n * clash — is left to the model merge, which shares the one model, as two\n * webhooks' identical variants are shared. A contested name moves EVERY\n * group minting it, each on its own identity and stem, so the outcome\n * never depends on which was declared first: a name that embeds a group's\n * stem is moved as the resolution moves one, the stem settled with six\n * more characters of its input's hash — or, hashing one string as another\n * minter of the name, with its source put in front of the text\n * (`partsBy`) — and the group minted again; one the hash cannot move is\n * renamed under the group's stem\n * (`<Stem><Name>`, numbered when that is taken too) with every reference\n * minted for it repointed through `renameTypeRefModels`, as the merge\n * passes rename, so\n * an explicit `$ref` to a component of the name — a parameter's union over\n * `components/schemas` — and the mapping entry it owns stay untouched.\n * Every contested name of a round is decided together: each replacement\n * is chosen against the names the round leaves occupied — the names\n * reserved before the batch, every name still minted once the round's\n * vacations are taken out (never a wave's old snapshot, which holds names\n * an earlier wave has since vacated — a nested callback under `d` must\n * not keep `CreatePetAShape` occupied for `a`), plus the replacements\n * already chosen — in identity order, never in the order the groups were\n * declared, so a name another group vacates is free to take whichever came\n * first: under `createPet`, `a` and `b` with differing variants titled\n * `Shape` beside `c` and `d` with differing variants titled\n * `CreatePetAShape` give `a` `CreatePetAShape`, the name `c` and `d`\n * leave, in either order, never `CreatePetAShape2` in one and\n * `CreatePetAShape` in the other. A group's renames of a round are applied\n * as one map over the models captured before any rename, in two passes\n * through names no real name spells, so a replacement never becomes a\n * source: `Shape` renamed to `<S>Shape` beside a variant titled\n * `<S>Shape` under a spent-hash stem `S` leaves two models, each union\n * reference on its own. The check runs again until no name is\n * contested. A contested inline enum name once the hash is spent cannot be\n * moved — nothing renames an enum reference — and is warned about and left\n * to the model merge, never merged silently.\n *\n * The `webhooks` map is not held to this: the one name the resolution\n * leaves two webhooks sharing is a title-mapped variant, which the model\n * merge shares when the shapes agree and renames otherwise, as it always\n * has, and a document without callbacks names its webhooks as before. A\n * callback batch — nested, shared across depths, its stems built on its\n * owners' — is held to the stricter rule (#382).\n */\nfunction separateMintedNames(\n  order: WebhookGroup[],\n  stems: Map<WebhookGroup, string>,\n  hashLength: Map<WebhookGroup, number>,\n  mintedByGroup: Map<WebhookGroup, MintedWebhook>,\n  reservedOf: Map<WebhookGroup, ReservedNames>,\n  /** The names reserved before the batch — what a replacement steps around beside the names still minted. */\n  reserved: ReservedNames,\n  identities: Map<WebhookGroup, HashIdentity>,\n  components: WebhookComponents,\n  siblingDocs: SiblingDocs,\n): void {\n  // The names warned about, left to the merge.\n  const given = new Set<string>();\n  for (;;) {\n    // Every name two or more groups mint, with the groups, in minting order.\n    const minters = new Map<string, WebhookGroup[]>();\n    for (const group of order) {\n      for (const name of mintedByGroup.get(group)!.names) minters.set(name, [...(minters.get(name) ?? []), group]);\n    }\n    // Every contested name — minted by two groups whose shapes disagree;\n    // identical shapes are the merge's to share, as two webhooks' are —\n    // decided together, one round at a time, so no replacement depends on\n    // the order the groups were declared in.\n    const contested = [...minters].filter(\n      ([name, groups]) =>\n        groups.length >= 2 &&\n        !given.has(name) &&\n        new Set(groups.map((group) => mintedShape(mintedByGroup.get(group)!, name))).size > 1,\n    );\n    if (contested.length === 0) return;\n    // Of a contested name's minters the hash moves, those hashed already\n    // that hash one string as another minter of the name — a key and an\n    // operationId of one text, which six more characters would never part —\n    // put their source in front of the text instead (`partsBy`), decided\n    // for every contested name of the round before any is applied, and are\n    // minted again at the length they have; a name that raises any of its\n    // minters moves those alone by the hash, their new inputs parting them\n    // from the rest, which the next round takes up if still contested.\n    const raisedBy = new Map(\n      contested.map(([name, groups]) => [\n        name,\n        new Set(\n          groups.filter(\n            (group) =>\n              (hashLength.get(group) ?? 0) > 0 &&\n              name.includes(toPascalCase(stems.get(group)!)) &&\n              groups.some((other) => other !== group && partsBy(identities.get(group)!, identities.get(other)!)),\n          ),\n        ),\n      ]),\n    );\n    const raised = new Set([...raisedBy.values()].flatMap((groups) => [...groups]));\n    for (const group of raised) identities.get(group)!.level += 1;\n    // How each minter of a contested name moves: a group whose stem the\n    // name embeds — raised, or with hash to spare where the name raises\n    // none of its minters — hashes once this round and mints again; a model\n    // the hash does not move is renamed; an inline enum of a spent hash\n    // cannot move — nothing renames an enum reference.\n    const hashing = new Set<WebhookGroup>();\n    const renaming: Array<{ group: WebhookGroup; name: string }> = [];\n    const stuck = new Map<string, Set<WebhookGroup>>();\n    for (const [name, groups] of contested) {\n      const raisedHere = raisedBy.get(name)!;\n      for (const group of groups) {\n        const stem = toPascalCase(stems.get(group)!);\n        const spare = (hashLength.get(group) ?? 0) < SHA1_HEX_LENGTH;\n        if (name.includes(stem) && (raisedHere.has(group) || (raisedHere.size === 0 && spare))) hashing.add(group);\n        else if (mintedByGroup.get(group)!.inlineModels.some((m) => m.name === name)) renaming.push({ group, name });\n        else stuck.set(name, new Set([...(stuck.get(name) ?? []), group]));\n      }\n    }\n    // The hash moves a stem on the group's input alone: six more characters\n    // — or, raised, as many of the new input's — minted again, the new\n    // names the hash's and no one else's. A group hashing this round\n    // renames nothing this round: its names are minted afresh, and a titled\n    // one still contested is renamed next round.\n    for (const group of hashing) {\n      const length = hashLength.get(group) ?? 0;\n      const next = raised.has(group) ? length : Math.min(SHA1_HEX_LENGTH, length + 6);\n      const hashed = plainStem(group.owner, webhookDisambiguator(hashInput(identities.get(group)!), next));\n      hashLength.set(group, next);\n      stems.set(group, hashed);\n      mintedByGroup.set(group, mintWebhook(group.owner, hashed, components, reservedOf.get(group)!, siblingDocs));\n    }\n    // A rename is chosen against the names this round leaves occupied —\n    // the names reserved before the batch, every name still minted once\n    // the round's vacations are taken out (never a wave's old snapshot,\n    // which holds names an earlier wave has since vacated), plus the\n    // replacements already chosen — in identity order, never declaration\n    // order, so a name another group vacates is free to take whichever\n    // came first.\n    const vacated = new Set(\n      contested\n        .filter(([name, groups]) =>\n          groups.every((group) => hashing.has(group) || renaming.some((r) => r.group === group && r.name === name)),\n        )\n        .map(([name]) => name),\n    );\n    const occupied = new Set(reserved.all);\n    for (const group of order) {\n      for (const name of mintedByGroup.get(group)!.names) if (!vacated.has(name)) occupied.add(name);\n    }\n    // The models to rename, captured before any rename, with each group's\n    // renames gathered into one map, so a replacement that spells another\n    // contested name of the group — `Shape` renamed to `<S>Shape` beside a\n    // variant titled `<S>Shape` under a spent-hash stem `S` — never\n    // becomes a source.\n    // Identity order reads a group's text, then its source — a key and an\n    // operationId of one text are two identities (#580) — then the name.\n    const byIdentity = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n    const identityOf = (group: WebhookGroup): StemIdentity => identities.get(group)!.identity;\n    const pending = renaming\n      .filter(({ group }) => !hashing.has(group))\n      .sort(\n        (a, b) =>\n          byIdentity(identityOf(a.group).text, identityOf(b.group).text) ||\n          byIdentity(identityOf(a.group).source, identityOf(b.group).source) ||\n          byIdentity(a.name, b.name),\n      );\n    const renamesOf = new Map<WebhookGroup, Map<string, string>>();\n    const modelsOf = new Map<WebhookGroup, Array<{ model: Model; to: string }>>();\n    for (const { group, name } of pending) {\n      const minted = mintedByGroup.get(group)!;\n      const model = minted.inlineModels.find((m) => m.name === name)!;\n      const stem = toPascalCase(stems.get(group)!);\n      let to = `${stem}${name}`;\n      for (let n = 2; occupied.has(to); n++) to = numberedName(`${stem}${name}`, n);\n      occupied.add(to);\n      renamesOf.set(group, new Map([...(renamesOf.get(group) ?? []), [name, to]]));\n      modelsOf.set(group, [...(modelsOf.get(group) ?? []), { model, to }]);\n    }\n    // Each group renamed under its stem, every reference minted for it\n    // repointed — an explicit `$ref` to a component of the name, and the\n    // mapping entry it owns, stay — in two passes through names no real\n    // name spells, so a replacement that spells another source of the\n    // group is never followed on, however many times one reference object\n    // is reached (a payload's reference is its content entry's too).\n    const admit = (ref: ModelRef): boolean => !isComponentModelRef(ref);\n    const staged = (name: string): string => `\\u0000${name}`;\n    for (const [group, renames] of renamesOf) {\n      const minted = mintedByGroup.get(group)!;\n      for (const { model, to } of modelsOf.get(group)!) model.name = to;\n      const passes = [\n        new Map([...renames].map(([from]) => [from, staged(from)])),\n        new Map([...renames].map(([from, to]) => [staged(from), to])),\n      ];\n      for (const pass of passes) {\n        for (const other of minted.inlineModels) {\n          for (const ref of collectModelTypeRefs(other)) renameTypeRefModels(ref, pass, admit);\n        }\n        for (const ref of mintedShapeRefs(minted)) renameTypeRefModels(ref, pass, admit);\n      }\n      for (const [from, to] of renames) {\n        minted.names.delete(from);\n        minted.names.add(to);\n      }\n    }\n    // A name none of whose minters could move is left to the merge, once.\n    for (const [name, groups] of stuck) {\n      if (!minters.get(name)!.every((group) => groups.has(group))) continue;\n      const sites = [...groups].map((group) => `\"${group.owner.label}\"`).join(', ');\n      console.warn(\n        `[oagen] Warning: Callbacks ${sites} each mint an inline enum \"${name}\" with different values, and no hash parts them; leaving them to the model merge.`,\n      );\n      given.add(name);\n    }\n  }\n}\n\n/**\n * What the groups minting `name` are compared on, the way the merge decides\n * a clash: a model's shape with `deprecated` read apart\n * (`shapeFingerprint`); an inline enum's values.\n */\nfunction mintedShape(minted: MintedWebhook, name: string): string {\n  const model = minted.inlineModels.find((m) => m.name === name);\n  if (model !== undefined) return `model:${shapeFingerprint(model)}`;\n  let values: string | undefined;\n  for (const ref of [...minted.inlineModels.flatMap(collectModelTypeRefs), ...mintedShapeRefs(minted)]) {\n    walkTypeRef(ref, {\n      enum: (r) => {\n        if (r.name === name && r.values) values ??= JSON.stringify(r.values);\n      },\n    });\n  }\n  return `enum:${values ?? ''}`;\n}\n\n/** Every reference a minting's shape holds: its parameters' types, its payload and its content entries' types. */\nfunction mintedShapeRefs(minted: MintedWebhook): TypeRef[] {\n  return [\n    ...[...minted.headerParams, ...minted.queryParams, ...minted.cookieParams].map((param) => param.type),\n    ...(minted.requestBody ? [minted.requestBody] : []),\n    ...(minted.requestBodyContents ?? []).map((content) => content.type),\n  ];\n}\n\n/**\n * Every inline enum name a minting produced — an enum reference carrying\n * its `values`, in a minted model's field or in the shape's own references\n * — which a later wave's model may not take (`ReservedNames.enums`).\n */\nfunction mintedEnumNames(minted: MintedWebhook): Set<string> {\n  const names = new Set<string>();\n  const refs: TypeRef[] = [...minted.inlineModels.flatMap(collectModelTypeRefs), ...mintedShapeRefs(minted)];\n  for (const ref of refs) {\n    walkTypeRef(ref, {\n      enum: (r) => {\n        if (r.values) names.add(r.name);\n      },\n    });\n  }\n  return names;\n}\n\n/**\n * Every model and enum name the rest of the parse has decided before webhooks\n * are extracted, for `extractWebhooks` to reserve: each model's name, each\n * enum's name, and every model or enum a model field or an operation refers\n * to (parameters, bodies, responses, errors, pagination envelopes, response\n * headers), inline enums included since their names are already fixed in the\n * references that carry them. A superset is harmless — a referenced name is\n * one that exists — and keeps the check from depending on which pass minted\n * what.\n */\nexport function collectExistingNames(\n  models: Model[],\n  services: Service[],\n  enums: Enum[],\n  webhooks: readonly Webhook[] = [],\n): Set<string> {\n  return collectExistingNamesByKind(models, services, enums, webhooks).all;\n}\n\n/**\n * The enum names among `collectExistingNames`: each enum's name, and every\n * enum a model field or an operation refers to, inline enums included. A\n * webhook model may never take one of these (`mintSchema`): a model and an\n * enum under one name would reach an emitter as one public symbol.\n */\nexport function collectExistingEnumNames(\n  models: Model[],\n  services: Service[],\n  enums: Enum[],\n  webhooks: readonly Webhook[] = [],\n): Set<string> {\n  return collectExistingNamesByKind(models, services, enums, webhooks).enums;\n}\n\n/** The names a webhook's minting must step around: every decided name, and among them the enums'. */\nexport interface ReservedNames {\n  all: ReadonlySet<string>;\n  enums: ReadonlySet<string>;\n}\n\n/**\n * `webhooks` — every webhook read so far, their callbacks included — is\n * given when the callbacks are named after them (`extractCallbacks`), so a\n * callback's models step around a webhook's too (#382).\n */\nfunction collectExistingNamesByKind(\n  models: Model[],\n  services: Service[],\n  enums: Enum[],\n  webhooks: readonly Webhook[],\n): { all: Set<string>; enums: Set<string> } {\n  const names = new Set<string>();\n  const enumNames = new Set<string>();\n  const collect = (ref: TypeRef): void => {\n    walkTypeRef(ref, {\n      model: (r) => names.add(r.name),\n      enum: (r) => {\n        names.add(r.name);\n        enumNames.add(r.name);\n      },\n    });\n  };\n  for (const model of models) {\n    names.add(model.name);\n    for (const field of model.fields) collect(field.type);\n  }\n  for (const e of enums) {\n    names.add(e.name);\n    enumNames.add(e.name);\n  }\n  for (const service of services) {\n    for (const op of service.operations) for (const ref of collectOperationTypeRefs(op)) collect(ref);\n  }\n  for (const webhook of webhooks) for (const ref of collectWebhookTypeRefs(webhook)) collect(ref);\n  return { all: names, enums: enumNames };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Flatten the map into one entry per (key, method), resolving path-item refs\n * and parameter / request-body refs up front so the stem resolution below can\n * mint every entry's names before any stem is decided.\n */\nfunction collectWebhookEntries(\n  webhooks: Record<string, unknown>,\n  components: WebhookComponents,\n  siblingDocs: SiblingDocs,\n  paths: unknown,\n): WebhookEntry[] {\n  const entries: WebhookEntry[] = [];\n  // Every key, an `x-` one included: unlike `paths`, the map takes no\n  // specification extensions (#421).\n  for (const [name, raw] of Object.entries(webhooks)) {\n    // The same resolver `extractOperations` reads a `paths` entry through, so\n    // a `$ref` into `components/pathItems`, or to another `webhooks` or\n    // `paths` entry, is followed the same way here.\n    const pathItem = resolvePathItemRef(\n      raw,\n      components.pathItems,\n      { kind: 'webhook', key: name },\n      { paths, webhooks },\n    ) as PathItem | undefined;\n    if (!pathItem) continue;\n    entries.push(\n      ...readPathItemEntries(\n        pathItem,\n        { kind: 'webhook', name, labelOf: (method) => `webhooks.${name}.${method}` },\n        components,\n        siblingDocs,\n      ),\n    );\n  }\n  settleStemOperationIds(entries, 'webhook');\n  return entries;\n}\n\n/** Where a path item's operations are read for (`readPathItemEntries`): the entry's key, how each method is labelled, and a callback's own fields. */\nexport interface PathItemEntrySite extends Pick<\n  WebhookEntry,\n  'kind' | 'name' | 'expression' | 'expressionCount' | 'parentStem' | 'parent'\n> {\n  /** The diagnostic label of one method's operation. */\n  labelOf: (method: HttpMethod) => string;\n}\n\n/**\n * One entry per HTTP method of a resolved path item, in the path item's own\n * key order, as the IR promises document order (an entry declaring `put`\n * before `post` keeps `put` first); a method whose value is not an object\n * is skipped. Each entry's parameters are read with the same precedence as\n * `buildOperation`'s — an operation-level parameter replaces a\n * path-item-level one of the same identity (`parameterKey`: location and\n * name, a header's name case-folded), in the path-level position; an\n * `Accept`, `Content-Type` or `Authorization` header is dropped — and a\n * `path` parameter, which a received request has no path to place in, is\n * dropped with a warning. The request body's `components/requestBodies`\n * ref is resolved here too. A parameter `content` map or a request body\n * none of whose media types is read is reported here, once per entry: the\n * mint runs twice for each (`resolveWebhookModelStems`, then the build), so\n * it must not report. `stemOperationId` is left for `settleStemOperationIds`\n * to set over the whole batch.\n */\nexport function readPathItemEntries(\n  pathItem: PathItem,\n  site: PathItemEntrySite,\n  components: WebhookComponents,\n  siblingDocs: SiblingDocs,\n): WebhookEntry[] {\n  const { kind, name, labelOf } = site;\n  const entries: WebhookEntry[] = [];\n  const methods = (Object.keys(pathItem) as string[]).filter(\n    (key): key is HttpMethod =>\n      (HTTP_METHODS as readonly string[]).includes(key) && isRecord(pathItem[key as HttpMethod]),\n  );\n  for (const method of methods) {\n    const op = pathItem[method] as OperationObject;\n    const label = labelOf(method);\n    const paramsByIdentity = new Map<string, ParameterObject>();\n    for (const rawParam of [...(pathItem.parameters ?? []), ...(op.parameters ?? [])]) {\n      const param = resolveParameterRef(rawParam, components.parameters, label, siblingDocs);\n      if (isIgnoredHeaderParameter(param)) continue;\n      paramsByIdentity.set(parameterKey(param.in, param.name), param);\n    }\n    const params: ParameterObject[] = [];\n    for (const param of paramsByIdentity.values()) {\n      if (param.in === 'path') {\n        console.warn(\n          `[oagen] Warning: Parameter \"${param.name}\" (in: path) on ${label} ignored: a ${kind} has no path to place it in.`,\n        );\n        continue;\n      }\n      warnUnreadParameterContent(param, `Parameter \"${param.name}\" (in: ${param.in}) on ${label}`);\n      params.push(param);\n    }\n    const body = resolveRequestBodyRef(op.requestBody, components.requestBodies, label, siblingDocs);\n    warnUnreadRequestBody(body, label);\n    const entry: WebhookEntry = { kind, name, method, op, pathItem, params, body, label, methodCount: methods.length };\n    // A callback's own fields, present only on a callback.\n    if (site.expression !== undefined) entry.expression = site.expression;\n    if (site.expressionCount !== undefined) entry.expressionCount = site.expressionCount;\n    if (site.parentStem !== undefined) entry.parentStem = site.parentStem;\n    if (site.parent !== undefined) entry.parent = site.parent;\n    entries.push(entry);\n  }\n  return entries;\n}\n\n/**\n * Decide which entries are named from their operationId. An operationId\n * names the stem only when it names something and exactly one operation\n * object among `entries` declares it. One with no ASCII letter or digit\n * once its trailing overload markers are stripped (`' '`, `'-'`, `'[1]'`,\n * `'[1][2]'`) counts as absent, as `''` does and as an operation's does\n * (`namesNothing`; #564): it neither names the stem nor counts toward a\n * duplicate, so the key names the models, as when no id is declared. Two\n * keys that `$ref` one path item resolve to the same object and are fine\n * — they will share a stem (see `groupEntries`); two different objects\n * declaring one id is a document error OpenAPI forbids, so neither is\n * named from it, with a warning naming every site. The batch is the\n * `webhooks` map's entries, or every callback entry of the document read\n * together (`extractCallbacks`), so the rule is the same for both.\n */\nexport function settleStemOperationIds(entries: WebhookEntry[], kind: ReceivedRequestKind): void {\n  const objectsByOperationId = new Map<string, Set<OperationObject>>();\n  for (const entry of entries) {\n    const id = entry.op.operationId;\n    if (typeof id !== 'string' || namesNothing(id)) continue;\n    const objects = objectsByOperationId.get(id) ?? new Set<OperationObject>();\n    objects.add(entry.op);\n    objectsByOperationId.set(id, objects);\n  }\n  for (const [id, objects] of objectsByOperationId) {\n    const declaring = entries.filter((entry) => entry.op.operationId === id);\n    if (objects.size === 1) {\n      for (const entry of declaring) entry.stemOperationId = id;\n      continue;\n    }\n    console.warn(\n      `[oagen] Warning: operationId \"${id}\" is declared by more than one ${kind} operation ` +\n        `(${declaring.map((entry) => entry.label).join(', ')}); naming their models from the ${kind} keys instead.`,\n    );\n  }\n}\n\n/**\n * Decide the stem every model of each webhook is named from: `<Stem>Payload`\n * for the payload, `<Stem>Payload<Field>` for objects nested in it,\n * `<Const><Stem>Payload` for a const-discriminated variant, `<Stem><Param>`\n * for an inline parameter object or enum.\n *\n * The plain stem is the `operationId` when the operation declares one that\n * names something — run through the same cleaning an operation's own\n * `…Request` model gets, so a webhook and an operation with the same id name\n * their models alike; one that names nothing (`namesNothing`: `' '`, `'-'`,\n * `'[1][2]'`) counts as absent, as an operation's does (#564) — and the\n * PascalCase of the webhook's key otherwise. When a key's path item\n * declares several methods, a key-derived stem has the method appended\n * (`PetUpdatedPut`) so the bodies never share a model. An operationId is\n * unique per document and needs no qualifier, with one caveat: two keys that\n * `$ref` the same `components/pathItems` entry resolve to one operation\n * object and so carry one operationId. Sharing a path item between events is\n * what that section is for, so such entries form one group (`groupEntries`)\n * that mints once and shares its stem and its models (`SharedPayload`)\n * rather than colliding with each other; each key is still its own\n * `Webhook`. An operationId that two different operation objects declare —\n * which no valid document does — is ignored for naming, with a warning, and\n * those webhooks take their key-derived stems (`collectWebhookEntries`). A\n * key that PascalCases to nothing, or to something starting with a digit,\n * gets `Webhook` in front.\n *\n * Whether a stem collides is decided from the names it actually mints, not\n * from a prefix: every group is first minted with its plain stem\n * (`mintWebhook`) and the model and inline-enum names that produces —\n * payload, nested objects, union variants with their const or title\n * prefixes, parameter objects, parameter enums, field enums — are collected\n * (`MintedWebhook.names`). A group collides when one of those names is\n * reserved (`collectExistingNames`: every model and enum the components and\n * the operations have decided, the components' own inline field models\n * included) or is also minted by another group. Two keys that flatten to\n * one stem (`pet_adopted` and `petAdopted`) collide on every name; a\n * `petEvent` union variant pinning `kind: returned` and a webhook keyed\n * `returnedPetEvent` collide on the one name `ReturnedPetEventPayload`; a\n * stem that merely starts with another's (`petAdopted` beside\n * `petAdoptedPayloadPet`) does not collide unless a name coincides. A\n * colliding stem takes the first six hex characters of the SHA-1 of the\n * webhook's operationId when it is named from one and of its key otherwise\n * — for a callback, of its site label (`stemIdentity`): the owner's label,\n * the key, the expression and the method, so the callbacks of two owners\n * whose stems coincide (`createPet` beside `create_pet`, both `CreatePet`)\n * under one key never hash alike, each keeping its own payload (#382) —\n * before the method qualifier (`PetAdoptedB4A950`), exactly as an\n * operationId-less operation's path prefix does, and is minted again under\n * it. What is hashed is the text as written (`groupIdentities`). Two\n * groups hashed already that still share a name because they hash one\n * string — a key and an operationId of one text, a webhook keyed\n * `petAdopted` without an operationId beside `noteAdded` declaring\n * `operationId: petAdopted`, both `PetAdoptedB4A950` — which six more\n * characters would never part, each put their source in front of the\n * text instead (`partsBy`: `key:petAdopted` and `operationId:petAdopted`)\n * and are minted again at the length they have, so the six characters\n * part them and each keeps its own payload whatever the key order (#580);\n * a key or operationId spelling such a prefixed text as written\n * (`key:petAdopted`) that shares a name with its group puts its source in\n * front too (`key:key:petAdopted`), being the one not yet prefixed. Two\n * groups that hash one string but share no name — the `post` and `put`\n * groups of one key, a key whose several methods qualify its stems past\n * the operationId's (`PetAdoptedPost` beside `PetAdopted`) — hash the\n * text as written. The names minted under the moved stems\n * are then checked again, against the reserved names and every other\n * group's: a group still\n * clashing — two hash prefixes that coincide, a reserved name that spells a\n * hashed stem — takes six more characters of its hash, and so on until no\n * stem-embedding name clashes or the hash is spent, when the clash is left\n * to the model merge. Both sides of a webhook-to-webhook collision are\n * hashed, since neither key is more canonical than the other. The outcome\n * depends only on the document's keys, operationIds, components and\n * operations, never on their order, and a key that stops colliding returns\n * to its plain stem.\n *\n * A name that does not embed the stem — a title-mapped union variant, which\n * is context-free by design — cannot be moved by the hash, so a clash on it\n * alone leaves the stem plain. One named like a decided enum is renamed\n * under the payload's root instead (`PetAdoptedPayloadCircle`, see\n * `mintSchema`), since a model and an enum under one name would reach an\n * emitter as one symbol; one named like a decided model, or like another\n * webhook's variant, is left to the model merge, which shares a component's\n * name when the component admits the shape and renames the variant under\n * the webhook's stem otherwise (`PetAdoptedComp`), as it does for\n * operations.\n *\n * `buildReceivedRequests` runs this twice: once over every group at every\n * depth, with every name counted as above except one a descendant mints\n * under a stem of its own, which `contends` keeps from moving an ancestor's\n * stem — the settling that holds across depths — and once per minting wave\n * under the same rule, from the `settled` stems and\n * hash lengths, where a name still taken moves a stem further, the\n * mint-time step-around. For the `webhooks` map, which nests nothing and\n * mints in one wave, the two are the one resolution this always was.\n */\nfunction resolveWebhookModelStems(\n  groups: WebhookGroup[],\n  reserved: ReservedNames,\n  components: WebhookComponents,\n  siblingDocs: SiblingDocs,\n  /** What each group is hashed from (`groupIdentities`), one record per group the resolution raises in place (`partsBy`). */\n  identities: Map<WebhookGroup, HashIdentity>,\n  /** Stems and hash lengths already settled, to start from and extend instead of the plain stems (`buildReceivedRequests`'s minting). */\n  settled?: ResolvedStems,\n  /** Whether a name `other` mints may move `group`'s stem; any may unless said otherwise. */\n  contends: (group: WebhookGroup, other: WebhookGroup) => boolean = () => true,\n): ResolvedStems {\n  const mint = (group: WebhookGroup, stem: string): Set<string> =>\n    mintWebhook(group.owner, stem, components, reserved, siblingDocs).names;\n  // How many hex characters of its hash each group's stem carries: none\n  // until it clashes, six more each time it still does.\n  const hashLength = new Map<WebhookGroup, number>(settled?.hashLength);\n  let stems = new Map(groups.map((group) => [group, settled?.stems.get(group) ?? plainStem(group.owner, '')]));\n  let names = new Map(groups.map((group) => [group, mint(group, stems.get(group)!)]));\n  for (;;) {\n    // Only a clashing name the hash would move — one that embeds the stem —\n    // moves the stem: a reserved one, or one a contending group also mints.\n    const embeds = (group: WebhookGroup, name: string): boolean => name.includes(toPascalCase(stems.get(group)!));\n    const onReserved = (group: WebhookGroup): boolean =>\n      [...names.get(group)!].some((name) => embeds(group, name) && reserved.all.has(name));\n    const rivals = (group: WebhookGroup): WebhookGroup[] =>\n      groups.filter(\n        (other) =>\n          other !== group &&\n          contends(group, other) &&\n          [...names.get(group)!].some((name) => embeds(group, name) && names.get(other)!.has(name)),\n      );\n    // Of the groups hashed already, those that hash one string as a group\n    // they share a name with — a key and an operationId of one text, which\n    // six more characters would never part — put their source in front of\n    // the text instead (`partsBy`), decided for every pair before any is\n    // applied, and are minted again at the length they have.\n    const raised = new Set(\n      groups.filter(\n        (group) =>\n          (hashLength.get(group) ?? 0) > 0 &&\n          rivals(group).some((other) => partsBy(identities.get(group)!, identities.get(other)!)),\n      ),\n    );\n    for (const group of raised) identities.get(group)!.level += 1;\n    // The groups that move: the raised, and those clashing on a reserved\n    // name or with a group not raised — a raised group's new input parts\n    // it from every group it shared a name with, which so stay put.\n    const clashing = groups.filter(\n      (group) => raised.has(group) || onReserved(group) || rivals(group).some((other) => !raised.has(other)),\n    );\n    // A clash that survives the whole hash is left to the model merge.\n    const movable = clashing.filter((group) => raised.has(group) || (hashLength.get(group) ?? 0) < SHA1_HEX_LENGTH);\n    if (movable.length === 0) return { stems, hashLength };\n    const moved = new Map(stems);\n    for (const group of movable) {\n      const length = raised.has(group)\n        ? hashLength.get(group)!\n        : Math.min(SHA1_HEX_LENGTH, (hashLength.get(group) ?? 0) + 6);\n      hashLength.set(group, length);\n      moved.set(group, plainStem(group.owner, webhookDisambiguator(hashInput(identities.get(group)!), length)));\n    }\n    // Minted again under the moved stems alone, then checked again: the\n    // groups that did not move keep the names they minted.\n    names = new Map(\n      groups.map((group) => [\n        group,\n        moved.get(group) === stems.get(group) ? names.get(group)! : mint(group, moved.get(group)!),\n      ]),\n    );\n    stems = moved;\n  }\n}\n\n/** The hex characters a SHA-1 spells: the most a disambiguator can take. */\nconst SHA1_HEX_LENGTH = 40;\n\n/** What `resolveWebhookModelStems` settles: each group's stem, and how many hex characters of its hash the stem carries. */\ninterface ResolvedStems {\n  stems: Map<WebhookGroup, string>;\n  hashLength: Map<WebhookGroup, number>;\n}\n\n/** Where an identity's text comes from: the operationId a stem is named from, or the key — a callback's site — otherwise. */\ntype IdentitySource = 'operationId' | 'key';\n\n/** What an entry or a group is told apart by: a text, and where it came from. */\ninterface StemIdentity {\n  source: IdentitySource;\n  text: string;\n}\n\n/**\n * What an entry's disambiguator is hashed from: its operationId when its\n * stem is named from one; else a webhook's key, and a callback's identity\n * (`WebhookEntry.identity`, its label when none was set) — the owner's\n * identity, the key, the expression and the method — so two owners\n * declaring one callback key, or two expressions of one key that\n * PascalCase alike (`#/url` and `#/URL`), never hash alike (#382). The\n * source comes with the text, so a key and an operationId that spell one\n * text can be told apart when a batch holds both (`groupIdentities`; #580).\n */\nfunction stemIdentity(entry: WebhookEntry): StemIdentity {\n  if (entry.stemOperationId !== undefined) return { source: 'operationId', text: entry.stemOperationId };\n  return { source: 'key', text: entry.kind === 'callback' ? (entry.identity ?? entry.label) : entry.name };\n}\n\n/**\n * The identity a group is hashed from: the smallest text among its members'\n * identities (`stemIdentity`), so the hash never depends on which site the\n * group was first read at. The members of an operationId-named group share\n * one identity, as do the sites of a shared callback operation's own\n * callbacks, whose owner's identity is that operationId; a group of\n * key-named entries reading one object under one stem from owners whose\n * identities differ takes the smallest, which a reorder of the owners\n * cannot move (#382). A group of one is hashed from its own. Every member\n * of a group has the one source, since a group is either named from one\n * operationId or made of key-named entries (`groupEntries`).\n */\nfunction groupIdentity(group: WebhookGroup): StemIdentity {\n  return group.entries.map(stemIdentity).sort((a, b) => (a.text < b.text ? -1 : a.text > b.text ? 1 : 0))[0]!;\n}\n\n/**\n * What a group is hashed from: its identity (`groupIdentity`), and how\n * many times its source has been put in front of the text (`hashInput`;\n * none to begin with). One record per group, shared by the settling, every\n * wave and the catch-all, which raise the level when two groups hashing\n * one string share a name (`partsBy`).\n */\ninterface HashIdentity {\n  identity: StemIdentity;\n  level: number;\n}\n\n/** The string a group's disambiguator is hashed from: its text, with its source in front once per level (`petAdopted`, `key:petAdopted`, `key:key:petAdopted`). */\nfunction hashInput({ identity: { source, text }, level }: HashIdentity): string {\n  return `${source}:`.repeat(level) + text;\n}\n\n/**\n * The identity each group is hashed from (`groupIdentity`), nothing in\n * front yet: what is hashed is the key or operationId as written, so a\n * document hashes exactly as it always has until two groups hashing one\n * string share a name — a key and an operationId of one text, which six\n * more characters of one hash would never part — and the resolution puts\n * a source in front (`partsBy`). A webhook keyed `petAdopted` without an\n * `operationId` and one keyed `noteAdded` declaring\n * `operationId: petAdopted` hashed one string, shared every hashed stem\n * to the last character and merged their payloads, the first declared\n * winning (#580); now, still sharing `PetAdoptedB4A950Payload` once\n * hashed, each hashes the text prefixed with its source, `key:petAdopted`\n * and `operationId:petAdopted`, and the six characters part them. Two\n * groups that hash one string but share no name keep hashing the text as\n * written, whatever their texts, so adding one half of such a pair never\n * renames a payload the other half had: a key `petAdopted` whose path\n * item declares several methods (`PetAdoptedPost`, `PetAdoptedPut`)\n * beside `noteAdded` declaring `operationId: petAdopted` (`PetAdopted`)\n * keeps `PetAdoptedB4A950PostPayload`, its `post` hashed because of a\n * component, on the day `noteAdded` is added; so does `noteAdded`\n * declaring `operationId: adoptions_created` (`AdoptionCreated`,\n * singularized) beside a key `adoptions_created` (`AdoptionsCreated`),\n * and one key whose `post` has no operationId (`PetAdoptedPost`) beside\n * its `put` declaring `operationId: petAdopted` (`PetAdopted`). The\n * entries of one key with several methods hold one text under one source\n * and hash one string, parted by the method qualifier, as they always\n * were. Which name two groups share is not foretold from the stems — a\n * const-discriminated variant is `<Const><Stem>Payload`, a parameter model\n * `<Stem><Param>`, and `Key` + `PetAdopted<hash>` + `PostPayload` is both\n * the `kind: key` variant of a `petAdopted` query parameter `post_payload`\n * and the `post` body of a webhook keyed `key:petAdopted` — so the\n * resolution reads the names minted, never the stems alone.\n */\nfunction groupIdentities(groups: WebhookGroup[]): Map<WebhookGroup, HashIdentity> {\n  return new Map(groups.map((group) => [group, { identity: groupIdentity(group), level: 0 }]));\n}\n\n/**\n * Whether `group`, sharing a name with `other` while hashing one string\n * (`hashInput`) — six more characters of which would never part them — is\n * one to put its source in front of its text. Both are, when they hash one\n * string at one level under different sources: the key and the operationId\n * of one text (`key:petAdopted` beside `operationId:petAdopted`). The one\n * at the lower level alone is, when the levels differ: a key spelling a\n * prefixed text as written, `key:petAdopted` beside the `petAdopted`\n * already prefixed to it, hashes `key:key:petAdopted` while `petAdopted`\n * stays, so the two never chase each other. Neither is, when they hash one\n * string at one level under one source: the several methods of one key,\n * which share no name and never ask. The decision reads the two records\n * alone, never the order the groups are declared in.\n */\nfunction partsBy(group: HashIdentity, other: HashIdentity): boolean {\n  if (hashInput(group) !== hashInput(other)) return false;\n  if (group.level < other.level) return true;\n  return group.level === other.level && group.identity.source !== other.identity.source;\n}\n\n/**\n * Entries that mint together. Those resolving to one operation object and\n * named from its operationId share a group: `owner` is the first of them in\n * document order, and its parameters and body stand for the group's, since\n * every member read the same path item. So do key-named callback entries\n * that read one operation object under one plain stem — the sites of one\n * shared callback operation's own callbacks (`noteRead` declared by a\n * `components/callbacks` entry two operations reference, or by a path item\n * two `webhooks` keys share), which every site reaches under the owner's\n * one stem — so a callback inside a shared minting mints once with it,\n * however many sites reach it (#382). Every other entry is a group of its\n * own: two keys reading one path item without an operationId keep their\n * key-derived stems, and two owners' inline callbacks are two objects.\n */\ninterface WebhookGroup {\n  owner: WebhookEntry;\n  entries: WebhookEntry[];\n}\n\nfunction groupEntries(entries: WebhookEntry[]): { groups: WebhookGroup[]; groupOf: Map<WebhookEntry, WebhookGroup> } {\n  const groups: WebhookGroup[] = [];\n  const groupOf = new Map<WebhookEntry, WebhookGroup>();\n  const byOperation = new Map<OperationObject, WebhookGroup>();\n  // A key-named callback's groups, by the operation object read and the\n  // plain stem it is read under (the owner's stem, key, expression and\n  // method; `plainStem`): the sites of one shared callback operation's own\n  // callbacks read one object under one stem and mint once (#382).\n  const byOwnedOperation = new Map<OperationObject, Map<string, WebhookGroup>>();\n  for (const entry of entries) {\n    const shared = entry.stemOperationId !== undefined;\n    const ownedStem = !shared && entry.kind === 'callback' ? plainStem(entry, '') : undefined;\n    let group = shared\n      ? byOperation.get(entry.op)\n      : ownedStem !== undefined\n        ? byOwnedOperation.get(entry.op)?.get(ownedStem)\n        : undefined;\n    if (!group) {\n      group = { owner: entry, entries: [] };\n      groups.push(group);\n      if (shared) byOperation.set(entry.op, group);\n      if (ownedStem !== undefined) {\n        const byStem = byOwnedOperation.get(entry.op) ?? new Map<string, WebhookGroup>();\n        byStem.set(ownedStem, group);\n        byOwnedOperation.set(entry.op, byStem);\n      }\n    }\n    group.entries.push(entry);\n    groupOf.set(entry, group);\n  }\n  return { groups, groupOf };\n}\n\n/** The plain stem of `entry` — before any collision hash — which a nested callback's key-derived stem is prefixed with (`extractCallbacks`). */\nexport function plainStemOf(entry: WebhookEntry): string {\n  return plainStem(entry, '');\n}\n\n/**\n * The stem of `entry` with `disambiguator` inserted before the qualifiers:\n * empty for the plain stem, else the hash prefix of what the resolution\n * hashes the entry's group from (`hashInput`,\n * `webhookDisambiguator`) — so two entries whose stems collide carry\n * different prefixes, a key and an operationId of one text included. A\n * key-derived stem is the key PascalCased, prefixed with\n * the declaring node's stem for a callback (`CreatePet` + `petAdopted` →\n * `CreatePetPetAdopted`; #382), then qualified by the expression\n * PascalCased when the callback's key declares several\n * (`CreatePetPetAdoptedRequestBodyCallbackUrl` for\n * `{$request.body#/callbackUrl}`) and by the method when the path item\n * declares several (`PetUpdatedPut`), so no two entries of one key share a\n * model; an operationId-derived stem needs neither. An empty stem, or one\n * starting with a digit, gets the kind's noun in front (`Webhook`,\n * `Callback`).\n */\nfunction plainStem(entry: WebhookEntry, disambiguator: string): string {\n  const operationId = entry.stemOperationId;\n  const expression = !operationId && (entry.expressionCount ?? 1) > 1 ? toPascalCase(entry.expression ?? '') : '';\n  const method = !operationId && entry.methodCount > 1 ? entry.method : '';\n  const base = operationId ? operationIdModelBase(operationId) : `${entry.parentStem ?? ''}${toPascalCase(entry.name)}`;\n  // `_` separators guarantee a word boundary on each side of the disambiguator\n  // and the qualifiers, whatever the base ends with; splitWords drops them, so\n  // the disambiguator is the suffix numberedName gives the base: a hash that\n  // starts with a digit is set off from a base that ends in one as a number\n  // is (`PetV2No2780A4`), as an operation's path prefix sets it off.\n  const hash = numberedName(base, disambiguator).slice(base.length);\n  const stem = toPascalCase([base, hash, expression, method].filter(Boolean).join('_'));\n  const noun = entry.kind === 'callback' ? 'Callback' : 'Webhook';\n  if (stem === '') return noun;\n  return /^\\d/.test(stem) ? `${noun}${stem}` : stem;\n}\n\n/** The first `length` (six, by default) hex characters of the SHA-1 of what a group is hashed from (`hashInput`). */\nfunction webhookDisambiguator(name: string, length = 6): string {\n  return createHash('sha1').update(name).digest('hex').slice(0, length);\n}\n\n/**\n * Type a webhook's parameters and payload under `stem`, materializing every\n * model they reference inline, in one namespace per webhook.\n *\n * The payload goes first, as the synthetic `payload` property of the stem\n * (`<Stem>Payload`, nested objects under it), through the same\n * `schemaToTypeRef` / `extractInlineModelsFromProperties` pair that names\n * component fields and response unions, so for every shape the field\n * extractor knows — an inline object, a `oneOf`/`anyOf` of inline objects, an\n * `allOf` merge or `$ref` augmentation, an array or map of any of those, an\n * inline enum, a nullable wrapper — the reference and the model are named by\n * one code path. A body with no schema is a binary or text primitive, as on\n * an operation.\n *\n * Each parameter then goes through `extractParams` with the stem as the\n * qualifying context, as a service name qualifies an operation's\n * (`PetAdopted` + `X-Event-Type` → `PetAdoptedXEventType`), and one whose\n * schema mints anything inline — an object, an array of them, an enum — is\n * run through the field extractor as a single synthetic property of the\n * stem, which names the model exactly as `extractParams` referenced it, the\n * pairing response headers already rely on. The property is the parameter's\n * own name unless a name it would mint is already taken by the payload or an\n * earlier parameter of this webhook: a query parameter named `payload` would\n * mint the body's `<Stem>Payload`, one named `payload_pet` the body's nested\n * `<Stem>PayloadPet`, and a header `X-Meta` beside a query `x_meta` would\n * mint `<Stem>XMeta` twice. Such a parameter is typed and minted under its\n * location-qualified name instead (`query_payload` → `<Stem>QueryPayload`),\n * then a numbered one (`<Stem>QueryPayload2`, …), the first that takes\n * nothing already minted, and its reference follows (see `mintParameter`).\n * Parameters are visited in document order, so the outcome depends only on\n * the document. `names` carries everything the webhook minted, for the stem\n * decision in `resolveWebhookModelStems`.\n */\nfunction mintWebhook(\n  entry: WebhookEntry,\n  stem: string,\n  components: WebhookComponents,\n  reserved: ReservedNames,\n  siblingDocs: SiblingDocs,\n): MintedWebhook {\n  const { params, body, label } = entry;\n  const parent = toPascalCase(stem);\n  const inlineModels: Model[] = [];\n  const names = new Set<string>();\n  const extract = (location: 'query' | 'header' | 'cookie'): Parameter[] =>\n    extractParams(params, location, stem, components.schemas, components.examples, label, siblingDocs);\n  const minted: MintedWebhook = {\n    headerParams: extract('header'),\n    queryParams: extract('query'),\n    cookieParams: extract('cookie'),\n    inlineModels,\n    names,\n  };\n\n  const payload = mintPayload(body, stem, components.schemas, reserved);\n  if (payload) {\n    minted.requestBody = payload.ref;\n    minted.requestBodyEncoding = payload.encoding;\n    minted.requestBodyContentType = payload.contentType;\n    minted.requestBodyContentTypes = payload.contentTypes;\n    minted.requestBodyContents = payload.contents;\n    inlineModels.push(...payload.models);\n    for (const name of payload.names) names.add(name);\n  }\n\n  // Each raw parameter and the IR parameter `extractParams` typed from it,\n  // paired on the identity every parameter lookup uses (`parameterKey`).\n  const typed = new Map<string, Parameter>();\n  for (const [location, list] of [\n    ['header', minted.headerParams],\n    ['query', minted.queryParams],\n    ['cookie', minted.cookieParams],\n  ] as const) {\n    for (const param of list) typed.set(parameterKey(location, param.name), param);\n  }\n  for (const param of params) {\n    const ir = typed.get(parameterKey(param.in, param.name));\n    // The schema `extractParams` typed the parameter from: `schema`, else\n    // the picked `content` entry's (`parameterTyping`).\n    const schema = parameterSchema(param);\n    if (!ir || !schema) continue;\n    const { ref, models, names: own } = mintParameter(param, schema, parent, names, components.schemas, reserved);\n    // `extractParams` typed the parameter from its schema alone; the minted\n    // reference is the one whose models exist — it differs when the parameter\n    // moved to a qualified property, and when a variant was renamed past a\n    // decided enum (`mintSchema`) under the parameter's own name — so it\n    // always replaces the extracted type, variants and discriminator mapping\n    // included, whether or not the property name changed.\n    ir.type = ref;\n    inlineModels.push(...models);\n    for (const name of own) names.add(name);\n  }\n  return minted;\n}\n\n/**\n * A copy of a minted shape for a second member of a group, carrying every\n * field the shape has: the fields that hold type references — the\n * parameters, the payload, the content entries — are copied through\n * `cloneTypeRef`, so each reference keeps the marks the merge passes read (a\n * `$ref` to a component, an inherited reference, an inline enum's members),\n * and each reference is cloned once, so a content entry whose `type` is the\n * payload's own reference shares the copy as it shared the original; every\n * other field (the encoding, the content type and its list, anything added\n * to the shape later) is copied structurally, present or absent exactly as\n * on the original. A field that comes to hold a type reference must join the\n * first group.\n */\nfunction cloneMintedShape(shape: MintedShape): MintedShape {\n  const clones = new Map<TypeRef, TypeRef>();\n  const clone = (ref: TypeRef): TypeRef => {\n    let copy = clones.get(ref);\n    if (!copy) clones.set(ref, (copy = cloneTypeRef(ref)));\n    return copy;\n  };\n  const cloneParameter = ({ type, ...rest }: Parameter): Parameter => ({ ...structuredClone(rest), type: clone(type) });\n  const { headerParams, queryParams, cookieParams, requestBody, requestBodyContents, ...rest } = shape;\n  return {\n    ...structuredClone(rest),\n    headerParams: headerParams.map(cloneParameter),\n    queryParams: queryParams.map(cloneParameter),\n    cookieParams: cookieParams.map(cloneParameter),\n    ...(requestBody ? { requestBody: clone(requestBody) } : {}),\n    ...(requestBodyContents\n      ? {\n          requestBodyContents: requestBodyContents.map(({ type, ...entry }) => ({\n            ...structuredClone(entry),\n            type: clone(type),\n          })),\n        }\n      : {}),\n  };\n}\n\n/** What one schema minted under one synthetic property: its reference, its models, and every name among them. */\ninterface MintedSchema {\n  ref: TypeRef;\n  models: Model[];\n  names: Set<string>;\n}\n\n/** What a webhook's body mints: the picked payload's reference and encoding, every media type with its type, and the models behind them. */\ninterface MintedPayload {\n  /** The picked entry's type (`Webhook.requestBody`); absent when no media type is read. */\n  ref?: TypeRef;\n  encoding?: Webhook['requestBodyEncoding'];\n  /** The picked entry's essence (`Webhook.requestBodyContentType`); set exactly when `ref` is. */\n  contentType?: string;\n  contentTypes: string[];\n  contents: RequestBodyContent[];\n  models: Model[];\n  names: Set<string>;\n}\n\n/**\n * The payload typed and materialized as the `payload` property of `stem`,\n * read from the content entry the operation body pick chooses\n * (`selectRequestBodyContent`, by media type essence), plus one entry per\n * media type the body declares, as `Operation.requestBodyContents` carries\n * them: the picked entry shares `ref`; every other entry with a schema is\n * typed and materialized as the `<MediaType>Payload` property of the stem\n * (`PetAdoptedTextCsvPayload`, named the way the body's own\n * `<Stem>Payload` is), and one without is typed as\n * `schemalessRequestContentType` types it. `undefined` when the body\n * declares no media type at all. A body none of whose media types is read\n * as `ref` is reported where the webhook's entry is built\n * (`warnUnreadRequestBody`), not here: the mint runs twice per webhook and\n * the warning fires once.\n */\nfunction mintPayload(\n  body: RequestBodyObject | undefined,\n  stem: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  reserved: ReservedNames,\n): MintedPayload | undefined {\n  const content = body?.content;\n  if (!content) return undefined;\n  const contentTypes = Object.keys(content);\n  if (contentTypes.length === 0) return undefined;\n  const minted: MintedPayload = { contentTypes, contents: [], models: [], names: new Set() };\n  const absorb = ({ ref, models, names }: MintedSchema): TypeRef => {\n    minted.models.push(...models);\n    for (const name of names) minted.names.add(name);\n    return ref;\n  };\n\n  const selected = selectRequestBodyContent(body);\n  if (selected) {\n    minted.encoding = selected.encoding;\n    minted.contentType = selected.essence;\n    // Only a binary or text pick comes without a schema; it is a primitive.\n    minted.ref = selected.schema\n      ? absorb(mintSchema(selected.schema, 'payload', stem, componentSchemas, reserved))\n      : schemalessRequestBodyType(selected.encoding);\n  }\n  // Minted — and so named — in naming order; listed as written.\n  const types = new Map<string, TypeRef>();\n  for (const contentType of mediaTypeNamingOrder(contentTypes)) {\n    const schema = content[contentType]?.schema;\n    const type =\n      selected && contentType === selected.contentType && minted.ref\n        ? minted.ref\n        : schema\n          ? absorb(mintSecondaryPayload(schema, contentType, contentTypes, stem, minted, componentSchemas, reserved))\n          : schemalessRequestContentType(contentType);\n    types.set(contentType, type);\n  }\n  for (const contentType of contentTypes) minted.contents.push({ contentType, type: types.get(contentType)! });\n  return minted;\n}\n\n/**\n * A secondary payload entry typed and materialized under the first\n * `<Fragment>Payload` property whose minted names are free of everything the\n * payload has minted so far — `<Fragment>Payload`, then `<Fragment>Payload2`,\n * `…Payload3`, … — the fragment coming from the media type's essence and,\n * when another key of the same essence sits beside it, the parameters\n * `oagen diff` compares, or a `charset` when nothing else tells them apart\n * (`mediaTypeNameFragment`), so `application/xml` and `APPLICATION/XML;\n * charset=utf-8` take `…ApplicationXmlPayload` and\n * `…ApplicationXmlCharsetPayload` before any candidate is tried; entries\n * still left with one fragment are minted in `mediaTypeNamingOrder`. A\n * candidate whose names are all taken by models of the very shape this entry\n * mints shares them and mints nothing, as the operation registry shares an\n * identical shape; a name taken by a different shape (`application/xml` and\n * `APPLICATION/XML` with other fields) steps on, so no two entries of one\n * payload ever point at a model with the other's fields. When a candidate\n * changes none of the clashing names (a title-mapped variant, which embeds\n * no property), no candidate can clear them: the earliest trial is kept,\n * under `<Fragment>Payload`, and the clash left to the model merge, as\n * `mintParameter` does.\n */\nfunction mintSecondaryPayload(\n  schema: SchemaObject,\n  contentType: string,\n  siblings: readonly string[],\n  stem: string,\n  minted: MintedPayload,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  reserved: ReservedNames,\n): MintedSchema {\n  const fragment = mediaTypeNameFragment(contentType, siblings);\n  const own = new Map(minted.models.map((model) => [model.name, model]));\n  let previous: { trial: MintedSchema; clashing: string } | undefined;\n  for (let attempt = 0; ; attempt++) {\n    const property = attempt === 0 ? `${fragment}Payload` : `${fragment}Payload${attempt + 1}`;\n    const trial = mintSchema(schema, property, stem, componentSchemas, reserved);\n    const taken = [...trial.names].filter((name) => minted.names.has(name));\n    if (taken.length === 0) return trial;\n    const sharesShape =\n      taken.length === trial.names.size &&\n      trial.models.every((model) => {\n        const owner = own.get(model.name);\n        return owner !== undefined && modelFingerprint(owner) === modelFingerprint(model);\n      });\n    if (sharesShape) return { ref: trial.ref, models: [], names: new Set() };\n    // Judged on the clashing names alone: a name that embeds the property (a\n    // variant renamed past a decided enum) changes with every candidate.\n    const clashing = taken.sort().join('\\n');\n    if (previous !== undefined && previous.clashing === clashing) return previous.trial;\n    if (attempt >= MAX_PARAMETER_PROPERTY_ATTEMPTS) return trial;\n    previous = { trial, clashing };\n  }\n}\n\n/**\n * A parameter's schema typed and materialized under the first synthetic\n * property whose minted names are all free: the parameter's own name, then\n * `<in>_<name>`, then that numbered by numberedProperty (`query_payload2`,\n * `query_payload3`, …; `query_v2No2` for a name that ends in a digit, which\n * an `_` before the number would not set off once PascalCased, and\n * `query_filter[v2]No2` for one that ends in a digit once cased, which a\n * number behind the bracket would run into once it is dropped —\n * `QueryFilterV2No2`, never `QueryFilterV22`, #533). A schema that\n * mints nothing (a primitive, a `$ref`) keeps the parameter's name at once.\n * When a candidate changes none of the clashing names — they do not embed\n * the property, as a title-mapped union variant does not — no candidate can\n * avoid the clash, so the earliest trial is kept, under the parameter's own\n * name, and the clash is left to the model merge, as for operations;\n * `MAX_PARAMETER_PROPERTY_ATTEMPTS` is a backstop behind that rule. The\n * caller always takes the returned reference, whether or not the property\n * moved: a variant renamed past a decided enum (`PetAdoptedFilterCircle`,\n * see `mintSchema`) is referenced only by the minted type.\n */\nfunction mintParameter(\n  param: ParameterObject,\n  schema: SchemaObject,\n  parent: string,\n  taken: ReadonlySet<string>,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  reserved: ReservedNames,\n): MintedSchema {\n  let previous: { minted: MintedSchema; clashing: string } | undefined;\n  // The name the models derive from is the one `extractParams` typed the\n  // parameter under — a header's lower-cased (`foldParameterName`) — so the\n  // reference and the models agree, and neither moves with the header's case.\n  const stem = foldParameterName(param.in, param.name);\n  for (let attempt = 0; ; attempt++) {\n    const property =\n      attempt === 0 ? stem : attempt === 1 ? `${param.in}_${stem}` : numberedProperty(`${param.in}_${stem}`, attempt);\n    const minted = mintSchema(schema, property, parent, componentSchemas, reserved);\n    const clashing = [...minted.names]\n      .filter((name) => taken.has(name))\n      .sort()\n      .join('\\n');\n    if (clashing === '' || attempt >= MAX_PARAMETER_PROPERTY_ATTEMPTS) return minted;\n    // The clash did not move with the property: what clashes are names that\n    // do not embed it (a title-mapped variant), which no candidate can clear\n    // — keep the earliest trial, under the parameter's own name, and leave\n    // the clash to the model merge. Judged on the clashing names alone, since\n    // a name that does embed the property (a variant renamed past a decided\n    // enum, `PetAdoptedXShapeCircle`) changes with every candidate.\n    if (previous !== undefined && previous.clashing === clashing) return previous.minted;\n    previous = { minted, clashing };\n  }\n}\n\n/** Hard cap on the properties `mintParameter` tries; the no-progress rule stops it long before in practice. */\nconst MAX_PARAMETER_PROPERTY_ATTEMPTS = 64;\n\n/**\n * Type `schema` as the synthetic property `property` of `parent` and\n * materialize what it declares inline, collecting every name that minted:\n * the models, and every inline enum (an enum ref carrying `values`; a `$ref`\n * to a component enum carries none and is a reference, not a minting) in the\n * reference and in the models' fields. Component references are deliberately\n * not names: a payload that refers to `AdoptionEvent` names nothing new.\n * A model minted under a name among `reserved.enums` — a title-mapped union\n * variant `Circle` beside a component enum `Circle`, which a property of the\n * same payload may reference — is renamed under the minted root\n * (`PetAdoptedPayloadCircle`; numbered when that is taken too, by anything\n * in `reserved.all` or minted here) with every reference among the models\n * and in the returned type rewritten, as `materializeInlineSchema` renames\n * one under a response body's root; an explicit `$ref` to a component model\n * of the name is never touched, and the enum reference is an `EnumRef`,\n * which no rename reaches. A model and an enum under one name would reach an\n * emitter as one public symbol. A variant named like a decided MODEL is left\n * to the stem hash and the model merge, as before: the names minted here are\n * not reserved from the extractor, so a stem-embedded clash still hashes the\n * stem and a context-free one still reaches the merge.\n */\nfunction mintSchema(\n  schema: SchemaObject,\n  property: string,\n  parent: string,\n  componentSchemas: Record<string, SchemaObject> | undefined,\n  reserved: ReservedNames,\n): MintedSchema {\n  const models: Model[] = [];\n  extractInlineModelsFromProperties({ properties: { [property]: schema } }, models, parent, componentSchemas);\n  const ref = schemaToTypeRef(schema, property, parent);\n  const root = qualifyInlineModelName(toPascalCase(property), parent);\n  const taken = new Set([...reserved.all, ...models.map((model) => model.name)]);\n  for (const model of models) {\n    if (!reserved.enums.has(model.name)) continue;\n    const from = model.name;\n    let to = `${root}${from}`;\n    for (let n = 2; taken.has(to); n++) to = numberedName(`${root}${from}`, n);\n    taken.add(to);\n    model.name = to;\n    for (const other of models) {\n      for (const typeRef of collectModelTypeRefs(other)) repointMintedRefs(typeRef, from, to);\n    }\n    repointMintedRefs(ref, from, to);\n  }\n  const names = new Set<string>();\n  const collectEnums = (typeRef: TypeRef): void => {\n    walkTypeRef(typeRef, {\n      enum: (r) => {\n        if (r.values) names.add(r.name);\n      },\n    });\n  };\n  for (const model of models) {\n    names.add(model.name);\n    for (const field of model.fields) collectEnums(field.type);\n  }\n  collectEnums(ref);\n  return { ref, models, names };\n}\n\n/**\n * Repoint every reference to the minted model `from` within `ref` to `to`,\n * an explicit `$ref` to a component of that name excepted\n * (`isComponentModelRef`); a discriminator mapping naming the model follows.\n */\nfunction repointMintedRefs(ref: TypeRef, from: string, to: string): void {\n  switch (ref.kind) {\n    case 'model':\n      if (ref.name === from && !isComponentModelRef(ref)) (ref as { name: string }).name = to;\n      return;\n    case 'array':\n      repointMintedRefs(ref.items, from, to);\n      return;\n    case 'nullable':\n      repointMintedRefs(ref.inner, from, to);\n      return;\n    case 'map':\n      repointMintedRefs(ref.valueType, from, to);\n      if (ref.keyType) repointMintedRefs(ref.keyType, from, to);\n      return;\n    case 'union':\n      for (const variant of ref.variants) repointMintedRefs(variant, from, to);\n      for (const [value, target] of Object.entries(ref.discriminator?.mapping ?? {})) {\n        if (target === from) ref.discriminator!.mapping[value] = to;\n      }\n      return;\n    default:\n      return;\n  }\n}\n\nfunction buildWebhook(\n  entry: WebhookEntry,\n  minted: MintedShape,\n  components: WebhookComponents,\n  siblingDocs: SiblingDocs,\n): Webhook {\n  const { name, method, op, pathItem, body, label } = entry;\n  const {\n    headerParams,\n    queryParams,\n    cookieParams,\n    requestBody,\n    requestBodyEncoding,\n    requestBodyContentType,\n    requestBodyContentTypes,\n    requestBodyContents,\n  } = minted;\n  // Read as an operation's are: the operation's own `summary` and\n  // `description`, or the path item's for each it declares none for.\n  const { summary, description } = resolveOperationDocs(op, pathItem);\n  const tags = extractTags(op.tags);\n  const security = extractSecurityRequirements(op.security, label);\n  // The payload's doc text, read as an operation's body's is: the Request\n  // Body Object's own, else its picked schema's (`requestBodyDescriptionOf`).\n  const requestBodyDescription = requestBodyDescriptionOf(body, selectRequestBodyContent(body));\n\n  return {\n    name,\n    // The document's operationId as written, when it names something; one\n    // that names nothing is left out, as on an operation (`namesNothing`;\n    // #564). No `operationIdTransform` is applied to a webhook's.\n    ...(typeof op.operationId === 'string' && !namesNothing(op.operationId) ? { operationId: op.operationId } : {}),\n    httpMethod: method,\n    ...(summary !== undefined ? { summary } : {}),\n    ...(description !== undefined ? { description } : {}),\n    // The operation's own link, present only when usable, as on an operation.\n    // A Path Item Object has no `externalDocs` field, so there is no path-item\n    // level to fall back to.\n    ...externalDocsEntry(op.externalDocs),\n    ...(op.deprecated === true ? { deprecated: true } : {}),\n    ...(tags !== undefined ? { tags } : {}),\n    headerParams,\n    queryParams,\n    ...(cookieParams.length > 0 ? { cookieParams } : {}),\n    ...(requestBody ? { requestBody } : {}),\n    ...(requestBodyEncoding ? { requestBodyEncoding } : {}),\n    ...(requestBodyContentType ? { requestBodyContentType } : {}),\n    // Set only when the body declares a media type, as an operation's flag is.\n    ...(requestBodyContentTypes && body?.required === true ? { requestBodyRequired: true } : {}),\n    ...(requestBodyDescription !== undefined ? { requestBodyDescription } : {}),\n    // Every media type the body declares, present only when there is one, as on an operation.\n    ...(requestBodyContentTypes ? { requestBodyContentTypes, requestBodyContents } : {}),\n    responses: extractWebhookResponses(op.responses, components.responses, label, siblingDocs),\n    ...(security !== undefined ? { security } : {}),\n  };\n}\n\n/**\n * The status codes the sender expects back, in document order. Only status\n * code keys (three digits, 100–599, as `classifyResponseKey` decides) are\n * carried: `default` and ranges such as `2XX` name no single code a handler\n * could return, and an `x-` key is a specification extension, so those are\n * skipped silently; a key OpenAPI does not define (`error`, `6XX`, `600`) is\n * warned about and ignored, as on an operation. A response written as a\n * `$ref` into `components/responses` is followed for its description, chains\n * included; a description written beside the `$ref` wins over the\n * component's under `siblingDocs: 'override'` (OpenAPI 3.1) and is ignored\n * under `'ignore'` (3.0), as beside every Reference Object\n * (`followReference`). A ref that leads nowhere, or anywhere else, keeps the\n * status code with a warning, and the description beside it by that rule, as\n * an operation's response does. A blank description is omitted. An entry at\n * a status code that is not an object (`200: \"oops\"`, `null`, `7`) is no\n * Response Object and no Reference Object: it is warned about once, naming\n * the site, and skipped, and a `responses` that is not an object at all is\n * read as absent, with a warning — as on an operation (`isResponseEntry`,\n * `isResponsesObject`, #617).\n */\nfunction extractWebhookResponses(\n  responses: OperationObject['responses'],\n  componentResponses: Record<string, Record<string, unknown>> | undefined,\n  label: string,\n  siblingDocs: SiblingDocs,\n): WebhookResponse[] {\n  const result: WebhookResponse[] = [];\n  // A `responses` that is not an object is no Responses Object: warned\n  // about once and read as absent, as on an operation (#617).\n  if (responses !== undefined && !isResponsesObject(responses, label)) responses = undefined;\n  for (const [code, raw] of Object.entries(responses ?? {})) {\n    const responseKey = classifyResponseKey(code);\n    if (responseKey.kind === 'unrecognized') warnUnrecognizedResponseKey(code, label);\n    if (responseKey.kind !== 'status') continue;\n    // An entry that is not an object (`200: \"oops\"`) is no Response Object\n    // and no Reference Object: warned about once, naming the site and the\n    // code, and skipped, as on an operation (#617). Only a status code is\n    // checked, since only one is read.\n    if (!isResponseEntry(raw, `${code} response of ${label}`)) continue;\n    const read = resolveResponseDescription(raw, componentResponses, code, label, siblingDocs);\n    if (read.skip) continue;\n    const description = presentText(read.description);\n    result.push({ statusCode: responseKey.code, ...(description !== undefined ? { description } : {}) });\n  }\n  return result;\n}\n\n/**\n * The description of a response, following a `components/responses` `$ref`\n * chain through `followReference`, the walk every Reference Object takes:\n * the outermost sibling description with content wins under `'override'`\n * and the component's own is read under `'ignore'`. A chain that loops, a\n * `$ref` that is not a string, or a ref nothing answers is warned about and\n * the walk's last object read as written, by the same rule: the text beside\n * the refs under `'override'`, none under `'ignore'`. The warning says\n * whether that leaves a description beside the status code. A chain that\n * ends on a `components/responses` entry that is no object (`Gone: []`) is\n * the inline case behind a pointer: it goes through `isResponseEntry` as an\n * inline entry does, warned about naming the component and the site, and\n * `{ skip: true }` tells the caller to skip the status code, as an\n * operation skips the entry (#617).\n */\nfunction resolveResponseDescription(\n  raw: Record<string, unknown>,\n  componentResponses: Record<string, Record<string, unknown>> | undefined,\n  code: string,\n  label: string,\n  siblingDocs: SiblingDocs,\n): { skip: true } | { skip?: undefined; description?: string } {\n  const followed = followReference<{ description?: unknown }>(raw, 'responses', componentResponses, siblingDocs);\n  if (followed.outcome === 'unresolved' && followed.found !== undefined) {\n    const { name, value } = followed.found;\n    if (!isResponseEntry(value, `components/responses/${name} (the ${code} response of ${label})`))\n      return { skip: true };\n  }\n  const { description } = followed.value;\n  const text = typeof description === 'string' ? description : undefined;\n  const keeping =\n    presentText(text) === undefined ? 'the status code only' : 'the status code and the description beside the $ref';\n  if (followed.outcome === 'circular' || followed.outcome === 'malformed') {\n    console.warn(\n      `[oagen] Warning: Circular or malformed response $ref for status ${code} in ${label}; keeping ${keeping}.`,\n    );\n  } else if (followed.outcome === 'unresolved') {\n    console.warn(\n      `[oagen] Warning: Unresolved response $ref \"${followed.ref}\" for status ${code} in ${label}: ` +\n        `no matching entry under components/responses. Keeping ${keeping}.`,\n    );\n  }\n  return { description: text };\n}\n","/**\n * Reading an Operation Object's `callbacks` (OpenAPI 3.x) into the IR\n * (#382).\n *\n * A callback is a request the API makes back to a URL the caller supplied\n * in the operation's request: under each key of the `callbacks` map sits a\n * Callback Object, or a `$ref` into `components/callbacks`, mapping runtime\n * expressions such as `{$request.body#/callbackUrl}` to path items. Each\n * HTTP method of each of those path items is one `Callback` — a `Webhook`\n * tied to the operation that registers it — carried on\n * `Operation.callbacks` or, for a `webhooks` operation's, on\n * `Webhook.callbacks`, and a callback operation's own `callbacks` nest the\n * same way. Everything is read through the webhook machinery\n * (`readPathItemEntries`, `buildReceivedRequests`): parameters (a `path`\n * one dropped with a warning), the payload with every media type,\n * responses, docs, deprecation, tags and security are read exactly as a\n * webhook's, and a callback's sites are labelled\n * `<owner label>.callbacks.<key>.<expression>.<method>`.\n *\n * **Naming.** A callback's models are named from a stem as a webhook's are:\n * the callback operation's `operationId` when it names something\n * (`namesNothing`; #564) and exactly one callback operation object in the\n * document declares it, else the declaring node's stem followed by the key\n * PascalCased — `createPet`'s `petAdopted` mints `CreatePetPetAdoptedPayload`,\n * `POST /pets`'s `PetsPostPetAdoptedPayload`, a nested callback\n * `<CallbackStem><Key>`. A key declaring several expressions qualifies\n * each key-derived stem with the expression PascalCased, and a path item\n * declaring several methods with the method, as one `webhooks` entry with\n * several methods is qualified (`plainStem`). The stems of every callback\n * are decided against every model and enum name the document already\n * holds — components, the operations' models, the webhooks' — and against\n * each other — once, across every depth, as the `webhooks` map's are, only a\n * name a descendant mints under a stem of its own never moving an ancestor's\n * stem; the minting then proceeds ancestors first (see `extractCallbacks`) —\n * so a collision hashes the\n * NEW stem as a webhook's is hashed — from the callback's identity: its\n * owner's identity (an operation's operationId, else `METHOD /path`; a\n * shared callback operation's operationId) with the key, expression and\n * method, so the callbacks of two owners whose stems coincide (`createPet`\n * beside `create_pet`) under one key never hash alike\n * (`CreatePetPetAdopted2Fac84Payload` beside a component\n * `CreatePetPetAdoptedPayload`), while a group read at several sites hashes\n * alike whichever site comes first; the moved names are checked again —\n * and never renames an existing model.\n *\n * **Cycles.** A `components/callbacks` entry, or a nested callback, can\n * refer back to a callback it sits in (a callback whose operation `$ref`s\n * the path item declaring the callback). The Callback Objects on the path\n * from the owner down are tracked by identity, after `$ref` resolution: a\n * callback already on that path is skipped with one warning naming the\n * site. Depth is otherwise unbounded, and one Callback Object reached from\n * two sites that do not nest is read at both, as two `webhooks` keys that\n * `$ref` one path item are.\n *\n * **Guards.** A `callbacks` value that is not a map, or an empty one,\n * declares no callback and is silent — as is an entry under\n * `components/callbacks` that nothing references. A Callback Object that is\n * not an object, a `$ref` that is not a string, one that resolves to\n * nothing under `components/callbacks`, or a chain that loops, is warned\n * about and skipped. An `x-` key inside a Callback Object is a\n * specification extension and is not an expression.\n */\nimport type { Callback, Model, Operation, Webhook } from '../ir/types.js';\nimport { callbackContext } from '../ir/types.js';\nimport type { InlineModelBundle } from './inline-models.js';\nimport type { DeclaredCallbacks, PathItem } from './operations.js';\nimport { resolveComponentRef, resolvePathItemRef } from './path-item-refs.js';\nimport type { SiblingDocs } from './reference-objects.js';\nimport {\n  buildReceivedRequests,\n  plainStemOf,\n  readPathItemEntries,\n  settleStemOperationIds,\n  type WebhookComponents,\n  type WebhookEntry,\n} from './webhooks.js';\n\nexport interface CallbackExtractionResult {\n  /** Models materialized from inline callback payload and parameter schemas, to merge into `ApiSpec.models`. */\n  inlineModels: Model[];\n  /** Where those models came from, one site per minting, as a webhook's (`WebhookExtractionResult.inlineModelBundles`). */\n  inlineModelBundles: InlineModelBundle[];\n}\n\n/** One callback entry waiting to be named and built, with where it attaches. */\ninterface PendingCallback {\n  entry: WebhookEntry;\n  /** The node the built `Callback` is appended to: the declaring operation or webhook, or the parent pending callback. */\n  owner: Operation | Webhook | PendingCallback;\n  /** The stem of `owner` when it is an operation or webhook; a parent callback's is its plain stem (`plainStemOf`). */\n  ownerStem: string | undefined;\n  /** The identity of `owner` when it is an operation or webhook (`DeclaredCallbacks.identity`); a parent callback's is its own. */\n  ownerIdentity: string | undefined;\n  /** The `Callback` built for this entry, once the batch is built (see `extractCallbacks`). */\n  node?: Callback;\n}\n\n/**\n * Read every declared `callbacks` map into `Callback` entries on its owner,\n * in place, and return the models the callbacks minted. `reservedNames` and\n * `reservedEnumNames` are every name decided before the callbacks — the\n * components', the operations', the webhooks' — see `collectExistingNames`.\n * `paths` and `webhooks` are the document's own maps, as written, which a\n * callback path item's `$ref` may name beside `components/pathItems`.\n *\n * Every callback of the document, nested ones included, is collected\n * first (`collectPendingCallbacks`), so an operationId names a stem only\n * when exactly one callback operation object in the whole document\n * declares it (`settleStemOperationIds`). Each key-named entry's stem is\n * then prefixed with its owner's stem — an operation's or webhook's settled\n * one, a parent callback's plain stem before any collision hash\n * (`plainStemOf`), parents preceding children — and every entry is grouped,\n * named, minted and built by `buildReceivedRequests`, as the `webhooks` map\n * is, in three phases: the groups are formed over every entry of the\n * document; the stems are settled once, in one resolution across every\n * depth, exactly as the `webhooks` map's are — a name a group would mint\n * that the document holds or another group also mints hashes the stem,\n * both of a colliding pair moving whichever depths reference them, so a\n * reference added at another depth renames nothing, and a group of one\n * plain stem with another is its peer whether referenced directly, nested\n * inside it, or both — with the one rule the `webhooks` map never\n * exercises, that a name a descendant mints under a stem of its own never\n * moves an ancestor's stem, so a new nested callback never renames its\n * parent's parameter or payload model (it is the one that hashes), two\n * groups nesting each other being peers again; and the minting\n * proceeds ancestors first, in waves by each group's shallowest member's\n * depth — every group with a member at depth 0, then those at depth 1, and\n * so on — each wave stepping around at mint time any name still taken,\n * while a group that spans depths is still one minting, named at its\n * shallowest depth and reused by its deeper members; last, whatever lets\n * two groups mint one name for two shapes past all that — a title-mapped\n * variant no stem hash moves — moves every group minting it, each on its\n * own stem (`separateMintedNames`), so no two callbacks ever share a model\n * by accident, while one shape under one name is the merge's to share, as\n * two webhooks' is. Entries reading one\n * operation object and named from\n * its operationId form one group whatever their depths (a\n * `components/callbacks` entry an operation references directly and\n * another callback nests), and so do key-named entries reading one object\n * under one plain stem (`groupEntries`: `noteRead` declared by a shared\n * `NoteAdded`; `Read` referenced by a path operation `registerEvent` and by\n * a callback operation `register_event`, both `RegisterEvent`), so each\n * mints once and every site references the one model\n * (`NotifyAdoptionPayload`, `OnNoteAddedNoteReadPayload`,\n * `RegisterEventReadPayload`) whichever site comes first; a nested site is\n * never named apart from a direct one. Every group is named against every\n * other and against every name decided before. Once every node exists,\n * each is attached to its owner in document order — `callbacks` key order,\n * expression order within each Callback Object, then the path item's\n * method order.\n */\nexport function extractCallbacks(\n  declared: readonly DeclaredCallbacks[],\n  components: WebhookComponents,\n  reservedNames: Iterable<string>,\n  reservedEnumNames: Iterable<string>,\n  siblingDocs: SiblingDocs,\n  paths?: unknown,\n  webhooks?: unknown,\n): CallbackExtractionResult {\n  const pending: PendingCallback[] = [];\n  for (const { owner, callbacks, label, stem, identity } of declared) {\n    collectPendingCallbacks(\n      callbacks,\n      label,\n      owner,\n      stem,\n      identity ?? label,\n      new Set(),\n      pending,\n      components,\n      siblingDocs,\n      { paths, webhooks },\n    );\n  }\n  const inlineModels: Model[] = [];\n  const inlineModelBundles: InlineModelBundle[] = [];\n  if (pending.length === 0) return { inlineModels, inlineModelBundles };\n\n  settleStemOperationIds(\n    pending.map(({ entry }) => entry),\n    'callback',\n  );\n  // Each entry's identity, once the operationIds are settled: the owner's\n  // — a parent callback's operationId when its stem is named from one, else\n  // the parent's own identity — with the key, expression and method, in\n  // the shape of the label. Parents precede their children in `pending`.\n  for (const candidate of pending) {\n    const { entry, owner } = candidate;\n    const parent = isPending(owner) ? (owner.entry.stemOperationId ?? owner.entry.identity!) : candidate.ownerIdentity!;\n    entry.identity = callbackContext(parent, {\n      name: entry.name,\n      expression: entry.expression!,\n      httpMethod: entry.method,\n    });\n  }\n\n  // Each key-named entry's parent stem: the owner's settled stem for an\n  // operation or webhook, a parent callback's plain stem (before the\n  // collision hash the batch below may give it). Parents precede their\n  // children in `pending`, so a parent's own parent stem is set first.\n  for (const candidate of pending) {\n    const { entry, owner } = candidate;\n    if (entry.stemOperationId !== undefined) continue;\n    entry.parentStem = isPending(owner) ? plainStemOf(owner.entry) : candidate.ownerStem!;\n  }\n\n  // Every callback of the document at once, as the `webhooks` map is read:\n  // entries reading one operation object under one plain stem form one\n  // group whatever their depths (`groupEntries`); the stems are settled\n  // once across every depth, as the `webhooks` map's are, only a name a\n  // descendant mints under a stem of its own never moving an ancestor's\n  // stem; the groups are minted in waves\n  // by their shallowest member's depth, each wave stepping around every\n  // name decided before it, and each mints once.\n  const batch = buildReceivedRequests(\n    pending.map(({ entry }) => entry),\n    components,\n    { all: new Set(reservedNames), enums: new Set(reservedEnumNames) },\n    siblingDocs,\n  );\n  inlineModels.push(...batch.inlineModels);\n  inlineModelBundles.push(...batch.inlineModelBundles);\n  for (const [index, { node }] of batch.built.entries()) {\n    const candidate = pending[index]!;\n    // The node `buildWebhook` made, with the expression after the key.\n    const { name, ...rest } = node;\n    candidate.node = { name, expression: candidate.entry.expression!, ...rest };\n  }\n  // Attached once every node exists, in document order: `pending` is\n  // collected depth-first, so an owner's callbacks come in key, expression\n  // and method order, and a parent's node is built before its children attach.\n  for (const candidate of pending) {\n    const owner = isPending(candidate.owner) ? candidate.owner.node! : candidate.owner;\n    owner.callbacks = [...(owner.callbacks ?? []), candidate.node!];\n  }\n  return { inlineModels, inlineModelBundles };\n}\n\nfunction isPending(owner: PendingCallback['owner']): owner is PendingCallback {\n  return 'entry' in owner;\n}\n\n/** The document's own `paths` and `webhooks` maps, which a callback path item's `$ref` may name. */\ninterface DocumentMaps {\n  paths?: unknown;\n  webhooks?: unknown;\n}\n\n/**\n * Read one `callbacks` map into pending entries, recursing into each\n * callback operation's own `callbacks` with the Callback Objects on the path\n * (`ancestors`) as the cycle guard. `label` is the declaring node's, which\n * each site is labelled under.\n */\nfunction collectPendingCallbacks(\n  callbacks: unknown,\n  label: string,\n  owner: PendingCallback['owner'],\n  ownerStem: string | undefined,\n  ownerIdentity: string | undefined,\n  ancestors: ReadonlySet<object>,\n  pending: PendingCallback[],\n  components: WebhookComponents,\n  siblingDocs: SiblingDocs,\n  document: DocumentMaps,\n): void {\n  // Not a map, or an empty one: nothing declared, nothing said.\n  if (!isRecord(callbacks)) return;\n  for (const [key, raw] of Object.entries(callbacks)) {\n    const site = `${label}.callbacks.${key}`;\n    const callback = resolveCallbackRef(raw, site, components.callbacks);\n    if (!callback) continue;\n    if (ancestors.has(callback)) {\n      console.warn(`[oagen] Warning: Callback \"${site}\" refers back to a callback it sits in; skipping it.`);\n      continue;\n    }\n    const onPath = new Set(ancestors).add(callback);\n    // An `x-` key is a specification extension of the Callback Object, not\n    // an expression (as `schemaRootsOf` steps over it).\n    const expressions = Object.keys(callback).filter((expression) => !expression.startsWith('x-'));\n    for (const expression of expressions) {\n      const expressionSite = `${site}.${expression}`;\n      const pathItem = resolvePathItemRef(\n        callback[expression],\n        components.pathItems,\n        { kind: 'callback', key: expressionSite },\n        document,\n      ) as PathItem | undefined;\n      if (!pathItem) continue;\n      const entries = readPathItemEntries(\n        pathItem,\n        {\n          kind: 'callback',\n          name: key,\n          expression,\n          expressionCount: expressions.length,\n          // The parent callback's entry, for the depth and the ancestry.\n          ...(isPending(owner) ? { parent: owner.entry } : {}),\n          labelOf: (method) => callbackContext(label, { name: key, expression, httpMethod: method }),\n        },\n        components,\n        siblingDocs,\n      );\n      for (const entry of entries) {\n        const candidate: PendingCallback = { entry, owner, ownerStem, ownerIdentity };\n        pending.push(candidate);\n        // The callback operation's own callbacks nest under it.\n        collectPendingCallbacks(\n          entry.op.callbacks,\n          entry.label,\n          candidate,\n          undefined,\n          undefined,\n          onPath,\n          pending,\n          components,\n          siblingDocs,\n          document,\n        );\n      }\n    }\n  }\n}\n\n/**\n * The Callback Object `raw` denotes: itself, or the `components/callbacks`\n * entry its `$ref` chain leads to. A Callback Object carries no\n * documentation a Reference Object could override, so nothing beside the\n * `$ref` is read. `undefined`, after one warning naming the site, for a\n * value that is not an object, a `$ref` that is not a string, a ref\n * nothing under `components/callbacks` answers (one into another section\n * included), or a chain that loops; the caller skips the callback.\n */\nfunction resolveCallbackRef(\n  raw: unknown,\n  site: string,\n  componentCallbacks: Record<string, Record<string, unknown>> | undefined,\n): Record<string, unknown> | undefined {\n  const seen = new Set<string>();\n  let current: unknown = raw;\n  while (true) {\n    if (!isRecord(current)) {\n      console.warn(`[oagen] Warning: Callback \"${site}\" is not a Callback Object; skipping it.`);\n      return undefined;\n    }\n    const ref = current.$ref;\n    if (ref === undefined) return current;\n    if (typeof ref !== 'string') {\n      console.warn(`[oagen] Warning: Callback \"${site}\" has a non-string $ref; skipping it.`);\n      return undefined;\n    }\n    if (seen.has(ref)) {\n      console.warn(\n        `[oagen] Warning: Circular callback $ref chain starting at \"${ref}\" for callback \"${site}\"; skipping it.`,\n      );\n      return undefined;\n    }\n    seen.add(ref);\n    const resolved = resolveComponentRef(ref, 'callbacks', componentCallbacks);\n    if (!resolved) {\n      console.warn(\n        `[oagen] Warning: Unresolved callback $ref \"${ref}\" for callback \"${site}\": ` +\n          'no matching entry under components/callbacks. Skipping the callback.',\n      );\n      return undefined;\n    }\n    current = resolved;\n  }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","import type { Enum, EnumRef, Model, ModelRef, Service, TypeRef, Webhook } from '../ir/types.js';\nimport {\n  walkTypeRef,\n  collectResponseHeaders,\n  collectModelRefs,\n  collectModelTypeRefs,\n  collectRequestBodyTypes,\n  collectResponseBodyTypes,\n  collectOperationTypeRefs,\n  collectWebhookTypeRefs,\n  renameModelRefs,\n  renameTypeRefModels,\n} from '../ir/types.js';\nimport { numberedName } from '../utils/naming.js';\nimport { modelFingerprint } from './operations.js';\nimport { isComponentModelRef } from './schemas.js';\nimport { unionShapeKey } from './union-shape.js';\nimport { shapeWithEnumFlags } from './enum-members.js';\nimport {\n  deprecatedFoldWarning,\n  fieldAdmits,\n  inheritedModelRefsOf,\n  isInheritedModelRef,\n  liftedFieldModelsOf,\n  looserFields,\n  modelAdmits,\n  modelShares,\n  recordFieldModelRename,\n  shapeFingerprint,\n  typeShapeKey,\n  type FieldInlineModelGroup,\n  type InlineModelBundle,\n  type ShapeReadOptions,\n} from './inline-models.js';\n\n/**\n * What the merge passes need to keep two definitions of one name apart — a\n * deprecated and a live one, an inline one and a component that does not\n * admit it, or an inline model and an enum (see `settleSharedNames`): the\n * site each inline model came from (`bundles`), so the copy that must leave\n * the shared name can be renamed and exactly its own references repointed;\n * every name already in play (`reserved`) — the component models and enums,\n * and every inline model of every pass — so the new name is free; and the\n * enum names among them (`enums`), which no inline model may keep, whatever\n * its shape: when the component fields are settled before the operations\n * are read (`settleFieldInlineModels`), the names `spec.enums` holds — the\n * component enums and the inline enums lifted from the component schemas'\n * own fields, union variants and array items; when the merges run, every\n * enum name in play — those, and every inline enum an operation's or a\n * webhook's reference carries (`reservedNamesByKind`). A name minted here is\n * added to `reserved`, so both passes, and every mint within one, agree, and\n * to `minted`, so a later pass can tell a copy whose fields reference a\n * model an earlier pass renamed — a parent whose child left a shared name —\n * from one that merely shares a name (`settleSharedNames`); a minted name is\n * taken against every name in play, so it names that one model and nothing\n * else. Absent, `minted` is created on first use, so a caller that gives\n * none still gets it within a pass; the parser hands one set to every pass.\n * The model a mint names is recorded too, under the name its copies left,\n * with how many sites share it (`mintedFor`), so an identical copy that\n * must leave that name later — an operation's nested object beside the\n * component field's that the settle moved before any operation was read —\n * joins the model rather than minting another (`renameClusters`); it is\n * created on first use and handed to every pass the same way.\n */\nexport interface InlineModelNaming {\n  bundles: InlineModelBundle[];\n  reserved: Set<string>;\n  enums: ReadonlySet<string>;\n  minted?: Set<string>;\n  mintedFor?: Map<string, Map<Model, number>>;\n  /**\n   * The component schemas' names among the owners a pass settles copies\n   * against (`settleSharedNames`). A component admits no copy while\n   * deprecated (`ownerFlagAdmits`, #441); every other owner — a model a\n   * component's field minted, the object the schema pass lifted from a\n   * field or the field extractor's settled copy of it — still admits a\n   * deprecated copy and yields its name to a live one. Absent, every owner\n   * is a component but those standing in for one (`yielding`).\n   */\n  components?: ReadonlySet<string>;\n}\n\n/**\n * Bundle the models each component field produced with the references that\n * field owns: its own type, looked up in `models` (the components), and\n * every reference an `allOf` merge has copied from it so far\n * (`inheritedModelRefsOf`), so a renamed child is repointed from the field\n * that produced it and from each copy of that field, and from nowhere else.\n * A field the model no longer has falls back to every field of its\n * component. A rename is recorded for the field (`recordFieldModelRename`),\n * so a reference an `allOf` merge copies from it afterwards — an operation's\n * or a webhook's, read after the fields are settled — is created under the\n * settled name. Read once before the operations (`settleFieldInlineModels`)\n * and again, with the copies made since, before the merges.\n *\n * `models` also holds the models the schema pass lifted from the same\n * inline schemas (`extractSchemas`: a component field's object, array items\n * or union variant, named as the field extractor names them), each\n * remembered by the field it was read from (`liftedFieldModelsOf`). Those\n * lifted from the group's own field are the group's twins, read from the\n * same schema: the group's copy folds onto its twin when the fields are\n * settled, and from then on the twin's own field references — minted for\n * the same nested objects the group holds — are the site's. The twins join\n * the bundle's `models`, so a rename of one of the group's models is\n * repointed in them as in the copy, and a copy whose child was renamed\n * still folds onto its twin. A twin is claimed by origin, never by name:\n * `Foo.barThing` and `FooBar.thing` both spell `FooBarThing`, only one of\n * them is lifted, and the other field's site leaves it alone. Claimed from\n * the moment it is lifted, the twin is in the site at the settle too, so a\n * child renamed there (against a component of its name) is repointed in\n * the twin as in the copy, and the copy still folds onto it rather than\n * take a name of its own and leave the twin referenced by nothing. A direct\n * caller whose schemas were not read by `extractSchemas` has no twins, and\n * its groups are bundled with their own models alone. The twin is among the\n * bundle's `models`, so a reference a header, parameter or fallback body\n * wrote by sharing it joins the field's site like one sharing a field model\n * (`attachSharedRefs`, run over the bundles once the operations are read)\n * and follows the site's renames.\n *\n * The fields of a component the SDK only sends (`sent`: the names\n * `sentOnlyComponentNames` gives) are sites the SDK sends\n * (`InlineModelBundle.sent`): their models share a component named like\n * them on an identical shape only, as an operation's request body does.\n */\nexport function fieldInlineModelBundles(\n  groups: FieldInlineModelGroup[],\n  models: Model[],\n  sent: ReadonlySet<string> = new Set(),\n): InlineModelBundle[] {\n  const byName = new Map(models.map((m) => [m.name, m]));\n  return groups.map(({ parentName, fieldName, models: fieldModels }) => {\n    const parent = byName.get(parentName);\n    const field = parent?.fields.find((f) => f.name === fieldName);\n    const own = field ? [field.type] : (parent?.fields.map((f) => f.type) ?? []);\n    return {\n      qualifier: parentName,\n      roots: [...own, ...inheritedModelRefsOf(parentName, fieldName)],\n      models: [...fieldModels, ...liftedFieldModelsOf(parentName, fieldName)],\n      renamed: (from, to) => recordFieldModelRename(parentName, fieldName, from, to),\n      ...(sent.has(parentName) ? { sent: true } : {}),\n    };\n  });\n}\n\n/**\n * The same field sites (`fieldInlineModelBundles`, one per group in order)\n * brought up to date for the merges, in place, once the operations and\n * webhooks are read: each site's roots gain the references an `allOf` merge\n * has copied from the field since (`inheritedModelRefsOf`), and its models\n * are the field models that survived the settle (`kept`) and the twins the\n * schema pass lifted — a copy that folded at the settle is dropped from the\n * site, so a site is never taken for the owner of a name it lost\n * (`attachSharedRefs` reads a site's names off its models: `Foo.barThing`\n * and `FooBar.thing` both folded onto the one lifted `FooBarThing`, and\n * `Foo.barThing`'s reference must reach that twin's site). The site objects\n * are kept rather than rebuilt, so what a fold carried onto one at the\n * settle (`InlineModelBundle.carried`) is still there when the field merge\n * renames the model it was carried onto.\n */\nexport function refreshFieldInlineModelBundles(\n  bundles: InlineModelBundle[],\n  groups: FieldInlineModelGroup[],\n  kept: readonly Model[],\n): InlineModelBundle[] {\n  const survivors = new Set(kept);\n  groups.forEach(({ parentName, fieldName }, i) => {\n    const bundle = bundles[i];\n    if (!bundle) return;\n    for (const ref of inheritedModelRefsOf(parentName, fieldName))\n      if (!bundle.roots.includes(ref)) bundle.roots.push(ref);\n    const twins = liftedFieldModelsOf(parentName, fieldName);\n    bundle.models = bundle.models.filter((model) => survivors.has(model) || twins.includes(model));\n  });\n  return bundles;\n}\n\n/**\n * Every type name the document will have minted by the time the IR is\n * finished, so a merge pass that must rename an inline model takes a name\n * nothing else has: the component models and enums, every inline model of\n * either pass (header models, list-envelope companions and union variants\n * included), and every inline enum — named on its `EnumRef` when the field,\n * parameter or header was typed, and only lifted into `spec.enums` after the\n * merges have run — found in any model's fields or named-union variants, or\n * anywhere on an operation or webhook. `reservedNamesByKind` gives the same\n * set beside the enum names among it.\n */\nexport function reservedTypeNames(\n  models: Model[],\n  enums: Enum[],\n  inlineModels: Model[],\n  fieldInlineModels: Model[],\n  services: Service[],\n  webhooks: Webhook[] = [],\n): Set<string> {\n  return reservedNamesByKind(models, enums, inlineModels, fieldInlineModels, services, webhooks).all;\n}\n\n/**\n * `reservedTypeNames` (`all`) beside the enum names among them (`enums`):\n * every enum in `enums` and every inline enum a model's field or variant, an\n * operation's reference or a webhook's carries — every enum name in play,\n * which no inline model the merge passes settle may keep\n * (`InlineModelNaming.enums`). One walk decides both, so the two sets\n * always agree on what an `EnumRef` names.\n */\nexport function reservedNamesByKind(\n  models: Model[],\n  enums: Enum[],\n  inlineModels: Model[],\n  fieldInlineModels: Model[],\n  services: Service[],\n  webhooks: Webhook[] = [],\n): { all: Set<string>; enums: Set<string> } {\n  const all = new Set<string>();\n  const enumNames = new Set<string>();\n  const visit = (ref: TypeRef): void => {\n    walkTypeRef(ref, {\n      enum: (r) => {\n        all.add(r.name);\n        enumNames.add(r.name);\n      },\n    });\n  };\n  for (const model of [...models, ...inlineModels, ...fieldInlineModels]) {\n    all.add(model.name);\n    for (const ref of collectModelTypeRefs(model)) visit(ref);\n  }\n  for (const e of enums) {\n    all.add(e.name);\n    enumNames.add(e.name);\n  }\n  for (const service of services) {\n    for (const op of service.operations) for (const ref of collectOperationTypeRefs(op)) visit(ref);\n  }\n  for (const webhook of webhooks) for (const ref of collectWebhookTypeRefs(webhook)) visit(ref);\n  return { all, enums: enumNames };\n}\n\n/**\n * Which references a merge pass may repoint when it renames an inline model,\n * by the reference's identity rather than its name alone: one minted for an\n * inline model, never an explicit `$ref` to a same-named component\n * (`isComponentModelRef`); and a reference an `allOf` merge copied from\n * another component's field (`isInheritedModelRef`) only for that field's\n * own site (`includeInherited`), since it belongs to that site. Handed to\n * `renameTypeRefModels`, so a union's discriminator mapping follows a\n * repointed variant and stays on a `$ref` left in place.\n */\nfunction inlineRefAdmit(includeInherited: boolean): (ref: ModelRef) => boolean {\n  return (ref) => !isComponentModelRef(ref) && (includeInherited || !isInheritedModelRef(ref));\n}\n\n/** The site each inline model of `naming` came from, by identity (`InlineModelBundle.models`). */\nfunction bundlesByModel(naming: InlineModelNaming | undefined): Map<Model, InlineModelBundle> {\n  const bundleOf = new Map<Model, InlineModelBundle>();\n  for (const bundle of naming?.bundles ?? []) {\n    for (const model of bundle.models) bundleOf.set(model, bundle);\n  }\n  return bundleOf;\n}\n\n/**\n * One definition per name among `models`, the pass's own choice: the one\n * with the most fields, the first declared on a tie, with a warning when\n * the definitions differ. Every other copy of the name is folded onto it\n * (`foldOnto`): with `naming`, the copy's site is carried onto the winner,\n * so a later rename of the winner through its own site repoints the copy's\n * references too — a component field's model that lost its name to a\n * homonymous field's larger model (`Foo.barThings` and `FooBar.things` both\n * minting `FooBarThing`) still follows that model off an enum's name. The\n * rule the final field merge applies, applied as soon as the field models\n * are settled, so the model a later pass meets under a name is the one that\n * survives it. A copy with a site that references a model of its own the\n * winner does not has left the name before this runs (`settleSharedNames`),\n * so no fold here leaves a nested model referenced by nothing.\n */\nfunction keepLargestByName(models: Model[], naming?: InlineModelNaming): Model[] {\n  const byName = new Map<string, Model>();\n  for (const model of models) {\n    const existing = byName.get(model.name);\n    if (existing && !haveSameFields(existing, model)) {\n      // Two inline models resolved to one name but describe different shapes\n      // (e.g. two operationIds that PascalCase to the same word). Only one can\n      // survive, so say which, instead of silently handing every other\n      // reference a model with someone else's fields.\n      const kept =\n        model.fields.length === existing.fields.length\n          ? 'keeping the first definition'\n          : 'keeping the one with more fields';\n      console.warn(\n        `[oagen] Warning: Inline model \"${model.name}\" has more than one definition with different fields or field types (${model.fields.length} vs ${existing.fields.length}) — ${kept}`,\n      );\n    }\n    if (!existing || model.fields.length > existing.fields.length) {\n      byName.set(model.name, model);\n    }\n  }\n  const bundleOf = bundlesByModel(naming);\n  const folded = new Map<Model, Model>();\n  for (const model of models) {\n    const winner = byName.get(model.name)!;\n    if (winner !== model) foldOnto(model, winner, bundleOf, folded);\n  }\n  return [...byName.values()];\n}\n\n/**\n * Settle every name an inline model shares with another definition before a\n * merge pass folds same-named models together, so a live operation or field\n * never resolves to a model marked `deprecated`, and no reference resolves to\n * a component of another shape, whatever order the document declares them\n * in.\n *\n * `owners` are the models whose name, shape and flag are authoritative — the\n * component schemas (and, in the field pass, every model the response pass\n * already settled, when the caller does not say which are components) — and\n * `contenders` the inline models competing for their names. For each name,\n * the flag the name carries is its owner's or, with no owner, live as soon\n * as any contender is live (a name every contender deprecates stays\n * deprecated, and the pass leaves it alone).\n *\n * A contender whose flag disagrees with the name's\n *\n * - folds onto the live definition — the one `keepLargestByName` would keep\n *   among the live contenders — when there is no owner and it is identical\n *   to every live contender in everything but the flag\n *   (`differOnlyByDeprecation`): the shared name keeps the live definition,\n *   with a warning, in either order; the deprecated schema's own field or\n *   operation still carries its flag. Live contenders that disagree among\n *   themselves are settled by document order (first declared, or the one with\n *   more fields), as they always were; a deprecated copy never inherits that\n *   tie and is qualified instead, so its name is the same in every order;\n * - folds onto a live owner, with the same warning — or, when the owner is\n *   looser, one naming what it no longer requires (`deprecatedFoldWarning`,\n *   `looserFields`) — when the owner shares its name with it\n *   (`ownerSharesWith`, the flag read apart from the shape by\n *   `ownerFlagAdmits`): the copy is dropped and its references resolve to\n *   the owner, the deprecated schema's own field, parameter or envelope\n *   field still carrying the flag (a request body or response has no flag\n *   of its own to carry it). An owner is never renamed and never takes a\n *   contender's flag; a deprecated owner shares its name with no live copy,\n *   whatever their shapes, so a live inline copy never folds onto a\n *   deprecated component, and a deprecated component shares it with no\n *   deprecated copy either (`InlineModelNaming.components`, #441), so a\n *   deprecated copy keeps the qualified name its live self had (below);\n * - otherwise leaves the name with the other copies the owner does not\n *   share (`settleRefusedCopies`, below), or, with no owner, takes a name of\n *   its own (`renameInlineCopy`).\n *\n * A contender whose flag agrees with an owner's\n *\n * - folds onto a live owner when the owner shares its name with it\n *   (`ownerSharesWith`: `modelAdmits` — the same fields and types, the owner\n *   no stricter on requiredness or nullability, everything else identical —\n *   or an identical shape for a copy the SDK sends): the copy is dropped and\n *   its references, which already carry the name, resolve to the owner, and\n *   its site joins the owner's (`foldOnto`), so a later rename of an owner\n *   that has a site — a field model, a lifted twin — repoints them with the\n *   owner's own. An owner is never replaced, whatever the copy's field\n *   count, so every `$ref` to a component keeps the shape the document\n *   declares;\n * - otherwise takes a name of its own (`renameInlineCopy`), with a note. Two\n *   contenders of one name without an owner are left to the pass's own choice\n *   (`keepLargestByName`).\n *\n * A contender named like an enum (`naming.enums`) with no owner of that\n * name takes a name of its own whatever its shape or flag, with a note —\n * identical copies one name per shape, as under an owner (`renameClusters`):\n * an enum admits no model, so the IR never declares a model and an enum\n * under one name. A name both a component model and an enum hold is the\n * document's own clash and is settled as the model's.\n *\n * A renamed copy takes its site's qualifier prefixed (`mintQualifiedName`) —\n * `GetLegacyWidgetWidget` or `GetWidgetWidget` for a response of\n * `getLegacyWidget` or `getWidget` pinned by `object: widget`,\n * `GetPetResponse2` or `CreateNoteRequest2` for a body already named from\n * its operation, `PetOwner2` for a field of `Pet` — minted against every name\n * in play, and the references minted for it are repointed, by identity\n * (`repointInlineModelRefs`): the references its site owns — the operation's\n * response or body, the component field and every `allOf` copy of that\n * field — and those in the fields of the models minted beside it\n * (`InlineModelBundle`); never an explicit `$ref` to a same-named component,\n * in the same response map or anywhere else, and never a reference another\n * site's field lent.\n *\n * Every copy that must leave a name leaves it clustered by shape, whichever\n * rule above moves it — the owner's shape, its flag, an enum holding the\n * name, a renamed child (below): identical copies share one renamed model\n * under the first site's qualified name, every site repointed to it, with\n * one note saying how many sites share it; a copy of another shape takes a\n * name of its own. Two deprecated `address` objects beside a live\n * `PetOwnerAddress` of another shape are one `PetOwnerAddress2`, as they\n * would be one `PetOwnerAddress` without the component. Under an owner, the\n * copies it does not share are settled among themselves as the copies of a\n * name with no owner are (`settleRefusedCopies`): the flag read apart\n * (`shapeFingerprint`), so a deprecated copy and its live twin share one\n * model, the live definition kept and the deprecated copy folded onto it\n * with the warning above, each cluster named by its first site whatever\n * its flag — so flipping one copy's flag never changes a copy's name, and\n * two identical responses beside a deprecated `Widget` keep sharing\n * `GetLegacyWidgetWidget` once one of them is deprecated (#441). Elsewhere\n * — a name an enum holds, a holder that references a renamed model — the\n * flag is part of the shape (`renameClusters`, `modelFingerprint`), so a\n * deprecated copy and a live one never cluster. Copies that leave the name\n * in different passes share it the same way (`naming.mintedFor`): a\n * component field's copy, settled before any operation is read, takes the\n * model, and an operation's identical copy joins it here — of either flag\n * under an owner, the model live as soon as one of them is — as does a\n * deprecated copy identical to a field model that yielded the name to a\n * live copy (`yielding`).\n *\n * Names are decided bottom-up — a name after every name its contenders'\n * fields reference, as the list-envelope pass decides nested companions —\n * so when a parent is compared its children are already named: a parent\n * whose child was just renamed no longer looks identical to its twin, or\n * admitted by its component, and keeps its own model, referencing the\n * renamed child. Under a component, that is the rule above (a copy the\n * owner does not share is qualified). Among the contenders of one flag\n * without an owner, where the shared name otherwise keeps whichever\n * definition the pass's own choice settles on (`keepLargestByName`, by\n * document order), a contender whose fields reference a model this pass or\n * an earlier one renamed (`naming.minted`; a reference the site itself\n * minted, never an explicit `$ref` or one lent by another component's\n * field) is settled the same way as a copy an owner does not share:\n * clustered by shape, each cluster qualified by its first site, with a note\n * — its shape is its site's own now, and folding it by name would leave the\n * renamed child referenced by nothing, or hand every other site the child\n * the pass had just kept off the shared name. The contenders that follow no\n * rename are settled by the pass's own choice, as they always were, but for\n * one that choice would fold onto a definition that does not reference a\n * model it references itself (a reference its site minted, as above, to a\n * model no owner holds): it leaves the name the same way, since folded by\n * name it would leave that model referenced by nothing (`strands`). When\n * every contender follows a rename, the first cluster keeps the name as\n * that choice would keep the first definition. A contender under a name a\n * rename minted — the leader of a cluster, which the other sites of the\n * cluster were repointed to — keeps it. The deprecated copies of a live\n * name are compared with the live contenders that follow no rename, those\n * the pass's choice would drop included, or, when every one follows a\n * rename, with the first cluster.\n *\n * A contender without a site — none the parser produces; a direct caller's —\n * cannot be renamed and is left under the shared name, with a warning: the\n * owner's definition stands and the caller drops the copy.\n *\n * Returns the contenders that still compete for a name, the renamed ones\n * under their new name, and the folded copies keyed to the definition that\n * replaced them — the live twin, or the owner that admitted the copy — so a\n * caller that keeps an owner list can seat the live copy where the folded\n * one was.\n */\nfunction settleSharedNames(\n  owners: Map<string, Model>,\n  contenders: Model[],\n  naming: InlineModelNaming | undefined,\n  yielding?: ReadonlySet<Model>,\n): { kept: Model[]; folded: Map<Model, Model> } {\n  const byName = new Map<string, Model[]>();\n  for (const model of contenders) {\n    const group = byName.get(model.name) ?? [];\n    group.push(model);\n    byName.set(model.name, group);\n  }\n  const bundleOf = bundlesByModel(naming);\n  const flagOf = (deprecated: boolean): string => (deprecated ? 'deprecated' : 'live');\n  /**\n   * Whether `owner` is a model a component's field minted rather than a\n   * component schema (`InlineModelNaming.components`; without the names,\n   * one standing in for a component, `yielding`): it still admits a\n   * deprecated copy while deprecated (`ownerFlagAdmits`, #441).\n   */\n  const fieldMinted = (owner: Model): boolean =>\n    naming?.components ? !naming.components.has(owner.name) : !!yielding?.has(owner);\n  // Every name the merge passes have minted so far (`renameInlineCopy`),\n  // shared with the passes before and after this one through `naming`.\n  const minted = naming ? (naming.minted ??= new Set<string>()) : new Set<string>();\n  /**\n   * Whether one of `copy`'s own references — a field's or a variant's,\n   * minted by its site: never an explicit `$ref`, never one lent by another\n   * component's field — names a model a merge pass renamed.\n   */\n  const followsRename = (copy: Model): boolean => {\n    let found = false;\n    for (const ref of collectModelTypeRefs(copy)) {\n      walkTypeRef(ref, {\n        model: (r) => {\n          if (inlineRefAdmit(false)(r) && minted.has(r.name)) found = true;\n        },\n      });\n    }\n    return found;\n  };\n  /**\n   * Whether `copy`, folded onto `kept`, would leave a model of its own\n   * referenced by nothing: whether one of its own references (as\n   * `followsRename` reads them) names a model `kept` does not reference —\n   * never its own name, which then resolves to `kept`, nor an owner's,\n   * which no pass drops.\n   */\n  const strands = (copy: Model, kept: Model): boolean => {\n    const keptNames = new Set(collectModelTypeRefs(kept).flatMap(collectModelRefs));\n    let found = false;\n    for (const ref of collectModelTypeRefs(copy)) {\n      walkTypeRef(ref, {\n        model: (r) => {\n          if (inlineRefAdmit(false)(r) && r.name !== copy.name && !owners.has(r.name) && !keptNames.has(r.name)) {\n            found = true;\n          }\n        },\n      });\n    }\n    return found;\n  };\n\n  const folded = new Map<Model, Model>();\n\n  for (const name of bottomUp(byName)) {\n    const group = byName.get(name)!;\n    let owner = owners.get(name);\n    // An owner that may yield (`yielding`: a component field's model standing\n    // in for a component in the response merge) does not hold its name\n    // against a live copy when it is deprecated itself: a live copy owns a\n    // shared name, so the owner leaves through its own site, with the note a\n    // deprecated copy gets (`PetNoteOwner2` for `Pet.note.owner` beside\n    // `getA`'s live owner), and the live copies settle the name among\n    // themselves as they would with no owner. A component is never yielded;\n    // its name and flag are the document's.\n    if (owner && yielding?.has(owner) && owner.deprecated && group.some((m) => !m.deprecated)) {\n      const bundle = naming && bundleOf.get(owner);\n      if (bundle) {\n        const renamed = renameInlineCopy(owner, name, bundle, naming);\n        shareMinted(naming, name, owner, 1);\n        console.warn(`[oagen] Renamed inline model \"${name}\" → \"${renamed}\": it is deprecated while \"${name}\" is live`);\n        owners.delete(name);\n        owner = undefined;\n      }\n    }\n    // A name an enum holds (`naming.enums`) is no model's, whatever the\n    // copy's shape or flag: nothing admits it and nothing folds onto it, so\n    // every copy leaves the name through its site, identical copies sharing\n    // one model under the new name as they do under an owner's\n    // (`renameClusters`). Live and deprecated copies never share a model\n    // (`differOnlyByDeprecation`), so each flag's copies cluster on their\n    // own. A name both a component model and an enum hold is the document's\n    // own clash and is settled as the model's, below.\n    if (!owner && naming?.enums.has(name)) {\n      for (const deprecated of [false, true]) {\n        renameClusters(\n          name,\n          group.filter((copy) => !!copy.deprecated === deprecated),\n          naming,\n          bundleOf,\n          folded,\n          `enum \"${name}\" owns the name`,\n          `[oagen] Warning: Inline model \"${name}\" is named like enum \"${name}\" and has no site to be renamed from — keeping both under the shared name`,\n        );\n      }\n      continue;\n    }\n    let nameDeprecated: boolean;\n    /** The live contenders a deprecated copy may fold onto; empty under an owner, which every copy is measured against instead (`ownerSharesWith`). */\n    let live: Model[] = [];\n    if (owner) {\n      nameDeprecated = !!owner.deprecated;\n    } else {\n      nameDeprecated = group.every((m) => m.deprecated);\n      const holders = group.filter((m) => !!m.deprecated === nameDeprecated);\n      // A holder of the name that follows a rename — a parent whose child\n      // left a shared name — is its site's own shape now, and leaves the\n      // name by its site rather than by the pass's choice between twins\n      // (`keepLargestByName`), which would drop it and orphan the child, or\n      // keep it and hand every other site the child the pass kept off the\n      // name. A holder under a name a rename minted is the leader the other\n      // sites of its cluster were repointed to, and keeps it. The twins that\n      // follow no rename are settled as always, but for one that would\n      // strand a model of its own (below); when every holder follows one,\n      // the first cluster keeps the name as the pass's choice would keep the\n      // first definition. The copies of the other flag below are measured\n      // against the holders that follow no rename, or that first cluster.\n      const own = holders.filter((m) => !minted.has(m.name) && followsRename(m));\n      const rest = holders.filter((m) => !own.includes(m));\n      const leaving = clustersBy(own, modelFingerprint);\n      const first = rest.length === 0 ? (leaving.shift() ?? []) : [];\n      renameClusters(\n        name,\n        leaving.flat(),\n        naming,\n        bundleOf,\n        folded,\n        `it references a renamed model and \"${name}\" keeps another definition`,\n        `[oagen] Warning: Inline model \"${name}\" references a renamed model, is named like another definition and has no site to be renamed from — keeping the usual definition under the shared name`,\n      );\n      live = holders.filter((m) => rest.includes(m) || first.includes(m));\n      // A holder the pass's choice would fold onto another definition\n      // (`keepLargestByName`: the most fields, the first on a tie) leaves the\n      // name by its site too when it references a model of its own that\n      // definition does not: folded by name, it would leave that model\n      // referenced by nothing. Its nested models were decided before it, so\n      // it is read with their final names, and its own parent, decided\n      // after it, follows its rename. The copies of the other flag below are\n      // still measured against every holder in `live`, so whether one folds\n      // never depends on which definition document order keeps on a tie.\n      if (live.length > 1) {\n        const kept = preferredDefinition(live);\n        renameClusters(\n          name,\n          live.filter((m) => m !== kept && strands(m, kept)),\n          naming,\n          bundleOf,\n          folded,\n          `it references a model the definition kept under \"${name}\" does not`,\n          `[oagen] Warning: Inline model \"${name}\" references a model the definition kept under \"${name}\" does not and has no site to be renamed from — keeping the usual definition under the shared name`,\n        );\n      }\n      if (live.length === 0 || holders.length === group.length) continue;\n    }\n\n    if (owner) {\n      // Under an owner, every copy is measured against it first: one the\n      // owner shares its name with (`ownerSharesWith`, the flag read by\n      // `ownerFlagAdmits`) is folded onto it — a deprecated copy onto a live\n      // owner with the warning two inline copies get, since the shared name\n      // keeps the live definition, naming what a looser owner no longer\n      // requires (`looserFields`); a deprecated owner shares with no live\n      // copy, and a deprecated component with no copy at all (#441). The\n      // copies the owner does not share leave its name settled among\n      // themselves as the copies of a name with no owner are\n      // (`settleRefusedCopies`): one model per shape, the flag read apart,\n      // named by its first site, the live definition kept — so a deprecated\n      // copy of a deprecated `Widget` is `GetLegacyWidgetWidget` as its\n      // live self was, and two sites sharing it keep sharing it when one of\n      // them is deprecated. The note names why the cluster leaves: a flag\n      // the owner's does not admit — a live copy's beside a deprecated\n      // owner, the live definition a mixed cluster keeps included, or a\n      // deprecated copy's beside a live owner that does not admit its shape\n      // — or, for deprecated copies beside a deprecated owner, the shape,\n      // or the component that would share the shape were it live\n      // (`refusedByFlag`).\n      const held = owner;\n      const refused: Model[] = [];\n      for (const copy of group) {\n        const bundle = naming && bundleOf.get(copy);\n        if (ownerSharesWith(held, copy, bundle, fieldMinted(held))) {\n          if (!!copy.deprecated !== nameDeprecated) console.warn(deprecatedFoldWarning(name, looserFields(held, copy)));\n          foldOnto(copy, held, bundleOf, folded);\n          continue;\n        }\n        refused.push(copy);\n      }\n      const differs: [string, string] = [\n        `its shape differs from component schema \"${name}\"`,\n        `[oagen] Warning: Inline model \"${name}\" has a different shape than component schema \"${name}\" and has no site to be renamed from — using the component schema`,\n      ];\n      const flagged = (flag: boolean): [string, string] => [\n        `it is ${flagOf(flag)} while \"${name}\" is ${flagOf(!flag)}`,\n        `[oagen] Warning: Inline model \"${name}\" is ${flagOf(flag)} in one definition and ${flagOf(!flag)} in another, with different shapes, and has no site to be renamed from — keeping the usual definition under the shared name`,\n      ];\n      settleRefusedCopies(name, refused, naming, bundleOf, folded, (cluster) => {\n        const anyLive = cluster.some((m) => !m.deprecated);\n        if (!nameDeprecated) return anyLive ? differs : flagged(true);\n        if (anyLive) return flagged(false);\n        const first = cluster[0]!;\n        return refusedByFlag(held, first, naming && bundleOf.get(first), fieldMinted(held))\n          ? [\n              `\"${name}\" is deprecated and admits no copy`,\n              `[oagen] Warning: Inline model \"${name}\" is named like component schema \"${name}\", which is deprecated and admits no copy, and has no site to be renamed from — using the component schema`,\n            ]\n          : differs;\n      });\n      continue;\n    }\n\n    // Without an owner, the copies whose flag disagrees with the name's and\n    // that no live twin takes in leave it the same way, clustered by shape\n    // in document order: two identical deprecated `address` objects beside\n    // live inline copies they do not twin are one `PetOwnerAddress2` rather\n    // than a `PetOwnerAddress2` and a `PetOwnerAddress3`. The note names the\n    // copies' flag and the name's; every copy here carries the one flag the\n    // name does not.\n    const disagreeing: Model[] = [];\n    for (const copy of group) {\n      if (!!copy.deprecated === nameDeprecated || folded.has(copy)) continue;\n      // Without an owner, a deprecated copy folds only when every live copy\n      // of the name is its twin but for the flag: then whichever live\n      // definition the shared name carries, the copy is interchangeable with\n      // it. Live copies that disagree among themselves (requiredness, say)\n      // are settled by document order, as always; a deprecated copy must not\n      // inherit that order, so it is qualified whenever they disagree.\n      if (live.length > 0 && live.every((l) => differOnlyByDeprecation(l, copy))) {\n        console.warn(deprecatedFoldWarning(name, []));\n        foldOnto(copy, preferredDefinition(live), bundleOf, folded);\n        continue;\n      }\n      disagreeing.push(copy);\n    }\n    renameClusters(\n      name,\n      disagreeing,\n      naming,\n      bundleOf,\n      folded,\n      `it is ${flagOf(!nameDeprecated)} while \"${name}\" is ${flagOf(nameDeprecated)}`,\n      `[oagen] Warning: Inline model \"${name}\" is ${flagOf(!nameDeprecated)} in one definition and ${flagOf(nameDeprecated)} in another, with different shapes, and has no site to be renamed from — keeping the usual definition under the shared name`,\n    );\n  }\n\n  return { kept: contenders.filter((m) => !folded.has(m)), folded };\n}\n\n/**\n * Whether `owner`, a component — or, with `fieldMinted`, a model a\n * component's field minted — shares its name with `copy` (`modelShares`):\n * when it admits the shape (`modelAdmits`) — or, for a copy the SDK sends\n * (`bundle.sent`: a request body, a parameter, a field object of a component\n * only those reach), only when the shapes are identical, since a caller\n * typed against a looser component could leave out what the operation\n * requires — the flag read apart from the shape either way\n * (`ownerFlagAdmits`: a live owner shares with a copy of either flag, a\n * deprecated component with none, a deprecated field model only with a\n * deprecated copy, #441). The same question `ownerShares` answers for the\n * shape registry.\n */\nfunction ownerSharesWith(\n  owner: Model,\n  copy: Model,\n  bundle: InlineModelBundle | undefined,\n  fieldMinted = false,\n): boolean {\n  return modelShares(owner, copy, !!bundle?.sent, fieldMinted);\n}\n\n/**\n * Whether `owner`, a deprecated component, would share its name with `copy`\n * (`ownerSharesWith`) were it live: what the component's flag alone refuses\n * (`ownerFlagAdmits`, #441), told from a shape the component would not\n * share either way, for the note the copy leaves the name with. False for a\n * live owner, which shares or refuses on the shape alone, and for a model a\n * component's field minted (`fieldMinted`), whose flag refuses no deprecated\n * copy.\n */\nfunction refusedByFlag(\n  owner: Model,\n  copy: Model,\n  bundle: InlineModelBundle | undefined,\n  fieldMinted: boolean,\n): boolean {\n  return !fieldMinted && !!owner.deprecated && ownerSharesWith({ ...owner, deprecated: undefined }, copy, bundle);\n}\n\n/**\n * Move `copy` off `name` to a free name qualified by its site\n * (`mintQualifiedName`), reserve it, record it as minted\n * (`InlineModelNaming.minted`, so a parent referencing it is told from a\n * mere namesake), and repoint exactly the references its site minted\n * (`repointSite`). Returns the new name.\n */\nfunction renameInlineCopy(copy: Model, name: string, bundle: InlineModelBundle, naming: InlineModelNaming): string {\n  const renamed = mintQualifiedName(name, bundle.qualifier, naming.reserved);\n  naming.reserved.add(renamed);\n  naming.minted?.add(renamed);\n  copy.name = renamed;\n  repointSite(bundle, name, renamed, copy);\n  return renamed;\n}\n\n/**\n * Repoint exactly the references a site minted for `name` to `renamed`\n * (`inlineRefAdmit`): the site's own roots, copies of its field included;\n * then the references in the models minted beside it, which never include\n * what another site's field lent them — every reference kind alike, a\n * union's discriminator mapping following its variant\n * (`renameTypeRefModels`, `renameModelRefs`); then, for `model` — the model\n * of the site leaving `name` — the sites of the copies that folded onto it\n * (`InlineModelBundle.carried`, read by the model's identity), whose\n * references under `name` are references to it. A site that copies\n * references later is told (`InlineModelBundle.renamed`).\n */\nfunction repointSite(bundle: InlineModelBundle, name: string, renamed: string, model: Model): void {\n  const renames = new Map([[name, renamed]]);\n  for (const root of bundle.roots) renameTypeRefModels(root, renames, inlineRefAdmit(true));\n  for (const m of bundle.models) renameModelRefs(m, renames, inlineRefAdmit(false));\n  for (const entry of bundle.carried ?? []) {\n    if (entry.owner !== model) continue;\n    for (const root of entry.roots) renameTypeRefModels(root, renames, inlineRefAdmit(true));\n    for (const m of entry.models) renameModelRefs(m, renames, inlineRefAdmit(false));\n  }\n  bundle.renamed?.(name, renamed);\n}\n\n/**\n * Fold `copy` onto `winner` — the definition that replaces it under the\n * shared name: a component or a model the document declares, the live twin\n * of a deprecated copy, or the leader of its cluster — and carry its site\n * into the winner's (`InlineModelBundle.carried`), keyed to the winner. The\n * copy's references name the winner from now on, so when the winner is\n * renamed through its own site, the references in the copy's roots and in\n * the models minted beside it that carry the winner's name are repointed\n * with the winner's own (`repointSite`): a field model folded onto while an\n * operation's enum of its name is not yet known still carries the\n * operation's response with it when the field merge moves it off the\n * enum's name. The carried site is read by the winner's identity, never by\n * name: a rename of another model of the winner's site leaves it alone,\n * since a model of the copy's site under that name is the copy's site's\n * own, decided on its own (a parent decided after its children, say, which\n * may keep the name the winner's site's model leaves). A site carried onto\n * the copy earlier is carried on to the winner. A winner without a site — a\n * component — is never renamed, so nothing is carried.\n */\nfunction foldOnto(\n  copy: Model,\n  winner: Model,\n  bundleOf: ReadonlyMap<Model, InlineModelBundle>,\n  folded: Map<Model, Model>,\n): void {\n  folded.set(copy, winner);\n  const site = bundleOf.get(copy);\n  const into = bundleOf.get(winner);\n  if (!site || !into || site === into) return;\n  const carried = (into.carried ??= []);\n  carried.push({ owner: winner, roots: site.roots, models: site.models.filter((m) => m !== copy) });\n  for (const entry of site.carried ?? []) {\n    if (entry.owner === copy) carried.push({ owner: winner, roots: entry.roots, models: entry.models });\n  }\n}\n\n/**\n * Move `copies` — contenders of `name` that may not keep it, whether a\n * component of another shape or an enum holds it — off the name, one model\n * per shape: the copies are clustered by shape in document order\n * (`modelFingerprint`), the first of a cluster with a site is renamed\n * through it (`renameInlineCopy`) and every later one is repointed to that\n * name (`repointSite`) and folded onto it, so identical copies that must\n * leave a name share one model under the new one, as they would share the\n * bare name with no claimant (`keepLargestByName`). A cluster identical to a\n * model already minted for copies leaving `name` (`naming.mintedFor`) — by\n * an earlier pass, as the settle moves a component field's copy before any\n * operation is read, or by a field model yielding the name — that is still\n * a site's model joins it the same way, every copy repointed and folded\n * onto it, rather than minting another. Each cluster's rename is noted as\n * `[oagen] Renamed inline model \"<name>\" → \"<renamed>\": <reason>`, with the\n * number of sites when more than one shares the model, those an earlier\n * rename moved onto it included. A copy without a site cannot be renamed\n * and is left under `name`, `noSite` said for each. The copies must agree\n * on `deprecated`: a cluster never joins a live copy to a deprecated one\n * (`differOnlyByDeprecation`). The copies an owner does not share are\n * clustered with the flag read apart instead (`settleRefusedCopies`).\n */\nfunction renameClusters(\n  name: string,\n  copies: readonly Model[],\n  naming: InlineModelNaming | undefined,\n  bundleOf: ReadonlyMap<Model, InlineModelBundle>,\n  folded: Map<Model, Model>,\n  reason: string,\n  noSite: string,\n): void {\n  for (const cluster of clustersBy(copies, modelFingerprint)) {\n    const leader = mintedLeader(name, modelFingerprint(cluster[0]!), modelFingerprint, naming, bundleOf, folded);\n    renameCluster(name, cluster, leader, naming, bundleOf, folded, reason, noSite);\n  }\n}\n\n/**\n * Settle `copies` — the contenders of `name` an owner does not share, every\n * one of which must leave it — among themselves, as the copies of a name\n * with no owner are settled: clustered by shape with the model's own\n * `deprecated` read apart (`shapeFingerprint`, the reading\n * `differOnlyByDeprecation` gives a deprecated copy beside its live twin),\n * one model per cluster under the first site's qualified name whatever that\n * site's flag (`renameCluster`), so flipping one copy's flag never changes a\n * copy's name: two identical live `object: widget` responses beside a\n * deprecated `Widget` share `GetLegacyWidgetWidget`, and still do once\n * either of them is deprecated (#441 review). A cluster that mixes flags\n * keeps the live definition — its members are identical but for the flag,\n * so the first site's model with the flag cleared — and each deprecated\n * member folds onto it with the warning a deprecated copy folding onto its\n * live twin gets (`deprecatedFoldWarning`), its own field, parameter or\n * envelope field still carrying the flag; a cluster is deprecated only when\n * every member is. A model an earlier pass minted for copies leaving `name`\n * (`mintedLeader`) is joined by shape the same way: a live operation copy\n * joining the `PetOwner2` a deprecated `Pet.owner` left the name for makes\n * it live, as its live twin would under no owner, the field keeping its own\n * flag. `noteFor` says why a cluster leaves, and what to say for a member\n * without a site, which stays under `name`.\n */\nfunction settleRefusedCopies(\n  name: string,\n  copies: readonly Model[],\n  naming: InlineModelNaming | undefined,\n  bundleOf: ReadonlyMap<Model, InlineModelBundle>,\n  folded: Map<Model, Model>,\n  noteFor: (cluster: readonly Model[]) => readonly [reason: string, noSite: string],\n): void {\n  for (const cluster of clustersBy(copies, shapeFingerprint)) {\n    const leader = mintedLeader(name, shapeFingerprint(cluster[0]!), shapeFingerprint, naming, bundleOf, folded);\n    const joining = cluster.filter((copy) => naming !== undefined && bundleOf.has(copy));\n    const members = leader ? [leader, ...joining] : joining;\n    const live = members.some((member) => !member.deprecated);\n    if (live) {\n      for (const member of members) if (member.deprecated) console.warn(deprecatedFoldWarning(name, []));\n    }\n    const [reason, noSite] = noteFor(cluster);\n    const kept = renameCluster(name, cluster, leader, naming, bundleOf, folded, reason, noSite);\n    if (kept && live) delete kept.deprecated;\n  }\n}\n\n/** `copies` clustered by `shapeOf`, each cluster in the copies' order and the clusters in the order of their first copy. */\nfunction clustersBy(copies: readonly Model[], shapeOf: (model: Model) => string): Model[][] {\n  const clusters = new Map<string, Model[]>();\n  for (const copy of copies) {\n    const shape = shapeOf(copy);\n    clusters.set(shape, [...(clusters.get(shape) ?? []), copy]);\n  }\n  return [...clusters.values()];\n}\n\n/**\n * The model an earlier rename minted for copies leaving `name`\n * (`naming.mintedFor`) that a cluster of shape `shape` joins: one of that\n * shape under `shapeOf` that is still a site's — one no site holds, or one\n * folded here, may be gone from the IR.\n */\nfunction mintedLeader(\n  name: string,\n  shape: string,\n  shapeOf: (model: Model) => string,\n  naming: InlineModelNaming | undefined,\n  bundleOf: ReadonlyMap<Model, InlineModelBundle>,\n  folded: Map<Model, Model>,\n): Model | undefined {\n  return [...(naming?.mintedFor?.get(name)?.keys() ?? [])].find(\n    (model) => bundleOf.has(model) && !folded.has(model) && shapeOf(model) === shape,\n  );\n}\n\n/**\n * Move one cluster of copies off `name` (`renameClusters`): onto `leader`\n * when an earlier rename minted one, else the first copy with a site is\n * renamed through it (`renameInlineCopy`) and leads; every later copy is\n * repointed to the leader's name (`repointSite`) and folded onto it. The\n * rename is noted with `reason` and the number of sites sharing the model;\n * `noSite` is said for a copy without a site. Returns the model the cluster\n * ends under, or none when no copy had a site and no leader was minted.\n */\nfunction renameCluster(\n  name: string,\n  cluster: readonly Model[],\n  leader: Model | undefined,\n  naming: InlineModelNaming | undefined,\n  bundleOf: ReadonlyMap<Model, InlineModelBundle>,\n  folded: Map<Model, Model>,\n  reason: string,\n  noSite: string,\n): Model | undefined {\n  for (const copy of cluster) {\n    const bundle = naming && bundleOf.get(copy);\n    if (!naming || !bundle) {\n      console.warn(noSite);\n      continue;\n    }\n    if (leader === undefined) {\n      renameInlineCopy(copy, name, bundle, naming);\n      leader = copy;\n      continue;\n    }\n    repointSite(bundle, name, leader.name, copy);\n    foldOnto(copy, leader, bundleOf, folded);\n  }\n  const sites = cluster.filter((copy) => naming && bundleOf.has(copy)).length;\n  if (naming && leader && sites > 0) {\n    const shared = shareMinted(naming, name, leader, sites);\n    console.warn(\n      `[oagen] Renamed inline model \"${name}\" → \"${leader.name}\": ${reason}${shared > 1 ? ` (shared by ${shared} sites)` : ''}`,\n    );\n  }\n  return leader;\n}\n\n/**\n * Count `sites` more sites sharing `model`, minted for copies leaving `name`\n * (`InlineModelNaming.mintedFor`), and return how many share it now.\n */\nfunction shareMinted(naming: InlineModelNaming, name: string, model: Model, sites: number): number {\n  const mintedFor = (naming.mintedFor ??= new Map());\n  const sharing = mintedFor.get(name) ?? new Map<Model, number>();\n  mintedFor.set(name, sharing);\n  const shared = (sharing.get(model) ?? 0) + sites;\n  sharing.set(model, shared);\n  return shared;\n}\n\n/**\n * The names in `groups`, each after every name the models under it reference\n * (through their fields and named-union variants, at any depth of array,\n * map, union or nullable wrapper) — a post-order walk, so a cycle is cut\n * where it closes and every name appears once. Insertion order breaks ties, so the result is as stable\n * as the document.\n */\nfunction bottomUp(groups: ReadonlyMap<string, Model[]>): string[] {\n  const order: string[] = [];\n  const visited = new Set<string>();\n  const visit = (name: string): void => {\n    if (visited.has(name)) return;\n    visited.add(name);\n    for (const model of groups.get(name) ?? []) {\n      for (const ref of collectModelTypeRefs(model)) {\n        walkTypeRef(ref, {\n          model: (r) => {\n            // An explicit `$ref` names a component, never a contender.\n            if (!isComponentModelRef(r) && groups.has(r.name)) visit(r.name);\n          },\n        });\n      }\n    }\n    order.push(name);\n  };\n  for (const name of groups.keys()) visit(name);\n  return order;\n}\n\n/** The definition `keepLargestByName` keeps of a name: the one with the most fields, the first declared on a tie. */\nfunction preferredDefinition(models: Model[]): Model {\n  let best = models[0]!;\n  for (const model of models) if (model.fields.length > best.fields.length) best = model;\n  return best;\n}\n\n/**\n * A free name for a copy that must leave `name`: `qualifier` prefixed, as a\n * list-envelope companion or header model is qualified\n * (`GetLegacyWidgetWidget`), or — when the name already starts with the\n * qualifier, as a request body named from its operation does — the name\n * itself; then, while that is taken, a numeric suffix (`CreateNoteRequest2`,\n * `…3`; `GetPetError404No2` and `PetTagV2No2` for a name that ends in a\n * digit, see numberedName), the fallback a header model uses. `reserved`\n * holds every name in play, so the search stops at the first free suffix and\n * the result collides with nothing any pass has minted or will mint.\n */\nfunction mintQualifiedName(name: string, qualifier: string, reserved: ReadonlySet<string>): string {\n  const base = name.startsWith(qualifier) ? name : `${qualifier}${name}`;\n  if (base !== name && !reserved.has(base)) return base;\n  for (let n = 2; ; n++) {\n    const candidate = numberedName(base, n);\n    if (!reserved.has(candidate)) return candidate;\n  }\n}\n\n/**\n * Whether `a` and `b` are the same model but for `deprecated` — one flagged,\n * the other not, and otherwise identical in everything the header registry's\n * `modelFingerprint` reads: every field's name, type, requiredness, limits,\n * default and access flags, and the model's own limits, type parameters and\n * discriminator (names and documentation aside). Only such a pair is\n * interchangeable under one name; a difference in requiredness alone would\n * make a deprecated response promise a field the wire may omit.\n */\nfunction differOnlyByDeprecation(a: Model, b: Model): boolean {\n  if (!!a.deprecated === !!b.deprecated) return false;\n  return shapeFingerprint(a) === shapeFingerprint(b);\n}\n\n/**\n * Same field names with the same types, in any order, and the same\n * named-union variants. Types are compared by their JSON serialization: the\n * parser builds a given shape's TypeRef with the same key order every time,\n * so equal shapes serialize identically. An inline enum serializes with its\n * per-value deprecation (`shapeWithEnumFlags`), so a member deprecated on\n * one side only is a different type.\n */\nfunction haveSameFields(a: Model, b: Model): boolean {\n  const signatures = (m: Model) =>\n    new Set([\n      ...m.fields.map((f) => `${f.name}:${JSON.stringify(shapeWithEnumFlags(f.type))}`),\n      ...(m.variants ?? []).map((v, i) => `variant${i}:${JSON.stringify(shapeWithEnumFlags(v))}`),\n    ]);\n  const aSignatures = signatures(a);\n  const bSignatures = signatures(b);\n  return aSignatures.size === bSignatures.size && [...aSignatures].every((s) => bSignatures.has(s));\n}\n\n/** Every type reference in play: each model's fields and variants, each operation's, each webhook's. */\nfunction typeRefsInPlay(\n  models: readonly Model[],\n  services: readonly Service[],\n  webhooks: readonly Webhook[],\n): TypeRef[] {\n  const refs: TypeRef[] = [];\n  for (const model of models) refs.push(...collectModelTypeRefs(model));\n  for (const service of services) for (const op of service.operations) refs.push(...collectOperationTypeRefs(op));\n  for (const webhook of webhooks) refs.push(...collectWebhookTypeRefs(webhook));\n  return refs;\n}\n\n/**\n * Repoint every model reference in `models`, `services` and `webhooks`\n * through `renames` in one pass — fields, named-union variants and\n * discriminator mappings alike — each reference read once, so a name one\n * entry vacates and another takes is never chained through; and, when\n * `inlineEnumName` is given, rename every inline enum reference — one\n * carrying its `values`, named by the extractor after the model and field\n * it sits in — through it the same way, returning each name so renamed with\n * the first reference renamed from it, which carries the name it was given\n * until a later pass renames it in turn. A component enum reference carries\n * no values and is left as written.\n */\nfunction rewriteModelRefs(\n  models: Model[],\n  services: Service[],\n  renames: ReadonlyMap<string, string>,\n  webhooks: Webhook[] = [],\n  inlineEnumName?: (name: string) => string,\n): Map<string, EnumRef> {\n  for (const model of models) renameModelRefs(model, renames);\n  for (const service of services) {\n    for (const op of service.operations) {\n      renameTypeRefModels(op.response, renames);\n      if (op.requestBody) renameTypeRefModels(op.requestBody, renames);\n      // The iterator's item type is its own reference when an explicit\n      // `dataPath` typed it from the document (`resolveDataPathFromSchema`),\n      // not the one `response` holds, so it is rewritten on its own.\n      if (op.pagination) renameTypeRefModels(op.pagination.itemType, renames);\n      for (const field of op.pagination?.envelopeFields ?? []) renameTypeRefModels(field.type, renames);\n      for (const error of op.errors) if (error.type) renameTypeRefModels(error.type, renames);\n      for (const header of collectResponseHeaders(op)) renameTypeRefModels(header.type, renames);\n      for (const { type } of collectResponseBodyTypes(op)) renameTypeRefModels(type, renames);\n      for (const { type } of collectRequestBodyTypes(op)) renameTypeRefModels(type, renames);\n      // The operation's callbacks, nested ones included, as a webhook's are (#382).\n      for (const callback of op.callbacks ?? []) {\n        for (const ref of collectWebhookTypeRefs(callback)) renameTypeRefModels(ref, renames);\n      }\n    }\n  }\n  for (const webhook of webhooks) {\n    for (const ref of collectWebhookTypeRefs(webhook)) renameTypeRefModels(ref, renames);\n  }\n  const enumRenames = new Map<string, EnumRef>();\n  if (!inlineEnumName) return enumRenames;\n  for (const ref of typeRefsInPlay(models, services, webhooks)) {\n    walkTypeRef(ref, {\n      enum: (r) => {\n        if (!r.values) return;\n        const name = inlineEnumName(r.name);\n        if (name === r.name) return;\n        if (!enumRenames.has(r.name)) enumRenames.set(r.name, r);\n        r.name = name;\n      },\n    });\n  }\n  return enumRenames;\n}\n\n/**\n * Fold the operations' and webhooks' inline models into the component\n * models. A component's name, shape and flag are authoritative, and among\n * the inline models a live copy owns a shared name, so `settleSharedNames`\n * runs first: an inline model named like a component keeps the name only\n * when the component admits it (and is then dropped, its references\n * resolving to the component) and takes a qualified name otherwise, so a\n * component is never replaced; the fold below (`keepLargestByName`) only\n * ever joins inline models that agree on `deprecated`. An inline model named\n * like one of the document's enums (`naming.enums`) — a request body or\n * primary response named from its operation, a model nested under one, a\n * list-envelope companion — takes a qualified name the same way, whatever\n * its shape. A copy the caller gave no site to rename from (`naming`) is\n * dropped in favour of the component, with the settle pass's warning; one\n * named like an enum is kept beside it, with a warning, since nothing\n * stands in for it.\n *\n * `declared` are the other models the document declares — the components'\n * own field models, settled first (`settleFieldInlineModels`) and merged\n * later (`mergeFieldInlineModels`) — which own their names here exactly as\n * the components do, as they do in the shape registry: an inline model\n * named like one folds onto it when it admits the shape and takes a\n * qualified name otherwise, decided bottom-up before its parent is compared\n * with anything. Read by name alone, a nested object of a response named\n * like a component field's model would pass for it under a parent the\n * lifted model admits, and be left behind, renamed, once the field merge\n * told the two apart. They are not returned: the caller merges them itself.\n */\nexport function mergeInlineResponseModels(\n  schemaModels: Model[],\n  inlineModels: Model[],\n  naming?: InlineModelNaming,\n  declared: Model[] = [],\n): Model[] {\n  return [\n    ...schemaModels,\n    ...settleAgainstComponents([...schemaModels, ...declared], inlineModels, naming, new Set(declared)),\n  ];\n}\n\n/**\n * Settle the components' own inline field models against the components —\n * the first merge step, run as soon as both are extracted and before any\n * operation or webhook is read (see `parseSpec`): a field object, array\n * item or union variant named like a component shares the name when the\n * component admits it — a deprecated one beside a live component included,\n * the field keeping the flag; only an identical one when the SDK only sends\n * its component (`InlineModelBundle.sent`) — and is dropped, the field\n * resolving to the component; one the component does not admit, one of\n * either flag beside a deprecated component included (#441), takes its\n * qualified name now (`PetOwner2`), its field and every `allOf` copy of it repointed\n * (`settleSharedNames`). Settling the fields first means every\n * later comparison with a component — the shape registry's, the response\n * merge's — reads the component's children by their final names, so a body\n * that `$ref`s a component `GetPetResponseOwner` is never admitted by a\n * component whose `owner` was an inline object of another shape that only\n * later becomes `GetPetResponseOwner2`. A field model named like one of the\n * document's enums (`naming.enums`) — a `Pet.owner` object beside a\n * component enum `PetOwner` — takes its qualified name here too (`PetOwner2`),\n * whatever its shape, so the IR never declares a model and an enum under one\n * name. Returns the field models still competing for a name, the renamed\n * ones under their new names; the response merge that follows settles the\n * operations' and webhooks' models against them as against the components\n * (`mergeInlineResponseModels`, `declared`), and the field merge folds them\n * in (`mergeFieldInlineModels`). A copy dropped here for the object the\n * schema pass itself lifted from the same field needs no record: that\n * object is in the field's site from the moment it is lifted\n * (`fieldInlineModelBundles`, `liftedFieldModelsOf`).\n */\nexport function settleFieldInlineModels(\n  components: Model[],\n  fieldInlineModels: Model[],\n  naming?: InlineModelNaming,\n): Model[] {\n  return settleAgainstComponents(components, fieldInlineModels, naming);\n}\n\n/**\n * `contenders` settled against `components` (`settleSharedNames`), minus\n * those that folded onto one and those still named like one — a kept copy\n * still carrying a component's name had no site to be renamed from, and the\n * component's definition stands — then one definition per name among what\n * is left (`keepLargestByName`, the pass's own choice, the folded copies'\n * sites carried), so what the caller returns, and what a later pass meets\n * under a name, is the definition that survives. `yielding` names the\n * components that are field models standing in for components, which yield\n * a name to a live copy when deprecated (`settleSharedNames`).\n */\nfunction settleAgainstComponents(\n  components: Model[],\n  contenders: Model[],\n  naming?: InlineModelNaming,\n  yielding?: ReadonlySet<Model>,\n): Model[] {\n  const owners = new Map(components.map((m) => [m.name, m]));\n  const { kept } = settleSharedNames(owners, contenders, naming, yielding);\n  return keepLargestByName(\n    kept.filter((model) => !owners.has(model.name)),\n    naming,\n  );\n}\n\n/**\n * Fold the field extractor's inline models into the models gathered so far.\n * `componentNames` tells a clash with a real component schema apart from one\n * between two inline models: the components are the owners the field models\n * are settled against, and every other existing model — the response pass's\n * inline survivors — competes with the field models for its name like any\n * inline copy.\n *\n * `settleSharedNames` runs first with the components (every existing model,\n * when the caller does not say which are components) as owners: a field\n * model named like a component keeps the name only when the component\n * admits it (and is then dropped, the field resolving to the component) and\n * takes a qualified name otherwise, so a component is never replaced; and a\n * deprecated and a live definition of one name are told apart. The parser\n * has already settled its field models against the components\n * (`settleFieldInlineModels`) and the response pass's models against the\n * field models (`mergeInlineResponseModels`, `declared`), so for it no\n * survivor shares a field model's name any more and this step only folds\n * the field models in; a direct caller's field models are settled here,\n * and a field model of theirs named like an inline survivor of another\n * shape is dropped in favour of the survivor, with a warning naming both\n * shapes, as the earlier definition of an inline name is kept everywhere.\n * The fold below only joins models that agree on the flag. A field model\n * named like one of the document's enums\n * (`naming.enums`) — a `Pet.owner` object beside a component enum\n * `PetOwner` — takes a qualified name (`PetOwner2`) whatever its shape, as\n * the response pass's models do; the parser's field models meet that rule\n * when they are settled (`settleFieldInlineModels`), a direct caller's here.\n * A copy without a site to rename from (`naming`) is dropped in favour of\n * the component, with the settle pass's warning; one named like an enum is\n * kept beside it, with a warning.\n */\nexport function mergeFieldInlineModels(\n  existingModels: Model[],\n  fieldInlineModels: Model[],\n  componentNames?: Set<string>,\n  naming?: InlineModelNaming,\n): Model[] {\n  const isComponent = (m: Model): boolean => !componentNames || componentNames.has(m.name);\n  const owners = new Map(existingModels.filter(isComponent).map((m) => [m.name, m]));\n  const { kept, folded } = settleSharedNames(\n    owners,\n    [...existingModels.filter((m) => !isComponent(m)), ...fieldInlineModels],\n    naming,\n  );\n  const keptSet = new Set(kept);\n  // An existing inline model folded onto a live field copy of its shape\n  // gives the copy its place; a field copy folded onto anything is simply\n  // dropped.\n  const promoted = new Set<Model>();\n  const retainedModels: Model[] = [];\n  for (const model of existingModels) {\n    if (isComponent(model) || keptSet.has(model)) {\n      retainedModels.push(model);\n      continue;\n    }\n    const winner = folded.get(model);\n    if (winner) {\n      retainedModels.push(winner);\n      promoted.add(winner);\n    }\n  }\n\n  const modelsByName = new Map(retainedModels.map((m) => [m.name, m]));\n  const fieldList = (m: Model): string => m.fields.map((f) => f.name).join(', ') || '(no fields)';\n\n  const deduplicatedFieldModels = fieldInlineModels.filter((model) => {\n    if (!keptSet.has(model) || promoted.has(model)) return false;\n    const existing = modelsByName.get(model.name);\n    if (!existing) return true;\n    // Still named like a component: it could not be renamed (no site), and\n    // the component's definition stands.\n    if (isComponent(existing)) return false;\n\n    const existingFieldNames = new Set(existing.fields.map((f) => f.name));\n    const inlineFieldNames = new Set(model.fields.map((f) => f.name));\n    const hasDifference =\n      model.fields.some((f) => !existingFieldNames.has(f.name)) ||\n      existing.fields.some((f) => !inlineFieldNames.has(f.name));\n    if (hasDifference) {\n      console.warn(\n        `[oagen] Warning: Two inline models are named \"${model.name}\" (fields: ${fieldList(existing)} | ${fieldList(model)}) — keeping the first, the second is dropped`,\n      );\n    }\n    return false;\n  });\n\n  return [...retainedModels, ...keepLargestByName(deduplicatedFieldModels, naming)];\n}\n\nfunction hasModelConstDiscriminant(model: Model): boolean {\n  return model.fields.some(\n    (f) => (f.name === 'object' || f.name === 'type') && f.type.kind === 'literal' && typeof f.type.value === 'string',\n  );\n}\n\nfunction isModelReferencedByOthers(name: string, models: Model[], excludeNames: Set<string>): boolean {\n  for (const model of models) {\n    if (excludeNames.has(model.name)) continue;\n    for (const ref of collectModelTypeRefs(model)) {\n      let found = false;\n      walkTypeRef(ref, {\n        model: (r) => {\n          if (r.name === name) found = true;\n        },\n      });\n      if (found) return true;\n    }\n  }\n  return false;\n}\n\n/**\n * The shape `base` has once `json` folds onto it, as a model of its own:\n * `json`'s fields and its named-union metadata — `variants`,\n * `compositionKind` and `discriminator`, each present or absent exactly as\n * on `json`, so a fold never turns a named union back into a plain object —\n * the two models' own limits (minProperties, dependentRequired, ...) merged\n * with `json`'s winning where both speak, `base`'s own link and `x-*` keys\n * or `json`'s where it has none, and `base`'s name, description and\n * `deprecated`: deprecation names the type the SDK exposes, and that is\n * `base`, so a deprecated `<Name>Json` folded into a live `<Name>` leaves\n * `<Name>` live. The bases `json` is built on (`Model.bases`) come with its\n * fields, each field's `inheritedFrom` included — less a base whose own\n * chain of bases, read through `models`, reaches `base` by either name:\n * `base` itself (`PetJson: { allOf: [{ $ref: Pet }], properties: { extra }\n * }` folded onto `Pet`) or a model built on it (`PetJson` on `Animal` on\n * `Pet`), since a model is no base of its own and the fold would close\n * the chain into a cycle; that entry is dropped and the fields it lent\n * are `base`'s own (#591, Greptile review: the fields came with their\n * origin and the bases were dropped, so a folded model named a base it did\n * not list; round two: `Pet` folded under `Animal`, which extends `Pet`).\n * A base that dispatches by rules `json` does not preserve is never folded\n * (`collapseJsonSuffixModels` refuses it), so this only ever adds union\n * metadata to a plain base or replaces a union's with identical rules. The\n * plan reads it to decide what the folded base admits before anything is\n * written; `applyFold` writes it. Every site that copies one model's shape\n * onto another goes through these two.\n */\nfunction foldedShape(base: Model, json: Model, models: readonly Model[]): Model {\n  const self = new Set([base.name, json.name]);\n  const byName = new Map(models.map((model) => [model.name, model]));\n  const reachesSelf = (name: string, visiting: Set<string>): boolean => {\n    if (self.has(name)) return true;\n    if (visiting.has(name)) return false;\n    visiting.add(name);\n    return (byName.get(name)?.bases ?? []).some((ref) => ref.kind === 'model' && reachesSelf(ref.name, visiting));\n  };\n  const ownOf = (ref: TypeRef | undefined): boolean => ref?.kind === 'model' && reachesSelf(ref.name, new Set());\n  const fields = json.fields.map((field) => {\n    if (!ownOf(field.inheritedFrom)) return field;\n    const { inheritedFrom: _self, ...own } = field;\n    return own;\n  });\n  const bases = (json.bases ?? []).filter((ref) => !ownOf(ref));\n  const shape: Model = { ...base, fields };\n  delete shape.bases;\n  delete shape.variants;\n  delete shape.compositionKind;\n  delete shape.discriminator;\n  if (bases.length > 0) shape.bases = bases;\n  if (json.variants) shape.variants = json.variants;\n  if (json.compositionKind) shape.compositionKind = json.compositionKind;\n  if (json.discriminator) shape.discriminator = json.discriminator;\n  if (json.constraints || base.constraints) shape.constraints = { ...base.constraints, ...json.constraints };\n  if (!base.externalDocs && json.externalDocs) shape.externalDocs = json.externalDocs;\n  if (!base.extensions && json.extensions) shape.extensions = json.extensions;\n  return shape;\n}\n\n/** Write `foldedShape(base, json, models)` onto `base`, in place. */\nfunction applyFold(base: Model, json: Model, models: readonly Model[]): void {\n  const shape = foldedShape(base, json, models);\n  delete base.bases;\n  delete base.variants;\n  delete base.compositionKind;\n  delete base.discriminator;\n  Object.assign(base, shape);\n}\n\n/**\n * The kind of a name the `…Json` fold reads: a model's, or an inline\n * enum's. A name is read among the names of its own kind and no other\n * (#534), so the fold keeps the two apart wherever it reads one.\n */\ntype NameKind = 'model' | 'enum';\n\n/**\n * A `<Name>Json` model, the `<Name>` model it may fold onto, and every name\n * the `…Json` model reaches (`reachedNames`), by kind — the only names its\n * fold may rename.\n */\ninterface FoldCandidate {\n  readonly jsonModel: Model;\n  readonly baseModel: Model;\n  readonly reached: Readonly<Record<NameKind, ReadonlySet<string>>>;\n}\n\n/**\n * Every name `jsonModel` reaches, by the kind that holds it. Under `model`:\n * its own name and the model references among its fields, variants and\n * mapping targets, and those of every model they name in turn (`byName`),\n * whatever that model is called; a reference no model of `byName` answers\n * is reached and goes no further. Under `enum`: the inline enum references\n * among the same. The two are kept apart because each kind follows only\n * names of its own kind (`foldReading`, #534).\n */\nfunction reachedNames(jsonModel: Model, byName: ReadonlyMap<string, Model>): FoldCandidate['reached'] {\n  const reached = { model: new Set([jsonModel.name]), enum: new Set<string>() };\n  const walked = new Set([jsonModel]);\n  const pending = [jsonModel];\n  const reach = (name: string): void => {\n    reached.model.add(name);\n    const model = byName.get(name);\n    if (model && !walked.has(model)) {\n      walked.add(model);\n      pending.push(model);\n    }\n  };\n  for (let model = pending.pop(); model; model = pending.pop()) {\n    for (const ref of collectModelTypeRefs(model)) {\n      walkTypeRef(ref, {\n        model: (r) => reach(r.name),\n        enum: (r) => {\n          if (r.values) reached.enum.add(r.name);\n        },\n      });\n    }\n    for (const target of Object.values(model.discriminator?.mapping ?? {})) reach(target);\n  }\n  return reached;\n}\n\n/**\n * How every name reads once a set of folds is applied (`foldReading`): one\n * reader per kind, the options every shape comparison of the fold reads\n * under (`ShapeReadOptions`).\n */\ninterface FoldReading {\n  readonly readModelName: (name: string) => string;\n  readonly readEnumName: (name: string) => string;\n}\n\n/**\n * How every name reads once the `accepted` folds are applied, as a function\n * of the names the models hold now, each kind read among the names of its\n * own kind: a name a fold renames (`innermostFold`: one its `…Json` model\n * reaches as that kind, that begins with that model's name as whole words)\n * reads with that prefix replaced by its base's reading, and the name that\n * gives is read in turn as the same kind, so a child that lands on a name\n * another child of its kind vacates follows it, while one that lands on a\n * name the other kind vacates stops there (#534). `PetJson` reads as `Pet`,\n * `PetJsonWithA` as `PetWithA`, and a model `PetJsonJsonThing` as `PetThing`\n * by way of a child model `PetJsonThing` — as `PetJsonThing` when the fold\n * reaches no model of that name, an inline enum `PetJsonThing` beside it\n * reading as `PetThing` on its own — and `NoteJsonPetJsonToy` as\n * `NotePetToy` under the folds of `NoteJsonPetJson` and `NoteJson`,\n * whichever the document declares first. Every step shortens the name, so\n * the reading ends, and it ends on a name that reads as itself, so no name\n * a model or an enum is renamed to is renamed again. A name no fold renames\n * reads as it is — `PetJsonPatch` beside a `PetJson` that never reaches it,\n * `PetJsonification` whether reached or not: the fold renames no literal\n * and no component enum.\n */\nfunction foldReading(accepted: readonly FoldCandidate[]): FoldReading {\n  const read: Record<NameKind, Map<string, string>> = { model: new Map(), enum: new Map() };\n  const reading = (name: string, kind: NameKind): string => {\n    const known = read[kind].get(name);\n    if (known !== undefined) return known;\n    const fold = innermostFold(accepted, name, kind);\n    // The base is a model whatever kind the name is: a `PetJsonMode` enum\n    // reads as `Pet`'s reading plus `Mode`.\n    const result = fold\n      ? reading(reading(fold.baseModel.name, 'model') + name.slice(fold.jsonModel.name.length), kind)\n      : name;\n    read[kind].set(name, result);\n    return result;\n  };\n  return { readModelName: (name) => reading(name, 'model'), readEnumName: (name) => reading(name, 'enum') };\n}\n\n/**\n * The accepted fold that renames `name`, a name of `kind`, first: of those\n * whose `…Json` model reaches it as that kind (`FoldCandidate.reached`) and\n * whose name it begins with as whole words — the next character, if any,\n * is no lower-case letter, so it starts a word of its own as `splitWords`\n * reads one (`PetJsonPatch`, `PetJson2`, never `PetJsonification`) — the\n * one with the longest name; none when no fold renames it. A model\n * `PetJsonMode` is renamed by a fold that reaches the model, never by one\n * that reaches only an inline enum of that name (#534).\n */\nfunction innermostFold(accepted: readonly FoldCandidate[], name: string, kind: NameKind): FoldCandidate | undefined {\n  let innermost: FoldCandidate | undefined;\n  for (const candidate of accepted) {\n    const prefix = candidate.jsonModel.name;\n    if (!candidate.reached[kind].has(name) || !name.startsWith(prefix) || /[a-z]/.test(name.charAt(prefix.length)))\n      continue;\n    if (!innermost || prefix.length > innermost.jsonModel.name.length) innermost = candidate;\n  }\n  return innermost;\n}\n\n/** The names of the models `model` dispatches to — every model reference among its variants — read under `readModelName`. */\nfunction variantModelNames(model: Model, readModelName: (name: string) => string): Set<string> {\n  const names = new Set<string>();\n  for (const variant of model.variants ?? []) walkTypeRef(variant, { model: (r) => names.add(readModelName(r.name)) });\n  return names;\n}\n\n/**\n * Fold every `<Name>Json` model that is a superset of a `<Name>` model onto\n * it: `<Name>` takes the `…Json` model's shape, every reference to the\n * `…Json` model resolves to `<Name>`, and every `<Name>Json…` child — a\n * model or inline enum the `…Json` model reaches (`reachedNames`) whose\n * name begins with `<Name>Json` as whole words, one the extractor named\n * under it or a component it references — is renamed `<Name>…`, or\n * collapsed onto the model that ends under that name when there is one. A\n * model merely spelled that way (`PetJsonPatch` beside a `PetJson` that\n * never reaches it, `PetJsonification`) is no child: it keeps its name and\n * has no say in the fold.\n *\n * Pass 1 keeps, as a candidate, each `…Json` model whose base admits the\n * fold on its own terms (the guards below, read against the models as the\n * document left them). Pass 2 decides the candidates together, so the\n * result depends on the document's names and shapes and never on the order\n * it declares them in: every name is read as it ends once the accepted\n * folds are applied (`foldReading` — a model's name among the models' and\n * an inline enum's among the inline enums', each kind following only names\n * of its own kind (#534); every model reference through\n * `ShapeReadOptions.readModelName` and every inline enum reference through\n * `readEnumName`), a base as the shape it takes (`foldedShape`), and\n *\n * - a candidate whose base dispatches by union rules the `…Json` model does\n *   not preserve, or declares a field the `…Json` model's does not admit\n *   (`fieldAdmits`), is refused;\n * - the models that end under one name are one group: with a model the\n *   folds leave under its own name among them, that model is the holder and\n *   must admit every other (`modelAdmits`), which collapses onto it;\n *   without one, every member must be equivalent (each admits each) and the\n *   first declared keeps the name while the others collapse onto it. A\n *   member not admitted refuses the fold that renames it — the innermost,\n *   when several do — with the union-rules warning when that fold's base\n *   dispatches to the name, else a shape warning. Two folds whose children\n *   would end under one name with different shapes refuse each other.\n * - a name an enum holds and no model keeps admits no model: a member\n *   renamed onto one — a component enum, or an inline enum a model,\n *   operation or webhook carries, read under the folds (the entry the\n *   component pass lifted under such an enum's old name, in `enums`, is\n *   read the same way: it holds that name only as long as the reference\n *   does) — refuses the fold that renames it, so a fold never puts a model\n *   and an enum under one name. A renamed model that lands on the name a\n *   renamed inline enum leaves is no such member: the model stops there\n *   while the enum reads on (#534).\n *\n * A refusal changes how the remaining names read, so the decision is\n * repeated over the folds still accepted until none is refused; a fold is\n * only ever refused, never re-admitted, so this ends. Only then is anything\n * written: each base takes its shape (`applyFold`), every reference is\n * repointed through the reading at once (`rewriteModelRefs`), the folded\n * `…Json` models and the collapsed members are dropped, and the names are\n * set. Nothing is collapsed by name alone, and nothing is half-applied.\n *\n * An inline enum a fold renames or removes was lifted into `enums` under\n * its old name by the component pass (a `…Json` component's field enum):\n * once no reference carries that name — every reference was renamed, or\n * the only one sat on a field the fold replaced (a base's own, which its\n * `…Json` model's of the same name takes the place of down a chain:\n * `PetJson.mode` under `PetJsonJson.mode`) or on a collapsed member\n * (`PetJsonCarrier.mode`, collapsed onto `PetCarrier`), and went with it —\n * the entry is dropped and the collectors that run after the fold lift the\n * reference that carries its reading afresh, the renamed reference or the\n * twin of the one that went (the field or member that took its place reads\n * to the same name) — onto the base's own enum when one has its members\n * (`PetJsonStatus` folds into `PetStatus`), under the new name otherwise\n * (`PetJsonMode` becomes `PetMode`), stepping around a different enum or a\n * model of that name as they do for any inline enum (`PetMode2` beside a\n * component model `PetMode`). So a model that lands on the old name\n * (`PetJsonJsonJsonMode` on `PetJsonMode`) never meets the entry there.\n * Each entry dropped is recorded in `foldedEnums` under its old name with\n * that reference, so the caller can note the name the collectors settle\n * on. An enum in `componentNames` is declared by the document and stays\n * whether referenced or not, as does an entry no reference carried going\n * in: the fold answers only for the references it renames or removes.\n */\nexport function collapseJsonSuffixModels(\n  models: Model[],\n  services: Service[],\n  webhooks: Webhook[] = [],\n  enums: Enum[] = [],\n  componentNames: ReadonlySet<string> = new Set(),\n  foldedEnums: Map<string, EnumRef> = new Map(),\n): Model[] {\n  const normalizedModels = [...models];\n  const byName = new Map(normalizedModels.map((m) => [m.name, m]));\n\n  // Pass 1: the candidates, each pair on its own, as the document left them.\n  const candidates: FoldCandidate[] = [];\n  for (const model of normalizedModels) {\n    if (!model.name.endsWith('Json')) continue;\n\n    const baseName = model.name.slice(0, -4);\n    const baseModel = byName.get(baseName);\n    if (!baseModel || model.fields.length <= baseModel.fields.length) continue;\n\n    const jsonFields = new Set(model.fields.map((f) => f.name));\n    const isSuperset = baseModel.fields.every((f) => jsonFields.has(f.name));\n    if (!isSuperset) continue;\n\n    // Guard: both models have a const discriminant — they are distinct entities\n    if (hasModelConstDiscriminant(model) && hasModelConstDiscriminant(baseModel)) continue;\n\n    // Guard: a third model explicitly references the Json-suffix model\n    if (isModelReferencedByOthers(model.name, normalizedModels, new Set([model.name, baseName]))) continue;\n\n    // Guard: a live Json model never folds onto a deprecated base — every\n    // live reference to it would then resolve to a deprecated type. (The\n    // other way round still folds: `<Name>` keeps its own, live, flag.)\n    if (baseModel.deprecated && !model.deprecated) {\n      console.warn(\n        `[oagen] Not merging \"${model.name}\" into \"${baseName}\": \"${baseName}\" is deprecated and \"${model.name}\" is live`,\n      );\n      continue;\n    }\n\n    candidates.push({ jsonModel: model, baseModel, reached: reachedNames(model, byName) });\n  }\n\n  // Pass 2: the folds that hold together, decided as a whole.\n  const unionRulesWarning = ({ jsonModel, baseModel }: FoldCandidate): string =>\n    `[oagen] Warning: Json-suffix model \"${jsonModel.name}\" does not preserve the union rules of \"${baseModel.name}\" — keeping both`;\n  const shapeWarning = ({ jsonModel, baseModel }: FoldCandidate, detail: string): string =>\n    `[oagen] Warning: Json-suffix model \"${jsonModel.name}\" does not preserve the shape of \"${baseModel.name}\": ${detail} — keeping both`;\n  const enumWarning = ({ jsonModel, baseModel }: FoldCandidate, child: Model, name: string): string =>\n    `[oagen] Warning: Json-suffix model \"${jsonModel.name}\" is not merged into \"${baseModel.name}\": \"${child.name}\" would be renamed \"${name}\", and enum \"${name}\" owns the name — keeping both`;\n\n  let accepted = candidates;\n  let read = foldReading(accepted);\n  for (;;) {\n    const { readModelName, readEnumName } = read;\n    const options: ShapeReadOptions = read;\n    const jsonOf = new Map(accepted.map((candidate) => [candidate.baseModel, candidate.jsonModel]));\n    // A `…Json` model that is itself a base (`PetJson` under `PetJsonJson`)\n    // passes on the shape it ends with, as the folds are applied.\n    const shapeOf = (model: Model): Model => {\n      const json = jsonOf.get(model);\n      return json ? foldedShape(model, shapeOf(json), models) : model;\n    };\n    const refused = new Set<FoldCandidate>();\n    const refuse = (candidate: FoldCandidate, warning: string): void => {\n      if (refused.has(candidate)) return;\n      refused.add(candidate);\n      console.warn(warning);\n    };\n\n    for (const candidate of accepted) {\n      const { jsonModel, baseModel } = candidate;\n\n      // Guard: the base is a union — a named union's variants, composition\n      // keyword and discriminator, or an allOf+oneOf dispatcher's mapping\n      // (such a base may have no fields at all) — that the Json model does\n      // not preserve: it has no variants or rules, or different ones.\n      // Folding would turn the dispatcher into a plain object, or swap its\n      // variants or rules, under operations that already use it (two\n      // undiscriminated unions share the rules `oneOf` while dispatching to\n      // different members). The variants and the mapping's targets are read\n      // under the folds on both sides, so `PetJsonWithName` matches\n      // `PetWithName`, and an inline `PetJsonState` enum matches `PetState`\n      // with the same members and no other; a literal, or a component\n      // enum, as it is. The models the variants name are compared below, as\n      // every folded child is. Identical shapes fold as before.\n      const baseShape = unionShapeKey(baseModel, (v) => typeShapeKey(v, options), { modelName: readModelName });\n      const jsonShape = unionShapeKey(jsonModel, (v) => typeShapeKey(v, options), { modelName: readModelName });\n      if (baseShape !== '' && baseShape !== jsonShape) {\n        refuse(candidate, unionRulesWarning(candidate));\n        continue;\n      }\n\n      // Guard: a field both declare must be one the Json model's describes\n      // every value of the base's for (`fieldAdmits`: the same type, limits,\n      // default and flags, the Json model's no stricter on requiredness or\n      // nullability), since the base takes the Json model's fields under\n      // operations that already use it. A field that shares only its name\n      // — `a: integer` beside `a: string`, or required beside optional —\n      // would retype the base, so the fold is refused.\n      const jsonFields = new Map(jsonModel.fields.map((f) => [f.name, f]));\n      const retyped = baseModel.fields.find((f) => !fieldAdmits(jsonFields.get(f.name)!, f, options));\n      if (retyped) refuse(candidate, shapeWarning(candidate, `field \"${retyped.name}\" has a different shape`));\n    }\n\n    // Guard: the models that end under one name. A `<Json>…` child that\n    // collapses — a variant model of the union, a nested object, or any\n    // model the `…Json` model reaches — must be admitted by the model it\n    // collapses onto (both read under the folds), since the child's\n    // references then resolve to it and a field the child adds would be\n    // lost: a variant of another shape is a different variant even when the\n    // fold would give it the base's name. The flag is read as `modelAdmits`\n    // reads it (`flagAdmits`): a deprecated child collapses onto a live\n    // holder, as a deprecated `<Name>Json` folds onto a live `<Name>`, a\n    // live child never onto a deprecated one, and a deprecated child onto a\n    // deprecated holder, as a deprecated `<Name>Json` folds onto a\n    // deprecated `<Name>` — the holder is the model under a folded name,\n    // not a declared owner measured against an inline copy, so\n    // `ownerFlagAdmits` (#441) is not asked here and a deprecated pair of\n    // children never refuses the merge of two components. A name an enum holds and no\n    // model keeps admits no child: a component enum, or an inline enum a\n    // model, operation or webhook carries, read as the folds leave it\n    // (`readEnumName`), which the collectors lift after the fold — a `toy`\n    // query enum `PetToy` of a `pet` service would step past a renamed\n    // `PetJsonToy`, and the parameter's type would hang on the fold. The\n    // entry the component pass lifted under an inline enum's old name\n    // (`enums`) is read the same way, since it holds that name only as long\n    // as a reference does: it is dropped below once the fold leaves none\n    // carrying it, whether every reference was renamed or the only one went\n    // with the folded `…Json` model or collapsed member that carried it (a\n    // twin on the base or the holder reads to the same name); a component\n    // enum is declared and keeps its name. The names are read\n    // per kind, so a renamed model that lands on a name a renamed inline\n    // enum leaves (`PetJsonJsonMode` on `PetJsonMode`, whose enum reads on\n    // as `PetMode`) meets no enum there (#534). A model the document\n    // already keeps under such a name is a holder like any other: a child\n    // collapsing onto it adds no type under the name.\n    const enumNames = new Set<string>();\n    for (const { name } of enums) enumNames.add(componentNames.has(name) ? name : readEnumName(name));\n    for (const ref of typeRefsInPlay(normalizedModels, services, webhooks)) {\n      walkTypeRef(ref, { enum: (r) => enumNames.add(r.values ? readEnumName(r.name) : r.name) });\n    }\n    const folded = new Set(accepted.map((candidate) => candidate.jsonModel));\n    const groups = new Map<string, Model[]>();\n    for (const model of normalizedModels) {\n      if (folded.has(model)) continue;\n      const name = readModelName(model.name);\n      const group = groups.get(name);\n      if (group) group.push(model);\n      else groups.set(name, [model]);\n    }\n    for (const [name, members] of groups) {\n      const holder = members.find((member) => member.name === name);\n      if (!holder && enumNames.has(name)) {\n        for (const member of members) {\n          const fold = innermostFold(accepted, member.name, 'model')!;\n          refuse(fold, enumWarning(fold, member, name));\n        }\n        continue;\n      }\n      if (members.length < 2) continue;\n      const admits = (owner: Model, member: Model): boolean => modelAdmits(shapeOf(owner), shapeOf(member), options);\n      const refuseMember = (member: Model, detail: string): void => {\n        const fold = innermostFold(accepted, member.name, 'model')!;\n        refuse(\n          fold,\n          variantModelNames(fold.baseModel, readModelName).has(name)\n            ? unionRulesWarning(fold)\n            : shapeWarning(fold, detail),\n        );\n      };\n      if (holder) {\n        for (const member of members) {\n          if (member !== holder && !admits(holder, member)) {\n            refuseMember(member, `\"${member.name}\" would fold onto \"${name}\", which has a different shape`);\n          }\n        }\n        continue;\n      }\n      const equivalent = (a: Model, b: Model): boolean => admits(a, b) && admits(b, a);\n      for (const member of members) {\n        const other = members.find((candidate) => candidate !== member && !equivalent(member, candidate));\n        if (other) {\n          refuseMember(\n            member,\n            `\"${member.name}\" would fold onto \"${name}\" beside \"${other.name}\", which has a different shape`,\n          );\n        }\n      }\n    }\n\n    if (refused.size === 0) break;\n    accepted = accepted.filter((candidate) => !refused.has(candidate));\n    read = foldReading(accepted);\n  }\n\n  // Apply: shapes, then names, then every reference the kept models, the\n  // operations and the webhooks hold, at once.\n  const renames = new Map<string, string>();\n  for (const model of normalizedModels) {\n    const name = read.readModelName(model.name);\n    if (name !== model.name) renames.set(model.name, name);\n  }\n  // The enum names a reference carries as the document stands, before a\n  // fold takes any away: the lifted entries the fold answers for below.\n  const carried = new Set<string>();\n  for (const ref of typeRefsInPlay(normalizedModels, services, webhooks)) {\n    walkTypeRef(ref, { enum: (r) => carried.add(r.name) });\n  }\n  // The deepest fold first: a base that is itself a folded `…Json` model\n  // (`PetJson` under `PetJsonJson`) takes its shape before its own base\n  // copies it, so `Pet` ends with `PetJsonJson`'s fields and keys whatever\n  // the declaration order. A chain's `…Json` names grow by `Json` a link.\n  const deepestFirst = [...accepted].sort((a, b) => b.jsonModel.name.length - a.jsonModel.name.length);\n  for (const { baseModel, jsonModel } of deepestFirst) applyFold(baseModel, jsonModel, models);\n\n  const removed = new Set<Model>(accepted.map((candidate) => candidate.jsonModel));\n  // The model that keeps each name: the one the folds leave under it, else\n  // the first declared of those that end under it.\n  const keepers = new Map<string, Model>();\n  for (const model of normalizedModels) {\n    if (removed.has(model)) continue;\n    const name = read.readModelName(model.name);\n    if (!keepers.has(name) || model.name === name) keepers.set(name, model);\n  }\n  for (const candidate of accepted) {\n    const { jsonModel, baseModel } = candidate;\n    console.warn(\n      `[oagen] Merged \"${jsonModel.name}\" into \"${read.readModelName(baseModel.name)}\" (${jsonModel.fields.length} fields, superset)`,\n    );\n    // e.g. when AuditLogSchemaJson → AuditLogSchema, also rename\n    // AuditLogSchemaJsonTarget → AuditLogSchemaTarget, or collapse it onto\n    // an AuditLogSchemaTarget that already exists.\n    for (const model of normalizedModels) {\n      if (removed.has(model) || innermostFold(accepted, model.name, 'model') !== candidate) continue;\n      const name = read.readModelName(model.name);\n      if (keepers.get(name) === model) {\n        console.warn(`[oagen] Renamed child \"${model.name}\" → \"${name}\"`);\n      } else {\n        removed.add(model);\n        console.warn(`[oagen] Collapsed child \"${model.name}\" into existing \"${name}\"`);\n      }\n    }\n  }\n  for (const model of normalizedModels) if (!removed.has(model)) model.name = read.readModelName(model.name);\n  const kept = normalizedModels.filter((m) => !removed.has(m));\n  // A folded `…Json` model's fields and variants are its base's now, and a\n  // collapsed member is gone, so each reference is rewritten once.\n  const enumRenames = rewriteModelRefs(kept, services, renames, webhooks, read.readEnumName);\n\n  // A lifted enum the fold left unreferenced: an entry a reference carried\n  // going in and none carries now, because every reference to it was\n  // renamed (`enumRenames`), or because the only one sat on a field the\n  // fold replaced — a base's own, which its `…Json` model's of the same\n  // name takes the place of down a chain — or on a collapsed member, and\n  // went with it. The entry is dropped either way, and noted under a\n  // reference that carries its reading now, one carrying its values, which\n  // the collectors lift: the first renamed from it, else the twin of the\n  // one that went — the field or member that took its place reads to the\n  // same name (`fieldAdmits`, `modelAdmits`), so a twin always carries it.\n  // A component enum stays, as does an entry no reference carried going in.\n  const inPlay = new Set<string>();\n  const carriers = new Map<string, EnumRef>();\n  for (const ref of typeRefsInPlay(kept, services, webhooks)) {\n    walkTypeRef(ref, {\n      enum: (r) => {\n        inPlay.add(r.name);\n        if (r.values && !carriers.has(r.name)) carriers.set(r.name, r);\n      },\n    });\n  }\n  const drop = (oldName: string, ref: EnumRef): void => {\n    const index = enums.findIndex((e) => e.name === oldName);\n    if (index < 0) return;\n    enums.splice(index, 1);\n    foldedEnums.set(oldName, ref);\n  };\n  for (const [oldName, ref] of enumRenames) {\n    if (!componentNames.has(oldName) && !inPlay.has(oldName)) drop(oldName, ref);\n  }\n  for (const name of enums.map((e) => e.name)) {\n    if (componentNames.has(name) || !carried.has(name) || inPlay.has(name)) continue;\n    drop(name, carriers.get(read.readEnumName(name))!);\n  }\n\n  return kept;\n}\n","import type { Enum, EnumValue, Model, Operation, ResponseHeader, Service, TypeRef, Webhook } from '../ir/types.js';\nimport {\n  walkTypeRef,\n  collectModelTypeRefs,\n  collectRequestBodyTypes,\n  collectResponseBodyTypes,\n  collectModelRefs,\n  collectWebhookTypeRefs,\n} from '../ir/types.js';\nimport { numberedName } from '../utils/naming.js';\nimport { collectInlineEnumFromRef } from './schemas.js';\nimport { enumValuesOf, sameEnumShape } from './enum-members.js';\nimport { isErrorStatusRange, STATUS_RANGE_LABELS } from './responses.js';\n\n/**\n * The step an operation-owned error body's enum takes past a taken name:\n * `<Op>Error<code>` → `<Op>Error<code>Body`, then `…Body2`, `…Body3`, … —\n * numbered under `Body`, the way the error models step in the shape\n * registry (`deferredNamingStem`, kind `error`), so an enum body and an\n * object body in the same spot take the same name (`distinctEnumName`).\n * Every error site passes it, and only an error site (`ownedErrorBodies`);\n * a status code or fallback label qualifies the other sites and numbers on\n * the bare name.\n */\nconst ERROR_BODY_STEP = 'Body';\n\n/**\n * Promote the inline enums a model's fields and named-union variants\n * declare to top-level enums. A field enum is named from its model and field alone\n * (`GetReportResponseStatus`, `ListPetsDefaultResponseStatus`), a name a\n * component enum — or the same field of another model — may already own with\n * other values; such a field is renamed to a distinct name before it is\n * promoted (`…Status2`), collision-aware like the operation pass below and the\n * way header and webhook enums are, so the field never points at the other\n * values. A taken name with the same members — values and per-value\n * deprecation (`sameEnumShape`) — is shared. A name a model owns is a clash\n * too, and the distinct name is never one of `models`' (see\n * `distinctEnumName`): a component field's enum named like a model\n * (`Pet.kind` beside a `PetKind` object) is left on its ref by\n * `extractSchemas` and promoted here as `PetKind2`.\n */\nexport function collectInlineEnumsFromModels(models: Model[], enums: Enum[]): void {\n  const enumNames = new Set(enums.map((e) => e.name));\n  const modelNames = new Set(models.map((model) => model.name));\n  for (const model of models) {\n    for (const ref of collectModelTypeRefs(model)) {\n      collectDistinctEnums(ref, undefined, enums, enumNames, modelNames);\n    }\n  }\n}\n\n/**\n * Collect inline enum definitions from operation parameters (query, path,\n * header, cookie), list-envelope companion fields, response headers, the\n * request body, every success body, error bodies, secondary and fallback\n * response bodies, and secondary request bodies, and promote them to\n * top-level enums so emitters can generate typed enum files.\n *\n * Every kind is collected collision-aware (`collectDistinctEnums`): a\n * parameter enum is named from the service and parameter name alone, so a\n * query parameter `error404` of a later operation derives the very name an\n * earlier operation's inline 404 enum body or `Error404` response header was\n * promoted under (`GetPetError404`), and whichever was collected first would\n * otherwise hand its values to the other's reference. A different value set\n * is renamed to a distinct name before it is promoted (`GetPetError404No2`);\n * identical members are shared, as a parameter repeated across the\n * operations of a service always was.\n *\n * `models` lets the walk continue into the models a header or secondary body\n * references — the ones the parser materialized for them, never a component\n * (`componentNames`), whose enums the model pass owns — so an enum nested in\n * such a model gets the same collision-aware treatment as one at the top: a\n * name a component enum already owns with other values is renamed, not\n * silently given the component's values. It is also the set of names a\n * renamed enum must step around (`distinctEnumName`), so pass every model of\n * the document, not only the ones to walk into.\n *\n * `shared` is the parser's record of every type reference a site shared\n * through `components/responses` wrote (`OperationExtractionResult.componentSites`:\n * the component's success, fallback or error body, a secondary body, a\n * header), by identity — the one record of which sites an operation owns and which a\n * component does. An enum such a site carries is named from the component\n * alone (`CardXMode`, `ProblemResponse`), so on a clash it steps by number\n * (`CardXMode2`, `ProblemResponse2`) — never by the status code, the\n * fallback label (`CardXModeDefault`, `CardXModeClientError`) or `Body`,\n * which qualify an operation's own sites — and every operation that returns\n * the component, at whatever key, settles on the one name. An error site\n * the record does not hold — `errors[].type`, a secondary body of an error\n * entry, a `4XX`/`5XX` range's body or secondary body — is the operation's\n * own, written as `<Op>Error<code>…`, and steps by `Body`\n * (`ownedErrorBodies`). The IR alone cannot tell a shared site from an\n * operation's (`CardXMode` is the name wherever the component is returned),\n * so the record is required: a caller that built `services` by hand passes\n * the references it shares, or an empty set when it declares no component\n * response.\n */\nexport function collectInlineEnumsFromOperations(\n  services: Service[],\n  enums: Enum[],\n  shared: ReadonlySet<TypeRef>,\n  models: readonly Model[] = [],\n  componentNames: ReadonlySet<string> = new Set(),\n): void {\n  // The record moved from the last argument to the third (workos/oagen#356),\n  // so a caller still on the old order hands the models list here and the\n  // record where `componentNames` is read; fail on the mismatch, by name,\n  // rather than inside `models.map` or, worse, silently.\n  if (!(shared instanceof Set)) {\n    throw new TypeError(\n      'collectInlineEnumsFromOperations(services, enums, shared, models?, componentNames?): `shared` must be the Set of ' +\n        `component-site references (\\`OperationExtractionResult.componentSites\\`), got ${describeArgument(shared)}`,\n    );\n  }\n  const enumNames = new Set(enums.map((e) => e.name));\n  const modelsByName = new Map(models.map((model) => [model.name, model]));\n  const modelNames = new Set(modelsByName.keys());\n  // Each materialized model is visited once, under the first qualifier that reaches it.\n  const visited = new Set<string>();\n  const collectThroughModels = (type: TypeRef, qualifier: string | undefined, steps: Set<string> | undefined): void => {\n    collectDistinctEnums(type, qualifier, enums, enumNames, modelNames, steps);\n    for (const name of collectModelRefs(type)) {\n      if (visited.has(name) || componentNames.has(name)) continue;\n      visited.add(name);\n      const model = modelsByName.get(name);\n      if (!model) continue;\n      for (const field of model.fields) collectThroughModels(field.type, qualifier, steps);\n    }\n  };\n  for (const service of services) {\n    for (const op of service.operations) {\n      // The names this operation's own sites stepped to, the only ones a\n      // later site of it may share as a step (`distinctEnumName`); a site\n      // a component response declares (`shared`) is the component's, so it\n      // neither reads nor adds to them.\n      const steps = new Set<string>();\n      for (const param of [\n        ...op.pathParams,\n        ...op.queryParams,\n        ...(op.bodyOwnedQueryParams ?? []),\n        ...op.headerParams,\n        ...(op.cookieParams ?? []),\n      ]) {\n        collectDistinctEnums(param.type, undefined, enums, enumNames, modelNames, steps);\n      }\n      // The iterator's item type is reached through `response` when detection\n      // unwrapped the data array, but an explicit `dataPath` can type it from\n      // the document — an inline enum, or an array or union holding one — on\n      // a body kept as a wrapper, where nothing else references it. It is\n      // walked on its own, like the envelope companions, under the name the\n      // path gave it (`ListPetsRecord`); one a component enum owns with other\n      // members falls back to a numeric suffix. A model it names is walked\n      // like a body's, so an enum nested in one is reached the same way.\n      if (op.pagination) collectThroughModels(op.pagination.itemType, undefined, steps);\n      for (const field of op.pagination?.envelopeFields ?? []) {\n        collectDistinctEnums(field.type, undefined, enums, enumNames, modelNames, steps);\n      }\n      // Response headers are typed like parameters, so an inline enum declared\n      // on one must reach `spec.enums` the same way or the IR would point at\n      // an enum no emitter ever generates. A header a component response\n      // declares (`shared`) carries no status code or fallback label: its\n      // enum steps by number, the same from every site that returns the\n      // component.\n      for (const { headers, qualifier } of responseHeaderGroups(op)) {\n        for (const header of headers) {\n          const own = !shared.has(header.type);\n          collectThroughModels(header.type, own ? qualifier : undefined, own ? steps : undefined);\n        }\n      }\n      // The request body and each success body are typed by `schemaToTypeRef`\n      // under the operation's `<Op>Request` / `<Op>Response` name (a success\n      // body's array items under `<Op>Item`), so one that is itself an inline\n      // enum, or an array of one, reaches no model and is promoted here —\n      // neither `collectResponseBodyTypes` nor the error loop below yields it\n      // (workos/oagen#281). Every `successResponses` entry is walked on its\n      // own under its status code, as its headers are: the 200 and the 202\n      // derive the same name, so a second body with other members steps to\n      // `CheckPetKindResponse202` (`CheckPetKindItem202` for an array of one),\n      // while identical members share. A lone success response, and the\n      // request body, carry no code and fall back to a numeric suffix\n      // (`GetPetKindResponse2`), as does a body a component response declares\n      // (`shared`) at any status code (`CardResponse2`). An enum nested in a\n      // body's model is collected with every other model's\n      // (`collectInlineEnumsFromModels`).\n      for (const { type, qualifier } of requestAndSuccessBodies(op)) {\n        const own = !shared.has(type);\n        collectDistinctEnums(type, own ? qualifier : undefined, enums, enumNames, modelNames, own ? steps : undefined);\n      }\n      // An error body that is itself an inline enum, or an array of one, is\n      // typed by `schemaToTypeRef` and reaches no model, so it is promoted\n      // here — after the headers, so a header enum of the same name keeps it\n      // as a header model would. An operation-owned body's name is already\n      // operation-qualified (`GetPetError404`); one a component, header or\n      // earlier error enum owns with other members steps to\n      // `GetPetError404Body`. No inline model holds it: the registry\n      // reserved it before any deferred model was named (`deferredEnumNames`\n      // in operations.ts), so an object `404` of another operation under\n      // the same stem is the one that stepped. An enum nested in an error\n      // body's model is collected with every other model's\n      // (`collectInlineEnumsFromModels`). A body a component response\n      // declares (`shared`, so not in `owned`) is the component's, not the\n      // operation's, and steps by number (`CardResponse2`) as it does at a\n      // `default` or range site.\n      const owned = ownedErrorBodies(op, shared);\n      for (const error of op.errors) {\n        if (!error.type) continue;\n        const own = owned.has(error.type);\n        collectDistinctEnums(\n          error.type,\n          own ? ERROR_BODY_STEP : undefined,\n          enums,\n          enumNames,\n          modelNames,\n          own ? steps : undefined,\n        );\n      }\n      // A body declared only for a secondary media type (`text/plain` next to\n      // `application/json`), or for a `default` or range response, is typed\n      // like a response body, so its inline enums are promoted the same way —\n      // a body that is itself an inline enum, or an array of one, reaches no\n      // model and is walked here; enums nested in its inline models are\n      // reached through them. Its name is already operation-qualified\n      // (`ListPetsDefaultResponse`) or the component's\n      // (`CardApplicationYamlResponse`, `shared`); a clash with a different\n      // value set falls back to a numeric suffix either way — except for an\n      // operation-owned error body (`owned`: a 4xx/5xx or `4XX`/`5XX` body\n      // under a secondary media type, a `4XX`/`5XX` range's body), named\n      // `<Op>Error<code>…` like `errors[].type`, which steps to `…Body` as\n      // that does.\n      for (const { type } of collectResponseBodyTypes(op)) {\n        collectThroughModels(type, owned.has(type) ? ERROR_BODY_STEP : undefined, shared.has(type) ? undefined : steps);\n      }\n      // A request body declared only for a secondary media type (`text/csv`\n      // next to `application/json`) is typed like one, with its name already\n      // operation-qualified (`ReplaceWidgetTextCsvRequest`), so its inline\n      // enums are promoted the same way.\n      for (const { type } of collectRequestBodyTypes(op)) {\n        collectThroughModels(type, undefined, steps);\n      }\n    }\n  }\n}\n\n/**\n * Promote the inline enums a webhook declares — on its header, query and\n * cookie parameters, or as its payload itself — to top-level enums, the way\n * response-header enums are: a name already taken by a different value set\n * is not silently shared (the webhook's reference would otherwise point at\n * an unrelated enum's values) but renamed to a distinct one before it is\n * promoted (`PetAdoptedXSource2`); a taken name with the same members is\n * shared, and the distinct name is never one of `models`'\n * (`distinctEnumName`). The parser's stem reservation keeps such a clash from\n * arising through `parseSpec`; this guards the IR for any caller. A payload\n * model's field enums are reached through `spec.models` by\n * `collectInlineEnumsFromModels`, since the model is materialized there.\n */\nexport function collectInlineEnumsFromWebhooks(\n  webhooks: Webhook[],\n  enums: Enum[],\n  models: readonly Model[] = [],\n): void {\n  const enumNames = new Set(enums.map((e) => e.name));\n  const modelNames = new Set(models.map((model) => model.name));\n  for (const webhook of webhooks) {\n    for (const ref of collectWebhookTypeRefs(webhook)) {\n      collectDistinctEnums(ref, undefined, enums, enumNames, modelNames);\n    }\n  }\n}\n\n/** What a misplaced argument is, for the signature error: `an array`, `undefined`, `an object`, … */\nfunction describeArgument(value: unknown): string {\n  if (Array.isArray(value)) return 'an array';\n  if (value === null) return 'null';\n  if (value === undefined) return 'undefined';\n  return `${/^[aeiou]/i.test(typeof value) ? 'an' : 'a'} ${typeof value}`;\n}\n\n/**\n * Every error body of one operation that the operation named itself, by\n * identity: its error sites — each `errors` entry's `type` and secondary\n * bodies, and the body and secondary bodies of each `4XX`/`5XX` range\n * (`isErrorStatusRange`) — less the ones a `components/responses` entry\n * declares (`shared`, `OperationExtractionResult.componentSites`). Each is\n * written as `<Op>Error<code>…` (`GetPetError404`,\n * `GetPetError404ApplicationYaml`, `GetPetError4Xx`), so an enum among them\n * steps by the same `Body` qualifier (`GetPetError4XxBody`); a shared body\n * among those sites is the component's (`ProblemResponse`) and steps by\n * number, as it does at a `default` site, so the one record decides both.\n */\nfunction ownedErrorBodies(op: Operation, shared: ReadonlySet<TypeRef>): ReadonlySet<TypeRef> {\n  const types = new Set<TypeRef>();\n  const own = (type: TypeRef | undefined): void => {\n    if (type && !shared.has(type)) types.add(type);\n  };\n  for (const error of op.errors) {\n    own(error.type);\n    for (const content of error.contents ?? []) own(content.type);\n  }\n  for (const range of op.rangeResponses ?? []) {\n    if (!isErrorStatusRange(range.range)) continue;\n    own(range.type);\n    for (const content of range.contents ?? []) own(content.type);\n  }\n  return types;\n}\n\n/**\n * Header lists to walk, each with the status-code qualifier that keeps a\n * colliding enum name apart. When `successResponses` exists the primary list\n * is the same array as its entry there, so the entries are walked with their\n * own codes instead of `responseHeaders`; a lone 2xx or 3xx response is not\n * listed in `successResponses` (set only for more than one), so its headers\n * get no qualifier — its `responseStatusCode` is deliberately not used here,\n * as qualifying by it would rename every enum such a header declares.\n */\nfunction responseHeaderGroups(op: Operation): Array<{ headers: ResponseHeader[]; qualifier?: string }> {\n  const groups: Array<{ headers: ResponseHeader[]; qualifier?: string }> = [];\n  if (op.successResponses) {\n    for (const entry of op.successResponses) {\n      if (entry.headers) groups.push({ headers: entry.headers, qualifier: String(entry.statusCode) });\n    }\n  } else if (op.responseHeaders) {\n    groups.push({ headers: op.responseHeaders });\n  }\n  for (const error of op.errors) {\n    if (error.headers) groups.push({ headers: error.headers, qualifier: String(error.statusCode) });\n  }\n  // A fallback response has no status code to qualify by; its label\n  // (`Default`, `ClientError`) qualifies its header models and enums, and\n  // names the inline body of a `default` or `1XX`–`3XX` response (a `4XX`\n  // or `5XX` body is named by its range key, `<Op>Error4Xx`).\n  if (op.defaultResponse?.headers) groups.push({ headers: op.defaultResponse.headers, qualifier: 'Default' });\n  for (const range of op.rangeResponses ?? []) {\n    if (range.headers) groups.push({ headers: range.headers, qualifier: STATUS_RANGE_LABELS[range.range] });\n  }\n  return groups;\n}\n\n/**\n * The bodies `collectResponseBodyTypes` leaves out because each is reached\n * through the entry's own `type`: the request body, then every success body,\n * each with the qualifier that keeps a colliding enum name apart. When\n * `successResponses` exists its entries are walked under their own status\n * codes — the primary's `type` is the very ref its entry carries, so\n * `response` is not walked again; a lone 2xx or 3xx response carries no\n * status code in the IR (`successResponses` is set only for more than one),\n * so `response` gets no qualifier, and neither does the request body. Error\n * bodies are walked by the caller under their own qualifier.\n */\nfunction requestAndSuccessBodies(op: Operation): Array<{ type: TypeRef; qualifier?: string }> {\n  const bodies: Array<{ type: TypeRef; qualifier?: string }> = [];\n  if (op.requestBody) bodies.push({ type: op.requestBody });\n  if (op.successResponses) {\n    for (const entry of op.successResponses) bodies.push({ type: entry.type, qualifier: String(entry.statusCode) });\n  } else {\n    bodies.push({ type: op.response });\n  }\n  return bodies;\n}\n\n/**\n * Promote the inline enums under a type reference — a response header's, a\n * secondary media type's or fallback response's body, a webhook parameter's\n * — without letting a taken name mislead. A response-header enum is named\n * from the service and header name alone, so `X-Policy` allowing\n * `fast`/`slow` on a 200 and `retry`/`stop` on a 429 would share one name\n * and whichever was collected first would silently win; a request parameter\n * named like the header, or a webhook parameter named like a component enum,\n * collides the same way. When the name is already taken by a different\n * member set — other values, or the same values with a different one\n * deprecated (`sameEnumShape`) — or by a model, the ref is renamed to a\n * distinct name before it is promoted: an enum and a model under one name\n * reach an emitter as one public symbol, so the name is checked against the\n * union of every model name (`modelNames`, every model of the document) and\n * every enum name (`enums`) before any minted enum keeps it, on every path\n * that promotes one — a field, a parameter, a response header, an error or\n * secondary body, a webhook parameter or payload. A taken name with the same\n * members is shared, as before; the first lifted copy's value descriptions\n * and link are the enum's. A component enum declared under a component\n * model's name is the document's own clash and is left as declared. `steps`\n * is the record of the names an operation's own sites stepped to, read and\n * extended here; a site no operation owns passes none.\n */\nfunction collectDistinctEnums(\n  ref: TypeRef,\n  qualifier: string | undefined,\n  enums: Enum[],\n  enumNames: Set<string>,\n  modelNames: ReadonlySet<string>,\n  steps?: Set<string>,\n): void {\n  walkTypeRef(ref, {\n    enum: (ref) => {\n      if (!ref.values) return;\n      const values = enumValuesOf(ref);\n      const existing = enums.find((e) => e.name === ref.name);\n      const ownedByOtherMembers = existing !== undefined && !sameEnumShape(existing.values, values);\n      const ownedByModel = existing === undefined && modelNames.has(ref.name);\n      if (ownedByOtherMembers || ownedByModel) {\n        ref.name = distinctEnumName(ref.name, values, qualifier, enums, modelNames, steps);\n        steps?.add(ref.name);\n      }\n      collectInlineEnumFromRef(ref, enums, enumNames);\n    },\n  });\n}\n\n/**\n * A name the same operation's own sites already stepped the stem to that\n * holds the same members (`steps`, `isNumericStep`), else the first name not\n * taken by a different member set, nor by a model: the base qualified by the\n * status code (`DocumentsXPolicy429`), then numeric suffixes\n * (`DocumentsXPolicy2`, `DocumentsXPolicy3`, ...), spelled by numberedName\n * (`PetSizeV2No2` for a base that ends in a digit). A site no operation owns\n * — a model's field, a webhook's, a component response's — passes no\n * `steps` and shares no step. An error body (`ERROR_BODY_STEP`) steps to\n * `GetPetError404Body` and then numbers under it (`GetPetError404Body2`,\n * `GetPetError404Body3`, ...), as the error models do in the shape registry,\n * never on the bare name (`GetPetError404No2` is what a parameter named\n * `error404` steps to, a different site). Deterministic for a given spec,\n * since it depends only on declaration order. The collectors\n * run after every model is named, and the merge passes mint against every\n * enum name an `EnumRef` carries (`reservedTypeNames`) — but not against the\n * names chosen here, so this is the side that steps around the other: a\n * model a merge pass qualified to `GetLegacyWidgetWidget2`, because a\n * component enum owns `GetLegacyWidgetWidget`, sends a query enum of that\n * name with other members on to `GetLegacyWidgetWidget3`, and no enum\n * promoted by a collector takes a model's name.\n */\nfunction distinctEnumName(\n  base: string,\n  values: readonly EnumValue[],\n  qualifier: string | undefined,\n  enums: Enum[],\n  modelNames: ReadonlySet<string>,\n  steps: ReadonlySet<string> | undefined,\n): string {\n  const isUsable = (name: string): boolean => {\n    if (modelNames.has(name)) return false;\n    const taken = enums.find((e) => e.name === name);\n    return !taken || sameEnumShape(taken.values, values);\n  };\n  // The stem the numbered steps extend: the bare name, or `<base>Body` for\n  // an error body, whose numbers come under `Body` so an enum body and an\n  // object body past the same two taken names agree (`…Body2`).\n  const stem = qualifier === ERROR_BODY_STEP ? `${base}${qualifier}` : base;\n  // A name this operation's own sites already stepped the stem to for the\n  // same members (`steps`) — another status code's body or header (`…200`\n  // when this is the 202's), or an earlier numeric step (`…2` for a lone\n  // 2xx header beside its 503's) — is shared before a new one is minted, so\n  // identical members on two status codes never become two enums once their\n  // plain name is taken. Another operation's step (`PetsXPolicy429` for\n  // `listPets`'s 429), or a component that merely reads as one\n  // (`PetsStatus2024`, `GetPetKindResponse404`), is not in `steps` and is\n  // never shared this way: it names another site (workos/oagen#391). Only a\n  // digit-qualified name is a step of this stem: the fallback labels\n  // (`…Default`) qualify other sites, and `…Body` itself is shared through\n  // `isUsable` below.\n  const stepped = enums.find(\n    (e) =>\n      steps?.has(e.name) === true &&\n      isNumericStep(e.name, stem) &&\n      !modelNames.has(e.name) &&\n      sameEnumShape(e.values, values),\n  );\n  if (stepped) return stepped.name;\n  if (qualifier && isUsable(`${base}${qualifier}`)) return `${base}${qualifier}`;\n  let suffix = 2;\n  while (!isUsable(numberedName(stem, suffix))) suffix++;\n  return numberedName(stem, suffix);\n}\n\n/**\n * Whether `name` is a step of `base`: `base` followed by a status code\n * (`PetsXPolicy429`), or numbered as numberedName numbers it\n * (`PetsXPolicy2`, and `PetsXModeV2No2` for a base that ends in a digit).\n */\nfunction isNumericStep(name: string, base: string): boolean {\n  if (!name.startsWith(base)) return false;\n  const step = name.slice(base.length);\n  return /^\\d+$/.test(step) || (/\\d$/.test(base) && /^No\\d+$/.test(step));\n}\n","import type {\n  ApiSpec,\n  Enum,\n  Model,\n  Operation,\n  Parameter,\n  ParameterGroup,\n  ParameterGroupVariant,\n  Service,\n  TypeRef,\n} from '../ir/types.js';\nimport { enumShapeKey } from './enum-members.js';\nimport { unionShapeKey } from './union-shape.js';\n\n/**\n * Assign `ParameterGroup.wrapperName` across the whole spec.\n *\n * Emitters derive a group's generated wrapper type name from the group name\n * alone, so two operations sharing a group name (create and update both\n * declare `protocol_options`) collapse onto a single type. That is only sound\n * while the two declarations carry the same members. Where they differ, one\n * operation ends up typed with the other's member — e.g. a connection update\n * forced to pass `CreateConnectionSAMLOptions`, which accepts three fields the\n * PATCH endpoint rejects.\n *\n * This pass fingerprints every group's members structurally and qualifies the\n * wrapper name with the operation name only for groups that genuinely diverge.\n * Groups whose declarations agree keep the bare group name, so wrapper types\n * already published in the SDKs are never renamed.\n */\nexport function assignParameterGroupWrapperNames(spec: ApiSpec): void {\n  const modelMap = new Map(spec.models.map((m) => [m.name, m]));\n  const enumMap = new Map(spec.enums.map((e) => [e.name, e]));\n\n  // group name -> the distinct structural fingerprints seen for it\n  const fingerprints = new Map<string, Set<string>>();\n  const occurrences: Occurrence[] = [];\n\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      for (const group of op.parameterGroups ?? []) {\n        const fp = fingerprintGroup(group, modelMap, enumMap);\n        let seen = fingerprints.get(group.name);\n        if (!seen) {\n          seen = new Set();\n          fingerprints.set(group.name, seen);\n        }\n        seen.add(fp);\n        occurrences.push({ service, op, group, fingerprint: fp });\n      }\n    }\n  }\n\n  for (const { op, group } of occurrences) {\n    const diverges = (fingerprints.get(group.name)?.size ?? 0) > 1;\n    group.wrapperName = diverges ? `${op.name}_${group.name}` : group.name;\n  }\n\n  qualifyResidualCollisions(occurrences);\n  reconcileSharedGroups(occurrences.map((o) => o.group));\n}\n\ninterface Occurrence {\n  service: Service;\n  op: Operation;\n  group: ParameterGroup;\n  fingerprint: string;\n}\n\n/**\n * Break the collisions the operation-qualified name can still leave behind.\n *\n * `${op.name}_${group.name}` is not a unique key, for two separate reasons:\n *\n *  - `disambiguateOperationNames` makes operation names unique only *within* a\n *    service, so two services that each own an operation named `create`, both\n *    declaring a `password` group with different members, both land on\n *    `create_password`.\n *  - Within one service it deliberately leaves same-name operations alone when\n *    they share a path (see the `uniquePaths.size <= 1` guard — \"same path,\n *    different methods\"), so `PUT` and `PATCH` on one path both stay `update`\n *    and a service prefix alone still produces one name for both.\n *\n * Either way `reconcileSharedGroups` would then fuse two incompatible\n * declarations into a single type — the exact failure this pass exists to\n * prevent — and it does not drop the surplus member, so the wrapper would\n * expose a field one of the operations rejects.\n *\n * So escalate in rounds, adding a qualifier at a time and re-testing what still\n * collides. `(service, path, method)` identifies an operation uniquely, and a\n * same-name collision within a service implies a shared path, so service then\n * method is sufficient to separate every case.\n *\n * Each round only touches names that *still* group differing fingerprints, so a\n * name whose sharers agree is never renamed: sharing one wrapper is exactly what\n * should happen there, and renaming it would move a type the SDKs already\n * publish. On a spec where no qualified name collides — the WorkOS spec today —\n * the whole pass is a no-op.\n */\nfunction qualifyResidualCollisions(occurrences: Occurrence[]): void {\n  // Prepended in order, matching how the operation and group names already\n  // compose, so a fully-escalated name reads `<method>_<service>_<op>_<group>`.\n  const qualifiers: ((o: Occurrence) => string)[] = [(o) => o.service.name, (o) => o.op.httpMethod];\n\n  for (const qualify of qualifiers) {\n    for (const sharers of collidingCandidates(occurrences)) {\n      // A declaration still holding its group's own bare name owns that name.\n      // A qualified name can land on some *other* group's literal name — an\n      // `update` operation's `parent` group qualifies to `update_parent`, which\n      // may already be a group called `update_parent` — and that group is\n      // internally consistent, never diverged, and already published under it.\n      // Move only the declarations that have already been escalated; anything\n      // left fused falls through to the terminal round.\n      //\n      // This cannot strand a collision. Two groups sharing a literal name with\n      // differing structures always diverge on that name and are both qualified\n      // in the first assignment, so at most one member of a colliding set can\n      // still be bare. When one is, moving the rest separates them; in the\n      // degenerate case where none are movable, nothing moves here and the\n      // terminal round separates by structure regardless.\n      const movable = sharers.filter((o) => o.group.wrapperName !== o.group.name);\n      for (const o of movable) {\n        o.group.wrapperName = `${qualify(o)}_${o.group.wrapperName ?? o.group.name}`;\n      }\n    }\n  }\n\n  separateRemainingByStructure(occurrences);\n}\n\n/**\n * Terminal round: separate whatever the operation attributes could not.\n *\n * No combination of operation attributes is unique by construction. Two\n * operations in one service can share a name, a method *and* differ only by\n * path — `normalizeOperationIdForNaming` strips the `[N]` suffix, so a NestJS\n * controller method bound to several routes derives one name for all of them.\n * The WorkOS spec already contains such a pair (`Authorization`'s\n * `listRoleAssignments` on two paths); it declares no parameter groups today,\n * so nothing is wrong in the SDKs, but the shape is present rather than\n * hypothetical. Adding `path` as a fourth qualifier would only move the\n * boundary again.\n *\n * So stop enumerating attributes and separate by the thing that actually\n * matters: a name still fusing distinct structures gets one wrapper per\n * distinct fingerprint. That makes \"same `wrapperName` implies same structure\"\n * hold unconditionally, which is the invariant every emitter relies on.\n *\n * Suffixes are keyed on the fingerprint, not on a per-occurrence counter, so\n * declarations that agree keep sharing a wrapper.\n *\n * Ordering is by first appearance, not by sorted fingerprint: the structure\n * declared first keeps the unsuffixed name. Sorting by fingerprint would be\n * equally deterministic but less stable in the way that matters — adding a\n * member to one operation changes its fingerprint and could swap which of two\n * published wrappers holds the bare name. Under first-appearance order only\n * reordering the operations themselves can shift a name, which is both rarer\n * and visible in the spec diff.\n *\n * Either way this is a no-op wherever an earlier round already sufficed —\n * including the WorkOS spec, which never reaches this round at all.\n */\nfunction separateRemainingByStructure(occurrences: Occurrence[]): void {\n  const taken = new Set(occurrences.map((o) => o.group.wrapperName ?? o.group.name));\n\n  for (const sharers of collidingCandidates(occurrences)) {\n    const base = sharers[0].group.wrapperName ?? sharers[0].group.name;\n\n    // First fingerprint seen keeps `base`; each new one takes the next free\n    // `base_N`, skipping any name already spoken for elsewhere in the spec.\n    const nameFor = new Map<string, string>();\n    let n = 2;\n    for (const o of sharers) {\n      if (nameFor.has(o.fingerprint)) continue;\n      if (nameFor.size === 0) {\n        nameFor.set(o.fingerprint, base);\n        continue;\n      }\n      while (taken.has(`${base}_${n}`)) n++;\n      const name = `${base}_${n}`;\n      taken.add(name);\n      nameFor.set(o.fingerprint, name);\n      n++;\n    }\n\n    for (const o of sharers) o.group.wrapperName = nameFor.get(o.fingerprint)!;\n  }\n}\n\n/**\n * Candidate wrapper names shared by declarations that do not agree — the only\n * ones an escalation round may rename.\n */\nfunction collidingCandidates(occurrences: Occurrence[]): Occurrence[][] {\n  const byCandidate = new Map<string, Occurrence[]>();\n  for (const o of occurrences) {\n    const key = o.group.wrapperName ?? o.group.name;\n    const list = byCandidate.get(key);\n    if (list) list.push(o);\n    else byCandidate.set(key, [o]);\n  }\n  return [...byCandidate.values()].filter(\n    (sharers) => sharers.length > 1 && new Set(sharers.map((o) => o.fingerprint)).size > 1,\n  );\n}\n\n/**\n * Make every group that shares a `wrapperName` describe literally the same\n * type.\n *\n * Deciding two declarations may share one wrapper is only half the job. The\n * fingerprint deliberately ignores nullability and member order, so sharers can\n * still disagree on both — and each emitter renders the wrapper from whichever\n * operation it happens to reach first while rendering call sites from their own\n * operation. Kotlin showed the consequence: `ParentResource.ById.id` emitted as\n * `String` from one operation, while the Java-friendly overload built from\n * another passed a `String?` into it, and the SDK stopped compiling.\n *\n * So normalize the two axes the fingerprint waived:\n *   - a member the sharers disagree on settles as non-nullable. Widening to\n *     nullable instead reads as the friendlier choice, but the nullable form\n *     doesn't survive every emitter's group paths (Kotlin's query dispatch\n *     builds a `Pair<String, String>` from the member, which a `String?` can't\n *     satisfy), and non-nullable is what all sharers carried before group\n *     member types were resolved at all — so it changes no published surface.\n *     A member every sharer agrees is nullable stays nullable.\n *\n *     The cost: an operation whose spec really does accept null for a member\n *     (`PATCH` on a resource may clear `parent_resource_id`) can't express that\n *     through the shared wrapper. It never could — the member used to be a flat\n *     `string` everywhere — so nothing regresses, but the limitation is real and\n *     removing it means letting that group's wrapper split per operation.\n *   - member order follows the first sharer, so positional constructors and\n *     their call sites agree.\n */\nfunction reconcileSharedGroups(groups: ParameterGroup[]): void {\n  const byWrapper = new Map<string, ParameterGroup[]>();\n  for (const group of groups) {\n    const key = group.wrapperName ?? group.name;\n    const list = byWrapper.get(key);\n    if (list) list.push(group);\n    else byWrapper.set(key, [group]);\n  }\n\n  for (const sharers of byWrapper.values()) {\n    if (sharers.length < 2) continue;\n\n    for (const variant of sharers[0].variants) {\n      const peers = sharers\n        .slice(1)\n        .map((g) => g.variants.find((v) => v.name === variant.name))\n        .filter((v): v is ParameterGroupVariant => v !== undefined);\n      if (peers.length === 0) continue;\n\n      // Settle nullability: unanimously-nullable members stay nullable, and any\n      // member the sharers disagree on drops to non-nullable in all of them.\n      for (const member of variant.parameters) {\n        const all = [member, ...peers.map((p) => p.parameters.find((q) => q.name === member.name)).filter(isParameter)];\n        if (all.every((p) => p.type.kind === 'nullable')) continue;\n        for (const p of all) {\n          if (p.type.kind === 'nullable') p.type = p.type.inner;\n        }\n      }\n\n      // Align order on the first sharer's, leaving any member it doesn't\n      // declare in place at the end rather than dropping it.\n      const canonical = variant.parameters.map((p) => p.name);\n      for (const peer of peers) {\n        peer.parameters.sort((a, b) => {\n          const ia = canonical.indexOf(a.name);\n          const ib = canonical.indexOf(b.name);\n          if (ia === -1 && ib === -1) return 0;\n          if (ia === -1) return 1;\n          if (ib === -1) return -1;\n          return ia - ib;\n        });\n      }\n    }\n  }\n}\n\nfunction isParameter(p: Parameter | undefined): p is Parameter {\n  return p !== undefined;\n}\n\n/**\n * Structural fingerprint of a group: its variants, their members, and each\n * member's resolved shape. Two declarations with the same fingerprint can\n * safely share one generated wrapper type.\n */\nfunction fingerprintGroup(group: ParameterGroup, modelMap: Map<string, Model>, enumMap: Map<string, Enum>): string {\n  const variants = group.variants.map((v) => {\n    // Members are sorted by name: every emitter renders the wrapper as a\n    // named-field type (dataclass, data class, readonly promoted properties,\n    // struct variant), so two operations listing the same members in a\n    // different order still describe the same type and must keep sharing one\n    // wrapper rather than being renamed apart.\n    const members = [...v.parameters]\n      .sort((a, b) => a.name.localeCompare(b.name))\n      .map((p) => `${p.name}:${fingerprintType(p.type, modelMap, enumMap, new Set())}`);\n    const optional = [...(v.optionalParameters ?? [])].sort();\n    return `${v.name}(${members.join(',')})[${optional.join(',')}]`;\n  });\n  // `optional` is deliberately excluded: whether the group as a whole may be\n  // omitted is a property of the operation's signature, not of the wrapper\n  // type, and create/update legitimately differ there (required vs optional)\n  // while sharing an identical wrapper.\n  return variants.join('|');\n}\n\n/**\n * Fingerprint a type by shape rather than by name.\n *\n * Names cannot be compared directly because the parser synthesizes a separate\n * name per declaration site for inline schemas: `create_user` and `update_user`\n * each get their own `PasswordHashType` enum, spelled `CreateUserPasswordHashType`\n * and `UpdateUserPasswordHashType`, though their values are identical. Comparing\n * names would report divergence and rename a wrapper for no reason.\n *\n * Nullability is also stripped: an update declaring a member nullable while\n * create declares it plain is not a reason to split the wrapper type.\n */\nfunction fingerprintType(\n  ref: TypeRef,\n  modelMap: Map<string, Model>,\n  enumMap: Map<string, Enum>,\n  visiting: Set<string>,\n): string {\n  switch (ref.kind) {\n    case 'nullable':\n      // Widening only — a nullable and a non-nullable member are compatible.\n      return fingerprintType(ref.inner, modelMap, enumMap, visiting);\n    case 'primitive':\n      return `p:${ref.type}`;\n    case 'literal':\n      return `l:${typeof ref.value}:${String(ref.value)}`;\n    case 'array':\n      return `a<${fingerprintType(ref.items, modelMap, enumMap, visiting)}>`;\n    case 'map':\n      return `m<${fingerprintType(ref.valueType, modelMap, enumMap, visiting)}>`;\n    case 'union':\n      // Sorted, like enum values and model fields: a union accepts the same set\n      // of types whichever order the branches are written in, so two operations\n      // listing equivalent branches differently describe the same type and must\n      // keep sharing a wrapper rather than renaming a published one apart.\n      return `u<${ref.variants\n        .map((v) => fingerprintType(v, modelMap, enumMap, visiting))\n        .sort()\n        .join(',')}>`;\n    case 'enum': {\n      const e = enumMap.get(ref.name);\n      if (!e) return `e:${ref.name}`;\n      // Values, not the synthesized name — two inline copies of one enum are\n      // the same type for wrapper-sharing purposes. The value's primitive type\n      // is part of the fingerprint (as it is for `literal`): the IR keeps\n      // numeric `5` and string `\"5\"` distinct, and so do the emitters, so two\n      // enums that stringify alike are still different types. So is each\n      // value's deprecation (`enumShapeKey`): a copy that deprecates a value\n      // the other does not is a different type, as a deprecated model is\n      // from a live one.\n      //\n      // Sorted, like model fields and group members above: declaration order of\n      // enum values does not change which values the member accepts, so two\n      // inline enums listing one set in different orders must keep sharing a\n      // wrapper rather than renaming an already-published type apart.\n      return `e<${enumShapeKey(e.values)}>`;\n    }\n    case 'model': {\n      const m = modelMap.get(ref.name);\n      if (!m) return `M:${ref.name}`;\n      // Recursion guard: a model reachable from itself fingerprints by name at\n      // the point of recurrence, which is enough to distinguish shapes.\n      if (visiting.has(ref.name)) return `M:${ref.name}`;\n      const next = new Set(visiting).add(ref.name);\n      const fields = [...m.fields]\n        .sort((a, b) => a.name.localeCompare(b.name))\n        .map((f) => `${f.name}${f.required ? '!' : '?'}:${fingerprintType(f.type, modelMap, enumMap, next)}`);\n      // A named union's variants are its shape too — sorted like a union\n      // TypeRef's, since order does not change what it accepts — and so are\n      // its dispatch rules: two unions with the same members but different\n      // discriminators are different member types and must not share a\n      // wrapper.\n      return `M<${fields.join(',')}>${unionShapeKey(m, (v) => fingerprintType(v, modelMap, enumMap, next), { sorted: true })}`;\n    }\n    default:\n      return 'unknown';\n  }\n}\n","import type { ApiSpec, Callback, TypeRef, Webhook } from '../ir/types.js';\nimport {\n  walkTypeRef,\n  callbackContext,\n  collectResponseHeaders,\n  collectRequestBodyTypes,\n  collectResponseBodyTypes,\n} from '../ir/types.js';\n\nexport function validateModelRefs(spec: ApiSpec): void {\n  const knownNames = new Set<string>();\n  for (const m of spec.models) knownNames.add(m.name);\n  for (const e of spec.enums) knownNames.add(e.name);\n\n  function walkRef(ref: TypeRef, context: string): void {\n    walkTypeRef(ref, {\n      model: (r) => {\n        if (!knownNames.has(r.name)) {\n          console.warn(`[oagen] Warning: Unresolved model reference \"${r.name}\" (context: ${context})`);\n        }\n      },\n    });\n  }\n\n  /** A webhook's or a callback's references, and its callbacks' after them, under `<context>.callbacks.<name>.<expression>.<method>` (#382). */\n  function walkReceived(node: Webhook, context: string): void {\n    for (const p of [...node.headerParams, ...node.queryParams, ...(node.cookieParams ?? [])]) {\n      walkRef(p.type, `${context}.${p.name}`);\n    }\n    if (node.requestBody) walkRef(node.requestBody, `${context}.requestBody`);\n    // The payload of every other media type, which shares no reference with `requestBody`.\n    for (const content of node.requestBodyContents ?? []) {\n      if (content.type !== node.requestBody) {\n        walkRef(content.type, `${context}.requestBodyContents.${content.contentType}`);\n      }\n    }\n    walkCallbacks(node, context);\n  }\n\n  function walkCallbacks(node: { callbacks?: Callback[] }, context: string): void {\n    for (const callback of node.callbacks ?? []) walkReceived(callback, callbackContext(context, callback));\n  }\n\n  for (const model of spec.models) {\n    for (const field of model.fields) {\n      walkRef(field.type, `${model.name}.${field.name}`);\n      if (field.inheritedFrom) walkRef(field.inheritedFrom, `${model.name}.${field.name}.inheritedFrom`);\n    }\n    for (const variant of model.variants ?? []) {\n      walkRef(variant, `${model.name}.variants`);\n    }\n    // The bases a composed component names (`Model.bases`; #591).\n    for (const base of model.bases ?? []) {\n      walkRef(base, `${model.name}.bases`);\n    }\n  }\n\n  for (const service of spec.services) {\n    for (const op of service.operations) {\n      for (const p of [\n        ...op.pathParams,\n        ...op.queryParams,\n        ...(op.bodyOwnedQueryParams ?? []),\n        ...op.headerParams,\n        ...(op.cookieParams ?? []),\n      ]) {\n        walkRef(p.type, `${service.name}.${op.name}.${p.name}`);\n      }\n      if (op.requestBody) walkRef(op.requestBody, `${service.name}.${op.name}.requestBody`);\n      walkRef(op.response, `${service.name}.${op.name}.response`);\n      // Every other success entry's own type: the primary's is `response`.\n      for (const entry of op.successResponses ?? []) {\n        walkRef(entry.type, `${service.name}.${op.name}.successResponses.${entry.statusCode}`);\n      }\n      if (op.pagination) walkRef(op.pagination.itemType, `${service.name}.${op.name}.pagination.itemType`);\n      for (const field of op.pagination?.envelopeFields ?? []) {\n        walkRef(field.type, `${service.name}.${op.name}.pagination.${field.name}`);\n      }\n      for (const error of op.errors) {\n        if (error.type) walkRef(error.type, `${service.name}.${op.name}.errors.${error.statusCode}`);\n      }\n      for (const header of collectResponseHeaders(op)) {\n        walkRef(header.type, `${service.name}.${op.name}.headers.${header.name}`);\n      }\n      for (const { type, source } of collectResponseBodyTypes(op)) {\n        walkRef(type, `${service.name}.${op.name}.${source}`);\n      }\n      for (const { type, source } of collectRequestBodyTypes(op)) {\n        walkRef(type, `${service.name}.${op.name}.${source}`);\n      }\n      // A body group's members are typed afresh from the body's variant\n      // schemas, so they are references of their own; a query group's are\n      // the operation's parameters, walked above.\n      for (const group of op.parameterGroups ?? []) {\n        for (const variant of group.variants) {\n          for (const p of variant.parameters) {\n            walkRef(p.type, `${service.name}.${op.name}.parameterGroups.${group.name}.${variant.name}.${p.name}`);\n          }\n        }\n      }\n      walkCallbacks(op, `${service.name}.${op.name}`);\n    }\n  }\n\n  for (const webhook of spec.webhooks ?? []) {\n    walkReceived(webhook, `webhooks.${webhook.name}.${webhook.httpMethod}`);\n  }\n}\n","import type {\n  ArrayType,\n  EnumRef,\n  Field,\n  MapType,\n  Model,\n  ModelRef,\n  NullableType,\n  TypeRef,\n  UnionType,\n} from '../ir/types.js';\nimport { assertNever, walkTypeRef } from '../ir/types.js';\nimport { shapeWithEnumFlags } from './enum-members.js';\nimport { stableStringify } from './inline-models.js';\nimport { isComponentModelRef } from './schemas.js';\n\n/**\n * Settle every model's `bases` and its fields' `inheritedFrom` once every\n * pass that builds, folds or renames a model has run — the last pass of\n * `parseSpec` — so the two keys describe the models as they end (#591,\n * Greptile review), `fields` untouched throughout:\n *\n * 1. No model's chain of bases reaches itself. A base whose own chain of\n *    bases, read through `models` by name, reaches the model — in a cyclic\n *    document (`A: { allOf: [{ $ref: B }] }`, `B: { allOf: [{ $ref: A }] }`),\n *    or once a `…Json` fold collapsed a base onto a kept model of the same\n *    shape (`PetJsonChild` onto `PetChild: { allOf: [{ $ref: PetJsonChild }]\n *    }` as `PetJson` folds onto `Pet`, directly or through a chain) — is\n *    dropped, and the fields it lent are the model's own. Decided on the\n *    graph as it stands before anything is dropped, so the models' order\n *    plays no part.\n * 2. A base named twice is one base, the first kept: a rename can send two\n *    bases to one name (`Bar` beside a `BarJson` folded onto it).\n * 3. A base is a base only while every field it ends with is on the model\n *    either as the model's own declaration — which overrides the base's,\n *    as `overrides.json`'s `name` does — or as the same field: same keys,\n *    same values, the type read as its final shape, an inline model built\n *    under either model (`PetMeta`, `AnimalMeta`) as it ends, a union's\n *    variants and mapping targets the same way, an inline enum by its\n *    values, a component by name (`sameField`) — so the model\n *    is its own fields plus its bases', and an emitter writing `extends`\n *    or an intersection of the bases types every field as `fields` does.\n *    Two bases declaring one property differently keep at most the one\n *    whose declaration the model carries: `Pet: { allOf: [{ $ref: Tagged\n *    }, { $ref: Kinded }] }` with `Tagged.tag: string` and `Kinded.tag:\n *    enum [cat, dog]` ends `Pet { tag?: string, kind? }` on `Tagged`\n *    alone, `kind` its own (#591 review: `Tagged & Kinded` types `tag` as\n *    the enum, and `interface Pet extends Tagged, Kinded {}` does not\n *    compile); the other way round, on `Kinded` alone with `tag: PetTag`.\n *    A fold that loosens a base after the model took its fields —\n *    `AnimalJson` declaring `name` optional beside `extra`, folded onto an\n *    `Animal` requiring `name`, under `Pet: { allOf: [{ $ref: Animal }] }`\n *    — leaves `Pet.name` required, so `Animal` is no base of `Pet` as it\n *    ends and `name` is `Pet`'s own. A field carries `inheritedFrom` only\n *    while its base stays.\n *\n * A base no model carries (a dangling reference) is left for\n * `validateModelRefs` to report.\n */\nexport function settleBases(models: readonly Model[]): void {\n  const byName = new Map(models.map((model) => [model.name, model]));\n  dropCircularBases(models, byName);\n  for (const model of models) {\n    if (!model.bases) continue;\n    dedupeBases(model);\n    // Whether each field is the model's own (no origin) or taken from a\n    // base, as the model stands before any base is dropped here, so the\n    // outcome does not depend on the order of the bases.\n    const origins = new Map(\n      model.fields.map((field) => [\n        field.name,\n        field.inheritedFrom?.kind === 'model' ? field.inheritedFrom.name : null,\n      ]),\n    );\n    const carried = (field: Field): boolean => {\n      const own = model.fields.find((candidate) => candidate.name === field.name);\n      if (!own) return false;\n      return origins.get(field.name) === null || sameField(own, field, byName, new Map());\n    };\n    const dropped: string[] = [];\n    for (const base of model.bases) {\n      const target = base.kind === 'model' ? byName.get(base.name) : undefined;\n      if (target && !target.fields.every(carried)) dropped.push(target.name);\n    }\n    for (const name of dropped) dropBase(model, name);\n    // A field inherited from no base that stays is the model's own.\n    const remaining = new Set(model.bases.flatMap((ref) => (ref.kind === 'model' ? [ref.name] : [])));\n    for (const field of model.fields) {\n      if (field.inheritedFrom?.kind === 'model' && !remaining.has(field.inheritedFrom.name)) delete field.inheritedFrom;\n    }\n    if (model.bases.length === 0) delete model.bases;\n  }\n}\n\n/** Step 1: drop, from every model, each base whose chain of bases reaches the model, with the `inheritedFrom` of the fields it lent. */\nfunction dropCircularBases(models: readonly Model[], byName: ReadonlyMap<string, Model>): void {\n  const reaches = (from: string, target: string, visiting: Set<string>): boolean => {\n    if (from === target) return true;\n    if (visiting.has(from)) return false;\n    visiting.add(from);\n    return (byName.get(from)?.bases ?? []).some((ref) => ref.kind === 'model' && reaches(ref.name, target, visiting));\n  };\n  const circular = new Map<Model, string[]>();\n  for (const model of models) {\n    const names: string[] = [];\n    for (const ref of model.bases ?? []) {\n      if (ref.kind === 'model' && reaches(ref.name, model.name, new Set())) names.push(ref.name);\n    }\n    if (names.length > 0) circular.set(model, names);\n  }\n  for (const [model, names] of circular) for (const name of names) dropBase(model, name);\n}\n\n/** Step 2: keep the first of two bases that name one model. */\nfunction dedupeBases(model: Model): void {\n  const bases = model.bases ?? [];\n  const named = new Set<string>();\n  const distinct = bases.filter((ref) => {\n    if (ref.kind !== 'model') return true;\n    if (named.has(ref.name)) return false;\n    named.add(ref.name);\n    return true;\n  });\n  if (distinct.length !== bases.length) bases.splice(0, bases.length, ...distinct);\n}\n\n/** Remove the base `name` from `model.bases`, in place, and the `inheritedFrom` of every field it lent. */\nfunction dropBase(model: Model, name: string): void {\n  const bases = model.bases ?? [];\n  const kept = bases.filter((ref) => !(ref.kind === 'model' && ref.name === name));\n  if (kept.length !== bases.length) bases.splice(0, bases.length, ...kept);\n  for (const field of model.fields) {\n    if (field.inheritedFrom?.kind === 'model' && field.inheritedFrom.name === name) delete field.inheritedFrom;\n  }\n}\n\n/**\n * Whether two fields are one field (step 3): every key but `inheritedFrom`\n * the same, and the type the same final shape (`sameType`) — a reference\n * to an inline model built under either model (`PetMeta`, `AnimalMeta`)\n * standing for that model as it ends, compared the same way in turn\n * (`sameModel`: its fields each by this test, its own keys beside them,\n * a pair of models met again on the way taken as one), a reference to a\n * component by name (`isComponentModelRef`: the same model on both sides),\n * an inline enum by its values and their flags alone, a component enum\n * by name — so a fold that changes a nested model under the base\n * (`AnimalMetaJson` onto `AnimalMeta`) is told from a name that only\n * differs by the model it was built under, and an unchanged inline enum\n * (`PetStatus` beside `AnimalStatus`) compares equal (Greptile review,\n * round six). Compared as values, never through a serialized key that\n * embeds a child's — which grew with each level of nesting (round seven).\n */\nfunction sameField(a: Field, b: Field, byName: ReadonlyMap<string, Model>, seen: ComparedPairs): boolean {\n  const { inheritedFrom: _originA, type: typeA, ...restA } = a;\n  const { inheritedFrom: _originB, type: typeB, ...restB } = b;\n  return stableStringify(restA) === stableStringify(restB) && sameType(typeA, typeB, byName, seen);\n}\n\n/** The pairs of models `sameModel` has entered, by identity: a pair met again on the way is one being compared, and is taken as one. */\ntype ComparedPairs = Map<Model, Set<Model>>;\n\n/** Whether two types are one final shape, as `sameField` reads them. */\nfunction sameType(a: TypeRef, b: TypeRef, byName: ReadonlyMap<string, Model>, seen: ComparedPairs): boolean {\n  if (a.kind !== b.kind) return false;\n  switch (a.kind) {\n    case 'primitive':\n    case 'literal':\n      return stableStringify(a) === stableStringify(b);\n    case 'array': {\n      const other = b as ArrayType;\n      return sameLimits(a.constraints, other.constraints) && sameType(a.items, other.items, byName, seen);\n    }\n    case 'nullable':\n      return sameType(a.inner, (b as NullableType).inner, byName, seen);\n    case 'map': {\n      const other = b as MapType;\n      if (!sameLimits(a.constraints, other.constraints)) return false;\n      if ((a.keyType === undefined) !== (other.keyType === undefined)) return false;\n      if (a.keyType && other.keyType && !sameType(a.keyType, other.keyType, byName, seen)) return false;\n      return sameType(a.valueType, other.valueType, byName, seen);\n    }\n    case 'union': {\n      const other = b as UnionType;\n      const { variants: _va, discriminator: discriminatorA, ...restA } = a;\n      const { variants: _vb, discriminator: discriminatorB, ...restB } = other;\n      if (stableStringify(restA) !== stableStringify(restB)) return false;\n      if (!sameDiscriminator(discriminatorA, discriminatorB, a.variants, other.variants, byName, seen)) return false;\n      return sameTypes(a.variants, other.variants, byName, seen);\n    }\n    case 'enum': {\n      const other = b as EnumRef;\n      if (a.values === undefined && other.values === undefined) return a.name === other.name;\n      return stableStringify(enumMembers(a)) === stableStringify(enumMembers(other));\n    }\n    case 'model': {\n      const other = b as ModelRef;\n      if (isComponentModelRef(a) || isComponentModelRef(other)) return a.name === other.name;\n      const modelA = byName.get(a.name);\n      const modelB = byName.get(other.name);\n      if (!modelA || !modelB) return a.name === other.name;\n      return sameModel(modelA, modelB, byName, seen);\n    }\n    default:\n      return assertNever(a);\n  }\n}\n\n/** Whether two type lists are one, pairwise. */\nfunction sameTypes(\n  a: readonly TypeRef[],\n  b: readonly TypeRef[],\n  byName: ReadonlyMap<string, Model>,\n  seen: ComparedPairs,\n): boolean {\n  return a.length === b.length && a.every((type, index) => sameType(type, b[index]!, byName, seen));\n}\n\n/** A `discriminator` as a union or a model carries it. */\ntype Discriminator = NonNullable<UnionType['discriminator']>;\n\n/**\n * Whether two discriminators dispatch alike: the same property and the\n * same keys, each key's target the same final shape — an inline variant\n * built under either model (`PetMeta` beside `AnimalMeta`, `DogPetMeta`\n * beside `DogAnimalMeta`) as it ends (`sameModel`), a component by name\n * (`componentNames`: the component references among the variants) — so a\n * mapping that names its targets by the model they were built under\n * compares as the variants do, not as strings (Greptile review, on the\n * merge after the maintainer's round).\n */\nfunction sameDiscriminator(\n  a: Discriminator | undefined,\n  b: Discriminator | undefined,\n  variantsA: readonly TypeRef[],\n  variantsB: readonly TypeRef[],\n  byName: ReadonlyMap<string, Model>,\n  seen: ComparedPairs,\n): boolean {\n  if (a === undefined || b === undefined) return a === b;\n  if (a.property !== b.property) return false;\n  const keys = Object.keys(a.mapping).sort();\n  if (stableStringify(keys) !== stableStringify(Object.keys(b.mapping).sort())) return false;\n  const components = new Set([...componentNames(variantsA), ...componentNames(variantsB)]);\n  return keys.every((key) => {\n    const nameA = a.mapping[key]!;\n    const nameB = b.mapping[key]!;\n    if (nameA === nameB) return true;\n    if (components.has(nameA) || components.has(nameB)) return false;\n    const modelA = byName.get(nameA);\n    const modelB = byName.get(nameB);\n    return modelA !== undefined && modelB !== undefined && sameModel(modelA, modelB, byName, seen);\n  });\n}\n\n/** The names of the component models referenced among `variants`, under any wrapper. */\nfunction componentNames(variants: readonly TypeRef[]): string[] {\n  const names: string[] = [];\n  for (const variant of variants) {\n    walkTypeRef(variant, {\n      model: (ref) => {\n        if (isComponentModelRef(ref)) names.push(ref.name);\n      },\n    });\n  }\n  return names;\n}\n\n/** Whether two sets of limits are one. */\nfunction sameLimits(a: unknown, b: unknown): boolean {\n  return stableStringify(a ?? null) === stableStringify(b ?? null);\n}\n\n/** An inline enum's members as `sameType` compares them: its values and, among them, the deprecated ones (`shapeWithEnumFlags`), its name set aside. */\nfunction enumMembers(ref: EnumRef): unknown {\n  const { name: _name, ...members } = shapeWithEnumFlags(ref) as EnumRef & { deprecatedValues?: unknown };\n  return members;\n}\n\n/**\n * Whether two inline models are one final shape: their own keys but the\n * name and the bases the same, the same field names, each field one by\n * `sameField`, and the same variants in order. A pair entered again on\n * the way — a model that reaches itself through a field — is taken as\n * one, so the walk ends; a difference found anywhere still answers for\n * the whole.\n */\nfunction sameModel(a: Model, b: Model, byName: ReadonlyMap<string, Model>, seen: ComparedPairs): boolean {\n  if (a === b) return true;\n  let pairs = seen.get(a);\n  if (pairs?.has(b)) return true;\n  if (!pairs) seen.set(a, (pairs = new Set()));\n  pairs.add(b);\n  const {\n    name: _nameA,\n    bases: _basesA,\n    fields: fieldsA,\n    variants: variantsA,\n    discriminator: discriminatorA,\n    ...restA\n  } = a;\n  const {\n    name: _nameB,\n    bases: _basesB,\n    fields: fieldsB,\n    variants: variantsB,\n    discriminator: discriminatorB,\n    ...restB\n  } = b;\n  if (stableStringify(restA) !== stableStringify(restB)) return false;\n  if (!sameDiscriminator(discriminatorA, discriminatorB, variantsA ?? [], variantsB ?? [], byName, seen)) return false;\n  if (fieldsA.length !== fieldsB.length) return false;\n  const byField = new Map(fieldsB.map((field) => [field.name, field]));\n  for (const field of fieldsA) {\n    const other = byField.get(field.name);\n    if (!other || !sameField(field, other, byName, seen)) return false;\n  }\n  if ((variantsA === undefined) !== (variantsB === undefined)) return false;\n  return !variantsA || !variantsB || sameTypes(variantsA, variantsB, byName, seen);\n}\n","/**\n * Collapse the models the parser materializes for inline error bodies onto a\n * handful of shared models named by shape.\n *\n * Since workos/oagen#243 every inline 4xx/5xx body is a model of its own,\n * `<Op>Error<code>` (#356), and two bodies share a model only when their\n * fingerprints agree — fields, types, every `const` and every description.\n * A document that writes its errors inline, one schema per error code, as a\n * generator such as NestJS does, declares hundreds of them: the WorkOS\n * document has 834 inline error bodies in 13 shapes, 433 of them\n * `{ message }` and 344 `{ code: <const>, message }`, and no SDK runtime\n * reads a single one of the 834 models — they reach a consumer as files,\n * barrel exports and round-trip tests only. Every emitter also writes the\n * models an operation references from `errors[].type`, so the per-operation\n * names (`ConnectionCreateError4222`, `WebhookEndpointsDeleteError404 =\n * DataIntegrationsUpsertApiKeyError404`) are what a reader of the SDK sees.\n *\n * This pass runs once the operations' models are merged and before the\n * inline-enum collectors (`parseSpec`). It reads every error site — each\n * `errors[]` entry's `type` and its secondary `contents[].type`, and the body\n * and secondary bodies of a `4XX`/`5XX` range — and takes the models only\n * those sites reach (`errorOnly`): a component schema, a model a success\n * body, parameter, header, webhook or component also reaches, and a body a\n * `components/responses` entry declares (`componentSites`) are left exactly\n * as they are. The models it takes are keyed by their shape (`ModelKeys`),\n * and a body's shape is its required fields — a body that requires none, all\n * of them (`namedFields`): each one's name, its domain name (a `fieldHints`\n * entry) and its type, a nested error-only model by its own key, and a\n * string the document pins — `const: idp_metadata_fetch_failed`, an inline\n * `enum`, a plain `string` — all as one string, so the bodies that differ\n * only in their error code, their prose or their `x-` extensions fold onto\n * one model. An optional field is not shape (#506, #516): a body gains one\n * without leaving its group, and the group's model carries every optional\n * field any member declares. Nor is `deprecated` — the body's own or a\n * field's — shape (#441, #629): a body's name never depends on a flag, as\n * an inline copy's never depends on its own (`flagAdmits`), so a flag flip\n * moves no body; the shared model, and each of its fields, is deprecated\n * only when every member that carries it is, and a deprecated member, or\n * a member's deprecated field, folds onto a live one with a warning naming\n * each side (`sharedModelDeprecated`, `sharedDeprecated`), since the model\n * is a body's only carrier for the flag and the field its own. A field's\n * other flags, default and limits are not shape either, and the shared\n * model keeps them where every member agrees — the limits at every level\n * of the field's type, an array's items, a map's values and a union's\n * variants each kept or dropped on their own (#611) — as it keeps a\n * description; an optional field's domain name is kept when the members\n * that hint it agree, and dropped with a warning when they do not. A string\n * inside an array, union or map keeps its value in the key (`L\"a\"`,\n * `E[\"a\",\"b\"]`), since nothing combines values there, so two bodies that\n * list different codes in an array stay two models.\n *\n * Each group becomes one model, named from its shape alone (`bodyName`), so\n * that a name is a function of the shape and two shapes never ask for one\n * name (#515): `ErrorBody` for `{ message }`, `OAuthErrorBody` for the OAuth\n * error format `{ error, error_description }`, else the base plus `With` and\n * a token per further required field. The fields a family implies — a\n * `message`, or `error` and `error_description` in the OAuth format — and\n * the field a value-named group pins are left out of the name only while\n * they are plain strings (no `null`, no format, no domain name); otherwise\n * their token is spelled like any other (`ErrorBodyWithNullableMessage`,\n * `OAuthErrorBodyWithErrorInteger`, `GoneErrorBodyWithNullableCode`). A\n * body that has no required `message` says so\n * (`ErrorBodyWithCodeWithoutMessage` for `{ code }`). A field's token is its\n * name in PascalCase, qualified by what its type adds so that two shapes\n * with the same field names still read apart: `Nullable` leads a field that\n * admits `null` (`NullableMessage`), a scalar that is not a plain string\n * follows the name (`CodeInteger`, `CreatedAtDateTime`), a non-string\n * `const` or inline `enum` spells its values (`Status404`, `OkTrue`,\n * `Status404Or410`; behind `No` after a name ending in a digit), a domain\n * name follows it after `As` (`MessageAsDetail`), an array of plain values\n * ends in `List` (`MessageList`), a union joins its variants with `Or`\n * (`MessageOrMessageList`), and a nested error body is prefixed with the\n * tokens of every required field of its own, the ones the parent also has\n * included (`ErrorBodyWithCodeFieldErrors` for\n * `{ message, errors: [{ code, field }] }`, `ErrorBodyWithCodeMessageErrors`\n * for items `{ code, message }`). A body that requires no\n * field is named from every field it has, under `Optional`, so it never\n * takes a required shape's name (`OptionalErrorBody` for `{ message? }`,\n * `OptionalErrorBodyWithCode` for `{ code?, message? }`). A group whose\n * members all pin one required string field to one value is named from that\n * value instead (`RateLimitExceededErrorBody`, `InvalidGrantOAuthErrorBody`;\n * the field's name follows the value unless it is `code` or `error`), plus\n * `With` and the tokens of any further fields, a nested body's fields left\n * out (`OrganizationSelectionRequiredErrorBodyWithOrganizations`). A model\n * only another error body reaches is named from its parent and field\n * (`OrganizationSelectionRequiredErrorBodyWithOrganization`, singular for an\n * array item), plus its own fields when the field is optional in the parent,\n * whose name then says nothing of it (`ErrorBodyDetailWithReason` for\n * `{ message, detail?: { reason } }`). `ErrorBody` rather than\n * `ErrorResponse` because an emitter may already spend that name on a\n * component called `Error` (Go does).\n *\n * The pass never numbers a name. A shared name a component schema of that\n * shape already holds is that component for every member it can stand for\n * (`componentAccepts`) — one that is live (a deprecated component takes no\n * body, as it takes no inline copy anywhere else, #441, #629), that\n * declares every field the member has, required or optional as the member\n * has it and deprecated only where the member's is (a live field takes a\n * deprecated one, with a warning, as the live model takes a deprecated\n * body), of its type and domain name, no stricter in its limits at any\n * level of a field's type (an array's items, a map's values, a union's\n * variants; #611), and admitting every value the member pins:\n * those members fold onto it, and a member it cannot stand for is left as\n * it is, with a warning that prints that member's shape, so a body that\n * gains a field the component lacks moves alone. A name anything else holds\n * — a component of another shape, an enum, a shared body whose shape\n * differs in what no name can spell (a value pinned inside an array, a\n * discriminator mapping, the component or named enum a field references, a\n * field named like another field's qualifier, a pinned value that spells a\n * family prefix) — leaves the group's models exactly as the parser\n * materialized them, with every error-only model they reach or are reached\n * from, and says so in a warning that prints both shapes with their types;\n * the fold then runs again without them, since a freed name may now suit\n * another group. The groups are ordered by shape, never by operation: fewer\n * named fields first, a shape whose name is its field names alone before\n * one a qualifier spelled (`qualified`), then the key, so the same shape\n * keeps a contested name whichever operation declared it, and adding\n * `{ message, code: integer }` beside `{ message, code_integer }` (both\n * `ErrorBodyWithCodeInteger`) leaves the latter's model as it is.\n *\n * A string field a group pins to two or more values becomes an enum shared by\n * every error body that has a field of that name — `ErrorBodyCode` for\n * `code`, `ErrorBodyError` for an OAuth `error` — holding every value any\n * error body pins that field to, which the collectors lift as they lift any\n * inline enum (an emitter's enums admit an unlisted value, and the field's\n * prose says more may come). An enum of that name the document already holds\n * is shared when the members agree; when they do not, or a model holds the\n * name, the fields stay plain strings, with a warning. One value every\n * member pins stays that literal, and a lone pinned value beside free\n * strings widens to `string`. An optional field the members type\n * differently is the union of the types they wrote. A field's description,\n * example and extensions survive only when every member wrote the same one;\n * the response's own `description` stays on the `errors[]` entry, where it\n * always was.\n *\n * Every other inline enum a shared body's field lists — an integer or\n * number `enum`, a string `enum` under array items or map values or in a\n * union, through a nullable wrapper, on a nested body — is named from the\n * field and its values, never from the operation whose body happened to\n * sort first (#612): `ErrorBody<Field><Values>`, the values spelled as the\n * model's token spells them (`ErrorBodyStatus404Or410` for\n * `status: { type: integer, enum: [404, 410] }`, `ErrorBodyCodesAOrB` for\n * `codes: [{ enum: ['a', 'b'] }]`), one enum shared by every shared body\n * whose field of that name lists those values, and by a field that spells\n * alike and lists them (`errorCode` beside `error_code`). The name depends\n * on the field and its values alone, never on what else the document\n * declares, so adding, removing or renaming an operation moves no enum. A\n * name an enum of the same members already holds is shared; one anything\n * else holds leaves the bodies that list the set as they are, with a\n * warning, as a taken model name does.\n *\n * The references are rewritten in place, so the `contents` entry that shared\n * its `type` with the entry's `type` keeps sharing it. A `oneOf` of variants\n * that fold onto one model is no longer a union: duplicate variants are\n * dropped and a lone survivor replaces the union. The models the pass folds\n * are removed; the shared ones join the list.\n *\n * `collapseErrorBodies: false` on `ParseOptions` keeps the per-operation\n * models for a consumer that names them.\n */\nimport type {\n  Constraints,\n  Enum,\n  EnumRef,\n  EnumValue,\n  Field,\n  Model,\n  Service,\n  TypeRef,\n  UnionType,\n  Webhook,\n} from '../ir/types.js';\nimport {\n  collectModelRefs,\n  collectModelTypeRefs,\n  collectOperationTypeRefs,\n  collectWebhookTypeRefs,\n  renameTypeRefModels,\n  typeRefConstraints,\n  walkTypeRef,\n} from '../ir/types.js';\nimport { numberedName, singularize, toPascalCase } from '../utils/naming.js';\nimport { sameEnumShape } from './enum-members.js';\nimport { isErrorStatusRange } from './responses.js';\nimport { combineConstraints } from './schemas.js';\n\n/** The stem every shared error body is named from: `ErrorBody`, `ErrorBodyWithCode`, and the enums `ErrorBodyCode`, `ErrorBodyError`. */\nexport const ERROR_BODY_BASE = 'ErrorBody';\n\n/** The prefix of the family a body that requires no field is named in: `OptionalErrorBody` for `{ message? }` (#515). */\nconst OPTIONAL_PREFIX = 'Optional';\n\n/** The clause ending the name of a body that has no required `message`: `ErrorBodyWithCodeWithoutMessage` for `{ code }` (#515). */\nconst WITHOUT_MESSAGE = 'WithoutMessage';\n\nexport interface CollapseErrorBodiesInput {\n  services: Service[];\n  webhooks?: readonly Webhook[];\n  models: Model[];\n}\n\nexport interface CollapseErrorBodiesOptions {\n  /** The document's component schema names (after `schemaNameTransform`): never folded, and whatever they reach stays. */\n  componentNames: ReadonlySet<string>;\n  /**\n   * Type references a `components/responses` entry wrote\n   * (`OperationExtractionResult.componentSites`): the component's body is\n   * the component's, named after it, and is left alone.\n   */\n  componentSites?: ReadonlySet<TypeRef>;\n  /**\n   * The document's enums and every enum lifted before the pass. No shared\n   * model takes one of their names (bodies whose shared name an `ErrorBody`\n   * enum a component's `body` field minted would take are left as they\n   * are), and a shared enum takes the name of one of them only when the\n   * members agree, sharing it as the collectors share any inline enum.\n   */\n  enums?: readonly Enum[];\n}\n\n/**\n * Where an error body's type is read and written back: an `errors[]` entry's\n * `type`, each of its `contents[].type`, and the same two on a `4XX`/`5XX`\n * range. Held as accessors so a union a fold turns into one reference can be\n * replaced at every site that held the union object.\n */\ninterface ErrorSlot {\n  get(): TypeRef | undefined;\n  set(type: TypeRef): void;\n}\n\n/** What a group's members pin a string field to: every `const` or inline `enum` value, and whether any member leaves it a plain string. */\ninterface PinnedValues {\n  values: Set<string>;\n  open: boolean;\n}\n\n/**\n * Fold the error-only models of `input.models` onto shared, shape-named\n * models; rewrite every error site of `input.services` to reference them;\n * and return the model list with the folded models removed and the shared\n * ones appended. The services are mutated in place; `input.models` is not.\n */\nexport function collapseErrorBodies(input: CollapseErrorBodiesInput, options: CollapseErrorBodiesOptions): Model[] {\n  const operations = input.services.flatMap((service) => service.operations);\n  const componentSites = options.componentSites ?? new Set<TypeRef>();\n  const slots = errorSlots(operations).filter((slot) => {\n    const type = slot.get();\n    return type !== undefined && !componentSites.has(type);\n  });\n  if (slots.length === 0) return input.models;\n\n  const byName = new Map(input.models.map((model) => [model.name, model]));\n  const slotTypes = new Set(slots.map((slot) => slot.get()!));\n\n  // Everything a non-error site reaches is kept: the components and what\n  // they reach, every parameter, request body, success, default and\n  // non-error range body, every header (an error's headers included — a\n  // header is not a body), every webhook, and every component response site.\n  const keepRoots: string[] = [...options.componentNames];\n  for (const op of operations) {\n    for (const ref of collectOperationTypeRefs(op)) if (!slotTypes.has(ref)) keepRoots.push(...collectModelRefs(ref));\n  }\n  for (const webhook of input.webhooks ?? []) {\n    for (const ref of collectWebhookTypeRefs(webhook)) keepRoots.push(...collectModelRefs(ref));\n  }\n  for (const ref of componentSites) keepRoots.push(...collectModelRefs(ref));\n  const kept = closure(keepRoots, byName);\n\n  const errorRoots = [...slotTypes].flatMap((type) => collectModelRefs(type));\n  const errorOnly = new Set(\n    [...closure(errorRoots, byName)].filter(\n      (name) => !kept.has(name) && !options.componentNames.has(name) && byName.has(name),\n    ),\n  );\n  if (errorOnly.size === 0) return input.models;\n\n  // A group whose shared name something of another shape already holds is\n  // left as it is, with every error-only model it reaches or is reached\n  // from, and the fold is retried without them: a name that group had taken\n  // may suit another.\n  let candidates: ReadonlySet<string> = errorOnly;\n  for (;;) {\n    const outcome = fold(candidates, { input, options, byName, slots, errorRoots });\n    if (outcome.frozen.size === 0) return outcome.models;\n    candidates = new Set([...candidates].filter((name) => !outcome.frozen.has(name)));\n    if (candidates.size === 0) return input.models;\n  }\n}\n\ninterface FoldContext {\n  input: CollapseErrorBodiesInput;\n  options: CollapseErrorBodiesOptions;\n  byName: ReadonlyMap<string, Model>;\n  slots: readonly ErrorSlot[];\n  /** The model names every error site references directly. */\n  errorRoots: readonly string[];\n}\n\n/** What a name reads of the models around a body: which are error-only, and each by name. */\ninterface NamingContext {\n  errorOnly: ReadonlySet<string>;\n  byName: ReadonlyMap<string, Model>;\n}\n\n/**\n * One attempt at folding the error-only models `errorOnly`: the model list\n * with every group folded, or — when a shared name is taken by something of\n * another shape, or an inline enum's name by anything else (#612) — the\n * names of the models to leave as they are, so the caller can try again\n * without them.\n */\nfunction fold(\n  errorOnly: ReadonlySet<string>,\n  { input, options, byName, slots, errorRoots }: FoldContext,\n): { models: Model[]; frozen: ReadonlySet<string> } {\n  const naming: NamingContext = { errorOnly, byName };\n  // Group by shape, each group's members in name order.\n  const keys = new ModelKeys(errorOnly, byName);\n  const groups = new Map<string, Model[]>();\n  for (const name of [...errorOnly].sort()) {\n    const key = keys.of(name);\n    const group = groups.get(key);\n    if (group) group.push(byName.get(name)!);\n    else groups.set(key, [byName.get(name)!]);\n  }\n  // Groups are ordered by shape, never by the operations that produced them:\n  // fewer named fields first, then a shape whose name is its field names\n  // alone before one a qualifier spelled, then the key, so when two shapes\n  // ask for one name the same one keeps it whichever operation declared it,\n  // renaming an operation moves no model name, and a field named like\n  // another field's qualifier (`code_integer` beside `code: integer`, both\n  // `ErrorBodyWithCodeInteger`) keeps its model when the qualified shape is\n  // added.\n  const orderedGroups = [...groups.entries()].sort(([keyA, a], [keyB, b]) => {\n    const fields = namedFields(a[0]).length - namedFields(b[0]).length;\n    if (fields !== 0) return fields;\n    const plain = Number(qualified(a[0], naming)) - Number(qualified(b[0], naming));\n    return plain !== 0 ? plain : keyA < keyB ? -1 : keyA > keyB ? 1 : 0;\n  });\n  const pinnedByKey = new Map<string, Map<string, PinnedValues>>();\n  for (const [key, members] of orderedGroups) pinnedByKey.set(key, pinnedValues(members));\n\n  // The values every error body pins a field of one name to, across every\n  // group: the members of the shared enum that field becomes.\n  const enumValuesByField = new Map<string, Set<string>>();\n  for (const pinned of pinnedByKey.values()) {\n    for (const [field, { values }] of pinned) {\n      const all = enumValuesByField.get(field) ?? new Set<string>();\n      for (const value of values) all.add(value);\n      enumValuesByField.set(field, all);\n    }\n  }\n\n  // Name the groups: the ones an error site references directly first, from\n  // their pinned value or their fields; then the ones only another error\n  // body reaches, from their parent and field.\n  const topLevel = new Set(errorRoots.filter((name) => errorOnly.has(name)));\n  const existingEnums = options.enums ?? [];\n  // Who holds each name a shared model or enum might take.\n  const holders = new Map<string, string>();\n  for (const model of input.models) if (!errorOnly.has(model.name)) holders.set(model.name, `model \"${model.name}\"`);\n  // A component holder prints its shape, as a shared-body holder does, so\n  // the warning says what differs — a field flagged on one side alone\n  // included (#629).\n  for (const name of options.componentNames) {\n    const component = byName.get(name);\n    const shape = component === undefined ? '' : ` ${shapeOf(component)}`;\n    holders.set(name, `${component?.deprecated ? 'deprecated ' : ''}component schema \"${name}\"${shape}`);\n  }\n  for (const e of existingEnums) holders.set(e.name, `enum \"${e.name}\"`);\n  const canonical = new Map<string, string>(); // group key → shared name\n  const absorbed = new Set<string>(); // group keys folded onto a component of their shape\n  const seeds = new Set<string>(); // the models of the groups left as they are\n  // The deprecated bodies, and the deprecated fields, a live component\n  // took, announced once the fold is known to be kept: a name a group\n  // cannot take — a model's, or an inline enum's (#612) — makes the pass\n  // run again (`frozen`), and the same bodies fold again then.\n  const deprecatedFolds: Array<{ name: string; field?: string; deprecated: string[] }> = [];\n  // Mark `left` as the models of a group left as it is, and say so.\n  const leaving = (left: readonly Model[]): string => {\n    for (const member of left) seeds.add(member.name);\n    const list = left.map((member) => `\"${member.name}\"`).join(', ');\n    return left.length === 1 ? `model ${list} as it is` : `models ${list} as they are`;\n  };\n  const leave = (name: string, holder: string, left: readonly Model[]): void => {\n    console.warn(\n      `[oagen] Warning: The shared error body ${shapeOf(left[0])} would be named \"${name}\", which ${holder} already holds — keeping ${leaving(left)}; give the two the same shape, or rename one`,\n    );\n  };\n  // An inline enum whose name is taken leaves its bodies the same way (#612).\n  const leaveEnum = (field: string, name: string, holder: string, left: readonly Model[]): void => {\n    console.warn(\n      `[oagen] Warning: The inline enum the shared error body ${shapeOf(left[0])} lists for \"${field}\" would be named \"${name}\", which ${holder} already holds — keeping ${leaving(left)}; rename one`,\n    );\n  };\n  const claim = (name: string, key: string, members: readonly Model[]): void => {\n    const holder = holders.get(name);\n    if (holder === undefined) {\n      holders.set(name, `the shared error body \"${name}\" ${shapeOf(members[0])}`);\n      canonical.set(key, name);\n      return;\n    }\n    // A component schema of this shape is the shared body of every member\n    // it can stand for; a member it cannot — one with a field, a domain\n    // name, a limit or a pinned value the component does not admit, a live\n    // field the component deprecates, or any member when the component is\n    // deprecated — is left as it is, alone, with its own shape in the\n    // warning, and the fold runs again with the rest (#506, #629).\n    const component = byName.get(name);\n    if (component && !errorOnly.has(name) && keys.of(name) === key) {\n      const left = members.filter((member) => !componentAccepts(component, member, keys));\n      if (left.length === 0) {\n        // A deprecated body a live component takes, and a deprecated field\n        // a live field of the component takes, are announced, as a\n        // deprecated inline copy a live component admits is (#441, #629):\n        // the flag has no carrier once the body folds.\n        const deprecated = members.filter((member) => member.deprecated).map((member) => member.name);\n        if (deprecated.length > 0) deprecatedFolds.push({ name, deprecated });\n        for (const field of component.fields) {\n          if (field.deprecated) continue;\n          const flagged = members\n            .filter((member) => member.fields.some((own) => own.name === field.name && own.deprecated))\n            .map((member) => member.name);\n          if (flagged.length > 0) deprecatedFolds.push({ name, field: field.name, deprecated: flagged });\n        }\n        canonical.set(key, name);\n        absorbed.add(key);\n        return;\n      }\n      leave(name, holder, left);\n      return;\n    }\n    leave(name, holder, members);\n  };\n  const frozenOut = (members: readonly Model[]): boolean => members.some((member) => seeds.has(member.name));\n  for (const [key, members] of orderedGroups) {\n    if (!members.some((member) => topLevel.has(member.name))) continue;\n    claim(bodyName(members[0], pinnedByKey.get(key)!, naming), key, members);\n  }\n  // Every (parent, field) that reaches a nested error-only model, read on\n  // the models before the fold.\n  const parentsOf = new Map<string, Array<{ parent: Model; field: Field }>>();\n  for (const name of errorOnly) {\n    const model = byName.get(name)!;\n    for (const field of model.fields) {\n      for (const child of collectModelRefs(field.type)) {\n        if (!errorOnly.has(child) || child === name) continue;\n        const list = parentsOf.get(child) ?? [];\n        list.push({ parent: model, field });\n        parentsOf.set(child, list);\n      }\n    }\n  }\n  for (let progressed = true; progressed;) {\n    progressed = false;\n    for (const [key, members] of orderedGroups) {\n      if (canonical.has(key) || frozenOut(members)) continue;\n      const candidates = members\n        .flatMap((member) => parentsOf.get(member.name) ?? [])\n        .map(({ parent, field }) => {\n          const parentName = canonical.get(keys.of(parent.name));\n          return parentName === undefined ? undefined : nestedName(parentName, parent, field, members[0], naming);\n        })\n        .filter((candidate): candidate is string => candidate !== undefined)\n        .sort();\n      if (candidates.length === 0) continue;\n      claim(candidates[0], key, members);\n      progressed = true;\n    }\n  }\n  // A group nothing named reaches — only through a cycle among error bodies,\n  // or through a group left as it is — is named from its own fields.\n  for (const [key, members] of orderedGroups) {\n    if (!canonical.has(key) && !frozenOut(members)) {\n      claim(bodyName(members[0], pinnedByKey.get(key)!, naming), key, members);\n    }\n  }\n  if (seeds.size > 0) return { models: input.models, frozen: frozenClosure(seeds, errorOnly, byName) };\n\n  // The shared enums, one per field name some group pins to two or more\n  // values, named from the same pool as the models so neither takes the\n  // other's name; a field whose enum name is taken stays a plain string —\n  // said once no inline enum below leaves a body as it is, which discards\n  // this attempt, as the deprecated folds are announced.\n  const warnings: string[] = [];\n  const enumNamesByField = new Map<string, string>();\n  const widened = new Set<string>();\n  for (const [key] of orderedGroups) {\n    if (absorbed.has(key)) continue;\n    for (const [field, { values }] of pinnedByKey.get(key)!) {\n      if (values.size < 2 || enumNamesByField.has(field) || widened.has(field)) continue;\n      const base = `${ERROR_BODY_BASE}${toPascalCase(field)}`;\n      const members = [...(enumValuesByField.get(field) ?? values)].sort().map((value) => ({ name: value, value }));\n      // An enum of that name with the same members is shared, as the\n      // collectors share any inline enum.\n      const shared = existingEnums.find((e) => e.name === base && sameEnumShape(e.values, members));\n      if (shared) {\n        enumNamesByField.set(field, shared.name);\n        continue;\n      }\n      const holder = holders.get(base);\n      if (holder === undefined) {\n        holders.set(base, `the shared enum \"${base}\"`);\n        enumNamesByField.set(field, base);\n        continue;\n      }\n      widened.add(field);\n      warnings.push(\n        `[oagen] Warning: The values error bodies pin \"${field}\" to would be the shared enum \"${base}\", which ${holder} already holds — keeping those fields plain strings`,\n      );\n    }\n  }\n\n  // Every other inline enum a shared body's field lists is named from the\n  // field and its values, never from the operation whose body sorted first\n  // (#612): `ErrorBody<Field><Values>`, the values spelled as the model's\n  // token spells them, so the name depends on nothing else in the document\n  // and adding a body moves no enum. A name an enum of the same members\n  // holds — the document's, or one claimed here by a field that spells\n  // alike — is shared; one anything else holds leaves the bodies that list\n  // the set as they are, like a taken model name.\n  const inlineEnumNames = new Map<string, string>();\n  const claimedEnums = new Map<string, EnumValue[]>();\n  for (const [field, sets] of inlineEnumSets(orderedGroups, pinnedByKey, absorbed)) {\n    const word = toPascalCase(field);\n    for (const { values, groups } of sets.values()) {\n      const name = `${ERROR_BODY_BASE}${enumValuesToken(word, values)}`;\n      const members: EnumValue[] = values.map((value) => ({ name: String(value), value }));\n      const existing = existingEnums.find((e) => e.name === name);\n      const claimed = claimedEnums.get(name);\n      const shared = existing\n        ? sameEnumShape(existing.values, members)\n        : claimed\n          ? sameEnumShape(claimed, members)\n          : !holders.has(name);\n      if (!shared) {\n        for (const left of groups) leaveEnum(field, name, holders.get(name)!, left);\n        continue;\n      }\n      if (!existing && !claimed) {\n        holders.set(name, `the shared enum \"${name}\"`);\n        claimedEnums.set(name, members);\n      }\n      inlineEnumNames.set(inlineEnumKey(field, values), name);\n    }\n  }\n  if (seeds.size > 0) return { models: input.models, frozen: frozenClosure(seeds, errorOnly, byName) };\n  for (const { name, field, deprecated } of deprecatedFolds) {\n    warnDeprecatedFold(name, field, deprecated, `component schema \"${name}\"`);\n  }\n  for (const message of warnings) console.warn(message);\n\n  // Build the shared models.\n  const renames = new Map<string, string>();\n  for (const name of errorOnly) renames.set(name, canonical.get(keys.of(name))!);\n  const sharedModels: Model[] = [];\n  for (const [key, members] of orderedGroups) {\n    if (absorbed.has(key)) continue;\n    const pinned = pinnedByKey.get(key)!;\n    const model = buildSharedModel(canonical.get(key)!, members, pinned, enumValuesByField, enumNamesByField, renames);\n    // The inline enums the shared fields list take the names claimed above,\n    // read by field and values — so the fields the string rule built are\n    // left alone: its enum holds every value the bodies pin, under the\n    // name it claimed, whatever an array or map under the same field\n    // elsewhere lists — and the per-operation names the parser minted them\n    // under go with the models the fold removes.\n    for (const field of model.fields) {\n      if (pinned.has(field.name)) continue;\n      walkTypeRef(field.type, {\n        enum: (ref) => {\n          const name = ref.values && inlineEnumNames.get(inlineEnumKey(field.name, ref.values));\n          if (name !== undefined) ref.name = name;\n        },\n      });\n    }\n    sharedModels.push(model);\n  }\n\n  // Rewrite every error site, then fold the unions whose variants became one.\n  for (const slot of slots) renameTypeRefModels(slot.get()!, renames);\n  const simplified = new Map<TypeRef, TypeRef>();\n  for (const slot of slots) {\n    const type = slot.get()!;\n    let replacement = simplified.get(type);\n    if (replacement === undefined) {\n      replacement = simplifyType(type);\n      simplified.set(type, replacement);\n    }\n    if (replacement !== type) slot.set(replacement);\n  }\n\n  return {\n    models: [\n      ...input.models.filter((model) => !errorOnly.has(model.name)),\n      ...sharedModels.sort((a, b) => a.name.localeCompare(b.name)),\n    ],\n    frozen: new Set(),\n  };\n}\n\ntype OperationErrorSites = Pick<Service['operations'][number], 'errors' | 'rangeResponses'>;\n\n/** Every error site of `operations` (`ErrorSlot`), in document order. */\nfunction errorSlots(operations: readonly OperationErrorSites[]): ErrorSlot[] {\n  const slots: ErrorSlot[] = [];\n  const entrySlots = (entry: { type?: TypeRef; contents?: Array<{ type: TypeRef }> }): void => {\n    slots.push({\n      get: () => entry.type,\n      set: (type) => {\n        entry.type = type;\n      },\n    });\n    for (const content of entry.contents ?? []) {\n      slots.push({\n        get: () => content.type,\n        set: (type) => {\n          content.type = type;\n        },\n      });\n    }\n  };\n  for (const op of operations) {\n    for (const error of op.errors) entrySlots(error);\n    for (const range of op.rangeResponses ?? []) if (isErrorStatusRange(range.range)) entrySlots(range);\n  }\n  return slots;\n}\n\n/** Every model name reachable from `roots` through model fields and variants. */\nfunction closure(roots: readonly string[], byName: ReadonlyMap<string, Model>): Set<string> {\n  const reached = new Set<string>();\n  const stack = [...roots];\n  while (stack.length > 0) {\n    const name = stack.pop()!;\n    if (reached.has(name)) continue;\n    reached.add(name);\n    const model = byName.get(name);\n    if (!model) continue;\n    for (const ref of collectModelTypeRefs(model)) stack.push(...collectModelRefs(ref));\n  }\n  return reached;\n}\n\n/**\n * Every error-only model that stays with the models of the groups left as\n * they are (`seeds`): a model left as it is keeps its fields, so everything\n * it reaches stays too; and a shared parent would reference one member's\n * child and strand the others', so everything that reaches a frozen model\n * stays as well.\n */\nfunction frozenClosure(\n  seeds: ReadonlySet<string>,\n  errorOnly: ReadonlySet<string>,\n  byName: ReadonlyMap<string, Model>,\n): Set<string> {\n  const errorOnlyClosure = (roots: readonly string[]): string[] =>\n    [...closure(roots, byName)].filter((name) => errorOnly.has(name));\n  const frozen = new Set(errorOnlyClosure([...seeds]));\n  for (let grew = true; grew;) {\n    grew = false;\n    for (const name of errorOnly) {\n      if (frozen.has(name)) continue;\n      const reached = errorOnlyClosure([name]);\n      if (reached.some((other) => frozen.has(other))) {\n        for (const other of reached) frozen.add(other);\n        grew = true;\n      }\n    }\n  }\n  return frozen;\n}\n\n/**\n * The fields a body's key and name read: its required fields, since an\n * optional one added later must not move the body to another model (#506,\n * #516) — or, for a body that requires none, every field it has, which is\n * all there is to name it from (#515).\n */\nfunction namedFields(model: Model): Field[] {\n  const required = model.fields.filter((field) => field.required);\n  return required.length > 0 ? required : model.fields;\n}\n\nconst byFieldName = (a: Field, b: Field): number => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);\n\n/**\n * The shape of an error-only model, independent of its name, its optional\n * fields, its documentation, its flags and limits (its own `deprecated`\n * and its fields' included, #629), its `x-` extensions and the values its\n * string fields are pinned to. Memoized per model; a cycle among error\n * bodies reads as the name on the cycle.\n */\nclass ModelKeys {\n  private readonly keys = new Map<string, string>();\n  private readonly visiting = new Set<string>();\n\n  constructor(\n    private readonly errorOnly: ReadonlySet<string>,\n    private readonly byName: ReadonlyMap<string, Model>,\n  ) {}\n\n  of(name: string): string {\n    const cached = this.keys.get(name);\n    if (cached !== undefined) return cached;\n    if (this.visiting.has(name)) return `cycle:${name}`;\n    this.visiting.add(name);\n    const model = this.byName.get(name)!;\n    // Each named field's name, requiredness, domain name and type: exactly\n    // what `bodyName` spells, so two keys never ask for one name (#515).\n    const fields = namedFields(model)\n      .map(\n        (field) =>\n          `${field.name}${field.required ? '!' : '?'}${field.domainName === undefined ? '' : `~${field.domainName}`}=${this.type(field.type, true)}`,\n      )\n      .sort()\n      .join('|');\n    const own = stableJson({\n      typeParams: model.typeParams,\n      compositionKind: model.compositionKind,\n      variants: model.variants?.map((variant) => this.type(variant, false)).sort(),\n      discriminator: model.discriminator && this.discriminator(model.discriminator),\n    });\n    const key = `${fields}#${own}`;\n    this.visiting.delete(name);\n    this.keys.set(name, key);\n    return key;\n  }\n\n  /**\n   * A type's structure. A field's own type (`direct`, through a nullable\n   * wrapper) reads every way the document pins or frees a string as one `S`,\n   * since `sharedFieldType` reads those values across the group; a string\n   * inside an array, union or map keeps its value in the key (`L\"a\"`,\n   * `E[\"a\",\"b\"]`), since nothing combines values there, so two bodies that\n   * list different codes in an array stay two models. An inline enum's\n   * values are read sorted (`sortedEnumValues`), as the name spells them,\n   * so reordering its entries moves no body.\n   */\n  type(type: TypeRef, direct: boolean): string {\n    switch (type.kind) {\n      case 'literal':\n        return direct && typeof type.value === 'string' ? 'S' : `L${JSON.stringify(type.value)}`;\n      case 'enum':\n        if (direct && isStringValuedInlineEnum(type)) return 'S';\n        return type.values ? `E${JSON.stringify(sortedEnumValues(type.values))}` : `E:${type.name}`;\n      case 'primitive':\n        return direct && type.type === 'string' && !type.format ? 'S' : `P:${type.type}:${type.format ?? ''}`;\n      case 'model':\n        return this.errorOnly.has(type.name) ? `M{${this.of(type.name)}}` : `R:${type.name}`;\n      case 'array':\n        return `A[${this.type(type.items, false)}]`;\n      case 'nullable':\n        return `N(${this.type(type.inner, direct)})`;\n      case 'union': {\n        const variants = type.variants.map((variant) => this.type(variant, false)).sort();\n        const discriminator = type.discriminator ? this.discriminator(type.discriminator) : '';\n        return `U${type.compositionKind ?? ''}${discriminator}(${variants.join(',')})`;\n      }\n      case 'map':\n        return `Map(${type.keyType ? this.type(type.keyType, false) : ''};${this.type(type.valueType, false)})`;\n    }\n  }\n\n  /** A discriminator's property and every mapping entry, the target read as the variants are. */\n  private discriminator(discriminator: { property: string; mapping: Record<string, string> }): string {\n    const entries = Object.entries(discriminator.mapping)\n      .map(([value, target]) => `${value}=${this.errorOnly.has(target) ? `M{${this.of(target)}}` : `R:${target}`}`)\n      .sort();\n    return `@${discriminator.property}{${entries.join(',')}}`;\n  }\n}\n\n/**\n * One field per name the members declare, in the order the shared model\n * lists them: the first member's fields, then the optional fields each\n * later member adds, in its order.\n */\nfunction sharedFieldOrder(members: readonly Model[]): Field[] {\n  const order: Field[] = [];\n  const seen = new Set<string>();\n  for (const member of members) {\n    for (const field of member.fields) {\n      if (seen.has(field.name)) continue;\n      seen.add(field.name);\n      order.push(field);\n    }\n  }\n  return order;\n}\n\n/** The members' fields of one name, in member order; a member without the field adds none. */\nfunction siblingsOf(members: readonly Model[], name: string): Field[] {\n  return members.flatMap((member) => member.fields.filter((field) => field.name === name));\n}\n\n/**\n * For every field the members type as a string (by name), the values pinned\n * and whether any member leaves it free. An optional field a member lacks\n * neither pins nor frees it: that member's body never carries the field.\n */\nfunction pinnedValues(members: readonly Model[]): Map<string, PinnedValues> {\n  const pinned = new Map<string, PinnedValues>();\n  for (const field of sharedFieldOrder(members)) {\n    const inners = siblingsOf(members, field.name).map((sibling) => unwrapNullable(sibling.type));\n    if (!inners.every(isStringLike)) continue;\n    const entry: PinnedValues = { values: new Set(), open: false };\n    for (const inner of inners) {\n      if (inner.kind === 'literal' && typeof inner.value === 'string') entry.values.add(inner.value);\n      else if (inner.kind === 'enum' && isStringValuedInlineEnum(inner)) {\n        for (const value of inner.values!) entry.values.add(String(value));\n      } else entry.open = true;\n    }\n    pinned.set(field.name, entry);\n  }\n  return pinned;\n}\n\n/** The field set of the OAuth 2.0 error response. */\nconst OAUTH_ERROR_FIELDS = ['error', 'error_description'];\n\n/** The fields that carry an error code; a body pinned on one is named from the value alone. */\nconst ERROR_CODE_FIELDS = ['code', 'error'];\n\n/**\n * Whether `component`, whose key is the group's, can stand for `member`: it\n * is live — a deprecated component takes no body, live or deprecated, as it\n * takes no inline copy anywhere else (`ownerFlagAdmits`, #441, #629), so no\n * live site resolves to a deprecated model; it declares every field the\n * member has, required or optional as the member has it, and deprecated\n * only where the member's field is — a component whose field is deprecated\n * would give a live member's readers a notice its schema never wrote, while\n * one whose field is live takes a member's deprecated field as the live\n * model takes a deprecated body (`flagAdmits`), announced by `claim` since\n * the field is the flag's only carrier — of the member's type and domain\n * name, so no body loses a field or a hint by folding onto it; it is no\n * stricter than the member — every limit it writes, on itself, a field or any level\n * of the field's type (`typeNoStricter`: the type's own, an array's items,\n * a map's values, a union's variants; #611), the member writes the same, so\n * no body is narrowed by folding onto it (the key leaves limits out, as the\n * shared model merges them); and it admits every value the member pins — a\n * string field the member pins is, on the component, a plain string, or,\n * when the member does not leave it free, a literal or inline enum holding\n * every pinned value. The key reads every string as one, so this is what\n * tells a component the body can reference from one that would narrow its\n * codes.\n */\nfunction componentAccepts(component: Model, member: Model, keys: ModelKeys): boolean {\n  if (component.deprecated) return false;\n  if (!noStricter(component.constraints, member.constraints)) return false;\n  for (const field of member.fields) {\n    const own = component.fields.find((f) => f.name === field.name);\n    if (\n      !own ||\n      own.required !== field.required ||\n      (own.deprecated === true && !field.deprecated) ||\n      own.domainName !== field.domainName ||\n      keys.type(own.type, true) !== keys.type(field.type, true) ||\n      !noStricter(own.constraints, field.constraints) ||\n      !typeNoStricter(own.type, field.type, keys)\n    ) {\n      return false;\n    }\n  }\n  for (const [name, { values, open }] of pinnedValues([member])) {\n    const field = component.fields.find((f) => f.name === name);\n    if (!field) return false;\n    const type = unwrapNullable(field.type);\n    if (type.kind === 'primitive' && type.type === 'string' && !type.format) continue;\n    if (open) return false;\n    if (type.kind === 'literal') {\n      if (values.size !== 1 || !values.has(String(type.value))) return false;\n      continue;\n    }\n    if (type.kind === 'enum' && type.values) {\n      const allowed = new Set(type.values.map((value) => String(value)));\n      if ([...values].some((value) => !allowed.has(value))) return false;\n      continue;\n    }\n    return false;\n  }\n  return true;\n}\n\n/** Whether every limit `component` writes, `member` writes the same: the component admits at least what the member does. */\nfunction noStricter(component: Constraints | undefined, member: Constraints | undefined): boolean {\n  if (component === undefined) return true;\n  const own = member ?? {};\n  return Object.entries(component).every(\n    ([keyword, value]) => stableJson(value) === stableJson(own[keyword as keyof Constraints]),\n  );\n}\n\n/**\n * Whether `component` admits at least what `member` does at every level of\n * the type (#611): every limit it carries — its own (`noStricter`), its\n * items' at every depth, its values' and keys', its variants' and its\n * inner's under a nullable wrapper — `member` carries the same. The two\n * read as one key (`ModelKeys.type`), so they are of one kind at every\n * level, a direct string the key reads as one `S` aside, and that string's\n * pinned values are compared by `componentAccepts`; a reference to a model\n * or an enum carries no limit and ends the walk. A union's variants are\n * matched by their key, not their position, since the key sorts them: each\n * variant the member writes is admitted when a variant of the component\n * with the same shape is no stricter than it, whichever order either side\n * wrote them in.\n */\nfunction typeNoStricter(component: TypeRef, member: TypeRef, keys: ModelKeys): boolean {\n  if (!noStricter(typeRefConstraints(component), typeRefConstraints(member))) return false;\n  switch (component.kind) {\n    case 'nullable':\n      return member.kind === 'nullable' && typeNoStricter(component.inner, member.inner, keys);\n    case 'array':\n      return member.kind === 'array' && typeNoStricter(component.items, member.items, keys);\n    case 'map':\n      return (\n        member.kind === 'map' &&\n        (component.keyType === undefined ||\n          member.keyType === undefined ||\n          typeNoStricter(component.keyType, member.keyType, keys)) &&\n        typeNoStricter(component.valueType, member.valueType, keys)\n      );\n    case 'union': {\n      if (member.kind !== 'union') return false;\n      const byKey = new Map<string, TypeRef[]>();\n      for (const variant of component.variants) {\n        const key = keys.type(variant, false);\n        const alike = byKey.get(key);\n        if (alike) alike.push(variant);\n        else byKey.set(key, [variant]);\n      }\n      return member.variants.every((variant) =>\n        (byKey.get(keys.type(variant, false)) ?? []).some((own) => typeNoStricter(own, variant, keys)),\n      );\n    }\n    default:\n      return true;\n  }\n}\n\n/**\n * `{ code: string, message?: string | null, detail as reason: Note }`: a\n * model's fields with their requiredness, domain name and type, so that a\n * warning printing two shapes says what tells them apart (#515), and\n * `(deprecated)` after a deprecated field's name\n * (`{ message (deprecated): string }`), so a warning says which side\n * deprecates a field (#629); the model's own flag is said by the holder.\n */\nfunction shapeOf(model: Model): string {\n  if (model.fields.length === 0) return '{ }';\n  const fields = model.fields.map(\n    (field) =>\n      `${field.name}${field.required ? '' : '?'}${field.deprecated ? ' (deprecated)' : ''}${field.domainName === undefined ? '' : ` as ${field.domainName}`}: ${describeType(field.type)}`,\n  );\n  return `{ ${fields.join(', ')} }`;\n}\n\n/** A type as a warning prints it: `string`, `string (date-time)`, `\"gone\"`, `Note`, `string | null`, `(Note | Tag)[]`, `map<string>`. */\nfunction describeType(type: TypeRef): string {\n  switch (type.kind) {\n    case 'model':\n      return type.name;\n    case 'enum':\n      return type.name || `enum (${(type.values ?? []).map((value) => JSON.stringify(value)).join(' | ')})`;\n    case 'literal':\n      return JSON.stringify(type.value);\n    case 'primitive':\n      return type.format ? `${type.type} (${type.format})` : type.type;\n    case 'array': {\n      const items = describeType(type.items);\n      return type.items.kind === 'union' || type.items.kind === 'nullable' ? `(${items})[]` : `${items}[]`;\n    }\n    case 'nullable':\n      return `${describeType(type.inner)} | null`;\n    case 'union':\n      return type.variants.map(describeType).join(' | ');\n    case 'map':\n      return `map<${describeType(type.valueType)}>`;\n  }\n}\n\n/**\n * The one string field among `names` every member of a group pins to one\n * value, when there is exactly one such field and the value can name a\n * model.\n */\nfunction singlePinned(\n  pinned: ReadonlyMap<string, PinnedValues>,\n  names: ReadonlySet<string>,\n): { field: string; value: string } | undefined {\n  const single = [...pinned.entries()].filter(\n    ([field, { values, open }]) => names.has(field) && values.size === 1 && !open,\n  );\n  if (single.length !== 1) return undefined;\n  const [field, { values }] = single[0];\n  const value = [...values][0];\n  const word = toPascalCase(value);\n  // A value that is empty or starts with a digit (`4001`) names nothing.\n  if (word.length === 0 || /^\\d/.test(word)) return undefined;\n  return { field, value };\n}\n\n/**\n * Whether a body's name spells more than its named fields' names: some\n * field's token carries a qualifier — `Nullable`, a type or format, a\n * value, a domain name after `As`, `List`, `Or`, a nested body's fields. No\n * qualifier is beyond what a field name can spell, in the IR or once an\n * emitter re-cases it (`code_integer` is `CodeInteger`, as `code: integer`\n * is), so the fold cannot keep the two apart by spelling; it orders a plain\n * shape before a qualified one instead, so that adding the qualified shape\n * leaves the plain one's model as it is.\n */\nfunction qualified(model: Model, naming: NamingContext): boolean {\n  const visiting = new Set([model.name]);\n  return namedFields(model).some((field) => fieldToken(field, true, naming, visiting) !== toPascalCase(field.name));\n}\n\n/** A plain string a name need not spell: a free, pinned or enumerated string under no `null`, no format and no domain name. */\nfunction isPlainString(field: Field): boolean {\n  return field.domainName === undefined && isStringLike(field.type);\n}\n\n/**\n * The name a group takes, read from the fields `namedFields` gives — the\n * required ones, or every field under `Optional` when none is required:\n * `ErrorBody` for `{ message }`, `OAuthErrorBody` for\n * `{ error, error_description }`, else the base plus `With` and a token per\n * further field (`fieldToken`). The fields the family implies — `message`,\n * or `error` and `error_description` in the OAuth format — and the field a\n * value-named group pins are left out only while they are plain strings;\n * one that admits `null`, has a format or carries a domain name is spelled\n * like any other field (`ErrorBodyWithNullableMessage`,\n * `OAuthErrorBodyWithErrorInteger`, `GoneErrorBodyWithNullableCode`), so two\n * shapes that differ there never ask for one name. A body of the\n * `ErrorBody` family with no required `message` ends in `WithoutMessage`. A\n * group every member of which pins one named string field to one value is\n * named from the value instead — followed by the field's name unless it is\n * `code` or `error` — plus `With` and the tokens of any further fields, a\n * nested body's own fields left out.\n */\nfunction bodyName(representative: Model, pinned: ReadonlyMap<string, PinnedValues>, naming: NamingContext): string {\n  if (representative.fields.length === 0) return `${ERROR_BODY_BASE}Empty`;\n  const read = namedFields(representative);\n  const optional = !read[0].required;\n  const fields = [...read].sort(byFieldName);\n  const names = new Set(fields.map((field) => field.name));\n  const oauth = OAUTH_ERROR_FIELDS.every((name) => names.has(name));\n  const base = `${optional ? OPTIONAL_PREFIX : ''}${oauth ? 'OAuth' : ''}${ERROR_BODY_BASE}`;\n  const single = singlePinned(pinned, names);\n  const implied = new Set<string>(oauth ? OAUTH_ERROR_FIELDS : ['message']);\n  if (single) implied.add(single.field);\n  const extras = fields\n    .filter((field) => !(implied.has(field.name) && isPlainString(field)))\n    .map((field) => fieldToken(field, single === undefined, naming, new Set([representative.name])));\n  const suffix = extras.length === 0 ? '' : `With${extras.join('')}`;\n  const without = !oauth && !names.has('message') ? WITHOUT_MESSAGE : '';\n  if (single === undefined) return `${base}${suffix}${without}`;\n  const field = ERROR_CODE_FIELDS.includes(single.field) ? '' : toPascalCase(single.field);\n  return `${toPascalCase(single.value)}${field}${base}${suffix}${without}`;\n}\n\n/**\n * The token a field contributes to a body's name: its name in PascalCase,\n * its domain name after `As` when it has one, and what its type adds\n * (`typeToken`).\n */\nfunction fieldToken(field: Field, qualify: boolean, naming: NamingContext, visiting: ReadonlySet<string>): string {\n  const word = `${toPascalCase(field.name)}${field.domainName === undefined ? '' : `As${toPascalCase(field.domainName)}`}`;\n  return typeToken(word, field.type, qualify, naming, visiting);\n}\n\n/**\n * `word` qualified by what `type` adds: `Nullable` first for a type that\n * admits `null`; a union's variants joined with `Or`; `List` appended for\n * an array of plain values, after what the item scalar adds; and, when\n * `qualify` is set, a nested error body's own required fields prefixed, so\n * `errors` arrays of different items read apart (`CodeFieldErrors`,\n * `ConstraintsPropertyErrors`). A scalar that is not a plain string follows\n * the word, a non-string `const` or inline `enum` by its values\n * (`scalarToken`). A reference to a component or a named enum, a map and an\n * untyped schema add nothing.\n */\nfunction typeToken(\n  word: string,\n  type: TypeRef,\n  qualify: boolean,\n  naming: NamingContext,\n  visiting: ReadonlySet<string>,\n): string {\n  switch (type.kind) {\n    case 'nullable':\n      return `Nullable${typeToken(word, type.inner, qualify, naming, visiting)}`;\n    case 'union': {\n      // Sorted, as the key sorts the variants: the name does not depend on\n      // which member of the group wrote the union first.\n      const tokens = type.variants.map((variant) => typeToken(word, variant, qualify, naming, visiting));\n      return [...new Set(tokens)].sort().join('Or') || word;\n    }\n    case 'array': {\n      const items = unwrapNullable(type.items);\n      if (items.kind === 'model' || items.kind === 'union') {\n        return typeToken(word, items, qualify, naming, visiting);\n      }\n      return `${scalarToken(word, type.items)}List`;\n    }\n    case 'model': {\n      const nested = qualify && naming.errorOnly.has(type.name) ? naming.byName.get(type.name) : undefined;\n      // A cycle among error bodies reads as the field's name alone.\n      const own = nested && !visiting.has(nested.name) ? nestedPrefix(nested, naming, visiting) : '';\n      return `${own}${word}`;\n    }\n    case 'primitive':\n    case 'literal':\n    case 'enum':\n      return scalarToken(word, type);\n    default:\n      return word;\n  }\n}\n\n/**\n * `word` followed by what a scalar adds: nothing for a plain string, a\n * string literal, an inline enum of strings, a named enum or an untyped\n * schema; `Nullable` for an array item that admits `null` (`TagsNullableList`\n * for `(string | null)[]`, apart from `NullableTagsList` for\n * `string[] | null`); a format (`DateTime`, `Int64`) or type (`Integer`,\n * `Number`, `Boolean`) in PascalCase; a non-string `const` by its value\n * (`Status404`, `OkTrue`, `RatioMinus1Point5`) and an inline\n * enum of non-string values by its values, sorted as the key sorts them\n * (`sortedEnumValues`) so that reordering the entries renames nothing, and\n * joined with `Or` (`Status404Or410`), since the key keeps those values and\n * nothing combines them (#515). A number is set off by `No` from a word\n * that ends in a digit (`V2No3`), as every number in a name is\n * (`numberedName`).\n */\nfunction scalarToken(word: string, type: TypeRef): string {\n  switch (type.kind) {\n    case 'nullable':\n      return scalarToken(`${word}Nullable`, type.inner);\n    case 'primitive':\n      if (type.type === 'unknown' || (type.type === 'string' && !type.format)) return word;\n      return `${word}${toPascalCase(type.format ?? type.type)}`;\n    case 'literal':\n      return typeof type.value === 'string' ? word : valueToken(word, type.value);\n    case 'enum':\n      if (!type.values || isStringValuedInlineEnum(type)) return word;\n      return enumValuesToken(word, type.values);\n    default:\n      return word;\n  }\n}\n\n/**\n * `word` followed by an inline enum's values, sorted as the key sorts them\n * (`sortedEnumValues`) and joined with `Or`, each spelled as a literal's is\n * (`valueToken`): `Status404Or410`, `CodesAOrB`, `V2No3Or4`.\n */\nfunction enumValuesToken(word: string, values: readonly (string | number)[]): string {\n  return sortedEnumValues(values)\n    .map((value, i) => valueToken(i === 0 ? word : 'Or', value))\n    .join('');\n}\n\n/** `word` followed by a literal's value: `True`, `False`, `Null`, a number with `-` as `Minus` and `.` as `Point`, a string in PascalCase. */\nfunction valueToken(word: string, value: string | number | boolean | null): string {\n  if (typeof value === 'string') return `${word}${toPascalCase(value)}`;\n  if (typeof value === 'boolean') return `${word}${value ? 'True' : 'False'}`;\n  if (value === null) return `${word}Null`;\n  const spelled = String(value)\n    .replace('-', 'Minus')\n    .replace('.', 'Point')\n    .replace(/[^A-Za-z0-9]/g, '');\n  return numberedName(word, spelled);\n}\n\n/**\n * The tokens of a nested error body's own named fields — every one, the\n * ones its parent also has included, so `[{ code, message }]` and\n * `[{ code }]` read apart (`CodeMessageErrors`, `CodeErrors`) — sorted by\n * field name and joined, each read as a body's own are so a body nested\n * deeper reads the same way.\n */\nfunction nestedPrefix(item: Model, naming: NamingContext, visiting: ReadonlySet<string>): string {\n  const inner = new Set([...visiting, item.name]);\n  return [...namedFields(item)]\n    .sort(byFieldName)\n    .map((field) => fieldToken(field, true, naming, inner))\n    .join('');\n}\n\n/**\n * The name of a nested error body `item` reached through `field` of a body\n * `parent` named `parentName`: the parent's name plus the field, singular\n * for an array item, replacing the field where the parent's name already\n * ends in it. When the field is not among the ones the parent's name reads\n * (an optional one), that name says nothing of the item, so the item's own\n * fields follow after `With`, as they prefix the field in a required\n * parent's name — `ErrorBodyDetailWithReason` for\n * `{ message, detail?: { reason } }` — so two items under one optional field\n * never ask for one name.\n */\nfunction nestedName(parentName: string, parent: Model, field: Field, item: Model, naming: NamingContext): string {\n  const word = toPascalCase(field.name);\n  const inArray = unwrapNullable(field.type).kind === 'array';\n  const itemWord = inArray ? toPascalCase(singularize(field.name)) : word;\n  const base =\n    inArray && word.length > 0 && parentName.endsWith(word)\n      ? `${parentName.slice(0, -word.length)}${itemWord}`\n      : `${parentName}${itemWord}`;\n  if (namedFields(parent).includes(field)) return base;\n  const own = nestedPrefix(item, naming, new Set([parent.name]));\n  return own.length === 0 ? base : `${base}With${own}`;\n}\n\n/**\n * One shared model for `members`, carrying every field any member declares\n * (`sharedFieldOrder`): each field's type reads as the group reads it\n * (`sharedFieldType`); its description, access flags, default, limits and\n * extensions are kept when every member that has the field wrote the same\n * one, the example only while the type is still the member's own, its\n * domain name when every member that hints the field agrees\n * (`sharedDomainName`), and its `deprecated` when every member that carries\n * the field deprecates it (`sharedDeprecated`), as the model is deprecated\n * only when every member is (`sharedModelDeprecated`): a deprecated member,\n * or a member's deprecated field, folds onto a live one with a warning, as\n * a deprecated inline copy folds onto its live twin (#441, #629).\n */\nfunction buildSharedModel(\n  name: string,\n  members: readonly Model[],\n  pinned: ReadonlyMap<string, PinnedValues>,\n  enumValuesByField: ReadonlyMap<string, ReadonlySet<string>>,\n  enumNamesByField: ReadonlyMap<string, string>,\n  renames: ReadonlyMap<string, string>,\n): Model {\n  const representative = members[0];\n  const fields: Field[] = sharedFieldOrder(members).map((field) => {\n    const siblings = siblingsOf(members, field.name);\n    const agree = <K extends keyof Field>(key: K): Field[K] | undefined =>\n      siblings.every((sibling) => stableJson(sibling[key]) === stableJson(field[key])) ? field[key] : undefined;\n    const constraints = agree('constraints');\n    const { type, changed } = sharedFieldType(\n      siblings,\n      pinned.get(field.name),\n      enumValuesByField,\n      enumNamesByField,\n      renames,\n      constraints,\n    );\n    const shared: Field = { name: field.name, type, required: field.required };\n    const domainName = sharedDomainName(name, members, field.name);\n    if (domainName !== undefined) shared.domainName = domainName;\n    const description = agree('description');\n    if (description !== undefined) shared.description = description;\n    const readOnly = agree('readOnly');\n    if (readOnly !== undefined) shared.readOnly = readOnly;\n    const writeOnly = agree('writeOnly');\n    if (writeOnly !== undefined) shared.writeOnly = writeOnly;\n    if (sharedDeprecated(name, members, field.name)) shared.deprecated = true;\n    const defaultValue = agree('default');\n    if (defaultValue !== undefined) shared.default = defaultValue;\n    if (constraints !== undefined) shared.constraints = constraints;\n    const extensions = agree('extensions');\n    if (extensions !== undefined) shared.extensions = extensions;\n    if (!changed) {\n      const example = agree('example');\n      if (example !== undefined) shared.example = example;\n      const examples = agree('examples');\n      if (examples !== undefined) shared.examples = examples;\n      const externalDocs = agree('externalDocs');\n      if (externalDocs !== undefined) shared.externalDocs = externalDocs;\n    }\n    return shared;\n  });\n  const model: Model = { name, fields };\n  const agree = <K extends keyof Model>(key: K): Model[K] | undefined =>\n    members.every((member) => stableJson(member[key]) === stableJson(representative[key]))\n      ? representative[key]\n      : undefined;\n  if (sharedModelDeprecated(name, members)) model.deprecated = true;\n  const constraints = agree('constraints');\n  if (constraints !== undefined) model.constraints = constraints;\n  if (representative.typeParams !== undefined) model.typeParams = representative.typeParams;\n  const extensions = agree('extensions');\n  if (extensions !== undefined) model.extensions = extensions;\n  if (representative.variants) {\n    const union = simplifyType({\n      kind: 'union',\n      variants: representative.variants.map((variant) => rewritten(variant, renames)),\n      ...(representative.compositionKind && { compositionKind: representative.compositionKind }),\n    });\n    model.variants = union.kind === 'union' ? union.variants : [union];\n    if (representative.compositionKind !== undefined) model.compositionKind = representative.compositionKind;\n  }\n  if (representative.discriminator) {\n    const mapping: Record<string, string> = {};\n    for (const [value, target] of Object.entries(representative.discriminator.mapping)) {\n      mapping[value] = renames.get(target) ?? target;\n    }\n    model.discriminator = { property: representative.discriminator.property, mapping };\n  }\n  return model;\n}\n\n/**\n * The domain name the shared model `name` gives its field `field`: the one\n * every member that hints the field gives it (a named field's is part of the\n * key, so the members agree; an optional field's is applied by whichever\n * members carry it, #506), or none, with a warning, when two members hint\n * it differently — a hint keyed by the shared name applies after the fold.\n */\nfunction sharedDomainName(name: string, members: readonly Model[], field: string): string | undefined {\n  const hinted = members.flatMap((member) => {\n    const own = member.fields.find((f) => f.name === field);\n    return own?.domainName === undefined ? [] : [{ member: member.name, domainName: own.domainName }];\n  });\n  const distinct = new Set(hinted.map(({ domainName }) => domainName));\n  if (distinct.size <= 1) return hinted[0]?.domainName;\n  const list = hinted.map(({ member, domainName }) => `\"${member}\" as \"${domainName}\"`).join(', ');\n  console.warn(\n    `[oagen] Warning: The shared error body \"${name}\" keeps \"${field}\" under its own name: its bodies hint it apart (${list}); hint it once, keyed by \"${name}\"`,\n  );\n  return undefined;\n}\n\n/**\n * Whether the shared model `name` is deprecated: every member is. A body's\n * own `deprecated` is not shape (its name never depends on its own flag,\n * #441), so a group may mix the flags; it then stays live, since a\n * deprecated model would type the live members' sites as deprecated, and\n * the deprecated members are announced (`settleDeprecated`, #629).\n */\nfunction sharedModelDeprecated(name: string, members: readonly Model[]): boolean {\n  const flagged = members.map((member) => ({ member: member.name, deprecated: member.deprecated === true }));\n  return settleDeprecated(name, undefined, flagged);\n}\n\n/**\n * Whether the shared model `name` deprecates its field `field`: every\n * member that carries the field does. A field's `deprecated` is not shape\n * either (#629), so the members may flag it apart; the field then stays\n * live, since a deprecated field would give the live members' readers a\n * notice their schemas never wrote, and the members that deprecate it are\n * announced (`settleDeprecated`), the field being the flag's only carrier.\n */\nfunction sharedDeprecated(name: string, members: readonly Model[], field: string): boolean {\n  const flagged = members.flatMap((member) => {\n    const own = member.fields.find((f) => f.name === field);\n    return own === undefined ? [] : [{ member: member.name, deprecated: own.deprecated === true }];\n  });\n  return settleDeprecated(name, field, flagged);\n}\n\n/** Whether every one of `flagged` is deprecated; when only some are, they are announced (`warnDeprecatedFold`) and the answer is no. */\nfunction settleDeprecated(\n  name: string,\n  field: string | undefined,\n  flagged: ReadonlyArray<{ member: string; deprecated: boolean }>,\n): boolean {\n  const deprecated = flagged.filter((entry) => entry.deprecated).map((entry) => entry.member);\n  if (deprecated.length === flagged.length) return flagged.length > 0;\n  if (deprecated.length > 0) {\n    const live = flagged.filter((entry) => !entry.deprecated).map((entry) => `\"${entry.member}\"`);\n    warnDeprecatedFold(name, field, deprecated, live.join(', '));\n  }\n  return false;\n}\n\n/**\n * The warning a deprecated body, or a body's deprecated field, folding onto\n * a live one of its shape is announced with — the shared model its live\n * twins make, or a live component of the name (`claim`) — as a deprecated\n * inline copy a live declared model admits is announced everywhere else\n * (`deprecatedFoldWarning`): the flag has no carrier once the body folds,\n * so the readers of its site lose the notice (#629). For a component,\n * printed only once `fold` knows its result is kept, after every group has\n * claimed a name, so a pass that runs again announces each fold once.\n */\nfunction warnDeprecatedFold(\n  name: string,\n  field: string | undefined,\n  deprecated: readonly string[],\n  live: string,\n): void {\n  const subject =\n    field === undefined ? `The shared error body \"${name}\" is` : `The shared error body \"${name}\" has \"${field}\"`;\n  const list = deprecated.map((member) => `\"${member}\"`).join(', ');\n  console.warn(`[oagen] Warning: ${subject} declared deprecated by ${list} and live by ${live} — keeping it live`);\n}\n\n/**\n * The type a shared model gives a field, read from the members' `siblings`\n * of it. A string the group pins — a `const`, an inline `enum`, beside a\n * plain `string` — is read as a whole: two or more distinct values make the\n * enum shared by every error body with a field of that name,\n * `<ErrorBody><Field>`, holding every value any body pins it to (a string\n * when that name is taken); one value every member pins stays that literal;\n * one value beside free strings is a string; and the field admits `null`\n * when any member's does. Any other type every member wrote alike is that\n * type, its references to folded models repointed and every inline enum in\n * it, read by its sorted values, named by `fold` from the field once the\n * shared models are built (#612); an optional field the members type\n * differently is the union of the types they wrote, sorted so the order\n * does not depend on the members' (`unionOf`). The type carries\n * the limits the field does: `constraints`, the ones every member wrote,\n * or none when they differ; and below its top level — an array's items, a\n * map's values, a union's variants — the limits every member that wrote\n * that level agrees on, each level kept or dropped on its own\n * (`agreedLimits`; #611), since two types that differ only in a limit are\n * one shape (`limitlessShape`), as are two unions that list one set of\n * variants in different orders, never two members of a union; and a union\n * whose variants are left alike once their limits are dropped keeps one of\n * them, a lone survivor standing for the union (`simplifyType`), so no\n * `oneOf` of two plain strings, which admits nothing, is ever written.\n */\nfunction sharedFieldType(\n  siblings: readonly Field[],\n  pinned: PinnedValues | undefined,\n  enumValuesByField: ReadonlyMap<string, ReadonlySet<string>>,\n  enumNamesByField: ReadonlyMap<string, string>,\n  renames: ReadonlyMap<string, string>,\n  constraints: Constraints | undefined,\n): { type: TypeRef; changed: boolean } {\n  const first = siblings[0];\n  if (pinned) {\n    const nullable = siblings.some((sibling) => sibling.type.kind === 'nullable');\n    let type: TypeRef;\n    const enumName = enumNamesByField.get(first.name);\n    if (pinned.values.size >= 2 && enumName !== undefined) {\n      const enumRef: EnumRef = {\n        kind: 'enum',\n        name: enumName,\n        values: [...(enumValuesByField.get(first.name) ?? pinned.values)].sort(),\n      };\n      type = enumRef;\n    } else if (pinned.values.size === 1 && !pinned.open) {\n      type = { kind: 'literal', value: [...pinned.values][0], ...(constraints && { constraints }) };\n    } else {\n      type = { kind: 'primitive', type: 'string', ...(constraints && { constraints }) };\n    }\n    const wrapped: TypeRef = nullable ? { kind: 'nullable', inner: type } : type;\n    return { type: wrapped, changed: stableJson(wrapped) !== stableJson(first.type) };\n  }\n  // An inline enum reads by its sorted values, as the key reads it, and not\n  // by the name the parser minted it under per operation: two members that\n  // list the same values, in any order, share one enum, which `fold` names\n  // from the field once the shared models are built (#612); a type reads\n  // without its limits at any level, so two members that differ\n  // only in a limit on an array's items share one type, carrying the limits\n  // they agree on; and a union reads with its variants sorted, as the key\n  // reads them, so two members that list them in different orders share\n  // one union (`limitlessShape`).\n  const alike = new Map<string, TypeRef[]>();\n  for (const sibling of siblings) {\n    const own = normalizeInlineEnums(rewritten(sibling.type, renames), true);\n    const type = constraints === undefined ? stripConstraints(own) : own;\n    const key = stableJson(limitlessShape(type));\n    const group = alike.get(key);\n    if (group) group.push(type);\n    else alike.set(key, [type]);\n  }\n  if (alike.size === 1) return { type: agreedLimits([...alike.values()][0]), changed: false };\n  const types = [...alike.entries()]\n    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n    .map(([, group]) => agreedLimits(group));\n  return { type: unionOf(types, constraints), changed: true };\n}\n\n/**\n * One type for `types`, which read alike but for the limits they carry and\n * the order of their variants (`limitlessShape`): the first, with the\n * limits at every level — its own, its items', its values' and keys', its\n * variants' — kept where every one of them writes the same and dropped\n * where they differ (#611), as the shared model keeps a field's own\n * (`buildSharedModel`); a new tree wherever something is dropped, the\n * first itself when nothing is. A level's limits are kept or dropped as a\n * whole, as a field's own are: items `{ maxLength: 2, pattern: '^a' }`\n * beside `{ maxLength: 3, pattern: '^a' }` carry none. A union's variants\n * are read by shape, not by position, whichever order each member lists\n * them in: a shape every member lists with the same variants keeps the\n * first member's, and one they list apart merges into one variant\n * carrying the limits every variant of the shape, in every member, agrees\n * on, so no limit survives on one variant of a shape that another lacks\n * (`oneOf: [{ string, pattern: '^[a-z]+$' }, { string, pattern: '^[0-9]+$' }]`\n * beside the same with `'^[A-Z]+$'` is a plain `string`, never\n * `oneOf: [{ string, pattern: '^[a-z]+$' }, string]`, which rejects what\n * both bodies admit); the result keeps the first member's order, and\n * variants left alike are one, a lone survivor standing for the union\n * (`simplifyType`), since a `oneOf` of two plain strings admits nothing —\n * the survivor, a nested union the outer collapses onto included, taking\n * the limits the union itself agreed on, conjoined onto its own\n * (`withLimits`), so none is lost with the union. A `oneOf` the merge\n * widened a variant of beside a variant it may now overlap — one of the\n * same JSON value kind, or an untyped one (`mayOverlap`) — is read as\n * `anyOf`, since its variants can no longer promise to match one value at\n * a time (`oneOf: [{ string, pattern: '^b' }, { const: 'a' }]` beside the\n * same with `'^c'` is `anyOf: [string, 'a']`, which admits the `\"a\"` both\n * bodies do); one widened beside variants of other kinds only stays\n * `oneOf`.\n */\nfunction agreedLimits(types: readonly TypeRef[]): TypeRef {\n  const first = types[0];\n  if (types.length === 1) return first;\n  const of = <K extends TypeRef['kind']>(kind: K): Extract<TypeRef, { kind: K }>[] =>\n    types.filter((type): type is Extract<TypeRef, { kind: K }> => type.kind === kind);\n  const own = stableJson(typeRefConstraints(first));\n  const agreed = types.every((type) => stableJson(typeRefConstraints(type)) === own);\n  const top = agreed ? first : stripConstraints(first);\n  switch (top.kind) {\n    case 'nullable':\n      return { kind: 'nullable', inner: agreedLimits(of('nullable').map((type) => type.inner)) };\n    case 'array':\n      return { ...top, items: agreedLimits(of('array').map((type) => type.items)) };\n    case 'map': {\n      const maps = of('map');\n      const keyTypes = maps.flatMap((type) => (type.keyType === undefined ? [] : [type.keyType]));\n      return {\n        ...top,\n        valueType: agreedLimits(maps.map((type) => type.valueType)),\n        ...(keyTypes.length === maps.length && { keyType: agreedLimits(keyTypes) }),\n      };\n    }\n    case 'union': {\n      // Each member's variants by shape (`limitlessShape`), each shape's in\n      // the member's order with its index in the union.\n      const byShape = of('union').map((union) => {\n        const shapes = new Map<string, Array<{ variant: TypeRef; index: number }>>();\n        union.variants.forEach((variant, index) => {\n          const shape = stableJson(limitlessShape(variant));\n          const alike = shapes.get(shape);\n          if (alike) alike.push({ variant, index });\n          else shapes.set(shape, [{ variant, index }]);\n        });\n        return shapes;\n      });\n      const variants = [...top.variants];\n      const widened = new Set<string>(); // the shapes merged into one variant that admits more than some member's did\n      for (const [shape, own] of byShape[0]) {\n        // A shape every member lists with the same variants keeps the\n        // first member's; one they list apart merges into one variant\n        // carrying the limits every variant of the shape, in every\n        // member, agrees on, so no limit survives on one variant of a\n        // shape that another lacks (MichaelDeBoey, #639: `^[a-z]+$` kept\n        // on one string beside a plain string rejects what both bodies\n        // admit).\n        const runs = byShape.map((member) => member.get(shape) ?? []);\n        const readings = runs.map((run) =>\n          run\n            .map(({ variant }) => stableJson(variant))\n            .sort()\n            .join('\\n'),\n        );\n        if (readings.every((reading) => reading === readings[0])) continue;\n        const merged = agreedLimits(runs.flatMap((run) => run.map(({ variant }) => variant)));\n        for (const { index } of own) variants[index] = merged;\n        widened.add(shape);\n      }\n      const merged = simplifyType({ ...top, variants });\n      // A lone survivor — the one variant left once the alike are dropped,\n      // told by their count rather than by the survivor's kind, since the\n      // survivor may be a union itself — takes the union's own agreed\n      // limits, conjoined onto its own, the stricter bound winning\n      // (`combineConstraints`): the string left of\n      // `{ oneOf: [...], minLength: 1 }` is under `minLength: 1`, not one\n      // that admits the empty string, and so is the `anyOf` or type list\n      // the `oneOf` collapses onto (Greptile, #639).\n      const distinct = new Set(variants.map((variant) => stableJson(variant))).size;\n      if (distinct === 1) return withLimits(merged, top.constraints);\n      if (merged.kind !== 'union' || merged.compositionKind !== 'oneOf' || widened.size === 0) return merged;\n      // A `oneOf` promises its variants match one value at a time, which a\n      // widened variant can break beside a variant it may now overlap —\n      // one of the same JSON value kind, or an untyped one (`mayOverlap`):\n      // `oneOf: [{ string, pattern: '^b' }, { const: 'a' }]` beside the\n      // same with `'^c'` would be `oneOf: [string, 'a']`, rejecting the\n      // `\"a\"` both bodies admit (Greptile, #639). Such a union is read as\n      // `anyOf`; one widened beside variants of other kinds only (a string\n      // beside an integer) stays `oneOf`.\n      const overlaps = [...byShape[0]].some(([shape, own]) => {\n        if (!widened.has(shape)) return false;\n        const indices = new Set(own.map(({ index }) => index));\n        return own.some(({ index }) =>\n          variants.some((other, i) => !indices.has(i) && mayOverlap(variants[index], other)),\n        );\n      });\n      if (!overlaps) return merged;\n      const open: UnionType = { ...merged, compositionKind: 'anyOf' };\n      return open;\n    }\n    default:\n      return top;\n  }\n}\n\n/**\n * `type` carrying `limits` conjoined onto its own (`combineConstraints`, the\n * stricter bound winning) on the node that can — the type itself, or the\n * `inner` of a nullable wrapper, whose keywords are the value's — as a new\n * tree; a `model` or `enum` reference carries none and is returned as it\n * is, as is `type` when `limits` is `undefined`.\n */\nfunction withLimits(type: TypeRef, limits: Constraints | undefined): TypeRef {\n  if (limits === undefined) return type;\n  switch (type.kind) {\n    case 'nullable':\n      return { kind: 'nullable', inner: withLimits(type.inner, limits) };\n    case 'primitive':\n    case 'literal':\n    case 'array':\n    case 'map':\n    case 'union':\n      return { ...type, constraints: combineConstraints(type.constraints, limits) };\n    default:\n      return type;\n  }\n}\n\n/**\n * The JSON value kinds `type` admits — `string`, `number` (an integer is\n * one), `boolean`, `null`, `array`, `object` (a map or a model) — or\n * `unknown` for an untyped schema and for a named enum whose values the\n * reference does not carry; a nullable wrapper adds `null` to its inner's,\n * a union gathers its variants'.\n */\nfunction valueKinds(type: TypeRef): Set<string> {\n  switch (type.kind) {\n    case 'primitive':\n      return new Set([type.type === 'integer' ? 'number' : type.type]);\n    case 'literal':\n      return new Set([type.value === null ? 'null' : typeof type.value]);\n    case 'enum':\n      return new Set(type.values?.map((value) => typeof value) ?? ['unknown']);\n    case 'array':\n      return new Set(['array']);\n    case 'map':\n    case 'model':\n      return new Set(['object']);\n    case 'nullable':\n      return new Set([...valueKinds(type.inner), 'null']);\n    case 'union':\n      return new Set(type.variants.flatMap((variant) => [...valueKinds(variant)]));\n  }\n}\n\n/** Whether one JSON value may match both `a` and `b`: they admit a value kind in common, or either admits any (`valueKinds`). */\nfunction mayOverlap(a: TypeRef, b: TypeRef): boolean {\n  const kinds = valueKinds(a);\n  const others = valueKinds(b);\n  return kinds.has('unknown') || others.has('unknown') || [...kinds].some((kind) => others.has(kind));\n}\n\n/**\n * An inline enum's values in the one order the key and the name read them\n * — numbers ascending, then strings in code-unit order — so that reordering\n * the entries in the document changes no shape and no name.\n */\nfunction sortedEnumValues(values: readonly (string | number)[]): (string | number)[] {\n  return [...values].sort((a, b) => {\n    if (typeof a === 'number' && typeof b === 'number') return a - b;\n    if (typeof a === 'number') return -1;\n    if (typeof b === 'number') return 1;\n    return a < b ? -1 : a > b ? 1 : 0;\n  });\n}\n\n/** One value set an inline enum lists under a field, sorted (`sortedEnumValues`), and the groups whose field lists it. */\ninterface InlineEnumSet {\n  values: (string | number)[];\n  groups: Model[][];\n}\n\n/** A field and a value set as one key: `[404, 410]` and `[410, 404]` under `status` read as one, `[1]` and `[\"1\"]` as two. */\nfunction inlineEnumKey(field: string, values: readonly (string | number)[]): string {\n  return JSON.stringify([field, sortedEnumValues(values)]);\n}\n\n/**\n * Every value set an inline enum lists under a field of a group to be\n * built — through a nullable wrapper, array items, map values and union\n * variants, on every member, since an optional field's type may differ by\n * member — by field name, each with the groups whose field lists it, less\n * the fields the string rule reads whole (`pinnedValues`), the groups a\n * component absorbs, and an enum that lists no value. The fields are sorted\n * by name and the sets by their values, so when two sets spell one name\n * with other members, which keeps it is the document's alone (#612).\n */\nfunction inlineEnumSets(\n  groups: ReadonlyArray<readonly [string, Model[]]>,\n  pinnedByKey: ReadonlyMap<string, ReadonlyMap<string, PinnedValues>>,\n  absorbed: ReadonlySet<string>,\n): Map<string, Map<string, InlineEnumSet>> {\n  const byField = new Map<string, Map<string, InlineEnumSet>>();\n  for (const [key, members] of groups) {\n    if (absorbed.has(key)) continue;\n    const pinned = pinnedByKey.get(key)!;\n    for (const member of members) {\n      for (const field of member.fields) {\n        if (pinned.has(field.name)) continue;\n        walkTypeRef(field.type, {\n          enum: (ref) => {\n            if (!ref.values || ref.values.length === 0) return;\n            const values = sortedEnumValues(ref.values);\n            const sets = byField.get(field.name) ?? new Map<string, InlineEnumSet>();\n            const setKey = JSON.stringify(values);\n            const set = sets.get(setKey) ?? { values, groups: [] };\n            if (!set.groups.includes(members)) set.groups.push(members);\n            sets.set(setKey, set);\n            byField.set(field.name, sets);\n          },\n        });\n      }\n    }\n  }\n  const byString = ([a]: readonly [string, unknown], [b]: readonly [string, unknown]): number =>\n    a < b ? -1 : a > b ? 1 : 0;\n  return new Map(\n    [...byField.entries()].sort(byString).map(([field, sets]) => [field, new Map([...sets.entries()].sort(byString))]),\n  );\n}\n\n/**\n * `type` with every inline enum's values sorted (`sortedEnumValues`), and,\n * unless `keepNames`, without the names the parser minted them under, as a\n * new tree; a reference to a component enum, and every other type, is\n * returned as it is.\n */\nfunction normalizeInlineEnums(type: TypeRef, keepNames: boolean): TypeRef {\n  switch (type.kind) {\n    case 'enum':\n      if (!type.values) return type;\n      return { kind: 'enum', name: keepNames ? type.name : '', values: sortedEnumValues(type.values) };\n    case 'nullable':\n      return { kind: 'nullable', inner: normalizeInlineEnums(type.inner, keepNames) };\n    case 'array':\n      return { ...type, items: normalizeInlineEnums(type.items, keepNames) };\n    case 'map':\n      return { ...type, valueType: normalizeInlineEnums(type.valueType, keepNames) };\n    case 'union':\n      return { ...type, variants: type.variants.map((variant) => normalizeInlineEnums(variant, keepNames)) };\n    default:\n      return type;\n  }\n}\n\n/**\n * The union of `types`, written as the parser writes a type list's: `null`\n * hoisted out of any member onto the whole, a member that is itself a plain\n * union spread into it, and one member standing alone. The union carries\n * `constraints`, the limits the field agreed on, since a spread member's\n * are left behind with it.\n */\nfunction unionOf(types: readonly TypeRef[], constraints: Constraints | undefined): TypeRef {\n  const nullable = types.some((type) => type.kind === 'nullable');\n  const variants: TypeRef[] = [];\n  const seen = new Set<string>();\n  const add = (type: TypeRef): void => {\n    const key = stableJson(type);\n    if (seen.has(key)) return;\n    seen.add(key);\n    variants.push(type);\n  };\n  for (const type of types) {\n    const inner = unwrapNullable(type);\n    if (inner.kind === 'union' && !inner.discriminator && !inner.compositionKind) {\n      for (const variant of inner.variants) add(variant);\n    } else add(inner);\n  }\n  const union: TypeRef =\n    variants.length === 1 ? variants[0] : { kind: 'union', variants, ...(constraints && { constraints }) };\n  return nullable ? { kind: 'nullable', inner: union } : union;\n}\n\n/** `type` with every reference to a folded model repointed, as a new tree. */\nfunction rewritten(type: TypeRef, renames: ReadonlyMap<string, string>): TypeRef {\n  const copy = structuredClone(type);\n  renameTypeRefModels(copy, renames);\n  return simplifyType(copy);\n}\n\n/** `type` without the validation keywords it carries at its top level — through a nullable wrapper — as a new tree. */\nfunction stripConstraints(type: TypeRef): TypeRef {\n  switch (type.kind) {\n    case 'nullable':\n      return { kind: 'nullable', inner: stripConstraints(type.inner) };\n    case 'primitive':\n    case 'literal':\n    case 'array':\n    case 'map':\n    case 'union': {\n      if (type.constraints === undefined) return type;\n      const { constraints: _constraints, ...rest } = type;\n      return rest as TypeRef;\n    }\n    default:\n      return type;\n  }\n}\n\n/**\n * `type` as the merge reads a shape (#611): without the validation keywords\n * at any level — its own, its items', values', keys' and variants' — every\n * inline enum unnamed with its values sorted (`normalizeInlineEnums`), and\n * a union's variants sorted by this reading, as the model key sorts them\n * (`ModelKeys.type`), so that neither a limit nor the order the variants\n * are listed in tells two members apart; a new tree.\n */\nfunction limitlessShape(type: TypeRef): TypeRef {\n  switch (type.kind) {\n    case 'nullable':\n      return { kind: 'nullable', inner: limitlessShape(type.inner) };\n    case 'enum':\n      return normalizeInlineEnums(type, false);\n    case 'array': {\n      const { constraints: _constraints, ...rest } = type;\n      return { ...rest, items: limitlessShape(type.items) };\n    }\n    case 'map': {\n      const { constraints: _constraints, keyType, ...rest } = type;\n      return {\n        ...rest,\n        valueType: limitlessShape(type.valueType),\n        ...(keyType && { keyType: limitlessShape(keyType) }),\n      };\n    }\n    case 'union': {\n      const { constraints: _constraints, ...rest } = type;\n      const variants = type.variants\n        .map((variant) => limitlessShape(variant))\n        .map((variant) => ({ variant, key: stableJson(variant) }))\n        .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))\n        .map(({ variant }) => variant);\n      return { ...rest, variants };\n    }\n    default:\n      return stripConstraints(type);\n  }\n}\n\n/**\n * A union whose variants fold onto fewer models, with the duplicates dropped\n * and a lone survivor standing in for the union; a nullable, array or map\n * simplified inside. Any other type is returned as it is.\n */\nfunction simplifyType(type: TypeRef): TypeRef {\n  switch (type.kind) {\n    case 'union': {\n      const seen = new Set<string>();\n      const variants: TypeRef[] = [];\n      for (const variant of type.variants) {\n        const simplifiedVariant = simplifyType(variant);\n        const key = stableJson(simplifiedVariant);\n        if (seen.has(key)) continue;\n        seen.add(key);\n        variants.push(simplifiedVariant);\n      }\n      if (variants.length === 1) return variants[0];\n      if (variants.length === type.variants.length && variants.every((variant, i) => variant === type.variants[i])) {\n        return type;\n      }\n      const union: UnionType = { ...type, variants };\n      return union;\n    }\n    case 'nullable': {\n      const inner = simplifyType(type.inner);\n      return inner === type.inner ? type : { kind: 'nullable', inner };\n    }\n    case 'array': {\n      const items = simplifyType(type.items);\n      return items === type.items ? type : { ...type, items };\n    }\n    case 'map': {\n      const valueType = simplifyType(type.valueType);\n      return valueType === type.valueType ? type : { ...type, valueType };\n    }\n    default:\n      return type;\n  }\n}\n\nfunction unwrapNullable(type: TypeRef): TypeRef {\n  return type.kind === 'nullable' ? unwrapNullable(type.inner) : type;\n}\n\n/** A plain string, a string literal, or an inline enum of strings: the shapes the pass reads as one. */\nfunction isStringLike(type: TypeRef): boolean {\n  if (type.kind === 'literal') return typeof type.value === 'string';\n  if (type.kind === 'enum') return isStringValuedInlineEnum(type);\n  return type.kind === 'primitive' && type.type === 'string' && !type.format;\n}\n\nfunction isStringValuedInlineEnum(type: EnumRef): boolean {\n  return type.values !== undefined && type.values.length > 0 && type.values.every((value) => typeof value === 'string');\n}\n\n/** JSON with object keys sorted at every level, `undefined` members dropped. */\nfunction stableJson(value: unknown): string {\n  return JSON.stringify(value, (_key, v) => {\n    if (v && typeof v === 'object' && !Array.isArray(v)) {\n      return Object.fromEntries(\n        Object.entries(v as Record<string, unknown>)\n          .filter(([, member]) => member !== undefined)\n          .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n      );\n    }\n    return v;\n  });\n}\n","import type { ApiSpec, AuthScheme, EnumRef, Model } from '../ir/types.js';\nimport { defaultSdkBehavior } from '../ir/sdk-behavior.js';\nimport { SpecParseError } from '../errors.js';\nimport { loadAndBundleSpec } from './refs.js';\nimport {\n  extractSchemas,\n  extractInlineModelsFromSchemas,\n  clearSchemaNameTransform,\n  resolveSchemaName,\n} from './schemas.js';\nimport { attachSharedRefs, extractOperations } from './operations.js';\nimport { sentOnlyComponentNames, type FieldInlineModelGroup } from './inline-models.js';\nimport { collectExistingEnumNames, collectExistingNames, extractWebhooks } from './webhooks.js';\nimport { extractCallbacks } from './callbacks.js';\nimport { followReference, siblingDocsMode, type ReferenceObject, type SiblingDocs } from './reference-objects.js';\nimport {\n  mergeInlineResponseModels,\n  collapseJsonSuffixModels,\n  mergeFieldInlineModels,\n  fieldInlineModelBundles,\n  refreshFieldInlineModelBundles,\n  reservedNamesByKind,\n  reservedTypeNames,\n  settleFieldInlineModels,\n  type InlineModelNaming,\n} from './normalize-inline-models.js';\nimport {\n  collectInlineEnumsFromModels,\n  collectInlineEnumsFromOperations,\n  collectInlineEnumsFromWebhooks,\n} from './collect-inline-enums.js';\nimport { assignParameterGroupWrapperNames } from './parameter-group-names.js';\nimport { validateModelRefs } from './normalize-model-refs.js';\nimport { settleBases } from './settle-bases.js';\nimport { resolveSchemaPointers } from './schema-pointers.js';\nimport { collapseErrorBodies } from './collapse-error-bodies.js';\nimport { extractSecurityRequirements, type RawSecurityRequirements } from './security.js';\nimport { extractServers, type RawServerObject } from './servers.js';\nimport { externalDocsEntry, type RawExternalDocs } from './external-docs.js';\nimport type { SchemaNameTransform } from './schemas.js';\nimport type { OperationHint } from '../ir/operation-hints.js';\n\n/**\n * A bundled OpenAPI document, post-`$ref` resolution but pre-IR extraction.\n *\n * This is the shape the spec author wrote, with external refs inlined and\n * internal refs left intact. It is intentionally loose (`Record<string,\n * unknown>`) so `transformSpec` can reach arbitrary spec extensions without\n * fighting types — narrow with `as` at use sites.\n */\nexport type OpenApiDocument = Record<string, unknown>;\n\nexport interface ParseOptions {\n  /**\n   * Custom transform for operation IDs. Receives each `operationId` once, as\n   * the document spells it with its trailing `[N]` overload markers stripped;\n   * returns the operation's name, used as is (no casing conversion). A result\n   * with no ASCII letter or digit once such markers are stripped (`''`,\n   * `' '`, `'-'`, `'[1]'`), or that is not a string, names nothing: the\n   * operation is then read as one without an `operationId` — path-named, its\n   * models named from its path, `Operation.operationId` unset — after one\n   * warning naming the id and the operation (#570). An `operationId` that\n   * itself names nothing is never passed. When omitted, ids are camelCased.\n   */\n  operationIdTransform?: (id: string) => string;\n  /**\n   * Custom transform for schema (model/enum) names. Receives the cleaned\n   * PascalCase name and, for component schemas, the original name as spelled\n   * in the document. Returning `originalName` opts out of normalization.\n   * See `SchemaExtractionOptions.schemaNameTransform`.\n   */\n  schemaNameTransform?: SchemaNameTransform;\n  /**\n   * Domain-facing field-name overrides, keyed by IR model name then wire field\n   * name: `{ Connection: { connection_type: 'type' } }`. Sets `Field.domainName`\n   * so emitters expose the field under the friendlier name while keeping the\n   * wire key. Language-agnostic — honored by any emitter that reads `domainName`.\n   */\n  fieldHints?: Record<string, Record<string, string>>;\n  /**\n   * Per-operation overrides keyed by \"METHOD /path\" — the same map\n   * `resolveOperations` reads. The parser applies only each hint's\n   * `pagination`, which wins over the operation's `x-pagination` extension\n   * and over name-based detection (see `PaginationHint`).\n   */\n  operationHints?: Record<string, OperationHint>;\n  /**\n   * Fold the models materialized for inline error bodies onto shared models\n   * named by shape (`ErrorBody`, `ErrorBodyWithCode`, the enum `ErrorBodyCode`;\n   * see `collapseErrorBodies`). A body's shape, and so its name, is its\n   * required fields — their names, domain names and types — so an optional\n   * field added to a body or to a nested item moves no model (#506, #516),\n   * and two shapes never ask for one name (#515): `{ message: string | null }`\n   * is `ErrorBodyWithNullableMessage`, `{ code: integer, message }` is\n   * `ErrorBodyWithCodeInteger`, `{ status: 404, message }` is\n   * `ErrorBodyWithStatus404`, `{ error: integer, error_description }` is\n   * `OAuthErrorBodyWithErrorInteger`, `{ message, errors: [{ code, message }] }`\n   * is `ErrorBodyWithCodeMessageErrors`, a `{ message }` hinted\n   * `message → detail` is `ErrorBodyWithMessageAsDetail`, and a body that\n   * requires no field is named from every field under `Optional`\n   * (`OptionalErrorBody` for `{ message? }`); what no name can spell — a\n   * value pinned inside an array, a discriminator mapping, the component or\n   * named enum a field references, a field named like another field's\n   * qualifier (`code_integer` beside `code: integer`), a pinned value that\n   * spells a family prefix (`code: 'optional'` beside `{ message? }`) —\n   * leaves the later shape's models as they are, with a warning; a shape\n   * whose name is its field names alone sorts before one a qualifier\n   * spelled, so adding the qualified shape moves no model. A component of the shared name takes each\n   * body it declares every field, domain name and limit of, and leaves a\n   * body it would narrow as it is. An optional field's hint is carried\n   * whichever bodies give it, and dropped with a warning when two bodies\n   * hint it apart. On by default; `false` keeps one model per operation and\n   * status code (`<Op>Error<code>`).\n   */\n  collapseErrorBodies?: boolean;\n  /**\n   * Pre-IR overlay applied to the bundled OpenAPI document before any IR\n   * extraction runs. Use this when the upstream spec can't be changed but you\n   * need to patch around a spec quirk that would otherwise emit a breaking SDK\n   * change — e.g. rewriting a path's response `$ref` back to its prior schema,\n   * merging the new fields onto the prior schema, and dropping the fork.\n   *\n   * The function may mutate the document in place and return it, or return a\n   * new object; the returned value is what the rest of oagen sees.\n   *\n   * Runs once, after `$ref` bundling and before schema/operation extraction.\n   * If you need to inspect the resulting IR instead, post-process the\n   * `ApiSpec` returned by `parseSpec`.\n   */\n  transformSpec?: (spec: OpenApiDocument) => OpenApiDocument;\n}\n\nexport async function parseSpec(specPath: string, options?: ParseOptions): Promise<ApiSpec> {\n  const { parsed } = await loadAndBundleSpec(specPath);\n  const transformed = options?.transformSpec ? options.transformSpec(parsed) : parsed;\n\n  const spec = transformed as {\n    openapi?: string;\n    info?: { title?: string; version?: string; description?: string };\n    servers?: RawServerObject[];\n    security?: RawSecurityRequirements;\n    tags?: Array<{ name?: string; description?: string; externalDocs?: RawExternalDocs }>;\n    externalDocs?: RawExternalDocs;\n    paths?: Record<string, unknown>;\n    webhooks?: unknown;\n    'x-webhooks'?: unknown;\n    components?: {\n      schemas?: Record<string, unknown>;\n      parameters?: Record<string, unknown>;\n      requestBodies?: Record<string, unknown>;\n      responses?: Record<string, unknown>;\n      examples?: Record<string, unknown>;\n      headers?: Record<string, unknown>;\n      pathItems?: Record<string, unknown>;\n      callbacks?: Record<string, unknown>;\n      securitySchemes?: Record<string, SecuritySchemeObject | ReferenceObject>;\n    };\n  };\n\n  // Validate OpenAPI version\n  const version = spec.openapi ?? '';\n  if (!version.startsWith('3.')) {\n    throw new SpecParseError(\n      `Unsupported OpenAPI version: ${version}. oagen requires OpenAPI 3.x`,\n      `Update the spec to OpenAPI 3.0 or 3.1. If you are using Swagger 2.x, convert it first with \\`npx swagger2openapi ${specPath}\\`.`,\n    );\n  }\n\n  // The whole document goes along so the rules that read every inline schema\n  // of a root at once see the operations' and webhooks' schemas too, not\n  // only the components' (`SchemaExtractionOptions.document`).\n  const { models, enums } = extractSchemas(\n    spec.components?.schemas as Record<string, Record<string, unknown>> | undefined,\n    { schemaNameTransform: options?.schemaNameTransform, document: transformed },\n  );\n\n  // Before the operations: an operation carries its own `servers` only when\n  // they differ from the document's, so the document's list is needed first.\n  const { servers, baseUrl } = extractServers(spec.servers);\n\n  // Extract inline models from model field definitions (objects/arrays with properties).\n  // schemaNameTransform is kept active so inline child names use the\n  // transformed parent name (e.g. AuditLogSchemaJson→AuditLogSchema yields\n  // AuditLogSchemaTarget, not AuditLogSchemaJsonTarget). Read before the\n  // operations and the webhooks so the names those mint — header and\n  // fallback models, webhook payloads — are reserved against these too: a\n  // map's values or a nested object a component field mints (`ReportDetail`)\n  // is not among `models`, and a titled fallback variant would otherwise take\n  // its name and the field merge below drop the component's definition.\n  // Each field's site is recorded too, so a merge pass that must rename one\n  // of these models can repoint exactly the references that mint it.\n  const fieldInlineModelGroups: FieldInlineModelGroup[] = [];\n  const extractedFieldModels = extractInlineModelsFromSchemas(\n    spec.components?.schemas as Record<string, Record<string, unknown>> | undefined,\n    fieldInlineModelGroups,\n  );\n  // The components' own field models are settled against the components\n  // right here, before any operation or webhook is read\n  // (`settleFieldInlineModels`): a field object named like a component that\n  // does not admit it takes its qualified name now (`PetOwner2`), and one\n  // the component admits is dropped for it, so every later reader — the\n  // operations' bodies, the shape registry, the webhooks, the merges below —\n  // sees each component referencing its children by their final names, and\n  // no parent is ever compared with a component on an unsettled child. The\n  // names are minted against everything decided so far; a reference an\n  // `allOf` merge copies from such a field later is created under the\n  // settled name (`recordInheritedModelRefs`). A field object named like\n  // one of the document's enums (`enumNames`: the component enums and the\n  // enums the component pass lifted) takes its qualified name here too; one\n  // named like an enum an operation or webhook carries, which is not known\n  // yet, takes it when the merges below settle the fields again against\n  // every enum name in play.\n  const enumNames: ReadonlySet<string> = new Set(enums.map((e) => e.name));\n  // The names every merge pass mints, shared across the passes so a later\n  // one can tell a parent whose child an earlier pass renamed\n  // (`InlineModelNaming.minted`). Each field's site already holds the object\n  // the schema pass lifted from the field's own schema\n  // (`fieldInlineModelBundles`, `liftedFieldModelsOf`), so a copy dropped\n  // here for it needs no record. The model each name was minted for goes\n  // along under the name it left (`InlineModelNaming.mintedFor`), so an\n  // operation's copy identical to a field's that left a name here joins the\n  // field's model rather than minting another.\n  const mintedNames = new Set<string>();\n  const mintedFor = new Map<string, Map<Model, number>>();\n  // The field sites, kept for the merges below (`refreshFieldInlineModelBundles`):\n  // what a fold carries onto a site here must still be there when a later\n  // pass renames the model it was carried onto. The fields of a component\n  // the operations only send, read off the document since none is read yet\n  // (`sentOnlyComponentNames`), are sites the SDK sends: a field object there\n  // shares a component of its name on an identical shape only.\n  const fieldInlineModelBundlesBySite = fieldInlineModelBundles(\n    fieldInlineModelGroups,\n    models,\n    sentOnlyComponentNames(transformed),\n  );\n  // The component schemas' names, resolved while the transform is still\n  // active so they match the models': they let every merge pass tell a\n  // clash with a component schema from one between two inline models, and\n  // tell a component — which admits no copy while deprecated (#441) — from\n  // the object the schema pass lifted from one of its fields, which still\n  // admits the field extractor's own deprecated copy of that field.\n  const componentNames = new Set(\n    Object.keys(spec.components?.schemas ?? {}).map((schemaName) => resolveSchemaName(schemaName)),\n  );\n  const fieldInlineModels = settleFieldInlineModels(models, extractedFieldModels, {\n    bundles: fieldInlineModelBundlesBySite,\n    reserved: reservedTypeNames(models, enums, [], extractedFieldModels, []),\n    enums: enumNames,\n    minted: mintedNames,\n    mintedFor,\n    components: componentNames,\n  });\n\n  const { services, inlineModels, inlineModelBundles, componentSites, declaredCallbacks } = extractOperations(\n    spec.paths as Record<string, Record<string, unknown>> | undefined,\n    options?.operationIdTransform,\n    spec.components?.schemas as Record<string, Record<string, unknown>> | undefined,\n    spec.components?.parameters as Record<string, Record<string, unknown>> | undefined,\n    spec.components?.requestBodies as Record<string, Record<string, unknown>> | undefined,\n    models,\n    spec.tags,\n    spec.components?.examples as Record<string, Record<string, unknown>> | undefined,\n    spec.components?.headers as Record<string, Record<string, unknown>> | undefined,\n    spec.components?.responses as Record<string, Record<string, unknown>> | undefined,\n    fieldInlineModels,\n    servers,\n    version,\n    options?.operationHints,\n    // The component enums, so no model the operations pass mints — a header,\n    // parameter, fallback, error or secondary body's, an array body's items —\n    // takes one of their names.\n    enums,\n    // A `paths` entry may be a `$ref` into this map (OpenAPI 3.1); the\n    // webhooks below resolve theirs against the same one.\n    spec.components?.pathItems as Record<string, Record<string, unknown>> | undefined,\n    // Or a `$ref` to a `webhooks` entry, as a webhook's may name a `paths` one.\n    spec.webhooks,\n  );\n\n  // Webhooks are read while the schema-name transform is still active, like\n  // operations, so a payload's `$ref`s resolve to the same names as a field's.\n  // Their models are named last, against every model and enum decided so far —\n  // components, operations, and the components' own inline field models — so\n  // a webhook never takes a name another pass has already minted.\n  const receivedComponents = {\n    schemas: spec.components?.schemas as Record<string, Record<string, unknown>> | undefined,\n    parameters: spec.components?.parameters as Record<string, Record<string, unknown>> | undefined,\n    requestBodies: spec.components?.requestBodies as Record<string, Record<string, unknown>> | undefined,\n    responses: spec.components?.responses as Record<string, Record<string, unknown>> | undefined,\n    examples: spec.components?.examples as Record<string, Record<string, unknown>> | undefined,\n    pathItems: spec.components?.pathItems as Record<string, Record<string, unknown>> | undefined,\n    callbacks: spec.components?.callbacks as Record<string, Record<string, unknown>> | undefined,\n  };\n  const {\n    webhooks,\n    inlineModels: webhookInlineModels,\n    inlineModelBundles: webhookInlineModelBundles,\n    declaredCallbacks: webhookCallbacks,\n  } = extractWebhooks(\n    spec.webhooks,\n    receivedComponents,\n    collectExistingNames([...models, ...inlineModels, ...fieldInlineModels], services, enums),\n    collectExistingEnumNames([...models, ...inlineModels, ...fieldInlineModels], services, enums),\n    // Text beside a `$ref` is read by the document's version, as for operations.\n    siblingDocsMode(version),\n    // A webhook entry may be a `$ref` to a `paths` entry, as to another webhook.\n    spec.paths,\n  );\n  warnOnLegacyWebhooks(spec['x-webhooks']);\n\n  // The callbacks every operation and webhook declares are read last, into\n  // `Operation.callbacks` / `Webhook.callbacks`, through the webhook\n  // machinery (#382): their models are named against every name decided so\n  // far — components, operations, webhooks, the components' field models —\n  // and join the webhooks' from here on, since a callback's payload is\n  // received exactly as a webhook's is and every later pass reaches it the\n  // same way (`collectWebhookTypeRefs`, `collectOperationTypeRefs`).\n  const { inlineModels: callbackInlineModels, inlineModelBundles: callbackInlineModelBundles } = extractCallbacks(\n    [...declaredCallbacks, ...webhookCallbacks],\n    receivedComponents,\n    collectExistingNames(\n      [...models, ...inlineModels, ...fieldInlineModels, ...webhookInlineModels],\n      services,\n      enums,\n      webhooks,\n    ),\n    collectExistingEnumNames(\n      [...models, ...inlineModels, ...fieldInlineModels, ...webhookInlineModels],\n      services,\n      enums,\n      webhooks,\n    ),\n    siblingDocsMode(version),\n    spec.paths,\n    spec.webhooks,\n  );\n  webhookInlineModels.push(...callbackInlineModels);\n  webhookInlineModelBundles.push(...callbackInlineModelBundles);\n\n  // The references a schema `$ref` that names no component left pending —\n  // a pointer deeper into a component, `#/components/schemas/Pet/properties/\n  // owner` (#539) — are settled now that every model is built and before\n  // any merge pass renames one, while the transform is still active so the\n  // component a pointer enters is typed as every `$ref` to it is. Each\n  // settled reference joins the site of the model it names\n  // (`attachSharedRefs` below), so a rename of that model reaches it.\n  const settledPointerRefs = resolveSchemaPointers(\n    { models: [...models, ...fieldInlineModels, ...inlineModels, ...webhookInlineModels], services, webhooks },\n    spec.components?.schemas as Record<string, Record<string, unknown>> | undefined,\n  );\n\n  clearSchemaNameTransform();\n\n  // Every name in play — component models and enums, every inline model of\n  // every pass, and every inline enum the collectors below will lift — so a\n  // copy a merge pass must rename (a response named like a component that\n  // does not admit it, a deprecated response named like a live one) takes a\n  // name nothing else has or will have, in either pass; and the enum names\n  // among them, which no inline model keeps: a `getPet` body beside a\n  // component enum `GetPetResponse` steps to `GetPetResponse2`, and so does\n  // a `createPet` body beside a `request` query enum of its service named\n  // `CreatePetRequest`, as a `request` parameter object beside that enum\n  // steps in the shape registry (`reserveEnumNames`) — the model steps\n  // wherever an enum of its name exists, so the IR never declares a model\n  // and an enum under one name. An enum the collectors lift after a model\n  // of its name that no pass could rename (a component model) steps itself\n  // (`collectDistinctEnums`). Every site is here: the operations', the\n  // webhooks', and the component fields' — read again, with the references\n  // the operations' and webhooks' `allOf` merges have copied from component\n  // fields since the fields were settled.\n  const reserved = reservedNamesByKind(\n    models,\n    enums,\n    [...inlineModels, ...webhookInlineModels],\n    fieldInlineModels,\n    services,\n    webhooks,\n  );\n  const naming: InlineModelNaming = {\n    bundles: [\n      ...inlineModelBundles,\n      ...webhookInlineModelBundles,\n      // The field sites from the settle, brought up to date: each holds the\n      // object the schema pass lifted from the field's own schema, which the\n      // extracted copy folded onto at the settle, and whatever a fold carried\n      // onto it there, so a rename here reaches all of it; the references a\n      // header or fallback body wrote by sharing that object join the site\n      // below (`attachSharedRefs`) and follow the rename.\n      ...refreshFieldInlineModelBundles(fieldInlineModelBundlesBySite, fieldInlineModelGroups, fieldInlineModels),\n    ],\n    reserved: reserved.all,\n    enums: reserved.enums,\n    minted: mintedNames,\n    mintedFor,\n    components: componentNames,\n  };\n  // The components' field models, settled above, own their names here as\n  // the components do (`declared`), so a nested object of a response named\n  // like one is decided against it before its parent is compared — never\n  // passed for it by name under a parent the lifted model admits.\n  const responseNormalizedModels = mergeInlineResponseModels(\n    models,\n    [...inlineModels, ...webhookInlineModels],\n    naming,\n    fieldInlineModels,\n  );\n  // An operation's array items that share a component field's model\n  // (`typeInlineItems`) join that field's site, so a rename of the field's\n  // model reaches the array too (`attachSharedRefs`); so does a reference a\n  // pointer into a component settled to that model (`settledPointerRefs`).\n  attachSharedRefs(naming.bundles, componentNames, settledPointerRefs);\n  const fieldMergedModels = mergeFieldInlineModels(responseNormalizedModels, fieldInlineModels, componentNames, naming);\n  // The lifted enums the fold renamed away, each with a reference that now\n  // carries the new name.\n  const foldedEnums = new Map<string, EnumRef>();\n  const finalModels = collapseJsonSuffixModels(\n    fieldMergedModels,\n    services,\n    webhooks,\n    enums,\n    componentNames,\n    foldedEnums,\n  );\n  applyFieldHints(finalModels, options?.fieldHints);\n  // The inline error bodies, one model per operation and status code until here,\n  // fold onto shared models named by shape (`ErrorBody`, `ErrorBodyWithCode`),\n  // their pinned `code`s gathered into one enum the collectors below lift.\n  const collapsedModels =\n    options?.collapseErrorBodies === false\n      ? finalModels\n      : collapseErrorBodies({ services, webhooks, models: finalModels }, { componentNames, componentSites, enums });\n  // A hint keyed by a shared model's name (`ErrorBodyWithCode`) applies here;\n  // one keyed by a folded model's name was applied above and rode along.\n  applyFieldHints(collapsedModels, options?.fieldHints);\n  // Each collector steps a renamed enum around every model name as well as\n  // every enum's, so the merge passes above (which mint against every enum\n  // name an `EnumRef` carries) and the collectors never meet on one name.\n  collectInlineEnumsFromModels(collapsedModels, enums);\n  collectInlineEnumsFromOperations(services, enums, componentSites, collapsedModels, componentNames);\n  // A webhook's callbacks are reached through the webhook; an operation's\n  // are lifted here, as received requests, after the operation's own.\n  collectInlineEnumsFromWebhooks(webhooks, enums, collapsedModels);\n  collectInlineEnumsFromWebhooks(\n    services.flatMap((service) => service.operations.flatMap((op) => op.callbacks ?? [])),\n    enums,\n    collapsedModels,\n  );\n  // Noted once the collectors have settled the name: `PetJsonMode` renamed\n  // to `PetMode` beside a component model `PetMode` is lifted as `PetMode2`.\n  for (const [name, ref] of foldedEnums) console.warn(`[oagen] Folded enum \"${name}\" into \"${ref.name}\"`);\n\n  // A `$ref` entry's sibling text is read by the document's version, as for operations.\n  const auth = extractAuthSchemes(spec.components?.securitySchemes, siblingDocsMode(version));\n\n  const result: ApiSpec = {\n    name: spec.info?.title ?? 'Unknown API',\n    version: spec.info?.version ?? '0.0.0',\n    description: spec.info?.description,\n    // The document's own link; the key stays absent when it declares none.\n    ...externalDocsEntry(spec.externalDocs),\n    baseUrl,\n    servers,\n    services,\n    // Omitted, not an empty list, for a document without webhooks so its IR\n    // keeps the shape it had before the key existed.\n    ...(webhooks.length > 0 ? { webhooks } : {}),\n    models: collapsedModels,\n    enums,\n    auth,\n    security: extractSecurityRequirements(spec.security, 'the document'),\n    sdk: defaultSdkBehavior(),\n  };\n\n  // Needs the finished models and enums: divergence is decided on member\n  // shape, so this can only run once every referenced type is resolvable.\n  assignParameterGroupWrapperNames(result);\n\n  // `bases` and `inheritedFrom` as the models end: no chain of bases\n  // reaching its own model, each base once, and no base or inherited field\n  // a fold has since changed under the model (#591).\n  settleBases(result.models);\n\n  validateModelRefs(result);\n\n  return result;\n}\n/**\n * Apply `fieldHints` onto the built models, setting `Field.domainName` for each\n * matching (model name, wire field name) pair. Serialization still uses\n * `Field.name`; only the domain-facing identifier changes.\n */\nfunction applyFieldHints(\n  models: import('../ir/types.js').Model[],\n  fieldHints: Record<string, Record<string, string>> | undefined,\n): void {\n  if (!fieldHints) return;\n  for (const model of models) {\n    const hints = fieldHints[model.name];\n    if (!hints) continue;\n    for (const field of model.fields) {\n      const domainName = hints[field.name];\n      if (domainName) field.domainName = domainName;\n    }\n  }\n}\n\n/**\n * `x-webhooks` is the extension some OpenAPI 3.0 documents use for what 3.1\n * standardized as the top-level `webhooks` map. The parser deliberately reads\n * the standard key only: an extension has no agreed shape to parse, and\n * reading it silently would make the IR depend on a convention the document\n * never declared. A document that carries one is told so, once, so the\n * omission is a visible choice rather than a quiet loss. An operation's\n * `callbacks`, which have an agreed shape, are read (`extractCallbacks`;\n * #382).\n */\nfunction warnOnLegacyWebhooks(legacy: unknown): void {\n  if (typeof legacy !== 'object' || legacy === null) return;\n  console.warn(\n    '[oagen] Warning: `x-webhooks` is not read. Declare the webhooks under the top-level `webhooks` map (OpenAPI 3.1) to have them parsed.',\n  );\n}\n\n/** A `components.securitySchemes` entry as it appears in the OpenAPI document. */\ninterface SecuritySchemeObject {\n  type: string;\n  description?: string;\n  scheme?: string;\n  in?: string;\n  name?: string;\n  flows?: Record<string, unknown>;\n}\n\n/**\n * Extract authentication schemes from OpenAPI securitySchemes.\n *\n * Document order is preserved. Each entry carries its `securitySchemes` key as\n * `schemeName` so emitters can join the requirements under `ApiSpec.security`\n * and `Operation.security` back to it.\n * Schemes the IR cannot represent are omitted with a warning rather than silently.\n *\n * An entry may be a `$ref` to another entry of the map — OAS 3.0.3 and\n * 3.1.0 both allow a Reference Object under `components.securitySchemes` —\n * and is followed, chains included, through `followReference`, the walk\n * every Reference Object takes, so the scheme is read under the REFERENCING\n * key with the target's definition: `petKey: { $ref:\n * '#/components/securitySchemes/sharedKey' }` is `schemeName: 'petKey'`\n * beside `sharedKey`'s own entry, and a requirement naming `petKey` joins to\n * it (#384). A `description` written beside the `$ref` overrides the\n * target's under 3.1 and is ignored under 3.0 (`siblingDocs`). A ref the map\n * does not answer — a pointer into another section, or a `$ref` that is not\n * a string — is omitted with the same warning an unsupported scheme gets,\n * naming the ref and how the walk ended; one that names no component at\n * all, or a cycle of refs, fails the bundle before parsing, as any dangling\n * ref does.\n */\nfunction extractAuthSchemes(\n  securitySchemes: Record<string, SecuritySchemeObject | ReferenceObject> | undefined,\n  siblingDocs: SiblingDocs,\n): AuthScheme[] | undefined {\n  if (!securitySchemes) return undefined;\n  const schemes: AuthScheme[] = [];\n  // Every pointer is `#/components/securitySchemes/<name>`, so the map\n  // itself is what a ref resolves against.\n  const components = securitySchemes as unknown as Record<string, Record<string, unknown>>;\n  for (const [schemeName, entry] of Object.entries(securitySchemes)) {\n    const followed = followReference<SecuritySchemeObject>(entry, 'securitySchemes', components, siblingDocs);\n    if (followed.outcome !== 'resolved') {\n      console.warn(\n        `[oagen] Warning: Unsupported security scheme \"${schemeName}\" ($ref ${followed.ref} ${followed.outcome}) omitted from spec.auth`,\n      );\n      continue;\n    }\n    const scheme = followed.value;\n    // Omit `description` entirely (rather than setting it to undefined) when the\n    // document does not declare one. An explicit empty string is a declared value\n    // and is kept, so consumers can tell \"empty\" from \"missing\".\n    const common = scheme.description !== undefined ? { schemeName, description: scheme.description } : { schemeName };\n    // HTTP authentication scheme names are case-insensitive (RFC 9110 §11.1).\n    const httpScheme = scheme.type === 'http' ? scheme.scheme?.toLowerCase() : undefined;\n    if (httpScheme === 'bearer') {\n      schemes.push({ kind: 'bearer', ...common });\n    } else if (httpScheme === 'basic') {\n      schemes.push({ kind: 'basic', ...common });\n    } else if (scheme.type === 'apiKey' && scheme.in && scheme.name) {\n      schemes.push({ kind: 'apiKey', ...common, in: scheme.in as 'header' | 'query' | 'cookie', name: scheme.name });\n    } else if (scheme.type === 'oauth2' && scheme.flows) {\n      schemes.push({ kind: 'oauth2', ...common, flows: scheme.flows });\n    } else {\n      // Other http schemes (digest, ...), openIdConnect, mutualTLS, and malformed\n      // entries have no IR representation; say so instead of dropping them silently.\n      const detail = scheme.type === 'http' ? `type: http, scheme: ${scheme.scheme}` : `type: ${scheme.type}`;\n      console.warn(`[oagen] Warning: Unsupported security scheme \"${schemeName}\" (${detail}) omitted from spec.auth`);\n    }\n  }\n  return schemes.length > 0 ? schemes : undefined;\n}\n","/**\n * Shared infrastructure for smoke tests.\n *\n * Types, operation planning, payload generation, ID registry, and capture format\n * used by both raw HTTP and SDK smoke test scripts.\n */\n\nimport 'dotenv/config';\nimport { readFileSync } from 'node:fs';\nimport type { ApiSpec, Operation, Parameter, StatusRange, TypeRef } from '../../src/ir/types.js';\nimport { parseSpec } from '../../src/parser/parse.js';\nimport { toSnakeCase, toCamelCase } from '../../src/utils/naming.js';\n\n// Re-export types and functions that external smoke runners need from oagen core.\n// External runners import from '@workos/oagen/smoke' which bundles this module.\nexport { parseSpec } from '../../src/parser/parse.js';\nexport { toCamelCase, toSnakeCase } from '../../src/utils/naming.js';\nexport type { StatusRange } from '../../src/ir/types.js';\n\n// ---------------------------------------------------------------------------\n// Capture format\n// ---------------------------------------------------------------------------\n\nexport interface ExchangeProvenance {\n  resolutionTier: 'exact' | 'crud-prefix' | 'fuzzy' | 'manifest';\n  resolutionConfidence: number;\n  sdkMethodName: string;\n  captureIndex: number;\n  totalCaptures: number;\n}\n\nexport interface CapturedExchange {\n  operationId: string;\n  service: string;\n  operationName: string;\n  request: {\n    method: string;\n    path: string;\n    queryParams: Record<string, string>;\n    body: unknown | null;\n  };\n  response: {\n    status: number;\n    body: unknown | null;\n  };\n  outcome: 'success' | 'api-error' | 'skipped';\n  error?: string;\n  /**\n   * True when the operation's declared responses do not cover the response\n   * status: no explicit code, no `1XX`–`5XX` range containing it and no\n   * `default` response. See `isUnexpectedStatus`.\n   */\n  unexpectedStatus?: boolean;\n  /**\n   * The explicit status codes the operation declares (`ExpectedStatuses.codes`:\n   * every declared 2xx/3xx code and every `errors` code; nothing is implied\n   * from the HTTP method). A range or `default` response is not listed here;\n   * `expectedStatuses` carries those.\n   */\n  expectedStatusCodes?: number[];\n  /**\n   * Everything the operation's declared responses cover — the explicit\n   * codes, the `1XX`–`5XX` ranges and whether a `default` response exists —\n   * as `unexpectedStatus` was decided against it. `expectedStatusCodes` is\n   * its `codes` list.\n   */\n  expectedStatuses?: ExpectedStatuses;\n  durationMs: number;\n  /** How the SDK method was resolved and which capture was selected */\n  provenance?: ExchangeProvenance;\n}\n\nexport interface SmokeResults {\n  source: 'raw' | 'spec-baseline' | `sdk-${string}`;\n  timestamp: string;\n  specVersion: string;\n  exchanges: CapturedExchange[];\n}\n\n// ---------------------------------------------------------------------------\n// Operation planning\n// ---------------------------------------------------------------------------\n\nexport interface PlannedOperation {\n  service: string;\n  operation: Operation;\n}\n\nexport interface PlannedGroup {\n  service: string;\n  operations: PlannedOperation[];\n}\n\n// ---------------------------------------------------------------------------\n// Smoke config — mutable state populated by loadSmokeConfig()\n// ---------------------------------------------------------------------------\n\n/** Operations that require complex preconditions and can't be auto-tested */\nexport let SKIP_OPERATIONS = new Set<string>();\n\n/** Services to skip entirely */\nexport let SKIP_SERVICES = new Set<string>();\n\n/**\n * Services that produce IDs other services depend on should run first.\n * Lower number = runs earlier. Unlisted services default to 50.\n */\nlet SERVICE_PRIORITY: Record<string, number> = {};\n\n/**\n * Map IR service names to SDK property names on the client object.\n * Empty = use toCamelCase(serviceName) as fallback.\n */\nexport let SERVICE_PROPERTY_MAP: Record<string, string> = {};\n\nexport interface SmokeConfig {\n  skipOperations: string[];\n  skipServices: string[];\n  servicePriority: Record<string, number>;\n  servicePropertyMap: Record<string, string>;\n}\n\n/** Load smoke test configuration from a JSON file */\nexport function loadSmokeConfig(configPath?: string): void {\n  if (!configPath) return;\n  const raw = readFileSync(configPath, 'utf-8');\n  const config: SmokeConfig = JSON.parse(raw);\n\n  if (config.skipOperations) SKIP_OPERATIONS = new Set(config.skipOperations);\n  if (config.skipServices) SKIP_SERVICES = new Set(config.skipServices);\n  if (config.servicePriority) SERVICE_PRIORITY = config.servicePriority;\n  if (config.servicePropertyMap) SERVICE_PROPERTY_MAP = config.servicePropertyMap;\n}\n\n/** Return the current smoke config values (for diff.ts to consume) */\nexport function getSmokeConfig() {\n  return {\n    skipOperations: SKIP_OPERATIONS,\n    skipServices: SKIP_SERVICES,\n    servicePriority: SERVICE_PRIORITY,\n    servicePropertyMap: SERVICE_PROPERTY_MAP,\n  };\n}\n\n/**\n * Assign a numeric sort key to an operation so that ID-producing operations\n * (parameterless creates and lists) run before ID-consuming ones.\n */\nfunction operationSortKey(op: Operation): number {\n  const hasParams = op.pathParams.length > 0;\n  const method = op.httpMethod;\n\n  if (method === 'post' && !hasParams) return 0; // top-level create\n  if (method === 'get' && !hasParams && op.pagination) return 1; // top-level list\n  if (method === 'get' && !hasParams) return 2; // top-level singular GET\n  if (method === 'post' && hasParams) return 3; // sub-entity create\n  if (method === 'get' && hasParams && op.pagination) return 4; // sub-entity list\n  if (method === 'get' && hasParams) return 5; // singular GET by ID\n  if (method === 'put' || method === 'patch') return 6; // update\n  if (method === 'delete') return 7; // delete\n  return 99;\n}\n\nexport function planOperations(spec: ApiSpec): PlannedGroup[] {\n  const groups: PlannedGroup[] = [];\n\n  for (const service of spec.services) {\n    if (SKIP_SERVICES.has(service.name)) continue;\n\n    const ops: PlannedOperation[] = [];\n    for (const op of service.operations) {\n      if (SKIP_OPERATIONS.has(op.name)) continue;\n\n      ops.push({ service: service.name, operation: op });\n    }\n\n    if (ops.length === 0) continue;\n\n    // Sort to maximize ID availability:\n    //   1. Parameterless POSTs (create new top-level entities → produce IDs)\n    //   2. Parameterless list GETs (discover existing IDs)\n    //   3. Parameterized POSTs (create sub-entities, need parent IDs)\n    //   4. Parameterized list GETs\n    //   5. Parameterized singular GETs (retrieve by ID)\n    //   6. PUT/PATCH (update)\n    //   7. DELETE\n    ops.sort((a, b) => {\n      return operationSortKey(a.operation) - operationSortKey(b.operation);\n    });\n\n    groups.push({ service: service.name, operations: ops });\n  }\n\n  // Sort service groups so ID-producing services run first\n  groups.sort((a, b) => {\n    const aPri = SERVICE_PRIORITY[a.service] ?? 50;\n    const bPri = SERVICE_PRIORITY[b.service] ?? 50;\n    return aPri - bPri;\n  });\n\n  return groups;\n}\n\n// ---------------------------------------------------------------------------\n// Wave-based operation planning for batched runners\n// ---------------------------------------------------------------------------\n\n/**\n * A single wave of operations that can be planned and executed together.\n * Wave 0 contains parameterless operations. Subsequent waves contain\n * operations whose path params became resolvable after earlier waves ran.\n */\nexport interface OperationWave {\n  /** Operations in this wave, with pre-resolved path params */\n  calls: Array<{\n    op: Operation;\n    irService: string;\n    pathParams: Record<string, string>;\n  }>;\n}\n\n/**\n * Plan operations in waves so that batched runners can execute each wave,\n * extract IDs from responses, then plan the next wave.\n *\n * Returns an iterator that yields one wave at a time. The caller must\n * execute each wave and populate the IdRegistry before calling next().\n *\n * @param groups - service groups from planOperations()\n * @param ids - the IdRegistry (mutated by the caller between waves)\n * @param resolveMethod - optional filter; return null to skip an operation\n */\nexport function* planWaves(\n  groups: PlannedGroup[],\n  ids: IdRegistry,\n  resolveMethod?: (op: Operation, irService: string) => boolean,\n): Generator<OperationWave, PlannedOperation[], void> {\n  // Flatten all operations into a single ordered list\n  const remaining: PlannedOperation[] = [];\n  for (const group of groups) {\n    for (const planned of group.operations) {\n      remaining.push(planned);\n    }\n  }\n\n  // Track which operations have been emitted\n  const emitted = new Set<number>();\n  const skipped: PlannedOperation[] = [];\n\n  // Pre-filter: mark operations that fail the resolveMethod check as skipped\n  for (let i = 0; i < remaining.length; i++) {\n    const { operation: op, service: irService } = remaining[i];\n    if (resolveMethod && !resolveMethod(op, irService)) {\n      emitted.add(i);\n      skipped.push(remaining[i]);\n    }\n  }\n\n  // Wave 0: operations with no path params\n  let wave: OperationWave = { calls: [] };\n  for (let i = 0; i < remaining.length; i++) {\n    if (emitted.has(i)) continue;\n    const { operation: op, service: irService } = remaining[i];\n    if (op.pathParams.length === 0) {\n      wave.calls.push({ op, irService, pathParams: {} });\n      emitted.add(i);\n    }\n  }\n\n  if (wave.calls.length > 0) {\n    yield wave;\n  }\n\n  // Subsequent waves: try to resolve remaining operations\n  let madeProgress = true;\n  while (madeProgress) {\n    madeProgress = false;\n    wave = { calls: [] };\n\n    for (let i = 0; i < remaining.length; i++) {\n      if (emitted.has(i)) continue;\n      const { operation: op, service: irService } = remaining[i];\n\n      const resolved = ids.resolvePathParams(op, irService);\n      if (resolved) {\n        wave.calls.push({ op, irService, pathParams: resolved });\n        emitted.add(i);\n        madeProgress = true;\n      }\n    }\n\n    if (wave.calls.length > 0) {\n      yield wave;\n    }\n  }\n\n  // Collect truly unresolvable operations for the caller to mark as skipped\n  const unresolved: PlannedOperation[] = [];\n  for (let i = 0; i < remaining.length; i++) {\n    if (!emitted.has(i)) {\n      unresolved.push(remaining[i]);\n    }\n  }\n  return unresolved;\n}\n\n// ---------------------------------------------------------------------------\n// Payload generation\n// ---------------------------------------------------------------------------\n\nexport function generateFixtureValue(typeRef: TypeRef, fieldName: string, spec: ApiSpec): unknown {\n  switch (typeRef.kind) {\n    case 'primitive':\n      return generatePrimitiveFixture(typeRef.type, typeRef.format, fieldName);\n    case 'array':\n      return [generateFixtureValue(typeRef.items, fieldName, spec)];\n    case 'model': {\n      const model = spec.models.find((m) => m.name === typeRef.name);\n      if (model) {\n        const obj: Record<string, unknown> = {};\n        for (const field of model.fields) {\n          if (field.required) {\n            obj[toSnakeCase(field.name)] = generateFixtureValue(field.type, field.name, spec);\n          }\n        }\n        return obj;\n      }\n      return {};\n    }\n    case 'enum': {\n      const e = spec.enums.find((en) => en.name === typeRef.name);\n      return e?.values[0]?.value ?? 'unknown';\n    }\n    case 'nullable':\n      return generateFixtureValue(typeRef.inner, fieldName, spec);\n    case 'union':\n      if (typeRef.variants.length > 0) {\n        return generateFixtureValue(typeRef.variants[0], fieldName, spec);\n      }\n      return null;\n  }\n}\n\nfunction generatePrimitiveFixture(type: string, format: string | undefined, fieldName: string): unknown {\n  if (type === 'string') {\n    if (format === 'uuid') return '550e8400-e29b-41d4-a716-446655440000';\n    if (format === 'date') return '2024-01-01';\n    if (format === 'date-time') return '2024-01-01T00:00:00Z';\n    if (format === 'email') return 'test@example.com';\n    if (format === 'uri' || format === 'url') return 'https://example.com';\n    return `test_${toSnakeCase(fieldName)}`;\n  }\n  if (type === 'integer') return 1;\n  if (type === 'number') return 1.0;\n  if (type === 'boolean') return true;\n  return null;\n}\n\n/** Generate a snake_case request body payload from an operation's requestBody type */\nexport function generatePayload(op: Operation, spec: ApiSpec): Record<string, unknown> | null {\n  if (!op.requestBody) return null;\n\n  const bodyType = op.requestBody;\n  if (bodyType.kind === 'model') {\n    const model = spec.models.find((m) => m.name === bodyType.name);\n    if (!model) return {};\n\n    const payload: Record<string, unknown> = {};\n    for (const field of model.fields) {\n      if (!field.required) continue;\n      const key = toSnakeCase(field.name);\n      let value = generateFixtureValue(field.type, field.name, spec);\n\n      // Inject uniqueness markers for name/slug fields\n      if ((key === 'name' || key === 'slug') && typeof value === 'string') {\n        value = `smoke-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n      }\n      payload[key] = value;\n    }\n    return payload;\n  }\n\n  // Fallback for non-model body types\n  return {};\n}\n\n/** Generate a fixture value with SDK-friendly types (e.g. Date objects for date-time) */\nfunction generateSDKFixtureValue(typeRef: TypeRef, fieldName: string, spec: ApiSpec): unknown {\n  const value = generateFixtureValue(typeRef, fieldName, spec);\n  // SDK methods expect Date objects for date-time fields, not ISO strings\n  if (typeRef.kind === 'primitive' && typeRef.format === 'date-time' && typeof value === 'string') {\n    return new Date(value);\n  }\n  return value;\n}\n\n/** Generate a camelCase payload for SDK method calls */\nexport function generateCamelPayload(op: Operation, spec: ApiSpec): Record<string, unknown> | null {\n  if (!op.requestBody) return null;\n\n  const bodyType = op.requestBody;\n  if (bodyType.kind === 'model') {\n    const model = spec.models.find((m) => m.name === bodyType.name);\n    if (!model) return {};\n\n    const payload: Record<string, unknown> = {};\n    for (const field of model.fields) {\n      if (!field.required) continue;\n      const key = toCamelCase(field.name);\n      let value = generateSDKFixtureValue(field.type, field.name, spec);\n\n      if ((field.name === 'name' || field.name === 'slug') && typeof value === 'string') {\n        value = `smoke-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n      }\n      payload[key] = value;\n    }\n    return payload;\n  }\n\n  return {};\n}\n\n/** Generate query params for an operation (required params only, plus limit=1 for lists) */\nexport function generateQueryParams(op: Operation, spec: ApiSpec): Record<string, string> {\n  const params: Record<string, string> = {};\n\n  if (op.pagination) {\n    params['limit'] = '1';\n  }\n\n  for (const p of op.queryParams) {\n    if (!p.required) continue;\n    const value = generateFixtureValue(p.type, p.name, spec);\n    params[toSnakeCase(p.name)] = String(value);\n  }\n\n  // Sort by key\n  const sorted: Record<string, string> = {};\n  for (const key of Object.keys(params).sort()) {\n    sorted[key] = params[key];\n  }\n  return sorted;\n}\n\n/** Generate camelCase query params for SDK method calls */\nexport function generateCamelQueryParams(op: Operation, spec: ApiSpec): Record<string, unknown> {\n  const params: Record<string, unknown> = {};\n\n  if (op.pagination) {\n    params['limit'] = 1;\n  }\n\n  for (const p of op.queryParams) {\n    if (!p.required) continue;\n    const value = generateFixtureValue(p.type, p.name, spec);\n    params[toCamelCase(p.name)] = value;\n  }\n\n  return params;\n}\n\n// ---------------------------------------------------------------------------\n// ID Registry\n// ---------------------------------------------------------------------------\n\nexport class IdRegistry {\n  private ids = new Map<string, string>();\n\n  set(service: string, field: string, value: string): void {\n    this.ids.set(`${service}.${field}`, value);\n  }\n\n  get(service: string, field: string): string | undefined {\n    return this.ids.get(`${service}.${field}`);\n  }\n\n  /** Resolve path parameters for an operation using stored IDs */\n  resolvePathParams(op: Operation, service: string): Record<string, string> | null {\n    const resolved: Record<string, string> = {};\n    for (const p of op.pathParams) {\n      const value =\n        this.get(service, p.name) ||\n        this.get(service, 'id') ||\n        this.findAcrossServices(p.name) ||\n        this.resolveFromParamName(p.name) ||\n        this.resolveFromExample(p);\n\n      if (!value) return null;\n      resolved[p.name] = value;\n    }\n    return resolved;\n  }\n\n  /** Try to find a param value across all services */\n  private findAcrossServices(field: string): string | undefined {\n    for (const [key, value] of this.ids.entries()) {\n      if (key.endsWith(`.${field}`)) return value;\n    }\n    // Also try snake_case variant: \"organizationId\" → \"organization_id\"\n    const snakeField = toSnakeCase(field);\n    if (snakeField !== field) {\n      for (const [key, value] of this.ids.entries()) {\n        if (key.endsWith(`.${snakeField}`)) return value;\n      }\n    }\n    return undefined;\n  }\n\n  /**\n   * Resolve a path param like \"organizationId\" by mapping it to the\n   * service that stores that entity's ID (e.g. Organizations.id).\n   * Also handles snake_case suffixed with _id by stripping the suffix\n   * and looking up the pluralized service name.\n   */\n  private resolveFromParamName(paramName: string): string | undefined {\n    // Infer from param name: \"resource_id\" → \"Resources\", \"role_assignment_id\" → \"RoleAssignments\"\n    // Handle snake_case: strip trailing _id, PascalCase+pluralize the rest\n    if (paramName.endsWith('_id')) {\n      const base = paramName.slice(0, -3); // e.g. \"resource_type\" from \"resource_type_id\"\n      const pascal = base\n        .split('_')\n        .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n        .join('');\n      const plural = pascal.endsWith('s') ? pascal : pascal + 's';\n      const val = this.get(plural, 'id') || this.get(plural, 'slug');\n      if (val) return val;\n\n      // Fallback: find any service whose name ends with the plural suffix\n      // e.g. \"user_id\" → \"Users\" not found → try \"UserManagementUsers\"\n      const suffixVal = this.findByServiceSuffix(plural, 'id') || this.findByServiceSuffix(plural, 'slug');\n      if (suffixVal) return suffixVal;\n    }\n\n    // Handle camelCase: \"resourceId\" → strip \"Id\", pluralize → \"Resources\"\n    if (paramName.endsWith('Id') && paramName.length > 2) {\n      const base = paramName.slice(0, -2); // e.g. \"organization\"\n      const pascal = base.charAt(0).toUpperCase() + base.slice(1);\n      const plural = pascal.endsWith('s') ? pascal : pascal + 's';\n      const val = this.get(plural, 'id') || this.get(plural, 'slug');\n      if (val) return val;\n\n      // Fallback: find any service whose name ends with the plural suffix\n      const suffixVal = this.findByServiceSuffix(plural, 'id') || this.findByServiceSuffix(plural, 'slug');\n      if (suffixVal) return suffixVal;\n    }\n\n    return undefined;\n  }\n\n  /**\n   * Find a value by looking for any service name that ends with the given suffix.\n   * e.g. suffix \"Users\" matches \"UserManagementUsers.id\"\n   */\n  private findByServiceSuffix(suffix: string, field: string): string | undefined {\n    for (const [key, value] of this.ids.entries()) {\n      if (key.endsWith(`.${field}`)) {\n        const servicePart = key.slice(0, -(field.length + 1));\n        if (servicePart.endsWith(suffix)) {\n          return value;\n        }\n      }\n    }\n    return undefined;\n  }\n\n  /**\n   * Last-resort fallback: use the spec's example or default value for a parameter.\n   * Many path params (e.g. actionName, slug, type) have example values in the spec.\n   */\n  private resolveFromExample(param: Parameter): string | undefined {\n    const value = param.example ?? param.default;\n    if (value !== undefined && value !== null) {\n      return String(value);\n    }\n    return undefined;\n  }\n\n  /**\n   * Extract IDs from a response body and store them.\n   * @param isTopLevel - true for operations without path params (their `id` belongs to this service).\n   *                     false for sub-resource operations (their `id` is a child entity, don't overwrite).\n   */\n  extractAndStore(service: string, responseBody: unknown, isTopLevel = true): void {\n    if (!responseBody || typeof responseBody !== 'object') return;\n\n    const body = responseBody as Record<string, unknown>;\n\n    // Only store direct ID from top-level operations to avoid overwriting\n    // e.g. Organizations.id with an API key ID from /organizations/{id}/api_keys\n    if (isTopLevel) {\n      if (typeof body.id === 'string') {\n        this.set(service, 'id', body.id);\n      }\n\n      // List response: extract from first item\n      if (Array.isArray(body.data) && body.data.length > 0) {\n        const first = body.data[0] as Record<string, unknown> | undefined;\n        if (first && typeof first === 'object') {\n          if (typeof first.id === 'string') {\n            this.set(service, 'id', first.id);\n          }\n          this.extractNestedIds(service, first);\n        }\n      }\n\n      if (typeof body.slug === 'string') this.set(service, 'slug', body.slug);\n      if (typeof body.key === 'string') this.set(service, 'key', body.key);\n    }\n\n    // Always extract nested reference IDs (e.g. organization_id, connection_id)\n    this.extractNestedIds(service, body);\n    if (Array.isArray(body.data) && body.data.length > 0) {\n      const first = body.data[0] as Record<string, unknown> | undefined;\n      if (first && typeof first === 'object') {\n        this.extractNestedIds(service, first);\n      }\n    }\n  }\n\n  /** Extract fields ending in _id or Id and store them for cross-service resolution */\n  private extractNestedIds(service: string, obj: Record<string, unknown>): void {\n    for (const [key, value] of Object.entries(obj)) {\n      if (typeof value !== 'string') continue;\n      if (key === 'id') continue; // already handled\n      // Store fields like \"organization_id\", \"connection_id\" directly\n      if (key.endsWith('_id') || (key.endsWith('Id') && key.length > 2)) {\n        this.set(service, key, value);\n      }\n    }\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Status code checking\n// ---------------------------------------------------------------------------\n\n/**\n * The statuses an operation's declared responses cover, read from every\n * response kind the IR carries: the explicit success and error codes, the\n * `1XX`–`5XX` range responses and the `default` response.\n */\nexport interface ExpectedStatuses {\n  /**\n   * The explicit status codes, ascending and without duplicates: every\n   * declared 2xx/3xx code (`responseStatusCode`, the primary success\n   * response's, plus every `successResponses` entry) and every `errors`\n   * code. An operation that declares no 2xx or 3xx response contributes no\n   * success code: nothing is implied from the HTTP method.\n   */\n  codes: number[];\n  /**\n   * The `rangeResponses` keys, in declaration order. A range covers every\n   * status in its hundred (`4XX` covers 400–499).\n   */\n  ranges: StatusRange[];\n  /**\n   * Whether the operation declares a `default` response, which covers every\n   * status that `codes` and `ranges` do not.\n   */\n  hasDefault: boolean;\n}\n\n/**\n * Read every status an operation's declared responses cover. Both\n * `getExpectedStatusCodes` and `isUnexpectedStatus` go through this, so the\n * one place that decides what counts as declared is here.\n */\nexport function getExpectedStatuses(op: Operation): ExpectedStatuses {\n  const codes = new Set<number>();\n  if (op.responseStatusCode !== undefined) codes.add(op.responseStatusCode);\n  for (const success of op.successResponses ?? []) codes.add(success.statusCode);\n  for (const err of op.errors) codes.add(err.statusCode);\n  return {\n    codes: [...codes].sort((a, b) => a - b),\n    ranges: (op.rangeResponses ?? []).map((entry) => entry.range),\n    hasDefault: op.defaultResponse !== undefined,\n  };\n}\n\n/**\n * Whether `expected` covers `status`, resolved the way OpenAPI resolves a\n * status: an explicit code, else the range whose hundred contains it, else\n * `default`.\n */\nexport function coversStatus(expected: ExpectedStatuses, status: number): boolean {\n  if (expected.codes.includes(status)) return true;\n  const range = `${Math.floor(status / 100)}XX`;\n  if (expected.ranges.some((entry) => entry === range)) return true;\n  return expected.hasDefault;\n}\n\n/**\n * The explicit status codes an operation declares — `getExpectedStatuses(op).codes`\n * alone. A range or `default` response cannot be expressed as a code and is\n * not listed, so this does not say whether a status is covered;\n * `isUnexpectedStatus` does.\n */\nexport function getExpectedStatusCodes(op: Operation): number[] {\n  return getExpectedStatuses(op).codes;\n}\n\n/**\n * `expected` as one token per entry, `/`-joined: `200/404/4XX/default`; an\n * operation that declares no responses covers nothing and reads\n * `none (no responses declared)`.\n */\nexport function formatExpectedStatuses(expected: ExpectedStatuses): string {\n  const tokens = [...expected.codes.map(String), ...expected.ranges, ...(expected.hasDefault ? ['default'] : [])];\n  return tokens.length > 0 ? tokens.join('/') : 'none (no responses declared)';\n}\n\n/**\n * Whether the operation's declared responses leave `status` uncovered: no\n * explicit code, no range containing it and no `default` response. A status\n * of 0 is never unexpected — it marks a skipped call or a network error, not\n * a status mismatch.\n */\nexport function isUnexpectedStatus(status: number, op: Operation): boolean {\n  if (status === 0) return false;\n  return !coversStatus(getExpectedStatuses(op), status);\n}\n\n// ---------------------------------------------------------------------------\n// Raw HTTP exchange capture\n// ---------------------------------------------------------------------------\n\n/** One request the raw runner sends, with the labels its exchange is recorded under. */\nexport interface RawRequest {\n  operationId: string;\n  service: string;\n  /** The HTTP method as sent, upper-case. */\n  method: string;\n  /** The resolved path, recorded as `request.path`. */\n  path: string;\n  /** The full URL to request, query string included. */\n  url: string;\n  /** The query parameters, recorded as `request.queryParams`. */\n  queryParams: Record<string, string>;\n  /** The JSON body: sent on POST, PUT and PATCH, recorded as `request.body` either way. */\n  body: unknown | null;\n  headers: Record<string, string>;\n}\n\nexport interface CaptureRawOptions {\n  /** The `fetch` to send with; `globalThis.fetch` by default. A test passes a stub. */\n  fetchImpl?: typeof fetch;\n  /** Milliseconds before the request is aborted; 30 000 by default. */\n  timeoutMs?: number;\n}\n\n/**\n * Send one request and record what came back as a `CapturedExchange`.\n *\n * Redirects are never followed (`redirect: 'manual'`): the exchange records\n * the operation's own response — the first hop — so a declared `302` is\n * recorded as 302 and judged like any other status by `isUnexpectedStatus`,\n * and a redirect the document does not declare is reported as unexpected\n * instead of being hidden behind its target's 200. The redirect target is\n * never requested. (Node's `fetch` returns a manual redirect with its real\n * status and `Location` header.)\n *\n * A 4xx or 5xx is an `api-error` exchange with `error: 'HTTP <status>'`; a\n * `fetch` that throws (timeout, DNS, connection refused) is an `api-error`\n * with status 0 and the error message, which is never an unexpected status.\n * The response body is read as JSON and recorded as null when it is not.\n */\nexport async function captureRawExchange(\n  op: Operation,\n  request: RawRequest,\n  options: CaptureRawOptions = {},\n): Promise<CapturedExchange> {\n  const { fetchImpl = fetch, timeoutMs = 30_000 } = options;\n  const { operationId, service, method, path, url, queryParams, body, headers } = request;\n  const base = { operationId, service, operationName: op.name, request: { method, path, queryParams, body } };\n  const start = Date.now();\n  const controller = new AbortController();\n  const timeout = setTimeout(() => controller.abort(), timeoutMs);\n  try {\n    const init: RequestInit = { method, headers, signal: controller.signal, redirect: 'manual' };\n    if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {\n      init.body = JSON.stringify(body);\n    }\n    const response = await fetchImpl(url, init);\n    clearTimeout(timeout);\n\n    const responseBody: unknown = await response.json().catch(() => null);\n    const isError = response.status >= 400;\n    const exchange: CapturedExchange = {\n      ...base,\n      response: { status: response.status, body: responseBody },\n      outcome: isError ? 'api-error' : 'success',\n      durationMs: Date.now() - start,\n    };\n    if (isError) exchange.error = `HTTP ${response.status}`;\n    if (isUnexpectedStatus(response.status, op)) {\n      const expected = getExpectedStatuses(op);\n      exchange.unexpectedStatus = true;\n      exchange.expectedStatusCodes = expected.codes;\n      exchange.expectedStatuses = expected;\n    }\n    return exchange;\n  } catch (err) {\n    clearTimeout(timeout);\n    return {\n      ...base,\n      response: { status: 0, body: null },\n      outcome: 'api-error',\n      error: err instanceof Error ? err.message : String(err),\n      durationMs: Date.now() - start,\n    };\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Path resolution\n// ---------------------------------------------------------------------------\n\nexport function resolvePath(op: Operation, pathParams: Record<string, string>): string {\n  let path = op.path;\n  for (const [name, value] of Object.entries(pathParams)) {\n    path = path.replace(`{${name}}`, value);\n  }\n  return path;\n}\n\n// ---------------------------------------------------------------------------\n// Utilities\n// ---------------------------------------------------------------------------\n\nexport function delay(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * The arguments a smoke script is run with: `--spec` (or `OPENAPI_SPEC_PATH`),\n * `--ir` (the IR `oagen verify` hands the script; see {@link loadSmokeSpec}),\n * `--sdk-path` and `--smoke-config` (or `SMOKE_CONFIG`).\n */\nexport function parseCliArgs(): { spec: string; ir?: string; sdkPath?: string; smokeConfig?: string } {\n  const args = process.argv.slice(2);\n  const specIdx = args.indexOf('--spec');\n  const spec = specIdx !== -1 && args[specIdx + 1] ? args[specIdx + 1] : process.env.OPENAPI_SPEC_PATH;\n  if (!spec) {\n    console.error('OpenAPI spec path is required. Set OPENAPI_SPEC_PATH env var or pass --spec <path>.');\n    process.exit(1);\n  }\n  const irIdx = args.indexOf('--ir');\n  const ir = irIdx !== -1 && args[irIdx + 1] ? args[irIdx + 1] : undefined;\n  const sdkPathIdx = args.indexOf('--sdk-path');\n  const sdkPath = sdkPathIdx !== -1 && args[sdkPathIdx + 1] ? args[sdkPathIdx + 1] : undefined;\n  const configIdx = args.indexOf('--smoke-config');\n  const smokeConfig = configIdx !== -1 && args[configIdx + 1] ? args[configIdx + 1] : process.env.SMOKE_CONFIG;\n  return { spec, ir, sdkPath, smokeConfig };\n}\n\n/**\n * The IR a smoke script plans its operations from.\n *\n * `oagen verify` hands every smoke script it runs — the spec-only baseline\n * and the runner — the IR it parsed, as `--ir <path>`: a JSON file in the\n * shape `oagen parse` prints, holding `--spec` parsed with the config's\n * settings (`operationIdTransform`, `transformSpec`, `operationHints`, …)\n * exactly as `generate` parses it. A script that reads it plans the\n * operations `generate` reads: `Pets.list` and `Pets.get` under a transform\n * that strips `PetsController_`, and no `Pets.get` under a `transformSpec`\n * that drops `/pets/{id}` (#567). Without `--ir` — a script run by hand —\n * `--spec` is parsed bare, so the operations are the document's as written.\n */\nexport async function loadSmokeSpec(args: { spec: string; ir?: string }): Promise<ApiSpec> {\n  if (args.ir) return JSON.parse(readFileSync(args.ir, 'utf-8')) as ApiSpec;\n  return parseSpec(args.spec);\n}\n","/**\n * Spec-only baseline generator.\n *\n * Generates expected request structure from the OpenAPI spec alone — no live\n * API needed. Produces a SmokeResults file that the diff tool can compare\n * against SDK smoke test output for offline CRITICAL-level verification.\n *\n * Usage:\n *   OPENAPI_SPEC_PATH=path/to/spec.yaml npm run smoke:baseline\n *   npx tsx scripts/smoke/baseline.ts --spec path/to/spec.yaml [--ir path/to/ir.json]\n *\n * `oagen verify` runs this script with `--ir`: the IR it parsed `--spec` to\n * with the config's settings, as `generate` parses it, so the baseline lists\n * the operations `generate` reads rather than those of a bare parse (see\n * `loadSmokeSpec`, #567). Run by hand without `--ir`, it parses `--spec` bare.\n */\n\nimport { writeFileSync } from 'node:fs';\nimport {\n  planOperations,\n  generatePayload,\n  generateQueryParams,\n  resolvePath,\n  parseCliArgs,\n  loadSmokeConfig,\n  loadSmokeSpec,\n  type CapturedExchange,\n  type SmokeResults,\n} from './shared.js';\n\nasync function main() {\n  const args = parseCliArgs();\n  loadSmokeConfig(args.smokeConfig);\n\n  console.log(args.ir ? 'Reading the IR verify parsed...' : 'Parsing spec...');\n  const spec = await loadSmokeSpec(args);\n  console.log(`Spec: ${spec.name} v${spec.version}`);\n\n  const groups = planOperations(spec);\n  const exchanges: CapturedExchange[] = [];\n\n  for (const group of groups) {\n    for (const planned of group.operations) {\n      const op = planned.operation;\n      const operationId = `${group.service}.${op.name}`;\n\n      // Build path with placeholder IDs for path params\n      const placeholderParams: Record<string, string> = {};\n      for (const p of op.pathParams) {\n        placeholderParams[p.name] = '<ID>';\n      }\n      const path = resolvePath(op, placeholderParams);\n\n      const queryParams = generateQueryParams(op, spec);\n      const body = generatePayload(op, spec);\n\n      // The declared primary success status; 0 when the operation declares\n      // no 2xx or 3xx response, as a status the document does not describe\n      // cannot be predicted. Nothing is guessed from the HTTP method.\n      const status = op.responseStatusCode ?? 0;\n\n      exchanges.push({\n        operationId,\n        service: group.service,\n        operationName: op.name,\n        request: {\n          method: op.httpMethod.toUpperCase(),\n          path,\n          queryParams,\n          body,\n        },\n        response: {\n          status,\n          body: null,\n        },\n        outcome: 'success',\n        durationMs: 0,\n      });\n    }\n  }\n\n  const results: SmokeResults = {\n    source: 'spec-baseline',\n    timestamp: new Date().toISOString(),\n    specVersion: spec.version,\n    exchanges,\n  };\n\n  writeFileSync('smoke-results-spec-baseline.json', JSON.stringify(results, null, 2));\n\n  console.log(`\\nGenerated ${exchanges.length} operations from spec`);\n  console.log('Written to smoke-results-spec-baseline.json');\n}\n\nmain().catch((err) => {\n  console.error('Baseline generation failed:', err);\n  process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqLA,SAAgB,qBAAkC;CAChD,OAAO;EACL,OAAO;GACL,sBAAsB;IAAC;IAAK;IAAK;IAAK;IAAK;GAAG;GAC9C,YAAY;GACZ,wBAAwB;GACxB,gBAAgB;GAChB,SAAS;IACP,cAAc;IACd,YAAY;IACZ,UAAU;IACV,cAAc;GAChB;EACF;EACA,QAAQ;GACN,eAAe;IACb,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;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