# IR Type System Reference

Source: `src/ir/types.ts`, `src/ir/sdk-behavior.ts`

The intermediate representation (IR) is the contract between the parser and all language emitters. It uses plain TypeScript interfaces (no classes) with a discriminated union type system.

## Top-Level: ApiSpec

```typescript
interface ServerVariable {
  default: string; // Fills the placeholder when nothing else is chosen; OpenAPI requires it
  enum?: string[]; // The values the variable may take; present only when declared (and non-empty)
  description?: string;
}

interface ServerEntry {
  url: string; // As written, placeholders included: https://{region}.api.example.com
  description?: string;
  variables?: Record<string, ServerVariable>; // Keyed by placeholder name; present only when declared
}

interface ApiSpec {
  name: string; // From info.title
  version: string; // From info.version
  description?: string; // From info.description
  externalDocs?: ExternalDocs; // The document's top-level externalDocs, when usable
  baseUrl: string; // servers[0].url with each variable's default filled in
  servers?: ServerEntry[]; // The document's servers; every operation inherits them unless it carries its own
  services: Service[]; // Grouped operations
  webhooks?: Webhook[]; // Top-level `webhooks` map (OpenAPI 3.1); absent when the document has none
  models: Model[]; // Schema objects
  enums: Enum[]; // String enums
  auth?: AuthScheme[]; // Authentication schemes
  security?: SecurityRequirementSet[]; // Document-level default requirements (see Operation.security)
  sdk: SdkBehavior; // Runtime policies (retry, errors, telemetry, etc.)
}
```

The `servers` array contains the document-level server entries from the OpenAPI spec — the ones every operation uses unless it carries `servers` of its own (see "Operation-level servers" below). `baseUrl` is always the first document server's URL, resolved: each `{name}` placeholder is replaced by that variable's `default`, so a client built on `baseUrl` requests `https://eu.api.example.com/v1`, not `https://{region}.api.example.com/v1`.

**Server variables.** `ServerEntry.url` keeps the template as written and `variables` carries what the document declares for it (same shape in OpenAPI 3.0 and 3.1), so an emitter can offer the choice — an environment or region picker — rather than only the default. There is no `resolvedUrl` on `ServerEntry`: `resolveServerUrl(server)` from `src/ir/server-url.ts` (exported from the package) returns `{ url, unresolved }` for any entry, which is exactly how the parser produced `baseUrl`. It is plain string scanning: a variable may appear more than once, the substituted value is not scanned again, and no pattern is built from the variable names. `serverUrlPlaceholders(url)` (same module, also exported) lists the placeholder names a template references, in order of first appearance, by the same scan; a declared variable not in that list is one the template never uses, which the differ treats as unable to move any resolved URL (see the servers paragraph under [`oagen diff`](../cli.md#oagen-diff)) and an emitter can leave out of a picker.

**Comparing server URLs.** Wherever the parser or the differ asks whether two server URLs are the same — a template or a resolved URL — it compares their RFC 3986 form, `normalizeServerUrl(url)` from the same module (exported from the package): the scheme and the host lower-cased, a port that is empty or the scheme's default (`80` for `http` and `ws`, `443` for `https` and `wss`) dropped, a wholly literal authority with no path given the path `/`, and a percent-encoded octet upper-cased or, when it encodes an unreserved character (a letter, a digit, `-`, `.`, `_`, `~`), decoded. The path, query and fragment keep their case and every other character, so `/v1` and `/V1`, or `/v1` and `/v1/`, stay different; dot-segments are not removed. A `{name}` placeholder is kept exactly as written wherever it sits, so a variable name is never folded and a template is never the URL it resolves to. A placeholder's value may carry any delimiter — a `@` that makes the text before it in the authority a username, a `:` and a port, a `/` and a path, a `://` and a whole URL — so nothing from the first placeholder on is folded, and a part is folded only when it is complete before that point: the scheme when its `:` comes first, the authority when its end (`/`, `?`, `#` or the end of the template) comes first. `HTTPS://API.example.com/{version}` is `https://api.example.com/{version}` and `HTTPS://API.example.com{basePath}` is `https://API.example.com{basePath}`, while `https://api.example.com{basePath}` and `https://api.example.com{basePath}/`, `https://{host}:443/v2` and `https://{host}/v2`, `https://USER{suffix}/v1` and `https://user{suffix}/v1` (a `suffix` of `@api.example.com` makes `USER` a username), or `{prefix}://api.example.com` and `{prefix}://api.example.com/` (a `prefix` of `https://gateway.example.com/path` makes the rest a path) stay two servers. From the first placeholder on not even percent-encoding is folded, and neither is it in an authority the placeholder sits in: a value may put the text in a scheme or a port, where `%` has no meaning (`{scheme}%73://notes.example.com` and `{scheme}s://notes.example.com`, or `https://api.example.com:4{port}` and `https://api.example.com:%34{port}`, stay two servers), or end in a `%` that joins with the text after it into another octet (`https://{host}/{x}7e` and `https://{host}/{x}%37e` stay two servers); a complete octet before the first placeholder in a path, query or fragment still folds. A relative reference with no scheme keeps every port. Every folding thus applies to text whose part and bytes no variable value can change, so two templates read as one resolve to one URL under every value of their variables. Not folded at all: dot-segments (`/v1/../v2` is compared as written) and internationalised host names (`https://bücher.example.com` and `https://xn--bcher-kva.example.com` are two servers). The IR never stores this form: `ServerEntry.url` and `baseUrl` stay as written.

The parser checks every server, not only the first, and reports each problem once with an `[oagen] Warning:` that names where the list sits (the document, a path item, an operation): a variable without a usable `default` is omitted from `variables` (the IR requires one) and its placeholder stays in the URL; a placeholder that names no declared variable stays in the URL; a `default` outside the variable's `enum` is kept as written. A declared variable the URL never uses is kept without comment. `default` and `enum` entries are strings; a number or boolean (YAML reads `default: 8443` as a number) is carried as its text. `variables`, `enum` and `description` are absent, not `undefined`, when the document does not declare them.

**Operation-level servers.** A Path Item and an Operation can declare `servers` of their own, and OpenAPI gives the operation's precedence over the Path Item's, which takes precedence over the document's. `Operation.servers` carries the winning list — the same `ServerEntry` shape, variables included, normalised by the same code as the document's, so `resolveServerUrl` works on it too — and only when it differs from `ApiSpec.servers`: an operation that declares nothing at either level, or whose winning list restates the document's, has no `servers` key and inherits. "Differs" is structural, by `serverListsEqual` (exported from the package): the two lists must have the same length and, position by position, the same `url` — in its RFC 3986 form, so an operation that restates the document's `https://api.example.com` as `https://API.example.com`, `https://api.example.com:443` or `https://api.example.com/` inherits (see "Comparing server URLs" above; that form folds nothing a placeholder's value could change, so two templates it reads as one resolve to one URL under every value of their variables, and `serverListsEqual` checks that value by value all the same — the defaults, then each enum value of each variable with the others at their defaults) — and the same `description` and `variables` (same names, each with the same `default`, `enum` in the same order, and `description`, all as written); a different description alone is a difference. The one exception is OpenAPI's default server: a list that is empty and one that holds nothing but `/` both mean it — `isDefaultServerList` (exported from the package), the entry's description and variables aside, since `/` references no variable and one declared on it changes nothing — and an operation whose list means it under a document whose list means it too inherits, so one that writes `/` out under a document that declares no servers inherits. A list with any other entry is compared as written, `/` entries included, because position decides the default host. Precedence is applied before the comparison, so an operation that restates the document's servers under a Path Item that diverges inherits. To find where a request goes, take `op.servers ?? spec.servers`; `baseUrl` is always the document's first server, resolved, whatever any operation declares.

Edge cases: `servers: []` at path or operation level is treated as absent — OpenAPI defines an empty list only at the document level (where it means `/`), not as an override — so the operation falls through to the next level; the same goes for a list whose entries are all unusable (not an object, no `url`, or a blank `url`), while the usable entries of a mixed list are kept. A document with no `servers` (or `servers: []`) means OpenAPI's default server, and so does one whose every server is `/` (description and variables aside), so an operation that declares any other usable list under either carries it, while one that writes `/` out under either inherits. `baseUrl` stays `''` for a document with no `servers` and is `/` for one that writes the default out; `ApiSpec.servers` is carried as written either way. A `paths` entry written as a `$ref` to another Path Item is resolved before any of this is read (see [Path Item references](#path-item-references)), so the referenced Path Item's `servers` are carried as an inline Path Item's are. The operations of one Path Item that inherit its list share the same array.

The differ reports a change as `serversChanged` on an `operation-modified` change, with `serverChanges` beside it: the changes the document-level diff reports for the same edit (`base-url-changed`, `server-added`, `server-removed`, `server-modified` with its `variableChanges`), each with its own classification, and the operation is breaking for its servers exactly when one of them is (#299). It judges where the operation is actually served from, `op.servers ?? spec.servers` on each side, not whether the field is set: a document that moves to where an operation already pointed (so the operation's override disappears) is not a change to that operation, and an operation that inherits on both sides is never reported here even when the document's own list moved — that is the document-level diff's. The comparison is the document-level diff itself (`diffServers`) rather than `serverListsEqual`, with each effective list read as a document whose `baseUrl` is its first entry resolved: the two lists are matched as multisets on `url` template plus variables (names, defaults, enum values as a set), so position, `description` on a server or a variable, and enum order do not count; a reorder counts only when it moves the first entry's resolved URL, the operation's default host. Templates and resolved URLs are compared in their RFC 3986 form (see "Comparing server URLs" above), so a host that only changed case, a default port written or dropped, or a `/` added after a bare authority does not count either. Any other difference counts, classified as it is for the document (see the servers paragraph and tables under [`oagen diff`](../cli.md#oagen-diff)): an entry removed, the first entry's resolved URL moved or gone, and a referenced variable removed, its default changed so that a resolved URL moves, an enum put on it or a value taken off it are breaking; an entry added, a first entry appearing where there was none, a variable added, an enum lifted or a value added to it, a default changed that moves no resolved URL in its RFC 3986 form whatever values a caller picks for the other variables (a host that only changed case), and any change to a variable the template never references are additive. OpenAPI's default server is one list here too: an operation served from `/` written out and one served from a document that declares nothing are served from the same place. A webhook carries no `servers` in the IR, so a `webhook-modified` change has no such flag.

`security` is the document-level `security` list, in the same shape as `Operation.security`; every operation that declares no `security` of its own inherits it. It is `undefined` when the document declares none. The differ reports it differing between two documents as one `security-changed` change, with `oldSecurity`/`newSecurity` (`[]` for none); see the security paragraph under [Service & Operation](#service--operation) for how the lists are compared and classified.

`webhooks` is the document's top-level `webhooks` map (OpenAPI 3.1) as a list of `Webhook`, in document order; see [Webhook](#webhook). The key is omitted — not set to an empty list — when the document declares none, so the IR of such a document is unchanged.

### ExternalDocs

```typescript
interface ExternalDocs {
  url: string; // Exactly as written in the document
  description?: string; // Only when it has non-whitespace content
}
```

An OpenAPI External Documentation Object — the document's way of linking to fuller documentation — carried on `ApiSpec` (the top-level `externalDocs`), `Service` (from the document tag, see below), `Operation`, `Webhook` (its operation's own, read as `Operation`'s is), `Model`, `Field`, `Parameter`, `ResponseHeader` and `Enum`, so an emitter can add it to a doc comment (a JSDoc `@see`, say). The key is present only when the document declares an entry with a non-blank `url`: a non-object, a missing or blank `url`, is dropped — silently, the way a malformed document tag is, since the parser ignored `externalDocs` entirely before and a malformed value must keep parsing. `url` is kept verbatim. OpenAPI allows it to be relative to the document's own location, which the parser does not know, so it is neither resolved nor rewritten, and `expandDocUrls` leaves it alone too; `expandDocUrls` does expand relative links inside `description`, which is CommonMark like every other description it walks. `description` is present only when it has non-whitespace content and is kept verbatim otherwise.

A `Model` built from an inline schema — a request body, a response, a `oneOf` variant, an object nested in a component field, array items, an `allOf` merge, a discriminated `allOf` + `oneOf` variant — carries the `externalDocs` of the schema it was built from. A wrapper the parser collapses or merges — a nullable `oneOf`/`anyOf` or `type: [..., "null"]`, a single-member `allOf`, an `allOf` response, field or nested-field merge — is the schema the document wrote, so the model built from what it unwraps or merges to carries the wrapper's link; a member's own stays on that member (a `$ref` member's on its component model), and a collapsed branch or member keeps its own link only when the wrapper has none. A collapsed wrapper's `description`, `example`, `examples` and `x-*` keys ride onto the branch or member by the same rule and at the same step (`withWrapperDocs`, see [Extensions](#extensions)), nested wrappers composing outermost-first; an `allOf` merge carries the wrapper layer's `description` with its link and keys onto the merged model, at every site alike (see Inline `allOf`; #604: a success body's merge left the text off). Every later pass that keeps, renames or merges models preserves the link; when `collapseJsonSuffixModels` folds `PetJson` into `Pet`, `Pet` keeps its own link as it keeps its own description, and takes `PetJson`'s only when it has none, and its `x-*` keys by the same rule (see [Extensions](#extensions)).

A Schema Object that does not become a model of its own keeps its link too. `Field.externalDocs` is the property schema's own, read like `description`: for a `$ref` with an `externalDocs` sibling (legal in OAS 3.1) the field carries the sibling's link while the referenced model keeps its own, and a bare `$ref` gives the field none — except a bare `$ref` to an array or primitive component, which has no model to keep the link, so the field takes it as it takes the component's `example` (see Array components and Primitive components), or to an alias of an enum component, whose own link the field takes while the enum keeps its own (see Enum). Every path that builds a field reads it: component properties, `allOf` merges, flattened `oneOf` variants, inline request bodies and responses, nested inline objects, list-envelope companions and header models. It is documentation, not shape: where two inline models are folded into one by structural agreement (`modelFingerprint`, the header-model registry, the same-named merge passes), two fields that differ only in their link are one shape, as two that differ only in `description` are. `Parameter.externalDocs` and `ResponseHeader.externalDocs` are read from the schema, as described under each. An `Enum` carries its schema's: a component enum's own, and — for an enum lifted into `spec.enums` from an inline schema on a property, parameter, response header, request body, response body (primary, secondary-media-type, error or fallback) or webhook parameter or payload, including array items, `oneOf` variants and a `oneOf` of string consts collapsed into one enum — that schema's. A nullable wrapper or single-member `allOf` the parser collapses carries its link onto the lifted enum by the rule above for models (the wrapper's wins; the branch's only when the wrapper has none). When several inline schemas lift to one enum name, the first lifted gives the link, as it gives the values. The link lives on the `Enum`, not on the field's or parameter's `EnumRef`.

### Extensions

```typescript
type Extensions = Record<string, unknown>;
```

The specification extensions (`x-*` keys) an OpenAPI object declares, each under the key as written with its value verbatim — a string, a boolean, a number, `null`, an array or an object, nested values included, the document's own value rather than a copy — in document order. Carried as `extensions` on `Operation`, `Model`, `Field` and `Enum`, present only when at least one key remains after the ones below are left out, so an emitter can read the keys it knows (`x-idempotent: true` on a `POST` that is safe to repeat, `x-since` for an `@since` tag) without the parser knowing each one. No other node carries one: the `x-*` keys of a Parameter Object, a Header Object, a Request Body or Response Object, a Path Item Object, a webhook's Operation Object, a tag, a server or the document are not read.

**Consumed keys.** A key the parser already reads into a typed field is not repeated in `extensions`. On an Operation Object: `x-pagination` (`pagination`), `x-oagen-async` (`async`), `x-mutually-exclusive-parameter-groups` and `x-mutually-exclusive-body-groups` (`parameterGroups`). On a Schema Object: `x-enum-descriptions` and `x-enumDescriptions` (each `EnumValue.description`). The sets are `OPERATION_CONSUMED_EXTENSIONS` and `SCHEMA_CONSUMED_EXTENSIONS` in `src/parser/extensions.ts`. A key is consumed by the object it is read from: `x-mutually-exclusive-body-groups` is read from the Operation Object only, so the same key written on a request body schema is carried on that schema's model.

**Source per node.** `Operation.extensions` is the Operation Object's own keys. `Model.extensions` is the keys of the schema the model was built from — a component's own, or the inline schema's for a request body, a response, a `oneOf` variant (each variant model carries its own variant's keys), an object nested in a field, array items; an `allOf` wrapper's own keys, a member's staying on that member and a `$ref` member's on its component, for a component `allOf`, an inline `allOf` merged into one model and an `allOf` response alike; a discriminated `oneOf` body merged into one model carries the wrapper's keys, not a variant's; a discriminated `allOf` + `oneOf` component's variant models carry each variant's own. `Field.extensions` is the field schema's own keys, read like `constraints`: keys written beside a `$ref` (OAS 3.1) are the field's, a bare `$ref` yields none — the referenced model, union or enum carries its own — unless it names an array or primitive component, whose keys the field then carries under its own, the field's winning per key, as it carries that component's `description` (see Array components and Primitive components), or an alias of an enum component, whose own keys the field carries the same way, the enum keeping its own (see Enum). A list envelope's `envelopeFields` carry theirs the same way.

**Several declarations of one property.** A property several `allOf` members always declare is typed by the first always-applying declaration that declares a type, its extensions included; a later typing declaration adds to it only where the two are conjoined, as JSON Schema applies both — two inline objects, any two declarations that each describe an object (an inline object, a `$ref` to an object component, or an `allOf` that reaches one — `describesObject` — which become the `allOf` of both: `result: { $ref: Meta }` beside `result: { allOf: [{ properties: { items } }] }` is a `Meta` that also has `items`, as it is beside `result: { properties: { items } }` and beside `result: { $ref: Listing }`, in either member order, with `nullable: true`, `type: 'object'` or a `description` written beside the inner `allOf` or not; the conjunction admits `null` exactly when every declaration does, as JSON Schema applies both — `Meta: { type: ['object', 'null'], … }` (OAS 3.0: `type: 'object', nullable: true`) beside `result: { type: ['object', 'null'], allOf: [{ properties: { items } }] }`, beside a second nullable `$ref` or beside a nullable inline object is `PetPageResult | null`, and beside a declaration that rejects `null` is `PetPageResult`, two inline objects alike (#653 review); the conjunction writes its `type` — two inline objects' the names both admit beside `object`, the intersection of their type lists (`type: ['object', 'string']` twice stays `['object', 'string']`, so a string is still an instance; `['object', 'string']` beside `['object', 'integer']` is `object`; `['object', 'number']` beside `['object', 'integer']` is `['object', 'integer']`, since `number` admits an integer), an `allOf`'s the names both declarations admit when `object` is among them, else `object` (a `$ref` admits what its component does, an `allOf` what every member that names a type does, and a declaration that names none constrains none: `result: { type: ['object', 'string'], allOf: [{ properties: { a } }] }` beside `result: { allOf: [{ properties: { b } }] }` is `['object', 'string']`, a `PetPageResult` with `a` and `b` or a string, in either member order, and beside `result: { $ref: Meta }` it is `object`, since `Meta` admits no string; where a member would type one of those names itself — a `$ref` to a component typed `['object', 'string']`, an inline object typed so — the pair keeps the first as written, its alternatives included) — with `null` beside it exactly when admitted, so a part's rejection of `null` (`{ type: 'object', allOf: [{ $ref: A }] }`) is kept on the conjunction and a third nullable declaration cannot restore it, in every member order; #432, #571; the conjunction's members are the parts of both — a declaration that is a bare `allOf`, with nothing beside it but the lifted keywords, a `required` the conjunction hoists, `type: 'object'` or a nullable spelling, a `title` or another annotation that constrains nothing, is spliced open into its members, so `result: { allOf: [{ $ref: A }] }` beside `result: { allOf: [{ $ref: B }] }` is `{ allOf: [{ $ref: A }, { $ref: B }] }`, which the readers type where the `allOf` of the two wrappers as written is `unknown` to them — and a part the first already has, the same object or a `$ref` to a component it names, adds nothing, so two `$ref`s to one component, or a `$ref` beside its own wrapper, keep the first (a first of several parts the readers would type non-null where every part admits `null` is rebuilt as the conjunction, so the admission is the same in either order); a wrapper spliced open inside a declaration keeps its limits and documentation as a member that declares no type, which the readers conjoin onto the schema as the wrapper's own keywords (`{ allOf: [{ allOf: [{ $ref: A }], minProperties: 2 }] }` beside an inline object keeps `minProperties: 2`, the stricter bound winning); a pair whose members the readers would not all read — one that is no `$ref`, no inline object member and no annotating or limiting member, such as an `allOf` of `$ref`s under a `discriminator` or `additionalProperties` — keeps the first as before, rather than lose a part to the reference reading (#653 review); a `$ref` to a component that dispatches a union — `Choice: { allOf: [{ $ref: Base }, { oneOf: [{ $ref: Cat }, { $ref: Dog }] }], discriminator }` — describes an object too, and `result: { $ref: Choice }` beside `result: { $ref: Meta }` is read as `result: { allOf: [{ $ref: Choice }, { $ref: Meta }] }` written by hand is, a model of the fields both share with the union left to `Choice`, see Inline `allOf` and #429), two arrays (see Inline `allOf`) — the later's keys then over the earlier's, and a typeless one fills in only the keys the typing one leaves unset, its `items` — typeless too, since `items: { description }` declares no type (`declaresType`) — only the keys the typing one's items leave unset (`combineDeclarations`: `data: { type: 'array', items: { $ref: Pet } }` beside `data: { items: { description: 'A pet' } }` is a `Pet[]` whose items carry the text, in either order, #431; two typeless declarations merge first, their `items` with them, so `{ description: 'Tags' }`, `{ items: { description: 'A tag' } }` and then the array give what the array first gives; and the same two declarations get the same object throughout the document, so a reader that guards by identity meets a conjunction once however often the merges build it, through whatever wrapper each strips from it (`sourceDeclaration`); #551, #566) — the precedence every keyword follows. A property only `oneOf`/`anyOf` variants declare carries exactly the keys every declaration as written agrees on, value for value — one reading, `agreedExtensions`, at every site that rebuilds or widens a property from several declarations without changing which declaration types it: `unionOfDeclarations` for an inline `allOf`; `declaredComponentProperty` for a component (a bare `oneOf` component, whose field is typed from the first branch, or a union member of a composed component, whose field is the union of the branches' declarations as the inline merge builds it, `unionOfDeclarations`); `mergeBranchPropertySchemas` for the nested sub-branches of a dispatched component `allOf` + `oneOf` variant, where boolean or string consts widen to a plain boolean or string; and `flattenDiscriminatedUnionBody` for a discriminated inline request body, whose discriminator is rebuilt as an enum of the pinned consts and whose other properties are typed from the first variant that declares them — whether the declarations share one shape or become a union: a key any declaration leaves unset or writes another value for is nobody's, and a declaration that repeats an earlier shape still has its say — three variants writing `x-since` as `1`, `2` and `1` leave it off. In an inline `allOf`, the lifted keywords (`description`, `readOnly`, `default`, the limits, …) are read by the same agreement whether the declarations share one shape or become a union, and make no shape of their own — at a declaration's top level, and inside its array items and map values, where `ArrayType` and `MapType` carry none of them: two `type: 'string'` declarations that differ only in them are one `string` field carrying what both write (#397), two `string[]` declarations whose items differ only in `readOnly` or `maxLength` one `string[]`, two maps whose values do one map. Inside a union of shapes, each shape is its first declaration as written, except that it is deprecated only when every declaration of the shape is: a deprecated object declaration beside a live one of its shape and an integer types one live variant model whichever object comes first, and a `const: cat` deprecated on one branch only is a live `CAT` member, so `diffSpecs` between the two orders reports nothing. The discriminator `flattenDiscriminatedUnionBody` rebuilds reads its `description` by the same agreement: the enum and the field it types carry the text every variant's declaration writes, and each value the text of the declaration that pins it — the first's, for a value two variants pin — as a `oneOf` of string consts documents its members, so variants that each document their own const leave the enum and the field without one (#446). Each value is deprecated as such a `oneOf` deprecates its members, when the declaration that pins it says `deprecated: true` — for a value several variants pin, only when every one does, as inside a union of shapes — and the field stays live (#501). `Enum.extensions` is the keys of the schema that declares the members: a component enum's own, or, for an enum lifted from an inline schema, that schema's — the field the schema types carries the same keys when the enum schema is the field's own schema; under a nullable `oneOf`/`anyOf` or single-member `allOf` wrapper the parser collapses, the field carries the wrapper's keys alone and the branch's stay on the enum (see Collapsed wrappers) — read as the enum's `description` and `externalDocs` are, through `collectInlineEnumFromRef`; when several inline schemas lift to one name, the first lifted gives the keys, as it gives the values.

**Collapsed wrappers.** A nullable `oneOf`/`anyOf` or single-member `allOf` wrapper the parser collapses carries its documentation layer onto what it unwraps to by one rule, `withWrapperDocs`, applied at every collapse step — by the type builder (`schemaToTypeRef`), by the model extractors (`unwrapNullableField` through `unwrapNullableSchema`, `unwrappedAllOfMember`) and by the response path — so the model built from the branch, the enum lifted from it and the field the wrapper types document themselves alike. The layer is every keyword that documents a schema without shaping it, the schema-side counterpart of `FIELD_DOC_KEYS`: `description` (when it has content), `externalDocs` (when usable), `example` (when the key is present), `examples` (when non-empty) and the `x-*` keys one by one, the consumed ones left out. The wrapper's value wins wherever both declare one and the branch keeps its own where the wrapper has none. Nested wrappers compose outermost-first: an outer wrapper's keys land on the inner wrapper before the inner wrapper's land on the branch, so with `x-since` on the outer and `x-owner` on the inner the branch carries both and an `x-since` on both is the outer's. `oneOf: [{ enum: [...] }, { type: "null" }]` and `type: ["string", "null"]` give the same enum the same keys. A `oneOf`/`anyOf` of consts read as an enum is no wrapper, even when one const sits beside `null` and an `enum:` list makes it an enum: the enum is decided before the nullable collapse, by the type builder and the model side alike (`nullableUnionBranch`, so `unwrapNullableSchema` and `unwrapCollapsedWrappers` stop there), and is built from the union itself, so the union's own documentation is the enum's and a variant's is its member's alone (#535). The field the wrapper types carries the outermost wrapper's keys alone, since that wrapper is its schema. An `allOf` member that declares no type of its own — no `type`, `$ref`, `properties`, `enum`, `const`, composition or map keyword, and no `items` that declare one themselves (`declaresType`), so a `{ description }`, `{ deprecated: true }`, `{ readOnly: true }`, `{ example }`, `{ maxLength: 3 }`, `{ 'x-internal': true }`, `{ items: { description: "An owner." } }` — is part of that wrapper, not a branch (`annotatingAllOfMembers`): its keys are the wrapper's where the wrapper declares none, the first such member's first (`allOfWrapperLayer`), so `allOf: [{ type: "string", enum: [...] }, { description: "The kind of pet." }]` is the enum `allOf: [{ type: "string", enum: [...] }], description: "The kind of pet."` is, with that text on the enum and on the field; its `items` document the typing member's items (`annotatedTypingMember`: `allOf: [{ type: "array", items: { $ref: Owner } }, { items: { description: "An owner." } }]` is `Owner[]`, the text on its items, as `{ type: "array", items: { $ref: Owner } }` beside `{ items: { description } }` under one property name is, #431 — not two typing members read as neither); the model built from the wrapper itself — a component `allOf` (`extractAllOfModel`) or an inline merge (`mergeAllOfMembers`) — carries the layer's `description`, `externalDocs`, `deprecated` and `x-*` keys, so `Owner: { allOf: [{ $ref: Base }, { type: "object", properties: { name } }, { description: "An owner.", deprecated: true }] }` is a deprecated `Owner` described "An owner." exactly as the same keys beside the `allOf` make it, and `oagen diff` between the two spellings reports nothing (a typing member's own keys stay on that member, a `$ref` member's on its component); a component that writes one typing `oneOf`/`anyOf` beside an `allOf` whose members only annotate or limit it — `New: { allOf: [{ description: "A new pet." }], oneOf: [{ $ref: Pet }, { $ref: Toy }] }`, `allOf: [{ minProperties: 1 }]`, `allOf: []` — is not composed at all: such an `allOf` does not type the schema (`allOfTypesSchema`, the one predicate `foldSiblingUnions` and `componentAllOfMembers` share), so the union is what types it, and the component is the named union `New` of `Pet` and `Toy` that `{ description: "A new pet.", oneOf: [...] }` is — described by the member, its limits conjoined onto the model's `constraints` — exactly as the same schema is the union inline, as a `$ref` member of a composed model and as a variant of another union alike, and `oagen diff` between the two spellings reports nothing (#613: any `allOf` made the component composed, and the union was flattened into `New { name?, toy? }`, the variants' properties as optional fields with no variants); a union of string consts beside such an `allOf`, or an `enum:` list, is the enum it is written alone, the layer's text and keys on it (see Enum); a component that writes both a typing `oneOf` and a typing `anyOf` beside such an `allOf` stays composed, each union one more member, since a named union carries one axis, and a `required` list such a member writes (`allOf: [{ required: ["id"] }]` beside the union) is the member's own, read wherever the member is read, as are its limits, which bind every variant model a dispatching member's union builds (`allOf: [{ maxProperties: 3 }]` beside `oneOf: [cat, dog]` puts `maxProperties` on each variant's `constraints`, as `maxProperties: 3` beside the `oneOf` does); a nullable union beside such an `allOf` collapses as it does with no `allOf` (`nullableAxisBranch`) — on a field, as a member of a composed model, whose one variant then always applies, and as an alias of an array, primitive or enum component — so `{ allOf: [{ description: "A new pet." }], oneOf: [{ $ref: Pet }, { type: "null" }] }` is `nullable<Pet>` on a field as `{ description: "A new pet.", oneOf: [{ $ref: Pet }, { type: "null" }] }` is, while a request body written so stays the union of one variant it was (the body builder's own wrapper test, pinned at the #535 review) and the branch's model keeps the wrapper's own keys, not the members'; and the field reads its `description`, `externalDocs`, `deprecated`, `readOnly`, `writeOnly`, `default`, `example`, `examples` and `x-*` keys from such members whatever the other members are — beside a `$ref` (`allOf: [{ $ref: Kind }, { deprecated: true }]` is a deprecated `Kind` field), beside the one typing member, or beside a merge — as it conjoins their limits (#555), the field's own `pattern` and `multipleOf` standing where a member's conflict, as `extractConstraints` reads the schema (`{ type: "string", pattern: "^a", allOf: [{ pattern: "b$" }] }` is limited to `^a`); a parameter reads the same keys it carries from them, and a response header its `deprecated` and `externalDocs` (`allOfWrapperLayer`; #605: the header read the flag from such members but the link from the schema's own keys alone), each by its own rule below. A single-member `oneOf`/`anyOf` is not collapsed — it stays a union of one variant — but the type builder types that variant by the same rule, so `oneOf: [{ enum: [...] }]` gives its enum the keys `allOf: [{ enum: [...] }]` does; the model built from an object variant carries its own, as every variant's model does (#445).

**Not shape.** Extensions never decide whether two schemas are one model or one enum: `schemaShapeKey` skips `x-*` keywords, `modelAdmits`, `fieldAdmits`, `modelFingerprint` and the differ's `sameShape` leave `extensions` out, the list-envelope and parameter-group fingerprints never read it, and two inline enums are shared on their members alone. An inline schema that differs from a model only in its extensions folds onto that model, which keeps its own keys; the folded copy's are dropped with it. A `<Name>Json` component folded into `<Name>` (`collapseJsonSuffixModels`) is no copy: `<Name>` keeps its own keys, as it keeps its own link, and takes the `…Json` model's only when it has none, so the keys of a schema the document uses as a body are not lost and `oagen diff` reports a change to them (`x-since` moving on a folded `PetJson` is an additive `extensionsChanged` on `Pet`). The differ reports a change to a node's extensions as additive — `extensionsChanged: true` with `oldExtensions`/`newExtensions` on an `operation-modified`, `model-modified` or `enum-modified` change, a `field-extensions-changed` entry in a model's `fieldChanges` or, for a list envelope's field that no model carries (`pagination.envelopeFields`, matched by name), in the operation's `envelopeFieldChanges`, each mirrored into `behaviorChanges` as `extensions-changed` — and never as a type change (see [docs/cli.md](../cli.md)). Every carrier of `extensions` has one such comparison site: operations, models, model fields, enums and envelope fields.

**Untrusted values.** Extension values come from the document unvalidated: an emitter that writes one into generated source must escape it as it escapes a `description`.

### SdkBehavior

Source: `src/ir/sdk-behavior.ts`

Language-agnostic runtime policies consumed by emitters via `ctx.spec.sdk`. Always populated by the parser with `defaultSdkBehavior()`. Override per-SDK via `oagen.config.ts`.

```typescript
interface SdkBehavior {
  retry: RetryPolicy; // Retry status codes, max attempts, backoff strategy
  errors: ErrorPolicy; // Status code → exception kind mapping, doc URL template
  telemetry: TelemetryPolicy; // Request metrics header, request ID header
  pagination: PaginationPolicy; // Auto-page delay
  idempotency: IdempotencyPolicy; // Idempotency header name, auto-generate for POST
  logging: LoggingPolicy; // Log events and levels
  userAgent: UserAgentPolicy; // SDK identifier template, AI agent detection
  requestGuard: RequestGuardPolicy; // Misplaced-options key detection
  timeout: TimeoutPolicy; // Default timeout, env var override
}
```

Use `defaultSdkBehavior()` for canonical defaults. Use `mergeSdkBehavior(overrides)` for partial overrides (arrays replace, objects merge recursively).

## TypeRef (discriminated union)

Every type in the IR is a `TypeRef`, discriminated on the `kind` field:

| Kind        | Interface       | Example                                                              |
| ----------- | --------------- | -------------------------------------------------------------------- |
| `primitive` | `PrimitiveType` | `{ kind: "primitive", type: "string" }`                              |
| `array`     | `ArrayType`     | `{ kind: "array", items: { kind: "primitive", type: "string" } }`    |
| `model`     | `ModelRef`      | `{ kind: "model", name: "Organization" }`                            |
| `enum`      | `EnumRef`       | `{ kind: "enum", name: "Status", values?: ["active", "inactive"] }`  |
| `union`     | `UnionType`     | `{ kind: "union", variants: [...], discriminator?: {...} }`          |
| `nullable`  | `NullableType`  | `{ kind: "nullable", inner: { kind: "primitive", type: "string" } }` |
| `literal`   | `LiteralType`   | `{ kind: "literal", value: "active" }`                               |
| `map`       | `MapType`       | `{ kind: "map", valueType: { kind: "primitive", type: "string" } }`  |

### Type constraints

Every `TypeRef` the parser builds from a schema it types in place — a `primitive`, `literal`, `array`, `map` or `union` — carries that schema's validation keywords as an optional `constraints?: Constraints` (#545), read exactly as a field's are (see Constraints below): the schema's own keywords conjoined with its `allOf` members' and, through a nullable wrapper, the wrapper's with its branch's — so `nullable` carries none of its own and its `inner` does — and, for a `$ref` to an array or primitive component, the component's and each alias's conjoined with whatever is written beside the reference, as `Field.constraints` conjoins them; for a JSON Pointer `$ref` deeper into a component (#539), the limits the schema it lands on carries on its own type, conjoined the same way with whatever is written beside the pointer once the site is settled (`resolveSchemaPointers`), so `{ $ref: '#/components/schemas/Owner/properties/code', maxLength: 3 }` to `{ type: string, pattern: '^own_', maxLength: 8 }` is `{ maxLength: 3, pattern: '^own_' }` and the bare pointer `{ maxLength: 8, pattern: '^own_' }`, on the field, the parameter and the type alike. A `model` or `enum` reference carries none: the model it names carries its own (`Model.constraints`), and what is written around such a `$ref` — a pointer to a property typed as a model included — stays the field's or parameter's. The key is absent when the schema declares no validation keyword.

So a field's or parameter's `constraints` equal those of its type (under its nullable wrapper) whenever the type can carry them — the field keeps its own copy so an emitter can read a value's limits without descending into its type — and the type carries them where no field could: an array's `items`, a union's variants, a map's values, a response header's type, a request or response body. A parameter reads its schema's limits exactly as a field does (`schemaConstraints` in `src/parser/schemas.ts`), level by level, so `{ type: string, pattern: '^a', allOf: [{ pattern: 'z$' }] }` is `{ pattern: '^a' }` on a query parameter, a field and their type alike (the schema's own keyword wins over an annotating member's, as `combineConstraints` keeps it), while a `$ref` to a model or enum component still merges the target's keywords underneath the parameter's own, as `Parameter.constraints` says. For the `petId` and `tagIds` of #545:

```yaml
petId:
  { anyOf: [{ type: string, pattern: "^pet_[0-9A-Z]{26}$" }, { type: string }] }
tagIds: { type: array, items: { type: string, pattern: "^tag_[0-9A-Z]{26}$" } }
```

```typescript
petId.type; // { kind: "union", compositionKind: "anyOf", variants: [{ kind: "primitive", type: "string", constraints: { pattern: "^pet_[0-9A-Z]{26}$" } }, { kind: "primitive", type: "string" }] }
tagIds.type; // { kind: "array", items: { kind: "primitive", type: "string", constraints: { pattern: "^tag_[0-9A-Z]{26}$" } } }
```

so an emitter can type `petId` as `` `pet_${string}` | (string & {}) `` and `tagIds` as ``Array<`tag_${string}`>``, document each variant's form, or check an item before sending it. A nested array carries each level's keywords where it sits: `{ type: array, minItems: 1, items: { type: array, uniqueItems: true, items: { type: string, pattern } } }` is `{ minItems: 1 }` on the array, `{ uniqueItems: true }` on its `items` and `{ pattern }` on their items. A `oneOf`/`anyOf` union carries what is written beside the keyword (`{ anyOf: [...], maxLength: 10 }` is `{ maxLength: 10 }` on the union), each variant its own. A union built from a type list (`{ type: [string, integer], maxLength: 20, minimum: 1 }`) carries the schema's keywords itself and its variants none: each variant is the same schema read as one of its types, so the limits are read from the union for whichever type the value takes — and so does the union a multi-type inline variant of a `oneOf` is typed as, on a named union and an inline one alike (`Shape: { oneOf: [{ type: [object, string], properties: { id }, maxLength: 5 }, { type: integer }] }` has `{ maxLength: 5 }` on the `union<ShapeWithId | string>` that is `Shape.variants[0]`). A property several variants of a merged `allOf` declare keeps on its items and values only the limits every declaration writes the same way, as the field itself keeps only the agreed keywords (`{ items: { type: string, pattern } }` beside `{ items: { type: string } }` is a plain `string[]`).

For `oagen diff`, a field's type's limits are shape as the field's own are when a renamed body is read through to its model (`sameShape`): a renamed model whose `tags` items differ in `pattern` alone is not the same shape, so the body is `retyped`, as it is when the `tags` field's `minItems` differs. A limit tightened or loosened on a field, a parameter, a response header, a model's own keywords or a named union's variant is reported, at every level the type carries one (`items.pattern`, `valueType.maxLength`, `variants[1].minimum`), as a `field-constraints-changed`, `param-constraints-changed`, `header-constraints-changed` or `variant-constraints-changed` entry or as `constraintsChanged` on the model, each naming every keyword that moved in `details` and breaking when a keyword was tightened on a request-facing site (#599; see **Constraints** under [`oagen diff`](../cli.md#oagen-diff) for the per-keyword and per-site rules). A limit on a body's type under one name, or on an inline body — a `maxLength` on a `text/plain` string, whether that is the body `requestBody` is read from or a secondary representation — is still no change the differ reports: a body typed in place has no flag to carry its limits.

### Primitive Formats

The `format` field on `PrimitiveType` carries additional type information:

| type      | format      | Semantic          |
| --------- | ----------- | ----------------- |
| `string`  | (none)      | Plain string      |
| `string`  | `date`      | ISO 8601 date     |
| `string`  | `date-time` | ISO 8601 datetime |
| `string`  | `uuid`      | UUID string       |
| `string`  | `binary`    | Binary data       |
| `integer` | (none)      | Integer           |
| `number`  | (none)      | Floating point    |
| `boolean` | (none)      | Boolean           |
| `unknown` | (none)      | Unknown/any type  |

### LiteralType

```typescript
interface LiteralType {
  kind: "literal";
  value: string | number | boolean | null;
  constraints?: Constraints; // What is written beside the const or single-member enum; see Type constraints
}
```

Represents a fixed value. The `null` variant maps to language-specific null literals.

### MapType

```typescript
interface MapType {
  kind: "map";
  valueType: TypeRef;
  keyType?: TypeRef; // Defaults to string when absent
  constraints?: Constraints; // The object schema's own minProperties / maxProperties / dependentRequired; the values' own are on valueType (see Type constraints)
}
```

The optional `keyType` allows non-string map keys (e.g., enum-keyed maps). When absent, emitters should assume `string` keys.

A map's value schema is typed the same way an array's items are: with the owning field's name and parent model. When the value is an inline object (or an array or `oneOf` of inline objects), the parser extracts it as a model named by the parent plus the singularized field name, e.g. `layers` on `CreateDrawingRequest` → `CreateDrawingRequestLayer`, matching `shapes` → `CreateDrawingRequestShape` for array items. `additionalProperties: {}` or `true` keeps the value type `unknown`. The singular form is taken only when no sibling property of the same object would itself mint that name — an inline object, an inline enum, an inline union (the names of its object variants and whatever its other variants mint, see below), or an array or map of such (a primitive `email` beside `emails` claims nothing); otherwise array items are `<Parent><Field>Item` (`DrawingLayersItem` beside a `layer` object with different fields) and map values `<Parent><Field>Value`; if a sibling claims that name too (a property `layers_item`), the fallback continues to `<Parent><Field>ArrayItem`, then `<Parent><Field>ArrayItem2`, and so on (`<Parent><Field>MemberValue`, `…MemberValue2` for maps), taking the first name no sibling mints. One deliberate exception: when the claiming sibling is an inline object structurally identical to the items or values (same properties, required, types, nested inline schemas and enum values; `description`, `title` and `example` ignored), both fields share one model under the singular name, since one type is right for both and a duplicate would only add noise; the split happens only once the shapes diverge. The choice reads sibling names and schema content only, so document order plays no part.

Inline object variants of a `oneOf`/`anyOf` are extracted as their own models. The first keeps the field's inline name (`DrawingShape`); later ones take a const-discriminator prefix when every variant pins one (`SquareDrawingShape`; a pin is read as UnionType's discriminator reads it, so `kind: { allOf: [{ const: 'square' }] }` prefixes as `kind: { const: 'square' }` does, #607). A variant with neither is named from its own content, so an SDK user can tell the variants apart and reordering them changes nothing but which one is first: its `title`, trimmed and PascalCased, as the same prefix form (`CircleDrawingShape`; a title the base name already starts with is not doubled, and a title an earlier variant already took is not reused); else the first property, in the variant's own order, that no other inline object variant of the union declares (`DrawingShapeWithSide`, `DrawingShapeWithRadius`); else, only when its property set adds nothing to another variant's, the position counter (`DrawingShape2`). Every candidate also steps around the inline names the parent's other properties mint, so a variant never overwrites another field's model: beside a `shape_with_side` object (`DrawingShapeWithSide`), the `{ side }` variant of `shape` takes the next candidate (`DrawingShape2`), and beside a `shape2` object the counter keeps counting (`DrawingShape3`); each sibling's names are read in isolation, so the choice depends on sibling names and content only. The same reservation is handed down to a union among a field's array items or map values. A `oneOf` without an explicit `discriminator:` whose every variant carries a `title` or is a `$ref` — its const read from the component it points at, or from the one model `$ref` a wrapper holds (#568) — and pins the same const property is the one shape named differently: its discriminator mapping has always named each titled variant by its title (`Circle`, `Square`) and a `$ref` variant by its component, so the extracted models carry those titles too, and the mapping is read from the same names (the titles are kept whenever every variant pins the property, two variants pinning one value included — the later falls back as a repeated title does — while the discriminator itself needs values that tell the variants apart, see UnionType, so such a union keeps its titles and carries none) — such a title is context-free and names one shape wherever it appears, as a component name would, so a second union beside it (at field level, or among a sibling array's items or map's values) that gives the same title a variant of the identical shape (same properties, required, types and nested schemas; `description`, `title` and `example` ignored — the rule array items already use to share a singular sibling's model) shares the model instead of stepping around it. A sibling that gives the same title a different shape reserves it, and because each side reads its siblings in isolation the decision is symmetric: when `Circle` is `{ radius }` on `shape` and `{ diameter }` on `marker`, both fall back to their context-qualified names (`CircleDrawingShape`, `CircleDrawingMarker`: the title as a prefix on the base, else a distinguishing property, else the counter) and neither keeps the bare `Circle`, with the mappings following; when the shapes are identical, both keep `Circle` and one model is emitted. The same holds at any depth of one root, not only between siblings: a title that two unions anywhere under the same root give different shapes — `Circle` as `{ radius }` on `shape` and as `{ diameter }` on `marker.shape` — is contested, decided once per document before any union is named, and every variant carrying it takes its context-qualified name (`CircleDrawingShape`, `CircleDrawingMarkerShape`), wherever in the root it sits and whichever is declared first, a later variant that repeats the title in its union included (`DrawingShapeWithDiameter` beside `CircleDrawingShape`, whose title prefix the first took); only the unions the parser types count, those reached through `properties`, `patternProperties`, `additionalProperties`, `items` and `allOf`/`oneOf`/`anyOf`, so a union under `not`, `if`/`then`/`else`, `$defs`/`definitions`, `dependentSchemas`, `contains`, `prefixItems`, `propertyNames`, `unevaluatedProperties` or any other keyword never becomes a model and contests no title; a union object one root holds in two places — nested under `shape` beside an earlier union that already claimed its title for that group, and again as `wrapper.marker`, where the title is a claim of its own — is read in each place, so its shape is compared with the earlier union's and the title contested when they differ; a title given one shape, or identical shapes, under a root is kept and shared. The component schemas are read as one root, since one pass collects their inline field models into one list and a named union's variants are already compared across every component; a request body, a response body, a response header, a parameter and a webhook payload are each a root of their own, and a title two such roots give different shapes is left to the passes that merge their models (the first owner keeps the name; a later shape is renamed or dropped with a warning). Outside the component schemas, an inline `allOf` merged into one model (`allOf: [{ $ref: Base }, { … }]`) is read as the model every extractor builds from it: its properties as the merge settles them, `Base`'s included (its own and its `allOf` chain's) and a property two members declare as the one declaration the merge keeps or conjoins from both (a `meta` both declare), so a title `Base.shape` and the inline member's `marker.shape` give different shapes is contested, and with the mark on `Base`'s own variants they are qualified wherever they appear (`CircleBaseShape`, beside `CircleGetDrawingResponseMarkerShape`); a declaration the merge drops (an inline `shape` beside `Base`'s, which types the field) and a union whose variants it flattens into the model's fields are no models and contest nothing, and a plain reference, a `$ref` under a variant and a union component's own variants are left to the components root. Each property is read once per root, a conjunction the merges build again from the same declarations included — the same two declarations combine into one object for the whole document, not only while a root's titles are walked (#566) — so `Note.reply` — which `Note`'s members declare as a `$ref` back to `Note` and as an inline object, and every merge of `Note` conjoins anew — ends the walk rather than looping on it (#531). Should a union variant still find its name taken by a model of another shape in the list it is extracted into, the extractor keeps the first model and warns that the variant's reference resolves to it, rather than dropping the variant silently; the two are compared with the nested models each builds (`deepModelFingerprint`), so an ordinary `circle` and a variant titled `Drawing circle` that both hold a `detail` object — `{ radius }` under one, `{ diameter }` under the other, both named `DrawingCircleDetail` — are two shapes, and the warning names the nested models that differ when the parents' own fields agree. A title that coincides with another field's context-dependent model name falls back the same way. When the union has no const discriminator and every variant carries a distinct title, the first variant takes its title too (`CircleDrawingShape` beside `SquareDrawingShape`) instead of being the only one left bare. The decision reads the variants' content only, and the union TypeRef and every extractor (component fields, request bodies, inline responses, array items, map values) make it through one function, so a reference always has a model behind it. A request body that is itself a `oneOf` of inline objects follows the same rule for its const-less variants (`CreateThingRequest`, `CreateThingRequestWithB`); a variant with a const string property is still named after it, and either kind steps around a name an earlier variant of the body already took (a variant titled `Foo` beside one pinning `kind: foo` gives `FooCreateThingRequest` and `FooCreateThingRequest2`). A response that is itself a `oneOf` goes through the field extractor under the response name, so every inline object variant — const-prefixed, titled, property-named, or nullable (`type: ['object', 'null']`) — is materialized under exactly the name the union references (`GetThingResponse`, `GetThingResponseWithSide`, `SquareGetThingResponse`). Everything nested under a variant is named from the variant, never from the union's field: an inline object under the second variant is `DrawingShapeWithSideCenter` (or `SquareDrawingShapeCenter` under a titled one); a multi-type variant such as `type: ['object', 'array']` keeps its other types beside the model (`union[model, array]`), and the inline items of that array member are `<Variant>Item` (`DrawingShapeWithSideItem`, with nested objects `DrawingShapeWithSideItemChild`); any other non-object member is named `<Variant>Value` (an inline enum, for instance). If a property of the variant already claims that model name (`item`, or `items`, which singularizes to the same `<Variant>Item`), the member falls back to `<Variant>ArrayItem` / `<Variant>MemberValue`, then `<Variant>ArrayItem2`, `<Variant>ArrayItem3`, and so on. A variant that admits null (`['object', 'null']` or `nullable: true`) keeps its `nullable` wrapper around the model.

Every other variant of an inline `oneOf`/`anyOf` — one that is neither a `$ref`, an inline object, nor its `null` variant (see UnionType) — is typed and extracted under a context decided by one function, which the union TypeRef, every extractor and the sibling-name reservation all read, so a reference always has a model behind it. An array or map variant is typed under `<field>_item` / `<field>_value`, so its inline items or values are `<Parent><Field>Item` / `<Parent><Field>Value` (`CreateThingRequestFItem` for the items of an array variant of `f`), never the name an object variant of the same union keeps. A variant that would mint a model or enum name under the field's own context — a union nested under the variant (its inline object variants are named from the field's name as the outer ones are, so its first one would otherwise take the outer variant 0's name), a nullable wrapper around an inline object (`oneOf: [{ … }, { type: 'null' }]`), an `allOf`, an inline enum or a `oneOf` of string consts — keeps the field's context when nothing it mints there is claimed, and is otherwise typed under `<field>_variant_<n>`, n its 1-based position among the non-null variants, as a named union's non-object variants are: beside an object variant `GetNoteError400`, the variants of a nested union are `GetNoteError400Variant2` and `BGetNoteError400Variant2`, a nullable object or an `allOf` is `GetNoteError400Variant2`, an inline enum is `GetNoteError400Variant2`; beside only a primitive, a nested union still names its variants `GetNoteError400` and `BGetNoteError400`, and an inline enum keeps `GetNoteError400`. Only context-dependent names take part: a nested `oneOf` whose every variant carries a `title` and pins the same const property names its variants by those titles (`A`, `B`), which are the same under every context — as is everything their models nest (`ALoc` for an inline `loc` of `A`) — so it keeps the field's context and is materialized under the titles — while one of its variants whose title is already taken falls back to a context-qualified name (`AGetNoteError400`) and steps with it. A variant typed under its context steps around every name claimed at that point — the sibling-minted and caller-reserved names the field's own variants step around, the union's inline object variants and everything nested under them, every name an earlier variant minted, and a context-free title an earlier variant kept for a different shape (one kept for the identical shape is shared, as between sibling fields) — so a nested titled variant whose title is already a sibling field's model (`HolderA` beside `Holder.a`), an earlier variant's model (`HolderShapeVariant2`) or an earlier nested variant's title of another shape takes its context-qualified name (`HolderAHolderShape`, `AHolderShape`) exactly as a field-level titled variant does beside the same sibling, and the union never exposes the sibling's fields. A name is claimed when a sibling property mints it, an inline object variant of the union takes it, an object variant's own property mints it at any depth (a `variant` object holding a `2` object mints `GetPetResponseShapeVariant2`, as a `variant_2` object does), or an earlier variant of the union minted it, at any depth too; when the chosen context still mints a claimed name — a model of the variant's own or one at any depth under it, so the `loc` of a nested variant `GetPetResponseShapeVariant2`, `GetPetResponseShapeVariant2Loc`, counts when the object variant's `variant_2_loc` takes that name — it steps on as an array's items do beside a claiming sibling (`<field>_array_item`, `<field>_array_item2`, … for an array or map variant; `<field>_variant_<n>_value`, `<field>_variant_<n>_member_value`, … for the rest). The rule applies wherever an inline union is typed — a component field, a request body (a `oneOf` body's inline object variants keep their body names, see below; its other variants follow this rule, and a body typed by `schemaToTypeRef` alone, such as an `anyOf` or an array, has every inline model it references materialized the same way), an inline 2xx response, an error body, a discriminated `allOf` + `oneOf` variant's field, array items and map values — and to a nested union's own variants in turn (`GetNoteError400Variant2Variant2` for a union nested two levels down).

**`properties` beside a composition.** JSON Schema applies every keyword of one schema at once, so an inline schema that writes `properties` beside an `allOf`, `oneOf` or `anyOf` that types it — `{ properties: { id }, allOf: [{ $ref: Pet }] }` is a `Pet` that also has `id`; `{ properties: { id }, oneOf: [pet, note] }` is one of `pet` or `note` with `id` in either case — is read as the composition carrying the properties, wherever it sits: a field, array items, map values, a request body, a response body, a list envelope's items, a parameter, a header, a webhook payload. An `allOf` gains the schema's own `properties` and `required` as its first member, so the augmentation of a `$ref` member (`HolderThing { id, name }`), a model merged from inline members, or a single member unwrapped carries them, the schema's own first. Each inline object variant of a `oneOf`/`anyOf` — `type: 'object'`, no `type`, or a type list naming `object`, so a nullable or multi-typed object variant included — gains them the same way (`HolderThing { id, name }`, `HolderThingWithText { id, text }`), the `required` naming the union of both lists. Where the variant declares the same property, the narrower declaration is kept, as JSON Schema applies both: the variant's when it pins the property's values with a `const` or an `enum` and the schema's own pins none, or pins those values and more — so `kind: { const: 'cat' }` beside an own `kind: { type: 'string' }` or `kind: { enum: [cat, dog] }` stays `'cat'`, the variants are named from their values (`HolderThing`, `DogHolderThing`) and a discriminated union keeps its mapping, while the own declaration's flags, documentation, limits and extensions (`readOnly`, `description`, `x-*`) stay the field's wherever the variant's sets none — and the schema's own otherwise, so an own `kind` enum beside a variant's plain `kind` stays the enum; the union keeps every variant. A `$ref` to an enum component — an `enum:` list, or a `oneOf`/`anyOf` of string consts — or an `allOf` read as a reference to one (a lone `allOf: [{ $ref }]`, or one whose other members add nothing to it, `allOf: [{ $ref: Kind }, { description }]`; see Inline `allOf`), pins that enum's values on either side, exactly as an inline `enum` of them does: an own `kind: { $ref: Kind }`, `Kind` the enum `[cat, dog]`, stays `Kind` over a variant's `enum: [cat, dog]` or `[cat, dog, bird]` (no duplicate enum is minted for the variant) and gives way to a variant's `const: 'cat'`, in OAS 3.0 and 3.1 and on a component field alike; a variant's `kind: { $ref: Kind }` beside an own plain `kind` stays `Kind`. `null` is one more value a declaration pins when it admits it by any spelling (a type list naming `null`, `nullable: true`, a `null` among its values, a `$ref` to a nullable enum), so a variant's `{ type: ['string', 'null'], enum: [cat] }` is not narrower than an own `enum: [cat, dog]` or an own `type: string`, which forbid `null`, and the own stays — while beside an own `type: ['string', 'null'], enum: [cat, dog]`, or a typeless own declaration, it is the narrower and the field is the nullable `'cat'`. Every other variant is typed as written: a `$ref` names a component the parser never merges properties into; a primitive, array or enum is no object, so `properties` constrains nothing in it; a nested composition or a nullable union wrapper is left to its own variants. The parser warns once per union, with the field's context, for the variants that may be objects and did not take the properties (a `$ref`, an `allOf`, a nested union, a map, a nullable wrapper around an object): ``[oagen] Warning: `properties` beside `oneOf` are carried into its inline object variants only; variant 1 is typed as written, without them (context: GetThingResponse.mixed)``. An empty `properties: {}` declares nothing and is left as written: beside an `allOf` the schema is that `allOf` (`{ properties: {}, allOf: [{ $ref: Pet }] }` is `Pet` on a field and as a response body, as `{ allOf: [{ $ref: Pet }] }` is), beside a `oneOf` the union — never an empty model that drops the composition. An `allOf` or `oneOf` of bare limits beside `properties` does not type the schema, which stays the object it is with the limits conjoined (see Constraints). A success body whose one property, or one `required` property, is a `type: 'object'` with a string `const`, or a `oneOf` of one such object with `null` beside it or not, is a single-resource wrapper and unwrapped to that object (`{ pet: { object: 'pet', … } }` is `Pet`; `oneOf: [pet, null]` is `Pet | null`). A `oneOf`/`anyOf` with more than one non-`null` variant — in the property's place, or beside the tagged object when any variant adds a shape the object does not already have: a `$ref`, another type, a property the object does not declare, or a const tag of its own, as two tagged objects do — is the body's own field, and the body is kept with every variant (`GetShapeResponse { shape }`, `shape` the union of both variant models), as a body with a second property is (#415); a union beside the object whose variants only limit it — `type: 'object'` repeated, `required`, a refinement of one of its own properties (`{ required: ['a'], properties: { a: { minLength: 1 } } }`) — leaves the resource to unwrap. Where the composition is merged into one model — an `allOf` as a field, as array items, as a response body or as a component schema — earlier members win on a shared property name, the schema's own first — among the declarations that declare a type; a typeless one, a bare `description` say, never types the property and only fills in what the typing declaration leaves unset, wherever it sits; two typing declarations of inline objects conjoin their properties and `required`, an inline object and a `$ref` to an object component conjoin as the `allOf` of both, two of arrays combine their `items` by this same rule, as JSON Schema applies both — so an own `kind` enum beside a member's plain `kind` stays the enum at every site; a property is matched by its own name (`Object.hasOwn`), so a field named `constructor` or `toString` is kept like any other. Under `components.schemas`, a schema's own `properties` and `required` beside an `allOf` are its first member, read before the members as written: `Dog: { allOf: [{ $ref: Pet }], properties: { breed }, required: [breed] }` is `Dog { breed, name }`, with `breed` required, and a `$ref` member's component is read the same way — its own properties, then its members — so a chain (`Pup → Dog → Pet`) carries every level's own properties, an inline object or enum under any of them is materialized under the model that inherits it, and a `required` naming only inherited properties applies to them. A member's own `properties` and `required` beside its `oneOf`/`anyOf` — an inline member's, or those of the component a `$ref` member names — always apply, the union's variants flattened or dispatched after them. An `allOf` combined with a `oneOf`/`anyOf` has one reading at every site — a component, a field, a request body, a response body — however the two are written (#398): JSON Schema applies every keyword of a schema, so the instance is the base and one (or any) of the variants, and the model is the base's fields plus each union's variant properties as optional fields, a property the variants type differently typed as their union. A union written beside an `allOf` that types the schema (`allOfTypesSchema`; beside one whose members only annotate or limit it, the union is what types the schema and the component is a named union — see Named unions and Collapsed wrappers; #613) is its last member (`NewPet: { allOf: [base], oneOf: [{ ownerId }, { shelterId }] }` is `NewPet { name, ownerId?, shelterId? }`, as `{ allOf: [base, { oneOf: [...] }] }` is, with a `discriminator` written beside them going with the union; before, a field, a component and a response body read the `allOf` alone and dropped the union, and a request body built the union from the variants alone, without `name`), a member writing both keywords carries two unions, each flattened or dispatched on its own (`Both { name, ownerId?, shelterId?, vetId?, clinicId? }`; before, the `anyOf` was dropped without a word), a nullable `oneOf` beside an `anyOf` on one member read per keyword (`{ oneOf: [{ a }, { type: 'null' }], anyOf: [{ b }, { c }] }` is `{ name, a?, b?, c? }` as one member, as two members and beside the `allOf` alike; before, `{ name, a? }` as one member), a dispatching axis beside a nullable one on one member read the same way by the member reader and the variant builder (`memberUnions`: `{ oneOf: [{ a }, { type: 'null' }], anyOf: [cat, dog] }` with `cat` and `dog` pinning `kind` dispatches to `PetCat` and `PetDog`, both built; the builder collapsed the nullable `oneOf` for the whole member and built neither), the folded reading one object per schema wherever it is read, so a field whose union names the component the field sits in (`Note.reply: { allOf: [{ depth }], oneOf: [{ $ref: Note }, { other }] }`) ends where the member spelling ends, at `NoteReply { depth, id, reply, other }` (before, it overflowed the stack), a variant's nested unions are read through however deep (`Nested: { allOf: [base, { oneOf: [{ oneOf: [{ a }, { b }] }, { c }] }] }` is `{ name, a?, b?, c? }`; before, `{ name, c? }`), a `$ref` variant's component is flattened in as an inline variant is (`{ oneOf: [{ $ref: Owner }, { $ref: Shelter }] }` beside the base gives `ownerId?` and `shelterId?`, the components keeping their own fields), and a property only variants declare is typed as the union of its declarations (`Typed: { allOf: [base, { oneOf: [{ kind: string }, { kind: integer }] }] }` is `{ name, kind?: (string | integer) }`, as its inline twin is; before, the component took the first variant's `string`). A discriminated `allOf` + `oneOf`/`anyOf` component — the union spelled with either keyword, written as a member or beside the `allOf`, every variant, a single one included, pinning one property to a distinct const (a `$ref` variant's read from its component), or the document declaring a `discriminator` for it, on the union or on the `allOf` wrapper around it (its `mapping`, when written, taken as a named union takes it) — carries its own properties into the dispatcher model and into every variant model, as it carries a member's, and the variant models are built for the union that dispatches whichever keyword spells it; a `$ref` variant's component is its model, named by the mapping as is, its const read from the component as a named union reads it — through the component's `allOf` members, a `$ref` member among them followed, and through a `$ref` to a const schema alike (#568; review round 3: the lookups ran without the component map, so `Cat: { allOf: [{ $ref: CatTag }, { lives }] }` pinned nothing and `Pet` was flattened, the diff seeing no variant added), and an inline variant pinning its tag the same way is named by it (`PetCat`) — (`Pet: { allOf: [{ $ref: Base }, { oneOf: [{ $ref: Cat }, { $ref: Dog }] }], discriminator: { propertyName: kind } }` is a dispatcher `Pet { id }` mapping `{ cat: 'Cat', dog: 'Dog' }`, so `oagen diff` reports `$ref: Bird` added to the union as an additive `variant-added` and removed as a breaking `variant-removed`; before, such a `Pet` was a plain `{ id }` and the diff saw nothing), and an inline variant's is built for it, each named for its const — one of several words alone (`user.created` → `UserCreated`), one word after the component's name (`PetEvent`'s `cat` → `PetEventCat`, and `CatEvent`'s → `CatEventCat`), as is a const that spells the component's own name (`Cat`'s `cat` → `CatCat`), so a variant never takes the dispatcher's name. Nor does a variant's model, or a model nested under it, take a name another model holds with another shape — a component's (`CatEventCat` beside a component `CatEventCat` of other fields), an enum's, a named union's variant's, an object another component's field mints, or a variant an earlier component in the document dispatches to (`user.created` on two dispatchers): the variant steps by number (`CatEventCat2`, then `CatEventCat3`, …), the number spelled as every numbered model name's is (see Numbered names under Inline model naming): behind `No` when the name ends in a digit, so `PetEvent`'s `pet.v2` beside a component `PetV2` of other fields is `PetV2No2`, then `PetV2No3`, never `PetV22`, which reads as version 22; the models nested under it moving with it (`CatEventCat2Owner`, `PetV2No2Owner`) and the mapping naming it there (`'pet.v2': 'PetV2No2'`); a holder of the identical shape is shared, and a component's model stands for the variant's, so the component keeps its own documentation. A union no discriminator dispatches — two of its variants named alike, or one whose const spells no name (`''`, `'-'`) — is flattened into the model and builds no variant model, each variant read as the inline merge reads it (`declareVariant`, the one branch reader both share): through its `allOf` wrappers, the unions nested in them and a `$ref` to the component it names, so a field written inside a variant's `allOf` (`{ allOf: [{ properties: { kind: { const: '-' }, meow } }] }`) is flattened in with the rest, a variant's own members conjoined into one declaration per name as a merge conjoins them (`value: { type: 'string' }` in one member and `value: { description }` in another is one described string, not `string | unknown`), and the consts the variants pin are the enum the field is typed as (`kind?: CatEventKind` of `'-'` and `'dog'`). A property declared twice keeps the first always-applying declaration that declares a type, the component's own first — a typeless declaration (`description` alone) never types it and only fills in what the typing one leaves unset, before or after it; two typing inline objects conjoin their properties and `required` into one declaration the component's model nests as its own (`PageResult { items, total_pages }` from `result` declared by two members), an inline object and a `$ref` to a component that declares properties (its own or its `allOf` chain's), or an `allOf` that reaches one, conjoin as the `allOf` of both, read as an inline `allOf` is (`result: { $ref: PetPage }` beside `result: { properties: { total_pages } }` is a `PageResult` with `PetPage`'s `items` and `total_pages`, whichever member comes first, `items` typed as `PetPage` types it, and the flags and documentation either declaration gives the field stay the field's), while a `$ref` to an array, enum, primitive or union component is no object to conjoin and the first declaration stays; two typing arrays combine their `items` by this same rule (`items: { description }` only annotates `items: { $ref: Pet }`, so `data` stays `Pet[]`) — whatever a `oneOf`/`anyOf` variant declares before or after it and at whatever depth — a declaration a nested member makes under a variant stays branch-only in every model that inherits it — so a component never carries two fields of one name; a property only variants declare is typed as the union of its distinct declarations, exactly as an inline merge types it (`unionOfDeclarations`, see Inline `allOf`; #398: a component took the first variant's declaration). That precedence is one rule (`declareProperty`, through `combineDeclarations`), shared with the inline merge, the dispatcher base and the list-envelope collector that reads a wrapper's companions and stop field, and the declaration it picks is the one every pass reads for the field (`componentPropertyLedger`): the field's type, the models nested under it and the sibling set its names are decided against all come from that declaration, never from one another member outranks. Every model a component field's type reaches — an inline object, array items, map values, a union's variants, under a nullable wrapper, at any depth — is built by the field extractor from that declaration under the component's name, an inherited declaration exactly as the component's own (`Puppy.meta`, inherited from `Dog`, is typed `PuppyMeta…` and built so), by the field pass that runs over every component (`extractComponentFieldModels`), so no field references a model nothing built. An `allOf` of bare limits beside a component's `properties` leaves the object its properties describe, with the limits conjoined. The component's model and an inline `allOf` merge that names it therefore carry the component's own and inherited properties in the same order, a union the component itself carries included: one its model flattens is flattened into the merge too, and one its model dispatches is left to the component, so the merge carries the base fields the dispatcher model carries and no variant's (#429; see Inline `allOf`). A `oneOf`/`anyOf` written beside `properties` under `components.schemas` is read as `allOf: [{ properties }, { oneOf }]` is: the properties are the base every variant carries, and the union is flattened or dispatched after them — `Pet: { properties: { id }, required: [id], oneOf: [{ ownerId }, { shelterId }] }` is `Pet { id, ownerId?, shelterId? }`, and `Dog: { allOf: [{ $ref: Pet }], properties: { breed } }` is `{ breed?, id, ownerId?, shelterId? }` as a component, as a response body written inline and as a field alike (#429: `Pet` kept the object model with the union unread, so only `Dog`'s component model carried the variants' properties, and the same schema inline carried `breed` and `id` alone); with variants that pin a const, or a `discriminator`, `Pet` dispatches to them. Beside an empty `properties: {}` the union is a named union, as before (see Named unions).

**Bases of a composed component.** A model built from a component schema whose `allOf` names other components keeps them beside the merged `fields` (#591): `bases` is one `{ kind: 'model' }` reference per `$ref` member, in document order, each once, and a field taken from a base unchanged carries that base as `inheritedFrom`. `Pet: { allOf: [{ $ref: Animal }], properties: { nickname } }` over `Animal { name }` is `Pet { nickname?, name }` with `bases: [Animal]` and `name` carrying `inheritedFrom: Animal`, as `Pet: { allOf: [{ $ref: Animal }, { type: 'object', properties: { nickname } }] }` is `Pet { name, nickname? }` with the same keys; `allOf: [{ $ref: Animal }, { $ref: Owned }]` has `bases: [Animal, Owned]`, `name` inherited from `Animal` and `ownerId` from `Owned`, and the members written the other way round name `[Owned, Animal]`. Each model names only its direct bases: with `Animal: { allOf: [{ $ref: Living }], properties: { name } }` and `Living { born }`, `Animal.bases` is `[Living]` with `born` inherited from `Living`, and `Pet.bases` stays `[Animal]` with `born` on `Pet` inherited from `Animal`, since `Animal & { … }` already covers `Living`. A field is taken unchanged when the declaration the model settles on (`declareProperty`, see Several declarations of one property) is the base's as written and the model requires it only as the base does: `Pet: { allOf: [{ $ref: Animal }], required: [name], properties: { name: { type: 'string', enum: [rex, max], description: "The pet's registered name." }, nickname } }` over `Animal { name?: string, species? }` carries `name` (the enum `PetName`) and `nickname` without `inheritedFrom` and `species` with `inheritedFrom: Animal`, so an emitter can write `Pet` as `Animal & { name: PetName; nickname?: string }`. A declaration of the model's own that changes any key of the base's — the type, a `description` the base has none of (`species: { description }` beside the `$ref`, in the component's own `properties` or in an inline member after it), a `nullable` or `deprecated` flip — makes the field the model's own, and so does `required: [species]` over a base that leaves `species` optional, written beside the `allOf` or in a member; `required: [name]` over a base that already requires `name` changes nothing, and neither does a declaration the merge sets aside — a later typing one the first outranks (an inline member's `species: { type: 'string', nullable: true }` after the `$ref`), or a `description` on a field the base already documents — so the field stays the base's, as the IR carries it. A `$ref` member names the component its reference resolves to, as the inline merge records a property's origin (`mergeAllOfMembers`, see Inline `allOf`): a bare alias (`Hop: { $ref: Animal }`), read as `allOf: [{ $ref: Animal }]` (#618), is a model of its own and the base, as `Hop: { allOf: [{ $ref: Animal }] }` is (`Pet.bases` is `[Hop]`, every field inherited from `Hop`, and `Hop.bases` is `[Animal]`, with `Animal`'s own base after it in a longer chain), while a nullable alias (`Alias: { oneOf: [{ $ref: Animal }, { type: 'null' }] }`) declares nothing of its own, so the base is `Animal`. A `$ref` member naming an enum, array or primitive component is no base: it builds no model and contributes nothing to the fields, as before. A named union a `$ref` member names — flattened in or dispatched, as its own model reads it (#429) — is a base, its flattened fields the model's own with no origin, as a field the component's own flattened variants declare is. A `$ref` member whose component an earlier member's chain already read declares nothing more but is a direct base all the same: `Pet: { allOf: [{ $ref: Animal }, { $ref: Living }] }` over `Animal: { allOf: [{ $ref: Living }] }` has `bases: [Animal, Living]`, and `[Living, Animal]` with the members the other way round, a field both carry (`born`) naming the first member that declares it; the same `$ref` twice is one base, a component naming itself, or an alias of itself, is no base of its own, and two bases a rename sends to one name — `Foo: { allOf: [{ $ref: Bar }, { $ref: BarJson }] }` once `BarJson` folds onto `Bar` — are one base, the first kept (`renameModelRefs`), with `BarJson`'s fields on `Foo` inherited from `Bar`. `bases` is present exactly when at least one base is named — on an allOf+oneOf dispatcher too (`Pet: { allOf: [{ $ref: Base }, { oneOf: […] }] }` has `bases: [Base]` and `id` inherited from `Base`) — and never on a model built from an inline `allOf` (a request or response body, a field; see Inline `allOf`) nor on a dispatcher's variant models, which are built as complete objects. Unchanged means as the document declares it: an inherited field's `type` is still built under the inheriting model's name, so an inline object `Animal.meta` declares is `AnimalMeta` on `Animal` and `PetMeta` on `Pet` — the same shape — with `inheritedFrom: Animal`. `fields` stays complete and in its order, so an emitter that reads neither key sees the model it always saw, as one that does not read `variants` sees the merge of a named union; the keys are provenance, not shape: the differ and the parser's fingerprints read a model with and without them as one shape (a component `PetCat: { allOf: [{ $ref: Base }], properties: { kind: { const: cat }, meow } }` still stands for a dispatcher's identical inline variant, and `oagen diff` sees nothing when `Pet` declares `name` itself in one document and inherits it in the other), `collectModelTypeRefs` leaves them out, `renameModelRefs` repoints them, `validateModelRefs` checks them, and reachability for emission (`collectReferencedNames`) chases `bases`, so the base of an emitted model is emitted even when no operation reaches it. `UnionType.compositionKind` admits `'allOf'`, but the parser never sets it; `bases` is what tells a composed model apart.

### UnionType

```typescript
interface UnionType {
  kind: "union";
  variants: TypeRef[];
  discriminator?: { property: string; mapping: Record<string, string> };
  compositionKind?: "allOf" | "oneOf" | "anyOf";
  constraints?: Constraints; // Written beside the oneOf/anyOf, or a type list's; each oneOf/anyOf variant carries its own, a type list's none (see Type constraints)
}
```

The `compositionKind` field tells emitters which OAS composition keyword produced the union, allowing them to distinguish inheritance (`allOf`) from exclusive union (`oneOf`) from open union (`anyOf`).

`discriminator` is resolved from the same sources, in the same order, as a named union's (see Named unions), from the same reading of the variants, wherever the union is written — a field, a response body, a parameter, an array's items, a map's values, a webhook payload (#568): the spec's own `discriminator.mapping`, each target as the document spelled it with a leading `#/components/schemas/` stripped (`cat_dto` stays `cat_dto`; an inline union's values are not IR model names — see Named unions for the one difference); else, under the keyword without a `mapping:`, each variant's const on the property paired with the model the variant is referenced by, and `{}` when any variant pins none or is unnamed; else, for a `oneOf` with no keyword, the first property the first variant pins whose values are distinct across all of them, a constant every variant shares (`version: 'v1'`) passed over. A `$ref` variant is named by its component and its const read from it, through the component's `allOf` members — a `$ref` member is followed to the component it names, through a chain of aliases, so `Cat: { allOf: [{ $ref: CatBase }, { properties: { lives } }] }` pins what `CatBase` pins and `Puppy: { allOf: [{ $ref: Dog }] }` what `Dog` pins, and a member pinning the property to one value outranks the open declaration another member makes, in either member order, since a const narrows and never widens (`Base.kind: { type: 'string' }` under a `$ref Base` member read before the variant's own `kind: { const: 'cat' }` leaves `Cat` pinned to `'cat'`) — and through a `$ref` on the property itself to a component pinning one value, or to an alias chain ending in one (`kind: { $ref: HamsterKind }` with `HamsterKind: { const: 'hamster' }`, or `enum: ['hamster']` in OAS 3.0). The declaration is read as the type builder reads it, at every hop (`pinnedDeclarationValue`): a `$ref` is followed to its component, a nullable wrapper to its one variant, and an `allOf` read as one member — a lone member, one typing member beside members that only annotate or limit it (a `description`, `title`, `deprecated`, `default`, `example`/`examples`, `readOnly`/`writeOnly`, a limit, an `x-*` key), or a lone `$ref` member beside such members (see Aliases) — to that member, then the `const` or one-value `enum:` written there is the pin. So `kind: { allOf: [{ const: 'cat' }] }` pins `cat` as `kind: { const: 'cat' }` does; `kind: { allOf: [{ $ref: HamsterKind }], description: 'The kind of pet.' }` pins `hamster`; and `kind: { $ref: RabbitKind }` with `RabbitKind: { allOf: [{ $ref: RabbitConst }] }` and `RabbitConst: { const: 'rabbit' }` pins `rabbit` — each spelling the same literal the model's `kind` field carries, so `Cat`, `Hamster` and `Rabbit` map exactly as `Dog`, written `kind: { const: 'dog' }`, does, in OAS 3.0 (`enum: ['cat']`) and 3.1 alike, on an inline variant's own property as on a component's (#607: only a bare `$ref` chain was followed and what it landed on read as written, so each pinned nothing and the union carried `{}` under the keyword and no discriminator without it). An `allOf` of two typing members (`kind: { allOf: [{ const: 'cat' }, { const: 'dog' }] }`), which the type builder reads as neither, pins nothing, even when the two agree; a component reached again on one walk is read once, so a cycle pins what it declares and nothing more, and a chain that repeats — through a `$ref` or an alias — pins nothing. So `oneOf: [{ $ref: Cat }, { $ref: Dog }]` carries `{ cat: "Cat", dog: "Dog" }`, `oneOf: [{ $ref: Hamster }, { $ref: Dog }]` carries `{ hamster: "Hamster", dog: "Dog" }` and `oneOf: [{ $ref: Puppy }, { $ref: CatBase }]` carries `{ dog: "Puppy", cat: "CatBase" }`, each as the models themselves pin `kind`, exactly as an inline `{ allOf: [{ $ref: Dog }] }` variant was mapped already. A variant that wraps one `$ref` to a model — a nullable wrapper, an `allOf` read as its reference, a `oneOf`/`anyOf` whose other members name no model, such as `oneOf: [{ $ref: Bird }, { $ref: Song }]` with `Song` an enum component — is read through that reference; an inline object variant is named by the model extracted for it, its title when the union is title-mapped (see Inline model naming), else the field's inline name or a const prefix on it; and a title on any other variant (an `allOf` merged into a model of its own, an array) names nothing, since no model is extracted under it. So `Owner.pet` written as `oneOf: [{ $ref: Cat }, { $ref: Dog }]` carries `{ cat: "Cat", dog: "Dog" }` with and without the keyword, exactly as the component `Pet` of the same `oneOf` does, and the same union with `Dog` written inline carries `{ cat: "Cat", dog: "OwnerPet" }`; a `oneOf` of two inline objects pinning `kind` keeps carrying `{ cat: "OwnerPet", dog: "DogOwnerPet" }`. A request body's union carries only the spec's own mapping (`typePickedRequestBody`); its variants' consts derive nothing — and a body that is a `oneOf` of inline objects under the keyword, each pinning the property, is folded into one object whose discriminator is an enum of the pinned values (`flattenDiscriminatedUnionBody`), the pin read as a union's discriminator reads one, so `kind: { allOf: [{ const: 'email' }] }` folds as `kind: { const: 'email' }` does, and a `$ref` to a const component or an alias of one folds too (#607); the rebuilt discriminator admits `null` exactly when a variant's declaration does, at any hop — a nullable wrapper, a type list naming `null`, OAS 3.0 `nullable: true` beside a type, never a keyword beside a `$ref`, which the type builder gives precedence over its siblings (`pinnedDeclarationAdmitsNull`) — so a `kind: { oneOf: [{ const: 'email' }, { type: 'null' }] }` variant beside one pinning `sms` folds to a `kind` typed `nullable<enum>`, as the variant's own field is `nullable<literal>` (#607 review: the fold rebuilt the field without `null`); and the rebuilt discriminator carries the settings every variant's declaration agrees on — `readOnly`, `writeOnly`, `deprecated`, `description`, `default`, `example`/`examples`, `externalDocs`, limits (conjoined across the levels as a field's are, the stricter bound winning: `combineConstraints`) and `x-*` keys — each declaration read exactly as a field written as it is read (`fieldSettings`, the reading `buildFieldFromSchema` makes, the pin walk kept apart: under a wrapper the declaration documents itself, from the wrapper and the members beside the `$ref`, and takes none of the component's text, flags, default, examples or keys, while a bare `$ref` reads the entries it passes, an enum component's staying on the `Enum`; its limits conjoin from every entry either way), so two variants writing `kind: { allOf: [{ const: … }], readOnly: true }` fold to a read-only `kind`, as each variant's own field is, while a flag one variant alone writes is nobody's (#607 review: `description` alone was carried).

A variant that admits `null` alone is a `null` variant, in every spelling JSON Schema gives it — `{ type: 'null' }` (or `type: ['null']`), `{ const: null }`, and an `enum:` list of nothing but `null` (`{ enum: [null] }`) — wherever the union sits (`isNullSchema`, the one test every site makes): it is never one of `variants` and mints no model or enum, one or more of them make the union `nullable<…>`, and a union left with one other variant collapses to that variant, so `oneOf: [{ type: 'string' }, { const: null }]` is `nullable<string>` and a list envelope whose `data` is `oneOf: [{ type: 'array', items: Pet }, { enum: [null] }]` is unwrapped as `Pet[] | null`. A `const` or `enum:` counts only as the keyword that types the variant (no `$ref` or composition beside it) and with no `type` beside it naming another type: `{ enum: [null, 'x'] }` and `{ type: 'string', const: null }` stay variants.

**Type lists.** An OAS 3.1 `type` list naming several types (`type: ['object', 'string']`) is a `union` of one variant per non-null type, in the list's order, each the schema read as that type alone (`typeListCopy`; #616). A type list says the instance is one of the types named, and JSON Schema applies each keyword to the instances of its own type alone, so a per-type copy keeps the keywords of its type's family — `properties`, `required`, `additionalProperties`, `patternProperties`, `minProperties`… for `object`; `items`, `prefixItems`, `minItems`… for `array`; `format`, `pattern`, `minLength`, `maxLength`… for `string`; `format` and the numeric bounds for `number` and `integer`; nothing for `boolean` — and sheds every other type's, while `const`, `enum`, a composition, `discriminator` and every annotation stay on every copy: `Note.author: { type: ['object', 'string'], properties: { name } }` is `NoteAuthor | string`, the model built from the `object` copy beside the bare `string`. A composition is read member by member against the copy's type. A member that declares a type excluding it — its own `type`, its component's (`Owner: { type: 'object' }`), what every member of its own `allOf` or any variant of its `oneOf`/`anyOf` declares, `number` admitting `integer` — admits no instance of that type, so an `allOf` with such a member leaves no copy, as does a `oneOf`/`anyOf` whose every variant is one. On an `object` or `array` copy — one the extractor builds models for, from the schema's composition read whole as a merge or a reference — a composition is kept or left off whole, never trimmed to the members that apply, since a copy reading a composition of its own would reference a model nobody builds: it stays while any member says something about an instance of the copy's type — a type admitting it, a `const` or `enum`, a keyword of the type's family — and is left off when no member does and the copy is then a bare object or array declaring no `properties`, `additionalProperties`, `patternProperties`, `items`, `prefixItems` or `contains` of its own; a copy that declares such a schema keeps the composition, so `{ type: ['array', 'string'], items: { … }, allOf: [{ $ref: Owner }] }` is `Owner | string`, not an array of items no extractor builds, and `{ type: ['array', 'string'], allOf: [{ properties: { name } }, { items: { … } }] }` is `NoteAuthor | string` with the merged `NoteAuthor { name }` the extractor builds. A primitive copy (`string`, `number`, `integer`, `boolean`), which nothing of reaches the extractor, keeps of an `allOf` the members that say something about its type alone and sheds the rest — `Owner: { properties: { name } }` beside `string`, `{ description }` beside anything — so `{ type: ['object', 'string'], allOf: [{ $ref: Owner }, { minLength: 1 }] }` with `Owner` untyped is `Owner | string`, the `string` copy keeping `{ minLength: 1 }` as it does when the keyword sits beside the list, and `['string', 'integer']` beside the same `allOf` is `string | integer`; a `oneOf`/`anyOf` is kept whole on every copy while any variant applies and left off a primitive copy when none does. So `Note.author: { type: ['object', 'string'], allOf: [{ $ref: Owner }] }` is `Owner | string` when `Owner` declares `properties` and no `type`, since its `properties` say nothing of a string, and `Owner` alone when `Owner` is `type: 'object'`, which no string satisfies; a `description` member beside the `$ref` changes nothing; `['object', 'string', 'null']` is the same under `nullable`, as `['object', 'null']` beside the `allOf` is `nullable<Owner>` and OAS 3.0 `nullable: true` beside it is. Two copies one keyword types alike are one variant — `{ type: ['string', 'integer'], enum: ['a', 1] }` is the one inline enum, `const: 'a'` the one literal, a model never twice — and a lone variant is the type itself, so no union holds one type twice (`dedupeTypeRefs`). A list no entry of which the composition admits (`['string', 'integer']` beside `allOf: [{ $ref: Owner }]`, `Owner` an object) contradicts itself and is read as written, every keyword on every copy, which the `allOf` then types alike: `Owner`. The limits written beside the list are the union's, not a copy's (see Type constraints); once the list collapses to one variant they are that variant's where it can carry them — an array, a map, a primitive, a literal, a nested union — and, for a model or enum reference, none, exactly as the same limits beside a bare `$ref` or an `allOf` of one at the same site are read (a model reference carries no site limits; the field or parameter the schema is written on keeps its own): `items: { type: ['object', 'string'], allOf: [{ $ref: Owner }], minProperties: 2 }` with `Owner` an object is `Owner[]`, as `items: { allOf: [{ $ref: Owner }], minProperties: 2 }` is. The same reading applies wherever the schema sits — a field, a response or request body, a parameter, array items, map values, a `oneOf`/`anyOf` variant (an inline object variant's non-object members are built from the same copies) — a response body's `allOf` beside the list included, read as the request body reads it rather than as the merge alone (`directResourceReading`; #616 review: `{ type: ['object', 'string'], allOf: [{ properties: { nick } }] }` as a `200` body was `CreateNoteResponse`, the `string` lost, while the request body was `CreateNoteRequest | string`; both are the merge beside the `string`) — and `typesAsUnknown` answers for a list as the union it builds: bare `unknown` exactly when every copy is. Before #616 every copy kept every keyword, so the `string` copy was typed by the `allOf` as the `object` copy was, and the field was `Owner | Owner`.

### TypeParam

```typescript
interface TypeParam {
  name: string;
  default?: TypeRef;
}
```

Generic type parameters on models. Example: `DirectoryUser<TCustomAttributes = Record<string, unknown>>`.

## AuthScheme

```typescript
type AuthScheme = { description?: string; schemeName: string } & (
  | { kind: "basic" }
  | { kind: "bearer" }
  | { kind: "apiKey"; in: "header" | "query" | "cookie"; name: string }
  | { kind: "oauth2"; flows: Record<string, unknown> }
);
```

Emitters use `AuthScheme` to generate authentication configuration and client constructors. The `cookie` variant supports cookie-based API key authentication.

`schemeName` is the key under `components.securitySchemes`, spelled exactly as in the document, and `description` is present only when the document declares one; entries keep the document's order. The requirements under `ApiSpec.security` and `Operation.security` refer to the same key, so an emitter joins a requirement to its scheme with `spec.auth?.find((a) => a.schemeName === requirement.schemeName)`. The optional chaining matters: `auth` is `undefined` when the document declares no scheme the IR can represent, and a requirement can still name a scheme that was omitted (see below), so a missing match means "no SDK-level auth is known for this operation", not an error.

HTTP scheme names are matched case-insensitively (`Bearer`, `bearer`, and `BEARER` all yield `kind: "bearer"`). Security schemes the IR cannot represent (other `http` schemes such as `digest`, plus `openIdConnect` and `mutualTLS`) are omitted from `auth`, and the parser prints an `[oagen] Warning:` diagnostic naming the scheme.

An entry under `components.securitySchemes` may be a `$ref` to another entry — OAS 3.0.3 and 3.1.0 both allow a Reference Object there — and the parser follows it, chains included, through `followReference` in `src/parser/reference-objects.ts`, the walk every Reference Object takes (#384). The scheme is read under the referencing key with the target's definition, so `petKey: { $ref: '#/components/securitySchemes/sharedKey' }` beside `sharedKey: { type: apiKey, in: header, name: X-Key }` yields `{ kind: 'apiKey', schemeName: 'petKey', in: 'header', name: 'X-Key' }` beside `sharedKey`'s own entry, in document order, and a requirement naming `petKey` joins to it. A `description` written beside the `$ref` overrides the target's on 3.1 and is ignored on 3.0 (`siblingDocsMode`), as beside every Reference Object. A ref the map does not answer — a pointer into another section (`#/components/schemas/Pet`), or a `$ref` that is not a string — is omitted with the same `[oagen] Warning: Unsupported security scheme` diagnostic, naming the ref and how the walk ended (`($ref #/components/schemas/Pet unresolved)`); one that names no component at all, or a cycle of refs, fails the bundle before parsing, as any dangling ref does.

The differ compares `auth` between two documents by `schemeName` (#384), since a requirement only names a scheme and the definition says what a request carrying it puts on the wire. A scheme the new document declares and the old did not is `security-scheme-added`: breaking when the old document already had the scheme in use under a definition the parser omits (every old request carried `openIdConnect`, say, and not the `apiKey` the new definition reads), additive otherwise. One the old declared and the new does not is `security-scheme-removed`: breaking when the scheme is in use in the old document — named by the effective requirement list, `node.security ?? spec.security ?? []`, of one of its operations, webhooks or callbacks (every callback of every operation and webhook, nested ones included; see [Callback](#callback)), so the document default counts only through a node that inherits it — or a requirement in the new document still names it; additive when nothing read it on either side. One both declare whose definitions differ in anything but `description` and `x-*` keys is `security-scheme-modified`, with `oldScheme`/`newScheme` and a `details` line (`apiKey in header "X-Key" → in header "X-Api-Key"`, `apiKey → http basic`, `oauth2 flows changed`, `oauth2 scopes changed; required scope "write:pets" removed`): breaking when its wire form regressed and the scheme is in use in the new document, additive when nothing in the new document uses it or the definition only grew. The wire form is the `kind`; an `apiKey`'s `in` and `name`, a header's name folded by `foldHeaderName` since HTTP header names are case-insensitive, so `X-Key` → `x-key` is reported but additive while a query or cookie name is compared as written; and an `oauth2` scheme's `flows`, their `x-*` keys dropped, read as `security-changed` reads a requirement's alternatives — a flow added, or a `refreshUrl` added to a flow that had none, is additive; a flow removed, or a URL a flow declared changed or removed, is breaking — with each flow's `scopes` left to the requirement that names them: a scope added, re-described, or removed while no requirement names it is additive, and one the old definition offered, the new does not, and a requirement in the new document still names is breaking. A scheme a webhook's or a callback's requirement names is in use as one an operation's names is: a changed header name breaks the handler as it breaks a caller. The three kinds are listed after the document's `security-changed` change and before the models, and each is mirrored into `behaviorChanges` as a `security-scheme-changed` entry with the definition on each side that declares it. The schemes omitted from `auth` are invisible to that comparison except as the old side of an added scheme or the new side of a removed one — a `digest` scheme changing its realm is no change — and `auth` absent and `[]` both read as no schemes. See [docs/cli.md](../cli.md) for the rule with the issue's example and exit codes.

## HttpMethod

```typescript
type HttpMethod =
  "get" | "post" | "put" | "patch" | "delete" | "head" | "options" | "trace";
```

All standard HTTP methods are supported. Emitters should handle `head`, `options`, and `trace` appropriately (e.g., HEAD returns no body).

## PaginationMeta

```typescript
type PaginationStrategy = "cursor" | "offset" | "page" | "link-header";

interface PaginationEndOfIteration {
  kind: "hasMore" | "totalPages" | "totalCount";
  path: string; // Dotted path from the response root, like dataPath: "has_more", "pagination.totalPages"
}

interface PaginationMeta {
  strategy: PaginationStrategy;
  param: string; // Query param that selects the page (e.g., "after" for cursor, "offset" for offset, "page" for page)
  limitParam?: string; // Page-size param (offset and page strategies, e.g., "limit")
  pageStart?: number; // First page number (page strategy only): the param's default, else its minimum, else 1
  dataPath?: string; // JSON path to the data array (e.g., "data", "results") — undefined means the response IS the data
  dataDescription?: string; // The data array property's own description, when it declares one
  itemType: TypeRef; // Type of each item in the paginated list
  envelopeFields?: Field[]; // Every envelope property besides the data array, in document order
  endOfIteration?: PaginationEndOfIteration; // Response field that ends the iteration, when one is recognized
}
```

Present on `Operation` when pagination is detected. The `strategy` discriminant tells emitters how an auto-paging iterator reaches the next page:

| Strategy      | Detected from                                                  | Next page                                                                       |
| ------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `cursor`      | a cursor-like query param (`cursor`, `after`, `page_token`, …) | send the cursor the previous response returned in `param`                       |
| `offset`      | `offset` or `skip` plus a page-size param                      | add the number of items received to `param`; send the page size in `limitParam` |
| `page`        | `page`, `page_number` or `page_num` plus a page-size param     | send `pageStart` first and add exactly one per request                          |
| `link-header` | never detected — set through an override                       | follow the RFC 5988 `Link: <…>; rel="next"` response header (e.g., GitHub API)  |

A cursor param wins over an offset param, which wins over a page param, when an operation declares more than one; a page or offset param without a page-size param (`limit`, `page_size`, `per_page`, `size`, `count`) is not pagination, and neither is a list envelope on its own. An iterator is driven only by a query parameter the operation declares — the one detection found, or the one an override names (see Overriding detection) — never by one guessed from the response. An operation that returns a recognized envelope but declares no such parameter (`GET /pets?page` returning `{ data, total_pages }`; `GET /waitlists` with no query parameters at all) has no `pagination`: the envelope is kept as a plain response model carrying every field, exactly as `strategy: 'none'` keeps it, so the wire shape survives, and one `[oagen] Warning:` names the operation and what is missing (`"page" is declared without a page-size parameter`). Declaring the parameter, or an `x-pagination`/`operationHints` entry naming a declared one (`{ strategy: 'page' }` on `GET /pets?page`), gives the iterator back, built around that envelope.

`pageStart` is set for the `page` strategy only: the page parameter's integer `default`, else its `minimum`, else 1 (`?page=0` APIs declare `default: 0` or `minimum: 0`), or whatever an override sets — an override may set it under the `page` strategy only; one that sets it under another strategy is unusable (see [Overriding detection](#overriding-detection)). The keywords are read from the parameter's schema as written — the schema's own value, then the component a `$ref` names, then `allOf` members in declaration order, then the non-null variant of a nullable wrapper — so a `default: 0` behind `allOf: [{ $ref }]` or a `$ref` into `components.parameters` still counts. Emitters read `pageStart` instead of re-deriving the base.

Every iterator stops on an empty page. `endOfIteration`, when present, lets it stop one request sooner:

- `hasMore` — a boolean that is `false` on the last page.
- `totalPages` — an integer count of pages; stop once the pages fetched so far reach it. Under `page` that is `page - pageStart + 1 >= totalPages` (`page >= totalPages` for a 1-based API, `page + 1 >= totalPages` for a 0-based one); under `offset` it is `floor(offset / limit) + 1 >= totalPages`; under `cursor`, whose opaque cursor carries no page number, it is the number of requests made so far `>= totalPages`.
- `totalCount` — an integer count of items; stop once the items received so far reach it.

It is detected from a recognized envelope — a boolean `has_more`/`hasMore`/`has_next`/`hasNext`/`has_next_page`/`hasNextPage`, an integer `total_pages`/`totalPages`/`page_count`/`pageCount`, or an integer `total`/`total_count`/`totalCount`/`total_items`/`totalItems`/`total_results`/`totalResults`, each in any spelling (its snake_case form is matched, as a companion's is below: `HasMore`, `has-more` and `HAS_MORE` are `has_more`, so `{ data, PageInfo: { HasNextPage } }` stops on `PageInfo.HasNextPage`) — beside the array first, when the `dataPath` is nested: the other properties of the object the array sits in, under whatever name (`result.total_pages` beside `result.items`, `data.page.has_more` beside `data.page.items`), then those of each object the path passes through on its way there, nearest the array first (`result.total_pages` beside `result.page` for `result.page.items`), every one reached as the path itself is resolved — one property walk (`collectObjectProperties`) reads a wrapper's companions, its stop field, each metadata companion and every segment of a `dataPath`, through `$ref`s, `allOf` members and nullable wrappers, settling a name two members declare as the model does (`combineDeclarations`); then at the top level; then one level down inside each top-level companion object whose name says it is pagination metadata (`meta`, `pagination`, `page_info`, `cursor`, …, in any spelling: the name's snake_case form is matched, so `pageInfo`, `PageInfo` and `page-info` are read exactly as `page_info` is — `{ data, pageInfo: { hasNextPage } }` is `string[]` with a `PageInfo` model and the stop field `pageInfo.hasNextPage` — while a name whose snake_case form carries none of these words (`nameTag`, whose `name_tag` spells `meta` only across a word boundary) marks no envelope, so `{ data, nameTag }` is a plain `ListPetsResponse` model; a name is read as several words only where it separates them, by a change of case or a separator such as `_` or `-`, so no pattern or stop-field name of several words is found in a name that runs them together: `pageinfo` and `PAGEINFO` are no `page_info` and `hasmore` is no `has_more`, so `{ data, pageinfo: { hasNextPage } }` and `{ data, hasmore }` are plain `ListPetsResponse` models, while a one-word pattern is still found inside such a name (`listmetadata` holds `meta`); inline, `$ref`, `allOf`, or a nullable wrapper) — a `stats.total` beside `pagination.page` is not the list's size, and nothing the path passes through, the array or an object on the way to it, is ever a stop field — and the path follows the `dataPath` convention, each segment spelled as the document spells it (`pageInfo.hasNextPage`); a name holding a `.` cannot be one segment of such a path, so it is never a stop field and a companion so named is not looked inside (`{ data, 'has.more', total }` stops on `total`, and `{ data, 'has.next' }` is no envelope). The body an explicit `dataPath` keeps as a wrapper (below) is read the same way. A stop field declared only by the variants of a `oneOf`/`anyOf` written beside an `allOf` or as one of its members — a body the parser reads as one model, the variants' properties its optional fields (see Inline `allOf` below) — is read when every non-null variant declares it with the kind's type, each variant's declaration tested in turn where their union is what types the field — a declaration that types itself is tested as written, so `total: { type: 'integer', anyOf: [{ maximum: 100 }, { minimum: 200 }] }` is the integer its `type` says, the union only limiting it, and a union reached again through another variant — `has_more: { $ref: Flag }` beside `has_more: { anyOf: [{ $ref: Flag }, { type: 'boolean' }] }`, `Flag` an `anyOf` of boolean consts — is a shared reference, read in each, only a union that reaches itself fitting nothing — as the walk to `meta.has_more` tests the field it lands on in every variant (so `has_more: { type: 'boolean', const: true }` in one variant beside `{ type: 'boolean', const: false }` in the other, or `{ $ref: Flag }` beside `{ type: 'boolean' }`, stops the iteration as `{ data, has_more: { type: 'boolean', const: true } }` written flat does, and an explicit `endOfIteration` naming it is kept): `{ allOf: [{ data }], oneOf: [{ has_more }, { has_more, total }] }` stops on `has_more` exactly as `{ data, has_more?, total? }` does, whichever keyword and in whichever order the two are written, through `$ref` variants (`oneOf: [{ $ref: CursorMeta }, { $ref: PageMeta }]`, each component declaring `has_more`) and inside a metadata companion (`meta: { allOf: [{ trace_id }], oneOf: [{ has_more }, { has_more, next }] }` stops on `meta.has_more`) alike; a stop field only some variants declare (`oneOf: [{ has_more }, { total }]`), or one they type differently (`oneOf: [{ has_more: boolean }, { has_more: string }]`, the field typed `boolean | string`), is an optional field of the envelope and no stop field — the iterator stops on an empty page, and an explicit `endOfIteration` naming it is rejected by the same rule (see Overriding detection) — while a member's declaration stands whatever a variant says, since a variant can only narrow what every instance carries (#622). When several candidates exist, `hasMore` beats `totalPages`, which beats `totalCount`. List-envelope recognition shares that list of names and reads a name the same way, so an envelope whose only companion is a stop field in any spelling — `{ data, has_more }`, `{ data, hasMore }`, `{ data, HasNext }`, `{ data, page-count }` — is recognized like any other: unwrapped when a declared query parameter drives the iterator, kept as a plain response model when none does (see the strategy table above).

The `dataPath` is dynamically detected from the response envelope — when `undefined`, emitters should treat the entire response as the data array or use their own default.

When the parser recognizes an inline list envelope — one array property plus a companion that looks like pagination metadata (a stop field in any spelling — `has_more`, `HasMore`, `total`, … — or a name whose snake_case spelling contains `meta`, `pagination`, `cursor`, `page_info`, `total`, `offset`, …, `pageInfo` and `page_info` alike) — and a query parameter the operation declares drives the iterator (the one detection found, or the one an override names), `Operation.response` becomes the bare array, and `envelopeFields` keeps everything else the envelope carries; an envelope nothing pages stays one plain response model, with no `pagination` (see the strategy table above). The envelope is recognized off the property set its model is built from: the `allOf` members' own properties and, for a `oneOf`/`anyOf` written beside the `allOf` or as one of its members (the one model such a body is, see Inline `allOf` below), every property the variants declare, the model's optional fields — so `{ allOf: [{ data }], oneOf: [{ has_more }, { has_more, total }] }` is `Pet[]` with `dataPath: 'data'`, `envelopeFields` `has_more?` and `total?` and the stop field `has_more`, exactly as `{ data, has_more?, total? }` is, with the `oneOf` written before or after the `allOf`, as an `anyOf`, or as a member (`allOf: [{ data }, { oneOf: [...] }]`) alike, and `oagen diff` between the two documents reports nothing (#622; before, detection read the members' own properties alone, so the body stayed the model `ListPetsResponse { data, has_more?, total? }` and the iterator yielded it). The array must be there whichever variant the wire sends — a member's, or declared by every non-null variant with one shape, as an explicit `dataPath` is resolved through a union — so `{ allOf: [{ has_more }], oneOf: [{ data }, { data, total }] }` is unwrapped on `data` while `oneOf: [{ data }, { total }]` leaves the body the model `{ has_more, data?, total? }`, and the body is unwrapped only on the array the companion walk reads at that name, the one `extractListResponse` unwraps on — a declaration a `$ref` member's component or a nested `allOf` member makes stands over the variants' there as in the model, an always-applying declaration over a branch-only one, so `allOf: [{ $ref: Base }, { oneOf: [{ data: integer[], has_more }, …] }]` with `Base: { data: { description } }` (or `data: { x }`) is no envelope but the model `{ data?, has_more?, … }`, while `Base: { data: integer[] }` is unwrapped on `Base`'s array, and every other property detection read must be no array there, so `Base: { has_more: integer[] }` beside variants typing `has_more` `boolean` is two arrays and no envelope, as `{ data, has_more: integer[] }` written flat is; a companion may be any variant's, and a stop field only some variants declare is a companion without being a stop field (see `endOfIteration` above). A bare `oneOf`/`anyOf` body, with or without `properties` beside it, is a union of models, never an envelope, and so is an `allOf` the parser reads as its lone union member (`allOf: [{ oneOf: [...] }]`, with or without annotations beside it: the body is that union, see Inline `allOf` below), so the variants are read only for an `allOf` the parser merges; a `$ref` member — with whatever is written beside its reference (`{ $ref: Base, oneOf: [A, B] }`, `{ $ref: Base, properties: { data } }`), which the model and the companion walk ignore for the component it names, so a `data` such siblings declare marks no envelope and the body stays the model the sibling-less document builds — is not read by detection, as before, while a nullable wrapper a member writes (`oneOf: [{ has_more }, { type: 'null' }]`, or `{ enum: [null] }` on OAS 3.0) is read as its one non-null variant, as the model and the companion walk read it: `allOf: [{ data }]` beside it is `Pet[]` stopping on `has_more`, as `allOf: [{ data }, { has_more }]` is, with one non-null variant as with two, and `oagen diff` between the two spellings reports nothing (a `$ref` variant of the wrapper is a `$ref` member, unread). The array property is an array in any spelling, and two `allOf` declarations of it — one nullable, one not; one with `items`, one with limits alone — merge as the arrays they wrap (their `items` combined by the rule two declarations of a property follow, so a typeless `items` only annotates a typed one; `null` admitted when either side admits it): `type: 'array'`, `items` with no `type`, or either under a nullable wrapper — `type: ['array', 'null']`, OAS 3.0 `nullable: true`, or a `oneOf`/`anyOf` with a `null` variant in any spelling (`{ type: 'null' }`, `{ const: null }`, `{ enum: [null] }`), with or without `items` beside it — in which case `response` is `nullable<array<Item>>` while `itemType` is still the element (`ListEventsItem[] | null`, `dataPath: 'data'`). Any of these, or a `$ref` to an array component, is still the array when written as an `allOf` that `schemaToTypeRef` reads as its member (`readInlineAllOf`: one member with nothing beside it that adds to it, or `$ref` members with nothing inline beside them), at any depth and on either side of a nullable wrapper, as a field of that schema is typed: `allOf: [{ type: 'array', items: Pet }]` is `Pet[]` and `allOf: [{ oneOf: [{ type: 'array', items: Pet }, { type: 'null' }] }]` is `Pet[] | null`, each with `dataPath: 'data'`. A `data` written as a JSON Pointer deeper into a component (`{ $ref: '#/components/schemas/Holder/properties/owners' }`; #609) is the array when the schema it lands on is typed as an array where it stands — any of these spellings, a `$ref` to an array component, or another such pointer, under the same wrappers — read ahead from the document as the settle will type it (`isArrayPointerRef`, `pointerTypesAsArray`; see Schema `$ref`s below), the declaration a `properties/<name>` step ends at read as the merged field it settles to (`Holder/allOf/1/properties/owners` to a member that only describes `owners` beside one that types it `Owner[]` is the array), so the envelope is unwrapped on it exactly as on `{ $ref: Owners }`: `response` is the array the pointed schema is typed as once settled, with its own nullability and its limits conjoined with those written beside the pointer, and `itemType` its items — the model the pointed schema's items built (`HolderOwner` for `Holder: { owners: { name }[] }`), never a copy of it. So `{ data: { $ref: '#/components/schemas/Holder/properties/owners' }, has_more }` with `Holder: { owners: Owner[] }` is `Owner[]` with `dataPath: 'data'`, `itemType` `Owner` and `has_more` among `envelopeFields`, as `data: { $ref: Owners }` and `data: Owner[]` are, and `oagen diff` between the three spellings reports nothing; a pointer to no array (`Holder/properties/owners/items`), one that leads nowhere (reported at the site, as any pointer that leads nowhere is) and a chain of pointers that reaches itself leave the body a plain response model, as any other non-array `data` does; beside another array property it is a second array, so `{ data: Pet[], related: { $ref: '#/components/schemas/Shelter/properties/pets' }, has_more }` is no envelope and stays a plain model, as beside `related: { $ref: Pets }`. Its items, whatever their shape, are typed as `<Op>Item` (see Inline model naming) when the array is written inline; a `$ref` to an array component or a pointer takes the items that reference resolves to. `envelopeFields` keeps everything else the envelope carries: the pagination companion (`list_metadata`, `pagination`, `has_more`, `total`, …) and any discriminant such as `object: "list"`. Each entry is an ordinary `Field` (wire name, type, `required`, description), so `dataPath` + `itemType` + `envelopeFields` together describe the full shape of what the endpoint returns, and an emitter can both type the response and read the page details it needs for the next request:

```typescript
// GET /customers?page=&limit= → { customers: Customer[] ("The customers on this page."), pagination: { page, totalPages } }
op.pagination = {
  strategy: "page",
  param: "page",
  limitParam: "limit",
  dataPath: "customers",
  dataDescription: "The customers on this page.",
  itemType: { kind: "model", name: "Customer" },
  envelopeFields: [
    {
      name: "pagination",
      type: { kind: "model", name: "Pagination" },
      required: true,
    },
  ],
  endOfIteration: { kind: "totalPages", path: "pagination.totalPages" },
};
```

A companion that is an inline object is lifted to a model. The same envelope recurs on every list endpoint of an API, so copies that agree structurally share one model named from the property alone (`list_metadata` → `ListMetadata`, `pagination` → `Pagination`) rather than one per operation as list items are (`ListUsersItem`). The bare name is taken only where it cannot change another type's shape. A copy collapses onto a target only when the target admits every value the copy can hold: the same limits and type parameters on the model itself (`modelPropertiesAdmit`, as a component fold reads them: a copy declaring `minProperties: 1` never shares a target declaring `2`, nor the reverse), the same fields with the same types and, on each field, the same `deprecated`, limits, default and access flags — everything but the type read as a component fold reads it (`fieldPropertiesAdmit`; a copy that deprecates or limits a field the target does not, or the reverse, keeps its own name, since the target's definition is what every site reads after the fold) — where the target may be looser (optional where the copy requires, nullable where the copy is not) but never stricter. When a component model of that name exists, the copies it admits collapse onto the component as written — a deprecated copy included when the component is live and the copy's nested models agree with the component's on the flag, the envelope field keeping the flag the schema wrote, while a deprecated component takes no copy of either flag (#441; a deprecated model a component's field minted, standing in for a component, takes a deprecated one); otherwise the most common shape becomes the target. Any other copy keeps its operation-qualified name (`ListUsersPagination`). An inline enum in a companion is qualified by operation exactly like a parameter enum (`ListUsersSortOrder`). Companions declared through an `allOf` `$ref` branch are resolved against the component schemas, and a companion declared by more than one branch merges both declarations. Models and enums reached only through `envelopeFields` count as referenced for emission, service assignment, compat scoping, and the differ's request/response direction.

The data array property's own description, when it declares one, is kept beside `dataPath` as `dataDescription`, so an emitter documenting what a list method returns (an `@returns` tag, say) reads it from the IR like the companions' descriptions rather than from the document. As with a `Field`'s `description`, it is the property's text and never the item schema's; an inline item object's description is on the lifted item model.

`envelopeFields` is absent when the response is a bare array, when the response is a `$ref` to a component schema (the wrapper model itself carries the companions), or when pagination was inferred from query parameters alone. `dataDescription` is absent in the same cases — the wrapper model's own data field carries the description — and whenever the data property declares none.

### Overriding detection

An `x-pagination` extension on the Operation Object, or the `pagination` entry of the operation's `operationHints["METHOD /path"]` in `oagen.config.ts`, states the pagination explicitly when the name-based guess is wrong. Both take the same object (`PaginationHint`), and precedence is per field — config hint, then `x-pagination`, then detection — so `{ strategy: "page" }` alone corrects the strategy and keeps the detected parameters, envelope and end-of-iteration field.

```yaml
# In the spec, for authors who can annotate it
paths:
  /pets:
    get:
      x-pagination:
        strategy: page # cursor | offset | page | link-header | none
        param: page # must be a query parameter of the operation
        limitParam: limit
        pageStart: 1 # page strategy only; defaults to the param's default, else minimum, else 1
        dataPath: pets # resolved against the response; the array's element type becomes itemType
        endOfIteration: { kind: totalPages, path: pagination.totalPages } # a field of the response, of the kind's type
```

```ts
// In oagen.config.ts, when the spec cannot be changed
export default {
  operationHints: {
    "GET /pets": { pagination: { strategy: "page" } },
  },
};
```

`strategy: "none"` turns pagination off for the operation. The decision is made before the response is classified, so a list envelope is not unwrapped: the body becomes one plain response model carrying every field (`pets`, `pagination`, …), exactly as a non-list body does, and nothing about the wire shape is lost. A recognized envelope that is kept — by `strategy: "none"`, for want of a declared paging parameter, or under an explicit `dataPath` that names another array — takes that one reading and never the single-resource one: `{ data, pagination: { type: "pagination", total } }` with `required: ["pagination"]` fits the single-resource wrapper shape (one required object with a constant `type`/`object`), and reading it that way would make the pagination object the whole response and drop `data`.

An explicit `dataPath` is resolved against the primary response (the lowest 2xx with a typed body, the one `Operation.response` describes — not whichever 2xx is declared last) and the element type of the array it lands on becomes `itemType`, so a wrapper with `pets: Pet[]` iterates `Pet` rather than the wrapper. The path is walked through `$ref`s, `allOf` members and nullable wrappers at every segment and, where an object on the way does not declare the next segment itself, through each non-null variant of a `oneOf`/`anyOf` that object is or has among its `allOf` members — and, where a variant is itself a union, written inline or a `$ref` to a union component, through each of its own non-null variants in turn, however deep — the one walk an explicit `endOfIteration` makes (below): `result.items` resolves on `{ result: { oneOf: [A, B] } }` when `A` and `B` each declare `items: Pet[]`, since whichever variant the wire carries the array is there, and so does `result.items` on `{ result: { anyOf: [{ oneOf: [A, B] }, B] } }`, or with that first variant written `$ref: PetPage` (`PetPage: { oneOf: [A, B] }`), and `itemType` is `Pet`, read on the IR side through each variant's model (`ListPetsResponseResult.items` and `ListPetsResponseResultWithTotal.items`); a `null` variant is set aside as a nullable wrapper is, and the body itself may be the union (`dataPath: 'items'` on `{ oneOf: [A, B] }`). A path that crosses the same union at segment after segment (`next.next.items` through two models whose `next` is a `oneOf` of both) reads each model once per segment, however long the path, and a component that several variants reference (`anyOf: [{ $ref: Next }, { $ref: Next }]`, twenty components deep) is read once, however many routes through nested unions reach it. Every variant must declare the segment, as an array, and the arrays must agree on their items, each read as the type builder reads an array's `items` — a nullable wrapper and an `allOf` of one member that types it collapsed, however the two alternate, so `{ allOf: [{ $ref: Pet }], description: 'A pet' }`, the OAS 3.0 way of describing a `$ref`, is the same `Pet` as `{ $ref: Pet }` or the OAS 3.1 sibling form `{ $ref: Pet, description: 'A pet' }` — the same component (`$ref: Pet` in both) or the same inline shape, descriptions and extensions aside, admitting `null` alike — since the SDK iterates one item type whichever variant arrives: a variant that lacks the array (`{ oneOf: [{ items }, { total }] }`), declares it as something else, or types its items otherwise (`Pet[]` in one variant, `Cat[]` in another, or `Pet[]` beside `(Pet | null)[]`) makes the override unusable, with a warning that says which variant lacks the field (`variant 2 of the oneOf at "result" declares no "items"`, counted as written, `null` variants in place; below a variant that is itself a union, the variant of its own that lacks it: `variant 2 of the oneOf in variant 1 of the anyOf at "result"`) or how the variants type it (`the variants of "result" type its items as Pet and Cat`). Detection reads nothing inside a union — no stop field is found beside `result.items` there — so such an iterator stops on an empty page unless the override names its `endOfIteration`, which is walked the same way. Inline items the variants declare alike are typed from the document under the path-derived name (`ListPetsResultItem`), since each variant's model types them under a name of its own. The IR is consulted first — the detected data array, an envelope companion's fields, or the response model's fields, through the models a component's fields mint too (`result.items` through a `result` two `allOf` members of `PetPage` conjoin yields the `PetPageResultItem` that `PetPageResult.items` holds), under every nullable wrapper a type wears (two for a site settled from a pointer to a schema that admits null; see Schema references) and, for a union a type list produced (`type: ['object', 'string']`), through its object member, as the document walk reads such a schema's `properties`, and through a named union's variants (`Page: { oneOf: [{ $ref: Result }, { type: null }] }`, a model with the one variant `Result` and no fields, reads `Result`'s, so a response `$ref: Page` or a pointer settled to `nullable<Page>` with `dataPath: 'items'` iterates `ResultItem`; each named union is read once per walk, however many routes through other unions reach it, as the document walk reads a component once) — so the item model the parser already created is reused; the document (through a root `$ref` wrapper, `allOf` members and nullable wrappers) is read only when the path crosses a model not yet materialized (an array component's, say) — never one not yet settled: a reference a schema `$ref` deeper into a component leaves pending (see Schema references) on the way — the response itself written as `{ $ref: '#/components/schemas/Holder/properties/result' }` with `dataPath: 'items'`, or a field of an inline body written so with `dataPath: 'result.items'` — names a model the parser has built and reaches once the pointer is settled, so the item type is decided at the settle, from the settled types (`settleDeferredDataPathItemType`), and is `HolderResultItem`, the very type `HolderResult.items` holds, never a `ListOwnersItem` copy of it read from the document (#608), exactly as a response written `$ref: Result` iterates `ResultItem` — except where the path goes on through the variants of a union to more than one array (`Holder.result: { oneOf: [A, B] }`, each declaring `items` of its own), which is read from the document at extraction as such a union is when the IR already holds it, since each variant's model types inline items under a name of its own (`AItem`, `BItem`) and only the document types them once (`ListOwnersItem`), while a `$ref` or primitive the variants share (`Pet`, `string`) is the one type either walk yields; variants that reach one array are no fork — every variant holding the same pointer (`{ oneOf: [A, B] }` with `A.result` and `B.result` both `{ $ref: '#/components/schemas/Holder/properties/result' }` and `dataPath: 'result.items'`), or pointers resolving to one component — and iterate `HolderResultItem`, the one model the pointed schema's items are built as, exactly as both holding `$ref: Result` iterate `ResultItem`; a path the settled types reach no array through (a pointer typed `unknown` where it stands, such as an inline `allOf` member) yields `unknown`, with a warning (`[oagen] Warning: dataPath "result.items" on Owners.listOwners reaches no array in the response once its schema $ref is settled — typing the iterator's items as unknown`) — and inline items found that way — a plain or nullable object, the object variants of a union, the objects of a nested array or map, and whatever those reference in turn — are materialized under a name derived from the path as the inline extractor names a field's items (`result.items` → `<Op>ResultItem`, `records` → `<Op>Record`), never the bare `<Op>Item` the envelope's own data array owns, so the item type never names a model the parser did not create. Such an item type is a reference nothing else in the IR holds, and the parser's later passes reach it on its own: an inline enum it is (or holds) is promoted to `spec.enums` under the path-derived name, stepping past a component enum with other members as a header enum would; a `…Json` model it names follows the Json-suffix fold; and an unresolved model in it is reported under `pagination.itemType`.

`param` is resolved in this order: the override's own, else the first query parameter the operation declares under the strategy's own names (`page` for `page`, `cursor`/`after`/… for `cursor`, `offset`/`skip` for `offset`), else the detected one — so `{ strategy: 'page' }` on `GET /pets?page` drives `page`, which detection alone makes no iterator of for want of a page size, and `{ strategy: 'cursor', param: 'c' }` on `GET /pets?c` iterates on a parameter detection does not know. The resolved `param` and `limitParam`, not only explicit ones, must be query parameters the operation declares, and must be two different ones: `{ param: 'limit' }` beside a detected `limitParam: 'limit'` is rejected, since one parameter cannot carry both the page and the page size. In both cases the override is what creates the iterator, and it is built around the envelope detection unwrapped: `dataPath`, `dataDescription`, `itemType`, `envelopeFields` and the stop field come from the response exactly as they do for a detected iterator.

An explicit `dataPath` that names another array than the one the parser would unwrap (`{ data, result: { items }, total }` with `dataPath: 'result.items'`) means detection was wrong for the operation, so the envelope is kept as a wrapper, exactly as `strategy: 'none'` keeps it: `response` is the wrapper model (what the wire returns), `dataPath` says where the items are in it, `itemType` is their type, and `envelopeFields` is absent since the wrapper carries the companions; the wrapper's stop field is still read (`total` → `endOfIteration`), also when the override is what creates the iterator — no paging parameter recognized, say a custom `param: 'p'` — rather than correcting a detected one. The stop field is read from whatever wrapper the override iterates, not only from an envelope detection recognized: a `$ref` list response (`PetList: { data: Pet[], has_more }` returned as `$ref: PetList` with `dataPath: 'data'` → `has_more`) and an inline body detection does not recognize because no top-level array sits beside a stop field (`{ result: { items: Pet[] }, total_pages }` with `dataPath: 'result.items'` → `total_pages`) are read exactly as a recognized envelope is — through the `$ref`, every `allOf` member however deep, and a nullable wrapper around the body or around any member (`{ allOf: [{ oneOf: [{ $ref: Base }, { type: 'null' }] }, { properties: { data } }] }` reads `Base`'s `has_more`, as does a `$ref` chain ending on such a wrapper) — keyed by the full path, so the array the override names is never taken for a stop field. A nullable `allOf` member applies as its one non-null variant for the model too, as a component and as an inline body: the wrapper's model carries `Base`'s `has_more` beside `data`, and a recognized envelope's `envelopeFields` carry what such a member declares (`trace_id` from a nullable `Meta`), so the fields an iterator stops on are fields the model declares. The array may sit under a nullable wrapper of any form — `type: ['array', 'null']`, OAS 3.0 `nullable: true`, `oneOf: [{ type: 'array' }, { type: 'null' }]`, a nullable `$ref` to an array component — and the document is read through the same wrappers the IR walk reads through, so whether the path reaches an array is decided once, the same way, before the body is classified and when its items are typed. A `dataPath` that restates the detected one changes nothing, and one that reaches no array leaves the envelope unwrapped and is ignored with a warning. Because a kept wrapper is not a recognized envelope, such an override needs a strategy from somewhere — its own, or the operation's query parameters. Whether an override can apply at all is decided before the response is read, against the pagination the query parameters alone yield (a parameter the operation does not declare never makes one usable), so an override that is rejected leaves the response exactly as detection reads it — kept as a plain response model when no declared parameter pages it, with the rejection as the one warning. When the override is the only possible source of an iterator (no query parameter yields one) and a 2xx body cannot satisfy it — its `dataPath` reaches no array in that body, or its `endOfIteration` resolves in it to no field of the fitting type (below) — that body's envelope is kept the same way rather than unwrapped for the iterator the dropped override would have made. `dataDescription` survives an override that keeps the detected array, and the stop field beside a nested array an override selects (`result.total_pages` next to `result.items`, `pagination.has_more` next to `pagination.items`) is read first, whatever the parent is called, then one beside each object further up the path, nearest first (`result.total_pages` next to `result.page` for `result.page.items`); a stop field wrapped in a nullable `oneOf` (`[{ type: 'boolean' }, { type: 'null' }]`), behind a `$ref`, or behind a lone `allOf` member that types it (`has_more: { allOf: [{ $ref: Flag }], description }`, or an inline `{ allOf: [{ type: 'boolean' }] }`, read as the member exactly as the IR types the field; an `allOf` of several members, of bare limits beside the field's own `type`, or of a lone `$ref` member with a `required` beside it that the component's properties can satisfy — the merged model the IR builds — is left as written), however the three alternate, is read like one declared with a type list, and a component that refers back to itself (`Flag: { oneOf: [{ $ref: Flag }, { type: 'null' }] }`) ends the walk rather than looping on it, as a stop field or as any other companion.

and of a variant that is itself a union in turn, An explicit `endOfIteration` is checked against the primary response as a detected one is read: its `path` starts from the property map a detected stop field is read from — the body's own properties and every `allOf` member's, through `$ref`s and nullable wrappers, with what every non-null variant of a `oneOf`/`anyOf` the `allOf` flattens declares (`has_more` on `{ allOf: [{ data }], oneOf: [{ has_more }, { has_more, total }] }` resolves; one only some variants declare, `oneOf: [{ has_more }, { total }]`, does not, and one they type differently is not of the kind's type; #622), for a recognized envelope and for a wrapper kept under an explicit `dataPath` alike — and is walked from there exactly as an explicit `dataPath` is (above): through `$ref`s, `allOf` members and nullable wrappers at every further segment, and, where an object on the way does not declare the next segment itself, through each non-null variant of a `oneOf`/`anyOf` that object is or has among its `allOf` members, since whichever variant the wire carries the field must be there: `meta.has_more` resolves when every variant of a `oneOf` `meta` declares `has_more` (a field detection does not read, so the override is how an iterator stops on it), also when a variant is itself a `oneOf` whose every variant declares it (`meta: { anyOf: [{ oneOf: [A, B] }, B] }`, or that variant a `$ref` to `MetaPage: { oneOf: [A, B] }`), and when that `oneOf` is one `allOf` member of `meta` beside others (`{ allOf: [{ oneOf: [A, B] }, { properties: { trace_id } }] }`, which detection reads too since #622, so there the override restates the detected `meta.has_more`), through each keyword of a member writing both (`{ allOf: [base, { oneOf: [a, b], anyOf: [cursor, page] }] }` resolves `meta.has_more` through the `anyOf`, as the model reads both keywords; a nullable axis beside the other keyword is its one variant, read as one more member, so `{ oneOf: [a, { type: 'null' }], anyOf: [cursor, page] }` resolves it too; before, a member writing both was one union read by its `oneOf`, and the path resolved to no field the model has), since an instance carries every member whichever variant it is, with `A` and `B` written inline or as `$ref`s alike, and whether the `oneOf` is written in the `allOf` or in a component a `$ref` member names (`{ allOf: [{ $ref: MetaUnion }, { properties: { trace_id } }] }`, bare, in a lone `allOf` or under a nullable wrapper): the one model such an `allOf` is flattened into — inline, or a component composed with `allOf`, even of the `oneOf` alone — reads a `$ref` variant's component in as an inline variant and a union a `$ref` member's component carries as that component's model reads it (see Inline `allOf` below; #398, #429), so `Meta` has `has_more` and the iterator stops on a field its type has (#527 rejected the override while the model left those fields out) — provided the model carries the union's fields at all: a union a `$ref` member's component dispatches (its variants pin a const, or the document declares a `discriminator` for it) is left to that component, as the merge leaves it, so `meta: { allOf: [{ $ref: MetaDispatcher }, { properties: { trace_id } }] }` with `MetaDispatcher: { allOf: [{ properties: { base } }, { oneOf: [{ $ref: CursorMeta }, { $ref: PageMeta }] }] }` is `Meta { base, trace_id }`, inline or as a component, and `meta.has_more` resolves to no field however many of the dispatched variants declare it (where `meta: { $ref: MetaDispatcher }` is the dispatcher itself, whose every variant model has it, and the path resolves; #398 review: every union on the way counted, and the iterator was told to read a field `Meta` lacks); the field it lands on, in every variant, must have the type the kind is tested against, a boolean for `hasMore` and an integer or number for `totalPages` and `totalCount`, under a type list (`['integer', 'null']`), a nullable wrapper or a lone `allOf` member too, read as a detected stop field is. A path that resolves to no field of the primary response (`nope.missing`, a field only some variants declare, one only the variants of a union a `$ref` member's component dispatches declare, or any path when the primary declares no body), or to a field of another type (`{ kind: 'hasMore', path: 'total' }` on an integer `total`, a field one variant types otherwise, or the data array itself), makes the override unusable; a field only another 2xx body declares does not count. The two fields that depend on the response — `dataPath` and `endOfIteration` — are decided together, once, against the primary response — the lowest 2xx with a typed body, the entry `Operation.response` describes, chosen by the one rule before any success body is classified, so a `200` whose schema describes nothing yields to a typed `201` for both — and every 2xx body is then read with that one decision: a rejected override is handed to none, so a secondary 2xx is read exactly as detection reads it rather than kept as the wrapper the override would have selected; an accepted one keeps the wrapper in each body its `dataPath` reaches an array in. An override a secondary 2xx could satisfy but the primary cannot is rejected, and so is one that asks of the response when there is no primary (no `responses`, no 2xx or 3xx) or the primary declares no body (a 204, or a 3xx when no 2xx is declared).

An override that cannot be applied is reported as an `[oagen] Warning:` and ignored, leaving the detected metadata in place. In the order checked: a malformed field or an unknown strategy, per source, so the other source still applies; then, on the merged override, no strategy from any source, a `pageStart` under a strategy other than `page`, no `param` from any source, a resolved `param` or `limitParam` the operation does not declare as a query parameter, a `param` and `limitParam` resolved to one parameter, a `dataPath` that does not reach an array in the response — in every variant of a union on the way, and the same array in each — and an `endOfIteration` that fails the check above. One warning names the override's source, the operation and the first of these met; an unknown key is skipped with a warning of its own. Under `strategy: 'none'` only the shape is checked: there is no iterator for the other fields to serve. `envelopeFields` always comes from the response.

## Service & Operation

Service names are derived from OpenAPI tags when present — the first tag on an operation that still has a name once converted to PascalCase names it (e.g., `tags: ["multi-factor-auth"]` → service `MultiFactorAuth`). `Operation.tags` drops every entry that is not a string with non-whitespace content, so `['', 'notes']`, `[' ', 'notes']` and `[42, 'notes']` all name `Notes`; an entry with no ASCII letter or digit, which converts to nothing, stays in `Operation.tags` but is passed over, so `['-', 'notes']` names `Notes` too. When no tag has a name, the operation counts as untagged and the parser falls back to a path segment (e.g., `/organizations/{id}` → `Organizations`), skipping the API root the document's untagged operations sit under. Each untagged path contributes its leading literal segments through the last API marker — `api`, `rest`, or a version such as `v1`, `2.0` or `2010-04-01` — and the root is the longest marker-terminated prefix shared (compared verbatim) by every contribution that no other contribution extends, so a document whose paths all start with `/api/v1/` groups `/api/v1/notes` under `Notes` rather than collapsing the whole API into one `Api` service, and `/wiki/rest/api/content` lands in `Content`. A path that stops short of that root — `/api/openapi.json` or `/api/admin/users` beside `/api/v1/notes` — skips only its own `api` (`OpenapiJson`, `Admin`) and leaves the root at `api/v1` for the rest, so `/api/v1/notes` stays `Notes`; only a second version, `/api/v2/…` beside `/api/v1/…`, shortens the root to `api`, which keeps the versions apart as `V1` and `V2`. The service is named from the first literal segment after the root, so `/v1/notes` and `/v1/{teamId}/notes` share `Notes`, and a custom method written after a colon (`/v1/pets:batchGet`, `/v1/pets/{petId}:adopt`; only a segment's one colon outside a parameter's braces starts one, so `file-{file_path:path}` and `urn:pet:1` are one segment each, and `{name}:a:b` is one literal segment rather than a parameter, so `/v1/{name}:a:b` names `NameAB`) is read as its segment followed by the verb, so both land in `Pets`, while the verb itself never names a service, so `/v1/{name}:cancel` stays in `V1` beside `/v1/{name}` (the slash-written `/v1/{name}/cancel` names `Cancel`); a path with nothing literal after the root (`/api` itself, `/api/{id}`, `/api/v1:reset`) keeps its first segment, `Api`. A path with no marker at all (`/health`, `/openapi.json`) sits outside the root, keeps its own first segment, and does not switch the root off for the rest of the document. A shared prefix that carries no marker is kept whole, since a module prefix every path shares (`/user_management/users`, `/user_management/invitations` → `UserManagement`) is the service, not noise; and `/v1/…` beside `/v2/…` has no shared root, so the versions stay separate services. Tagged operations and path items without an operation take no part. The path-prefix split that carves a tagged service into one per first segment (`/organizations` and `/organization_domains` both tagged `organizations` → `Organizations` and `OrganizationDomains`) is decided over the tag's own operations alone, from the grouping before any service is split: a tag whose operations all sit under one first segment keeps them together even when that segment is not the tag, so `/api/v1/notes` tagged `notes` stays in `Notes`, not `Api`, whatever untagged operations `Notes` picked up by path. An untagged operation keeps the service its path named — it is never moved by a split, and it neither causes nor prevents one — so `/notes` and `/api/v1/notes` meet in `Notes` instead of the latter moving to `Api`, and the collision rules below tell their names apart. A split-off part named like an existing service — another tag's, or a path-named one — joins it, and the operations it brings do not re-split that service. Fallback operation names skip the root and the service segment the same way, so `/api/v1/notes` is `Notes.list`, never `Notes.listV1Notes`; when two path-named operations still share a name in one service and their paths differ only by parameters, the parameters qualify them (`/v1/notes` → `Notes.list`, `/v1/{teamId}/notes` → `Notes.listByTeamId`; see the collision rules under Operation below). Without a root — a root-less document, or a path outside the root — a path-named service is the path's first segment (`Default` when that segment is a parameter) and the fallback name skips the service segment alone, up to those collision rules: an untagged `/{tenant}/users` is `Default.listUsers`, and `/{id}` is `Default.get`. A tagged operation's service is its tag whatever the root, subject only to the path-prefix split above: `/api/notes` tagged `notes` is `Notes.listNotes`. Emitters can further remap service names via an overlay (e.g., `MultiFactorAuth` → `Mfa`) to match existing SDK class names.

`Service.description` comes from the document's top-level `tags` list, matched by name: a tag entry applies to the service whose PascalCase name its `name` converts to, so `user-management`, `User Management`, and `user_management` all map to `UserManagement`. A service whose own name is a declared tag is described by that tag alone — its description when it has one, nothing otherwise — so another tag's wording is never borrowed for it (operations tagged `api_keys` that the path-prefix split merges into `UserManagement` do not label it "API keys"). A service whose own name is not declared, which is what the split produces when it carves `OrganizationDomains` out of operations tagged `organizations`, inherits the description of the first described tag its operations carry. The key is omitted when neither rule yields a description, including for path-named services whose operations have no tag. Malformed `tags` values (a non-array, `null` entries, non-string names) are skipped rather than failing the parse.

`Service.externalDocs` is the tag's `externalDocs` (see [ExternalDocs](#externaldocs)), resolved by the same rule through the same code path: a service named after a declared tag takes that tag's link or nothing, and a split-off service inherits the link of the first linked tag its operations carry. Each field is chosen independently, from the first tag that gives it — among the tags a split-off service inherits from and among several document tags that normalize to one service name — so the description and the link need not come from the same tag, and adding a link to a tag never changes which description a service shows. A tag entry whose `externalDocs` is unusable keeps its description and gives no link.

`Operation.externalDocs` is the operation's own `externalDocs`, present only when it declares a usable one. A Path Item Object has no `externalDocs` field, so an operation that declares none carries none.

An operation's `callbacks` — the requests the API sends back to URLs the caller supplied — are read into `Operation.callbacks`, one `Callback` per HTTP method of each path item under each runtime expression of each key, in document order, each a `Webhook` tied to the operation and named from the operation's stem (`CreatePetPetAdoptedPayload`); a `webhooks` operation's are read into `Webhook.callbacks` the same way. A callback is not an SDK method. See [Callback](#callback) for the rule.

An operation carries its OpenAPI `summary` and `description` in two fields, each read from the Operation Object and, when the operation declares none with content, from the Path Item it sits on (the `paths` entry itself, or the Path Item a `$ref` entry leads to; see [Path Item references](#path-item-references)) — OpenAPI defines a Path Item's `summary` and `description` as applying to every operation on it. The two fall back one by one: an operation with a `summary` of its own and no `description` shows its own `summary` and the Path Item's `description`, and an operation with both shows only its own. Each field is the resolved text alone, as the document writes it: `Operation.summary` is present only when one of the two levels has content, and `Operation.description` is never built from the summary, so an operation that declares only a `summary` has no `description`; a `description` identical to the `summary` (`summary: "Lists notes"` beside `description: "Lists notes"`) is kept in both, since each is the document's own text. A `summary` or `description` that is not a string, or is empty or whitespace-only, is treated as absent at either level — `summary: "List pets"` with `description: ""` yields that `summary` and no `description`, and `summary: ""` on an operation takes the Path Item's — and text that has content is kept verbatim, surrounding whitespace included. An emitter therefore sees the same text whether the document put it on the operation or on its Path Item; one that wants the summary in its doc comment renders `summary` itself, as a one-line label or as a first paragraph above `description`. When a doc URL base is configured, relative links are expanded in `summary` exactly as in `description`.

An operation without an `operationId` is named from its method and path (`GET /orgs/{id}/teams` → `listTeams`), and that name is only as unique as the path words it was built from. An `operationId` is read with every overload marker at its end stripped, whitespace after each included, so `listPets[1]`, `listPets[1][2]` and `listPets[2] [3]` all name `listPets`, never `listPets1`; a marker not at the end (`list[1]Pets`) is kept. One with no ASCII letter or digit left once they are stripped — only whitespace or punctuation (`' '`, `'-'`), or only markers (`'[1]'`, `'[1][2]'`) — camel-cases to nothing, so it names nothing and counts as absent, as `''` does: the operation is path-named (`GET /pets` → `list`), its models are named from its path, `Operation.operationId` is not set, and an `operationIdTransform` is not called with it. What the transform returns for an `operationId` that does name something is read the same way: a result with no ASCII letter or digit once trailing overload markers are stripped (`''`, `' '`, `'-'`, `'[1]'`), or that is not a string, names nothing, and the operation is read as one without an `operationId` — path-named, its models named from its path, `Operation.operationId` not set — after one warning naming the document's id and the operation; so `operationIdTransform: (id) => id.split('.').at(1) ?? ''` names `GET /pets` (`operationId: pets.list`) `list` and leaves `GET /pets/{petId}` (`operationId: getPet`) path-named — `get`, with a `PetsByPetIdGetResponse` and the method name `get_pet` under either `operationNaming` — rather than naming it `''`, and two such operations in one service are told apart by their paths, never renamed `2`. A result that names something is the operation's name as returned. The transform is called once per operation, with the id's trailing overload markers stripped. Within a service, a name taken from an `operationId` is kept as written, and path-derived names that collide with each other or with it are qualified until every path has a name of its own; two operations on one path share a name only when both are path-named and their methods take the same CRUD verb (PUT and PATCH both `update`); a literal is one verb's action whichever methods the document declares on its path — the verb it carries, the first method's in HTTP method order when it carries several, else POST's — so a method of another verb is never read as an action on it and declaring that method takes no name from an operation already there (`POST /pets/bulk-delete` is `createBulkDelete`, beside `DELETE /pets/bulk-delete`'s `bulkDelete` or not, and `POST /v1/pets:batchGet` is `createBatchGet`); a path-named operation that would share an `operationId`'s name on its path takes the name it has without the action rule, numbered when that name is held on the path too (a path-named PATCH beside `operationId: updatePet` on the PUT is `updatePet2`), and an `operationId` reused on one path — as written, or up to the overload markers at its end, `listPets[1]` beside `listPets[2]` or `listPets[1][2]` — is numbered with a warning; a name any pass produces is checked against every name the service holds — an action takes the first of its names no operation holds (`createCreate` when `createPets` is an `operationId` on its path) — the name of another action still to yield is not held (`POST /pets/create` is `createPets` beside `POST /pets/create-pets`, whose `createPets` yields to `createCreatePets`), nor is one held only by path-named operations on other paths naming the noun the action names that a later qualifier tells from it, which the action joins as a qualifier joins such a name (`POST /pets/create` is `createPets` beside `POST /pets/{id}/pets`, told apart next as `createPets` and `createPetsById`; beside `POST /pets/pets`, which nothing after could tell from it, the action is `createCreate`) — numbered on the last when every one is held (`createCreate2`) or is its own name (`update2` for `PUT /{id}/update`, whose `PUT /{id}` is `update`), and after all passes a path-named operation left sharing a name on its path with an `operationId` or another verb is numbered (`updatePet2` for a path-named PATCH beside `operationId: updatePet` on the PUT; a name another operation holds is never what a qualifier gives, so `GET /api/notes` beside `operationId: listNotes` on its POST is `list2`, never `listNotes2`). Qualifiers are tried in order, each on whatever still collides, every one through one rule. A qualifier is added only when it tells the colliding paths apart, and a context two paths write alike is spelled alike for both: `Teams` sits in both `/org/teams/members` and `/org/teams/{teamId}/members`, so they are `listMembers` and `listMembersByTeamId`, never `listMembersTeams` and `listMembersTeam`. A qualified name another operation in the service already has is skipped for that operation and the next qualifier is tried, so a number never lands on a name another operation already had: `/org/members/archived` beside `/org/teams/archived` and `/org/archived_members` is `listArchived`, `listArchivedTeams` and `listArchivedMembers`, never `listArchivedMembers2`. A name held only by path-named operations naming the same noun is joined instead, when a later qualifier would tell them apart by a name no other operation has — by a parameter, a segment between the service and the resource, a root word, or the plural only the nested item can take back: `/notes` beside `operationId: list` restores `Notes` and meets the nested collection `/notes/{noteId}/notes` at `listNotes`, and the parameter then tells them apart, `listNotes` and `listNotesByNoteId` (`getNote` and `getNoteByChildId` for their items). Otherwise the name counts as taken, since joined the two would only be numbered: `/notes/notes` has nothing `/notes` lacks, so beside it `/notes` is `list2` and `/notes/notes` keeps `listNotes` — and so does `/notes/{noteId}/notes` when `operationId: listNotesByNoteId` holds the name its parameter would give it. Operations a qualifier does not tell from each other take one spelling and stay together for the next one, numbered on it when nothing after tells them apart (`listV1` and `listV1No2` for `/api/v1/{userId}/notes` and `/api/v1/{user_id}/notes` beside `/api/{userId}/notes`): `/orgs/{orgId}/groups/members` and `/orgs/{orgId}/groups/{groupId}/members` beside `/orgs/teams/members` are `listMembersGroups` and `listMembersGroupsByGroupId`. A qualifier never puts the same word twice in a row into a name (word for word on the camelCase boundary). The words it starts with are left off where they repeat the words the name ends with, each compared by its singular form, so `listNotes` never becomes `listNotesNotes`, nor `listNotesNote` for `/orgs/notes/{id}/notes`; inside the qualifier only the same word is a repeat, so `/org/analytics/analytics/teams` next to `/org/teams` yields `listTeamsAnalytics`, while a plural segment and its singular are two words: `/x/notes/{id}/note/tags` next to `/x/notes/{id}/tags` yields `listTagsNotesNote` and `listTagsNotes`. Every qualifier skips the API root and the service segment just as the name itself does, so `DELETE /api/v1/notes/all` in `Notes` is `deleteAll`, never `deleteAllV1Notes`. Before the qualifiers, an action yields its name when an operation of its method would have it on the path without the action's verb (`POST /pets` is `create`, `PUT /pets` is `update`, `GET /pets/all` is `listAll`), whether or not that operation is declared, so declaring it never renames the action, and when it shares its name with a path-named operation of another shape: it takes back the collection it dropped (`POST /pets/create` is `createPets` and `PUT /pets/update` is `updatePets`, while `create` and `update` stay with `POST /pets` and `PUT /pets/{id}`) or, when that adds nothing, its name without the action rule (`createPetCreate` for `POST /store/pets/{id}/create`, as `POST /store/pets/{id}` is `createPet`). The order: first the resource noun — for the service's own path the service noun as well, when a path-named operation already carries it under the name it would make and a later qualifier can tell the two apart (`/notes` beside `operationId: list` meets `/notes/{noteId}/notes` at `listNotes`, told apart next as `listNotes` and `listNotesByNoteId`); then the path segments between the service and the resource, each singular when a path parameter follows it, as the resource of an item operation is (`GET /users/{id}/legacy/factors` next to `GET /users/{id}/factors` becomes `listFactorsLegacy`, and `GET /store/cats/{id}/toys/{toyId}` next to `GET /store/dogs/{id}/toys/{toyId}` becomes `getToyCat` and `getToyDog`), unless the singular spelling would give a path the name of an operation outside its group or of another path that the spelling as written sets apart, which keeps the segments as written, the plural being what tells them apart (`GET /store/pets/{id}/toys/{toyId}` next to `GET /store/pet/{id}/toys/{toyId}` becomes `getToyPets` and `getToyPet`, and `/store/cats/{id}/toys/{toyId}` next to `operationId: getToyCat` becomes `getToyCats`), and as written alike when another colliding path writes the same words, so a segment singular in one path and plural in another from one spelling is one qualifier, which tells nothing apart and is left to the parameters (`/store/cats/toys/{toyId}` beside `/store/cats/{id}/toys/{toyId}` is `getToy` and `getToyById`, as `/org/teams/members` beside `/org/teams/{teamId}/members` is `listMembers` and `listMembersByTeamId`); then `By<Param>` for each path parameter the colliding paths do not all share, in path order, when those are what tell the paths apart (`GET /v1/notes` keeps `list` while `GET /v1/{teamId}/notes` becomes `listByTeamId`, `GET /users/teams` keeps `listTeams` while `GET /users/{id}/teams` becomes `listTeamsById`, `/orgs/{orgId}/{teamId}/members` beside `/orgs/members` gains `ByOrgIdByTeamId`, and `GET /api/notes/{noteId}` keeps `get` while `GET /api/{teamId}/notes/{noteId}` becomes `getByTeamId`, the shared `noteId` adding nothing, and a parameter that carries a custom method contributes the parameter alone: `GET /v1/pets/{petId}:history` beside `GET /v1/{orgId}/pets/{petId}:history` becomes `getPetHistoryByOrgId`); then the API root words a path skipped beyond those the colliding rooted paths all skipped, when they sit under different lengths of the document root — the one place a root word belongs in a name: `GET /api/notes` keeps `list` while `GET /api/v1/notes` becomes `listV1`, and a root-less path takes no part; then the resource noun the plain name left off because it names the service, when the colliding paths do not all drop the same one — this is what tells a path-named operation from an `operationId` it collides with, since that name is never rewritten and the parameters may have nothing to add: `GET /api/notes` beside `operationId: list` on `GET /api/{teamId}/notes` is `listNotes`, and `list` stays with the `operationId`, while the item `GET /api/notes/{noteId}` beside `operationId: get` is `getNote`, the noun singular as an item operation's resource is; then, for an item still colliding because an operation outside its group has that singular name, the noun as written, as for the segments between the service and the resource: with `operationId: getNote` on `POST /api/notes/pinned` as well, `GET /api/notes/{noteId}` is `getNotes`; then, for an item operation whose singular name none of those could tell apart, the plural it had before singularisation (`GET /store/pets/{id}` is `getPet`, and so is `operationId: getPet` on `/store/featured/{id}` or path-named `GET /store/pet/{id}`, so it becomes `getPets`) when no operation outside its group has that name — an `operationId`-named operation, an action, a singleton of one item (`GET /store/pets/{id}/status` is `getPetStatus`) and a name a qualifier has extended have no plural, except that a singleton beside another path-named singleton that writes the parent otherwise keeps the parent as written, its name carrying the parent singular and its qualifiers reading the path without it, so that the plural is all that tells the two apart (`GET /shop/pets/{id}/status` beside `GET /shop/pet/{id}/status` is `getPetsStatus` and `getPetStatus`, while beside `operationId: getPetStatus` alone it is `getPetStatus2`); members that would all take the same plural are numbered instead, and members that share a plural some other member does not take it together and are numbered (`/store/Pets/{id}` and `/store/pets/{id}` beside `/store/pet/{id}` or `operationId: getPet` are `getPets`, `getPets2` and `getPet`); and finally, when no qualifier is left, a numeric suffix (`list2`, `list3`, …) for paths that flatten to the same words (`/v1/{userId}/notes` and `/v1/{user_id}/notes`, or `/notes` and `/api/v1/notes`, which differ only by the root) or whose every qualified name is taken (`/api/notes` beside `operationId: list` on `/api/{teamId}/notes` and `operationId: listNotes` on `/api/{orgId}/notes` is `list2`, never `listNotes2`). A name that already ends in a digit — the version a root word gave it, a path word such as `top10`, or an `operationId` such as `getV2` — takes the number behind `No`, so that it cannot be read as part of the number the name ends with: `GET /api/v1` beside `GET /api/v1/` is `listV1` and `listV1No2`, never `listV12`, which would read as version 12, `GET /api/v1/{userId}/notes` beside `GET /api/v1/{user_id}/notes` under a versionless `GET /api/{userId}/notes` is `listV1` and `listV1No2`, and `GET /pets/top10` beside `GET /pets/top10/` is `listTop10` and `listTop10No2`; a number on one path is spelled the same way, so a path-named PATCH on `/store/top10/{id}` beside `operationId: updateTop10` on the PUT is `updateTop10No2`. For the plain name, an `operationId`-named operation outranks a path-named one, then the path that skipped the shorter root (`/health` or a tagged `/notes` keeps `list` over `/api/health` or `/api/v1/notes`, exactly as without the root), and otherwise the lexically first path wins, so the outcome does not depend on document order. The suffix is silent for a path-derived name, like a hashed inline model name; when the document itself reuses an `operationId` within a service, the later path is suffixed with a `[oagen] Warning:`, since that changes a name the author chose, and its inline models follow the new name (`createNote2` sends a `CreateNote2Request`; see Inline model naming); two ids that strip to one (`listPets[1]`, `listPets[1][2]`) are one id reused and are read exactly so, `listPets2` returning a `ListPets2Response`. Two colliding actions are qualified by the path of their parent, never by repeating the verb (`adoptPet` and `adoptPetRescue`, not `adoptPetAdopt`), and two colliding singletons by the path around the parent, never by repeating it (`getPetStatus` and `getPetStatusRescue`, not `getPetStatusPet`).

```typescript
interface Service {
  name: string; // e.g., "Organizations"
  description?: string;
  externalDocs?: ExternalDocs; // The document tag's link, by the same rule as description
  operations: Operation[];
}

interface Operation {
  name: string; // e.g., "listUsers", "getUser", "createUser"
  operationId?: string; // The document's operationId, verbatim; absent on a path-named operation
  summary?: string; // The document's summary alone; only when it has non-whitespace content
  description?: string; // The document's description alone, never built from the summary (one identical to it is kept); only when it has non-whitespace content
  externalDocs?: ExternalDocs; // The operation's own externalDocs, when usable
  extensions?: Extensions; // The Operation Object's own x-* keys, less the ones the parser consumes (see Extensions)
  httpMethod: HttpMethod; // All 8 standard HTTP methods
  path: string; // e.g., "/organizations/{id}"
  servers?: ServerEntry[]; // The operation's own servers, else its Path Item's; only when they differ from ApiSpec.servers
  pathParams: Parameter[];
  // Excludes `in: query` params that a POST/PUT/PATCH request body also declares;
  // those travel body-only and are kept in bodyOwnedQueryParams instead.
  queryParams: Parameter[];
  // Query declarations the body owns (see above). Emitters never serialize
  // these to the URL; enum collection and the compat surface still walk them.
  bodyOwnedQueryParams?: Parameter[];
  headerParams: Parameter[]; // Every declared header parameter but Idempotency-Key (see Idempotency Key below) and an Accept, Content-Type or Authorization header, which OpenAPI says to ignore
  cookieParams?: Parameter[]; // Present only when cookie params exist
  requestBody?: TypeRef;
  requestBodyEncoding?:
    "json" | "form-data" | "form-urlencoded" | "binary" | "text";
  requestBodyRequired?: boolean; // Whether the caller must send the body; present exactly when requestBodyContentTypes is, so also for a body carried in requestBodyContents alone
  requestBodyDescription?: string; // The Request Body Object's description, else the picked schema's own, a collapsed wrapper or single-member oneOf/anyOf read through to its branch (only when one has content)
  requestBodyContentType?: string; // The essence of the media type requestBody was read from — send it as Content-Type; set exactly when requestBody is
  requestBodyContentTypes?: string[]; // Media types the request body declares, in document order (only when any exist)
  requestBodyContents?: RequestBodyContent[]; // A type per media type above, same order (only when any exist)
  response: TypeRef; // Primary response: the lowest 2xx with a typed body, else the lowest declared 2xx/3xx; unknown when there is none
  responseStatusCode?: number; // The status code the primary response was read from (only when a 2xx or 3xx is declared)
  responseHeaders?: ResponseHeader[]; // Headers declared on the primary response (only when any exist)
  responseDescription?: string; // The primary response's description (only when it has content)
  responseContentTypes?: string[]; // Media types the primary response declares, in document order (only when any exist)
  responseContents?: ResponseContent[]; // A type per media type above, same order (only when any exist)
  successResponses?: SuccessResponse[]; // Every declared 2xx and 3xx response; only when more than one is declared
  errors: ErrorResponse[];
  defaultResponse?: DefaultResponse; // The `default` response (only when declared)
  rangeResponses?: RangeResponse[]; // `1XX`–`5XX` range responses, in declaration order (only when any exist)
  pagination?: PaginationMeta;
  injectIdempotencyKey: boolean; // true when the operation declares an Idempotency-Key header parameter, which is then left out of headerParams
  deprecated?: boolean; // Present, and true, only when the Operation Object says deprecated: true
  async?: boolean; // The x-oagen-async extension, carried as the document writes it (see Async marker below)
  tags?: string[]; // The operation's tags in document order, entries that are not strings with non-whitespace content dropped, repeats folded; only when at least one remains; the service is named from the first entry that has a name once PascalCased, or from the path when none has one
  security?: SecurityRequirementSet[]; // Per-operation requirements; undefined inherits ApiSpec.security
  parameterGroups?: ParameterGroup[]; // Mutually-exclusive parameter groups from x-mutually-exclusive-parameter-groups; see ParameterGroup in src/ir/types.ts
  callbacks?: Callback[]; // The requests the API sends back to URLs the caller supplied, each read as a Webhook (see Callback); only when at least one is readable
}

interface SecurityRequirement {
  schemeName: string; // Matches AuthScheme.schemeName in ApiSpec.auth
  scopes: string[];
}

// One alternative: every scheme in the set is required together.
type SecurityRequirementSet = SecurityRequirement[];
```

`security` mirrors the OpenAPI document instead of flattening it. Each requirement object in the document becomes one `SecurityRequirementSet` whose schemes must all be satisfied together ("all of"); the list of sets is satisfied by any one of them ("either of"); an empty set is an alternative that needs no credentials, which is how a document marks authentication optional. The field therefore distinguishes cases a flat list could not:

| Document                                            | `Operation.security`                  | Meaning                                              |
| --------------------------------------------------- | ------------------------------------- | ---------------------------------------------------- |
| no `security` key                                   | `undefined`                           | inherit `ApiSpec.security`                           |
| `security: []`                                      | `[]`                                  | no authentication                                    |
| `security: [{ userToken: [] }, { partnerKey: [] }]` | `[[{ userToken }], [{ partnerKey }]]` | either scheme                                        |
| `security: [{ userToken: [], partnerKey: [] }]`     | `[[{ userToken }, { partnerKey }]]`   | both schemes together                                |
| `security: [{ userToken: [] }, {}]`                 | `[[{ userToken }], []]`               | `userToken`, or nothing (authentication is optional) |

To resolve what an operation accepts, take `op.security ?? spec.security`; a result of `undefined` means the document declares no requirements at all. The same list shape applies to `ApiSpec.security`.

The differ compares security on what a request actually carries, resolved the same way on each side (`[]` when neither the node nor its document declares a list), and reports a difference as `securityChanged: true` on the `operation-modified` or `webhook-modified` change with `oldSecurity`/`newSecurity` beside it, present exactly when the flag is. A node that declares no list on either side inherits twice and is not reported: a moved document default is the document-level `security-changed` change's to report, so a document that moves to what an operation already declared (its override vanishing with it) is no change to that operation. Lists are compared as sets of alternatives, each a set of schemes with scopes as sets, so order and repetition do not count, and `security: []`, a lone anonymous alternative (`[{}]`) and nothing declared anywhere are the same thing: no authentication. The classification is read from the node's side of the wire, by one rule applied in each direction (`classifySecurityChange` in `src/differ/security.ts`): for an operation, a caller built for the old list must still satisfy the new one — breaking when some old alternative satisfies no new one (a scheme or scope now required, an alternative removed, an anonymous alternative withdrawn), additive when every old alternative still passes (an alternative added, a scheme or scope no longer needed, authentication made optional); for a webhook, the handler built for the old list must still find what it checked for in whatever the sender now presents — breaking when some new alternative carries no old one (a credential the sender stops presenting, an alternative it may now use that the old list never offered), additive when every new alternative still carries some old one (a credential the sender starts carrying beside the old ones, an alternative withdrawn). The document-level change is read from each side that inherits the default in both documents — the caller's when an operation does, the receiver's when a webhook does, each matched across the two documents as its own change is (an operation by name within its service, a webhook by name and method) — and is breaking if any such side breaks. No other node reads both defaults: one that declares its own list on either side is compared on its own, as above, and one added or removed is reported as such. When nothing inherits the default in both documents, no request reads both defaults, so the change is additive. Every security change is mirrored into `behaviorChanges` as a `security-changed` entry naming the node (`document`, `operation` or `webhook`) with the two lists and the security change's own classification, beside the deprecation and parameter-default entries collected there. `tags` differing — compared in document order, an absent key as an empty list — is `tagsChanged: true` on the same changes with `oldTags`/`newTags` beside it, additive always and not mirrored into `behaviorChanges`. That flag can only ever carry an edit that leaves the operation in a service of the same name, because operations are matched by name within a service: the parser groups an operation by its first tag with a name (`tags[0]` unless it has no ASCII letter or digit) and then the path-prefix split (see Service above), so a first-tag change that the split files back under the same path-named service is a `tagsChanged`, while one that moves the operation to a service of another name leaves nothing to match, and the diff reports the move as `operation-removed` plus `operation-added` across the two services, or `service-removed` plus `service-added` when a service goes or comes with it — breaking, as a moved method is. A webhook belongs to no service, so every edit to its `tags` is a `tagsChanged`.

```typescript
interface SuccessResponse {
  statusCode: number; // A declared 2xx or 3xx code
  type: TypeRef; // The body type; always `unknown` for a 3xx entry
  headers?: ResponseHeader[]; // Only when the spec declares at least one
  contentTypes?: string[]; // Media types under `content`, in document order; only when at least one
  contents?: ResponseContent[]; // One per contentTypes entry, same order; only when contentTypes is
  description?: string; // The response's description; only when it has non-whitespace content
}

interface ResponseContent {
  contentType: string; // As written in the spec, e.g. "application/vnd.api+json", "text/html; charset=utf-8"
  type: TypeRef;
}

interface ResponseHeader {
  name: string; // As written in the spec, e.g. "Content-Disposition"
  type: TypeRef;
  required: boolean;
  description?: string;
  deprecated?: boolean;
  externalDocs?: ExternalDocs; // The header schema's (`schema`, or the `content` entry read in its place), when usable
}

interface Parameter {
  name: string;
  type: TypeRef;
  required: boolean;
  description?: string;
  deprecated?: boolean;
  externalDocs?: ExternalDocs; // The schema's, else the `$ref` target's, when usable
  default?: unknown;
  example?: unknown; // The document's `example`, else `examples[0]`
  examples?: unknown[]; // Every example value, in document order; only when non-empty
  style?: "form" | "simple" | "label" | "matrix";
  explode?: boolean;
  contentType?: string; // The `content` key the value is serialized under, as written; only for a `content` parameter whose map is read
  contentTypes?: string[]; // Every `content` key, in document order and as written, read or not; only for a `content` parameter
  constraints?: Constraints; // Validation keywords; see Constraints below. Equal to the type's (under its nullable wrapper) wherever the type can carry them (see Type constraints)
}
```

A parameter is identified by its location and its name (`parameterKey` in `src/ir/parameter-key.ts`, exported from the package): a path `id` and a query `id` are two parameters. A header's name is compared case-insensitively, since HTTP header names are (RFC 9110 §5.1); path, query and cookie names are compared as written. A path item's parameters are merged into each of its operations on that identity — an operation-level parameter replaces a path-level one with the same identity, in the path-level position, so a path-level `X-Pet-Token` and an operation-level `x-pet-token` give one header parameter, the operation's. `Parameter.name` is always the name as the winning declaration wrote it; emitters apply their own casing. The differ pairs parameters on the same identity (see [`oagen diff`](../cli.md#oagen-diff)).

A header parameter named `Accept`, `Content-Type` or `Authorization` is ignored, as OpenAPI requires: the request's media types and its `security` set those headers. The name is compared case-insensitively, as every header name is, once a `components/parameters` `$ref` is resolved, so the header is dropped wherever it is declared — on the operation or its Path Item, inline or through a ref, on a webhook as on an operation (`isIgnoredHeaderParameter` in `src/parser/operations.ts`): it reaches no `headerParams`, its schema mints no model or enum, and a `content` map on it is not reported. A query, path or cookie parameter of one of those names is kept. An `x-mutually-exclusive-parameter-groups` variant that names such a header (`variants: { header: ['Authorization'], query: ['api_key'] }`) has that member dropped with a warning naming the cause (`… names the header parameter "Authorization", which OpenAPI says to ignore …`), and a variant left with no member, then a group left with no variant, is dropped the same way — the document declares the parameter, so failing the parse with "does not exist in the operation's parameters[]" would point at the wrong cause; a member no parameter declares still fails it. `oagen diff` therefore never sees an ignored header: declaring a required `Authorization` header is no change.

A parameter's schema is its `schema` or, when it declares a `content` map in its place, the schema of the entry read from that map: `application/json` or a `+json` media type when the entry declares a schema, else `text/plain` with or without one, each matched by media type essence — `type/subtype` with parameters stripped and case folded, so `application/json; charset=utf-8` and `APPLICATION/JSON` are read as `application/json` — and, within one tier, the first matching key in document order. A `text/plain` entry without a schema types the parameter as a `string`. A map none of whose media types is read types it as a `string` too, with a warning that names the media types, once per operation parameter, once per webhook parameter and once per response header; an empty map is not reported. A `schema` beside a `content` map wins and the map is not consulted. Every rule in this section that reads the parameter's `schema` — its `type`, the inline model or enum it mints, `description`, `deprecated`, `default`, `example` and `examples`, `externalDocs`, `constraints`, and the page start a `page` parameter gives `PaginationMeta.pageStart` — reads this schema, in every location, on an operation and on a webhook alike, so a parameter declared either way is typed by one rule.

`Parameter.contentType` is the media type the value is serialized in: the `content` key the parameter's schema was read from, as written (`application/json; charset=utf-8`). It is present exactly when the parameter is declared with `content` and the map is read — a schema-less `text/plain` entry included — and absent for a `schema` parameter and for a `content` map none of whose media types is read, whose string value is sent as written. `Parameter.contentTypes` lists every media type the map declares — its keys, in document order and as written — whenever the parameter is declared with a `content` map that declares at least one, read or not, as `requestBodyContentTypes` does for a body; a `schema` beside the map wins, and the parameter carries neither. OpenAPI allows the map one entry, which `contentType` names when it is read; for a map none of whose media types is read, `contentTypes` is where the media type the document declares the value in is kept (`['application/xml']`), the value itself being a string sent as written. Both are carried wherever a parameter is: an operation's own and path-level parameters, a webhook's, and one reached through a `components/parameters` ref. An emitter that serializes parameters by `style` and `explode` must instead serialize a value that has a `contentType` in that media type — JSON-encode an `application/json` or `+json` value (`filter={"owner":"a","tag":"b"}`, not `owner=a&tag=b`), send a `text/plain` value as text. `oagen diff` compares the two sides by media type essence — `contentType`, else the first of `contentTypes`, so a parameter moving to or from an unread map is not taken for a `schema` one — and reports a difference as a `param-content-type-changed`, breaking unless both sides are read from a JSON media type (see [docs/cli.md](../cli.md)); the webhook stem naming reads neither.

`Parameter.description` is the first non-empty `description` found on, in order, the parameter itself, its schema, and the `$ref`'d component schema. An empty string at any level counts as absent, and the field is `undefined` (never `""`) when nothing in the chain is documented. A `description` written beside a `$ref` into `components/parameters` is the parameter's own in an OAS 3.1 document and ignored in a 3.0 one (see Reference Objects below). `deprecated` and `example` read the same three levels, each by its own rule: `deprecated` is `true` when any level says `deprecated: true` (see Deprecation below), `example` takes the first level that gives a value (an explicit `null` is kept; see Parameter Examples below). `default` does not: it is read from the inline `schema`, else the `$ref`'d component schema, with `??`, so a `false` or `0` default is kept, and the Parameter Object itself is never consulted since OpenAPI gives it no `default`. `Parameter.externalDocs` follows the same chain from the schema down — the parameter's `schema` (a sibling of a `$ref` included), then the component schema its `$ref` points at — an unusable entry at one level falling through to the next; a Parameter Object declares no `externalDocs` of its own.

`ResponseHeader.externalDocs` is the header schema's `externalDocs` — the Header Object's `schema`, or the schema of the `content` entry read in its place (see Response Headers below), after a `$ref` into `components/headers` is resolved — when it declares a usable one: the schema's own, else the first `allOf` member's that declares no type of its own and so only annotates the schema (`allOfWrapperLayer`; see Collapsed wrappers above), an unusable link at one level falling through to the next, so `X-Rate-Limit: { schema: { allOf: [{ type: "integer" }, { externalDocs: { url } }] } }` gives the header the link `{ schema: { allOf: [{ type: "integer" }], externalDocs: { url } } }` does, as it gives a field, a parameter and the model built from the schema (#605: the header read its `deprecated` from such members but its link from the schema's own keys alone, so the member's link was dropped). A header reads only its own schema — its own keys and such members — never the component a `$ref` in it names, as its `deprecated` reads only the Header Object and that schema (see Deprecation below) and its `description` only the Header Object: a `$ref` sibling's link is the header's, a member's beside a `$ref` member is too (`allOf: [{ $ref: Meta }, { externalDocs }]`, the component keeping its own), and a bare `$ref` gives none (the referenced model carries its own), as a typing member's own link stays on that member (`allOf: [{ type: "integer", externalDocs }]` gives none, as it gives a field none). A `description` written beside a `$ref` into `components/headers` is the Header Object's own in an OAS 3.1 document and ignored in a 3.0 one (see Reference Objects below).

A parameter's `constraints` come from its own schema. When that schema is a `$ref`, the target's keywords are merged underneath the parameter's own — `{ $ref: Limit, minimum: 5 }` against `Limit: { type: integer, minimum: 1, maximum: 100 }` gives `{ minimum: 5, maximum: 100 }` — the per-value way `default` and `example` fall back, so a parameter can be read on its own without chasing the target (a primitive or an array component becomes no model, nor does an alias of an enum component, whose own limits conjoin above the enum's; see Enum). The key is absent when neither declares any. The parameter's type carries the same limits wherever it can (see Type constraints), and the limits of an array parameter's items or a union parameter's variants are on those types alone.

### Path Item references

OpenAPI 3.1 lets a `paths` entry be written as a `$ref` to another Path Item, which may be any Path Item Object: one under `components/pathItems`, or another entry of `paths` or `webhooks` (`#/paths/~1pets`, `#/webhooks/petAdopted`). A pointer into either map names one entry whole, its single token decoded as the bundler decodes it (`~1` for `/` and `~0` for `~`, percent-escapes decoded, RFC 6901 §6), so `#/paths/~1pets~1%7BpetId%7D` and `#/paths/~1pets~1{petId}` both name `/pets/{petId}`. The parser resolves it before reading anything from the entry — chains included, with a cycle guard — through `resolvePathItemRef` in `src/parser/path-item-refs.ts`, the function a `webhooks` entry's `$ref` is resolved by (see [Webhook](#webhook)), so the referenced item's operations, `parameters`, `servers`, `summary` and `description` reach the IR as an inline Path Item's do: the same operations in the same services, with the same `Operation.servers`, doc text and inline model names. Fields written beside the `$ref` — on the entry, or on a link of its chain — are not merged in: OpenAPI leaves a field present on both sides undefined, and the referenced item is taken whole so the rule does not depend on which fields clash; they are reported once per entry with one `[oagen] Warning:` naming the path and the keys (`Path "/pets" has fields beside its $ref ("summary", "post") that are not read: the referenced path item is taken whole.`), so a `post` written beside a ref to an item that declares only `get` is not lost silently; the contested-title walker (`schemaRootsOf` in `src/parser/inline-models.ts`) steps over the fields beside the `$ref` the same way, so a titled union under such a `post` contests no title (#601). An `x-` extension beside the `$ref` is not reported, since the parser reads none off a path item. Two `paths` keys that `$ref` one entry are two operations, one per path, read from one Operation Object, and so are a key and the `paths` entry it `$ref`s (`/animals` written as `$ref: '#/paths/~1pets'` beside `/pets`); both carry its `operationId`, and when that puts two operations of one name in one service the second is numbered, with a warning, as a reused `operationId` is (see the operation-name paragraph above). An entry the resolver rejects is warned about once, naming the path, and skipped, the rest of the document parsing as usual: a value that is not an object, a `$ref` that is not a string, a ref that names no Path Item (into another section such as `#/components/schemas/Pet`, deeper into an entry such as `#/paths/~1pets/get`, or to an `x-` extension under `paths`), a dangling ref, or a cycle; an unresolved ref's warning names where it was looked up, `paths` or `webhooks` for a pointer into either and `components/pathItems` for any other (`no matching entry under paths`). A dangling ref and a cycle are reachable only when the document bypassed the bundler, which fails on either before parsing (`Can't resolve $ref`; `Self-referencing circular pointer`). A key starting with `x-` under `paths` is a specification extension, not a path item, and is stepped over without a warning whatever its value — a scalar, or an object shaped like a path item; the contested-title walker (`schemaRootsOf` in `src/parser/inline-models.ts`) steps over it too, so nothing under such a key is ever read. A key under `webhooks` is never one: OpenAPI gives that map no specification extensions, so a key starting with `x-` there is a webhook like any other (see [Webhook](#webhook)).

### Reference Objects

A Parameter, Request Body, Response, Header or Example Object may be written as a Reference Object — `{ $ref: '#/components/parameters/Limit' }` — and the parser resolves every one through one walk (`followReference` in `src/parser/reference-objects.ts`): the `#/components/<section>/<name>` pointer is matched whole, so a ref into another section never resolves off a same-named entry of this one; a chain of refs is followed with a cycle guard; JSON Pointer escapes are decoded; a component that is not an object — `null`, a string, a number, a boolean or an array — answers nothing, so a ref to one is unresolved, and the walk hands the entry back so a reader can report it as the malformed entry it is rather than as missing (the response readers do; see Responses below). The text written beside the `$ref` is read by one rule at every site. In an OAS 3.1 document a Reference Object's `description` — and its `summary`, for an Example Object, the one referenced type that has one — overrides the referenced component's: each ref in a chain overrides what it points at, so the outermost text with non-whitespace content wins over an inner ref's and over the component's own, and a blank sibling is no text and falls through to the next, as a blank operation `summary` falls through to its path item's. In an OAS 3.0 document a Reference Object has no field but `$ref`, so text beside one is ignored and the component's own is read; a document whose version is not recognised is read as 3.1. Nothing else may be written beside a `$ref` in either version — OpenAPI says any other property added to a Reference Object SHALL be ignored — so a `content` or `headers` beside a response ref, a `value` beside an example's, or an `x-` key there is never read: a ref that resolves reads the component alone, and one that fails is read as the Reference Object it is, its `$ref` and, in a 3.1 document, its text (#562). What is never read types nothing, mints no model and contests no title either: the contested-title walker (`schemaRootsOf` in `src/parser/inline-models.ts`) steps over a Reference Object whole, as the readers do, at every site that takes one — a parameter, request body, response or header on an operation, a webhook or a callback, or as a `components` entry itself, resolving or not — so a titled union under a `content` or `headers` written beside the `$ref` never contests the title a component gives another shape: with `404: { $ref: '#/components/schemas/Pet', content: { 'application/json': { schema: { allOf: [{ $ref: '#/components/schemas/Pet' }, { properties: { note: { oneOf: [{ title: 'Tag', … }, { title: 'Sticker', … }] } } }] } } } }` beside a `Pet` whose `collar` is a `oneOf` of a `Tag` and a `Chip` of other shapes, the models are `Pet`, `Tag` and `Chip`, exactly as without the `content`, rather than `Pet`, `TagPetCollar` and `Chip`, and `oagen diff` between the two documents is empty (#601). So `Parameter.description` sees a sibling beside a `components/parameters` ref as the parameter's own text, first in its chain; `Operation.requestBodyDescription` and `Webhook.requestBodyDescription` see one beside a `components/requestBodies` ref ahead of the shared body's own (see Request Body Description); a response's `description` and `ResponseHeader.description` see one beside a `components/responses` or `components/headers` ref ahead of the component's; and an Example Object's `summary` and `description` are overridden the same way, though the parser reads only an example's `value`, so that text never reaches the IR. What a failed resolution does is each site's own: a parameter or request body ref that nothing answers, or that loops, fails the parse; a header or example ref is dropped with a warning; a response ref nothing answers, or one whose `$ref` is not a string (`{ $ref: 42 }`), is read as the Reference Object it is with a warning naming the ref and the response (`Malformed response $ref 42 in 404 response of getPet: a $ref must be a string — reading the response as written, without a body or headers`), its sibling text kept in an OAS 3.1 document and ignored in a 3.0 one, as beside a ref that resolves, and a `content` or `headers` written beside the `$ref` ignored in both, as beside a ref that resolves — so `404: { $ref: '#/components/schemas/Pet', content: { … }, headers: { … } }` is an error entry with no `type` and no `headers` — and a circular response chain fails the parse — on a webhook, each keeps the status code with a warning, and its sibling text by the same rule. A Path Item's `$ref` is not a Reference Object — OpenAPI leaves a field present on both sides undefined — and the referenced item is taken whole (see Path Item references above); a Schema Object's `$ref` is JSON Schema's, whose siblings the field extractor reads whatever the document's version (see Model & Field), and which is followed as the JSON Pointer it is, into a component or deeper (see Schema references).

### Parameter Examples

`example` and `examples` are read from these levels in order: the parameter itself, then — for a parameter declared with `content` — the Media Type Object of the entry its schema was read from, then the parameter's schema, then the component schema its `$ref` points at. A parameter-level or media-type-level `examples` is an OpenAPI map of Example Objects, so each entry's `value` is taken in document order; a `$ref` entry is resolved against `components.examples` (a dangling ref is skipped with a warning), and an `externalValue` entry is skipped. A schema-level `examples` is the JSON Schema list and is taken as-is.

Each value walks the levels on its own. `examples` is the first level's non-empty list. `example` comes from the first level that has either an `example` or a list, preferring that level's own `example` over its first list entry, so a schema-level `example` can never mask the parameter's own `examples` map. A level with neither falls through; an explicit `null` is a value and is kept. Emitters that read only `example` therefore still see a value for an OAS 3.1 document that uses `examples` alone.

### Idempotency Key

The `injectIdempotencyKey` flag is spec-driven: it is `true` only when the operation declares an `Idempotency-Key` header parameter — on the operation or on its Path Item, the name compared case-insensitively as every header name is. That parameter is left out of `headerParams`: the SDK injects the header itself rather than typing it as a method argument, so its `description`, `required` flag and schema do not reach the IR, and a `content` map on it is not reported. APIs that don't use idempotency keys (e.g., GitHub) get `false`, while APIs that do (e.g., Stripe, billing APIs) declare the header in their spec and get `true`.

### Async marker

`Operation.async` is the Operation Object's `x-oagen-async` extension, carried as the document writes it: the parser neither tests nor coerces the value, so `x-oagen-async: true` arrives as `true` and `'x-oagen-async': 'yes'` as the string `'yes'`, although the IR types the field as `boolean`; the key is absent when the document declares none. An emitter that marks a method async should test `=== true`.

### Request Body Encoding

`requestBody` is read from one entry of the Request Body Object's `content` map (after a `$ref` into `components/requestBodies` is resolved), and `requestBodyEncoding` tells emitters how to serialize it:

| Value             | Media types                                         |
| ----------------- | --------------------------------------------------- |
| `json`            | `application/json`, any concrete `+json` media type |
| `form-data`       | `multipart/form-data`                               |
| `form-urlencoded` | `application/x-www-form-urlencoded`                 |
| `binary`          | `application/octet-stream`                          |
| `text`            | `text/plain`                                        |

Media types are matched by essence — `type/subtype` with parameters stripped and case folded, as response media types are (see Multiple Success Responses below) — so `application/json; charset=utf-8`, `APPLICATION/JSON` and `multipart/form-data; boundary=x` are read as their bare types, and `application/vnd.api+json` or `application/merge-patch+json` as JSON. A media range is never read, since no request can be labelled with one: a body under `application/*+json` is not read as JSON, although a response under it is. The entries are tried in a fixed order: `application/json`, then a `+json` media type, then `multipart/form-data`, then `application/x-www-form-urlencoded`, each only when it declares a schema (an `application/json` entry without one yields to a later media type that has one); then `application/octet-stream`, then `text/plain`, with or without a schema — a schema-less binary body is a `string` with `format: "binary"`, a schema-less text body a `string`, and one with a schema is typed from it. Within a tier the first matching key in document order wins. `requestBodyEncoding` is set exactly when `requestBody` is, and so is `requestBodyContentType`: the essence of the media type the body was read from (`application/merge-patch+json`; `application/json` for `application/json; charset=utf-8`; `multipart/form-data` for `multipart/form-data; boundary=x`), which is what an emitter sends as the request's `Content-Type` — `requestBodyEncoding` says how to serialize the body, `requestBodyContentType` how to label it, so a server that requires its declared media type accepts the request; parameters such as a multipart boundary are the emitter's to produce. A body that declares media types but none the parser reads — `application/xml`, `text/csv`, a media range such as `application/*` or `application/*+json`, or only an `application/json` entry without a schema — yields no `requestBody`, `requestBodyEncoding` or `requestBodyContentType`; it is carried in `requestBodyContents` alone (see Request Body Content Types below), and the parser warns once per operation (and once per webhook, whose payload goes through the same pick) rather than dropping it silently. The `x-mutually-exclusive-body-groups` extension resolves its members from the same pick, as do the body-owned query parameters (`bodyOwnedQueryParams`).

A body that is itself an inline enum, or an array of one, mints no model: it is promoted to `spec.enums` under the `<Op>Request` name it is typed by (`SetMoodRequest`), whichever media type it was read from, with the per-value documentation and link the schema declares (see Enum below). Both spellings of an inline enum are read here, as at every other site: an `enum:` list, and a `oneOf`/`anyOf` whose every non-null variant is a string `const` (an OAS 3.0 single-value `enum` counts) — `oneOf` exactly as `anyOf`. `POST /notes` (`addNote`) with the body `{ oneOf: [{ type: 'string', const: 'draft', description: 'A draft.' }, { type: 'string', const: 'final', description: 'A final note.' }] }`, or in OAS 3.0.3 `{ oneOf: [{ type: 'string', enum: ['draft'], description: 'A draft.' }, { type: 'string', enum: ['final'], description: 'A final note.' }] }`, is `requestBody: { kind: 'enum', name: 'AddNoteRequest' }` with `AddNoteRequest` in `spec.enums`, its members `draft` ("A draft.") and `final` ("A final note.") — the same enum the body written with `anyOf` is, and the same schema as a webhook or callback payload (`NoteAddedPayload`) or on a field is, so `oagen diff` between the two spellings reports nothing (#603: the `oneOf` body was a union of two literals with no enum and no member text, and the switch read as breaking). A `null` variant beside the consts (`{ type: 'null' }`, `{ const: null }` or `{ enum: [null] }`), or `nullable: true` / `type: ['string', 'null']` beside the union, makes the body `nullable<AddNoteRequest>`; an `enum:` list beside the union restricts the members as it does on a field. A `oneOf`/`anyOf` that mixes consts with any other variant — a bare `type: 'string'`, a `$ref`, an object, a number const — is a union, as it is everywhere, and a lone const beside `null` with no `enum:` list is the nullable literal. A name an enum of other members already owns — a component's — is numbered (`SetMoodRequest2`), and a name a model owns is never taken; identical members share the existing enum. An enum nested in the body's model (`SetMoodRequest.mood`) is promoted with every other model's field enums (`SetMoodRequestMood`).

### Request Body Required

`requestBodyRequired` carries the Request Body Object's `required` flag, so an emitter can make the body argument mandatory or optional to match the document. It is read after a `$ref` into `components/requestBodies` is resolved, so a referenced body's flag counts. OpenAPI defaults the flag to `false`, so a body the document does not mark required is `false` here — an explicit `required: false` and an omitted flag are the same thing, and only a literal `true` makes a body required. The field is present exactly when `requestBodyContentTypes` is — whenever the body declares at least one media type — whatever the encoding or the body's shape (an inline object, a bare `$ref`, a `oneOf`, a schema-less binary or text body), and whether or not one of its media types is read as `requestBody`: a body carried in `requestBodyContents` alone (see Request Body Encoding above) keeps its flag, as a webhook payload does, so an emitter that offers it can tell whether the caller must send it, and `oagen diff` compares it on such a body as on one read as `requestBody` (see below). The field is therefore set beside every `requestBody` but does not imply one. An operation without a body, or whose body declares no media type (no `content`, or an empty map), has no entry, and neither has a webhook whose payload declares none (see Webhook below).

Whenever both specs carry a body the flag is kept on — one read as `requestBody`, or one carried in `requestBodyContents` alone — the differ reports a flip as `requestBodyRequiredChanged` on an `operation-modified` change: optional → required is breaking (callers must now send a body), required → optional is additive. A `createPet` body under `application/xml` alone, or under the media range `application/*+json`, that goes from `required: false` to `required: true` is therefore the same breaking `operation-modified` change, and the same exit `2` from `oagen diff`, as one under `application/json` — an SDK that offers the body through its contents makes the argument mandatory just the same — and the reverse flip is additive (exit `1`) under every media type (#528). The flag is compared whichever way each spec reads the body, so a body carried in its contents in the old spec and read as `requestBody` in the new, with the flag flipped, sets `requestBodyRequiredChanged` beside `requestBodyChanged`; an absent flag beside a carried body reads as optional, and a body that declares no media type keeps no flag and has nothing to compare. A body appearing or disappearing takes its flag with it: one read as `requestBody` is reported as `requestBodyChanged` alone, one carried in its contents alone is not reported. A body changing type also sets `requestBodyChanged`, and if its required flag flips in the same change, both flags are set. A body change is breaking, except when a body appears with `requestBodyRequired` not `true`: an optional body only gives callers an argument they may leave out, so it is additive, the same as `param-added` for an optional parameter. A body appearing as required, a body disappearing and a changed body type stay breaking, and as with every other flag, one breaking flag makes the whole `operation-modified` change breaking (an optional body added alongside a required parameter is breaking). While both specs declare a body — one read as `requestBody`, or one carried in `requestBodyContents` alone, as the flag's rule reads it, so `createPet`'s body under `application/xml` alone gaining `text/csv` is reported — the media types it may be sent as (`requestBodyContentTypes`) are compared by essence as a response entry's are and reported as `requestBodyContentTypesChanged` with `requestBodyContentTypeChange` beside it: a media type callers could send that is gone, or a secondary media type whose body changed type, is breaking; one they can newly send is additive (see `oagen diff` in the CLI reference). A body changing encoding — `requestBodyEncoding`, the wire format it is serialized as (see Request Body Encoding above) — while both specs carry a `requestBody` (no encoding is read from a body carried in `requestBodyContents` alone, so such a body on either side reports only what its media types did) sets `requestBodyEncodingChanged`, with `oldRequestBodyEncoding`/`newRequestBodyEncoding` beside it, and is breaking when the new document no longer accepts the representation the old document's body was read from — that media type gone from `requestBodyContentTypes`, or its shape changed (compared as `retyped` is) — since an SDK built for the old document keeps serializing and labelling the body as that document said; it is additive when the new document still accepts it, as when a media type the parser prefers is added beside it (a body without media-type lists reads as breaking). A body moving from `application/json` to `application/x-www-form-urlencoded` sets both flags — the JSON media type is removed and the form one added — while a media type changing essence within one encoding (`application/json` → `application/vnd.api+json`) sets `requestBodyContentTypesChanged` alone. A body that appears or disappears takes its encoding with it and is `requestBodyChanged` alone; one that changes type and encoding at once sets `requestBodyChanged` and `requestBodyEncodingChanged`. A webhook payload's encoding is compared through the same function (see Webhook below).

### Request Body Description

`requestBodyDescription` carries the doc text for the request body — what an emitter prints for the body argument, as `responseDescription` is what it prints for the return ("The pet to add to the shelter."). It is read from two places, in order. First, the Request Body Object's own `description`, after a `$ref` into `components/requestBodies` is resolved, so a shared body's text counts — and a `description` written beside that `$ref` is the body's own in an OAS 3.1 document, ahead of the shared body's, while a 3.0 document ignores it (see Reference Objects). Second, when that has no non-whitespace content, the `description` written on the schema of the content entry `requestBody` is read from (the fixed-order pick under Request Body Encoding above), as that schema stands in the document: a `$ref` is not followed, so a component's text stays on its model (`Pet.description`, read through `requestBody`), while a `description` written beside the `$ref` is read, as a field's is. A wrapper the type builder collapses — a nullable `oneOf`/`anyOf`, a single-member `allOf` — or keeps as a union of one variant it types by the same rule — a single-member `oneOf`/`anyOf` — is read by the rule its enum follows (see Enum): its own text when it has content, else its branch's or member's, nested wrappers composing outermost-first and a `$ref` branch never followed (`unwrapCollapsedWrappers`), so `oneOf: [{ type: 'string', description }, { type: 'null' }]` carries the text `type: ['string', 'null']` beside the same `description` does, and `oneOf: [{ type: 'string', description }]` the text `allOf: [{ type: 'string', description }]` does (#445). A `oneOf`/`anyOf` of consts read as an enum is the schema that declares the members, so its own text stands and a variant's, which documents that one value, is not read — nullable or not: `{ enum: ['draft', null], anyOf: [{ const: 'draft', description: 'Only drafts are accepted.' }, { type: 'null' }] }` is a nullable enum of `draft`, decided before any nullable wrapper is collapsed, as the type builder decides it (`nullableUnionBranch`), so the body carries no text and the member alone carries the variant's, as two consts beside `null` already read (#535). When both have content the body's own wins. The field is present only when one of the two has content, and the text is kept verbatim, as `responseDescription` is. The body's own text is carried whether or not a media type is read as `requestBody` — a body declared as `application/xml` alone still has its `description` — while the schema's is read only from the entry the pick chooses, never from a secondary media type's.

The schema's text has a second home when the body is an inline object: the model it is materialized as (`CreatePetRequest`) carries it as `description`, as a `oneOf` variant's model, a response body's model and a secondary media type's model already did, and as a webhook payload's does. So an inline object body described by its schema alone has the same text on `requestBodyDescription` and on `CreatePetRequest.description`; one described by the Request Body Object alone has the body's text on the operation and no `description` on the model; one described twice has the body's text on the operation and the schema's on the model. A body no single model carries — an inline `oneOf` (a union of variant models, each with its own text or none), an array, a primitive — has its schema's text on `requestBodyDescription` alone; an inline enum body has it there and as the `description` of the `Enum` it is lifted to (`<Op>Request` in `enums`, see Enum). A `oneOf: [object, null]` body is one schema: the model built from its object branch and, when the Request Body Object has none, `requestBodyDescription` both take the wrapper's text when it has content and the branch's own otherwise (`withWrapperDocs`). A `oneOf: [object]` body reads the same way on the operation, while the model built from its one variant keeps the variant's own text, as every variant's model does (see Collapsed wrappers): the two agree exactly when the wrapper has no text of its own. A discriminated union of inline objects flattened into one object (see Request Body Encoding) keeps the union schema's `description` on the flattened model. When a doc URL base is configured, relative links are expanded in `requestBodyDescription` exactly as in `description`.

A webhook's `requestBodyDescription` is read by the same rule from its payload (see Webhook below). The differ does not report a changed request body description, on an operation or on a webhook, the same as a changed response or operation description: it is documentation, not shape, and neither an `operation-modified` nor a `webhook-modified` change has a flag for it.

### Request Body Content Types

A request body that offers more than one media type (`application/json` and `text/csv` for a widget replaced from a record or from a spreadsheet row; `application/json` and `multipart/form-data` for an upload) keeps every media type it declares, as a response does (see Response Content Types below). `requestBodyContentTypes: string[]` holds the keys of the body's `content` map, in document order and exactly as written — parameters (`application/json; charset=utf-8`, `multipart/form-data; boundary=x`), vendor suffixes and case included — and `requestBodyContents: RequestBodyContent[]` one entry per media type in the same order, with the type that media type resolves to. Both are present only when the body declares at least one media type, whether or not one of them is read as `requestBody`; an operation without a body, or whose body has an empty `content` map, has neither. A key is never normalised or merged: `application/json` and `application/json; charset=utf-8` declared side by side are two entries.

`requestBody` is the type of the media type the fixed-order pick chooses (see Request Body Encoding above), the `requestBodyContents` entry for that media type carries the very same `TypeRef`, so the two can never disagree, and `requestBodyContentType` is that media type's essence. Every other entry is typed the way `requestBody` would be if it were the only one declared: from its schema when it has one — a `$ref` stays a reference to the component, an inline object is materialized as a model (below) — else `string` with `format: "binary"` for `application/octet-stream`, `string` for `text/plain`, and `unknown` for any other media type without a schema, a JSON or form media type included, since the pick reads those only with a schema. In the widget example `requestBody` is `ReplaceWidgetRequest` (the JSON wins the fixed order) while `requestBodyContents` reads `[{ application/json → ReplaceWidgetRequest }, { text/csv → string }]`. A body none of whose media types is read (`application/xml` alone) has `requestBodyContents` but no `requestBody`, and the parser warns once, as described under Request Body Encoding.

An inline object declared only for a secondary media type is materialized as a model named from the primary body's name without its `Request` suffix, the media type and `Request` — `ReplaceWidgetTextCsvRequest` beside `ReplaceWidgetRequest`; for an operation without an `operationId`, the path-derived prefix in place of the stem — with nested objects, array items and union variants named under it as `schemaToTypeRef` names them. The media type's fragment comes from its essence (`mediaTypeNameFragment`): case is folded, a wildcard segment reads as `Any`, and only when another key of the same essence is declared beside it does the fragment carry the key's parameters — the ones `oagen diff` compares, `charset` left out and the rest sorted, then `Charset`, without its value, when the key declares one and nothing else tells it apart — so two spellings of one media type take names that depend on neither their order nor a `charset`'s value: `application/xml` and `APPLICATION/XML; charset=utf-8` beside a primary `application/json` are `ReplaceWidgetApplicationXmlRequest` and `ReplaceWidgetApplicationXmlCharsetRequest`, and `application/xml; version=2` beside `application/xml` is `ReplaceWidgetApplicationXmlVersion2Request`. Keys still left with one name — case-only spellings (`Application/XML`, `APPLICATION/XML`), or keys that differ only in the order of their parameters or the value of the `charset` both declare — share one model when their shapes are identical, and otherwise the later steps to `ReplaceWidgetApplicationXmlRequest2`, in one order whatever the document's — by its essence as written, its parameters as `oagen diff` reads them (decoded, sorted) and its `charset`, case folded, lower case first — however a key quotes, spaces or orders its parameters, while keys alike in all of that differ only in such syntax and keep their document order (`mediaTypeNamingOrder`), with the limits a response's keys have (see Response Content Types). The name goes through the same spec-wide shape registry secondary response bodies, headers and fallback bodies use (`materializeInlineSchema`), seeded with every component and primary model before any of them is named and resolved in document order, an operation's secondary request bodies before its response bodies: an identical shape (fields, types, requiredness, limits, defaults and access flags alike) under a taken name shares the model, and a different shape under a taken name — a component's, a primary body's, another operation's — is re-derived with a numeric suffix (`ReplaceWidgetTextCsvRequest2`, `…3`, …); a title-mapped variant whose title is taken falls back to its context-qualified name, and one nested below the top level is renamed under the body's root with every reference rewritten, exactly as a secondary response body's is. The registry also holds every enum name decided before it runs — the component enums, and every inline enum any earlier pass minted on a model's field or an operation's parameter, envelope field, body or header — as names no model may take, so a secondary body (or a header, fallback, error or secondary response body) that derives an enum's name steps to its next candidate: a component enum `ReplaceWidgetTextCsvRequest` sends the `text/csv` body's model to `ReplaceWidgetTextCsvRequest2`. An inline enum under a secondary media type, at the top level or inside its models, is promoted to `spec.enums` like a secondary response body's (`ReplaceWidgetApplicationXmlRequestMode`); a name taken by an enum with a different value set, or by any model, is stepped to a distinct one (`collectDistinctEnums`) before the enum is promoted, on every path that promotes one, so the IR never declares a model and an enum under one name. The primary body's own `oneOf` handling — a discriminated union of inline objects flattened into one object, a union's variants named from their consts — applies to `requestBody` only; a secondary body is typed as any deferred schema is.

`collectRequestBodyTypes(op)` (exported from `@workos/oagen`) is the request-side twin of `collectResponseBodyTypes`: it yields every request body type an operation declares besides `requestBody` — every `requestBodyContents` entry except the one that shares `requestBody`'s type (`collectAlternateRequestBodyContents`), so every entry when no media type was read — each with a `source` for diagnostics (`requestBodyContents.text/csv`). Every pass that walks an operation's type refs — reachability (`collectReferencedNames`), model assignment (`assignModelsToServices`, `collectRequestBodyModels`), ref rewriting and validation (context `<Service>.<op>.requestBodyContents.<media type>`), the differ's direction index, where such a body is request-facing since the caller constructs it, the compat filter (`specDerivedNames`) and inline-enum collection — calls it beside `collectResponseBodyTypes`, so a body declared only for a secondary media type is emitted like the primary one. A webhook's secondary payloads are reached through `collectWebhookTypeRefs` the same way.

### Multiple Success Responses

`successResponses` holds every 2xx and 3xx response the operation declares, one `SuccessResponse` per status code with its own `type`, `headers` and `description`. A 2xx entry's `type` is its body, read from its `content` map by media type — compared by essence, so parameters and case do not matter (`application/json; charset=utf-8`, `TEXT/PLAIN`) while the keys themselves stay as written — in this order: the JSON schema when one is declared (`application/json`, else a `+json` media type such as `application/problem+json`); else `string` with `format: "binary"` when the map has `application/octet-stream` or `application/pdf`; else `string` when it has `text/plain`, `text/html`, `text/xml` or `application/xml` (a schema written on one of those four is not read); else the schema of the first media type that declares one. It is `unknown` when the response declares no content or none of those rules gives a type: a schema-less `text/csv` body is `unknown`, not `string`, while a `text/csv` body with a schema is typed from that schema. A 3xx entry's `type` is always `unknown`; the entry is kept so an emitter can recognize a redirect endpoint rather than try to deserialize a body. The list is set only when more than one such response is declared, counting 2xx and 3xx together: `200` + `201`, `200` + `302` and `301` + `302` all set it, while a lone `200` (or a lone `302`) leaves it `undefined`. Every 2xx body's inline models are read under the operation's one `<Op>Response` context, and the primary's (the lowest status code whose body has a type) keep it. Every later status code's body is then named for itself before it is merged (`stepSecondaryBody`): it moves, with every model and inline enum that context names, to the stem an earlier later status code took for a body of its shape (the same type and the same models by `shapeFingerprint`: the order of the fields, documentation and each model's own `deprecated` aside, so a 202 identical to the 201 but for the flag shares its stem, and the shared model is live while either body's copy is, see Deprecation, #630) — so a 201 and a 202 that declare one body are both `CreatePetResponse201` — else to its own status code (`CreatePetResponse201`, `CreatePetResponse201Owner`, `CreatePetResponse201Status`), then a number (`CreatePetResponse2`, `…3`) — a later status code's secondary media-type body steps from its status code to a number under it instead (`CreatePetApplicationYamlResponse201No2`, see Response Content Types) — a candidate being taken when no name it would give is kept, or owned by a component or another operation, under a shape the owner does not share, nor is the body of a response shared through `components/responses`, whichever operation returning it is read first (beside a schema `CardResponse201`, `card`'s 201 steps past a component `Card` whose body took `CardResponse2`, to `CardResponse3`). It moves whatever the primary declares, so it never shares the primary's models, whatever their shape: a 201 identical to the 200 is `CreatePetResponse201` beside `CreatePetResponse`, a 201 `{ owner: { id }, extra }` beside a 200 `{ owner: { id } }` is `CreatePetResponse201` over a `CreatePetResponse201Owner` of its own, and a list envelope kept at a 201 (no paging parameter) is `ListPetsResponse201 { data, total_pages }` whatever the 200 is. So no edit to the primary renames a later status code's models: a field added to a 201 that matched the 200 is an additive change to `CreatePetResponse201` in `oagen diff`, not a move off `CreatePetResponse`, and a `status` enum the 200 adds leaves the 201's own `status`, `CreatePetResponse201Status`, as it was, and the status code's secondary media-type bodies are named for it the same way (`CreatePetApplicationYamlResponse201`, see Response Content Types); and `successResponses` never gives a status code a shape it did not declare. Two bodies keep the names they were read under unless one of those names clashes, and then step the same way: a response shared through `components/responses`, whose body is the component's wherever it is mounted (see Inline model naming), and an array body or a list envelope unwrapped to its items, whose items were settled against the spec-wide registry as they were read (`CreatePetItem`). A model carries the context as a prefix (`CreatePetResponseOwner`), as a suffix (a const-named variant, `BCreatePetResponse`) or in between (a const-named nested variant, `SquareCreatePetResponseShape`), and moves by that one occurrence (`BCreatePetResponse201`, `SquareCreatePetResponse201Shape`), as an inline enum does (`CreatePetResponseOwnerRole` → `CreatePetResponse201OwnerRole`; a `$ref` to a component enum, which carries no values, stays as written); every reference moves through the one rewriter every rename site uses (`renameTypeRefModels`, `renameModelRefs`), so a union's `discriminator.mapping` follows each variant (`{ a: 'CreatePetResponse201', b: 'BCreatePetResponse201' }`) and never keeps naming the model that moved — and only a reference the body itself minted moves, by identity rather than by name (`isComponentModelRef`, `isInheritedModelRef`, the filter the merge passes use): beside a component `CreatePetResponseOwner { id }`, a 201 `{ owner: { name }, original: { $ref: CreatePetResponseOwner } }` steps its inline `owner` to `CreatePetResponse201Owner` while `original` keeps naming the component. A model the context does not name — a settled item (`CreatePetItem`), a titled variant — keeps its name, and a clash on such a model still resolves to the kept definition, with a warning — unless the two are the same shape but for the model's own `deprecated`: then the kept definition stays, its references with it, live while either copy is and documented as the first live copy is, silently (see Deprecation, #630). Of a later status code's models, those its entry's `type` still reaches are kept (a model the context does not name that the primary holds under the same name and shape is read through the primary's), and the models only a dropped copy referenced go with it, so no model is left that nothing references; the primary's are all kept, its paging companions included. 4xx and 5xx responses go to `errors`; `default` and the ranges `1XX`–`5XX` go to `defaultResponse` and `rangeResponses` (see Default and Range Responses below); an explicit 1xx code is not carried. A key is a status code only when it is exactly three digits in 100–599; a key that merely starts with digits (`6XX`, `4XXX`, `20X`, `600`, `200 `) is neither a status code nor a range and is ignored with a warning, as the Default and Range Responses section describes.

`response` always points at the primary response, chosen by one rule before any body is classified (the choice a pagination override is decided against; see [Overriding detection](#overriding-detection)): the lowest declared status code whose type is not `unknown` — the lowest 2xx with a typed body, so a `200` whose body the media-type rules leave `unknown` (a schema-less `text/csv`) yields to a `201` typed from a schema, and `response` and `responseDescription` then come from the `201` — falling back to the lowest declared code (an untyped 2xx, or a 3xx when the operation declares no 2xx). `responseHeaders` and `responseDescription` come from that same entry, whether or not `successResponses` is set. An operation declaring no 2xx or 3xx response at all (only `default` or `2XX`, only a `404`, an empty `responses` map, or no `responses` key) has `response` set to `{ kind: "primitive", type: "unknown" }` — the type of a body the document does not describe — with no `responseDescription` or `responseHeaders`: a `2XX` range or `default` body is never promoted into `response` (see Default and Range Responses below). An emitter that handles status codes differently (200 vs 204, or a 302 beside a 200) reads `successResponses`; one that only needs the return type reads `response`. `responseStatusCode` is the status code of that primary entry (`200`; `201` when an untyped `200` yielded to a typed `201`; `302` for a lone redirect), present exactly when the operation declares at least one 2xx or 3xx response and absent otherwise, so a consumer that checks a live status against the document — the smoke helpers in `@workos/oagen/smoke` — reads the declared code instead of guessing one from the HTTP method. When `successResponses` is set, it equals the `statusCode` of the entry `response` was taken from. The differ pairs a lone 2xx/3xx by it — with the other spec's entry of the same code, whether that spec declares it alone or beside a code it added — and reports it moving while both specs carry one as `responseStatusCodeChanged`, breaking unless the new spec still declares the old code among its 2xx/3xx — a lone `200` that became a lone `201` is breaking; a `200` added beside a lone `201`, which makes the `200` the primary, is additive, since the `201` is still declared; only two lone primaries pair over such a move, so a primary replaced among several 2xx (`200` + `202` → `201` + `202`) has what it declared reported removed under its old code, breaking as well (see `oagen diff` in the CLI reference).

A 2xx body that is itself an inline enum, or an array of one, mints no model: it is promoted to `spec.enums` under the name the body is typed by — `<Op>Response` for an enum (`GetPetKindResponse`), and for an array of one the `<Op>Item` name an array body's items take (`GetPetKindItem`) — with the per-value documentation and link the schema declares (see Enum below). When `successResponses` is set, each entry's body is promoted on its own under its status code: every entry of one shape derives the same name, `<Op>Response` or `<Op>Item`, so identical members share one enum, and a body with other members — or the same values deprecating a different one — is qualified with its status code (`CheckPetKindResponse202`, `CheckPetKindItem202`), then numbered. A body whose name an enum of other members already owns — a component's — is qualified the same way when `successResponses` is set (`CheckPetKindResponse200`, which a later entry with the same members shares) and numbered otherwise (`GetPetKindResponse2`, even beside a component `GetPetKindResponse404` with the same members: only a name the operation's own sites stepped to is shared, see Response Headers); a name a model owns is never taken. A body a response shared through `components/responses` declares is the component's at whatever status code an operation mounts it, so its enum steps by number alone (`CardResponse2`), never by the status code, and every operation that returns the component shares it, as it shares the component's headers. The request body's enum is promoted the same way under `<Op>Request` (see Request Body Encoding above).

```yaml
responses:
  "200":
    description: The pet
    content:
      application/json:
        schema: { type: string }
  "302":
    description: Moved
```

```typescript
op.response = { kind: "primitive", type: "string" };
op.responseDescription = "The pet";
op.successResponses = [
  {
    statusCode: 200,
    type: { kind: "primitive", type: "string" },
    description: "The pet",
  },
  {
    statusCode: 302,
    type: { kind: "primitive", type: "unknown" },
    description: "Moved",
  },
];
```

### Response Descriptions

A response's `description` — often the clearest statement of what an operation gives back ("The pet, with its owner.", "Not found") — is kept with the status code it belongs to as `description` on each `SuccessResponse` and `ErrorResponse`. Because `successResponses` is only set when more than one 2xx or 3xx response is declared, the primary response's description (the one `response` is the body of) is also exposed directly as `Operation.responseDescription`, where an emitter can print it as a `@returns` tag. All three fields follow the rule `Operation.summary` uses: present only when the document declares a description with non-whitespace content, kept verbatim when it does, and omitted otherwise — a description is never borrowed from another status code. A `$ref` into `components/responses` is resolved first, so the component's `description` is read; in an OAS 3.1 document a `description` written next to the `$ref` overrides it (outermost first along a chain; a blank one falls through), while in an OAS 3.0 document, where properties beside a `$ref` are ignored, the component's own is kept — the rule every Reference Object follows (see Reference Objects). A `$ref` that points outside `components/responses` is read as written, so only its sibling `description` is seen, and in an OAS 3.0 document none is (see "Shared through `components/responses`" under Inline model naming). When a doc URL base is configured, relative links are expanded in response descriptions exactly as in `description`. The differ does not report a changed response description, the same as a changed operation description.

### Response Headers

Headers a response declares (`Content-Disposition` on a download, `Location` after a create, `ETag`, rate-limit headers) are kept with the status code they belong to as `headers: ResponseHeader[]` on each `SuccessResponse` and `ErrorResponse`. Because `successResponses` is only set when more than one 2xx or 3xx response is declared, the primary response's headers are also exposed directly as `Operation.responseHeaders`.

Each header is typed like a parameter via its `schema` or, in its place, the entry of its `content` map read by the parameter rule (see `Parameter` above: `application/json` or a `+json` media type when the entry declares a schema, else `text/plain`, matched by media type essence); a header with neither, a `text/plain` entry without a schema, or a map none of whose media types is read — the last with a warning that names them — is a `string`. `$ref`s into `components/headers` are resolved, and a `description` written next to the `$ref` overrides the component's (OpenAPI 3.1); a ref that cannot be resolved is warned about and dropped rather than failing the parse. A header named `Content-Type` is ignored, as OpenAPI requires. Header names are case-insensitive (RFC 9110 §5.1; OpenAPI says so of the `headers` map), so two keys of one response that differ in case alone (`X-Request-Id` beside `x-request-id`) declare one header: the later key is kept, in the earlier one's position, with an `[oagen] Warning:` naming both, and `ResponseHeader.name` is that key as written. All three fields are present only when at least one header survives, so operations without headers keep their shape.

An object-shaped header (directly, inside an array, or as a oneOf variant) is materialized as an inline model named from the service and the lower-cased header name (`Documents` + `X-Meta` → `DocumentsXMeta`; `X-RateLimit-Policy` → `DocumentsXRatelimitPolicy`, whatever case the document writes the header in, so the name does not move when the case does), nested objects included (`DocumentsXMetaOrigin`). A header declared on a response shared through `components/responses` is named from the component's stem and the header name instead (`Card` + `X-Meta` → `CardXMeta`, nested `CardXMetaOrigin`), the same name from every operation that returns the component, whatever service the operation belongs to and whatever status code or fallback key it mounts the component at, so they share one model as they share the body (see "Shared through `components/responses`" under Inline model naming); when that name is owned by a shape it does not share, it steps by number (`CardXMeta2`, `CardXMeta3`, …), never by the operation or the status code, so the stepped name still comes out the same from every operation. Because that name can already belong to a differently shaped component schema, to the same header on another status code, or to the same header on another operation of the service, the parser keeps a spec-wide registry of model shapes, seeded with the component models and enums and the models and enums the components' fields mint, and filled as the operations are read: each operation's request body and primary response models (nested objects and union variants included) once it is built — the items of an array body or a list envelope are settled against the registry as they are typed (see Inline model naming) — then the shared envelope companions once named, then each header, secondary body and parameter: those of the responses shared through `components/responses` first, component by component (see "Shared through `components/responses`" under Inline model naming), then every operation's own in document order (path order; within an operation its responses first — ascending status code, headers before bodies — then its parameters). The registry also holds every enum name — the component enums' and the name every inline enum a model field, a parameter, a body or a response header mints is lifted under (`PetsKind`; an operation's references are listed by `collectOperationTypeRefs`) — which no model may take, each recorded with the operation whose own reference carries it, so a deferred model named like an enum steps as it would beside a model of another shape: by operation when the enum is a component's, a field's or another operation's, by location when it is the operation's own (`PetsQueryStatus` for a `status` query object beside the operation's `status` header enum). Every enum a deferred site types — a header or body that is itself an enum, an enum nested in a model the site mints — is held the same way before any deferred site is named, under the name the site lifts it under at its bare name, so a site that derives one of them steps the same way whether the document declares it before or after the enum (`PetsSearchPetsXMode` for an `X-Mode` header parameter object beside another operation's `X-Mode` response-header enum; `GetPetError404Body` for `getPet`'s object 404 beside `get-pet`'s enum 404; `SearchPetsError404ListNotesX` for an `x` parameter or header object of `listNotes`, in a `SearchPetsError404` service, beside the `x` enum nested in `searchPets`'s 404 body). A site that itself steps past its bare name lifts its nested enums under the name it steps to (`GetPetError404BodyX`), so the name held for one of them is then no enum's, and a model that derives it has stepped all the same; a name one of the site's own models takes too is left to the merge passes (see Inline model naming). The first owner of a name keeps it, and a later header with a different shape is re-derived under the first free candidate — bare name; then each name an earlier `X-Meta` header of the service settled on, in the order they were resolved and with the renames made under it replayed, so a header identical to one that had to step past a taken bare name shares its model under that name, nested models included (when a title-mapped variant of the 200 body owns `DocumentsXMeta`, the 200's header settles on `DocumentsXMeta200` and the identical 429 header shares it rather than minting `DocumentsXMeta429`) while a different shape steps past it; then the status code (`DocumentsXMeta429`) when the clash is inside the same operation, or the operation when it is with a component (a header or body of a response shared through `components/responses` among them, whichever operations return it), a primary body or another operation — the stem the operation's request and response models are built from, never its name: for an operation with an `operationId`, the id's stem cleaned as its `…Response` model name is (`DocumentsCreateDocumentXMeta` from `operationId: createDocument`; `PetsAnimalListNotesXMeta` from `Animals_ListNotes`, beside `AnimalListNotesResponse`; `PetsNoteListXMeta` from `notes.list`, beside `NoteListResponse`), so what an `operationIdTransform` makes of the id renames no header — a transform that drops the `Animals_` prefix names the operation `ListNotes` and its header `PetsAnimalListNotesXMeta` still, never `PetsListNotesXMeta` (before #537 the operation's name qualified it, so a change to the transform was a breaking `model-removed` in `oagen diff` for the header while the body kept its name) — the stem alone, though, only while it names something: an id that cleans to nothing (`ListItem`) is qualified by the id PascalCased before the cleaning instead, which no transform changes either (`PetsListItemXMeta`), and an operation that loses its stem to another's id (`listNotesByExternalId` beside `listNotes` or `list_notes`, `ByExternalId` being a marker the cleaning strips; see "With an `operationId`" under Inline model naming) is path-named throughout, so its header is qualified by its path stem as its bodies are (`PetsByIdNotesByExternalIdGetXMeta` beside `PetsByIdNotesByExternalIdGetResponse`), while `listNotes` keeps `PetsListNotesXMeta` whatever operation is added beside it (before #627 one stem named both operations' bodies, so it qualified neither one's header and each was qualified by its id as written, `PetsListNotesByExternalIdXMeta`; before #537 the second one's header fell to `PetsXMeta200`, and which operation kept the qualified name followed document order); whether a stem is contested depends on the document's ids alone, never on their order, so adding `listNotesByExternalId` beside `listNotes` adds its path-named models and renames nothing, while adding `listNotes` beside a lone `listNotesByExternalId`, which held the stem alone, is what `oagen diff` reports as the models under the stem modified beside the path-named ones added; for an operation without one, the path stem, less the service's own leading word, so `POST /notes/{id}/pin` in `Notes` gives `NotesByIdPinPostXMeta` beside `NotesByIdPinPostResponse`, and the name depends on the method and path alone, never on the derived operation name; then the other of those two; then both (`DocumentsCreateDocumentXMeta429`); then a numeric suffix (`DocumentsXMeta2`, `DocumentsXMeta3`, …). A union variant named from its title (`Circle`) does not change with the candidate, so every taken name is also reserved for the extractor, which gives such a variant its context-qualified name instead (`CircleDocumentsXMeta`); a titled variant nested below the top level, which no reservation reaches, is renamed under the header's root (`DocumentsXMetaCircle`) with every reference rewritten (`materializeInlineSchema`, see Default and Range Responses below), so naming always terminates. A header whose shape matches the name's owner shares it and materializes nothing new, so a header matching a component schema simply references that schema; the shape covers every field's type, requiredness, limits, default and access flags and the model's own limits, so two headers that differ only in a `minLength` keep separate models. Inline header enums follow the same idea with their own, status-code-based rule: a header enum is named from the service and header (`PetsXPolicy`); a name an enum of other members, or a model, already owns steps to the status code (`PetsXPolicy429`; the response's label for a fallback, `PetsXPolicyDefault`), then a numeric suffix — except for a header of a response shared through `components/responses`, whose enum is the component's (`CardXMode`) and steps by number alone (`CardXMode2`), the same from every operation, status code and fallback key that mounts the component (the parser hands the collector the references such sites wrote, `componentSites`, since the IR alone cannot tell them from an operation's); a taken name with the same members is shared, and identical members on a later status code or on the `default` response share the name an earlier header of the same operation stepped to (`PetsXPolicy429` for the 503 and the `default`, so no `PetsXPolicy503` or `PetsXPolicyDefault` is minted), as #331 shares an identical inline model across status codes. Only the operation's own steps are shared that way: a name another operation's header stepped to (`listPets`'s `PetsXPolicy429`), or a component enum whose name merely reads as a step (`PetsXPolicy2024`), belongs to another site, so `getPet`'s lone 2xx header with those members is numbered (`PetsXPolicy2`), and so are a parameter enum and a component response's header beside such a component (`PetsStatus2` beside `PetsStatus2024`, `CardXMode2` beside `CardXMode2024`). The rule is applied inside a header's models too, so a nested enum whose name a component enum already owns with other values is renamed rather than silently given the component's values.

A parameter in any location — path, query, header or cookie, a query parameter the body owns included — whose inline schema mints a model (an object, as a `style: deepObject` query parameter is; an array or map of objects; a union with an inline object variant; a nullable wrapper around one; at any depth) is materialized through the same registry, named from the service and parameter name as `schemaToTypeRef` referenced it (`Pets` + `filter` → `PetsFilter`, nested objects `PetsFilterOwner`; a header's name lower-cased first, so `X-RateLimit-Meta` and `x-ratelimit-meta` both give `PetsXRatelimitMeta`, a path, query or cookie name as written), with the parameter's location where a header has its status code: the bare name; then the location (`PetsQueryFilter`) when the clash is inside the same operation — one name in two locations, or a response header of the same name, which the operation typed first and which keeps its name (`PetsXMeta` for the header, `PetsHeaderXMeta` for the header parameter), or an enum the operation's own parameter, body or response header carries (`PetsStatus` lifted from a `status` header enum, so a `status` query object is `PetsQueryStatus`); or the operation (`PetsListPetsFilter`) when it is with a component model, a component enum, an enum another operation's parameter or a field lifts (`PetsKind` on `listPets`, so `kind` on `searchPets` is `PetsSearchPetsKind`), a primary body or another operation — the operation spelled as a response header's is (see Response Headers), by the stem its bodies are named from and never by its name, so a `filter` query object or an `X-Trace` header parameter object on `Animals_ListNotes` is `PetsAnimalListNotesFilter` or `PetsAnimalListNotesXTrace` beside `AnimalListNotesResponse` whatever an `operationIdTransform` names the operation — or by the id as written when the stem names nothing (`PetsListItemFilter` on `ListItem`, see Response Headers), and by the path stem when the operation lost its stem to another's id, since it is then path-named throughout (`PetsByIdNotesByExternalIdGetFilter` and `PetsByIdNotesByExternalIdGetXTrace` on `listNotesByExternalId` beside `listNotes`'s `PetsListNotesFilter` and `PetsListNotesXTrace`; see "With an `operationId`" under Inline model naming) — and on a path-named `GET /pets/{id}/notes` in `Pets` `PetsByIdNotesGetFilter` beside `PetsByIdNotesGetResponse`; then the other of those two; then both (`PetsListPetsQueryFilter`); then a numeric suffix (`PetsFilter2`, …). A parameter whose shape matches the name's owner shares it, so the same `filter` on two operations of one service is one `PetsFilter`. An enum keeps a name a parameter model also derives, wherever the document declares the two. One a parameter, a request body, a success body or a pagination field carries is typed as its operation is built, before any deferred site is named: a `status` query enum on a later operation sends an earlier operation's `status` object to `PetsListPetsStatus`, so adding such an operation to a document renames the existing model, which `oagen diff` reports as a breaking `model-removed` beside a `model-added`. One a deferred site types — a response header, an error, secondary or fallback body, a parameter model, whether the site is itself the enum or nests it in a model it mints — is held before any deferred site is named, as above: a `filter` response-header enum sends a `filter` parameter object to `PetsListPetsFilter` whichever of the two operations comes first, and a `status` enum nested in a later operation's `filter` object (`PetsFilterStatus`) sends an earlier operation's `filterStatus` object to `PetsListPetsFilterStatus`. A parameter that mints no model — a primitive, a `$ref`, an inline enum, an array of either — keeps the type `schemaToTypeRef` gave it and is not registered; an inline parameter enum is still lifted under its service-qualified name (`PetsKind`). Webhook parameters are materialized under the webhook's stem instead (see Webhook).

`collectResponseHeaders(op)` (exported from `@workos/oagen`) yields every header list once — the primary list is the same array as its `successResponses` entry — and is what reachability, model assignment, ref rewriting/validation, the differ, and the compat filter use, so a model or enum reached only through a header is emitted like any other. `collectOperationTypeRefs(op)` (also exported) yields every type reference an operation carries — its parameters in every location, the query parameters the body owns included, its request body and the body of every other request media type (`collectRequestBodyTypes`), its primary response and every other success body, every error body, the pagination item type and envelope fields, every header through `collectResponseHeaders` and every secondary, fallback and range body through `collectResponseBodyTypes` — the one list the parser's name reservations read (the enum names held before the deferred pass, the names a merge pass must mint around, the names a webhook must step around), as `collectWebhookTypeRefs(webhook)` is for a webhook.

The differ compares the headers themselves, entry by entry, and reports a header added, removed, retyped, re-required, respelled or deprecated under `responseHeaderChanges` on the `operation-modified` change, each entry carrying the header's name as written and its `statusCode` or `fallback` (`responseStatusCode` for a lone 2xx; neither only for a lone 2xx of a hand-built IR that carries no code). A change is located at the entry of the spec that declares what changed — a removal at the old spec's entry, every other kind at the new spec's — so an operation that lost its only 2xx, whose new primary carries no code, reports that entry's headers under its old code. It walks the entries through the walk its media-type comparison uses rather than through `collectResponseHeaders`, since that flat list does not say which response a header belongs to; a test pins that the two walks yield the same headers, list for list. Headers are matched by name case-insensitively, as HTTP compares header names, and classified from the reader's side: removed, retyped or no longer required is breaking; added, respelled, deprecated or now always sent is additive (see `oagen diff` in the CLI reference).

### Response Content Types

A response that offers more than one media type (`text/html` and `application/pdf` for a card that renders as a page or a printout; `application/json` and `application/vnd.api+json`; `application/json` and `*/*`) keeps every media type it declares. Each `SuccessResponse` and `ErrorResponse` carries `contentTypes: string[]` — the keys of its `content` map, in document order and exactly as written, parameters (`application/json; charset=utf-8`), vendor suffixes and wildcards included, so an emitter can offer them verbatim in an `Accept` header — and `contents: ResponseContent[]`, one entry per media type in the same order, with the type that media type's schema resolves to. Both are present only when the response declares at least one media type; a response without `content` (a 204, a redirect without a body) or with an empty `content` map has neither. As with headers, the primary success response's two lists are also exposed on the operation as `responseContentTypes` and `responseContents` (the same arrays), because `successResponses` only exists when there is more than one 2xx or 3xx response.

`Operation.response` is the type of the media type the parser's fixed-order pick chooses (the JSON schema — `application/json`, else a `+json` media type; else `application/octet-stream` or `application/pdf` as binary; else `text/plain`, `text/html`, `text/xml` or `application/xml` as a string; else the schema of the first media type that declares one — each matched by essence, see Multiple Success Responses above). The `contents` entry for that media type carries the very same `TypeRef` as `response` (and as `type` on the `SuccessResponse`), so the two can never disagree. Every other media type is typed the way `response` would be if it were the only one declared — binary for `application/octet-stream` and `application/pdf`, a string for the text and XML types whatever their schema says, the schema's type for anything else, and `unknown` for a media type with no schema. A body under one of those binary or text media types — `application/octet-stream`, `application/pdf`, `text/plain`, `text/html`, `text/xml`, `application/xml`, by essence (`responseBodyReading`, the one classification the primary pick, every secondary entry and `sentOnlyComponentNames` read) — reaches no component: its schema is not read, as the primary body or a secondary one, at a 2xx, 3xx, error, `default` or range entry, inline or shared through `components/responses`, so a `listNotes` `200` of `$ref: Pet` under `application/xml` alone types nothing as `Pet` and does not count as receiving it — `Pet` stays only sent when `createPet` alone sends it (see Inline model naming) — while one under `application/json`, `application/yaml`, `*/*` or a `+xml` type such as `application/atom+xml` is typed from its schema and receives it. In the card example `response` is binary (the PDF wins the fixed order) while `contents` reads `[{ text/html → string }, { application/pdf → binary }]`. A 3xx entry's `type` is not read from any media type, so each of its entries is typed on its own — the JSON body of a response shared through `components/responses` is still named after the component there (`CardResponse`, see Inline model naming), so it is one model with the body a `200` or a `404` that returns the component has. An error entry's `type` is read from its JSON body — `application/json`, else the first `+json` media type (`application/problem+json`), matched by essence as for a fallback response — and is otherwise untouched; its `contents` entry for that media type shares it, and the others are typed as above. Because an error's `type` is its JSON body by definition, an error carries the two lists only when they say something `type` does not — it declares another media type (`text/html` beside `application/json`), a JSON media type other than plain `application/json` (`application/problem+json` alone, or `application/json; charset=utf-8`), or a JSON body with no schema that `type` could not be read from. An error that declares only `application/json` with a schema, the overwhelmingly common case, keeps exactly the shape it had.

An inline object declared only for a secondary media type is materialized as a model named from the entry's body name and the media type: for a success entry, the operation's response stem, the media type and `Response` (`RenderPetCardTextHtmlResponse`); for an error entry, the error body's `<Op>Error<code>` and the media type (`RenderPetCardError500ApplicationYaml`), so the status code is in the name whether or not another status code declares the same media type, and the body is deferred and stepped as the error body is (`RenderPetCardError500ApplicationYamlBody` on a clash; see Error Responses below) — with nested objects, array items and union variants named under it as `schemaToTypeRef` names them. One declared on a response shared through `components/responses` is named from the component's stem and the media type, with `Response` as the suffix at whatever status code or fallback key an operation mounts the component — `CardApplicationYamlResponse` from a 200 and from a 404 alike, as the component's primary body is `CardResponse` at either — so every operation that returns the component shares one model; when that name is owned by a shape it does not share (a component response `CardApplicationYaml`, whose body is `CardApplicationYamlResponse`), it steps by number (`CardApplicationYamlResponse2`), never by the status code, so the 200 and the 404 still agree. Which keyword types an ambiguous schema — `allOf` before `oneOf`/`anyOf`, before `items`, before `properties`, before a bare map — is decided once by `classifyInlineSchema`, which `schemaToTypeRef` and every inline-model extractor dispatch on, so the models materialized are exactly the ones the type references. The media type's PascalCase form is taken from its essence — parameters stripped, case folded (`mediaTypeNameFragment` in `src/utils/media-type.ts`) — so a key that only respells itself between two spec versions keeps its model name (`application/yaml` and `application/yaml; charset=utf-8` both give `ApplicationYaml` when each is the only YAML key), which is what lets `oagen diff` see an unchanged body; a wildcard segment reads as `Any` (`ApplicationAny`). Two keys of one essence declared side by side in one response are told apart by the parameters `oagen diff` compares them by — every parameter but `charset`, sorted by name, lower-cased and cased after the essence (`application/yaml; version=2` → `ApplicationYamlVersion2`, `application/yaml; b=2; a=1` → `ApplicationYamlA1B2`) — and a key that declares a `charset` beside a key with the same other parameters by `Charset`, without its value (`application/yaml` → `ApplicationYaml`, `application/yaml; charset=utf-8` → `ApplicationYamlCharset`). So a key's fragment depends on neither the keys' order, nor its parameters' order, nor its `charset`'s value, and a key with no parameter but a `charset` keeps its name when a key told apart by another parameter is declared beside it (`application/yaml; charset=utf-8` stays `ApplicationYaml` beside a new `application/yaml; version=2`). Declaring a key beside another of its essence can still rename the other, since a name is decided from the keys alone: a key's other parameters reach its name only beside a key of its essence, so a lone `application/yaml; version=1` is renamed `ApplicationYamlVersion1` once a `version=2` is declared beside it; and its `charset` reaches its name only beside a key with the same other parameters, so `application/yaml; charset=utf-8` is renamed `ApplicationYamlCharset` once `application/yaml` is declared beside it, whatever else is (a `version=2` included). Two keys still left with one name — they differ only in case (`application/yaml`, `Application/YAML`), in the order or quoting of their parameters, or in the value of the `charset` both declare — go through the registry described next in one order whatever the document's — by its essence as written, its parameters as `oagen diff` reads them (decoded, sorted) and its `charset`, case folded, lower case first — however a key quotes, spaces or orders its parameters (`mediaTypeNamingOrder`), so `application/yaml` takes the bare name beside `Application/YAML` wherever either is written, and `application/yaml; profile=print` beside `Application/YAML; profile="print"`; two keys alike in all of that differ only in such syntax (`; b=2; a=1` beside `; a=1; b=2`) and keep their document order. An edit that changes that order still swaps the two keys' models — a case edit to one of two case-only keys (`application/yaml` → `APPLICATION/YAML` beside `Application/YAML`), a `charset` edit to one of two keys that differ in nothing else (`latin1` → `windows-1252` beside `utf-8`), or a reorder of two keys that differ only in syntax — since no order stays put both when two keys are reordered and when one of them is respelled. Editing such a key's parameters other than `charset` (`; version=1` → `; version=3`) renames its model; `oagen diff` compares paired bodies by shape, so that rename is reported as `model-removed` + `model-added` plus the key as `reparameterized` (additive), and not as a retyped media type (see `oagen diff` in the CLI reference). The name goes through the same spec-wide shape registry headers and fallback bodies use (`materializeInlineSchema`, see below), seeded with every component (and every model a component's field mints) and primary model before any of them is named, and resolved in document order, the bodies and headers of the responses shared through `components/responses` first (see Inline model naming). A component's name is shared by every shape the component admits — the same fields and types, the component no stricter on requiredness or nullability, everything else identical; the one rule by which an inline model folds onto a component anywhere (see Models) — and an operation's model by an identical shape only (fields, types, requiredness, limits, defaults and access flags alike). The bare name belongs to the primary status code's body (the entry `Operation.response` is read from, see Multiple Success Responses): a shape the owner of a taken name does not share — a component that does not admit it, a differing primary body, another operation's model — is re-derived with its status code (`…Response200`), then a numeric suffix (`…Response2`, `…Response3`, …). A later 2xx's secondary body is named for its status code, as its primary body is, and then numbered under that code (`…Response201`, then `…Response201No2`, `…Response201No3`, … — the `No` that keeps a number off a digit), a run of its own that the primary's `…Response2`, `…Response3` never meets, whatever the primary's body under that media type declares, so it never shares the primary's model and no edit to the primary — a key it gains, a shape it changes, a component it stops fitting — renames it: a 201 `application/yaml` body identical to the 200's is `CreatePetApplicationYamlResponse201` beside the 200's `CreatePetApplicationYamlResponse`, a field added to either is an additive `model-modified` to that one's model in `oagen diff` (exit `1`), not a retyped media type, and the names are the same whichever status code the document declares first. Among the later status codes, an identical shape shares the model under whichever name the earlier status code's body settled on — `…Response201`, or the `…Response201No2` it took when a component schema owned `…Response201` — because each such site tries the names the earlier later sites of the same bare name settled on before its own, replaying the renames made under each (a nested titled variant renamed under the body's root, `…Response201Circle`, is built under that name again, so it is shared too), and a different shape is re-derived with its own status code (`…Response202`), then a number under it (`…Response202No2`), and a status code after it with that shape shares it in turn (`…Response202` for a 202 and the identical 203); a later body that is itself an inline enum clashes with no model, so it shares an earlier later status code's name only when that body is an enum of the same members, and is otherwise named for its own status code as an object body in its place is (`…Response202` for a 202 enum `[c, d]` beside a 201 enum `[a, b]`, never `…Response201No2`; `…Response201` for a 202 enum `[a, b]`); a later body that is a primitive, an array of primitives or a `$ref` to a component owns no name under its stem, so a later object body never takes it (a 202 object beside a 201 `type: string` YAML body is `…Response202`, and stays so when the 201's YAML body is removed); the sites of one bare name are the bodies whose keys derive it — the same key on two status codes, a key respelled without parameters another key beside it shares (`application/yaml; charset=utf-8` alone on the 201, `application/yaml` on the 202), two keys of one response left with one name, such as two that differ only in case (on the 201, the second steps to `…Response201No2`) — while two spellings side by side told apart by their parameters, or by a `charset`, derive two names and never share. A 3xx entry's bodies, none of which its `type` is read from, and a fallback entry's are not a later 2xx's: they keep the bare name and step by status code as the primary's do, so a 302's `application/yaml` body of the 200's shape still shares `CreatePetApplicationYamlResponse`. An error entry's secondary body carries its status code in its bare name, so it has no such sibling: a 400 and a 404 that declare the same `application/yaml` shape get `GetNoteError400ApplicationYaml` and `GetNoteError404ApplicationYaml`, two models, as their JSON bodies are two. A title-mapped variant whose title is taken falls back to its context-qualified name (`CircleRenderPetCardApplicationVndShapeJsonResponse`), and one nested below the top level, which no reservation reaches, is renamed under the body's root (`RenderPetCardApplicationVndShapeJsonResponseCircle`) with every reference rewritten, exactly as a header's or a fallback body's is. An inline enum under a secondary media type, at the top level or inside its models, is promoted to `spec.enums` like a header's; a clash with a different value set, or with a name a model owns, is renamed with a numeric suffix — for a component response's YAML body that is itself an enum, `CardApplicationYamlResponse2` from a `default` and a `4XX` alike. Two media types of one response with identical inline bodies keep a model each — `ListPetsResponse` for the primary `application/vnd.a+json` body and `ListPetsApplicationVndBJsonResponse` for `application/vnd.b+json` — since a secondary body's name carries its media type by design; the sharing above is between the sites of one bare name, never across media types.

`collectResponseBodyTypes(op)` (exported from `@workos/oagen`) yields every response body type an operation declares besides `response`, each with a `source` for diagnostics (`contents.text/html`): today the bodies of its secondary media types — every content entry except the one that shares the response's own `type`, which `response`, `successResponses[].type` and `errors[].type` already cover, each list once — then the fallback bodies of its `default` and range responses (`defaultResponse`, `rangeResponses.4XX`). It is the one place to extend: reachability, model assignment, ref rewriting/validation, the differ, the compat filter and enum collection all call it beside `collectResponseHeaders`, so a body declared only for a secondary media type is emitted like the primary one.

### Default and Range Responses

OpenAPI lets a Responses Object carry two kinds of key besides explicit status codes: `default`, which applies to every status the operation does not list, and the ranges `1XX`–`5XX`, each of which applies to every status in its hundred that is not listed explicitly. Neither has a status code, and `ErrorResponse.statusCode` / `SuccessResponse.statusCode` are numbers that emitters compare and format as such, so they live in two additive fields instead of being folded into `errors` or `successResponses`:

| Document key     | IR                                                                                                                |
| ---------------- | ----------------------------------------------------------------------------------------------------------------- |
| `default`        | `Operation.defaultResponse: { type?, contentTypes?, contents?, headers?, description? }`                          |
| `4XX` (or `4xx`) | an entry of `Operation.rangeResponses: { range: '4XX', type?, contentTypes?, contents?, headers?, description? }` |

To resolve what an operation returns for a status, an emitter follows OpenAPI's own precedence: the explicit entry (`successResponses`/`errors`), then the range the status falls in (`rangeResponses`), then `defaultResponse`. In practice `defaultResponse.type` is the API's error shape, so an emitter can type the errors it does not list individually. Both fields are absent — not empty — on an operation that declares neither.

What the parser deliberately does not do:

- **No promotion.** `response` is the primary pick described under Multiple Success Responses (the lowest explicit 2xx or 3xx with a typed body, else the lowest declared); an operation whose only success is `default` or `2XX` has `response` set to `{ kind: 'primitive', type: 'unknown' }`, the type of a body the document does not describe. What to use instead: an emitter resolves any status as the explicit entry, then the matching `rangeResponses` entry, then `defaultResponse` — so when no explicit 2xx exists, the success body is the `2XX` range's `type`, then `defaultResponse.type`. `errors` likewise holds explicit 4xx and 5xx codes only.
- **No synthetic codes.** A `4XX` is never recorded as a `400`, which would make an emitter claim a code the spec does not.

A fallback response written as a Reference Object (`default: { $ref: '#/components/responses/Problem' }`) is resolved first — chains are followed, JSON Pointer escapes honored, and a `description` written beside the `$ref` wins over the component's in an OAS 3.1 document and is ignored in a 3.0 one; a `$ref` that points outside `components/responses` (into another section, or a pointer the bundler wrote), or that is not a string (`default: { $ref: 42 }`), is warned about and the response read as the Reference Object it is, with no body or headers — a `content` or `headers` written beside the `$ref` is ignored, as beside a ref that resolves (#562) — while a `$ref` into `components/responses` that names no entry fails the bundle before the parser runs (`Failed to parse spec: Can't resolve $ref`); and an inline body the component declares is named after the component (`ProblemResponse`) and shared by every operation that returns it, as `default`, in a range or at an explicit status code — the same rules as for an explicit status code (see "Shared through `components/responses`" under Inline model naming). The body is then read from `application/json`, else the first `+json` media type (`application/problem+json`), matched by essence; other media types leave `type` unset, as they do for `errors`. Every media type the response declares is kept in `contentTypes`/`contents` exactly as on a `SuccessResponse` (see Response Content Types above): present whenever there is at least one, the entry for the media type `type` was read from sharing that very `TypeRef` — so a reader can tell a `default` typed from `application/problem+json` apart from one typed from `application/json` — and every other entry typed on its own, an inline object under it materialized as `<Op>Default<MediaType>Response` (`ListPetsDefaultApplicationYamlResponse`) for `default`, `<Op><Label><MediaType>Response` (`ListPetsSuccessApplicationYamlResponse`) for a `1XX`–`3XX` range, or `<Op>Error4Xx<MediaType>` (`ListPetsError4XxApplicationYaml`) for a `4XX` or `5XX` range, the name an explicit error status code's secondary body takes with the range key in place of the code — or, when the fallback is a `$ref` into `components/responses`, as `<Component><MediaType>Response` (`ProblemApplicationYamlResponse`), the name the same component yields at an explicit status code, so the operations that return it share one model. The differ reports a media type such a response gains, loses or retypes under `responseContentTypeChanges` with `fallback` set (`'default'`, `'4XX'`) in place of `statusCode`, matching the two specs' media types by essence — case folded, parameters stripped — as the parser types them, so `application/problem+json; charset=utf-8` is `application/problem+json` to it (see `oagen diff` in the CLI reference).

The body is typed as if it were a field named `<Op>DefaultResponse` or, for a `1XX`, `2XX` or `3XX` range, `<Op>` + the range's word + `Response` — `Informational`, `Success`, `Redirect` (`ListPetsSuccessResponse`) — or, for a `4XX` or `5XX` range, `<Op>Error` + the range key in PascalCase (`ListPetsError4Xx`, `ListPetsError5Xx`; the key itself does not survive PascalCasing), the scheme an explicit error status code's body follows (`<Op>Error404`, see Error Responses below): such a body is an error body throughout — on a clash it steps to `ListPetsError4XxBody` rather than to a numbered name, and a body that is itself an inline enum steps to `ListPetsError4XxBody` in `spec.enums` the same way — or, for a response written as a `$ref` into `components/responses`, `<Component>Response` (`ProblemResponse`), the name every operation returning the component shares, at `default`, in a range or at an explicit status code — of a parent with no name, through the same extractor every field goes through. So a `$ref` is the referenced model, and every shape a field can take is materialized under that name by the field rules: an inline object (`ListPetsDefaultResponse`), a nullable one, nested objects (`…Detail`), array items and map values (they take the body's name, as a field's items take the field's), `oneOf`/`anyOf` variants (`…`, `…WithReason`), an `allOf` merge. The ref and the models agree by construction, so nothing dangles. The body is named once every operation has been read, in document order with the header and secondary-body schemas, those of the responses shared through `components/responses` first (`resolveDeferredInlineTypes`; see Inline model naming), and its names are checked against the spec-wide model registry (components and the inline models their fields mint — a nested object, a map's values — every operation's request body and primary response models, envelope companions, and every header, secondary-body and fallback model named so far) by the same `materializeInlineSchema` helper header and secondary-body models use: a body whose shape matches the name's owner shares it and materializes nothing new (a header or secondary body also tries, between its bare name and its own qualifiers, the names the earlier sites of the same bare name settled on — see Response Headers and Response Content Types above — while a fallback body named from the operation carries the response's label in its bare name and an error body named from it its status code, so within an operation neither has such a sibling; a component's body carries the component's name at every site that returns it, so the `default` of one operation and the `404` of another are siblings, step by number alike — `ProblemResponse2`, whichever kind of site each is — and settle on one name), and a clash is cleared by the cheapest move that can still change something — a `oneOf`/`anyOf` variant named from its own `title` or const is reserved so variant naming steps around it (`CircleListPetsDefaultResponse`, as beside a sibling's model), and a name derived from the stem (the root, nested objects, array items) moves the whole body to the next free stem (`ListPetsDefaultResponse2`, `…3`), nested models and ref together. The clashing set is compared between attempts, so when a stem advance changes nothing the loop stops (no input can make it retry forever; a hard cap backs the test) and the clashing names themselves are renamed under the root (`ListPetsDefaultResponseCircle`), then numbered, with every reference rewritten to match — the case of a titled variant nested below the top level, where no reservation reaches. Sameness is decided on the final shapes, after every rename: renaming a child changes its parent's shape, so a parent that matched a registered model (a component `ListPetsDefaultResponse` whose `shape` points at the component's own `Circle`) and no longer does moves to the next free stem with its children (`ListPetsDefaultResponse2`, `ListPetsDefaultResponse2Circle`; a header's next qualified candidate) rather than being dropped as already defined, which would leave the body resolving to the component and its old child. The move is decided per model, by shape: a child whose name an identical definition already owns (a component, an earlier operation's model) stays shared under that name and the moved parent keeps referencing it, exactly as it is shared when nothing moves; only the root and the children that need distinct names move. A schema that both inlines such a clashing `Circle` and `$ref`s component model `Circle` fails the parse with a message naming both, since the rewrite could not tell the two references apart; a `$ref` to a component enum of that name is an enum reference the rewrite never touches, so it does not stand in the way of the rename, and a rename an earlier site of the same bare name recorded that this schema's `$ref` to a component model would make unsafe is skipped rather than failed — the schema is compared as extracted, an inline `Circle` of the component's shape shares the component, and the root takes the site's own next candidate. So a component, or another operation's response or request body, that happens to carry a fallback's name is never overwritten by inline-model merging. A body that is itself an inline enum, or an array of one, is typed like a parameter and promoted to `spec.enums` under the same name, which is reserved before any fallback, header, parameter or error model is named, so an inline model of the name steps instead; it is numbered on a clash with an enum of other values or with a component model's name; enums nested in a fallback's models are collected with every other model's, and a field enum whose name an enum of other values already owns is numbered the same way (`ListPetsDefaultResponseStatus2`) rather than left pointing at those values. List-envelope and pagination detection are skipped, since a fallback body is not what the SDK method returns.

Headers declared on these responses are kept as `headers` and qualified by the response's label where a status code would qualify an explicit response's (`PetsXMetaDefault`, `PetsXPolicyClientError`); a header of a fallback written as a `$ref` into `components/responses` is named from the component's stem (`ProblemXMeta`), as at an explicit status code. `collectResponseHeaders(op)` yields them after the explicit lists. `collectFallbackResponseTypes(op)` (exported from `@workos/oagen`) yields the `default` body then each range body; it feeds `collectResponseBodyTypes(op)` (see Response Content Types above), which every pass that walks an operation's type refs — reachability, model assignment, ref rewriting and validation, direction, the compat filter, enum collection — goes through. The differ reports a `default` or range response added as additive and one removed or retyped as breaking (`OperationModified.fallbackResponsesChanged`), and compares the headers declared on a `default` or range response both specs declare exactly as it compares an explicit response's, each change reported under `responseHeaderChanges` with `fallback` set (`'default'`, `'4XX'`) in place of `statusCode`.

Keys the specification does not define are not dropped silently. The whole key decides what it names, in one shared classifier (`classifyResponseKey`) every reader of a Responses Object goes through: a status code is exactly three digits in 100–599, a range is `1XX`–`5XX` in either case, `default` is itself, and an `x-` extension key is skipped. Any other key is warned about (`Ignoring response key "…"`) and ignored, with no model minted for its body — `error` and `Default`, and just as much a key that only starts with digits: `6XX`, `4XXX` and `20X` are neither a range nor a code, `600` and `099` are outside 100–599, and `200 ` (with a trailing space) is not a code either; none is read from its numeric prefix. The key classified is the one the YAML or JSON loader decoded, not its spelling in the file: YAML — YAML 1.2's core schema, as `@redocly/openapi-core` loads it (js-yaml 5) — reads an unquoted key that looks like a number as that number, so unquoted `0x1F4`, `0o620` and `0404` (or `+404`, `404.0`, `4.22e2`, `5e2`) arrive as `500`, `400` and `404` (`422`, `500`) and are taken as those status codes with no warning, where the same keys quoted (`'0404'`), or in JSON, are warned about and ignored; an unquoted number that is no status code is warned about as YAML reads it (`0099` as `"99"`, `0777` as `"777"`), and a spelling the core schema does not read as a number at all (`1_000`, `0b111110100`) as written. Which spellings are affected depends on that schema: a YAML 1.1 reader would read `0404` as octal 260, `0777` as 511, `1_000` as 1000 and `0b111110100` as 500 instead. An unquoted key that decodes to a code the same Responses Object already declares — `0404` beside `'404'`, `200.0` beside `'200'` — is a duplicate mapping key, so the document does not load at all: `parseSpec` throws `duplicated mapping key in "…" (10:9)` before the classifier runs. OpenAPI requires a status code key to be quoted (`'404'`) for compatibility between JSON and YAML, so the parser leaves an unquoted key as YAML reads it rather than loading YAML with a schema that keeps it as written. A duplicate range (`4XX` beside `4xx`) keeps the first and warns. A webhook's responses apply the same classifier (see Webhooks below).

An entry that is not an object is not read either, and does not fail the parse. A Responses Object entry is a Response Object or a Reference Object, both objects; one written as a string, a number, a boolean, `null` or an array — `responses: { '200': 'oops', '204': { description: 'No pets.' } }`, or `null`, `7`, `true` or `[]` in place of `'oops'` — is neither, so nothing could be read from it, not even a `$ref`. It is warned about once, naming the site and the value as JSON (`200 response of listPets is not a Response Object ("oops"); skipping it.`), and skipped, and the operation is read from its other entries: `listPets` above is read from its `204` (`responseStatusCode: 204`, `response` `unknown`, `responseDescription: 'No pets.'`), with no `successResponses`, `errors`, `defaultResponse` or `rangeResponses` entry for the skipped key, and the rest of the document parses — where the parser used to fail the whole document with a `TypeError` that named neither the operation nor the key (#617). Every key a reader reads is checked alike, on OAS 3.0 and 3.1 and in either declaration order — a 1xx, 2xx, 3xx, 4xx or 5xx code, `default` and a `1XX`–`5XX` range; an `x-` key is an extension and may hold anything, and a key OpenAPI does not define is reported as above whatever it holds. A `responses` that is not an object at all (`responses: "oops"`) is no Responses Object and is read as absent, as for an operation that declares none, after one warning (`responses of listPets is not a Responses Object ("oops"); reading no response from it.`) — never as the map of its characters' or elements' indexes. A `components/responses` entry that is not an object — `Gone: []`, `"oops"`, `null`, `7`, `true` — mints no model and is not reported on its own; a `$ref` to it, direct or at the end of a chain, is that same malformed entry behind a pointer, so it goes through the same check: it is warned about once per operation that writes it, naming the component and the site (`components/responses/Gone (the 200 response of listPets) is not a Response Object ([]); skipping it.`), and skipped, and `listPets` is read from its `204` exactly as with `200: []` written inline, so the two spellings give one IR and `oagen diff` between them reports no change. (A pointer the section holds nothing under is still a ref nothing answers, read as written — one into another section, `Unresolved response $ref "#/components/schemas/Gone" in 200 response of listPets: no matching entry under components/responses — …`, since a pointer to a `components/responses` name that does not exist never reaches the parser, as above.) A webhook's and a callback's responses apply the same checks (see Webhooks below).

## Webhook

Source: `src/parser/webhooks.ts`

A webhook is a request the API sends to its users. OpenAPI 3.1 describes them under a top-level `webhooks` map whose keys name path items; the parser reads that map into `ApiSpec.webhooks`, one `Webhook` per HTTP method of each entry, in document order. A webhook is not an SDK method: it has no path, belongs to no `Service`, gets no resolved operation name, and is untouched by operation hints and mount rules. What an emitter does with it is generate a payload type, or a typed handler, per event.

```typescript
interface Webhook {
  name: string; // The key under `webhooks`, verbatim: "petAdopted", "user.created"
  operationId?: string; // Verbatim, when the document declares one that names something, as on Operation
  httpMethod: HttpMethod;
  summary?: string; // As on Operation: the operation's own, else the path item's
  description?: string; // As on Operation: the operation's own, else the path item's; never built from the summary (one identical to it is kept)
  externalDocs?: ExternalDocs; // The operation's own, when usable, as on Operation
  deprecated?: boolean; // Present, and true, only when deprecated
  tags?: string[]; // As on Operation: document order, unusable entries dropped, repeats folded, only when at least one remains
  headerParams: Parameter[]; // Signatures, event types, delivery ids
  queryParams: Parameter[];
  cookieParams?: Parameter[]; // Only when any exist
  requestBody?: TypeRef; // The payload the receiver is handed
  requestBodyEncoding?:
    "json" | "form-data" | "form-urlencoded" | "binary" | "text";
  requestBodyContentType?: string; // The essence of the media type the payload was read from, as on Operation; present exactly when requestBody is
  requestBodyRequired?: boolean; // Present, and true, only when the body is `required` and declares a media type (only when requestBodyContentTypes is, as on Operation)
  requestBodyDescription?: string; // The Request Body Object's description, else the picked schema's own, a collapsed wrapper or single-member oneOf/anyOf read through to its branch, as on Operation (only when one has content)
  requestBodyContentTypes?: string[]; // Media types the payload declares, in document order (only when any exist)
  requestBodyContents?: RequestBodyContent[]; // A type per media type above, same order (only when any exist)
  responses: WebhookResponse[]; // What the sender expects back
  security?: SecurityRequirementSet[]; // Same semantics as Operation.security
  callbacks?: Callback[]; // The webhook operation's own callbacks, read as Operation.callbacks is (see Callback); only when at least one is readable
}

interface WebhookResponse {
  statusCode: number;
  description?: string;
}
```

`summary`, `description` and `externalDocs` are read as an operation's are: `summary` and `description` from the operation or, for each the operation declares none with content for, from its path item — the entry itself, or the Path Item its `$ref` leads to (text written beside the `$ref` is not read — a Path Item's `$ref` is not a Reference Object, see Reference Objects — and is reported with the other keys beside it) — each on its own field, `description` never built from the summary (one identical to it is kept in both); `externalDocs` from the operation alone, since a Path Item Object has none. Everything else is read from the receiver's side of the wire. `headerParams`, `queryParams` and `cookieParams` are the values the request carries, typed exactly as an operation's parameters are (`components/parameters` refs resolved, a path-item-level parameter overridden by an operation-level one of the same identity — location and name, a header's name compared case-insensitively, as `parameterKey` decides — and an `Accept`, `Content-Type` or `Authorization` header ignored, as OpenAPI requires); a parameter with an inline object schema, or an array of them, is materialized as a model under the name the parameter references (`<Stem>XMeta`, `<Stem>Filter`; a header's name lower-cased first, so `X-RateLimit-Meta` gives `<Stem>XRatelimitMeta` whatever its case), so no parameter type dangles — and when a name it would mint is already taken by the payload or an earlier parameter of the same webhook (a query parameter named `payload` would mint the body's `<Stem>Payload`, one named `payload_pet` the body's nested `<Stem>PayloadPet`, a header `X-Meta` and a query `x_meta` would both mint `<Stem>XMeta`), the parameter is typed and minted under its location-qualified name instead (`<Stem>QueryPayload`, then `<Stem>QueryPayload2`, …), the first that takes nothing already minted — and the parameter always references what its mint produced, whether or not the property moved, so a variant renamed past a decided enum under the parameter's own name (`PetAdoptedFilterCircle`) is what its union and discriminator mapping point at; when only context-free names clash (a titled variant another parameter also mints), the earliest trial is kept under the parameter's own name and the clash is left to the model merge; a `path` parameter has nowhere to go and is dropped with a warning. `requestBody` is the payload, read like an operation's body (`components/requestBodies` refs resolved, the same media-type pick by essence, a schemaless binary or text body typed as a primitive), with `requestBodyEncoding` and `requestBodyContentType` beside it as on an operation, and `requestBodyDescription` read as `Operation.requestBodyDescription` is — the Request Body Object's own `description`, else the `description` written on the picked entry's schema itself, a `$ref` not followed (see Request Body Description) — while the model an inline object payload is materialized as carries that schema's `description` itself; `requestBodyContentTypes` and `requestBodyContents` carry every media type the payload declares, read as `Operation.requestBodyContents` is (see Request Body Content Types), with an inline object under a secondary media type materialized as `<Stem><MediaType>Payload` (`PetAdoptedTextCsvPayload`, the fragment from the media type's essence, plus its parameters when another spelling of the same essence sits beside it, as a request body's is) and named by the stem rules below, so it takes part in the stem's collision check like `<Stem>Payload` itself; within one payload, a secondary entry whose names are already minted by another entry shares that model when the shapes are identical and otherwise mints under the next free property (`<Stem><MediaType>Payload2`, …), the entries minted in `mediaTypeNamingOrder`, so two case-only spellings with different fields never point at one model, and which of them steps does not depend on their order. `responses` lists the status codes the sender expects the receiver to return, one entry per status code key (three digits, 100–599, as the shared `classifyResponseKey` decides) in document order with the document's description, following a `components/responses` `$ref` for it (chains included; a description written beside the `$ref` wins in an OAS 3.1 document and is ignored in a 3.0 one, as beside every Reference Object; a ref that leads nowhere keeps the code with a warning, and the description beside it by the same rule, as on an operation); `default`, range keys such as `2XX` and `x-` keys are not carried, a key that is none of those (`error`, `6XX`, `600`) is warned about and ignored exactly as on an operation, an entry at a status code that is not an object (`200: "oops"`, `null`, `7`) is no Response Object and is skipped with one warning naming the site (`200 response of webhooks.petAdopted.post is not a Response Object ("oops"); skipping it.`), a `$ref` whose chain ends on a `components/responses` entry that is not an object (`Gone: []`) is skipped the same way, the warning naming the component (`components/responses/Gone (the 200 response of webhooks.petAdopted.post) is not a Response Object ([]); skipping it.`), and a `responses` that is not an object at all is read as declaring none, with a warning (`responses of webhooks.petAdopted.post is not a Responses Object ("oops"); reading no response from it.`), both exactly as on an operation (#617; a callback's responses are read the same way, under its own label), and body schemas on these responses are not carried either, since a webhook response is an acknowledgement. `security` mirrors the document the way `Operation.security` does: `undefined` inherits `ApiSpec.security`, `[]` means none.

One `webhooks` key may declare several methods, so `name` alone does not identify a webhook; `name` + `httpMethod` does, and that pair is what `oagen diff` keys its `webhook-added` / `webhook-removed` / `webhook-modified` changes on. A `webhook-modified` change reads from the receiver's side: a payload type, encoding or `requestBodyRequired` change sets `requestBodyChanged` with `details` saying which (type and required → optional are breaking; encoding is breaking unless the representation the sender now uses is one the old document declared with the same shape; optional → required is additive; the flag is compared whenever both documents carry a payload it is kept on, read as `requestBody` or carried in `requestBodyContents` alone — a `petAdopted` payload under `application/xml` alone turning `required` is `body optional → required` as one under `application/json` is (#528) — so a payload read as `requestBody` appearing or disappearing is `payload added` / `payload removed` alone, and one carried in its contents alone appearing or disappearing is nothing) and, for an encoding change — compared only while both documents carry a `requestBody`, as on an operation, so a payload appearing or disappearing, or one carried in its contents alone on either side, carries neither field — `oldRequestBodyEncoding`/`newRequestBodyEncoding` beside the flag as an `operation-modified` change carries them, and so does a change to the media types the sender may use (`requestBodyContentTypes`, compared by essence, both sides declaring a payload — read as `requestBody` or carried in its contents alone, so a `petAdopted` payload under `application/xml` alone gaining `text/csv` is `payload media type text/csv added`, breaking), with `requestBodyContentTypeChange` beside it listing them (a media type the sender can newly use, or whose body changed type, is breaking — the handler must decode it; one it can no longer use is additive), a change to the status codes the sender accepts sets `responsesChanged` (a code no longer accepted is breaking, since a handler that keeps returning it now fails the delivery; a newly accepted one is additive; descriptions are not compared), and parameters are matched by location and name — a header and a query parameter may share one, and a header's name is compared case-insensitively, so one that only changed case is a `param-name-changed` entry (additive) rather than a removal beside an addition — with every `ParamChange` carrying its `paramLocation` (added is additive, removed breaking, optional → required additive, required → optional breaking). The webhook's own `deprecated` flipping sets `deprecatedChanged`, with `oldDeprecated`/`newDeprecated` beside it, and a parameter's is a `param-deprecated-changed` entry in `paramChanges`; both are additive in either direction and mirrored into `behaviorChanges` as `webhook` and `webhook-parameter` nodes, exactly as an operation's are (see [Deprecation](#deprecation)). The security the request carries — `webhook.security ?? spec.security` on each side, a webhook that inherits on both sides being left to the document-level `security-changed` change — sets `securityChanged` with `oldSecurity`/`newSecurity` beside it, read from the receiver's side: a credential the sender stops presenting, or an alternative it may now present that the handler never checked for, is breaking; a credential it starts carrying beside the old ones, or an alternative withdrawn, is additive; the change is mirrored into `behaviorChanges` as a `webhook` node (see the security paragraph under [Service & Operation](#service--operation)). The webhook's `tags` differing, in document order, sets `tagsChanged` with `oldTags`/`newTags`, additive always. An entry that is a `$ref` into `components/pathItems`, or to another `webhooks` or `paths` entry (`petReturned: { $ref: '#/webhooks/petAdopted' }` is a second webhook with `petAdopted`'s operations), is resolved, chains included, by `resolvePathItemRef` in `src/parser/path-item-refs.ts`, the function a `paths` entry is resolved by too (see [Path Item references](#path-item-references)); fields written beside the `$ref` are not merged in, since OpenAPI leaves a field present on both sides undefined, and are reported once per entry, naming the key and the fields (`Webhook "petAdopted" has fields beside its $ref ("summary") that are not read: the referenced path item is taken whole.`); a ref that names no Path Item, a cycle, or an entry that is not an object is warned about and skipped (a ref the document cannot resolve at all fails the bundle before parsing, as any dangling ref does). A value under `webhooks` that is not an object is ignored with a warning. Every key of the map is a webhook, one starting with `x-` included: OpenAPI gives `webhooks` no specification extensions, unlike `paths` (see [Path Item references](#path-item-references)), so `x-pet-returned` is read, resolved and warned about like any other key — a webhook whose inline payload is `XPetReturnedPayload`, and a `webhook-added` or `webhook-removed` change to `oagen diff`.

**Payload models.** An inline payload schema is materialized the way a component field's would be: the parser types it as the `payload` property of a synthetic object named by the webhook's _stem_, so the reference and the model are named by the same code and always agree. An inline object becomes `<Stem>Payload`, with nested objects qualified under it (`<Stem>PayloadPet`) and inline enums promoted as `<Stem>Payload<Field>`; a `oneOf`/`anyOf` of inline objects stays a union — discriminator intact, because an event handler switches on it — with its variants named as any field-level union's are (`<Stem>Payload`, `<Const><Stem>Payload`, …); a `$ref` stays a reference; a payload that is itself an inline enum is promoted as `<Stem>Payload`. Nothing is flattened. Inline parameter enums are qualified with the stem the way a service name qualifies an operation's (`PetAdoptedXEventType`).

The stem is the `operationId` when the operation declares one that names something — cleaned exactly as an operation's own `…Request` model name is, so `adoptions_created` gives `AdoptionCreatedPayload` and `petAdopted[1][2]` gives `PetAdoptedPayload` — and the PascalCase of the key otherwise (`pet.returned` → `PetReturnedPayload`). An `operationId` with no ASCII letter or digit once its trailing overload markers are stripped — `' '`, `'-'`, `'[1]'`, `'[1][2]'` — names nothing and counts as absent, exactly as an operation's does (see Service & Operation): the stem comes from the key, `Webhook.operationId` is not set, and two webhooks declaring such ids are not a duplicate, so `petAdopted` with `operationId: '-'` and `petReturned` with `operationId: ' '` (or both with `'-'`) give `PetAdoptedPayload` and `PetReturnedPayload`, exactly as they do with no `operationId` at all, never `WebhookPayload` or a hashed `Webhook3Bc15CPayload`. No `operationIdTransform` is applied to a webhook's `operationId`. When a key's path item declares several methods, a key-derived stem has the method appended (`PetUpdatedPostPayload`, `PetUpdatedPutPayload`); an `operationId` is unique per document and needs no qualifier, with one caveat: two keys that `$ref` the same `components/pathItems` entry resolve to one operation and so carry one `operationId`, which is what that section is for, so they share one stem and one set of models (`SharedPayload`, minted once) while each stays its own `Webhook` with its own IR nodes; without an `operationId` such keys keep their key-derived stems (`APayload`, `BPayload`). A key that `$ref`s another `webhooks` entry reads that entry's operation, and pairs with it the same way. An `operationId` that two different operations declare, which no valid document does, is ignored for naming with a warning, and those webhooks take their key-derived stems. A key that PascalCases to nothing, or to something starting with a digit, gets `Webhook` in front (`Webhook2FaEnabledPayload`). Whether a stem collides is decided from the names it actually mints: every webhook is first minted under its plain stem and the model and inline-enum names that produces — payload, nested objects, union variants with their const or title prefixes, parameter models, parameter and field enums — are compared, by exact name, against every model and enum name the rest of the parse has already decided (component models and enums, the operations' inline models, response-header models and envelope companions, the components' own inline field models, and every inline enum any of those reference; webhooks are extracted last for this reason) and against the names every other webhook mints. Two keys that flatten to one stem (`pet_adopted` and `petAdopted`) collide on every name; a `petEvent` union variant pinning `kind: returned` and a webhook keyed `returnedPetEvent` collide on the single name `ReturnedPetEventPayload`; a component `Event` whose `payload` field is a map of inline objects owns `EventPayload`, so a webhook keyed `event` collides; a stem that merely starts with another's does not collide unless a name coincides. A colliding stem takes the first six hex characters of the SHA-1 of its `operationId` when it is named from one and of its key otherwise, before the method qualifier (`PetAdoptedB4A950Payload`), the rule an operationId-less operation's path prefix follows — a hash that starts with a digit set off from a stem that ends in one by `No` included (`pet.v2` and `petV2` → `PetV2No2780A4Payload` and `PetV2No931202Payload`) — and is minted again under it; both sides of a webhook-to-webhook collision are hashed, since neither key is more canonical. What is hashed is the `operationId` or the key as written. Two webhooks that hash one string — a key and an `operationId` of one text — and still share a name once hashed, which six more characters of one hash would never part, each hash the text with where it came from in front instead, `key:petAdopted` and `operationId:petAdopted`, and are minted again: a webhook keyed `petAdopted` without an `operationId` and one keyed `noteAdded` declaring `operationId: petAdopted` — which would otherwise share every hashed stem to its last character and merge their payloads into one model, the first declared winning — get `PetAdopted15Fe0FPayload` with `petId` and `PetAdoptedB0Ca6APayload` with `noteId`, whatever the key order, and a webhook keyed `pet_adopted` beside them keeps `PetAdoptedF79708Payload`, hashed from its key as written. A webhook whose own key and `operationId` spell one text (`petAdopted` declaring `operationId: petAdopted`) is one webhook with one text and hashes it as written (`PetAdoptedB4A950Payload` when `pet_adopted` collides with it). A key or `operationId` that spells a prefixed text as written (a webhook keyed `key:petAdopted` beside that pair) hashes the string `petAdopted`'s key hashes and names apart as long as the two share no name (`KeyPetAdopted15Fe0FPayload` beside `PetAdopted15Fe0FPayload` when a key `key_pet_adopted` collides with it); when they do share one — a `petAdopted` payload variant pinning `kind: key` is named `KeyPetAdopted<hash>Payload`, the literal key's own payload name, at every length of one hash, as the `kind: key` variant of a `petAdopted` query parameter `post_payload` (`KeyPetAdopted<hash>PostPayload`) is the literal key's `post` body's — the one of the two not yet prefixed puts its source in front too (`key:key:petAdopted`): the literal key's payload is `KeyPetAdopted130B64Payload` beside the variant `KeyPetAdopted15Fe0FPayload`, both intact in either order, and `pet_adopted` beside them keeps `PetAdoptedF79708Payload`. Two webhooks that hash one string but share no name keep hashing their texts as written, whatever the texts, so adding one half of such a pair never renames a payload the other half already had: a key `petAdopted` whose path item declares several methods (`PetAdoptedPost`, `PetAdoptedPut`, hashing one text for all of them and parted by the method, `PetAdoptedB4A950PostPayload` and `PetAdoptedB4A950PutPayload` beside `pet_adopted`'s) keeps `PetAdoptedB4A950PostPayload`, its `post` hashed because a component holds `PetAdoptedPostPayload`, on the day `noteAdded` declaring `operationId: petAdopted` (`PetAdopted`) is added, and `oagen diff` reports `model-added PetAdoptedPayload` and `webhook-added noteAdded` only, exit `1`; `noteAdded` declaring `operationId: adoptions_created` (`AdoptionCreated`, singularized) keeps `AdoptionCreatedA40316Payload`, hashed because a component holds `AdoptionCreatedPayload`, when a key `adoptions_created` (`AdoptionsCreated`) is added; and one key `petAdopted` whose `put` declares `operationId: petAdopted` (`PetAdopted`) keeps the `put`'s `PetAdoptedB4A950Payload`, hashed because a component holds `PetAdoptedPayload`, when a `post` without an `operationId` (`PetAdoptedPost`) is added beside it. The rule is the `webhooks` map's own, and the callbacks' own among themselves (see [Callback](#callback)): a webhook and a callback operation of one text are parted through the reserved names, the callback hashing (`PetAdoptedB4A950Payload` for a callback declaring `operationId: petAdopted` beside the webhook keyed `petAdopted`, which keeps `PetAdoptedPayload`), as before. A key that stops colliding returns to its plain stem, and the outcome depends only on the document, never on its order. A name that does not embed the stem — a title-mapped union variant, context-free by design — cannot be moved by the hash, so a clash on it alone leaves the stem plain. One named like a decided enum (a component enum `Circle`, which a property of the same payload may well reference) is renamed under the payload's root instead (`PetAdoptedPayloadCircle`, numbered when that is taken too) with every reference rewritten, since a model and an enum under one name would reach an emitter as one symbol; one named like a decided model, or like another webhook's variant, is left to the model merge, which shares the component's name when the component admits the variant's shape and renames the variant under the webhook's stem otherwise (`PetAdoptedComp`), as for operations.

**Downstream.** `collectWebhookTypeRefs(webhook)` (exported from `@workos/oagen`) yields a webhook's parameter and body types, and its callbacks' after them (see [Callback](#callback)), and every pass that walks an operation's type refs walks a webhook's through it: reachability (`collectReferencedNames` with `opts.webhooks`, so a payload model is never pruned as an orphan, in a scoped run as much as a full one — webhooks are not a service, so no scope selects or excludes them), the `…Json` collapse's ref rewriting, model-ref validation (context `webhooks.<name>.<method>.…`), inline-enum promotion (with the value check response-header enums get: a name already taken by a different value set, or by a model, is renamed, `PetAdoptedXSource2`, rather than silently shared), and the differ's direction index, where a payload or parameter model is response-facing — the user reads it and never constructs it, so a field added to the payload is an additive `field-added` even when required (`required on a response-only model`); an existing field made required stays a breaking `field-required-changed`, which is direction-blind on purpose (see `diffFields` in `src/differ/models.ts`), and one made optional additive. Payload models belong to no service in `assignModelsToServices`: they stay unassigned unless a service also references them or a `modelHints` entry pins them.

`x-webhooks`, the extension some OpenAPI 3.0 documents use for the same thing, is deliberately not read — it has no agreed shape — and a document that carries one gets a warning saying so. The standard `webhooks` key is read on any 3.x document.

A webhook operation's `callbacks` (OpenAPI 3.x), whose path items have the shape of a `webhooks` entry, are read into `Webhook.callbacks` exactly as an operation's are into `Operation.callbacks` — one `Callback` per (key, method) entry that declares them, so two keys that `$ref` one `components/pathItems` entry each carry the callbacks, named from each key's own stem (`SharedASharedPayload`, `SharedBSharedPayload`). See [Callback](#callback).

## Callback

Source: `src/parser/callbacks.ts`

A callback is a request the API sends to a URL the caller handed it in a request. OpenAPI 3.x describes them under an Operation Object's `callbacks` map, whose keys name Callback Objects — or `$ref`s into `components/callbacks` — each mapping runtime expressions such as `{$request.body#/callbackUrl}` to path items. The parser reads that map into `Operation.callbacks` — and, for a `webhooks` operation, into `Webhook.callbacks` — one `Callback` per HTTP method of each path item under each expression of each key, in document order: `callbacks` key order, then expression order within each Callback Object, then the path item's method order (#382). A `Callback` is a `Webhook` with two fields more, read from the receiver's side exactly as a webhook is; it is not an SDK method, belongs to no service and gets no resolved operation name — what an emitter does with it is type its payload, or a handler for it, beside the operation that registers it. An operation or webhook that declares no readable callback carries no `callbacks` key at all, so the IR of a document without callbacks is unchanged.

```typescript
interface Callback extends Webhook {
  name: string; // The key under the operation's `callbacks` map, verbatim: "petAdopted"
  expression: string; // The runtime expression the path item is keyed by, verbatim: "{$request.body#/callbackUrl}"; a callback has no fixed path
}
```

One key may map several expressions to path items, each declaring several methods, so `name` alone does not identify a callback; `name` + `expression` + `httpMethod` does, and that triple is what `oagen diff` keys its `callback-added` / `callback-removed` / `callback-modified` changes on (see **Callbacks** under [`oagen diff`](../cli.md#oagen-diff)).

Everything else is read as a webhook's is, by the same code (`readPathItemEntries`, `buildReceivedRequests` in `src/parser/webhooks.ts`): `headerParams`, `queryParams` and `cookieParams` typed as a webhook's parameters are, a `path` parameter dropped with a warning since a callback has no path to place it in; the payload as `requestBody`, with `requestBodyEncoding`, `requestBodyContentType`, `requestBodyRequired`, `requestBodyDescription`, `requestBodyContentTypes` and `requestBodyContents` (an inline object under a secondary media type is `<Stem><MediaType>Payload`, `CreatePetPetAdoptedTextCsvPayload`); `responses` as the three-digit status codes the sender expects back; `summary`, `description`, `externalDocs`, `deprecated`, `tags` and `security` as a webhook carries them. The path item under an expression may be a `$ref` into `components/pathItems`, or to a `paths` or `webhooks` entry, resolved by `resolvePathItemRef` as a webhook's is, fields beside the `$ref` reported and not merged. Every warning, and every context `validateModelRefs` reports under, labels a callback's site `<owner>.callbacks.<key>.<expression>.<method>` — `createPet.callbacks.petAdopted.{$request.body#/callbackUrl}.post` — where the owner is the operation's `operationId` (else `METHOD /path`), the webhook's `webhooks.<key>.<method>`, or a parent callback's own label; `callbackContext(context, callback)` (exported from `@workos/oagen`) builds it.

**Naming.** A callback's models are named from a stem as a webhook's are (`<Stem>Payload`, `<Stem>PayloadPet`, `<Stem>XMeta`, `<Stem>Kind` for an inline parameter enum): the callback operation's `operationId` when it declares one that names something and exactly one callback operation object in the document declares it (`notifyAdoption` → `NotifyAdoptionPayload`, with `Callback.operationId` set; the rule a webhook's follows, #564), else the owner's stem — the one the owner's own models are named from: `CreatePet` for `createPet`, `PetsPost` for an operationId-less `POST /pets`, a webhook's `PetAdopted`, a parent callback's own — followed by the key PascalCased. So the issue's repro, `createPet` declaring `petAdopted`, mints `CreatePetPetAdoptedPayload`; `POST /pets` mints `PetsPostPetAdoptedPayload`; a webhook `petAdopted` declaring `adoptionConfirmed` mints `PetAdoptedAdoptionConfirmedPayload`; and a callback nested in that `petAdopted` under `confirmed` mints `CreatePetPetAdoptedConfirmedPayload`. When one key maps several expressions, each key-derived stem is qualified with the expression PascalCased (`CreatePetPetAdoptedRequestBodyCallbackUrlPayload` beside `CreatePetPetAdoptedRequestBodySecondUrlPayload`), and when a path item declares several methods, with the method, as one `webhooks` entry with several methods is. Two sites that `$ref` one `components/callbacks` entry whose operation declares an `operationId` share one minting (`NotifyAdoptionPayload` once, each site its own `Callback` with its own IR nodes), at whatever depths they sit — one operation referencing it directly and another callback nesting it — as two `webhooks` keys sharing a path item do; without one, each mints under its own owner's stem (`CreatePetAdoptedPayload`, `UpdatePetAdoptedPayload`). A key-named callback such a shared callback operation declares itself — `NoteAdded`'s own `noteRead`, reached from every operation that references `NoteAdded`, or from every `webhooks` key sharing its path item — is read from every site under one stem and one operation object, so it mints once with its owner (`OnNoteAddedNoteReadPayload`), however many sites reach it, and adding a second reference to the shared operation renames nothing; two owners' inline callbacks are two objects and mint apart. The callbacks are named after every webhook, against every model and enum name the document already holds — components, the operations' models, the webhooks', the components' field models — and against each other, in three phases, as the `webhooks` map is read. First every callback of the document is collected and grouped: each key-named stem is prefixed with its owner's stem — an operation's or webhook's settled one, a parent callback's plain stem before any collision hash — and two sites reading one callback operation object under one plain stem are one group at whatever depths they sit, so the groups span depths (`Read` referenced by a path operation `registerEvent` directly and by a callback operation `register_event` inside another callback, both `RegisterEvent`, is one `RegisterEventReadPayload`, and adding either reference renames nothing). Then every group's stem is settled once, in one resolution across every depth, exactly as the `webhooks` map's are — a document without callbacks names its webhooks as it always has — with reserved-name hits and collisions decided together: a name a group would mint that the document already holds, or that another group also mints, hashes the stem, both of a colliding pair moving whichever depths reference them (a direct callback operation `notify_adoption` beside a shared `components/callbacks` operation `notifyAdoption` that another callback nests, both `NotifyAdoption`, both hash from their identities, so a reference to the nested one added directly under an operation renames nothing and is one additive `callback-added`). A group of one plain stem with another is its peer however the two nest — two callback operations `notify_adoption` and `notifyAdoption` both hash whether the second is referenced directly, nested inside the first, or both. The one rule the `webhooks` map never exercises: a name a descendant mints under a stem of its own never moves an ancestor's stem, so a nested `confirmed` callback asking for the `CreatePetPetAdoptedConfirmedPayload` its parent's `confirmedPayload` parameter already holds is the one that hashes, and adding it is one additive `callback-added`; two groups that each nest a reference to the other are peers again, neither protected, and both hash. Minting then proceeds ancestors first — every group with a member directly under an operation or webhook, then those one level down, and so on — each wave stepping around, at mint time, any name still taken; a group that spans depths is one minting, named at its shallowest depth. Last, whatever lets two callback groups mint one model or enum name for two shapes past all that — a title-mapped union variant, which embeds no stem and so no stem hash moves — moves every group minting it once minted, each on its own identity and stem, so the outcome never depends on which was declared first: a stem hashed further when the hash moves the name, the model renamed under its stem (`<Stem><Name>`) otherwise, with every reference minted for it repointed while an explicit `$ref` to a component of the name — a parameter's union over `components/schemas` — and the mapping entry it owns stay untouched. One shape under one name — the model's with `deprecated` read apart, an enum's values, as the merge decides a clash — is the merge's to share, so two callbacks' identical `Shape` variants are one `Shape` and two differing ones are `<Stem>Shape` each; every contested name of a round is decided together, each replacement chosen against the names the round leaves occupied, in identity order rather than declaration order, so a name another callback vacates is free to take whichever was declared first (`a` and `b` titled `Shape` beside `c` and `d` titled `CreatePetAShape`: `a` is `CreatePetAShape` in either order); a contested inline enum name once the hash is spent is warned about and left to the model merge. The `webhooks` map is not held to this and keeps the merge's sharing and renaming of a title-mapped variant, as it always has. A collision hashes the new stem as a webhook's is hashed, from the callback's identity — its owner's identity, then the key, expression and method, where an operation's identity is its operationId (the one its models are named from), else `METHOD /path`, and a webhook's or a callback's is its operationId when its stem is named from one, else its own identity — so the callbacks of two owners whose stems coincide (`createPet` beside `create_pet`, both `CreatePet`) under one key and expression never hash alike and each keeps its own payload model (as the owners' own `CreatePetRequest` bodies, which the parser merges with a warning when their shapes differ, do not); `CreatePetPetAdopted2Fac84Payload` beside a component `CreatePetPetAdoptedPayload`, which keeps its name and its fields. The sites of a shared callback operation share one identity (its operationId), and a group is hashed from the smallest of its members' identities, so a shared group's hashed name — `NoteAdded`'s `noteRead` beside a component `OnNoteAddedNoteReadPayload` — is the same whichever operation references `NoteAdded` first, and whichever `webhooks` key sharing its path item comes first. The names minted under a hashed stem are checked again, and a stem still clashing (two hash prefixes that coincide) takes six more characters of its hash, until none clashes. A collision never renames an existing model, and the outcome depends only on the document, never on its order. A stem that would be empty or start with a digit gets `Callback` in front.

**Cycles and guards.** A `components/callbacks` entry, or a nested callback, can refer back to a callback it sits in — a callback whose operation `$ref`s the path item declaring it, say — so the Callback Objects on the path from the owner down are tracked by identity after `$ref` resolution, and a callback already on that path is skipped with one warning naming the site (`Callback "createPet.callbacks.petAdopted.{$request.body#/callbackUrl}.post.callbacks.again" refers back to a callback it sits in; skipping it.`); depth is otherwise unbounded, and one Callback Object reached from two sites that do not nest is read at both. A `callbacks` value that is not a map, or an empty one, declares no callback and is silent, as is an entry under `components/callbacks` nothing references; a Callback Object that is not an object, a `$ref` that is not a string or that resolves to nothing under `components/callbacks`, or a chain that loops, is warned about and skipped; an `x-` key inside a Callback Object is a specification extension, not an expression, and a `components/callbacks` `$ref` nothing in the document answers fails the bundle before parsing, as any dangling ref does.

**Downstream.** `collectWebhookTypeRefs(webhook)` yields a webhook's callbacks' references after its own, nested callbacks included, and `collectOperationTypeRefs(op)` an operation's last, so every pass that walks a webhook's or an operation's type refs reaches a callback's: reachability for emission (a callback payload is never pruned as an orphan), the merge passes' ref rewriting (a callback payload the `…Json` fold merges onto its base is repointed to the base), the error-body collapse (a callback payload is kept, as any body a non-error site reaches is), model-ref validation, inline-enum promotion (a webhook's callbacks' enums with the webhook's, an operation's as received requests after the operation's own), and the differ's direction index, where a callback's payload and parameters are received and so response-facing — a field added to the payload is an additive `field-added` even when required, while an existing field made required stays a breaking `field-required-changed` (direction-blind on purpose, as on a webhook's payload) and one made optional additive. An operation's callback models are assigned to the operation's service (`assignModelsToServices`), as the operation's own are; a webhook's callbacks belong to no service, as the webhook does.

## Model & Field

```typescript
interface Model {
  name: string; // PascalCase, e.g., "Organization"
  description?: string;
  externalDocs?: ExternalDocs; // The schema's externalDocs, when usable
  deprecated?: boolean; // The schema's own `deprecated: true`; absent otherwise (see Deprecation below)
  fields: Field[];
  bases?: TypeRef[]; // The components a composed component's allOf names, one model ref per $ref member in document order; absent when none (see `properties` beside a composition)
  typeParams?: TypeParam[]; // Generic type parameters
  variants?: TypeRef[]; // A named union's members, one per non-null oneOf/anyOf variant (see Named unions)
  compositionKind?: "oneOf" | "anyOf"; // Which keyword produced `variants`; present exactly when `variants` is
  discriminator?: { property: string; mapping: Record<string, string> }; // Dispatch property and value → IR model name
  constraints?: Constraints; // The object schema's own minProperties / maxProperties / dependentRequired; a model reference carries none (see Type constraints)
  extensions?: Extensions; // The x-* keys of the schema the model was built from, less x-enum-descriptions / x-enumDescriptions (see Extensions)
}

interface Field {
  name: string; // snake_case from the spec
  type: TypeRef;
  required: boolean;
  inheritedFrom?: TypeRef; // The direct base (an entry of Model.bases) the field is taken from unchanged; absent when the model declares or changes it (see `properties` beside a composition)
  description?: string;
  externalDocs?: ExternalDocs; // The field schema's own, a $ref sibling included; a bare $ref yields none unless it names an array or primitive component, or an alias of an enum component, whose link the field carries (see ExternalDocs)
  readOnly?: boolean;
  writeOnly?: boolean;
  deprecated?: boolean;
  default?: unknown;
  example?: unknown; // The schema's `example`, else `examples[0]`
  examples?: unknown[]; // The JSON Schema `examples` list; only when non-empty
  constraints?: Constraints; // Validation keywords on the field's schema, siblings of a $ref included; a bare $ref to a model yields none, one to an array or primitive component conjoins the component's, one to an alias of an enum component the alias's (see Array components and Enum). Equal to the type's wherever the type can carry them; an array's items' and a union's variants' are on those types alone (see Type constraints)
  extensions?: Extensions; // The field schema's own x-* keys, read like constraints (see Extensions)
}
```

**Nullable components.** A `$ref` to a component that admits `null` is typed under `nullable`, whatever the component is, so the two spellings of one schema — written inline, or extracted into a component and named by a `$ref` — agree. An array or primitive component is typed from its schema, wrapper included (see Array components and Primitive components); an enum (see Enum), a named union (see Named unions) or an object component that admits `null` is wrapped by `componentTypeRef`, since the enum or model built for it carries no wrapper. For an object component, "admits `null`" is read exactly as `schemaToTypeRef` reads the same schema written inline (`declaresNull`): an OAS 3.1 type list naming `'null'` (`PetOwner: { type: ['object', 'null'], required: ['name'], properties: { name: { type: 'string' } } }`), OAS 3.0 `nullable: true` beside the `type` (`PetOwner: { type: 'object', nullable: true, required: ['name'], properties: { name: { type: 'string' } } }`), a nullable `oneOf`/`anyOf` wrapper around one object (`PetOwner: { oneOf: [{ type: 'object', properties: { name } }, { type: 'null' }] }`, in either order, with `properties` written beside the wrapper or not — those keep the component the object model it always was), a single-member `allOf` around one of these, or a `null`-only schema in either spelling (`{ type: 'null' }`, `{ type: ['null'] }`, which keeps the fieldless model it always became). With `Pet: { type: 'object', properties: { owner: { $ref: PetOwner } } }` and a response written as `{ $ref: PetOwner }`, both `Pet.owner` and the response are `{ kind: "nullable", inner: { kind: "model", name: "PetOwner" } }`, in OAS 3.0 and 3.1 documents alike — what `Pet.owner` written inline is, and what the JSON Pointer `#/components/schemas/Pet/properties/owner` to that inline field is (see Schema references) — so `oagen diff` between the two spellings of that document reports no change (#615: the bare `$ref` was `PetOwner`, the inline field and the pointer `nullable<PetOwner>`). This holds at every site typed through `schemaToTypeRef`: a component field, array items, map values, a `oneOf`/`anyOf` variant and a named union's variant, a request body, a parameter in any location, a response header, a success, error, `default` or range response body, a webhook or callback payload. A site that wraps the `$ref` itself — `oneOf: [{ $ref: PetOwner }, { type: 'null' }]` or `anyOf`, in either order, an `allOf` read as the reference (`allOf: [{ $ref: PetOwner }]`), OAS 3.0 `nullable: true` or a type list beside either — is wrapped once, never twice. An alias of such a component — an `allOf` read as its `$ref` member, alone or beside members that only annotate or limit it (`PetOwnerAlias: { allOf: [{ $ref: PetOwner }] }`, `{ allOf: [{ $ref: PetOwner }, { description: 'The owner.' }] }`, an alias of an alias), or a bare `$ref` (`PetOwnerAlias: { $ref: PetOwner }`, with or without annotations beside it, at every hop of a chain; #618, where the bare spelling lost the `null`) — is a model of its own carrying `PetOwner`'s fields (see Array components) and admits `null` as `PetOwner` does, so a `$ref` to it is `nullable<PetOwnerAlias>` in either spelling, as the same `allOf` on a field is `nullable<PetOwner>`. A bare `$ref` admits what its target admits and nothing the keywords beside it say, since nothing but annotations is read beside a `$ref`: over a `Cat` that admits no `null`, `B: { $ref: Cat, type: ['object', 'null'] }` (OAS 3.0: `type: 'object', nullable: true`) is the bare `B` and `A: { $ref: B }` the bare `A`, as `{ $ref: Cat, type: ['object', 'null'] }` on a field is `Cat`. An `allOf` that merges — a typing member beside the `$ref` (`Cat: { allOf: [{ $ref: PetOwner }, { type: 'object', properties: { meow: { type: 'string' } } }] }`), two `$ref` members, a `required` that adds to the reference — is the object its merged fields describe, so a `$ref` to `Cat` is the bare `{ kind: "model", name: "Cat" }`, as the same `allOf` on a field is a bare model: a member's nullability never wraps the composed model, while the composed schema's own declaration does (`Cat: { type: ['object', 'null'], allOf: [...] }`, or `nullable: true` beside its `type`, is `nullable<Cat>`; `nullable: true` beside an `allOf` with no `type` declares nothing, as beside any schema without one). A chain of aliases that returns to itself admits nothing through the loop. The nullability is the key's, as the `$ref` names it, never the resolved name's: with `Note: { type: ['object', 'null'], properties: { text } }` and `note: { type: 'object', properties: { text } }`, which resolve to one model `Note`, `{ $ref: Note }` is `nullable<Note>` and `{ $ref: note }` is the bare `Note`. The model is untouched by any of this: `PetOwner` keeps its fields, and nothing else in the IR records the component's nullability.

### Named unions

A component schema that is itself a `oneOf`/`anyOf` — no `allOf` that types the schema (`allOfTypesSchema`: a `$ref` member, a member declaring properties, or one member that types on its own; an `allOf` whose members only annotate or limit the schema, `allOf: [{ description }]`, `allOf: [{ minProperties: 1 }]`, `allOf: []`, is part of the wrapper, so `New: { allOf: [{ description: "A new pet." }], oneOf: [{ $ref: Pet }, { $ref: Toy }] }` is the named union `New` of `Pet` and `Toy` that `{ description: "A new pet.", oneOf: [...] }` is, described by the member and carrying its limits as `constraints`, exactly as the same schema is the union inline, while a `oneOf` and an `anyOf` written together beside such an `allOf` stay composed, each one more member, since a named union carries one axis — #613: it was a composed model, the union flattened into optional fields with no variants), no `properties` of its own, not every non-null variant a string `const` (that is an enum; see Enum), and not a `null` variant beside one array or `$ref` to an array component (that is an array component; see Array components) or beside one primitive, `const`, type list of primitives or schema that declares no type, or `$ref` to a primitive component (that is a primitive component; see Primitive components), and not a `null` variant beside one `$ref` to an enum component (that is an alias of the enum; see Enum) or beside one enum declaration — an `enum:` list, a `oneOf`/`anyOf` of consts, or an `allOf` read as one (that is the enum itself, nullable; see Enum, #606) — is a named union. It still becomes a `Model` (every component other than an enum or an alias of one, an array component or a primitive component does; see Enum, Array components and Primitive components below), and a `$ref` to it stays `{ kind: "model" }`, but the model carries the union: `variants` holds one `TypeRef` per non-null variant in document order, `compositionKind` says which keyword produced them, and `discriminator` is set when the union is discriminated. `fields` holds the inline variants' properties merged as optional fields (`UpdateOrganizationMembership`'s `role_slug` / `role_slugs`), so an emitter that reads only `fields` sees a plain object model, while one that reads `variants` emits the union from them.

The variants are built exactly as the same union written inline is (`UnionType`): a `$ref` variant is a model or enum ref; an inline object variant is referenced by a model extracted for it; a nullable (`type: ['object', 'null']`) or multi-type (`['object', 'string']`) inline variant keeps its wrapper around that model; a primitive stays a primitive; the `null` variant (in any spelling, see UnionType) is dropped from `variants` — an inline union lifts it into a `nullable` wrapper, and a `Model` has no wrapper to carry it — so, as for a nullable enum component, the nullability travels on the reference instead: every `$ref` to a named union that admits `null` (a `null` variant, a `type` list with `'null'`, or OAS 3.0 `nullable: true`) resolves to `nullable<model>`, the shape the same union written inline has. Every other variant — a primitive, an inline enum, an array, a map, an `allOf`, a nested union — is typed and extracted as the `variant_<n>` property of one synthetic object under the union's name, where n is the variant's 1-based position among the non-null variants, so whatever it mints is named `<Model>Variant<n>…` by the one rule a field's inline models follow (an inline enum second in the list is `PetVariant2`, an array's inline items third in the list are `PetVariant3`, a nested object under them `PetVariant3Child`), and two variants of the same kind can never share a name or a value list. When a name such a variant would mint is already a component's, or another named union's inline variant's, of a different shape, the context steps exactly as an array's or map's does beside a claiming sibling — `variant_1_item` / `variant_1_value` (`PetVariant1Item`, `PetVariant1Value`), then `variant_1_array_item` / `variant_1_member_value`, then numbered, with the same no-progress and attempt-cap guards — and every name nested under the variant moves with it, since both the reference and the extractor read the chosen context; a claimant of the identical shape is shared instead (the array's items then point at the component).

Inline object variants are named by the inline-variant rules with the union's model name as the base, except that the base itself is taken by the union's own model, so variant 0 steps off it like every later variant: a const-discriminator prefix (`CatPet` for `kind: cat`), its title as a prefix (`CircleShape`), the first property no other variant declares (`UpdateAuditLogsRetentionDtoWithRetentionPeriod` beside `…WithRetentionPeriodInDays`), else the position counter (`Pet1`, `Pet2`). Every component schema's name is reserved, so a variant can never shadow a component (a variant titled `Cat` beside a component `Cat` takes `CatPet`), and so is every context-free title another named union keeps for a variant of a different shape — the comparison sibling field unions already make (`schemaShapeKey`), read symmetrically: when `Circle` is `{ radius }` on `Shape` and `{ diameter }` on `Marker`, both fall back (`CircleShape`, `CircleMarker`) and the mappings follow; when the shapes are identical, both keep `Circle` and one model is emitted. The component schemas are one root for the depth rule above as well, so a title a field union nested in any component gives a different shape (`Drawing.marker.shape`'s `Circle` as `{ diameter }`) is contested for the named union too, and both fall back (`CircleShape`, `CircleDrawingMarkerShape`). Each variant and everything nested under it — objects with or without `type`, array items, map values, `allOf`s, nested unions, the members of a multi-type variant — is materialized by the same inline extractor a field's union variants go through, so a reference always has a model behind it. Each extracted variant model is a complete model of its own, so the union's merged fields and the variant's fields are typed independently (an inline `config` object appears as both `PetConfig` and `CatPetConfig`).

`discriminator` is resolved from the same sources, in the same order, as an inline union's (see UnionType), from the same reading of the variants (`unionMembers`; #568) — a `$ref` variant is named by its component and its const read from it, through the component's `allOf` members — a `$ref` member followed to its component, through a chain of aliases (`Cat: { allOf: [{ $ref: CatBase }, … ] }`, `Puppy: { allOf: [{ $ref: Dog }] }`), a member's pin outranking the open declaration another member makes in either order — and through a `$ref` on the property to a component pinning one value or an alias of one (`kind: { $ref: HamsterKind }`), the declaration read as the type builder reads it at every hop — a nullable wrapper and an `allOf` read as one member included, so `kind: { allOf: [{ const: 'cat' }] }`, `kind: { allOf: [{ $ref: HamsterKind }], description }` and a `$ref` to `RabbitKind: { allOf: [{ $ref: RabbitConst }] }` pin as `kind: { const: … }` does (#607) — a component reached again on one walk read once and a chain that repeats pinning nothing (the examples are under UnionType); a variant wrapping one model `$ref` is read through that reference; an inline object variant is named by the model extracted for it; a title on any other variant names nothing, since no model is extracted under it: an explicit `discriminator:` with a `mapping:` is the spec's own, each target reduced to the IR model name it refers to (the component the `$ref` names, or a bare schema name, through `schemaNameTransform`, so `#/components/schemas/Cat` → `Cat`, and a component that is an alias, `Hound: { $ref: … }`, read through the alias to what it stands for; a target that is a pointer deeper into a component is settled to the model the schema it points at is built as — the variant's model when a variant is written as that pointer, `ZooDog`, and the pointed schema's own otherwise, `ShelterDog` for `dog: '#/components/schemas/Shelter/properties/dog'` beside a variant `Zoo/properties/dog` (#619) — see Schema references) — an entry pointing outside the variant list is kept as written, and an entry naming an inline variant's const redirects that variant's object member to its target, as it does inline — to the pointed schema's model, `ShelterDog`, for a pointer target, the member's reference settled as a pointer variant's is (#619) — while the items or values of a multi-type variant's other members stay named from the model extracted for the variant (`PetWithKindItem`, never `CatItem`), so they always resolve; an explicit `discriminator:` without `mapping:` pairs each variant's const on the property with its model name (`{ cat: "Cat", dog: "Dog" }`), and is `{}` when any variant pins none, as it is inline; a `oneOf` with no keyword whose every variant is nameable (a `$ref`, a titled or inline object) is discriminated implicitly on the first property the first variant pins whose values are distinct across all of them — a constant every variant shares (`version: 'v1'`) is passed over, not taken as proof there is none. Both derivations read a variant that wraps one `$ref` to a model as that reference, its const and model name alike, as the differ reads the models under a variant's wrapper: a nullable wrapper (`anyOf: [{ $ref: Bird }, { type: 'null' }]`, typed `nullable<Bird>`), a `oneOf`/`anyOf` whose other members name no model, whether written inline or as a `$ref` to an enum component or an alias of one (#560), or to an array or primitive component, which builds no model (`oneOf: [{ $ref: Bird }, { type: 'string' }]`, typed `union<Bird|string>`, or `oneOf: [{ $ref: Bird }, { $ref: Song }]` with `Song` an enum component, typed `union<Bird|Song>`), or an `allOf` read as its reference — so adding such a variant adds its key, `{ bird: "Bird" }`, beside the others. A wrapper around two references to models, or around one beside an inline object, names no model, since a key read off one would leave the other out. An `anyOf` is never discriminated implicitly, and the OpenAPI default of "the discriminator value is the schema name" is not synthesized. Mappings are built as own keys, so a value spelled like an inherited property (`constructor`) is neither rejected nor lost. As for an allOf+oneOf model, a set `discriminator` means emitters should dispatch on it, and its mapping values are IR model names; such a model's inline variant is named from the const it pins (`PetCat`), read as its mapping value is, so a variant pinning `kind: { allOf: [{ const: 'cat' }] }`, `kind: { $ref: CatKind }` with `CatKind: { const: 'cat' }`, or a `$ref` to an alias of it is named and dispatched to exactly as one pinning `kind: { const: 'cat' }` (#607: the name was read as written, so the variant was named as the component and the union flattened into one `Pet` instead). That is the one place the two forms differ. Both reduce `#/components/schemas/Cat` to `Cat`, but `Model.discriminator.mapping` holds IR model names — each target's last `$ref` segment through `resolveSchemaName`, so `cleanSchemaName` and the project's `schemaNameTransform` apply (`#/components/schemas/cat_dto` → `CatDto`, or whatever the transform makes of it), as an allOf+oneOf model's always has — while an inline union's `discriminator.mapping` only strips a leading `#/components/schemas/` and otherwise keeps each target as the document spelled it (`cat_dto` stays `cat_dto`; a target in another section, such as `#/components/responses/Cat`, stays whole) — except an entry whose target is a pointer deeper into a component, settled to the model the pointed schema is built as, as a named union's is (see Schema references), since a pointer (`Zoo/properties/dog`) names no model however it is cleaned. An emitter reading a named union's mapping can use its values as model names directly; one reading an inline union's mapping has to clean and transform them itself.

Four shapes are deliberately not unions. A `oneOf`/`anyOf` whose every non-null variant is a string `const` is an enum (see Enum), and so is a nullable wrapper around one enum declaration — `Color: { oneOf: [{ type: 'string', enum: ['black', 'white'] }, { type: 'null' }] }`, `Kind: { oneOf: [{ allOf: [{ type: 'string', enum: ['cat', 'dog'] }] }, { type: 'null' }] }` — which is the nullable enum `Color` or `Kind`, as the same schema inline collapses to `nullable<enum>` (#606; before, a `Color {}` model carrying the enum as `ColorVariant1`). The OAS 3.0 form of that wrapper — `nullable: true` beside a `oneOf`/`anyOf` of one variant, since a `null` variant cannot be written there — is the same nullable enum: `Color: { oneOf: [{ type: 'string', enum: ['black', 'white'] }], nullable: true }` in a 3.0.3 document is `nullable<enum Color>` exactly as the `null` variant makes it in a 3.1.0 one, because the flag is read beside a union (every `$ref` to the component is nullable, as it is for a named union), unlike beside an `allOf` or any other schema without a `type`, where it declares nothing; so moving a document from 3.0.3 to 3.1.0 is no change and `oagen diff` between the two reports nothing. A `oneOf` of one variant with neither a `null` variant nor `nullable: true` beside it — `{ oneOf: [{ type: 'string', enum }] }` — is no wrapper and stays the union of one it was, as the same schema inline is a union of one. A `oneOf` written beside `properties` is a composed model, the properties its base and the union flattened or dispatched after them, as beside an `allOf` that types the schema (#429; see `properties` beside a composition) — an `allOf` whose members only annotate or limit it composes nothing beside one typing union (`composesComponentModel`, by the predicate `foldSiblingUnions` reads an inline schema by, `allOfTypesSchema`), and that union is the named union it is written alone, while a `oneOf` and an `anyOf` written together beside such an `allOf` stay composed, two members (#613) — and a component that is only a nullable wrapper around one plain inline object — `oneOf: [{ type: object, … }, { type: 'null' }]`, the object typed `object`, untyped, or `['object', 'null']` — stays the object its merged fields describe, as an inline wrapper collapses to `nullable<model>` rather than a union. A wrapper around one `$ref`, one primitive, or one object that also admits another type (`type: ['object', 'string']`) is a union of one, so the other type is kept.

Every pass that walks a model's type refs — reachability for emission, service assignment, ref rewriting and validation, dependency collection for imports, inline-enum promotion, the differ's direction index and model comparison, compat scoping, and the companion and parameter-group fingerprints — reads fields and variants alike through `collectModelTypeRefs`, so a model reached only as a variant is emitted, placed, and compared like one reached through a field. A composed component's `bases` and its fields' `inheritedFrom` are provenance, not types the model owns (see `properties` beside a composition): `collectModelTypeRefs` leaves them out, so the fingerprints and the differ read a model with and without them as one shape, while `renameModelRefs` repoints them with the fields, `validateModelRefs` checks them and reachability for emission (`collectReferencedNames`) chases `bases`. Every rename and fold goes through `renameModelRefs` and `renameTypeRefModels`, which repoint fields, variants and `discriminator.mapping` targets together — a union's mapping with the variant it names, by name in the Json fold and the list-envelope pass and by reference identity in the merge passes — and a `…Json` component folded onto its base carries its variants, composition keyword and discriminator onto the base as it carries its fields — and its `bases`, with each field's `inheritedFrom`, less a base whose own chain of bases reaches the folded model by either name — the model itself (`PetJson: { allOf: [{ $ref: Pet }] }` onto `Pet`) or a model built on it (`PetJson` on `Animal` on `Pet`), which the fold would close into a cycle — whose lent fields become the base's own; and the parser's last pass (`settleBases`) settles both keys against the models as they end: no model's chain of bases reaches itself — a base that does, in a cyclic document (`A: { allOf: [{ $ref: B }] }`, `B: { allOf: [{ $ref: A }] }`) or once a fold collapsed it onto a kept model of the same shape (`PetJsonChild` onto `PetChild: { allOf: [{ $ref: PetJsonChild }] }` as `PetJson` folds onto `Pet`, directly or through a chain), is dropped and the fields it lent are the model's own; a base named twice is one base; a base stays a base only while every field it ends with is on the model either as the model's own declaration — which overrides the base's, as `overrides.json`'s `name` does — or as the same field, the base's declaration and not another's (every key; the type as its final shape — an inline model built under either model, `PetMeta` or `AnimalMeta`, as it ends, a discriminated union's variants and mapping targets the same way; an inline enum by its values, so `PetStatus` beside `AnimalStatus` is the same field; a component by name) — so the model is its own fields plus its bases' and an emitter writing `extends` or an intersection of the bases types every field as `fields` does: `Pet: { allOf: [{ $ref: Tagged }, { $ref: Kinded }] }` with `Tagged.tag: string` and `Kinded.tag: enum [cat, dog]` ends `Pet { tag?: string, kind? }` on `Tagged` alone, `kind` its own (`Tagged & Kinded` would type `tag` as the enum, and `interface Pet extends Tagged, Kinded {}` does not compile), the other way round on `Kinded` alone with `tag?: PetTag`, and on both when they agree; a fold of `AnimalMetaJson` onto `AnimalMeta` alone takes `Animal` off `Pet` and makes `Pet.meta` its own; a field carries `inheritedFrom` only while its base stays; so `AnimalJson: { properties: { name, extra } }` folded onto `Animal: { required: [name], properties: { name } }` under `Pet: { allOf: [{ $ref: Animal }], properties: { nickname } }` leaves `Pet { nickname?, name }` with `name` required and its own and no `bases`, since the `Animal` that ends — `{ name?, extra? }` — is not what `Pet` carries — so a union never silently becomes a plain object or keeps a dispatcher pointing at a name that is gone; a base that is a union the `…Json` model does not preserve — a named union's variants, keyword and discriminator, or an allOf+oneOf dispatcher's mapping, which may sit on a model with no fields — is not folded at all (both are kept, with a warning). The `…Json` folds of a document are decided together, so the result depends on the document's names and shapes and never on the order it declares them in: every name is read as it ends once the accepted folds are applied — a model or inline enum an accepted `…Json` model reaches (through its fields, variants and mapping targets, and theirs in turn) whose name begins with that model's name as whole words (the next character, if any, is no lower-case letter) reads with that prefix replaced by its base's reading, the innermost such fold first, and the name that gives is read in turn among the names of its own kind — a renamed model follows only a name a model holds, a renamed inline enum only one an inline enum holds (#534) — so `PetJsonWithA` reads as `PetWithA`, `PetJsonJsonThing` as `PetThing` by way of a child model `PetJsonThing`, and `NoteJsonPetJsonToy` as `NotePetToy` under the folds of `NoteJsonPetJson` and `NoteJson` whichever is declared first, while `PetJson { name, mode: enum ['ball', 'rope'], json_mode: { q } }` beside `Pet { name }` folds to `Pet { name, mode: enum PetMode, json_mode: model PetJsonMode }`: the model `PetJsonJsonMode` lands on `PetJsonMode`, a name only the inline enum held, and stops there, while the enum reads on to `PetMode` (with `json_mode` the enum and `mode` a `$ref` to a component model `PetJsonMode`, the model reads as `PetMode` and the enum as `PetJsonMode`), so a renamed model and a renamed enum never end under one name by following each other; a model the `…Json` model does not reach is no child of its fold however it is spelled, and neither is a name that only starts with the same letters, so `PetJsonPatch` beside a `PetJson` that never references it, and `PetJsonification` whether it does or not, keep their names and have no say in whether `PetJson` folds — and a base as the shape it takes, a chain (`PetJsonJson` onto `PetJson` onto `Pet`) applied from the deepest fold outward, so `Pet` ends with the fields, link and keys `PetJson` ends with whatever the declaration order. Two undiscriminated unions share the rule `oneOf`, so the variants are compared too, every model reference on either side (a variant, a mapping target) read that way, and so is every inline enum reference, which the fold renames with its model: a `PetJsonState` enum with the members of `PetState` reads as `PetState` and the base keeps its own enum (the entry the component pass had lifted under the old name is dropped once nothing references it — whether the fold renamed every reference, or the only one sat on a base's own field that its `…Json` model's of the same name replaced down a chain, or on a collapsed member, and went with it: under `Pet { name }`, `PetJson { name, mode: enum ['ball', 'rope'] }` and `PetJsonJson { name, mode: enum ['ball', 'rope'], json_mode: { q } }`, `PetJson`'s `mode` gives way to `PetJsonJson`'s, so the entry `PetJsonMode` is dropped as `Pet.mode` is lifted as `PetMode` (the parser notes `Folded enum "PetJsonMode" into "PetMode"`), and the model `PetJsonJsonJsonMode`, which lands on `PetJsonMode`, is the only type under that name; likewise `PetJsonCarrier.mode`'s entry when `PetJsonCarrier` collapses onto a `PetCarrier` whose `mode` reads to the same name — and the collectors that run after the fold lift the reference that carries its reading afresh, the renamed one or the twin of the one that went (the field or member that took its place, which reads to the same name) — onto `PetState`, or under its new name, `PetJsonMode` as `PetMode`, when the base has none, stepping past a model of that name, `PetMode2` beside a component model `PetMode`, which the parser's note names: `Folded enum "PetJsonMode" into "PetMode2"`), while one with other members is another shape, since the members are compared with the name; a literal is compared as it is, since the fold rewrites no value, and so is a `$ref` to a component enum, which carries no members at this point and is never renamed — `PetJsonStatus` beside `PetStatus` declared as components refuses the fold even when their members agree. The models that end under one name are one group: with a model the folds leave under its own name among them, that model holds the name and must admit every other (`modelAdmits`, the rule by which an inline model folds onto a component), which collapses onto it; without one, every member must be equivalent (each admits each) and the first declared keeps the name while the others collapse onto it. A member not admitted refuses the fold that renames it — the innermost, when several do — with the union-rules warning when that fold's base dispatches to the name, so a variant model of another shape is a different variant even when the fold would give it the base's name (`PetJsonWithA` with `a` and `b` beside `PetWithA` with `a` keeps `PetJson` and `getPetJson` returns it), and a shape warning for any other member (`PetJsonToy` with `a` and `b` beside `PetToy` with `a`); two folds whose children would end under one name with different shapes refuse each other. A name an enum holds and no model keeps admits no child: a member the folds would rename onto one — a component enum, or an inline enum a model, operation or webhook carries, such as a `toy` query enum `PetToy` of a `pet` service, read under the folds (the entry the component pass lifted under an inline enum's old name holds that name only as long as a reference does — it is dropped once the fold leaves none, renamed or gone with the model that carried it — so it is read under the folds too) — refuses the fold that renames it, with a warning (`"PetJsonToy" would be renamed "PetToy", and enum "PetToy" owns the name`), so a fold never puts a model and an enum under one name and the enum keeps its name, as it does beside any model a pass can rename (see Inline model naming); a renamed model that lands on the name a renamed inline enum leaves meets no enum there, since each kind is read among its own (#534), while a component enum `PetMode` declared beside a fold that would rename a model `PetJsonMode` onto it refuses that fold as before; a model the document keeps under such a name is a holder like any other, since a child collapsing onto it adds no type under the name. A field both models declare must be one the `…Json` model's admits (`fieldAdmits`: the same type, limits, default and flags, the `…Json` model's no stricter on requiredness or nullability, references read as above), since the base takes the `…Json` model's fields under operations that already use it; a field shared by name alone (`id: integer` beside `id: string`) refuses the fold with a warning. A refusal changes how the remaining names read, so the decision is repeated over the folds still accepted until none is refused, and only then is anything written — each base takes its shape, every reference is repointed at once, the folded `…Json` models and the collapsed members are dropped — so nothing is collapsed by name alone and nothing is half-applied. An identical union folds; and a component — a named union or a plain object — is never replaced by a same-named inline model, whatever its field count (see Models: the inline model shares the component only when the component admits it, and takes a qualified name otherwise). The fingerprints that decide whether two companions or parameter groups share one model include the variants and the dispatch rules (composition keyword, discriminator property and mapping), so two unions with the same members but different rules are kept apart. The differ reports a variant added (additive, like a new enum value, from either side of the wire: a caller may construct it but need not, a reader may receive it), removed (breaking), a change of composition keyword between two unions (breaking), and a discriminator change (breaking) under `ModelModified.variantChanges`. A mapping entry that comes with an added variant — a new key whose target is a model no variant of the old union names, under any wrapper (`nullable<Cat>` added beside a kept `Cat` brings no new model) — or goes with a removed one is part of that variant's entry, carried as its `details` (`mapping added for 'bird'`, `mapping removed for 'dog'`, the keys of every model the variant names listed once each and sorted), not a discriminator change of its own, so a variant added to a discriminated union is additive whether the spec writes the `mapping` or the parser derives it from the variants' consts. A key retargeted, a key added for a model the old union already dispatched to (or for no variant), a key removed while its model stays, and the discriminator added, removed or moved to another property stay breaking: each changes how an existing payload is dispatched. An allOf+oneOf dispatcher, whose `variants` is absent and whose mapping alone names them, is compared as a union of the mapping's targets, so a target added to or removed from its mapping is that same `variant-added` or `variant-removed`.

### Array components

A component schema that is an array — `type: 'array'`, an OAS 3.1 type list `['array', 'null']`, OAS 3.0 `nullable: true` beside `type: 'array'`, a `oneOf`/`anyOf` whose one variant beside a `null` one is such an array (`oneOf: [{ type: 'array', items }, { type: 'null' }]`, unwrapped as `unwrapNullableSchema` unwraps it everywhere else, unless the component declares `properties` of its own, which keep it the object model), or `items` with no `type`, in every case with `items` declared (`isArrayComponentSchema`) — or one `schemaToTypeRef` types as an array through its readings of a nullable wrapper, a `$ref` and an `allOf`: a bare `$ref` to it; such a nullable `oneOf`/`anyOf` around a `$ref` to it (`oneOf: [{ $ref: Pets }, { type: 'null' }]`); an `allOf` read as a plain reference (`readInlineAllOf`: `$ref` members with nothing inline beside them — `allOf: [{ $ref: Pets }]`, `allOf: [{ $ref: Pets }, { maxItems: 10 }]`), read as its first `$ref` member; an `allOf` of one member, read as that member; followed through aliases of aliases (`isArrayComponentEntry`) — becomes no `Model`. The parser knows an array component by its `components/schemas` key, the key a `$ref` names, not by its IR name: `cleanSchemaName` singularizes the leading word, so `Note: { type: object }` and `Notes: { type: array, items: { $ref: Note } }` both resolve to `Note`, and keying by name would send `$ref: Note` into the array; keyed by `Notes`, the object keeps its model and `$ref: Notes` is `array<Note>`. A `$ref` is resolved by its key before any name-based test, so `$ref: Notes` is the array even when another key resolving to `Note` is an enum. A `$ref` to an array component resolves to the array the component declares, the shape the same array written inline has: with `Pets: { type: array, items: { $ref: Widget } }`, every `$ref` to `Pets` is `{ kind: "array", items: { kind: "model", name: "Widget" } }`, and a component that admits `null` wraps that in `nullable`, as a `$ref` to a nullable enum, named union or object component is wrapped (see Nullable components under Model & Field). This holds at every reference site — a component field, an `allOf` member (`allOf: [{ $ref: Pets }]`, with or without limits beside it), a named union's variant, a request body, a parameter in any location, a response header, a success, error, `default` or range response body, a webhook payload — because every site types a `$ref` through `schemaToTypeRef`; and a list envelope whose data array is a `$ref` to an array component, under any nullable wrapper or an `allOf` read as the reference (`allOf: [{ $ref: Pets }]`), is detected and unwrapped as one whose array is written inline, iterating the component's items. `spec.models` holds no `Pets`, so an emitter never sees an empty class, or a list typed as one object.

What the items reference is extracted under the component's name, by the inline extractor a field's array goes through, as the `item` property of a synthetic object under the component: an inline object item is `<Component>Item` (`PetsItem`), with everything nested under it named from that (`PetsItemOwner`); the object variants of an `items.oneOf` are named by the inline-variant rules from `PetsItem` (`PetsItem`, `PetsItemWithSide`); an inline enum is `PetsItem`, lifted into `spec.enums` whether or not anything refers to the component (an inline object item's model is likewise emitted for a component nothing refers to); the objects of a nested array or map are `PetsItem` too, by the one rule a field's items and values follow. The component's name is the one `cleanSchemaName` and `schemaNameTransform` give it, so a component `pet_list` renamed to `PetCollection` gives `PetCollectionItem`. A `$ref` item mints nothing: it stays a reference to its model or enum, and a `$ref` to another array component resolves in turn (`array<array<Widget>>`). Every name the whole tree mints — the item model, an object nested under it (`PetsItemOwner`), an inline enum a nested field holds, a union variant — is read off a rehearsal of the extraction itself before any plan is decided, so a nested name counts exactly as the item model's does. When any of them is already claimed for a different shape — by any name any extraction pass takes from another `components/schemas` entry, read off a rehearsal of those passes: the entry's own model (compared by `modelFingerprint`), enum (by its members), or array or primitive component's name, a discriminated allOf+oneOf variant (an `Event` whose variant pins `type: 'pets_item'` owns `PetsItem`), a named union's variant or `variant_<n>` member, an object or enum the entry's fields mint, and everything nested under those; or by another array component's tree — the whole tree's context steps exactly as a named union's `variant_<n>` does (see Named unions): `item_item` (`PetsItemItem`, `PetsItemItemOwner`), then `item_array_item`, then numbered, until no name under it is claimed; a claimant of the identical shape is shared, and the tree references it. Shapes are compared as the real pass types them, under the names the plans settle on. The plans are decided in rounds: every tree starts under `item`; a round registers every tree under its current context, so a `$ref` to an array component resolves to its array in every rehearsal — `{ value: { $ref: Notes } }` and `{ value: { $ref: Note } }` differ, as `array<Note>` and `Note` do, although both keys resolve to `Note` — while the names a tree mints are read with none registered, so an enum another component's items hold is never counted as the tree's own; then the trees are decided one at a time, in the order of their keys sorted by code point — never the document's order — each against every component and every other tree's current names, a tree that moves being re-registered at once so the trees after it resolve its items under its new name. A round that moves nothing is the last, so no sharing rests on a name a tree then steps away from (`Pets`'s items holding `{ value: { $ref: Palette } }` are shared with a component `PetsItem { value: array<PaletteItem> }` only while `Palette`'s items are still `PaletteItem`; once `Palette` steps to `PaletteItemItem`, the next round reads `array<PaletteItemItem>`, and `Pets`'s items step to `PetsItemItem`), no two trees end on one name for different shapes however many step (two trees whose names nest into each other, `Pets` and `PetsItemItemCat`, both step, the second past the first's names), and the decision does not depend on declaration order; two trees that mint one name for the identical shape keep it and one model is emitted. Two rounds suffice unless trees chase each other's names; after eight the last decision is kept with a warning. The reference and the extractor read one plan, decided once per document before any reference is typed, so the two agree. A name an operation mints — `operationId: listPets` names an inline array response's items `ListPetsItem`, as a component `ListPets` names its own — is not read here: the component's name is settled first, and the operation's items are settled afterwards against the spec-wide registry of model shapes (see Inline model naming), so a name the component's items own with another shape sends them to `ListPetsResponseItem`, and an identical shape shares the model.

A component whose items reach back to it — `Tree: { type: array, items: { $ref: Tree } }`, directly or through another array component — has no finite type in the IR: the inner reference is typed as `unknown` (`array<unknown>`), with one `[oagen] Warning:` per component however often it is referenced.

The component's own `description`, `deprecated`, `externalDocs`, limits, `readOnly`, `writeOnly`, `default` and `x-*` keys sit on no model, so the one node that names the component with a bare `$ref` and has a place for them carries them. A parameter whose schema is a `$ref` to the component takes the component's `description`, `deprecated`, `default`, `example` and `externalDocs` as fallbacks and merges the component's limits (`minItems`, `maxItems`) underneath its own. A field whose schema is a bare `$ref` to an array component carries what the same array written inline carries: the component's `description`, `externalDocs` and `default` when it declares none of its own, as it takes the component's `example` and `examples`; `deprecated`, `readOnly` and `writeOnly` when either side says so; the component's limits conjoined with any written beside the `$ref`, as JSON Schema applies both (`Tags: { minItems: 1, maxItems: 5, uniqueItems: true }` with `{ $ref: Tags, maxItems: 3 }` gives `{ minItems: 1, maxItems: 3, uniqueItems: true }`, and a wider `maxItems: 10` beside it keeps `5`); and the component's `x-*` keys under the field's own, the field's winning per key. The reference is read through every alias it passes on its way to the array — `PetsAlias: { $ref: Pets }`, `PetsList: { allOf: [{ $ref: Pets }] }`, an alias of an alias — each entry under the nearer one, so an alias's own `description` is the field's and `Pets`'s is read where no alias declares one; the lone member of an `allOf` entry is that entry's own declaration, whose limits count, as `constraints` always conjoins an `allOf`'s members, and whose text and flags do not, as a component model built from one does not read them. This holds on every path that builds a field, an `allOf` merge's inherited property included; a `$ref` to a model, named union or enum leaves all of it but `example` and `examples` on that node, and a `$ref` under a nullable wrapper or an `allOf` read as the reference (`oneOf: [{ $ref: Tags }, { type: 'null' }]`, `allOf: [{ $ref: Tags }, { description }]`) reads none of the text, flags, default, examples or keys — the field documents itself there, from the wrapper and the members written beside the `$ref` — but does conjoin the component's limits with its own, since the wire enforces them wrapped or not and nothing else carries them (`{ allOf: [{ $ref: Tags }, { description: 'The tags.' }] }` beside `Tags`'s `minItems: 1` is `{ minItems: 1 }` with that text). The items' own keywords are the item model's, as for any inline object. No named alias is left for an emitter: an SDK gets `Pet[]` where the document wrote `Pets`, not a `type Pets = Pet[]`.

Two shapes are not array components. A `type: 'array'` with no `items` still becomes a fieldless model, and a `$ref` to it stays `{ kind: "model" }`, since `schemaToTypeRef` types the inline form as `unknown` with a warning. A composition beside the array — an `enum:` list, a `oneOf`/`anyOf` with a typing variant (one that is a nullable wrapper around an array makes the component that array, above), an `allOf` with a member that declares an object inline — is read first, as `isArraySchema` reads it, so such a component is what the composition makes it (an enum, a named union, an `allOf` model with the inline member's fields); an `allOf` of a `$ref` to an array component and limits alone is an alias of it (above), as the same `allOf` on a field is the array. The kinds of alias differ in what a `$ref` to them resolves to (an alias of an enum component resolves to the enum, with no model of its own; see Enum): an alias of an object component — `WidgetAlias: { allOf: [{ $ref: Widget }] }`, with or without limits beside the member, or the bare `$ref` spelling, `WidgetAlias: { $ref: Widget }`, with or without `description`, `deprecated`, `externalDocs`, limits or `x-*` keys beside the `$ref`, which the parser reads exactly as `allOf: [{ $ref: Widget }]` (#618: it was a model with no fields, every `$ref` to it typed as that empty model, and `oagen diff` between the two spellings reported `Widget`'s fields removed) — is a model of its own, `WidgetAlias`, carrying `Widget`'s fields, `required` and discriminator and its own `description`, `deprecated`, `externalDocs`, `extensions` and limits (a `maxProperties` written beside the member, or beside the `$ref`, is `WidgetAlias`'s; `Widget`'s stay on `Widget`), and a `$ref` to it resolves to `{ kind: "model", name: "WidgetAlias" }`, never to `Widget`, at every site that names it — a field, a request or response body, a parameter, array items, map values, an `allOf` member (whose merge types the inherited fields under the alias, `WidgetAliasOwner`, as the alias's own model does) and a union variant, which pins what `Widget` pins, so `Pet: { oneOf: [{ $ref: CatAlias }, { $ref: Dog }] }` with `kind` pinned on `Cat` and `Dog` maps `{ cat: 'CatAlias', dog: 'Dog' }` in either spelling. Both spellings are read through a chain of aliases (`A: { $ref: B }`, `B: { $ref: Widget }`: `A` and `B` each carry `Widget`'s fields, and a `$ref` to `A` is `A`), and nothing an alias writes beside its `$ref` but those annotations is read — not `properties`, not `required`, not a further `allOf`, a `oneOf`/`anyOf` or a `discriminator` — in the alias, at any hop of a chain, in an `allOf` member naming it or in a `$ref` member of an inline `allOf`, as nothing but annotations is read beside any `$ref` (#618 review, #622): `B: { $ref: Widget, required: ['x'] }` under `A: { $ref: B }` is `Widget` at `B`, at `A` and in a merge of `{ $ref: A }`, with `x` as optional as `Widget` declares it, where `B: { allOf: [{ $ref: Widget }], required: ['x'] }` composes the `required` and requires `x` at every hop; `P: { $ref: Pet, discriminator }` dispatches as `Pet` does, by `Pet`'s consts, not by the keyword beside the `$ref`; `CatAlias: { $ref: Cat, properties: { kind: { const: 'other' } } }` as a union variant maps `cat`, the value `Cat` pins and its field carries, never `other`), into a component that itself composes (`Puppy: { $ref: Dog }` with `Dog: { allOf: [{ $ref: Pet }, { properties: { breed } }] }` carries `Pet`'s fields and `breed`, and `Dog`'s dispatcher when it has one), and whichever order the document declares the alias and its target in. A chain of bare `$ref`s that returns to itself (`Loop: { $ref: Loop }`; `A: { $ref: B }` beside `B: { $ref: A }`) names nothing: each such component is a model with no fields, reported once (`[oagen] Warning: Component schema "Loop" is a $ref that resolves to no component … — reading it as a model with no fields`), and the parser never loops; a chain that reaches a cycle through an `allOf` member (`A: { $ref: B }`, `B: { allOf: [{ $ref: A }] }`) ends where the `allOf` reader ends it, declaring nothing more. An alias of an array component (`PetsAlias: { allOf: [{ $ref: Pets }] }`, `PetsAlias: { $ref: Pets }`) has no model to resolve to, so a `$ref` to it is the array `Pets` names (`array<Widget>`), as a bare `$ref` to `Pets` is; an alias of a primitive or enum component is read through the same way (see Primitive components, Enum), unchanged by #618.

### Primitive components

A component schema `schemaToTypeRef` types from its own keywords alone, with no model, enum, array or map — a primitive: `type: string`, `integer`, `number` or `boolean`, with or without `format`, and no keyword beside it that types the schema otherwise (`classifyInlineSchema`: an `enum:` list, a composition that types it); a literal: a `const` of any value (`Kind: { type: string, const: 'cat' }`, `{ const: 7 }`, `{ const: true }`; #569); a union of primitives: a type list of several such types (`Tag: { type: ['string', 'integer'] }`; #569); or `unknown`: a schema that declares no type at all — no `type`, `$ref`, `properties`, `items`, `enum`, `const`, `allOf`/`oneOf`/`anyOf`, `additionalProperties` or `patternProperties` — only annotations and limits (`Anything: { description: 'Any value.' }`, `{}`, `{ format: uuid }`; #569), or an `allOf` alone whose members each declare none of those (`Metadata: { allOf: [{ description: 'Free-form metadata.' }] }`, `{ allOf: [{}] }`, `{ allOf: [{ description: 'a' }, { maxLength: 3 }] }`; #569 review: no member types the schema, so inline it is `unknown` with the members' text and limits on the field, and the component is read the same — a `$ref` to `Metadata` is `unknown`, documented `'Free-form metadata.'`, where it was a fieldless model while the lone-`allOf` spelling of a `const`, a type list or a primitive was read through; an `allOf` with a member that declares a type keeps its own reading — one typing member is that member, several are a fieldless model) — nullable or not, whether by an OAS 3.1 type list naming `null` (`['string', 'null']`, `['string', 'integer', 'null']`), OAS 3.0 `nullable: true`, or a `oneOf`/`anyOf` whose one variant beside a `null` one is such a schema (`oneOf: [{ type: 'string' }, { type: 'null' }]`, `oneOf: [{ description: 'Any.' }, { type: 'null' }]`) — or an alias of one, read through a bare `$ref`, a nullable wrapper and an `allOf` as an array component's alias is (and as an enum component's is; see Enum), is a primitive component and becomes no `Model` (#512, #569). A `$ref` to it resolves to what it declares, the shape the same schema written inline has: with `PetId: { type: string, format: uuid, pattern: '^pet_' }`, every `$ref` to `PetId` is `{ kind: "primitive", type: "string", format: "uuid" }`; with `Kind: { type: string, const: 'cat' }`, every `$ref` to `Kind` is `{ kind: "literal", value: "cat" }`; with `Tag: { type: ['string', 'integer'], maxLength: 20 }`, `{ kind: "union", variants: [string, integer] }`, the `maxLength` on the field; with `Anything: { description: 'Any value.' }`, `{ kind: "primitive", type: "unknown" }`, the text on the field; and a component that admits `null` wraps each in `nullable` (`Kind: { type: ['string', 'null'], const: 'cat' }` is `nullable<'cat'>`, `Tag: { type: ['string', 'integer', 'null'] }` is `nullable<string | integer>`). Before #569 the last three became fieldless models, a `$ref` to each `{ kind: "model" }`, and `Tag`'s `maxLength` sat on the model where no field carried it, while the same schema inline was the literal, the union with the limit, or `unknown`. Like an array component, it is known by its `components/schemas` key, resolved by that key before any name-based test, typed so at every reference site, and its name stays claimed: an array component's items and a named union's variants step around it as they step around any component's. What it declares beside its type — `description`, `deprecated`, `externalDocs`, limits (`pattern`, `minimum`, `maxLength`, ...), `readOnly`, `writeOnly`, `default`, `example`, `examples` and `x-*` keys — is read as an array component's is (see Array components): a parameter whose schema is a `$ref` to the component, or to an alias of it, takes its `description`, `deprecated`, `default`, `example` and `externalDocs` as fallbacks — through every entry the reference passes, nearest first — and conjoins its limits with its own as a field does, the stricter bound winning (`{ $ref: Limit, minimum: 1 }` beside `Limit`'s `minimum: 5` keeps `5`, since the wire enforces it and no model is left to carry it; a `$ref` to a model or enum component still lets the parameter's own keyword override the component's), and under a nullable wrapper or an `allOf` read as the reference conjoins the limits alone, documenting itself from the wrapper and the members beside the `$ref`, exactly as a field does (below), so `Alias: { $ref: Name }` and `allOf: [{ $ref: Name }]` on a query parameter both carry `Name`'s `minLength`; and a field whose schema is a bare `$ref` to it, or to an alias of it, reads all of it from every entry the reference passes, under the field's own, so `{ $ref: PetId, maxLength: 10 }` beside `PetId`'s `maxLength: 36` gives `{ maxLength: 10 }`; a `$ref` under a nullable wrapper or an `allOf` read as the reference — `{ allOf: [{ $ref: PetId }, { description: 'The pet.' }] }`, the usual OAS 3.0 way to document a reference, `{ allOf: [{ $ref: PetId }] }`, `oneOf: [{ $ref: PetId }, { type: 'null' }]` — reads the component's limits the same way, conjoined with the field's own and any written beside the `$ref` (`{ pattern: '^pet_' }` on that `Pet.id`, where `PetId` declares the pattern), since the wire enforces them wrapped or not and no model carries them, but none of the component's text, flags, default, examples or keys: there the field documents itself, from the wrapper and the members beside the `$ref` (`'The pet.'`), as a field naming an array component does. A response or request body that is a `$ref` to the component is typed the same way, and one to a component that declares no type is `unknown` to the primary-response pick as an inline `{}` body is (`bodyTypesAsUnknown`): the lowest 2xx whose body is typed wins, so `200: { $ref: Anything }` beside `201: { $ref: Pet }` makes `Pet` the response — through an alias too, one that writes a single-entry type list beside the `allOf` included (`Alias: { type: ['string'], allOf: [{ $ref: Anything }] }` is the reference, since a list of one type is that type and the `allOf` beside it is followed; #569 review: the pick read the list as typed and exposed `unknown`), while a list naming `null` beside the type (`['string', 'null']`) is `nullable<unknown>`, which is typed and keeps the pick. No named alias is left for an emitter: an SDK gets `string` where the document wrote `PetId`, the literal `'cat'` where it wrote `Kind`, and `unknown` where it wrote `Anything`, not a `type PetId = string`. A type list naming `object` or `array` (`['object', 'string']`, `['array', 'string']` with `items`), a `type` no rule knows, `type: 'null'` alone in either spelling (`{ type: 'null' }`, `{ type: ['null'] }`), `type: 'array'` without `items`, and a schema with no `type` but an `additionalProperties` or `patternProperties` map are not primitive components: each still becomes a fieldless model, and a `$ref` to it stays `{ kind: "model" }`. A `oneOf`/`anyOf` of string `const` variants, one beside a `null` variant included, is an enum component, not a literal (see Enum).

### Schema references

A Schema Object's `$ref` is a JSON Pointer (RFC 6901), and the parser reads every one through one module (`src/parser/schema-refs.ts`; #539). A `$ref` that is exactly `#/components/schemas/<key>` names that component, by its key as written with the tokens decoded as the bundler decodes them when it checks that the `$ref` resolves (`unescapePointerFragment` from `@redocly/openapi-core`, per token: the pointer escapes undone, `~1` for `/` then `~0` for `~`, then the percent-escapes a URI fragment carries, RFC 6901 §6 — so `#/components/schemas/a~1b` names the key `a/b`, `#/components/schemas/Pet%20Owner` the key `Pet Owner` and `#/components/schemas/Note/properties/due%20date` the property `due date`; the bundler leaves the `$ref` string as written, so the parser decodes it itself, in the bundler's order, and every `$ref` the bundler resolved is followed to the same place: a `%2F` decodes inside its token and never splits one), and resolves as the sections above say: a model, a named union, an enum or an alias of one, the array an array component declares, what a primitive component declares — under `nullable` when the component admits `null` (see Nullable components under Model & Field). A `$ref` deeper into a component is a pointer to a schema inside it, followed as RFC 6901 evaluates it — each token a key of the object at hand, or the index of a list member (`0`, or digits with no leading zero; `-` names nothing), through the keywords a schema holds schemas under (`properties/<name>`, `items`, `additionalProperties`, `patternProperties/<pattern>`, `allOf/<n>`, `oneOf/<n>`, `anyOf/<n>`, `not`, `prefixItems/<n>`, `$defs/<name>`, …) and never through a `$ref` on the way — and the site is typed as that schema is typed where it stands, never as a copy of it. With `Pet: { properties: { id: { type: string }, owner: { type: object, required: [name], properties: { name: { type: string } } } } }`, a response (the primary's body or any other success entry's), request body, parameter of any location (a cookie's included), member of a mutually-exclusive body group (typed afresh from the body's variant schema, so a reference of its own; a query group's members are the operation's parameters), component field, array items, map values, union variant or webhook payload written as `{ $ref: '#/components/schemas/Pet/properties/owner' }` is `{ kind: "model", name: "PetOwner" }`, the model `Pet.owner` is built as — one model, referenced from both places, and a merge pass that renames it repoints the pointer site with the field; `#/components/schemas/Pet/properties/id` is `string`, and so is `Pet/properties/owner/properties/name`; `#/components/schemas/Pets/items` is what the array component `Pets` resolves to holds (`PetsItem` for inline object items, `Widget` for `items: { $ref: Widget }`); `Pet/properties/tags/items` and `Pet/properties/labels/additionalProperties` are that field's items and values — a map's values when the schema pointed at is the one the values are typed from (`mapValueSchema`: a non-empty `additionalProperties`, else the first `patternProperties` entry; `additionalProperties: {}` types them `unknown` on its own, so a pointer to it is `unknown` without a warning), so `patternProperties/^n` beside a first pattern `^s`, or a pattern beside a non-empty `additionalProperties`, names no type and is reported (`the values are typed from another schema than "patternProperties/^n"`), never typed as the other schema; and, for a model with named properties, the values of its catch-all `additionalProperties` field (`Box/additionalProperties` is `integer` for `Box: { properties: { id }, additionalProperties: { type: integer } }`), while a pattern beside named properties, which no field carries, is reported (`a schema with named properties types no "patternProperties/^s" values`); `Pet/properties/choice/oneOf/1` and a named union's `Shape/oneOf/1` are the union's second non-null variant, and the one non-null member of a union collapsed to a nullable wrapper (`maybe: { anyOf: [X, { type: null }] }`, typed `nullable<X>`) is `X` whole for `maybe/anyOf/0` — a union of its own (`union<array<integer>|string>` for `X: { type: ['array', 'string'], items }`) or a named union (`Shape`) included, never that union's first variant; a step through a multi-type schema (`type: ['object', 'string']`, typed as a union of one member per type) reads the member that carries the keyword — the object member's model for `properties/<name>` (`Thing/properties/shape/oneOf/1/properties/side` is `number` for a `['object', 'string']` variant declaring `side: { type: number }`), the array member for `items`, the map member, or the object member's catch-all field, for `additionalProperties`; `Base/allOf/0` is the `$ref` member's own type and `Base/allOf/1/properties/extra` the merged model's field, while a pointer that stops at an inline `allOf` member is typed as the member is where it stands: when the `allOf` is read as that member — its one typing member beside members that only annotate it (`readInlineAllOf`; #555) — the `allOf`'s own type (`Kind/allOf/0` for `Kind: { allOf: [{ type: string, enum: [a, b] }, { description }] }` is what `{ $ref: Kind }` is), and otherwise `unknown` with a warning, since the parser builds no type for the member on its own — it declares into the merged model (`Pet/allOf/1` for `Pet: { allOf: [{ $ref: Owner }, { properties: { nickname } }] }`, or a field's `Note/properties/author/allOf/1`) or only annotates the member the `allOf` is read as — and never the merged model, which would require `Owner`'s `email` the member does not declare (`[oagen] Warning: Unresolved schema $ref "#/components/schemas/Pet/allOf/1" in Pets.getPetNickname.response: "allOf/1" is an inline allOf member, which has no type of its own — typing the site as unknown`); a pointer that lands on a `$ref` schema (`Pet/properties/friend` with `friend: { $ref: Owner }`) is what that `$ref` is (`Owner`), and one that lands on another pointer is what that pointer is. Before #539 the last token was taken for a component's key, so such a site was typed as a model `Owner` that nothing declared (`[oagen] Warning: Unresolved model reference "Owner"`), or, when an unrelated component `Owner` existed, as that component, silently; `Pets/items` named `Item` and `Pet/properties/id` a model `Id`.

The type is settled once every model is built (`resolveSchemaPointers` in `src/parser/schema-pointers.ts`, before any merge pass renames a model), by walking the pointer through the IR alongside the document; until then the site holds a reference named by the `$ref` itself, which no model can be named. A pointer that leads nowhere is reported once, at the site, and the site typed `unknown`, never a model the pointer does not name: one into another section of the document (`{ $ref: '#/components/responses/Problem' }` as a schema), to a component the document lacks, to no schema (`Pet/properties/id/type`, `Kind/enum/0`, a pointer through a `$ref` on the way), or to a schema the parser builds no type for at that place (a union's `null` variant, which the IR carries as nullability; a property of an enum or primitive component; a keyword the parser never reads, such as `not` or `prefixItems`; an inline `allOf` member the `allOf` is not read as, above), and a chain of pointers that reaches itself — through a field whose type is the site, or through an array component whose items point back into it (`Loop: { type: array, items: { $ref: '#/components/schemas/Loop/items' } }`, written through `transformSpec`, types `{ $ref: Loop }` as `array<unknown>` and `Loop/items` as `unknown`, each site reported once) — `[oagen] Warning: Unresolved schema $ref "#/components/schemas/Pet/properties/nope" in Pets.getPetOwner.response: no schema at that pointer — typing the site as unknown`, `[oagen] Warning: Circular schema $ref chain starting at "#/components/schemas/Kennel/properties/self" in Kennel.self — typing the site as unknown`. The bundler rejects a dangling or self-referencing pointer before the parser runs (`Can't resolve $ref`, `Self-referencing circular pointer`), so those reach the parser only through `transformSpec`. A pointer site reads what a bare `$ref` to a model reads of the pointed schema's text and flags: its `example` and `examples` (and a parameter its `description` and `default`, as from any referenced schema), nothing else, which stays on the field or model the schema belongs to. Its limits it reads as a `$ref` to a primitive or array component reads the component's (see Type constraints; #545): once the site is settled, the limits the pointed schema's own type carries — read through every nullable wrapper the site settles into, two for a chain whose link is a nullable wrapper around a pointer to a schema that admits null — are conjoined with what is written beside the pointer and around a nullable wrapper the type builder reads through (`maxLength: 10` on `oneOf: [{ $ref: …/code, maxLength: 3 }, { type: null }]` keeps the `3`), the stricter bound winning, on the field, the parameter and the type alike — `{ $ref: '#/components/schemas/Owner/properties/code', maxLength: 3 }` to `{ type: string, pattern: '^own_', maxLength: 8 }` is `{ maxLength: 3, pattern: '^own_' }` — while a pointer to a schema typed as a model or enum adds none, that node carrying its own, and the site keeps what it wrote beside the `$ref`, as beside any `$ref` to a model. What a site decided from the pending reference is decided again from the settled type. The primary response is chosen knowing what a pointer settles to: `bodyTypesAsUnknown` reads the pointer ahead from the document (`pointerTypesAsUnknown`: it leads nowhere, or to a schema the parser builds no type for at that place, or to one typed `unknown` where it stands, as `{}` is; a pointer ending at a `properties/<name>` step lands on the declaration the merged model's field is typed from, every `allOf` member's combined as `collectObjectProperties` combines them, so `Holder/allOf/1/properties/owners` to a member declaring `owners: { description }` beside one declaring `owners: Owner[]`, or beside a `$ref` member to a component that does, is the array `Holder.owners` is, as the settle types it), so a `200` body written as `{ $ref: '#/components/schemas/Pet/properties/anything' }` beside `anything: {}` loses to a typed `201` exactly as the same schema written inline would, and `200: { $ref: Pet/properties/id }` keeps the `200`; a chain of pointers that reaches itself is seen only at the settle, so it counts as typed there. An operation whose primary response was a pointer chooses its iterator's item type from the settled response (`paginatedItemType`): a paginated response written as `{ $ref: '#/components/schemas/Pet/properties/tags' }` with `tags` an array of strings yields strings, not arrays, and one pointing at an object yields the object, as a `$ref` to a component does — through every nullable wrapper the settled response wears, two for a nullable site settled from a pointer to a schema that admits null (`{ oneOf: [{ $ref: '#/components/schemas/Holder/properties/owners' }, { type: null }] }` to `owners: { type: [array, null] }` is `nullable<nullable<array<Owner>>>` and yields `Owner`; #609). So does an operation whose list envelope's `data` was a pointer (see Pagination above): the envelope is recognized from what the pointer lands on, read ahead from the document as `bodyTypesAsUnknown` reads one (`pointerTypesAsArray`), and until the settle its `response` is the pending reference and its `itemType` that very reference, which the settle rereads as the settled array's items. An explicit `dataPath` whose walk through the IR crossed a pending reference — that response, or a field on the way — is walked again at the settle, from the settled types through the models, under every nullable wrapper the site settled into (`nullable<nullable<HolderResult>>` for `oneOf: [{ $ref: …/Holder/properties/result }, { type: null }]` to a nullable `result`), so it reuses the model the pointed schema's items are built as and never a copy of it read from the document (#608): `x-pagination: { dataPath: 'items' }` on a response written `{ $ref: '#/components/schemas/Holder/properties/result' }`, with `Holder: { result: { items: { name: string }[] } }`, iterates `HolderResultItem`, the very type `HolderResult.items` holds, and no `ListOwnersItem` is built, so `spec.models` is `Holder`, `HolderResult`, `HolderResultItem` — as with `Holder.result` and the response both `$ref: Result`, which iterates `ResultItem`. A path that goes on through the variants of a union to more than one array is read from the document at extraction instead, as any such path is, while variants that all hold one pointer land on one array and settle like any other path (see Overriding detection). A `$ref` that names no component names no model either: as a named union's variant it is unnamed (no implicit discriminator is derived from it; see Named unions). A discriminator `mapping:` target that is a pointer — written as one, or as a component that is an alias of one (`Hound: { $ref: '#/components/schemas/Shelter/properties/dog' }` with `dog: '#/components/schemas/Hound'`; #619 review) — is settled to the model the schema it points at is built as, wherever that schema stands (#539, #619). The bundler would have the parser read it otherwise: it hoists the schema such a target points at, through the alias, into a component named by the pointer's last token — `#/components/schemas/Zoo/properties/dog` becomes a component `dog`, the very object `Zoo.dog` is — and rewrites the target to `#/components/schemas/dog`, while a variant written as the pointer stays as written; read by key, the target would name a model built for the hoisted component (`Dog`) that no variant, field or operation references. So the parser writes every such target back as the document wrote it once the bundler is done and drops the component the bundler added for it (`loadAndBundleSpec`; a component the document declares itself, which the bundler found equal to the pointed schema and folded the target onto, stays, and the target is written back all the same), and each target is read through its alias chain and deferred to the settle of the reference it follows (`deferPointerMappingEntries`): a target whose schema — at any hop of the chain — is a pointer variant's, matched by identity through the variant's own aliases, follows the variant, to the model it settles to (`dog: Hound` beside the variant `Shelter/properties/dog` is `ShelterDog`, as the pointer spelling is, so `oagen diff` between the two spellings reports nothing; `Hound` itself as the variant keeps `Hound`, the variant's model; an alias of a component, `Hound: { $ref: Cat }`, names that component, `Cat`, as the bundler's rewrite made it before; an alias of a pointer no variant holds settles like the pointer, to `ShelterDog`); a target outside the variants follows a pending reference of its own, settled at the mapping site to the model the pointed schema is built as (`settleDeferredMappingEntries`). A request body written as the union settles its entries as a field's or a response's inline union does (`deferInlineUnionMappingEntries`), so the body's `dog` is `ZooDog` or `ShelterDog` too, never the pointer as written, a name no model has. Either follows a later rename of that model (`renameVariants`: the union is handed to the model's site with a copy of each settled entry's reference put before its variants, so every key sharing one pointed model follows — three keys `dog`, `hound` and `puppy` on `Shelter/properties/dog` beside a pointer variant and a redirected inline variant all move to `ShelterDog2` with it). `Pet: { oneOf: [{ $ref: Cat }, { $ref: Zoo/properties/dog }], discriminator: { propertyName: kind, mapping: { cat: Cat, dog: Zoo/properties/dog } } }` carries `{ cat: "Cat", dog: "ZooDog" }` beside variants `Cat | ZooDog`; with `dog: Shelter/properties/dog` instead, beside `Shelter: { properties: { dog: { … } } }`, it carries `{ cat: "Cat", dog: "ShelterDog" }` beside the same variants, and `models` holds `Cat`, `Pet`, `Shelter`, `ShelterDog`, `Zoo` and `ZooDog` — no `Dog` — as a component, written inline on a field (`Home.pet`, whose other entries stay as the document spelled them) and as an allOf+oneOf dispatcher's mapping alike; an inline object variant pinning the entry's value, which the entry redirects to its target, is typed as that model too (`ShelterDog`, the variant's own extracted model kept beside it, as under a component target), the object member of a multi-type variant included, and a later rename of that model reaches the entry through the member as it does through a variant; two keys pointing at one schema both name its model; a target into an array's items (`Kennel/properties/dogs/items`) or a map's values (`Kennel/properties/byName/additionalProperties`) names the model built for them (`KennelDogs`, `KennelByName`); one landing on a `$ref` names the component it refers to; one landing on a schema that admits null is read through the nullable wrapper the site settles into. A target that leads nowhere — which reaches the parser only through `transformSpec`, since the bundler rejects it — is reported once, at the entry, and the entry left as written (`[oagen] Warning: Unresolved schema $ref "#/components/schemas/Shelter/properties/nope" in Pet.discriminator.mapping.dog: no schema at that pointer — leaving the entry as written`; `Home.pet.discriminator.mapping.dog` for a field's union); one that settles to no model — a pointer to a string — is left as written too, silently, as a target naming a primitive component is (an inline union's with the leading `#/components/schemas/` stripped, as its other entries are). A target that is a pointer into another section of the document, or into another file, is no schema `$ref` the parser follows: the bundler's hoist of it stands.

### Inline model naming

Models come from `components/schemas` (named as written, after `cleanSchemaName` — which singularizes the leading word by the rule stated below for an array's items, `Licenses` → `License`, `Statuses` → `Status` — and any `schemaNameTransform`; an enum or an alias of one, an array or primitive component yields none — see Enum, Array components and Primitive components) and from inline object schemas in operations, which the parser materializes as models so emitters have something to reference. Two component keys that resolve to one name (`Note` and `note`) keep the definition with more fields, the first on a tie; when the two differ in fields, types or limits (`modelFingerprint`), the parser prints `[oagen] Warning: Component schemas "Note" and "note" both resolve to "Note" with different fields or field types` before dropping the other, and folds identical definitions silently. An inline request body or response is named from its operation:

- **With an `operationId`:** `PascalCase(operationId)` + `Request` / `Response`, passed through `cleanSchemaName`. `createNote` → `CreateNoteRequest` / `CreateNoteResponse`. An `operationId` declared on more than one Operation Object, which OpenAPI forbids, names the models of one of those Operation Objects only, so no two bodies share a model. Two `operationId`s that strip to one id once the overload markers at their ends go (`listPets[1]` and `listPets[2]`, or `listPets[1][2]`; see Service & Operation) take one name and one stem, so they are that id declared twice and are read exactly so: `listPets[1]` on `GET /pets` beside `listPets[1][2]` on `GET /pets/all` returns a `ListPetsResponse` and a `ListPets2Response`, each with its own fields, never one `ListPetsResponse` keeping the larger shape for both. An operation the reuse renames within its service (see Service & Operation) names its models after its new name: `createNote2` on `POST /notes/drafts` beside `createNote` on `POST /notes` sends a `CreateNote2Request`, and its response, error bodies and nested models follow (`CreateNote2Response`, `CreateNote2Error404`, `CreateNote2ResponseOwner`). Of the operations that keep the name — one per service — the first by API root length, then path, then HTTP method keeps the `operationId`'s models, and every other one names its models from its path, as an operation without an `operationId` does: `createNote` on `POST /archived-notes` and on `POST /notes`, in two services, send a `CreateNoteRequest` and a `NotesPostRequest`. A new name is the parser's, so, like a path-derived prefix, it yields to every `operationId` whose models could start with it: a renamed operation names its models from its path as well when another `operationId` names models from its new name (`createNote2` in `Notes` beside `operationId: createNote2` in `Tags` sends a `NotesDraftsPostRequest`) or from a name that extends it (a renamed `getNote2` beside `operationId: getNote2Response` returns a `NotesDraftsGetResponse`, since the `request` object it returns would otherwise be `GetNote2ResponseRequest`, the body `getNote2Response` sends). Two paths that `$ref` one Path Item read one Operation Object and one body, so they share its models, named as the first of its paths in that order names them (`listPets` on `/pets` and `listPets2` on `/pets/all` both return a `PetsGetResponse` when `operationId: listPets` on `/other` keeps `ListPetsResponse`). The outcome does not depend on document order. Two distinct `operationId`s can clean to one stem — `createPet` beside `create_pet` or `CreatePet` (each PascalCases to `CreatePet`), beside `createPetController` (`Controller` is a backend word the cleaning strips), `listNotes` beside `listNotesByExternalId` (`ByExternalId` is a marker it strips), `Notes_List` beside `Note_List` (the leading word is singularized) — and would name every model the stem names alike (`CreatePetRequest`, `CreatePetResponse`, `CreatePetError404`, a list's `CreatePetItem`, the nested models and envelope companions under them, the enums the bodies mint), the merge keeping the first definition for both with a warning, so that one operation was typed with fields it does not take and which one followed the order of the paths (#627). Such a stem is _contested_, and the contest is settled before any operation is built, exactly as a reused id is: the operation the cleaning moved least keeps the stem and the plain names, and every other one names its models from its path, as an operation without an `operationId` does, its header and parameter models included (see Response Headers and Parameters). An id the cleaning stripped a marker or a backend word from (`listNotesByExternalId`, `createPetController`) never keeps a contested stem; among the rest, one whose PascalCase form (read up to the overload markers at its end) is the stem as written — `createPet`, `create_pet` and `CreatePet` alike for `CreatePet`, `list_notes` or `ListNotes` for `ListNotes`, whatever case the document writes its ids in — outranks one whose leading word was only singularized (`Notes_List`, `NotesList` to `NoteList`); a tie, between ids that differ in case or separators alone, goes to the one written in camelCase when there is exactly one, and to none when there is none. So `createPet` on `POST /pets` beside `create_pet` on `POST /pet-drafts` sends a `CreatePetRequest` and a `PetDraftsPostRequest` and returns a `CreatePetResponse` and a `PetDraftsPostResponse`, each with its own fields, in either path order, and so beside `CreatePet` or `createPetController`; `list_notes` on `GET /notes` keeps `ListNotesResponse` beside `list_notes_by_external_id` on `GET /notes/external` (`NotesExternalGetResponse`), as `ListNotes` does beside `ListNotesByExternalId`, `CreatePet` beside `CreatePetController` and `Notes_List` (`NoteListResponse`) beside `Notes_ListByExternalId`; `Note_List` keeps `NoteListResponse` beside `Notes_List`, and `notesList` beside `Notes_List`; while `create_pet` beside `CreatePet`, or `listNotesByExternalId` beside `list_notes_by_external_id`, path-names every one of them. Whether the contested bodies agree in shape takes no part — two bodies of one shape under `createPet` and `create_pet` are two models, named from the ids alone, so a field added to one of them later changes its own model rather than renaming it — and an `operationIdTransform` renames the operation only, as always. Adding `POST /pet-drafts` (`create_pet`) beside `createPet` is therefore additive: `oagen diff` reports the `PetDrafts` service and its two models added, `createPet`'s models unchanged, and exits `1`; adding `createPet` beside a lone `create_pet`, which held the stem alone, reports `CreatePetRequest` and `CreatePetResponse` modified beside `PetDraftsPostRequest` and `PetDraftsPostResponse` added. The reuse pass runs first, and a reused id's claim yields to every id declared once whose stem it is, so `createPet` declared on two Operation Objects beside a lone `create_pet` leaves `create_pet` holding `CreatePet` alone and both `createPet` operations path-named. Two paths that `$ref` one Path Item whose operation loses its stem share its path-named models, named as the first of its paths in that order names them. The outcome depends on the document's `operationId`s alone, never on their order.
- **Without an `operationId`:** from the full path and method, as for an `operationId` that names nothing (`' '`, `'-'`, `'[1]'`, `'[1][2]'`; see Service & Operation). Each non-parameter segment is PascalCased in order, each `{param}` segment becomes `By` + `PascalCase(param)`, a custom method written after a colon is read as its segment followed by the verb (`POST /pets/{id}:adopt` → `PetsByIdAdoptPostRequest`, the prefix of `/pets/{id}/adopt`), a segment with several colons outside braces is one literal even when a parameter opens it (`POST /v1/pets/{id}:adopt:now` → `V1PetsIdAdoptNowPostRequest`), then the method and `Request` / `Response` are appended, and the whole name is normalized with `toPascalCase` so an operation's body and response share a prefix (`POST /a/b` → `AbPostRequest` / `AbPostResponse`). `POST /notes` → `NotesPostRequest` / `NotesPostResponse`; `POST /notes/{id}/pin` → `NotesByIdPinPostResponse`; `GET /users/{user_id}/sessions` → `UsersByUserIdSessionsGetResponse`. This tells the common path shapes apart (list vs. item, sibling and nested sub-resources) but is not unique by construction: `/foo-bar` and `/foo/bar`, `/notes/by-id` and `/notes/{id}`, `/notes` and `/notes/`, or `/pets/{id}:adopt` and `/pets/{id}/adopt` flatten to the same words. Names already taken are reserved first: every component schema name and, for every operation with an `operationId`, the stem all of its models start with (`PascalCase(operationId)` after `cleanSchemaName`). A path-based prefix is treated as colliding when any reserved name starts with it, because one prefix is the stem of several emitted names (`…Request`, `…Response`, a list's `…Item`, nested inline models such as `…ResponseOwner`, envelope companions such as `…ListMetadata`). A prefix that _extends_ such a stem is the one case that check does not reach — `GET /create/pet/response/drafts` beside `createPet` flattens to `CreatePetResponseDraftsGet`, and its `…Response` is exactly the name of a `drafts_get_response` object nested in `createPet`'s response (`CreatePetResponseDraftsGetResponse`), as `POST /create/pet/request/foo` would name its body after a `foo_post_request` object nested in `createPet`'s request body, or in the items of its array request body, which are `CreatePetRequest` itself — so when any prefix extends an operation's stem, every name the operations' inline request and success bodies mint, nested models included and each body read as the operation will type it, is reserved as well, and such a path is hashed (`CreatePetResponseDrafts93Edb5GetResponse`) whether it is path-named for want of an `operationId` or because its `operationId` lost its stem (#627). Names derived from a path-based prefix use it verbatim — body `oneOf` variants included (`NotesPostRequest`, `NotesPostRequest2`, `EmailNotesPostRequest`) — and are never re-cleaned, so no later step can move them out from under the reservation; as a second line of defence the check also runs on the cleaned spellings of the prefix (`cleanSchemaName`, the project's `schemaNameTransform`, `ListItem`-marker stripping), so an unnamed `GET /notes` also yields to a component `NoteGetItem`. Names that embed the prefix behind a const value are covered as well: a body `oneOf` variant pinning `kind: email` is `EmailTagsPostRequest` and a nested `oneOf`/`anyOf` variant is `<Const><Parent><Field>`, so every string `const` (or single-value `enum`) found in the operation's inline body and 2xx response variants, top level and nested, is prepended to every spelling before the check, and a hashed prefix lands inside those names too (`EmailTags151Dd5PostRequest`). Names that do not embed the prefix at all — a response `oneOf` variant named from its bare const (`Email`) or a `title`-mapped variant — are outside what a disambiguator can separate and are left as they are. This is deliberately a superset: a component `AuditEventsGetter`, or an operationId `auditEventsGetSummary`, also pushes an unnamed `GET /audit/events` onto a hashed name although no emitted name would coincide; determinism and never sharing a name wrongly matter more than the rare extra hash. The reservation is unconditional, so an inline body is never merged into a same-named component even when their shapes agree. When two distinct paths with the same method would collide, the path spelled most plainly keeps the plain name (no trailing slash, `{id}` rather than a literal `by-id`; precisely, the lowest `[trailing slash, custom methods written after a colon, literal segments with a character outside a-z0-9]`, so `/pets/{id}/adopt` keeps the plain name over `/pets/{id}:adopt` and `/pets/{id}/batchAdopt` over `/pets/{id}:batchAdopt`, while a parameter segment is never irregular and `/tags/{tag}.json` beside `/tags/{tag}/json` ties), and every other path in the group gets a six-character disambiguator derived from its raw path (the start of its SHA-1, inserted before the method): `POST /foo/bar` next to `POST /foo-bar` → `FooBarPostResponse` and `FooBar546F12PostResponse`; `GET /notes/{id}` next to `GET /notes/by-id` → `NotesByIdGetResponse` and `NotesByIdBa41B5GetResponse`. The hash follows the prefix as a number does (see Numbered names below), so one that starts with a digit is set off from a prefix that ends in one by `No`: `GET /pets/top10/` next to `GET /pets/top10` → `PetsTop10No567B59GetResponse`, never `PetsTop10567B59GetResponse`, whose hash would read as part of `Top10`. When two paths tie for plainest (`/foo-bar` and `/foo_bar`), or the path-based name matches a reserved one (an unnamed `POST /audit/events` next to `operationId: auditEventsPost` or next to `components/schemas/AuditEventsPostRequest`), nobody keeps the plain name and every path in the group is disambiguated. The result depends only on the document's paths, `operationId`s and component names and never on their order; `operationId`-derived and component names never change, and paths that do not collide keep the plain name.
- **Shared through `components/responses`:** a response written as `{ $ref: '#/components/responses/PetFound' }` is resolved before it is read (chains are followed; a circular chain fails the parse; a `$ref` that points outside `components/responses` — into another section such as `#/components/schemas/Pet`, or a bundler-written pointer such as `#/paths/~1pets/get/responses/200` — is warned about (`Unresolved response $ref "#/components/schemas/Pet" in 404 response of getPet: no matching entry under components/responses — reading the response as written, without a body or headers`) and read as the Reference Object it is, with no body or headers — `404: { $ref: '#/components/schemas/Pet', content: { … }, headers: { … } }` is an error entry with neither `type` nor `headers`, since a `content` or `headers` written beside a `$ref` is ignored as it is beside a ref that resolves (#562) — as is a `$ref` that is not a string (`{ $ref: 42 }` → `Malformed response $ref 42 in 404 response of getPet: a $ref must be a string — …`; the value is rendered as JSON, so `{ $ref: [] }` reads `Malformed response $ref [] in …`, never an empty slot, and `{ $ref: ['#/components/responses/NotFound'] }` reads `Malformed response $ref ["#/components/responses/NotFound"] in …`, never the string it is not), while a `$ref` into `components/responses` that names no entry never reaches the parser: the bundler rejects it, and `parseSpec` throws `Failed to parse spec: Can't resolve $ref`; a sibling `description` beside the `$ref` wins in an OAS 3.1 document, outermost first, and is ignored in an OAS 3.0 one). Its inline body is named after the component, not the operation — `PascalCase(componentName)` + `Response`, passed through `cleanSchemaName`, the suffix not doubled when the component is already named `…Response` (`PetFound` → `PetFoundResponse`, `ErrorResponse` → `ErrorResponse`) — so every operation that returns it shares one model instead of minting a `<Op>Response` copy each — whether it returns it at an explicit status code (at a `3xx` too, where the entry's `type` stays `unknown` and its JSON media type's `contents` entry is that model), as `default` or in a `1XX`–`5XX` range: a `default` and a `4XX` both written as `$ref: '#/components/responses/Problem'` are one `ProblemResponse`, shared with the `404` of another operation that points at it; a chain is named after the ref the operation wrote. Everything else the component declares that mints a model is named from the stem of that shared body name — `<Component>Response` less its `Response` (`Card`), or `CardResponse2` when the body stepped to it — too: an inline object under another media type is `<Component><MediaType>Response` (`Card` with an `application/yaml` body → `CardApplicationYamlResponse`) and an object-shaped header is `<Component><Header>` (`Card` with `X-Meta` → `CardXMeta`), nested objects under either qualified by it. These names do not depend on the operation, its service, or the status code or fallback key (`404`, `302`, `default`, `4XX`) the operation mounts the component at, so every operation that returns the component shares one model of each, as it shares the body; a name a component schema or another site already owns with a shape it does not share steps by number (`CardXMeta2`, `CardApplicationYamlResponse2`), as the component's body steps to `CardResponse2`, never by the operation or the status code — those qualifiers belong to an inline response's sites; an inline enum such a site carries — a header's, a secondary body's, the body's — steps by number the same way when the collectors promote it (`CardXMode2`), never by the status code or fallback label (see Response Headers and Response Content Types above). The models of these sites are named before those of every operation's own sites, component by component in `components/responses` order (an entry already named like its body, `CardResponse`, ahead of one that only derives that name, as the bodies are settled), and belong to no operation, whichever operations return the component: of two components whose sites derive one name the earlier keeps it (`Card`'s `X-Meta` header is `CardXMeta`, `CardX`'s `Meta` header `CardXMeta2`), and an operation's own header or body that derives a component's name steps past it as past a component (`CardGetCardXMeta` for `getCard`'s own `X-Meta` beside `Card`'s, `CardApplicationYamlResponse200` for the `application/yaml` body of an operation `card`, `ListNotesDefaultResponse2` for `listNotes`'s own `default` beside a component `ListNotesDefault`), whatever the order of the paths and whether or not that operation returns the component too. So a stepped name depends on the component alone too, and removing one of the operations that return the component leaves the others' names unchanged. A component no operation returns has no sites, though, so the first operation to return it can still rename a clashing site of a component later in that order, or an operation's own, which `oagen diff` reports as breaking. The component's stem is reserved like an `operationId`'s, so an unnamed `GET /owner` beside a component response `OwnerGet` takes a hashed name. The body itself steps by number (`CardResponse2`, `…3`), its nested models with it, past every name a component schema (or a model a component's field mints), an earlier component's body or an operation's own inline success body already takes, whatever its shape — an operation named from its `operationId` keeps the names its inline 2xx bodies mint, at any success code — the primary's under `<Op>Response`, a later status code's under the stem it moves to (`CardResponse201`, see Multiple Success Responses): `card`'s inline 200 keeps `CardResponse`, and the body of a component `Card` that `getNote` returns is `CardResponse2` at every site, whatever the order of the paths, while an operation that mints no model under that name (one that returns the component itself, a `$ref` or a string, or an inline body at a later status code only) takes nothing from it. The names are reserved as the operation settles them, its array items included: beside a schema `CardItem`, `card`'s inline array of `{ j }` is `CardResponseItem[]` (the items retry described below), so a component `Card` whose body nests an `item` steps to `CardResponse2` (`CardResponse2Item { q }`) in either path order, rather than minting a second `CardResponseItem` of another shape that the merge would fold onto the first with a warning. So adding such an operation moves the component's body to the next number, which `oagen diff` reports as breaking, as it does for a component schema added under the body's name. The names a body mints are reserved under every reading an operation can give it — a list envelope unwrapped for an iterator (`NotePage: { data: { title }[], has_more }` → `NotePageItem`) and kept as the wire shape (`NotePageResponse`, `NotePageResponseData`) — since which reading an operation takes depends on its own query parameters and override, and two operations returning one component can differ (`GET /notes` keeps it, `GET /notes/recent?after` unwraps it): beside a schema `NotePageResponseData` or `NotePageItem` the stem steps to `NotePageResponse2` for every operation, so a kept body's item model is never renamed late and both readings move together. The component's headers resolve through `components/headers` as inline ones do.

A response object with a string `const` discriminant (`object: "note"`) is named from that value instead (`Note`), except a list envelope kept as a plain model: its const (`object: "list"`) names the kind every envelope shares, not what it lists, so it keeps the operation's name (`ListPetsResponse`, never `List`). Of an inline `allOf` body, only a const an always-applying member declares can name it: a property only the `oneOf`/`anyOf` variants of a member declare holds on a branch, not on every body, so `allOf: [{ properties: { name } }, { oneOf: [{ properties: { kind: { const: cat } } }, { properties: { bark } }] }]` keeps the operation's name (`CreatePetResponse`, never `Cat`), even when every variant declares the same const, and a const added to a variant renames nothing (#396). Nested inline objects are qualified with their parent model's name, and an array's items (a map's values too) with the field's singular, which is read by suffix as a path segment's is (`singularize` and `singularizePathSegment` share one rule, `stripPluralSuffix`, so a `causes` field and a `/causes/{id}` resource spell one `cause`; #620): `-ies` becomes `-y` (`policies` on `Pet` → `PetPolicy`), `-yses` becomes `-ysis` (`analyses` → `PetAnalysis`), the `es` of a sibilant stem is dropped — `-sses`, `-uses` after a consonant, `-iases`, `-xes`, `-ches`, `-shes` (`addresses` → `PetAddress`, `statuses` → `PetStatus`, `aliases` → `PetAlias`, `boxes` → `PetBox`, `batches` → `PetBatch`, `hashes` → `PetHash`), except `-aches` after a consonant, an `-ache` noun's plain `s` (`caches` → `PetCache`, `headaches` → `PetHeadache`; an `-ach` noun has a vowel there, `coaches` → `PetCoach`) — and any other `s` is a plain plural `s` (`notes` → `PetNote`, `causes` → `PetCause`, `licenses` → `PetLicense`, `responses` → `PetResponse`, `releases` → `PetRelease`; before #620 every `-ses` word lost its `es`, `PetCaus`, `PetLicens`, `PetRespons`, and every other `-es` word only its `s`, `PetBoxe`, `PetBatche`). A safe-listed word (`Status`, `Address`, `Access`, `Process`, `Canvas`, `Radius`, `Series`, `Species`, …) and its `-es` plural (`canvases` → `PetCanvas`, `radiuses` → `PetRadius`, whatever the suffix rules would make of them), a word of four letters or fewer (`tags` → `PetTags`, `axes` → `PetAxes`), a word ending in `ss` and a `-ysis` word are kept as they are; any other `-us` or `-is` word is read as a plural (`menus` → `PetMenu`, `emojis` → `PetEmoji`, at the price of `campus` → `PetCampu` — and so the `-us` a consonant + `-uses` plural gives is the one singular the rule writes that it reads as a plural again, `Bonuses` → `Bonus` → `Bonu`, which makes `cleanSchemaName` idempotent on every name but such a plural, as on every version before), and the suffix rules' other limits are the ones documented on `singularizePathSegment` (`gases` → `PetGase`, `lenses` → `PetLense`, `atlases` → `PetAtlase`, `niches` → `PetNich`, `quizzes` → `PetQuizze`, `diagnoses` → `PetDiagnose`; before #620 the two-branch rule happened to give `PetGas`, `PetLens`, `PetAtlas` and `PetNiche`). The same singular names a component by its leading word (`Licenses` → `License`, `Analyses` → `Analysis`, `Caches` → `Cache`; `cleanSchemaName`) — and so an inline body named from an `operationId` or from a `components/responses` key, which go through `cleanSchemaName` too (`operationId: casesCreate` → `CaseCreateRequest` / `CaseCreateResponse`; a component response `Boxes` → `BoxResponse`) — a nested error body's array items (`ErrorBodyCauseWithReason` for `{ message, causes?: [{ reason }] }`; see Shared error bodies) and the items a pagination `dataPath` hint ends in (`result.responses` → `ListPetsResultResponse`). The qualified name is `<Parent><Field>`, the field PascalCased and its trailing word singularized, the parent's `ListItem` marker stripped first (`Connection` + `domains` → `ConnectionDomain`; `ConnectionListItem` + `domains` → `ConnectionDomain`) — unless the field's name already starts with the parent's and adds something after it, when it stands as it is (`Pet` + `petOwner` → `PetOwner`, never `PetPetOwner`; `Pet` + `pets_item` → `PetsItem`). A field named exactly like its parent adds nothing and is qualified like any other, so it never takes the component's own name and never steps past it by number: `Reply` + `reply` → `ReplyReply`, the name `Reply` + `replies` gives its items on its own (beside each other, the field holds `ReplyReply` and the items step to `ReplyRepliesItem`, with no warning); `Pet` + `pet` → `PetPet`; `Reply` + `reply` + `reply` → `ReplyReplyReply`, every level kept (#621). It steps by number only as any qualified name does, when a component of that name holds another shape (`ReplyReply2`, with the rename warning; see Numbered names), and folds onto one that admits it. An inline enum under a parent is named by the same test (`inlineEnumName`: `Pet` + `status` → `PetStatus`; `Connection` + `connectionType` → `ConnectionType`; `Reply` + `reply` → `ReplyReply`, never `Reply`, which would push the component off its own name), as is every other inline name minted under a parent — the base of a `oneOf`'s inline variants (`ReplyReply`, `ReplyReplyWithN`), a merged `allOf` (`ReplyReply`), an array's items (`Pet` + `pet` → `PetPet`) or a map's values, and a field of a response named from its `object` const (`Reply` + `reply` → `ReplyReply`, never the response itself), of a webhook payload (`ReplyCreatedPayload` + `replyCreatedPayload` → `ReplyCreatedPayloadReplyCreatedPayload`) or of a shared error body (`ErrorBody` + `errorBody` → `ErrorBodyErrorBody`). The items of an array primary success body (`Operation.response`: `type: 'array'` or bare `items`, nullable in any spelling or not; a secondary media type's, fallback or error body keeps its own name, `ListPetsApplicationVndPetJsonResponse`, `ListPetsError409`) and of a list envelope's data array are typed as a field named `<Op>Item` — the `Response` suffix replaced with `Item` — under no parent, whatever their shape, so every model they reference is created under the name the reference uses: a plain object is `ListPetsItem`; a nullable object is `nullable<ListPetsItem>`; the inline object variants of a `oneOf`/`anyOf` take the union's names from it (`ListPetsItem`, `ListPetsItemWithSide`, `CircleListPetsItem`); an inline enum is `ListPetsItem`; the objects of a nested array or map, and anything under any of these, are qualified under it (`ListPetsItemOwner`); a `$ref` stays the reference and mints nothing. The names are settled against the spec-wide registry of model shapes as the operation is read (see Response Headers): when a name the items mint — `<Op>Item` itself, a union variant, a nested object — already belongs to another shape, a component model or enum (`ListShapesItem { id }`), a component's field model or an earlier operation's model, the items are retried as `<Op>ResponseItem` (`ListShapesResponseItem`, `ListShapesResponseItemWithSide`), then `<Op>Item2`, `<Op>Item3`, …, the first candidate that clashes with nothing; items identical to a name's owner share it and mint nothing, so an array of `{ name }` beside a component `ListPetsItem { name }` references the component. A request body or parameter that is an array is typed as the body or parameter itself, so its inline object items are `CreatePetsRequest` and `PetsFilter`, not `…Item`.

If two inline models still resolve to the same name with different fields or field types (two `operationId`s that PascalCase to the same word, for example), the parser keeps the one with more fields — the first definition on a tie — and prints `[oagen] Warning: Inline model "…" has more than one definition with different fields or field types`. Two kinds of same-named model are never settled that way. One is a model whose own field or variant references a model the merge passes renamed — a parent whose nested object left a shared name, in this pass or an earlier one (`InlineModelNaming.minted`; a reference the site minted, never an explicit `$ref` or one an `allOf` merge copied from another component's field). Its shape is its site's own, so it leaves the shared name the way a model a component does not admit does — clustered by shape with the others like it, each cluster qualified by its first site — and the merge passes say so: `[oagen] Renamed inline model "Widget" → "GetBWidget": it references a renamed model and "Widget" keeps another definition`. Folded by name onto the first definition, it would leave the renamed child referenced by nothing; kept as the larger definition, it would hand every other operation sharing the name the deprecated child the passes had just kept off it. The other is a model the parser would drop that way although it references a model of its own the kept definition does not — one its site minted, never a component or a model an earlier pass decided, which nothing drops: `getA`'s `Note { owner: NoteOwner }` beside `getC`'s larger `Note { holder: NoteHolder, extra }`, or `getC`'s `Note { owner: NoteOwner }` beside a `Note` declared first whose `owner` is a `$ref` to a component. Dropped, it would leave that nested model referenced by nothing, so it leaves the shared name the same way, and the merge passes say so: `[oagen] Renamed inline model "Note" → "GetANote": it references a model the definition kept under "Note" does not`. Its nested models are decided first, so when one of them leaves its own name this way, the model references a renamed model and leaves by the first rule. The other models are settled as above; when every model of a name follows a rename, the first cluster keeps the name, as the first definition would; and a model under a name a rename minted — the leader of a cluster, which the other sites of the cluster reference — keeps it. The schema pass also lifts a component field's own object, array items or union variant into the models under the field extractor's name (`PetWidget` for `Pet.widget`); such a model is not a component, so it belongs to the field's site: the field extractor's copy of the same schema folds onto it when the fields are settled, and a rename of one of the field's nested models is repointed in it as in the copy, so `Pet.widget` keeps resolving to a `PetWidget` that references the renamed `PetWidgetOwner2`.

An inline model that resolves to a component schema's name — a request body or response named from its operation or pinned by an `object` const, a component field's object, a nested object, an array's items, a `oneOf` variant, a header, fallback, error or secondary-body model — shares the component only when the component admits it: the same field names; each field the same type, limits, default, access flags and `deprecated`; the component allowed to be looser on requiredness (a field the inline model requires may be optional on the component) and on the field type's own nullable wrapper (non-null on the inline model, `nullable<…>` on the component), never stricter; and the models' own limits, type parameters, variants and dispatch rules identical. The models' own `deprecated` is read apart from the shape: a live component admits an inline model of either flag — a deprecated one keeps its flag on the field, parameter, header or envelope field that wrote the schema, not on a second model of the same shape; a site with no node of its own carries none — a request body or response, an array's items, a `oneOf` variant, a webhook payload variant, an error or secondary body — so deprecating only the items of `Pet.owners` beside a live component of their shape leaves no trace in the IR and nothing for `oagen diff` to report, as deprecating one of two identical inline copies leaves none (two operations' copies, or one operation's `200` and `202`, #630) — and a deprecated component admits no inline model, live or deprecated: a live site never resolves to a deprecated component, and a deprecated inline model keeps the qualified name its live self takes, so writing `deprecated: true` on the inline model flips the flag on that model and renames nothing (#441). `getLegacyWidget`'s inline copy of a deprecated `Widget` is `GetLegacyWidgetWidget` while live and `GetLegacyWidgetWidget` (deprecated) once deprecated, and `oagen diff` reports the flip as one additive `model-modified GetLegacyWidgetWidget` with `deprecatedChanged: true`, in either direction — where folding the deprecated copy onto `Widget` swapped the operation's type and was reported as `model-removed` beside a breaking `responseChanged`. So an inline copy's name never depends on the copy's own flag; it depends on the component's: a live component takes its identical copies, of either flag, under its own name, and a deprecated component takes none. Two trade-offs follow. Deprecating a component moves every identical copy off it, whether the copies are deprecated in the same edit or already were: with `Pet` and `getLegacyPet`'s identical inline response both live, then both deprecated — or `Pet` alone deprecated while the copy already was — the copy goes from `Pet` to `GetLegacyPetPet`, which `oagen diff` reports as `model-added GetLegacyPetPet` beside a breaking `responseChanged` on `getLegacyPet` and the additive `model-modified Pet` flip, exit 2 in either direction (`model-removed` the other way), the retype deprecating `Pet` alone has always cost a live copy; two copies move together (`getLegacyPet` and `getOldPet` to one `GetLegacyPetPet`), and a `Note.pet` field deprecated together with its `NotePet` component moves to `NotePet2` with a breaking `field-type-changed`. No naming rule avoids it without a live site resolving to a deprecated model: under a deprecated `Pet` the live copy must be `GetLegacyPetPet`, and a deprecated copy can match only one of its two neighbours — its live self beside the deprecated `Pet`, or its fold under a live `Pet` — so one of the two flips retypes it, and the copy's own flip, the edit made on the copy's side, is the one kept additive. And a copy deprecated from the start beside a deprecated component is a second deprecated model of the shape (`Widget` and `GetLegacyWidgetWidget`, both deprecated) on a surface nothing live reaches, two such copies sharing the one qualified model as identical copies always do (below) — whatever their flags: the copies a deprecated component refuses are settled among themselves as the copies of a name with no owner are, clustered by shape with the model's own flag read apart, each cluster named by its first site in document order, the live definition kept while any member is live (a deprecated member folds onto it with the warning a deprecated copy folding onto its live twin gets) and the model deprecated only when every member is, so two identical `getLegacyWidget` and `getOldWidget` responses keep sharing `GetLegacyWidgetWidget` once either is deprecated, and `oagen diff` reports nothing for that flip (the response has no node of its own to carry the flag), as it reports nothing when one of two inline twins is deprecated — and the merge passes say so: `[oagen] Renamed inline model "Widget" → "GetLegacyWidgetWidget": "Widget" is deprecated and admits no copy`. The inline model is then dropped and its references resolve to the component. Otherwise the inline model takes a name qualified by its site — the stem the operation's request and response models are built from prefixed: the `operationId`'s, cleaned as its `…Request` model name is (`GetWidgetWidget` for a `getWidget` body pinned by `object: widget`; `UserListWidget` for a `users.list` body, beside its `UserListRequest`), or, for an operation without an `operationId`, the path stem (`PetsByIdLegacyWidgetGetWidget` for `GET /pets/{id}/legacy-widget`, beside its `PetsByIdLegacyWidgetGetResponse`), so the name depends on the `operationId` or on the method and path alone, never on the operation's name — neither the one `inferOperationName` derives nor what an `operationIdTransform` makes of the `operationId` — as a header or parameter model the shape registry qualifies by its operation does, by that stem or, when another operation's models are named from the same stem, by the `operationId` as written (see Response Headers); a numeric suffix when the name already starts with it (`GetPetResponse2` for the `getPet` body, `CreateNoteRequest2` for the `createNote` body, `PetsByPetIdGetResponse2` for the `GET /pets/{petId}` body, `PetsGetPetResponse2` for the `Pets_GetPet` body whatever an `operationIdTransform` names the operation); `PetOwner2` for a field object of `Pet`; the shape registry's own candidates for a header, fallback, error or secondary body (`ListPetsDefaultResponse2`) — and the merge passes say so: `[oagen] Renamed inline model "GetPetResponse" → "GetPetResponse2": its shape differs from component schema "GetPetResponse"`. A component is never replaced: every operation that `$ref`s it keeps the shape the document declares, whatever an inline model of the same name adds, and the component's `description`, `externalDocs` and `deprecated` stay its own. Nested models are decided before their parents, so a parent whose child was renamed references the renamed child and, no longer admitted by the component of its name, is renamed with it (`GetPetResponse2 { owner: GetPetResponseOwner2 }`). The components' own inline field models are settled first, before any operation or webhook is read, so every later comparison with a component — the shape registry's, the merges' — reads the component's children by their final names: when `GetPetResponse.owner` is an inline object and a component `GetPetResponseOwner` of another shape exists, the field object becomes `GetPetResponseOwner2` at once, and a `getPet` body whose `owner` `$ref`s `GetPetResponseOwner` is not admitted by the component and keeps the reference it declared, under `GetPetResponse2`; a reference an operation's or webhook's `allOf` merge copies from such a field is created under the settled name. The settle also leaves one definition per name among the field models — the one the field merge would keep, the most fields or the first declared, with its warning — so a name the response merge meets is held by the model that survives: `Foo.barThings` and `FooBar.things`, maps whose values both mint `FooBarThing`, settle to the first's model at once, and a response of the second's shape is measured against that model, not against a definition the field merge then drops. The settled field models then own their names in the response merge as the components do, as they do in the shape registry: an operation's or webhook's inline model named like one (`getPetWidget`'s nested `owner` beside the `PetWidgetOwner` that `Pet.widget.owner` minted) folds onto it when it admits the shape and is qualified by its site otherwise, decided before its parent is compared with anything, so the parent never passes for a model of the field's name by the child's name alone, and the field's own model is never dropped for an operation's. One thing a field model does not do that a component does: hold its name against a live copy while deprecated. A live copy owns a shared name, so a deprecated field model yields it through its own site — `Pet.note.owner` written `deprecated: true` becomes `PetNoteOwner2` beside `getA`'s live `{ city }` owner, which keeps `PetNoteOwner` — while a deprecated component keeps its name and the live copy is qualified (`GetAPetNoteOwner`). And one thing it does that a deprecated component does not: admit a deprecated copy while deprecated. The object the schema pass lifts from a component's field is the owner the field extractor's own copy of that field folds onto when the fields are settled, so a deprecated field model admits a deprecated copy as it always did, where a deprecated component schema admits none (#441; `ownerFlagAdmits`, `InlineModelNaming.components`, `InlineModelOwner.fieldMinted`). A fold carries the folded copy's site into the winner's: the references the copy's site minted and the models minted beside it join the winner's site, so a later rename of the winner through its own site repoints them too — a field model folded onto while a `Pet` query enum `entry` of its name is not yet known (`PetEntry`, lifted only once the operations are read) still carries `getEntry`'s response with it when the field merge moves it to `PetEntry2`, and `Pet.entries` and `getEntry` resolve to one model named off the enum. A component is never renamed, so nothing is carried onto one. A webhook's models have a site of their own, qualified by the webhook's stem (`PetAdoptedComp` for a payload variant titled like a component of another shape). A rename repoints every reference kind alike (`renameTypeRefModels`): each entry of a union's `discriminator.mapping` follows the variant it belongs to, in a field, a response, a payload or a header — a name one variant carries owns every entry naming it, and a name several variants carry hands the j-th entry to the j-th such variant, so beside a `$ref` to `Comp` (`kind: legacy`) an inline variant titled `Comp` (`kind: new`) renamed to `ThingComp` leaves `{ legacy: 'Comp', new: 'ThingComp' }`. What the SDK sends shares a component's name only on an identical shape, the models' own `deprecated` read apart as above (a deprecated `createNote` body identical to a live `CreateNoteRequest` resolves to it) — an operation's request body, primary or secondary, an inline parameter, and a component field's object when every site that reaches the component, directly or through other components, is one of those two, each read as the parser reads it (a parameter by the one schema that types it — its `schema`, else the `content` entry the parser picks — so one typed as a string reaches nothing, a Path Item parameter not at all when the operation overrides it, and neither an `Accept`, `Content-Type` or `Authorization` header, which OpenAPI says to ignore, nor a webhook's `path` parameter, which is dropped, since nothing types them; a response by the key it is declared under, as the operation reader classifies it (`classifyResponseKey`, see Default and Range Responses above): its body and headers under a 200–599 status code, `default` or a `1XX`–`5XX` range, the first of two range keys that differ in case alone, and nothing under a 1xx status code, which the reader keeps as written and types nothing of, an `x-` key, or a key OpenAPI does not define (`600`, `6XX`), which is warned about and ignored — a `103` on `listNotes` with an `X-Pet` header or a body of `$ref: Pet` leaves `Pet` only sent, as the document without it does, while a `1XX` range with the same header receives it; a response body by the media types whose schema the reader reads (`responseBodyReading`, see Response Content Types above): every one but `application/octet-stream`, `application/pdf`, `text/plain`, `text/html`, `text/xml` and `application/xml`, which it types as a binary string or a string without reading the schema, at a 2xx, 3xx, error, `default` or range entry alike, so a `listNotes` `200` of `$ref: Pet` under `application/xml`, `text/plain` or `application/octet-stream` alone — or under `application/xml` beside a `201` whose `application/json` is `{ type: string }` — leaves `Pet` only sent and `Pet.owner` `PetOwner2`, as the document without it does, while a body under `application/json`, `application/yaml` or `*/*` receives it (#610); a request body by every media type that declares a schema, since each is typed through it, as `requestBody` or in `requestBodyContents` — so a `postNote` body of `$ref: Pet` under `application/xml` alone, which nothing reads as `requestBody`, still sends `Pet`, and a webhook's or a callback's under it receives it; a response header likewise by the one schema that types it, the later of two keys that differ in case alone (see Response Headers above), and one named `Content-Type`, which OpenAPI says to ignore, not at all, whatever its case or what its `$ref` leads to — a `Content-Type` header of `$ref: Pet` on `createPet`'s `204` leaves `Pet` only sent, so `Pet.owner` requiring `name` is `PetOwner2` beside a `PetOwner` that does not, as it is without the header, while an `X-Rate-Limit` header of `$ref: Pet` receives `Pet` and `Pet.owner` shares `PetOwner`; `sentOnlyComponentNames`), are never typed as a looser component, since a caller could then leave out what the operation requires (`CreateNoteRequest2` for a `createNote` body requiring `title` beside a component that does not, and `PetOwner2` for a `Pet.owner` requiring `name` beside a `PetOwner` that does not when only `createPet` sends `Pet`, as `CreatePetRequestOwner2` is for the same body written inline) — while what it receives (a response body or header, a webhook's payload or parameter) and every other component field's object — one a response, a header or a webhook reaches, or one no site reaches, whose direction the document does not say — share a component that admits them. Identical inline models that must leave a component's name share one model under the first site's qualified name (`GetAWidgetWidget` for the `object: widget` bodies of `getAWidget` and `getBWidget` beside a component `Widget` of another shape; the note says how many sites share it), as they would share the bare name without the component. That holds whatever moves the copies off the name — a shape the component does not admit, a copy of either flag beside a deprecated component (see Deprecation), an enum holding the name (below), a renamed child, or a nested model the kept definition does not reference (above): the copies are clustered by shape in document order, and each cluster takes one name; a copy of another shape takes a name of its own beside it. The copies a component does not share are clustered with the model's own `deprecated` read apart (above: a live `getLegacyPet` copy and a deprecated `getOldPet` copy beside a deprecated `Pet` are one live `GetLegacyPetPet`); the copies an enum's name or a renamed child moves are clustered with it included, so there a deprecated copy and a live one never share a model. It holds whichever pass moves a copy, too: the component fields are settled first, so a component field's copy that leaves a name has its model before any operation or webhook is read, and an operation's or webhook's identical copy that must leave the same name joins that model rather than taking another, its note counting every site that shares the model by then — the deprecated `address` objects of `Pet.owner` and of a `getOwner` body of the same `object: pet_owner` shape, beside a live `PetOwnerAddress` of another shape, are one `PetOwnerAddress2`, and `getOwner`, identical to `Pet.owner` once more, is typed `PetOwner`, as it is without the component; a deprecated copy identical to a field model that yielded the name to a live copy (above) joins it the same way. The first site is the first in document order among the copies that leave the name, a component field's ahead of any operation's (the leader `renameClusters` picks), so an operation added, removed or moved ahead of the others renames the model they share — `getAncientWidget` declared above `getLegacyWidget` and `getOldWidget` turns their `GetLegacyWidgetWidget` into `GetAncientWidgetWidget`, and swapping the two paths turns it into `GetOldWidgetWidget` — and `oagen diff` reports the old name removed and the new one added, a breaking change the copies' own names would not have shown. A model the parser could not rename — none the parser produces; a direct caller of the merge passes that gives no site — is dropped in favour of the component, with a warning.

An inline model never keeps a name an enum holds, whatever its shape or flag — an enum admits no model — so the model is always the one that steps, wherever the enum sits: a component enum, an inline enum lifted from a component schema's own fields, union variants or array items, or an inline enum an operation or webhook carries (a parameter's, a body's, a header's, one nested in a model). A request body or primary response named from its operation, a model nested under one, a list-envelope companion and a component field's object take the qualified name described above through the merge passes, which check every enum name in play (`reservedNamesByKind`): `GetPetResponse2` for the `getPet` body beside a component enum `GetPetResponse`; `CreatePetRequest2` for the `createPet` body beside a component enum `CreatePetRequest`, or beside a `request` query enum of its own service under that name (a `request` parameter object beside that enum steps in the shape registry to `CreatePetListPetsRequest`, and the enum keeps the name in both cases); `GetPetResponseOwner2` for the `owner` object nested under the `getPet` body beside a component enum `GetPetResponseOwner`; `ListPetsListMetadata` for the companion a `list_metadata` field of `listPets` mints beside a component enum `ListMetadata`; `PetOwner2` for the `owner` object of `Pet` beside a component enum `PetOwner`, settled with the fields before any operation is read; and `PetStatus2` for the `status` object of `Pet` beside a `status` query enum `PetStatus` of a `pet` service, settled at the merges once the enum is known — a header that shared the object's model follows it to the new name. Identical copies that must leave the name share one model under the new one, as they share the bare name: two identical `getPet` bodies are one `GetPetResponse2`, two identical bodies pinned by `object: widget` beside a component enum `Widget` one `GetAWidget`. The passes say so: `[oagen] Renamed inline model "GetPetResponse" → "GetPetResponse2": enum "GetPetResponse" owns the name`, with `(shared by 2 sites)` when two do. A parameter model, a header and a fallback, error or secondary body step past every enum name in play as they are named in the shape registry instead (see Response Headers and ErrorResponse), the names of the bodies that are themselves enums reserved first, so the same holds there: an object `404` body is `GetPetError404Body` beside an enum `404` body of another operation under the same stem, declared before or after it. The one enum that steps instead is one the collectors lift after a model of its name no pass can rename — a component model (`PetsMode2` for a `mode` parameter enum beside a component model `PetsMode`; see Response Headers). A name both a component schema and a component enum hold is the document's own clash and is settled as a component schema's. A model named like an enum that the parser could not rename — only a direct caller's — is kept beside the enum, with a warning.

**Numbered names.** Every number a model or enum name takes to step past a taken name — the merge passes' (`GetPetResponse2`, `PetOwner2`), the shape registry's (`DocumentsXMeta2`, `GetPetError404Body2`), an inline enum's (`PetsMode2`), a union variant's position (`DrawingShape2`), a discriminated variant's (`CatEventCat2`), a webhook model's (`<Stem>QueryPayload2`) — is spelled as an operation name's number is (see Service & Operation): bare after a letter, and behind `No` after a digit, so that it cannot be read as part of the number the name ends with. A `tagV2` object of `Pet` beside a component `PetTagV2` of another shape is `PetTagV2No2`; a `sizeV2` enum of `Pet` beside a component enum `PetSizeV2` of other members is `PetSizeV2No2`; the `pet.v2` variant of a discriminated `PetEvent` beside a component `PetV2` of another shape is `PetV2No2`, its nested `owner` object `PetV2No2Owner` and the mapping naming it there; the `error404` object of a component `GetPet`, which leaves `GetPetError404` to the `getPet` 404 enum body, is `GetPetError404No2` — never `PetTagV22`, `PetSizeV22`, `PetV22` or `GetPetError4042`, which read as version 22 and as a 4042 error. The rule reads the name as it is cased, not as the document writes it: the shape registry and a webhook's parameters number the raw parameter or header name before it is PascalCased, and one that ends in a digit once the characters that are neither letters nor digits are dropped takes its number behind `No` too, so a `deepObject` query parameter `filter[v2]` (or `filter_v2_`) of `pets` whose every candidate before a number is taken is `PetsFilterV2No2`, a header `X-Meta-V2_` is `PetsXMetaV2No2`, and a webhook `note`'s query parameter `filter[v2]` moved past its header parameters `filter[v2]` and `query_filter[v2]` is `NoteQueryFilterV2No2` — exactly as `filterV2`, `X-Meta-V2` and `v2` give, never `PetsFilterV22`, `PetsXMetaV22` or `NoteQueryFilterV22`. The hash that sets a path-derived prefix or a webhook stem apart follows the same rule, so one that starts with a digit is set off from a name that ends in one (`PetsTop10No567B59GetResponse`, above; see Webhook).

**Inline `allOf`.** An inline schema composed with `allOf` is merged into one model by a single reading (`mergeAllOfMembers`), wherever it appears: a request body, a response body of every kind (primary, secondary media type, error, `default` and range), a response header, a webhook payload or parameter, a component or inline model's field, array items, map values, a union's `allOf` variant, and a field nested under a discriminated component variant. Members are read in document order. A `$ref` member contributes its component's properties (those of the component's own `allOf` chain included). A model built from an inline merge carries neither `bases` nor `inheritedFrom`: the two keys are a component model's (see `properties` beside a composition). A model built from the merge (`materializeMergedAllOf`: a field anywhere, a field nested under a discriminated component variant) types each inherited property as the component's model types it (`Base.meta` stays `BaseMeta`) and does not read into it again — the component being the one whose own model carries the field: an `allOf` component that inherits it, through a `$ref` or a nullable member, types everything reached inside its chain under its own name (`DogMeta`), while a bare alias (`Hop: { $ref: Base }`), a nullable alias (`Alias: { oneOf: [{ $ref: Base }, { type: 'null' }] }`) or a chain of either declares nothing of its own and builds no model, so a field reached through one is typed under the component that declares it (`Base.meta` is `BaseMeta` through `Alias`, never `AliasMeta`) — so a component that extends itself through a field (`Node.child: allOf: [{ $ref: Node }, …]`) is typed as the `NodeChild` that exists, and one whose inline member redeclares the inherited field (`Note.reply: allOf: [{ $ref: Note }, { properties: { quoted, reply: { properties: { depth } } } }]`) conjoins `Note.reply` with the inline `reply` into one declaration every merge of `Note` owns, built once: `NoteReply { id, reply, quoted }` re-enters it as `NoteReplyReply { id, reply, quoted, depth }`, whose own `reply` is that same conjunction and is typed as `NoteReplyReply` itself rather than re-extracted without end — a typeless inline `reply: { description }`, an array `replies` whose items merge `Note` and redeclare `replies`, the same field nested under an inline object or a union variant, and two components that do this to each other (`Note.thread` merging `Thread` while `Thread.note` merges `Note`: each component's chain is built under its own name, whichever is declared first, so `NoteThread`, `NoteThreadNote`, `NoteThreadNoteThread` and `ThreadNote`, `ThreadNoteThread`, `ThreadNoteThreadNote` are the same six models in either order) end the same way (#566), and so does a field whose merge reaches itself through a union written beside the `allOf` — `Note.reply: { allOf: [{ depth }], oneOf: [{ $ref: Note }, { other }] }` is `NoteReply { depth, id, reply, other }`, as the union written as a member is — or through `properties` written beside it, since a schema folds to one object however often it is folded, which stands for the declaration it was spread from (`foldSiblingProperties`, `derivedCopy`; #398 review: every fold made a new copy, which no guard had seen, and the re-entry never ended); and so does each form under a nullable wrapper of any spelling, a single-member `allOf` wrapper, or a multi-type list (`type: ['object', 'string']`, each type read from a copy of its own): a merge is the declaration that carries its `allOf`, and a copy a reader spreads from one — a nullable wrapper stripped, sibling properties or a union beside the `allOf` folded, a wrapper's documentation or limits carried onto the branch it collapses to, a type list read one type at a time — stands for the declaration it was spread from (`sourceDeclaration`, recorded by `derivedCopy` at each such site), so a conjunction that keeps the wrapper — a typeless `reply: { description }` beside a nullable `Note.reply` annotates it without stripping it — is met once however often it is unwrapped, by the extractor and the type builder alike: `Note.reply: { type: 'object', nullable: true, allOf: [...] }` (or `type: ['object', 'null']`) gives the same three models with `reply` nullable at every level, nullable array items the same two models the plain typeless array form gives (`Note { id, replies }`, `NoteReply { id, replies }`, the item nullable), and the mutual pair the same six chain names; a `oneOf: [{ allOf: [...] }, { type: 'null' }]` or `allOf: [{ allOf: [...] }]` wrapper and the conjunction annotating it share the one branch or member that carries the `allOf`, so `NoteReply`'s own `reply` is `NoteReply` itself; under a multi-type list every type of `NoteReplyReply`'s own `reply` is `NoteReplyReply` (#596 review: the path was keyed by the copy each unwrap made, and never met the same one twice; the type builder read each type of a list from a copy that stood for nothing, and named a model the extractor never built); a primary response body types inherited properties under its own name. The merged model's `description`, link, `deprecated` and `x-*` keys are the wrapper layer's: the wrapper's own, else those of a member that declares no type (see Collapsed wrappers; #555 review), a typing member's staying on that member and a `$ref` member's on its component — at every site alike, a response body of every kind included: `{ allOf: [{ $ref: Base }, { properties: { name } }, { description: 'A pet.', deprecated: true }] }` as the `201` body of `createPet` is a deprecated `CreatePetResponse` described "A pet.", exactly as it is as the request body (`CreatePetRequest`) or with the two keys written beside the `allOf`, while the Response Object's own `description` stays `Operation.responseDescription` and never reaches the model (#604: the primary and further success bodies were rebuilt without the text, so `CreatePetResponse` had none while `CreatePetRequest`, a secondary media type's body, an error body and a fallback body kept theirs). A discriminated component variant's model is built as any inline object's is — its fields by the field extractor under the variant's name — so every shape under it (a nested object, typed or not; array items and map values of any shape; a union and its members; an `allOf` merge; an inline enum) is materialized under the name its type uses, and typing and extraction cannot disagree there. A ref no component schema answers contributes nothing (a response whose only `$ref` is unanswered is typed as that reference). A `oneOf`/`anyOf` member with exactly one non-null variant beside `null` is a nullable wrapper, not a union — decided by `nullableUnionBranch`, the definition `unwrapNullableSchema` collapses by, per keyword: a member writing a nullable `oneOf` beside an `anyOf` (`{ oneOf: [{ a }, { type: 'null' }], anyOf: [{ b }, { c }] }`) is `a` as one more member with `b` and `c` flattened, `{ name, a?, b?, c? }`, exactly as the two keywords written as two members or beside the `allOf` are read (#398 review: the member was read by one keyword, so it gave `{ name, a? }` where the other spellings gave all four) — and applies as that variant wherever the member sits, a `$ref` member's component included: its `$ref` is followed, its `required` read and its properties always-applying, for the inline merge, for a component's `allOf` model (`readComponentAllOfMember`) and for a list envelope's companions (`collectObjectProperties`) alike, so `allOf: [{ oneOf: [{ $ref: Base }, { type: 'null' }] }, { properties: { data } }]` carries `Base`'s fields beside `data` (#308). An inline member contributes its own properties, those of its nested `allOf` members and — for each `oneOf`/`anyOf` it carries with more than one non-null variant, a member writing both keywords carrying two — those of every variant, read as the component reader reads a flattened variant (`declareVariant`): through the variant's own `allOf` members, the unions nested in it however deep, and a `$ref`, the variant itself or one met under it, to the component it names, whose own properties, `allOf` chain and unions are read the same way — as optional fields, one declaration per name per variant: what always applies within the variant (its own properties, its `allOf` members', a `$ref`'s component's) is conjoined as any merge conjoins it (`combineDeclarations`), so a variant `{ allOf: [{ properties: { value: { type: 'string' } } }, { properties: { value: { description: 'doc' } } }] }` declares one described `value: string` (#398 review: each member's was a branch of its own, and the field was `value?: string | unknown`), a component two variants name declared into each variant's conjunction (`{ allOf: [{ $ref: C }, { payload: { b } }] }` beside `{ allOf: [{ $ref: C }, { payload: { c } }] }`, `C.payload { a }`, is `payload: { a, b } | { a, c }`; the guard against a component naming itself under a variant was shared across the variants, and the second read `{ c }` alone), and only the unions nested in the variant make alternatives, each nested branch read as a conjunction of its own the same way and settled before it joins (`{ oneOf: [{ allOf: [{ $ref: C }, { payload: { b } }] }, { allOf: [{ $ref: C }, { payload: { c } }] }] }` nested in a variant is `payload: { a, b } | { a, c }` too; review round 4: the nested branches were read into the variant's ledger as one more set of alternatives, `{ a } | { b } | { c }`, sharing its guard), the path above a nested branch still ending a component that names itself under it: `allOf: [{ properties: { name }, required: [name] }, { oneOf: [{ properties: { ownerId } }, { properties: { shelterId } }] }]` is `{ name, ownerId?, shelterId? }` inline exactly as it is as a component, and so is `{ oneOf: [{ $ref: Owner }, { $ref: Shelter }] }` in the union's place (#398: a `$ref` variant was left to its component, and only the `oneOf` of a member writing both keywords was read). A union written beside an `allOf` that types the schema is one more member, the last, so `{ allOf: [base], oneOf: [...] }` is read as `allOf: [base, { oneOf: [...] }]` is, at every site (#398: the `allOf` was read alone, and a request body read the union alone); beside an `allOf` whose members only annotate or limit the schema, the union is what types it and is read alone, the members part of the wrapper, inline and as a component alike — a named union of its variants, or, for a union of string consts, the enum it is inline (`Kind: { allOf: [{ description: 'A kind.' }], oneOf: [{ const: 'cat' }, { const: 'dog' }] }` is the enum `Kind`; see Enum) (#613; see Named unions and Collapsed wrappers). A variant's `required` list is not read, since its properties are present only on that branch. A union a `$ref` member's component carries is read as that component's own model reads it (#429): flattened into the merge when the model flattens it — `Dog: { allOf: [{ $ref: Pet }], properties: { breed } }` inline carries `Pet`'s `ownerId?` and `shelterId?` as `Pet`'s and `Dog`'s component models do — and left to the component when its model dispatches it (its variants pin a const, or the document declares a `discriminator` on the union or on the `allOf` wrapper around it — carried through a nullable wrapper around the union onto its one variant, as the component reader carries it — the `allOf` wrapper's, and the member's own written on the nullable wrapper (`{ oneOf: [{ oneOf: [{ $ref: Cat }, { $ref: Dog }] }, { type: 'null' }], discriminator: { propertyName: kind, mapping } }`), by the component reader, the variant builder, the inline merge and the pagination walk alike; review round 6: the member's own was dropped at the wrapper, and the union flattened where the mapping dispatches it — so `{ oneOf: [{ oneOf: [{ $ref: Cat }, { $ref: Dog }] }, { type: 'null' }] }` beside a mapping on `Pet` is left to `Pet` inline as it is as a component; review round 5: the merge dropped it when it followed the wrapper, and flattened the fields the component leaves out), so the merge carries the base fields the dispatcher model carries and no variant's; an inline member's union is always flattened, since an inline `allOf` never dispatches. A property keeps the first always-applying declaration that declares a type, a typeless one before or after it only annotating it — two typing inline objects conjoin their properties and `required`, any two declarations that each describe an object — an inline object, a `$ref` to an object component, an `allOf` that reaches one — conjoin as the `allOf` of both (`result` is a `PetPage` that also has `total_pages`, its inherited fields typed as `PetPage` types them, whether `total_pages` is declared inline, under an `allOf` or by a second `$ref`; #432, #571), two typing arrays combine their `items` by this same rule, and a declaration conjoined from two components' is the merged model's own (`HolderValueResult`), since no component model nests the whole — whatever a variant says; a property only variants declare is typed as the union of its distinct declarations (the keywords the field reads from its own schema, below, ignored — at the declaration's top level and inside its array items and map values alike, since `ArrayType` and `MapType` carry none of them: `items: { type: string }` beside `items: { type: string, readOnly: true }`, or with `maxLength: 5` on the items, is one `string[]`, and two maps whose values differ so are one map): one shape is its first declaration, several shapes are a `oneOf` of them read as any inline union is — `kind: { const: cat }` beside `kind: { const: dog }` becomes an inline enum `<Model>Kind`, `const: true` beside `const: false` a union of literals, two inline objects a union of two variant models — so a field is never typed from one variant's value alone. A field reads its flags, documentation and limits from its own schema, never from a union's variants, so the combined declaration — one shape's or a union's — carries every such keyword the declarations agree on, value for value — `readOnly`, `writeOnly`, `deprecated`, `description`, `default`, `example`, `examples`, `externalDocs` and the validation keywords: two `kind` declarations both `readOnly: true` with different consts make a read-only enum field; a keyword the declarations disagree on, or only some declare, is not the field's, nor a second shape: `kind: { type: string, description: A }` beside `kind: { type: string, readOnly: true }` is a `string` field with neither (#397). A `null` any declaration admits (`nullable: true` or a `type` list naming it) is a value the property takes on that branch, so the combined declaration admits it (`nullable<enum>`, `nullable<union>`). The declarations themselves are kept as written inside the union, so an enum member or a variant model still carries its own description and limits — except `deprecated`, which a shape keeps only when every declaration of the shape has it, at the top level and inside array items and map values alike: one live declaration makes a live variant model or enum member whichever declaration comes first, so `[{ object, deprecated: true }, { object }, { integer }]` and its swapped order are one live `<Model>Kind` beside `integer`, `{ const: cat, deprecated: true }` beside `{ const: cat }` and `{ const: dog }` a live `CAT`, and `diffSpecs` between the orders reports nothing. A schema reached twice is read once in each capacity it is reached in — as an inline member (every union flattened), through a `$ref` member (a union its component dispatches left to the component) or under a variant — and only an inline reading stands for the others: an object shared between a variant and a member (a YAML anchor, an object a `transformSpec` hook reuses, a `$ref` written twice) still contributes its `required`, and is still followed, when the member is reached; a component's own object reused as an inline member (`allOf: [{ $ref: Shared }, Shared]`) still has a dispatched union flattened after the `$ref` reading left it to the component. An inline `allOf` is always flattened: the dispatcher form — a `discriminator` whose mapping names one model per variant — is built for component schemas only. How an inline `allOf` is read is one decision made everywhere — by the type builder, the name predictor, both extractors and the primary response body path (`readInlineAllOf`) — so a model is built exactly when a reference names it: a `$ref` member beside an inline object member (`type: 'object'`, or properties declared inline — its own, a nested `allOf` member's or a `oneOf`/`anyOf` variant's, a `$ref` variant of a union of two or more variants included, since the merge flattens its component in: `declaresInlineProperties`), or several inline members one of which declares properties, is the merged model `<Parent><Field>` (`allOf: [{ $ref: Base }, { oneOf: [...] }]` carries `Base`'s fields and the variants', not a bare reference to `Base`, the variants `$ref`s or not); a single non-`$ref` member with nothing beside it that adds to it is unwrapped and read as the field or body itself, the wrapper's limits, `deprecated` and link carried onto it (a `required` the wrapper writes beside a lone member that declares properties adds to it, so `{ allOf: [{ properties: { name } }], required: [name] }` is the merged model with `name` required; beside a lone array, primitive or enum member `required` constrains nothing and the member is unwrapped) — and so is the one member that declares a type when every other member declares none and only annotates or limits it (`allOfTypingMember`; a member that declares no type is part of the wrapper, see Collapsed wrappers), so `kind: { allOf: [{ type: 'string', enum: ['cat', 'dog'] }, { description: 'The kind of pet.' }] }` is the inline enum `PetKind` documented "The kind of pet.", `name: { allOf: [{ type: 'string' }, { description }] }` a described `string`, `id: { allOf: [{ oneOf: [{ $ref: PetId }, { type: 'null' }] }, { description }] }` a described nullable `string` with `PetId`'s limits, and `{ allOf: [{ type: 'string' }, { maxLength: 3 }] }` a `string` limited to 3 — each exactly as the lone-member spelling with the same keywords on the wrapper (#555: these were `unknown`, the text lost with them) — and `owners: { allOf: [{ type: 'array', items: { $ref: Owner } }, { items: { description: 'An owner.' } }] }` an `Owner[]` whose items the second member documents, since `items` that declare no type themselves declare none for the member either (`declaresType`; the #555 review); two members that each declare a type, neither of them properties — two primitives, say, or an array beside `{ items: { type: 'string' } }` — are read as neither, and such a schema is typed from its own keywords (an `allOf` of bare limits beside the schema's own `type` likewise); a single `$ref` member with nothing beside it that adds to the component (`allOf: [{ $ref: Base }]`, `allOf: [{ $ref: Base }, { description }]`, `allOf: [{ $ref: Base }, { maxItems: 10 }]`) is a reference to that component, and nothing is minted — a component the document declares under the nested name is never replaced by an unused merged copy, and a response body written so is `Base`, not a copy of `Base` under the operation's name. A second `$ref` member, or a `required` list beside the `$ref` — the schema's own, or a member's — adds to the component, so `allOf: [{ $ref: Pet }, { $ref: Owner }]` and `allOf: [{ $ref: Pet }], required: [name]` are the merged model (`<Parent><Field>`, `<Op>Response`), carrying every component's properties and every `required`, at every site alike. A `required` adds to the component only when the component declares properties the merge reads — its own, or its `allOf` chain's: JSON Schema applies `required` to an object instance only, so beside a `$ref` to an array, a primitive, an enum or a union component it constrains nothing, and the reference stands (`{ allOf: [{ $ref: Pets }], required: [name] }` with `Pets` an array component is `Pet[]`, as `{ allOf: [{ $ref: Pets }] }` is). A merged model is built with whatever fields the merge yields: an empty `properties: {}` is an inline object with no fields, as it is as a plain field or a union variant, so `{ allOf: [{ oneOf: [{ type: 'object', properties: {} }] }, { description }] }` is a model with no fields rather than a reference nothing creates — documented by the member, which declares no type and so is part of the wrapper (see Collapsed wrappers).

### Field Examples

OpenAPI 3.1 deprecates a schema's `example` in favour of the JSON Schema `examples` list. The parser reads both: `examples` carries every value the document gives, and `example` is the document's `example` when present, otherwise the first entry of `examples`. A field whose schema is a `$ref` to a component falls back to that component's `example`/`examples`, the same way a parameter does; when the component is an array or primitive component, each value is read from the nearest level the reference passes on its way to the array or primitive (the field schema, then an alias's own, else the component's), as `description` is (see Array components); when it is an alias of an enum component, from the aliases first, then the enum, as a bare `$ref` to the enum reads it (see Enum). A field whose schema (and the levels its `$ref` passes, if any) gives neither has no `example` and no `examples` key.

### Constraints

JSON Schema's validation keywords are carried on `Field`, `Parameter` and `Model`, and on every `primitive`, `literal`, `array`, `map` and `union` type the parser builds from a schema (see Type constraints), so an emitter can document a value's limits ("at most 100"), check a value before sending it, or keep a generated example within range. `type`, `enum`, `const` and `required` already have their own place in the IR and are not repeated here.

```typescript
interface Constraints {
  // numbers
  minimum?: number;
  maximum?: number;
  exclusiveMinimum?: number;
  exclusiveMaximum?: number;
  multipleOf?: number;
  // strings
  minLength?: number;
  maxLength?: number;
  pattern?: string; // ECMA-262 regex, verbatim from the document
  // arrays
  minItems?: number;
  maxItems?: number;
  uniqueItems?: boolean; // present only when true
  minContains?: number;
  maxContains?: number;
  // objects
  minProperties?: number;
  maxProperties?: number;
  dependentRequired?: Record<string, string[]>;
}
```

Every member is optional and present only when the document declares it. A schema with no validation keyword yields no `constraints` key at all, so `field.constraints?.maxLength` is the idiomatic read. The parser ignores a keyword whose value has the wrong type (a string `maxLength`, say) rather than carrying it. `oagen diff` compares the keywords on every node that carries them, the type's at every level included, and reports each one tightened or loosened — breaking when tightened on a request-facing site (#599; see **Constraints** under [`oagen diff`](../cli.md#oagen-diff)).

**OAS 3.0 → 3.1 normalization.** OpenAPI 3.1 (JSON Schema 2020-12) gives `exclusiveMinimum` / `exclusiveMaximum` as the bound itself; OpenAPI 3.0 spells them as booleans that make `minimum` / `maximum` exclusive. Both versions are parsed, and the IR always uses the 3.1 shape:

| Document (3.0)                             | IR                                         |
| ------------------------------------------ | ------------------------------------------ |
| `minimum: 0, exclusiveMinimum: true`       | `{ exclusiveMinimum: 0 }` (no `minimum`)   |
| `maximum: 100, exclusiveMaximum: true`     | `{ exclusiveMaximum: 100 }` (no `maximum`) |
| `minimum: 0, exclusiveMinimum: false`      | `{ minimum: 0 }`                           |
| `exclusiveMinimum: true` with no `minimum` | nothing                                    |

A 3.1 document's numeric form passes through unchanged, including the legal-but-unusual case of an inclusive and an exclusive bound on the same side.

**Scope.** The keywords declared on the field, parameter or model schema are collected, conjoined with those of its inline `allOf` members: the parser unwraps a single-member `allOf`, so `{ allOf: [{ type: string, maxLength: 3 }] }` is a string field carrying `{ maxLength: 3 }`, and a `$ref` member contributes the keywords written beside the reference while the referenced model keeps its own. Limits nested inside array `items` or map values (e.g. `items: { maxLength: 10 }`) are not the field's: they are carried on the items' or values' type (see Type constraints). The one exception is a nullable wrapper — a `oneOf`/`anyOf` with exactly one non-null, non-`$ref` branch, which the IR collapses to `nullable<T>` — whose branch keywords are conjoined with the wrapper's own (and its `allOf` members'), so `anyOf: [{ type: string, maxLength: 8 }, { type: "null" }]` gives `{ maxLength: 8 }` and `{ allOf: [{ maxLength: 30 }], anyOf: [{ type: string, minLength: 20 }, { type: "null" }] }` gives `{ maxLength: 30, minLength: 20 }`, and an inline model built from that branch carries the same conjoined keywords, so `minProperties` written beside `anyOf: [{ type: object, … }, { type: "null" }]` reaches both the field and its model. Limits written beside a general multi-variant union are the field's and the union type's; each variant's own are on that variant's type (see Type constraints). Keywords written beside a `$ref` (OpenAPI 3.1 allows them) are the field's own and are kept; a bare `$ref` to a model, named union or enum adds none of the target's, because its limits belong to the referenced node, while one to an array or primitive component, which has no model, conjoins the component's limits with the field's own (see Array components and Primitive components), and one to an alias of an enum component conjoins the alias's own, the enum's staying on the enum (see Enum). A `Model` carries whatever its own schema declares — for an object schema that is `minProperties`, `maxProperties` and `dependentRequired`; for an `allOf` model — a component, or an inline response, request body or field the parser rebuilds from `allOf` members — it is the wrapper's keywords conjoined with its members' (the stricter bound wins; a `$ref` member contributes the keywords written beside the reference, while the referenced model keeps its own). A variant model of a discriminated `allOf` + `oneOf` union conjoins the shared keywords — the outer wrapper's, the base members' and any written beside the `oneOf` — with the variant's own the way `allOf` does — an instance must satisfy both, so the larger `min*` and the smaller `max*` win and `dependentRequired` maps are unioned per property.

### Deprecation

`Model.deprecated` and `Enum.deprecated` are present, and `true`, only when the schema the type was built from says `deprecated: true` — the literal `true`; any other value (`"yes"`, `1`) is not a declaration; the key is absent otherwise, as on `Operation`, `Parameter`, `ResponseHeader` and `Field`, each of which reads the keyword from its own source by the same rule (listed at the end of this section). Which schema that is, per model:

- A component schema: its own top-level keyword. For an `allOf` component it is the wrapper's; a member's flag is not read — a `$ref` member's stays on the referenced model, so `Composed: { allOf: [{ $ref: Legacy }, …] }` is live while `Legacy` is deprecated, and an inline member's is dropped, as `Field.deprecated` drops it on a field.
- A discriminated `allOf` + `oneOf` union: the wrapper deprecates the dispatcher model; each variant model carries its own variant's flag.
- An inline object that becomes a model — a request body, a `oneOf` body variant (a discriminated body takes the wrapper's flag, since the variants merge into one model), a response (an `allOf` response takes the wrapper's flag), a nested field object, array items, map values, a field's `oneOf` variant — carries that schema's flag. A multi-variant union is never collapsed, nullable or not (`type: ['object', 'null']` beside a `oneOf` included): each variant model is built from its variant, with the variant's own flag, and the wrapper's flag stays on the field. A field spelled `{ deprecated: true, anyOf: [{ type: object, … }, { type: "null" }] }` or `{ deprecated: true, allOf: […] }` carries its wrapper's flag onto the model built from the branch or the merge, the same way its `constraints` travel, so the nullable and composed forms match the direct-object form — and only the wrapper's: a flag written on the null-wrapped branch or on an `allOf` member is not read, exactly as `Field.deprecated` does not read it.
- A `<Name>Json` model folded into `<Name>` does not carry its flag over: deprecation names the type the SDK exposes, and `<Name>` keeps its own. A live `<Name>Json` is never folded onto a deprecated `<Name>` — every live reference to it would then resolve to a deprecated type — so both models stay, and the parser says so.

An inline enum (one declared on a field, parameter or header rather than under `components.schemas`) carries no flag of its own: the IR reaches it through an `EnumRef`, and the field or parameter that declares it carries `deprecated`.

Wherever two inline models are folded into one by structural agreement — list-envelope companions sharing a bare name, header models and array items sharing a registry entry, same-named inline models in the merge passes — `deprecated` is part of the shape, and a deprecated copy never shares a live inline model's name except as the merge passes fold a copy identical but for the flag (below) and as one operation's success bodies share a model (below; see Success Responses); a model the document declares — a component schema, or a model a component's field minted — reads the flag apart from its shape (see Models), so a deprecated copy a live one admits shares it. An envelope companion keeps its operation-qualified name (`ListLegacyUsersListMetadata`) while the live copies share the majority name — beside a live component that admits it, its nested models agreeing on the flag, a deprecated companion shares the component, with the warning below, and its envelope field keeps the flag, while beside a deprecated component no companion shares it, so its name is the same under either flag (#441) — and a header model gets a qualified name of its own. A site that shared a model rather than minting it — a `default` body or header matching a primary body's model, an array body's items matching a component field's model or an earlier operation's — has its references attached to the owner's site, so when the merge renames the owner (a deprecated `Circle` variant two arrays share, once a live `Circle` of other fields appears) every sharing response, header and array is repointed with it. A reference a header, secondary-body, fallback-body or error-body schema wrote by sharing a primary body's or a companion's model (its shape matched the name's owner) belongs to that model's site too, so renaming the model repoints the `default` response or header along with the site's own references. Within one operation, two success bodies that resolve to one name — pinned by the same `object` const, or a later body settled on an earlier later body's stem (`CreatePetResponse201`, see Success Responses) — are reconciled before the merge passes see them (`extractResponses`), by the rule the merge passes apply: the model's own `deprecated` read apart (`shapeFingerprint`), the primary's definition is kept — its references with it, so a `200` whose `owner` is `$ref: PetOwner` keeps naming the component when the `202` nests an inline `owner` of the same name, which the merge passes rename apart — the shared model is live while any copy is, and its `description`, `externalDocs` and extensions are the first live copy's in status order, as the merge passes keep a live copy's definition across operations: a deprecated `200` described `Old pet.` beside a live `202` described `A pet.` gives a live `Pet` described `A pet.`, carrying the `202`'s `externalDocs`, and a live `202` with neither gives a `Pet` with neither, so a description written for the deprecated copy never documents a model that is not; with no warning. With a `200` and a `202` both returning an inline `{ object: 'pet', name }`, writing `deprecated: true` on the `200` body alone leaves one live `Pet` that both status codes return, as writing it on the `202` alone does, and as declaring the `202` above the `200` does; `oagen diff` reports nothing for either edit, in either direction (exit 0), and `Pet` is deprecated only when every body's copy is (#630) — the same copies on `getPet` and `getLegacyPet` share the live `Pet` the same way, with the warning below. A copy that differs in a field as well — one more field, a field's own `deprecated` (a nested object's flag sits on the field that wrote it, so a `PetOwner` deprecated on the `200` only is one live `PetOwner` under a `Pet.owner` the `200` flags), a limit — is resolved to the primary's definition under the existing warning (`Inline model "Pet" from the 202 response has different fields than the 200 response's — using the 200 response's`), the flag with it. In the merge passes, a live copy owns a shared name: when a deprecated inline model and a live one would resolve to the same name — two inline responses pinned by the same `object` const, an inline request body or a component field's object named like another — the deprecated copy is folded onto the live definition only when it is identical to every live copy of that name in everything but the flag (fields, requiredness, types, limits, defaults), with a warning; a copy that differs in anything else, requiredness included, keeps its own model under a qualified name — the stem its operation's models are named from prefixed: the `operationId`'s, cleaned as its `…Request` model name is (`GetLegacyWidgetWidget`; `UserListWidget` for `users.list`, never its name `usersList`), or the path stem of an operation without an `operationId` (`PetsByIdLegacyWidgetGetWidget`, never the derived `getPetLegacyWidget`), or, when the name already starts with it, as a request body named from its operation does, a numeric suffix (`CreateNoteRequest2`); a component field's object likewise takes a suffix (`PetOwner2`) — minted against every model and enum name in the document (inline enums the collectors lift later included); identical copies that must leave the name share one such model under the first site's qualified name, the note saying how many sites share it (`PetOwnerAddress2` for the deprecated `address` objects of `Pet.owner` and of a deprecated `PetOwner` component beside a live `PetOwnerAddress` of another shape, `GetLegacyWidgetWidget` for identical deprecated `object: widget` responses of `getLegacyWidget` and `getOldWidget` beside a live `Widget` that does not admit them), and a copy of another shape takes a name of its own beside it; and only the references minted for each copy are repointed — by identity, never by name: an explicit `$ref` to a same-named component stays as written even in the same response map, a reference an `allOf` merge copied from another component's field follows that field's model, and nested models are named before their parents, so a parent whose child was just renamed is no longer "identical but for the flag" to its live twin — and, referencing a renamed model, leaves the shared name by its site rather than by the choice between live twins (see Models: `GetBWidget { owner: GetBWidgetOwner }` beside the `Widget` the other operation keeps), so the renamed child is never left referenced by nothing. A component's name and flag are authoritative: an inline model of either flag named like a deprecated component — an inline response, a request body, a field object, array items, a `oneOf` variant, a header, parameter, error or secondary-body model, a list-envelope companion — takes a qualified name the same way, whatever its shape: a live one so that no live field resolves to a deprecated component (`Pet.owner` → `PetOwner2` beside a deprecated `PetOwner`), and a deprecated one so that it keeps the name its live self took (`PetOwner2`, deprecated, once `Pet.owner` is written `deprecated: true`; `GetLegacyWidgetWidget` for a `getLegacyWidget` response identical to a deprecated `Widget`, live or deprecated), since a deprecated component admits no copy (#441, see Models) — so deprecating or undeprecating the copy is the flag flip below, never a move between the qualified model and the component; a deprecated inline model named like a live component shares the component when the component admits its shape, the flag read apart (see Models) — `Pet.owner` written `deprecated: true` resolves to a live `PetOwner` of the same shape and the field keeps its flag, a deprecated `getLegacyWidget` response identical to a live `Widget` resolves to `Widget`, a deprecated `createNote` body identical to a live `CreateNoteRequest` resolves to it — with the warning two inline copies get when the two are the same shape, and otherwise one naming what the looser component no longer requires (`[oagen] Warning: Inline model "PetOwner" is declared both deprecated and live, with a looser live definition that does not require "name" — keeping the live definition under the shared name` for a deprecated `Pet.owner` requiring `name` when a response returns `Pet`; a type the copy leaves non-null that the component makes nullable reads `allows null in "id"`, and a list-envelope companion's looser nested model or enum `loosens "cursor"`), and takes a qualified name otherwise (a deprecated `Pet.owner` of a `Pet` only sent is `PetOwner2`, see Models). An inline model named like a component of its own flag shares the component when the component admits its shape and takes a qualified name otherwise (see Models); the component's fields, `deprecated`, `description` and `externalDocs` are never replaced. So two things never depend on document order: whether a reference reaches a deprecated model — only where the document itself wrote `deprecated: true`, on the component or on that very operation's or field's own schema, never because of folding — and the name a deprecated copy takes: the shared name when it is identical but for the flag to every live copy of that name, or when a live component admits it, its own qualified name otherwise (when the live copies disagree among themselves, the deprecated copy is always qualified; beside a deprecated component, every copy is). A third thing does not depend on the copy's own flag: the name of an inline model beside a deprecated component, which is the same qualified name live or deprecated — and the name the copies the component refuses share, which is their first site's whatever that site's flag, the model live while any of them is and deprecated only when every one is, so flipping one copy's flag never changes any copy's type (#441). What follows document order is which live definition a shared name carries when the live copies disagree — the first declared, or the one with more fields — and, for a list-envelope companion several operations share, which of them qualifies it (the operation the envelope pass made its owner: the first declared of the most common shape).

**Source per node.** Each node reads `deprecated` from one place: `Operation` from the Operation Object's own keyword; `Parameter` from any of the Parameter Object (after a `components.parameters` `$ref` is resolved), its inline `schema` and the component schema its `schema.$ref` points at — deprecated when any of the three says `deprecated: true`, so a `false` on one level does not stop a `true` on another; `ResponseHeader` from either of the Header Object (after a `components/headers` `$ref` is resolved) and the schema that types it — its `schema`, or the `content` entry's read in its place, a keyword written beside a `$ref` or on an `allOf` member that declares no type of its own included (`allOfWrapperLayer`; see Collapsed wrappers), as the header's `externalDocs` reads them — deprecated when either says `deprecated: true`, so a deprecated header schema that folds onto a live component (see Models) leaves the flag on the header, while the model or enum a bare `$ref` names keeps its own; `Field` from the property schema itself, a keyword written beside a `$ref` included, while the referenced model keeps its own, and a typing `allOf` member's is not read but an annotating one's is (`allOfWrapperLayer`; see Collapsed wrappers), as a header reads them: `notes: { allOf: [{ type: "integer" }, { deprecated: true }] }` is a deprecated field, as `X-Notes` with that schema is a deprecated header, while `allOf: [{ type: "integer", deprecated: true }]` flags neither — or, for a bare `$ref` to an array or primitive component, which has no model to keep the flag, from the component and every alias the reference passes as well (see Array components), and, for a bare `$ref` to an alias of an enum component, from every alias the reference passes, the enum keeping its own flag (see Enum); `Model` and `Enum` from the schema's own top-level keyword as described above. At every site the parser tests `=== true`: a `false`, absent or non-boolean keyword (`"yes"`, `1`) leaves the key absent, so the IR never carries anything but a literal `true`, on any of the six nodes. `EnumValue.deprecated` reads the value's own `const` member — an enum declared as a `oneOf`/`anyOf` of `const` schemas — by the same `=== true` rule, and is absent on every value of a plain `enum:` list, which has no per-value keyword (see Enum below).

The differ compares the flag on every node that carries it — operation, parameter, response header, model, field, list envelope field, enum, enum value, webhook and webhook parameter, callback and callback parameter — and reads it the way the parser writes it: only `true` is deprecated, so `false` and an absent key are the same thing, and a document that spells out `deprecated: false` diffs as unchanged against one that omits it. A flip is reported on the owning `-modified` change: `deprecatedChanged: true` on `operation-modified`, `model-modified`, `enum-modified`, `webhook-modified` and `callback-modified`, with `oldDeprecated`/`newDeprecated` beside it (present exactly when the flag is); a `param-deprecated-changed`, `header-deprecated-changed`, `field-deprecated-changed` or `value-deprecated-changed` entry, carrying the same two values and a `details` that reads `live → deprecated` or `deprecated → live`, in the change's `paramChanges`, `responseHeaderChanges`, `fieldChanges`, `envelopeFieldChanges` or `valueChanges` for an operation's or a webhook's parameter, an operation's response header, a field, an operation's list envelope field (`pagination.envelopeFields`, matched by name while both specs paginate) or an enum value. A model, enum, operation or webhook whose only change is the flag is still reported, with an empty nested list. Becoming or ceasing to be deprecated changes no contract — the node is still there with the same shape — so every one of these is additive, in either direction, an inline copy of a deprecated component included: the copy keeps its qualified model under either flag (`GetLegacyWidgetWidget` beside a deprecated `Widget`), so deprecating it is `model-modified GetLegacyWidgetWidget` with `deprecatedChanged: true` and nothing else, where it was once `model-removed` beside a breaking `responseChanged` (#441) — except that the component's own flip beside such copies retypes them, since a copy's name follows the component's flag and never its own (see Models): deprecating `Pet` together with `getLegacyPet`'s identical inline copy, or `Pet` alone while the copy stays deprecated, moves the copy from `Pet` to `GetLegacyPetPet`, `model-added GetLegacyPetPet` beside a breaking `responseChanged` and the additive `model-modified Pet`, exit 2 in either direction, as deprecating `Pet` alone has always done to a live copy; it still counts as `modified` in the summary, and a breaking change on the same node (a removed field beside the model's flag, a changed response beside the operation's, a retyped payload beside the webhook's) keeps the change breaking. Each flip is also mirrored into `behaviorChanges` as a `deprecated-changed` entry naming the node (`operation`, `parameter`, `response-header`, `model`, `field`, `envelope-field`, `enum`, `enum-value`, `webhook`, `webhook-parameter`, `callback` or `callback-parameter`, the last two carrying the callback's triple and site as its change does) and copying `oldDeprecated`/`newDeprecated` from the change, the way a parameter default change is, so a changelog can say which way it went without reading both specs. Parameters are compared in every location a node carries them — an operation's path, query, header and cookie parameters, a webhook's header, query and cookie parameters — and matched by location and name, since a path `id` and a query `id` may sit on one operation and a webhook's header and query parameters may share a name — a header's name compared case-insensitively, so a header deprecated and respelled `x-pet-token` in one step is still the `X-Pet-Token` it was, and its flip is reported; every `paramChanges` entry carries `paramLocation` to say which one it is about. A response header's flag is compared on every response entry that declares headers — the primary and every other 2xx/3xx entry, every error, the `default` and every range — with headers matched by name case-insensitively, and every `responseHeaderChanges` entry carries its `statusCode` or `fallback` to say which entry it is about (see Response Headers above).

## Enum

```typescript
interface Enum {
  name: string; // PascalCase
  description?: string; // The enum schema's own `description`, when it has non-whitespace content: a component's, or the inline schema's the enum was lifted from (a collapsed wrapper's or a single-member `oneOf`/`anyOf`'s text wins over its branch's)
  values: EnumValue[];
  externalDocs?: ExternalDocs; // The enum schema's externalDocs, when usable — a component's, or the inline schema's the enum was lifted from
  deprecated?: boolean; // The component enum schema's own `deprecated: true`; absent otherwise
  extensions?: Extensions; // The x-* keys of the schema that declares the members, less x-enum-descriptions / x-enumDescriptions (see Extensions)
}

interface EnumValue {
  name: string; // UPPER_SNAKE_CASE display name
  value: string | number; // Actual value from spec (preserves numeric types)
  description?: string; // The value's own documentation (a const member's `description`, else its `x-enum-descriptions` / `x-enumDescriptions` entry); absent otherwise
  deprecated?: boolean; // `true` when the value's const member says `deprecated: true`; absent otherwise
}
```

**Two spellings declare an enum.** An `enum:` list, and — the OAS 3.1 way to document or deprecate values one by one — a `oneOf`/`anyOf` whose every non-null variant is a string `const` schema (a single-member string `enum` counts as a const). Under `components.schemas`, both become an `Enum`, and a `$ref` to either resolves to `{ kind: "enum" }`; a `oneOf` of consts there is an enum, not a named union, so `PetStatus: { oneOf: [{ const: "available" }, { const: "sold" }] }` is `enums[].PetStatus` with no `PetStatus` model. Either may sit inside an `allOf` the type builder reads as its one typing member — a lone member, or one beside members that only annotate or limit it (see Inline `allOf`), however nested: `Kind: { allOf: [{ type: 'string', enum: ['cat', 'dog'] }], description: 'The kind of pet.' }` and `Kind: { allOf: [{ type: 'string', enum: ['cat', 'dog'] }, { description: 'The kind of pet.' }] }` are the enum `Kind`, read as `Kind: { type: 'string', enum: ['cat', 'dog'], description: 'The kind of pet.' }` is, in OAS 3.0 and 3.1 documents alike (`enumComponentDeclaration`). An `enum:` list or a `oneOf`/`anyOf` of consts written beside an `allOf` whose members only annotate or limit it is the same enum, since such an `allOf` does not type the schema (`allOfTypesSchema`, the predicate the named-union reading shares; see Named unions): `Kind: { allOf: [{ description: 'A kind.' }], oneOf: [{ const: 'cat' }, { const: 'dog' }] }` is the enum `Kind` described 'A kind.', as `Kind: { description: 'A kind.', oneOf: [...] }` is and as the same schema is inline — under a nullable wrapper of either spelling too (`Kind: { allOf: [{ description }], oneOf: [{ type: 'string', enum }, { type: 'null' }] }`, or with `nullable: true` in the `null` variant's place in a 3.0.3 document, is the nullable enum `Kind`) — the layer's text, link, flag, examples, keys and `default` read as the `allOf` spelling's are, and `oagen diff` between the two spellings reports nothing (#613 review: the component was a model with no fields and no variants). The wrapper's `description`, `externalDocs`, `default`, `example`, `examples` and `x-*` keys, and its annotating members', are the enum's — the wrapper's own winning, then the first annotating member's, the member's standing where the layer declares none, nested wrappers composing outermost-first — its `deprecated` is the wrapper layer's alone, as a field's is, and a parameter that names the enum reads the wrapper's limits conjoined with the member's, as it reads any enum component's limits; the member's own nullability (`enum: [..., null]`, `type: ['string', 'null']`, OAS 3.0 `nullable: true` on the member) makes a `$ref` to it `nullable<Kind>`, while `nullable: true` beside the `allOf` declares nothing, as beside any schema without a `type`. Either spelling, and the `allOf` around it, may also sit inside a nullable `oneOf`/`anyOf` wrapper — the one non-null variant beside `null` variants, in either order, however nested (`nullableUnionBranch`, the wrapper the type builder collapses on a field, read one level at a time so a nested wrapper is a wrapper of its own: the nearest outer level's text, flag, key or `default` wins, an inner level's stands where the outer declares none) — which is the same enum, nullable (#606): `Kind: { oneOf: [{ allOf: [{ type: 'string', enum: ['cat', 'dog'] }] }, { type: 'null' }] }`, `Size: { anyOf: [{ allOf: [{ type: 'string', enum: ['large', 'small'] }, { description: 'The size of the pet.' }] }, { type: 'null' }] }` and `Color: { oneOf: [{ type: 'string', enum: ['black', 'white'] }, { type: 'null' }] }` are the enums `Kind`, `Size` (with its text) and `Color`, and a `$ref` to each is `nullable<Kind>`, `nullable<Size>`, `nullable<Color>` — the shape the same schemas written inline on a field have — at every reference site. The wrapper is read as a field's wrapper is (see Collapsed wrappers): its `description`, `externalDocs`, `example`, `examples` and `x-*` keys are the enum's over the branch's, its `deprecated` stands in place of the branch's own (an annotating member's inside the `allOf` still counts, as above), its `default` wins over the branch's, and its limits conjoin with the branch's for a parameter that names the enum. In OAS 3.0, where a `null` variant cannot be written, `nullable: true` beside a `oneOf`/`anyOf` of one variant is the same wrapper (`flaggedNullableUnionBranch`): `Kind: { oneOf: [{ allOf: [{ type: 'string', enum }] }], nullable: true }` and `Color: { oneOf: [{ type: 'string', enum }], nullable: true }` are the nullable enums `Kind` and `Color` in a 3.0.3 document as the `null` variant makes them in a 3.1.0 one. The flag is read there because beside a union it is never nothing — every `$ref` to such a component is nullable, as it is for a named union — while beside an `allOf` or any other schema without a `type` it declares nothing, as above. A `oneOf` of one variant with neither a `null` variant nor the flag stays the named union of one it was (see Named unions). Such a component names no enum component, so it is no alias of one (see Aliases) and nothing is lifted as `UnknownEnum`: `oagen diff` between the `allOf` spelling and the plain one, between `Kind` written as `Color` is and written with the `allOf`, or between the 3.0.3 document and the 3.1.0 one, reports nothing. The same `oneOf` written inline on a field, parameter or header collapses to an inline enum (one of two or more consts; a single const with no `enum:` list beside it stays a `literal`), and so does one written as a request body at every site — an operation's, a webhook's or a callback's, the primary media type or a secondary one — `oneOf` exactly as `anyOf`: the `addNote` body above (see Request Body Encoding) is the enum `AddNoteRequest`, in OAS 3.0.3 (single-value `enum` variants) and 3.1.0 (`const` variants) alike (#603). A union with any other variant — a `$ref`, an object, a number const — is a union. Inline, what is written beside the union of consts does not unmake the enum unless it types the schema: `{ allOf: [{ description: 'Annotated.' }], oneOf: [{ const: 'draft' }, { const: 'final' }] }` is the enum at every site — a field, a parameter, a header, a response body, a webhook or callback payload, and a request body — since an `allOf` of members that only annotate or limit types nothing (see Inline `allOf`), and so is the same `oneOf` beside `properties: { name: { type: 'string' } }`, since `properties` constrain nothing in a const variant (see `properties` beside a composition); `{ allOf: [{ $ref: '#/components/schemas/Pet' }], oneOf: [the same consts] }` is `Pet` at every site, the union read as one more member of the typing `allOf` (#398). Under `components.schemas`, the same `oneOf` beside `properties` is a composed model (`NoteStatus { name }`; see Named unions), not an enum. An `enum:` list written beside a `oneOf`/`anyOf` of consts applies together with it, as JSON Schema keywords do: the members are the consts whose value the list allows (a const the list leaves out is dropped, with its documentation), and a `null` variant (`{ type: 'null' }`, `{ const: null }` or `{ enum: [null] }`) admits `null` only when the list does not leave `null` out — so `{ enum: ["a"], oneOf: [{ const: "a" }, { const: "b" }, { type: "null" }] }` is the one-value enum `a`, not nullable. Inline, the list is read the same way whatever it leaves — the members `constUnionEnumMembers` keeps and the nullability `enumListAdmitsNull` decides, the two helpers the component path reads: one member left is an inline enum of that member, none left is an inline enum with no members (as an empty `enum:` list is), never the union of every const the list forbade — so that schema on a field is the one-value inline enum `a`, not nullable, exactly as the component is.

**Enum description.** `Enum.description` is the enum schema's own `description`, present only when it has non-whitespace content and kept verbatim. For a component enum it is the component's, as a model's is `Model.description`. For an enum lifted into `spec.enums` from an inline schema — on a property, parameter, response header, request body, response body (primary, secondary-media-type, error or fallback) or webhook parameter or payload, including array items, `oneOf` variants and a `oneOf` of string consts collapsed into one enum — it is the text of the schema that declares the members: the `enum:` list's schema, or the `oneOf`/`anyOf` wrapper whose consts are the members, read where that schema's link is read (`inlineEnumRef` records both; `collectInlineEnumFromRef`, the one place an inline enum becomes an `Enum`, writes both). A nullable `oneOf`/`anyOf` or single-member `allOf` wrapper the type builder collapses — and a single-member `oneOf`/`anyOf`, which it keeps as a union of one variant but types that variant by the same rule — is the schema the document wrote for the property, parameter, header or body, so its text is the enum's when it has content, and the branch's own counts only when the wrapper has none (`withWrapperDocs`, which carries the wrapper's text and link onto the branch by one rule, at the type builder's wrapper sites, the request-body path's own `oneOf` included, and where the response path types the member of a single-member `allOf` body it unwrapped itself — through nested wrappers the outermost text with content wins, so a nullable wrapper around a single-member `oneOf` gives the enum its own text as it does around a single-member `allOf` (#445)); the `type: [..., 'null']`, `nullable: true` and `enum: [..., null]` spellings are one schema, so their text is the enum's as written. The model built from an object branch or member of such a wrapper documents itself by the same rule and at the same step (`unwrapNullableField` through `unwrapNullableSchema`, `unwrappedAllOfMember`, both reading `withWrapperDocs`): the wrapper's text when it has content, the branch's or member's own only when it has none, nested wrappers composing outermost-first. The text stays where it was as well: the `Field`, `Parameter` or `ResponseHeader` typed by the schema keeps its own `description` by its own rule, and an inline enum body's text is also the operation's `requestBodyDescription` (see Request Body Description). A Parameter Object's or Header Object's `description` is never the enum's: only a Schema Object's text is read. `Enum.description` is documentation, not shape: the differ does not report a change to it (no change carries a flag for it), and two inline enums with the same members that differ only in it are one enum.

**Per-value documentation.** Each `EnumValue` carries what the document attaches to that one value. `description` is the const member's own `description`; a value whose own text has no content — every value of an `enum:` list — takes its entry from the enum schema's `x-enum-descriptions` or `x-enumDescriptions` extension. Either key may hold an object mapping each value's text form (`"5"` for a numeric `5`) to its description, or a list aligned with the members as written (the `enum:` entries, or the `oneOf`/`anyOf` variants, a `null` entry or `null` variant counted in its place); `x-enum-descriptions` is read when it holds an object or a list, `x-enumDescriptions` otherwise. Text reaches the IR only when it has non-whitespace content; the key is absent otherwise. `deprecated` is present, and `true`, only when the value's const member says `deprecated: true` — the literal `true`, as on every other node — so a value of an `enum:` list never carries it. Members are read by occurrence, not by value: a `oneOf`/`anyOf` that repeats a const yields one `EnumValue` per branch, each with its own documentation, inline and under `components.schemas` alike. Nullability is never a member: a `null` entry or a `null` variant makes a `$ref` to the component resolve to `nullable<enum>`.

**Aliases.** A component that is only a reference to an enum component — a bare `$ref` (`PetKind: { $ref: Kind }`, with or without text beside it), a nullable `oneOf`/`anyOf` around that `$ref` (`{ oneOf: [{ $ref: Kind }, { type: 'null' }] }`), an `allOf` read as the reference, alone or beside members that only annotate or limit it (`{ allOf: [{ $ref: Kind }] }`, `{ allOf: [{ $ref: Kind }, { description: 'The kind of pet.' }] }`, the usual OAS 3.0 way to document a reference), or an alias of such an alias — becomes no `Model` and no `Enum` of its own (#560): a `$ref` to it resolves to the enum it names, `{ kind: "enum", name: "Kind" }`, exactly as the same schema written inline is typed, under `nullable` when the alias wraps the `$ref` in a `null` variant or the enum itself admits `null` (OAS 3.0 `nullable: true` beside the `allOf` declares nothing, as it declares nothing beside any schema without a `type`). This holds at every reference site — a field, a parameter, a request body, a response, a webhook payload, array items, map values, a union variant, and a named union's variant, which is then the enum and names no model for a discriminator — in OAS 3.0 and 3.1 documents alike. Like an array or primitive component, an alias is known by its `components/schemas` key, resolved by that key before any name-based test, and its name stays claimed: an array component's items step around it as they step around any component's. What the alias declares — its own `description`, `externalDocs`, `deprecated`, `readOnly`, `writeOnly`, `default`, `example`, `examples`, limits and `x-*` keys, and those of an `allOf` member of its that declares no type, which is part of its own declaration as such a member is part of a field's (see Inline `allOf`), while the lone member it is read as is not, as for an array component's alias — sits on no node, so a field or parameter that names it with a bare `$ref` carries it as it carries an array or primitive component's (see Array components and Primitive components), through every alias the reference passes, nearest first: `Pet.kind: { $ref: PetKind }` carries `'The kind of pet.'`, as `Pet.size: { allOf: [{ $ref: Size }, { description: 'The size of the pet.' }] }` carries its text. The members are levels for documentation alone: an alias's limits are read once, its annotating members' conjoined with its own as `extractConstraints` reads a field's schema, so the alias's own `pattern` or `multipleOf` stands where a member's conflicts (`NameAlias: { allOf: [{ $ref: Name }, { pattern: 'b$' }], pattern: '^a' }` limits a field or parameter that names it to `^a`, as it did before the members were levels; see Collapsed wrappers). The enum is no such level: `Kind` keeps its own text, link, flag, default, limits and keys on the `Enum`, as it does for a bare `$ref` to it, and a field takes only its `example`/`examples` where no alias gives one, as it takes any component's; a parameter, which reads the component a bare `$ref` names, reads the enum after the aliases and merges the enum's limits underneath the aliases' conjoined with its own. Under a wrapper — `{ allOf: [{ $ref: PetKind }] }`, `{ oneOf: [{ $ref: PetKind }, { type: 'null' }] }` — the field or parameter documents itself and conjoins the aliases' limits alone, exactly as for an array or primitive component. A component that is more than a reference stays a model: two `$ref` members (`allOf: [{ $ref: Kind }, { $ref: Size }]`), `properties` beside the `allOf`, or a reference chain that returns to itself. A discriminator reads a pinned value through the same shapes: a variant's `kind: { $ref: RabbitKind }` with `RabbitKind: { allOf: [{ $ref: RabbitConst }] }` and `RabbitConst: { const: 'rabbit' }` (`enum: ['rabbit']` in OAS 3.0, where `RabbitConst` is a one-value enum component and `RabbitKind` its alias) pins `rabbit`, as `kind: { allOf: [{ $ref: HamsterKind }], description: 'The kind of pet.' }` pins what `HamsterKind` pins and `kind: { allOf: [{ const: 'cat' }] }` pins `cat` (see UnionType; #607). An alias is only a chain that ends at a `$ref` to an enum component (`isEnumComponentAlias`: the entries a reference reads through, `componentEntries`, list the component and then one entry per `$ref` followed, and a chain of one followed none): a component that declares its enum inside the `allOf` itself, with no `$ref` — `Kind: { allOf: [{ type: 'string', enum: ['cat', 'dog'] }], description: 'The kind of pet.' }`, alone or beside annotating members, with or without an alias in front of it — or inside a nullable `oneOf`/`anyOf` wrapper, around the `allOf` or around the enum itself — `Kind: { oneOf: [{ allOf: [{ type: 'string', enum: ['cat', 'dog'] }] }, { type: 'null' }] }`, `Size: { anyOf: [{ allOf: [{ type: 'string', enum }, { description: 'The size of the pet.' }] }, { type: 'null' }] }`, `Color: { oneOf: [{ type: 'string', enum }, { type: 'null' }] }` (#606: `Kind` and `Size` were aliases of nothing, their enums lifted as `UnknownEnum` and `UnknownEnum2`, the components' names lost) — is the enum `Kind`, `Size` or `Color` (see Two spellings above), never an alias, so nothing is lifted as `UnknownEnum` and its `deprecated`, `default` and limits are read as the enum's. A true alias wrapped the same way — `MaybeKind: { oneOf: [{ allOf: [{ $ref: Kind }] }, { type: 'null' }] }` — is an alias still, its chain passing the `$ref`, and a `$ref` to it is `nullable<Kind>`; so is a `$ref` with a `oneOf` beside it (`{ $ref: Kind, oneOf: [{ type: 'string', enum }, { type: 'null' }] }`), which is the reference whatever sits beside it, as the type builder reads it, and declares no enum of its own.

**Inline enums sharing a name.** When two inline enums lift to one name, the first lifted gives the enum its `description` and its value descriptions, as it gives its link — so a later copy's text is not read even when the first declared none. Per-value deprecation is part of the members, not documentation: a second copy with the same values that deprecates a different one is renamed (`PetsMode2`) before it is promoted, as a copy with other values is, so a field whose schema does not deprecate a value never resolves to an enum that marks it. Every pass that compares shapes to decide whether two models are one reads an inline enum the same way — each value with its deprecation (`shapeWithEnumFlags`, `enumShapeKey`): the materialization fingerprint header and body models share a registry entry by, the merge passes' identical-shape checks and the `<Name>Json` fold, the named-union shape key, and the companion and parameter-group fingerprints — so a copy differing only in that keeps its own model name, as a deprecated copy of a model does. The raw-schema comparison that lets two sibling inline objects share one model, or two unions' variants share a title (`schemaShapeKey`), reads `deprecated: true` as shape at every level for the same reason, a const member's included. The member key is a JSON pair of value and flag, so a live `"active!deprecated"` and a deprecated `"active"` never read alike, and a member list is compared as a complete sorted list, so a repeated member counts each time it occurs: `[a, a!, b]` and `[a, a, b]` are different types. With `--doc-url`, `Enum.description` has its relative links expanded exactly as `Model.description` and every `EnumValue.description` do.

## ErrorResponse

```typescript
interface ErrorResponse {
  statusCode: number; // e.g., 401, 404, 422
  type?: TypeRef; // Response body type, if any
  headers?: ResponseHeader[]; // e.g. Retry-After on a 429; only when the spec declares at least one
  description?: string; // e.g. "Not found"; only when it has non-whitespace content
  contentTypes?: string[]; // Media types under `content`, in document order; only when they add to `type` (see below)
  contents?: ResponseContent[]; // One per contentTypes entry, same order; the entry `type` was read from (application/json, else the first +json media type) shares `type`
}
```

`type` is the JSON body — `application/json` by essence, else a `+json` media type such as `application/problem+json` — read as a fallback body's is. A `$ref` body is a plain reference to the component model; an inline body is materialized into `spec.models` under an operation-qualified name so that two operations' inline `404`s never share one model, nor do two status codes of one operation: `<Op>Error<code>` from the `operationId` (`getPet` + `404` → `GetPetError404`), or the path-derived prefix plus `Error<code>` without one (`GET /pets/{petId}` → `PetsByPetIdGetError404`); a body that came from `components/responses` is named after the component instead (`<Component>Response`), shared by every operation that returns it, at a status code, as `default` or in a range alike, and so are the component's other media types (`<Component><MediaType>Response`) and headers (`<Component><Header>`). An inline body the same error declares under another media type is named from the error body's name and the media type — `GetPetError404ApplicationYaml` (see Response Content Types above) — so the status code is in every error body's name, and it is deferred and stepped exactly as the JSON body is (`GetPetError404ApplicationYamlBody` on a clash); two status codes that declare the same media type get two models, as their JSON bodies do. The body of a `4XX` or `5XX` range is an error body too, named with the range key in PascalCase where a status code would stand (`GetPetError4Xx`, `GetPetError4XxApplicationYaml`; see Default and Range Responses above). Nested objects, array items, `oneOf`/`anyOf` variants and map values under the body follow the usual inline-model naming rules from that name (`GetPetError404Detail`, `GetPetError404WithCode`). The body is typed through the same deferred mechanism as a response header or a `default` body (see [Default and Range Responses](#default-and-range-responses)): it is named only once every operation's request-body and primary-response models are known, against the spec-wide registry of model shapes, so a name a component schema, a model nested in one (`GetPet.error404` owns `GetPetError404`), or an earlier header, fallback or error model already owns with a different shape — or an enum owns at all: a component enum, an enum a parameter or body of any operation carries, any operation's error, fallback or secondary body that is itself an enum under the same stem, declared before or after it — moves the whole body to the next free name (`GetPetError404Body`, then `GetPetError404Body2`, …), nested models and reference together; an identical shape shares it. A component's body steps by number instead (`ProblemResponse2`, then `ProblemResponse3`, …), the way the same component's body steps at a `default` or range site, so a `404` here and a `default` there settle on one name. A `oneOf` variant named by its bare title (`Circle`) that clashes is reserved and takes its qualified name exactly as when a sibling owns the title (`CircleGetPetError400`), while a `$ref` inside it keeps its component; a titled variant nested below the top level is renamed under the body (`GetPetError400Circle`) with every reference rewritten. A body that is itself an inline enum, or an array of one, is promoted to `spec.enums` under the same name, which is reserved before any header, parameter, fallback or error model is named: another same-stem operation's inline object `404`, declared before or after it, is the one that moves to `GetPetError404Body`, and the enum keeps the name; one a component or header enum owns with other members steps to `GetPetError404Body` itself. An enum body under a secondary media type (`GetPetError404ApplicationYaml`) and the enum body of a `4XX`/`5XX` range (`GetPetError4Xx`) step to `…Body` the same way, and when `…Body` is owned too (a component enum of other members) every error-site enum numbers under it — `GetPetError404Body2`, `GetPetError404Body3`, … — exactly as the object bodies do, never on the bare name (`GetPetError404No2` is what a parameter named `error404` steps to); a `…Body2` that already holds the same members is shared. The `Body` step is for the bodies an operation named itself: an enum body a `components/responses` entry declares is named after the component (`ProblemResponse`, `ProblemApplicationYamlResponse`) wherever an operation returns it, and on a clash steps by number (`ProblemResponse2`) at a `404`, in a `4XX` and at `default` alike, so every operation that returns the component shares one enum, as they share its model (the parser hands the collector the identity of every reference a shared site wrote, `OperationExtractionResult.componentSites`, so an error site outside that record is the operation's own and a shared one is never told from its name). An enum nested in the body (`GetPetError422Severity`) is promoted with every other model's field enums: one a component enum owns with other members is numbered (`GetPetError422Severity2`), identical members share. Two operations with identical inline bodies get two models, exactly as they get two `<Op>Response` models.

### Shared error bodies

By default the parser then folds the inline error bodies onto shared models named by shape (`collapseErrorBodies`, `src/parser/collapse-error-bodies.ts`), so the `<Op>Error<code>` names above are what a body is materialized under, not what the IR keeps. Once every operation's models are merged, the pass reads every error site — each `errors[]` entry's `type` and its secondary `contents[].type`, and the body and secondary bodies of a `4XX`/`5XX` range — and takes the models only those sites reach: a component schema (and whatever it reaches), a model a success body, parameter, header, webhook or component also reaches, and a body a `components/responses` entry declares (`componentSites`) are left exactly as they are.

**What a shape is.** A body's shape is its required fields — for a body that requires none, every field it has — each read as its name, its domain name (a `fieldHints` entry applied to the materialized model) and its type, with a nested error-only model read by its own shape and a string the document pins (`const: idp_metadata_fetch_failed`, an inline `enum`) read as a plain string, so the bodies that differ only in their error code or their prose fold onto one model. An inline `enum`'s values are read sorted (numbers ascending, then strings), so reordering its entries changes no shape, and two bodies that list the same values in any order share one enum on the shared model, named from the field (see Shared error body enums), rather than a union of two. An optional field is not shape (#506, #516): a body that gains one stays in its group, and the group's model carries every optional field any member declares, in the first member's order and then each later member's — `{ message }` beside `{ message, hint? }` is one `ErrorBody { message, hint? }`, and `oagen diff` reads the addition as an additive `model-modified`. An optional field the members type differently is the union of the types they wrote, sorted, `null` hoisted (`hint?: integer | string | null`), the union carrying the limits the members agree on (two `hint?` type lists both under `maxLength: 10` give a union with `maxLength: 10` on the field and on its type); one pinned in a member that another lacks stays the literal. An optional field's domain name (a `fieldHints` entry keyed by one body's per-operation name) is not shape either: the shared field carries it whichever bodies hint it — `fieldHints: { GetPetError404: { hint: 'tip' } }` beside an unhinted `GetNoteError404 { message, hint? }` gives `ErrorBody { message, hint? → tip }` — and drops it, with a warning naming each body's hint, only when two bodies hint the field apart (`tip` beside `clue`); a hint keyed by the shared name (`fieldHints: { ErrorBody: { hint: 'tip' } }`) applies after the fold either way. Nor are a field's flags, default and limits, or a model's, shape: the shared model keeps them when every member wrote the same ones and drops them otherwise, as it keeps a description, example or `x-` extension only when every member wrote the same one — and the limits at every level of a field's type each on their own, by the same rule (#611): an array's items, a map's values and a union's variants keep the limits they carry when every member wrote the same ones there and drop them, as a whole, otherwise (items `{ maxLength: 2, pattern: '^a' }` beside `{ maxLength: 3, pattern: '^a' }` carry no limit, the shared `pattern` included, as a field's own would), so `{ message, tags: string[] }` with `maxLength: 2` on the items beside one whose items carry none is one `ErrorBodyWithTagsList` whose `tags` items carry no limit, never a union of the two arrays, and beside one with `minItems: 1` on `tags` and `maxLength: 2` on its items it keeps the items' limit and drops the array's. A union's variants are read by shape, whichever order each member lists them in: a shape every member lists with the same variants keeps the first member's (`oneOf: [{ string, maxLength: 2 }, integer]` beside `oneOf: [integer, string]` is one `string | integer`; `oneOf: [{ string, pattern: '^[a-z]+$' }, { string, pattern: '^[0-9]+$' }]` beside the same two reversed keeps both), and a shape the members list apart merges into one variant carrying the limits every one of its variants, in every member, agrees on, level by level, so no limit survives on one variant of a shape that another lacks (`oneOf: [{ string, pattern: '^[a-z]+$' }, { string, pattern: '^[0-9]+$' }]` beside `oneOf: [{ string, pattern: '^[a-z]+$' }, { string, pattern: '^[A-Z]+$' }]` is a plain `string`, never `oneOf: [{ string, pattern: '^[a-z]+$' }, string]`, which rejects `"abc"` though both bodies admit it; `oneOf: [{ string, maxLength: 2 }, { string, minLength: 3 }]` beside `oneOf: [{ string, maxLength: 3 }, { string, minLength: 4 }]` is a plain `string` too, never a `oneOf` of two strings, which admits nothing) — a lone survivor under the limits the union itself agreed on, conjoined onto its own with the stricter bound winning, so with `minLength: 1` beside each `oneOf` the string is under `minLength: 1`, and so is a survivor that is itself a union, the `anyOf` or type list the `oneOf` collapses onto. A `oneOf` one of whose variants the merge widened beside a variant of the same JSON value kind — a string beside a string literal or enum, an integer beside a number, an object beside an object, or an untyped schema — is read as `anyOf`, since its merged variants can no longer promise to match one value at a time: `oneOf: [{ string, pattern: '^b' }, { const: 'a' }]` beside the same with `'^c'` is `anyOf: [string, 'a']`, which admits `"a"` as both bodies do, where `oneOf: [string, 'a']` would reject it; one widened beside a variant of another kind (`oneOf: [{ string, maxLength: 2 }, integer]` beside `oneOf: [integer, string]`) stays `oneOf: [integer, string]`. Every `x-` extension and every description is set aside. A string inside an array, union or map keeps its value in the shape (`codes: ['a']` beside `codes: ['b']` stay two models), as does a discriminator mapping and the component a field references.

**What `deprecated` is to a shape, a name and a component.** Neither the body's own `deprecated` nor a field's is shape (#441, #629): a body's name never depends on a flag, as an inline copy's never depends on its own (`flagAdmits`, see Deprecation), so a flag flip moves no body. The shared model is deprecated only when every body of the shape is, and each of its fields only when every body that carries the field deprecates it; a deprecated body beside live ones, or a body's deprecated field beside live ones, folds onto the live model with a warning naming each side (`The shared error body "ErrorBody" is declared deprecated by "GetTagError404" and live by "GetNoteError404", "GetPetError404" — keeping it live`; `The shared error body "ErrorBody" has "message" declared deprecated by "GetPetError404" and live by "GetNoteError404" — keeping it live`), as a deprecated inline copy folding onto its live twin or onto a live component is announced, since the model is a body's only carrier for the flag and the field its own — the `errors[]` entry carries none. So deprecating one `{ message }` body among twins, or one body's `message`, leaves no trace in the IR (exit 0), as deprecating one of two identical inline response copies leaves none; deprecating `message` on every `{ message }` body is one additive `field-deprecated-changed` on `ErrorBody` (exit 1); and a lone deprecated `{ message }` is `ErrorBody` (deprecated), its flip one additive `model-modified ErrorBody`. A nested error body's own flag is settled among its twins the same way, so deprecating `getNote`'s `detail` beside `getPet`'s live `{ message, detail: { reason } }` keeps both bodies on `ErrorBodyWithReasonDetail` and the `detail` object on `ErrorBodyWithReasonDetailDetail`, live, with the two warnings and nothing for `oagen diff` to report. A component schema of the name takes a body only when it is live and deprecates no field the body keeps live (`componentAccepts`, below): a deprecated component takes no inline copy anywhere else (see Deprecation; #441), so a live site never resolves to it — beside a deprecated component `ErrorBody { message }` the live `{ message }` bodies of `getPet` and `getNote` keep live models of their own, `GetPetError404` and `GetNoteError404`, as they would beside a component of another shape, with the warning that gets, and `oagen diff` from the document with `ErrorBody` live reports `model-added GetPetError404`, `model-added GetNoteError404`, the additive `model-modified ErrorBody` flip and a breaking `operation-modified` with `errorsChanged` on each operation, exit 2, where it reported the flip alone and left both operations typed as deprecated; a component `ErrorBody` whose `message` is deprecated takes a live `{ message }` body no more, since it would give the body's readers a notice its schema never wrote (the bodies keep `GetPetError404` and `GetNoteError404`, `oagen diff` reporting the same with the flip a `field-deprecated-changed` on `ErrorBody`), and a component `ErrorBody { message, hint? }` whose `hint` is deprecated takes a body whose `hint` is live no more; while a live component, or a live field of one, takes a deprecated body or a body's deprecated field as the live model does, with the same warning (`… and live by component schema "ErrorBody" — keeping it live`), printed once the fold is known to be kept. So the one flag flip that is not additive is the component's — its own, or one of its fields' — as it is for every inline copy (see `oagen diff`'s Deprecation). The warning that leaves a body as it is prints the holder's shape beside the body's, a component's as a shared body's (`which component schema "ErrorBody" { message (deprecated): string } already holds`, `which deprecated component schema "ErrorBody" { message: string } already holds`), with `(deprecated)` after a deprecated field, so it says what differs.

**What a shape is named.** Each group becomes one model named from its shape alone, so that a name is a function of the shape and two shapes never ask for one name (#515): `ErrorBody` for `{ message }`, `OAuthErrorBody` for the OAuth error format `{ error, error_description }`, else the base plus `With` and a token per further required field, sorted by field name. The fields the family implies — `message`, or `error` and `error_description` in the OAuth format — and the field a value-named group pins (below) are left out of the name only while they are plain strings, free, pinned or enumerated, under no `null`, no format and no domain name (`ErrorBodyWithCode` for `{ code, message }`, `OAuthErrorBody` for `{ error, error_description }`); one that is not is spelled like any other field, so two shapes that differ there never ask for one name (`ErrorBodyWithNullableMessage` for `{ message: string | null }`, `OAuthErrorBodyWithErrorInteger` for `{ error: integer, error_description }`, `GoneErrorBodyWithNullableCode` for `{ code: 'gone' | null, message }` beside `GoneErrorBody`, `GoneErrorBodyWithCodeAsKind` for `{ code: 'gone', message }` hinted `code → kind`). A body of the `ErrorBody` family that has no required `message` ends in `WithoutMessage` (`ErrorBodyWithCodeWithoutMessage` for `{ code }` and for `{ code, message? }`; `OAuthErrorBodyWithMessage` for `{ error, error_description, message }`, since the OAuth family implies `error_description` instead). A field's token is its name in PascalCase, qualified by what its type adds so that two shapes with the same field names read apart: `Nullable` leads a field that admits `null` (`ErrorBodyWithNullableMessage` for `{ message: string | null }`), a scalar that is not a plain string follows the name — its type (`ErrorBodyWithCodeInteger` for `{ code: integer, message }`, `OkBoolean`) or its format (`CreatedAtDateTime`, `CountInt64`) — a non-string `const` (or single-member `enum`) its value, so bodies pinned to different ones read apart (`ErrorBodyWithStatus404` beside `ErrorBodyWithStatus410`, `OkTrue` beside `OkFalse`, `RatioMinus1Point5`; behind `No` after a name that ends in a digit, `V2No3` for `v2: const 3`, as every number in a name is), an inline `enum` of non-string values its values — sorted, numbers ascending then strings, so reordering the entries renames nothing — joined with `Or` (`Status404Or410` for `enum: [404, 410]` and for `enum: [410, 404]`), a domain name follows it after `As` (`ErrorBodyWithMessageAsDetail` for `{ message }` hinted `message → detail`), `List` ends an array of plain values after what its items add (`ErrorBodyWithErrorMessageList`, `CodesIntegerList`, `TagsNullableList` for `(string | null)[]`, apart from `NullableTagsList` for `string[] | null`), a union's variants are joined with `Or` (`ErrorBodyWithMessageOrMessageList`), and a nested error body's own required fields — every one, the ones the parent also has included — are prefixed as tokens, recursively (`ErrorBodyWithCodeFieldErrors` for `{ message, errors: [{ code, field }] }`, `ErrorBodyWithCodeMessageErrors` for items `{ code, message }` beside `ErrorBodyWithCodeErrors` for items `{ code }`, `ErrorBodyWithCodeTagsIntegerListErrors` for items `{ code, tags: integer[] }`). A reference to a component or a named enum, a map and an untyped schema add nothing. A body that requires no field is named from every field it has under `Optional`, so it never takes a required shape's name: `OptionalErrorBody` for `{ message? }`, `OptionalErrorBodyWithCode` for `{ code?, message? }`, `OptionalErrorBodyWithCodeWithoutMessage` for `{ code? }`; `{ }` is `ErrorBodyEmpty`. Adding a field to such a body renames it, since every field it has is in its name — requiring at least one field gives it a stable name. A group every member of which pins exactly one required string field to one value is named from that value instead, as a const-discriminated variant is named everywhere else (`RateLimitExceededErrorBody`, `InvalidGrantOAuthErrorBody`; the field's name follows the value unless it is `code` or `error`), plus `With` and the tokens of any further fields, a nested body's own fields left out (`OrganizationSelectionRequiredErrorBodyWithOrganizations`, `RateLimitExceededErrorBodyWithRetryAfterInteger`), and `WithoutMessage` as above (`GoneErrorBodyWithoutMessage` for `{ code: 'gone' }`); a value that is empty or starts with a digit names no group, which falls back to its fields. A model only another error body reaches is named from its parent and the field (`OrganizationSelectionRequiredErrorBodyWithOrganization`; singular for an array, by the rule under Inline model naming: `causes` → `…Cause`, `statuses` → `…Status`), as a nested inline object is named everywhere else; when the field is optional in the parent, whose name then says nothing of the item, the item's own fields follow after `With`, every one (`ErrorBodyDetailWithReason` for `{ message, detail?: { reason } }`, `ErrorBodyDetailWithMessageReason` for an item `{ reason, message }`), so two items under one optional field never ask for one name — `{ message, detail?: { reason } }` beside `{ message, detail?: { cause } }` is one `ErrorBody` whose `detail?` is `ErrorBodyDetailWithCause | ErrorBodyDetailWithReason`. So an optional property added to a body or to a nested item moves no model: `{ message, errors: [{ code, field, hint? }] }` keeps `ErrorBodyWithCodeFieldErrors` and `ErrorBodyWithCodeFieldError`, and `oagen diff` reads one additive `model-modified`. And adding an operation never renames an existing model: beside two `{ message? }` bodies (`OptionalErrorBody`), a new `{ message }` is `ErrorBody`; beside `{ message: string | null }` (`ErrorBodyWithNullableMessage`), it is `ErrorBody`; beside `{ code: string, message }` (`ErrorBodyWithCode`), a `{ code: integer, message }` is `ErrorBodyWithCodeInteger`; and a `{ message }` hinted `message → detail` is `ErrorBodyWithMessageAsDetail` beside the unhinted `ErrorBody`, whichever body carries the hint. `ErrorBody` rather than `ErrorResponse`, since an emitter may already spend that name on a component called `Error`.

**What a name may already hold.** The pass never numbers a name: a shared name a component schema of that shape already holds is that component for every body it can stand for — one that declares every field the body has, required or optional as the body has it, of its type and domain name; that is no stricter than the body, every limit it writes on itself, on a field or at any level of the field's type — the type's own, an array's items at every depth, a map's values, a union's variants, through a nullable wrapper — being one the body writes the same (a component `ErrorBody { message: string, maxLength: 3 }` does not take an inline `{ message: string }`, which it would narrow; nor does `ErrorBodyWithTagsList { message, tags: string[] }` with `maxLength: 2` or a `pattern` on its items take an inline `{ message, tags: string[] }` whose items carry none, any more than with `minItems: 1` on `tags`, nor `ErrorBodyWithTags { message, tags: map<string> }` with `maxLength: 2` on its values, nor `ErrorBodyWithTagsOrTagsInteger` with the limit on its `string` variant, whichever order either side lists the variants in (#611); while a component without the limit takes a body that writes one, and one that writes the same limit at the same level takes it too); and whose string fields admit every value the body pins — those bodies fold onto it, and a body it cannot stand for is left as it is, alone, with its own shape in the warning, so that with a component `ErrorBody { message }` and two inline `{ message }` bodies, an optional `hint` added to one moves that body alone to its per-operation model (`GetPetError404`, the warning printing `{ message: string, hint?: string }`), the other keeps `ErrorBody`, and `oagen diff` reports one `operation-modified`; a name anything else holds — a component of another shape, an enum, a shared body whose shape differs in what no name can spell (a value pinned inside an array, a discriminator mapping, the component or named enum a field references: `{ message, detail: Note }` beside `{ message, detail: Tag }` both ask for `ErrorBodyWithDetail`) — leaves the group's models exactly as the parser materialized them, together with every error-only model they reach or are reached from, with a warning that prints both shapes with their requiredness, domain names and types (`{ message: string | null, detail: Tag }` beside `{ message: string, detail: Note, hint?: string }`) so it says what differs, and the fold runs again without them. The groups are ordered by shape, fewer named fields first, then a shape whose name is its field names alone before one a qualifier spelled, then by key, never by the operations that declared them, so when two shapes do ask for one name the same one keeps it and renaming an operation moves no model name. Two such shapes the names above cannot tell apart are a field named like another field's qualifier and a pinned value that spells a family prefix: `{ message, code_integer: string }` and `{ message, code: integer }` both ask for `ErrorBodyWithCodeInteger`, `{ message, code: 'optional' }` and `{ message? }` both for `OptionalErrorBody`, since no qualifier is beyond what a field name can spell — every word sequence PascalCase makes of a field name is one, and a marker outside it would collapse once an emitter re-cases the name — so the plain shape keeps the model (`{ message, code_integer }` keeps `ErrorBodyWithCodeInteger` when an operation with `{ message, code: integer }` is added, which stays per-operation with a warning printing both shapes, and `oagen diff` reports only the added model) and adding the plain shape beside an existing qualified one moves the qualified model; renaming or hinting the field tells them apart. A shared enum takes the name of an enum the document already holds only when the members agree, sharing it as the collectors share any inline enum; when they differ, or a model holds the name, the fields stay plain strings, with a warning. A string field a group pins to two or more values becomes an enum shared by every error body with a field of that name — `ErrorBodyCode` for `code`, `ErrorBodyError` for an OAuth `error` — holding every value any error body pins that field to (the collectors lift it like any inline enum; an emitter's enums admit an unlisted value); one value every member pins stays that literal, and a lone pinned value beside free strings widens to `string`. The response's own `description` stays on the `errors[]` entry. The references are rewritten in place — the `contents` entry that shared its `type` with the entry's `type` keeps sharing it — and a `oneOf` whose variants fold onto one model is no longer a union: duplicate variants are dropped and a lone survivor replaces the union. On the WorkOS document this takes 834 error-body models to 21 and 14 per-operation `…Error400Code` enums to 2, with every `errors[].type` still resolving. `collapseErrorBodies: false` (on `ParseOptions` and in `oagen.config.ts`) keeps one model per operation and status code for a consumer that names them.

### Shared error body enums

A string field the shared bodies pin to two or more values is the shared enum `ErrorBody<Field>` described above (`ErrorBodyCode`), holding every value any body pins the field to. Every other inline enum a shared body's field lists — an integer or number `enum`, a string `enum` under array items or map values or in a union, through a nullable wrapper, on a nested body — is named from the field and its values, never from the operation whose body happened to sort first (#612): `ErrorBody<Field><Values>`, the values spelled as the model's token spells them — sorted, numbers ascending then strings, joined with `Or`, a number behind `No` after a field that ends in a digit — `ErrorBodyStatus404Or410` for `status: { type: integer, enum: [404, 410] }` on `ErrorBodyWithStatus404Or410`, and under an optional `status?` on `ErrorBody` alike; `ErrorBodyRatio1Point5Or2Point5` for `ratio: { type: number, enum: [1.5, 2.5] }`; `ErrorBodyCodesAOrB` for `codes: { items: { enum: ['a', 'b'] } }`; `ErrorBodyLevels1Or2` under map values; `ErrorBodyLevel1Or2` for a nested `detail: { level: { enum: [1, 2] } }`; `ErrorBodyStatusXOrY` beside `ErrorBodyStatus404Or410` under a `oneOf` of two inline enums; `ErrorBodyV2No3Or4` for `v2: { enum: [3, 4] }`. It is one enum shared by every shared body whose field of that name lists those values, whichever operations declare them and under however many status codes, and by a field that spells alike and lists them (`errorCode` beside `error_code`, one `ErrorBodyErrorCode1Or2`). The name depends on the field and its values alone, never on what else the document declares, so adding, removing or renaming an operation moves no enum: beside `ErrorBodyStatus404Or410`, a body with `status: { enum: [500, 503] }` adds `ErrorBodyStatus500Or503`, bodies pinning `status` to `'gone'` and `'lost'` add the string rule's `ErrorBodyStatus`, and `{ message, errorCode: { enum: [3, 4] } }` beside `{ message, error_code: { enum: [1, 2] } }` adds `ErrorBodyErrorCode3Or4` — each an additive `oagen diff` (exit `1`). A name an enum of the same members already holds — a component `ErrorBodyStatus404Or410: { type: integer, enum: [410, 404] }` — is shared; the string rule's enum keeps its name and every pinned value whatever an array or map under the same field lists (`ErrorBodyStatus` for `status: 'a' | 'b'` beside `ErrorBodyStatusAOrB` for `status: ('a' | 'b')[]`); and a name anything else holds — a component enum of other members, a model, a set that spells alike with other members (`[1, 2]` beside `['1', '2']`, both `1Or2`; the set that sorts first keeps the name) — leaves the bodies that list the set exactly as the parser materialized them, with a warning that prints the body's shape and the field, as a taken model name does.

## DefaultResponse & RangeResponse

```typescript
// The `default` response: every status the operation does not list.
interface DefaultResponse {
  type?: TypeRef; // Response body type: the application/json body, else the first +json one; absent when the response declares neither
  headers?: ResponseHeader[]; // Only when the spec declares at least one
  contentTypes?: string[]; // Media types under `content`, in document order and as written; only when at least one
  contents?: ResponseContent[]; // One per contentTypes entry, same order; the entry `type` was read from shares `type`
  description?: string; // The response's own description, as on SuccessResponse/ErrorResponse; only with non-whitespace content
}

type StatusRange = "1XX" | "2XX" | "3XX" | "4XX" | "5XX";

// A range response: every status in its hundred the operation does not list explicitly.
interface RangeResponse {
  range: StatusRange; // Uppercase as OpenAPI writes it; `4xx` is read as `4XX`
  type?: TypeRef; // Response body type: the application/json body, else the first +json one; absent when the response declares neither
  headers?: ResponseHeader[]; // Only when the spec declares at least one
  contentTypes?: string[]; // Media types under `content`, as on DefaultResponse
  contents?: ResponseContent[]; // One per contentTypes entry, as on DefaultResponse
  description?: string; // The response's own description, as on SuccessResponse/ErrorResponse; only with non-whitespace content
}
```

Both carry the response's `description` by the rule `SuccessResponse` and `ErrorResponse` follow: present only with non-whitespace content, kept verbatim, read from the resolved Response Object — so a `$ref` into `components/responses` gives the component's, and a sibling `description` beside the `$ref` wins where `resolveResponseRef` keeps one. Both carry every media type the response declares as `contentTypes` / `contents`, in the shape a `SuccessResponse` carries them (see Response Content Types): present only when at least one is declared, the entry for the media type `type` was read from — `application/json`, else the first `+json` media type — sharing that very `TypeRef`, every other entry typed on its own.

See [Default and Range Responses](#default-and-range-responses) for how they are resolved and named.

## Operation Resolution

Source: `src/ir/operation-hints.ts`

The operation resolver derives method names, mount targets, and wrapper metadata for all operations in the spec. It runs in `buildEmitterContext()` and produces `ResolvedOperation[]` on `ctx.resolvedOperations`.

### Algorithm

The method name is a `name` hint when one is set, else the algorithm below — unless the consumer sets `operationNaming: 'operationId'` (`oagen.config.ts`; the fourth argument of `resolveOperations`), in which case an operation the document declares an `operationId` for (`Operation.operationId` is set, which it is not for an `operationId` that names nothing, such as `'-'`, nor for one an `operationIdTransform` returns nothing for; see Service & Operation) resolves to `Operation.name` as the parser spelled it — an `operationIdTransform` applied — converted to snake_case, so `getAuthorizationUrl` resolves to `get_authorization_url` whatever its path, and only a path-named operation goes through the algorithm. The conversion (`snakeCaseOperationName`) reads a boundary wherever the name writes one, since the parser's camelCase keeps an acronym in capitals and a transform may keep the id's own separators: a lower-case letter before a capital, a digit or a run of capitals before a capitalized word, and any character that is not a letter or digit (`-`, `:`, `.`, `/`, a space), so `getSSOAuthorizationUrl` resolves to `get_sso_authorization_url`, `createM2MApp` to `create_m2m_app`, `createJWTToken` to `create_jwt_token` and `pets:adopt`, handed back as written by an identity transform, to `pets_adopt`; a digit otherwise stays in its word (`m2m`, `v2`, `oauth2`). The path-segment converter `deriveMethodName` uses is a different, narrower one, so `path` names are not affected. The default is `path`, since a spec whose ids are not written as method names (NestJS-style `UsersController_list`, stripped to `list` by a transform) would otherwise rename every method and collide across remounted services.

`deriveMethodName(op, service)` derives a snake_case name from the HTTP method and path:

1. Strip path-param segments (`{id}`, `{slug}`, etc.)
2. If the terminal segment is an action verb (`verify`, `enroll`, `confirm`, `revoke`, etc.), use it as the verb with the preceding resource as the noun: `verify_challenge`
3. Otherwise, use a CRUD verb from the HTTP method: GET → `list`/`get`, POST → `create`, PUT/PATCH → `update`, DELETE → `delete`
4. Singularize the resource noun for single-resource operations

### Hint types

Consumer-provided overrides keyed by `"METHOD /path"`:

```typescript
interface OperationHint {
  name?: string; // Override derived method name
  mountOn?: string; // Remount to different service/namespace
  split?: SplitHint[]; // Split union body into N typed wrappers
  defaults?: Record<string, string | number | boolean>;
  inferFromClient?: string[];
  pagination?: PaginationHint; // Explicit pagination, applied by the parser — see "Overriding detection" under PaginationMeta
}
```

### Resolved output

```typescript
interface ResolvedOperation {
  operation: Operation; // Original IR
  service: Service; // Original owning service
  methodName: string; // Resolved snake_case name
  mountOn: string; // Resolved target service (PascalCase)
  wrappers?: ResolvedWrapper[];
}
```

### Mount rules

Service-level remounting maps an IR service name to a target namespace. All operations in the source service are mounted on the target unless overridden per-operation. Per-operation `mountOn` hints take precedence over service-level rules.

Rule keys may be exact service names or trailing-`*` prefix patterns. Precedence: an exact key always wins; otherwise the wildcard with the longest prefix wins. Matching is plain `startsWith` string comparison — `*` is only meaningful as the final character, and no regex is involved. This lets a family of tags collapse to a few rules:

```typescript
{
  "UserManagement*": "UserManagement",                          // catch-all for the family
  "UserManagementOrganizationMembership*": "OrganizationMembership", // longer prefix wins
  "UserManagementDataProviders": "Pipes",                       // exact wins over wildcard
}
```

Note that a catch-all also absorbs future tags added to the spec under that prefix — a new `UserManagementFoo` tag mounts silently instead of surfacing as a new top-level service, so review `oagen diff` output (or run `/oagen:review-operations`) when the spec adds tags.

### CLI

`oagen resolve --spec <path> --format table|json` outputs the full resolution table for review. Use `--format json` for programmatic consumption.

The three settings `resolveOperations` takes beside the spec — `operationHints`, `mountRules` and `operationNaming` — are one object, `OperationResolution`, and every command that reads the SDK `generate` writes resolves with the config's: `generate` hands them to the engine, `resolve` prints what they resolve to, `compat-extract` matches the SDK's callables by the names they resolve to, and `verify`'s compat scope and staleness check (`specDerivedNames`, `specDerivedMethodPaths`, `detectStaleSymbols` in `compat`) read the classes and methods they resolve to. Under `mountRules: { Pets: 'Animals' }` and `operationHints: { 'GET /pets': { name: 'list_all' } }`, `GET /pets` and `GET /pets/{id}` tagged `Pets` resolve to `Animals.list_all` and `Animals.get_pet`, so `verify` scopes the SDK's `Animals` class and those two methods (in the language's casing); with no settings, to `Pets.list_pets` and `Pets.get_pet`. See [Non-additive changes](non-additive-changes.md).

## Versioning

The IR does not currently use a version constant. As a 0.x project with no external consumers yet, formal IR versioning is deferred until post-open-source when external emitters need a stable contract signal.

**Compile-time safety:** `assertNever` enforces exhaustive `switch` statements over `TypeRef.kind` at compile time. Adding a new variant causes build failures in any emitter that doesn't handle it — this is the primary compatibility mechanism.

**Walker/Mapper utilities:** `walkTypeRef` and `mapTypeRef` handle recursive traversal of `TypeRef` trees. Both visit `MapType.keyType` when present. The `mapTypeRef` mapper callback for `map` receives an optional third argument `mappedKey?: T` for the mapped key type.
