# 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` into `components/pathItems` 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's link and keys but leaves its `description` off the merged model. 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.

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 component, which has no model to keep the link, so the field takes it as it takes the component's `example` (see Array components). 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 component, whose keys the field then carries as it carries that component's `description`. 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 is not conjoined into it, and a typeless one fills in only the keys the typing one leaves unset (`combineDeclarations`) — 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 or a union member of a component `allOf`, whose field is typed from the first branch); `mergeBranchPropertySchemas` for the nested sub-branches of a discriminated `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. The lifted keywords (`description`, `readOnly`, the limits, …) are read by the same agreement when the declarations become a union; when they share one shape, the first declaration gives them. `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, parameter or header the schema types carries the same keys, since they are its schema's own — 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. The field the wrapper types carries the outermost wrapper's keys alone, since that wrapper is its schema.

**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. 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" } }`  |

### 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;
}
```

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
}
```

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 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` and pins the same const property is the one shape named differently: its discriminator mapping has always named each variant by its title (`Circle`, `Square`), so the extracted models carry those titles too, and the mapping is read from the same names — 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 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). 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 `type: 'null'` — 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, 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 their children, 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, or an earlier variant of the union minted it; when the chosen context still mints a claimed 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 schema's own declaration kept where the variant declares the same property and the `required` names the union of both lists; the union keeps every variant. 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). 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`, two of arrays keep the `items` that say something, 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. A discriminated `allOf` + `oneOf`/`anyOf` component — the union spelled with either keyword, every variant, a single one included, pinning one property to a distinct const — 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 union no discriminator dispatches is flattened into the model and builds no variant model. 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), two typing arrays keep the `items` that say something — 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 takes the first variant's declaration (the union of distinct branch declarations an inline merge builds is not built for a component). 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 is the component's own to dispatch or flatten; the merge does not read it, see Inline `allOf`). A `oneOf` written beside `properties` under `components.schemas` keeps the object model (see Named unions).

### UnionType

```typescript
interface UnionType {
  kind: "union";
  variants: TypeRef[];
  discriminator?: { property: string; mapping: Record<string, string> };
  compositionKind?: "allOf" | "oneOf" | "anyOf";
}
```

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`).

### 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.

## 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`.
- `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` — 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`), that object 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; inline, `$ref`, `allOf`, or a nullable wrapper) — a `stats.total` beside `pagination.page` is not the list's size, and the array itself is never a stop field — and the path follows the `dataPath` convention, each segment spelled as the document spells it (`pageInfo.hasNextPage`). The body an explicit `dataPath` keeps as a wrapper (below) is read the same way. When several candidates exist, `hasMore` beats `totalPages`, which beats `totalCount`. List-envelope recognition shares that list of names, so an envelope whose only companion is a stop field in any of these spellings — `{ data, has_more }`, `{ data, hasMore }`, `{ data, hasNext }`, `{ data, pageCount }` — 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 — `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 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 (the later `items` when they narrow, the earlier otherwise, `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, with or without `items` beside it — in which case `response` is `nullable<array<Item>>` while `itemType` is still the element (`ListEventsItem[] | null`, `dataPath: 'data'`). Its items, whatever their shape, are typed as `<Op>Item` (see Inline model naming). `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 live copy; 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 IR is consulted first — the detected data array, an envelope companion's fields, or the response model's fields — 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), 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; 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.

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, for a recognized envelope and for a wrapper kept under an explicit `dataPath` alike — and is walked from there as an explicit `dataPath` is, through `$ref`s, `allOf` members and nullable wrappers at every further segment; the field it lands on 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`, or any path when the primary declares no body), or to a field of another type (`{ kind: 'hasMore', path: 'total' }` on an integer `total`, 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, 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 usable tag on an operation (`Operation.tags[0]`: the first entry that is a non-empty string, so `['', 'notes']` and `[42, 'notes']` both name `Notes`) is converted to PascalCase (e.g., `tags: ["multi-factor-auth"]` → service `MultiFactorAuth`). When no usable tag is present, 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`) 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` are not read; a `paths` operation that declares any is warned about once, by name, and parsed as if it declared none. See [Webhook](#webhook) for the rule, which covers a `webhooks` operation too.

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 `components/pathItems` 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` over the Path Item's `description`, and an operation with both shows only its own. `Operation.description` is the combined doc text of the two resolved texts: `summary + "\n\n" + description` when both have content, or whichever one has content (a summary identical to the description is not repeated). 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 `description: "List pets"`, and `summary: ""` on an operation takes the Path Item's — and text that has content is kept verbatim, surrounding whitespace included. An emitter that prints `description` as the doc comment therefore sees the same text whether the document put the text on the operation or on its Path Item, and whether or not it used a summary. `Operation.summary` is the resolved `summary` alone and is present only when one of the two levels has content, so an emitter that wants a one-line label (and the description without it) reads `summary` rather than guessing whether the first paragraph of `description` is one. 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. 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 path-named operation of another verb takes the name it has without the action rule (`POST /pets/bulk-delete` beside `DELETE /pets/bulk-delete` is `createBulkDelete`), 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 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), 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: `/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). 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, each word compared by its singular form): one the name already ends with is not repeated, so `listNotes` never becomes `listNotesNotes`, nor `listNotesNote` for `/orgs/notes/{id}/notes`, and one that repeats a word itself is collapsed, so `/org/analytics/analytics/teams` next to `/org/teams` yields `listTeamsAnalytics`. 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 that shares its name with a path-named operation of another shape yields: it takes back the collection it dropped (`POST /pets/update` beside `PUT /pets/{id}` is `updatePets`, and `update` stays with the PUT) or, when that adds nothing, its name without the action rule (`createPetCreate` for `POST /store/pets/{id}/create` beside `POST /store/pets/{id}`). 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 (`/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 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; 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. 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"
  summary?: string; // The document's summary alone; only when it has non-whitespace content
  description?: string; // summary + "\n\n" + description when both have content, else whichever does
  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)
  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 requestBody is
  requestBodyDescription?: string; // The Request Body Object's description, else the picked schema's own (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 non-empty strings dropped, repeats folded; only when at least one remains; the service is named from [0]
  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
}

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 — the caller's when an operation in either document declares no `security` of its own, the receiver's when a webhook does — and is breaking if any such side breaks; when nothing inherits it, no request reads the default, 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 `tags[0]` (the first usable entry) 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
  constraints?: Constraints; // Validation keywords; see Constraints below
}
```

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 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. It is 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 such a value 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 and reports a difference as a breaking `param-content-type-changed` (see [docs/cli.md](../cli.md)); the webhook stem naming does not read it.

`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. A header reads only its own schema, as its `description` and `deprecated` read only the Header Object: a `$ref` sibling's link is the header's, and a bare `$ref` gives none (the referenced model carries its own). 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 component becomes a fieldless model; an array component becomes no model). The key is absent when neither declares any.

### Path Item references

OpenAPI 3.1 lets a `paths` entry be written as a `$ref` to a Path Item under `components/pathItems`. 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. 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; 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 outside `components/pathItems` (into another section, or into another `paths` entry such as `#/paths/~1pets`), a dangling ref, or a cycle. 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 — as one under `webhooks` is; the contested-title walker (`schemaRootsOf` in `src/parser/inline-models.ts`) steps over both too, so nothing under such a key is ever read.

### 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. 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. 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 is read as written with a warning, its sibling text kept, and a circular response chain fails the parse — on a webhook, either keeps the status code with a warning. 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).

### 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 `+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. 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`, 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). 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 `requestBody` is, whatever the encoding or the body's shape (an inline object, a bare `$ref`, a `oneOf`, a schema-less binary or text body); an operation without a body, or whose declared body yields no `requestBody`, has no entry.

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 body appearing or disappearing is reported as `requestBodyChanged` alone. 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, 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 declare one 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. 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 takes that branch's own `description`, and the wrapper's, when the Request Body Object has none, is what `requestBodyDescription` carries. 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 a key's parameters join the fragment only when another key of the same essence is declared beside it, so two spellings of one media type take names that do not depend on their order — `application/xml` and `APPLICATION/XML; charset=utf-8` beside a primary `application/json` are `ReplaceWidgetApplicationXmlRequest` and `ReplaceWidgetApplicationXmlCharsetUtf8Request`. Two case-only spellings with no parameters (`Application/XML`, `APPLICATION/XML`) derive one name: they share one model when their shapes are identical, and otherwise the second steps to `ReplaceWidgetApplicationXmlRequest2`, in document order. 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 named under the operation's one `<Op>Response` context, the primary's first (the lowest status code whose body has a type): a later status code's model of a shape the kept one shares (`modelFingerprint`) resolves to the kept definition and is dropped silently, so identical bodies on a 200 and a 201 are one model. A later status code's body that reaches a model the primary — or an earlier status code — already holds under another shape is re-derived under its own stem before it is merged, the status code first (`CreatePetResponse201`, with every model that context names moved with it, `CreatePetResponse201Owner` — except one a kept model already holds under the same shape, which stays shared: a 201 `{ owner: { id }, extra }` beside a 200 `{ owner: { id } }` is `CreatePetResponse201` over the 200's `CreatePetResponseOwner`), then a number (`CreatePetResponse2`, `…3`), the chain a secondary media-type body steps through, a candidate being taken when a name it would give is kept, or owned by a component or another operation, under a shape the owner does not share: `{ owner: { id } }` as the 201 body beside a 200 `{ id }` is `CreatePetResponse201` with `CreatePetResponse201Owner`, and a list envelope kept at a 201 beside a 200 `{ id }` (no paging parameter) is `ListPetsResponse201 { data, total_pages }` rather than the 200's model, so `successResponses` never gives a status code a shape it did not declare. 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`); 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. Of a later status code's models, those its entry's `type` still reaches are kept (a nested model 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`, additive on its own, since the old code may still be declared (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 `<Op>Response` name the body is typed by (`GetPetKindResponse`), 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 derives the same `<Op>Response` name, 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`), 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`); a name a model owns is never taken. 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 (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 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). Each deferred site registers the enums it types — a body that is itself an enum, an enum nested in a model it minted — as it is resolved, so a later site that derives one of them steps the same way (`PetsSearchPetsXMode` for an `X-Mode` header parameter object after an earlier operation's `X-Mode` response-header enum; `GetPetError404Body` for `getPet`'s object 404 after `get-pet`'s enum 404). 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 primary body or another operation — `DocumentsCreateDocumentXMeta` from an `operationId`; for an operation without one, the path stem its request and response models are built from, 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 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. 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; 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`. Two precedences decide a name a parameter model and an enum both derive. An enum a parameter, a request body, a success body or a pagination field carries — typed as its operation is built, before any deferred site is named — keeps its name wherever the document declares it: 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`. Among the deferred sites — response headers, error bodies, secondary and fallback bodies, parameter models — document order decides, the earlier site keeping the name: adding an operation with a `filter` response-header enum after an operation whose `filter` parameter object is `PetsFilter` leaves the model alone (the header enum, lifted after the model, is `PetsFilter2`; a lone 2xx response carries no status code to qualify it by), while the same header enum on an earlier operation sends the parameter model to `PetsListPetsFilter`. 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. 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. 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 their parameters, lower-cased and cased after the essence (`application/yaml` → `ApplicationYaml`, `application/yaml; charset=utf-8` → `ApplicationYamlCharsetUtf8`), so each spelling's name does not depend on the keys' order and reordering them is no change; two such keys that differ only in case (`application/yaml`, `Application/YAML`) take the same name and go through the registry described next, in document order. Editing such a key's parameters (`; 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. 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). So an identical shape on another status code shares the model under whichever name that status code's body settled on — the bare name, or the `…Response200` it took when a component, a primary body or another operation owned the bare name with a shape it does not share — because each site tries, after the bare name, the names the earlier 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, `…ResponseCircle`, is built under that name again, so it is shared too); 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 200, `application/yaml` on the 201), two keys of one response that differ only in case — while two spellings side by side told apart by their parameters derive two names and never share; 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 or an earlier status code's model — is re-derived with its own status code (`…Response201`), then a numeric suffix (`…Response2`, `…Response3`, …), and a status code after it with that shape shares it in turn (`…Response202` for a 202 and the identical 203). 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) is warned about and the response read as written, with no body or headers, 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 (`resolveDeferredInlineTypes`), 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. A duplicate range (`4XX` beside `4xx`) keeps the first and warns. A webhook's responses apply the same classifier (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; // When the document declares one
  httpMethod: HttpMethod;
  summary?: string; // As on Operation: the operation's own, else the path item's
  description?: string; // As on Operation: summary + "\n\n" + description when both have content
  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`
  requestBodyDescription?: string; // The Request Body Object's description, else the picked schema's own, 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
}

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 `components/pathItems` 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) — combined into `description` by the operation's rule; `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); 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) 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`, …), so two case-only spellings with different fields never point at one model. `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 without a description, with a warning); `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, 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) and, for an encoding change — compared only while both documents declare a payload, as on an operation, so a payload appearing or disappearing 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), 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` 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 anywhere else, 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; a key starting with `x-` is a specification extension, not a webhook, and is stepped over without a warning whatever its value, as under `paths` (see [Path Item references](#path-item-references)).

**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 — cleaned exactly as an operation's own `…Request` model name is, so `adoptions_created` gives `AdoptionCreatedPayload` — and the PascalCase of the key otherwise (`pet.returned` → `PetReturnedPayload`). 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`). 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, and is minted again under it; both sides of a webhook-to-webhook collision are hashed, since neither key is more canonical. 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 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 newly required payload field is 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.

An operation's `callbacks` (OpenAPI 3.x) — the requests the API makes back to a URL the caller supplied in its request, each a path item keyed by a runtime expression such as `{$request.body#/callbackUrl}` — are not read, on an operation under `paths` or on one under `webhooks`: the IR has no node for a request tied to the operation that provoked it, so a callback's request body never becomes a model. Every site that reads an operation declaring at least one callback gets one warning — a `paths` operation once, a `webhooks` (key, method) entry once each, so two keys that `$ref` one `components/pathItems` entry are reported under each key — naming the site (the `operationId`, else `METHOD /path`; `webhooks.<key>.<method>` for a webhook's operation) and the callback keys in document order; the operation is otherwise parsed exactly as it would be without them. An empty `callbacks` map, or a value that is not a map, declares no callback and is silent. A `$ref` into `components/callbacks` is reported at the operation that writes it, under the key it is written as; an entry under `components/callbacks` that no operation references is not reported, since nothing reaches it. The path item under a callback has the shape of a `webhooks` entry, so declaring it there gets its payload typed.

## 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[];
  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
  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;
  description?: string;
  externalDocs?: ExternalDocs; // The field schema's own, a $ref sibling included; a bare $ref yields none unless it names an array 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 yields none
  extensions?: Extensions; // The field schema's own x-* keys, read like constraints (see Extensions)
}
```

### Named unions

A component schema that is itself a `oneOf`/`anyOf` — no `allOf`, no `properties` of its own, and not every non-null variant a string `const` (that is an enum; see Enum) — is a named union. It still becomes a `Model` (every component other than an enum or an array component does; see Array 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; a `type: 'null'` variant 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 `type: '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, with a `$ref` variant's const read from the component it points at: an explicit `discriminator:` with a `mapping:` is the spec's own, each target reduced to the IR model name it refers to (the last `$ref` segment through `schemaNameTransform`, so `#/components/schemas/Cat` → `Cat`) — 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, 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. 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. 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). 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.

Three shapes are deliberately not unions. A `oneOf`/`anyOf` whose every non-null variant is a string `const` is an enum (see Enum). A `oneOf` written beside `properties` keeps today's object model (the properties are its fields; the branches are not read), 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. 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, 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 name beginning with an accepted `…Json` model's name reads with that prefix replaced by its base's, the longest such prefix first and again until none applies, so `PetJsonWithA` reads as `PetWithA`, `PetJsonJsonThing` as `PetThing` by way of `PetJsonThing`, and `NoteJsonPetJsonToy` as `NotePetToy` under the folds of `NoteJsonPetJson` and `NoteJson` whichever is declared first — and a base as the shape it takes. 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, and the collectors that run after the fold lift the renamed reference afresh — onto `PetState`, or under its new name, `PetJsonMode` as `PetMode`, when the base has none), 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 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'`, or `items` with no `type`, in every case with `items` declared (`isArrayComponentSchema`) — or one `schemaToTypeRef` types as an array through its readings of a `$ref` and an `allOf`: a bare `$ref` to it; 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 component is wrapped. 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, 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 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` and `externalDocs` 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 takes the component's `description` and `externalDocs` when it declares none of its own, and is deprecated when either side says so — as it takes the component's `example` and `examples` — on every path that builds a field, an `allOf` merge's inherited property included; a `$ref` to a model, named union or enum leaves them on that node, and a `$ref` under a nullable wrapper or an `allOf` reads none, as `example` reads none there. A bare `$ref` field still has no `constraints`: the limits a parameter merges in are not carried onto a field. 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, 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 two kinds of alias differ in what a `$ref` to them resolves to: an alias of an object component (`WidgetAlias: { allOf: [{ $ref: Widget }] }`, with or without limits beside the member) is a model of its own, `WidgetAlias`, carrying `Widget`'s fields and its own `description`, `deprecated`, `externalDocs`, `extensions` and limits (a `maxProperties` written beside the member is `WidgetAlias`'s), and a `$ref` to it resolves to `{ kind: "model", name: "WidgetAlias" }`, never to `Widget`; an alias of an array component (`PetsAlias: { allOf: [{ $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.

### Inline model naming

Models come from `components/schemas` (named as written, after `cleanSchemaName` and any `schemaNameTransform`; an enum or array component yields none — see Enum and Array 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`.
- **Without an `operationId`:** from the full path and method. 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`), 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`). 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`. 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 written, with no body or headers, 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, 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 — 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; 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 component's stem is reserved like an `operationId`'s, so an unnamed `GET /owner` beside a component response `OwnerGet` takes a hashed 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`); nested inline objects are qualified with their parent model's name. 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`. One kind of same-named model is never settled that way: 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 models that follow no rename are settled as above; when every model of a name follows one, 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 — and a deprecated component admits only a deprecated inline model, so a live site never resolves to a deprecated component. 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 operation's name prefixed (`GetWidgetWidget` for a `getWidget` body pinned by `object: widget`), a numeric suffix when the name already starts with it (`GetPetResponse2` for the `getPet` body, `CreateNoteRequest2` for the `createNote` body), `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`). 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, and an inline parameter 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) — while what it receives (a response body or header, a webhook's payload or parameter) and a component field's object, 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 live copy's flag beside a deprecated component (see Deprecated), an enum holding the name (below), or a renamed child (above): the copies are clustered by shape, `deprecated` included, in document order, and each cluster takes one name; a copy of another shape takes a name of its own beside it. The first site is the first in document order among the copies that leave the name (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.

**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 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; a primary response body types inherited properties under its own name. 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 — 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 a `oneOf`/`anyOf` member with more than one non-null variant — those of every inline object variant — read through the variant's own `allOf` members and nested unions the same way — as optional fields: `allOf: [{ properties: { name }, required: [name] }, { oneOf: [{ properties: { ownerId } }, { properties: { shelterId } }] }]` is `{ name, ownerId?, shelterId? }` inline exactly as it is as a component. A variant's `required` list is not read, since its properties are present only on that branch; a `$ref` under a variant — the variant itself, or a member of the variant's own `allOf` — is not followed (its component keeps its fields); and a union a `$ref` member's component carries is not read (that component's own model dispatches or flattens it). 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`, two typing arrays keep the `items` that say something, 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 (documentation ignored): one shape is that 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 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. 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. A schema reached twice is read once in each capacity it is reached in — as an inline member (unions included), through a `$ref` member (its unions left to its 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 its union read 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: `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`); 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); 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.

### 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. A field whose schema (and `$ref` target, if any) gives neither has no `example` and no `examples` key.

### Constraints

JSON Schema's validation keywords are carried on `Field`, `Parameter` and `Model` 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.

**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 carried. 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 on a general multi-variant union are not carried. Keywords written beside a `$ref` (OpenAPI 3.1 allows them) are the field's own and are kept; a bare `$ref` field gets no `constraints`, because its limits belong to the referenced model. 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); 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 — 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. 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 — its operation's name prefixed (`GetLegacyWidgetWidget`), 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: a live inline model named like a deprecated component — an inline response, a request body, a field object, array items, a `oneOf` variant — takes a qualified name the same way, whatever its shape, so a live field never resolves to a deprecated component (`Pet.owner` → `PetOwner2` beside a deprecated `PetOwner`); 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, and takes a qualified name otherwise. 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). 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 the Header Object only (after a `components/headers` `$ref` is resolved), never from its schema; `Field` from the property schema itself, a keyword written beside a `$ref` included, while the referenced model keeps its own and an `allOf` member's is not read — or, for a bare `$ref` to an array component, which has no model to keep the flag, from the component as well (see Array components); `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, enum, enum value, webhook and webhook 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` and `webhook-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` or `valueChanges` for an operation's or a webhook's parameter, an operation's response header, a field 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; 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`, `enum`, `enum-value`, `webhook` or `webhook-parameter`) 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 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. 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`). A union with any other variant — a `$ref`, an object, a number const — is a union, and a `oneOf` written beside `properties` or an `allOf` is 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 `type: 'null'` variant 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 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 two wrapper sites 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); 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 `type: '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 `type: 'null'` variant makes a `$ref` to the component resolve to `nullable<enum>`.

**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 (`GetPetError404Details`, `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 (`GetPetError4042` 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. The models it takes are keyed by structure alone — field names, requiredness, flags and types, a nested error-only model by its own key, every `x-` extension and every description set aside — with 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. Each group becomes one model named from its shape alone: `ErrorBody` for `{ message }`, `OAuthErrorBody` for the OAuth error format `{ error, error_description }`, else the base plus `With` and a token per further field — the field's name in PascalCase, qualified by what its type adds so that two shapes with the same field names read apart: `List` for an array of plain values (`ErrorBodyWithErrorMessageList`), a union's variants joined with `Or` (`ErrorBodyWithMessageOrMessageList`), and a nested error body's own field names prefixed (`ErrorBodyWithCodeFieldErrors` for `{ message, errors: [{ code, field }] }`). A group every member of which pins exactly one 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 plain names of any further fields (`OrganizationSelectionRequiredErrorBodyWithOrganizations`); 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), as a nested inline object is named everywhere else. The pass never numbers a name: a shared name a component schema of exactly that shape already holds is that component, and the group folds onto it; a name anything else holds — a component of another shape, an enum, a shared body of another shape — 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 naming both sides, and the fold runs again without them. The groups are ordered by shape, fewer fields first and then by key, never by the operations that declared them, so when two shapes ask for one name the same one keeps it and renaming an operation moves no model name. 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. `ErrorBody` rather than `ErrorResponse`, since an emitter may already spend that name on a component called `Error`. 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`. A field's description, example and extensions survive only when every member wrote the same one; 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.

## 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

`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.

## 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.
