Skip to content

Commit 8a5abff

Browse files
dinwwwhclaude
andauthored
fix(downgrader): keep a $ref bare beside a type its tagged target holds too (#344)
<!-- claude-projects-attribution: {"github_login":"dinwwwh"} --> _Requested by **dinwwwh** · [project thread](https://claude.ai/code/project/chan_01UcKMz91tMarPV1kWLVgLYE?thread=cmsg_01UcKMz91tMarPV1kWLVgLYE3WDrsammLg4kGEz5ZjzAjg)_ ## What #174 already turns a `$ref` into the bare `$ref` when two things hold: only annotations sit beside it, and its target keeps a `discriminator`. Without that, the `allOf` wrapper reads as a subtype in 3.0. That change left a `type` sibling wrapped. With this PR, a `type` beside the `$ref` that equals the target's own `type` also counts. It restricts nothing the target doesn't already restrict, so dropping it changes no value. Any other `type` stays wrapped: - a list such as `['object', 'null']` beside an `object` target, which would reject null where the target allows it - `string` beside an `object` target - any `type` beside a target that is itself a `$ref` and so holds no `type` of its own The change is in `isTaggedRef` (it now takes the schema and checks its keys). `convertSchema` calls it in place of `isAnnotatedRef(...) && isTaggedRef(...)`. ## Why I found this on a recent SwaggerHub document, the NPP (National Parking Platform) API 3.1.0: ```json "EntranceOpenTime": { "title": "EntranceOpenTime", "description": "...", "type": "object", "x-package": "time", "$ref": "#/components/schemas/PeriodsOrValidity" } ``` Here `PeriodsOrValidity` is `type: "object"` with a `discriminator` on `type` (`validity` / `periods`). On main, 3.0 gets `{ ..., type: "object", allOf: [{ $ref: PeriodsOrValidity }] }`, which 3.0 reads as one of the discriminator's subtypes. openapi-typescript 7.13 then types the property as `{ type: "EntranceOpenTime" } & Omit<PeriodsOrValidity, "type">`. That type rejects every real value. `ExitOpenTime` has the same problem. With this change, both become the bare `$ref`, and the openapi-typescript diffs for these two properties go away. Round 855 of the earlier hunt saw the same shape in OpenAI's `InputItem` branch `{ type: "object", title: "Item", description, $ref: Item }`. ## Checks - **Output against main:** across 279 3.1/3.2 docs (225 recent SwaggerHub docs, GitHub, Discord, Figma, OpenRouter and others, oRPC corpora, FastAPI, Litestar, Huma, utoipa, Effect, Fastify, aide, Elysia, swagger-core, ASP.NET Core 10, OAI fixtures), the 3.0 output changes only in the NPP document, at those two components. - **Values on NPP:** none of the 120,757 values the 3.1 schema accepts is lost (Ajv 2020 on the input, draft-04 with `nullable` on the output), and the 3.0 output is valid. - **Tests:** the #174 test fails on main and passes here. The `typed` case is now bare, and new `nullable`, `other` and `alias` cases stay wrapped. 363 tests pass with 100% coverage, and `pnpm check` is clean. - **README:** the `$ref`-with-siblings row now names the case. --- _Generated by [Claude Code](https://claude.ai/code/session_01VVaw7PbWyR4kZ18CjgHzqs)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 06b5d00 commit 8a5abff

3 files changed

Lines changed: 31 additions & 7 deletions

File tree

‎packages/downgrader/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ Accepts the default OAS dialect, which adds `discriminator`, `xml`, `externalDoc
201201
| [`contentEncoding`][js-content-encoding] and [`contentMediaType`][js-content-media-type] | `format: "byte"` for `base64`, and `format: "binary"` for `binary` or a media type without an encoding or a `contentSchema`, which marks structured text. It replaces a `format` that only repeats the encoding, such as Zod's `format: "base64"`. Without a `type`, it gains only the `format`, so it still takes every value, unless it holds a `$ref`, `allOf`, `anyOf`, `oneOf`, `properties`, `items` or `prefixItems`, as a JSON body marked with its media type does. Then the keywords are removed. |
202202
| An [`anyOf`][js-any-of] with a branch that holds only `contentMediaType`, as Zod writes for a file with several media types | Removed, since that branch matches every value. |
203203
| An [`anyOf`][js-any-of] with branches that become equal, as oRPC 1.x writes a file with several media types, a string for each, and Effect a nullish union, with `{ type: "null" }` twice | A branch equal to the one before it is removed, as the `anyOf` then matches the same values, and a lone branch left takes the place of the `anyOf` when the schema around it holds only annotations that the branch lacks or holds with the same value, or nothing else beside a `$ref`, so a nullable one then merges as above. NSwag and oapi-codegen read the `anyOf` of equal binary strings as a generated class or a union, not as a file upload. Branches are equal when each keyword holds the same value, or the same object rather than a copy. A `oneOf` keeps them, since it rejects a value that two branches match. |
204-
| A [`$ref`][js-ref] with siblings | `allOf: [{ $ref }]` beside the siblings, which 3.0 would ignore. A branch of a `oneOf` or `anyOf` beside a `discriminator` that stays, with only annotations beside its `$ref`, such as the `description` the Anthropic and ElevenLabs APIs write for each, becomes the bare `$ref` instead, since 3.0 maps a discriminator only to the `$ref`s among its branches, not to inline schemas, and oapi-codegen stops on the `allOf` there. So does a `$ref` with only annotations beside it to a schema whose `discriminator` stays, such as the `description` the OpenAI and Adyen APIs write beside a property holding a tagged union, or the `examples` the Anthropic API writes there, since 3.0 reads an `allOf` holding that `$ref` as one of the schemas the discriminator picks among. openapi-typescript then leaves out its tag, and Hey API pins the tag to the name of the schema around it when the target has no `oneOf`, as for Adyen's base with a `mapping`. In both cases the annotations beside the `$ref` are dropped, so a `readOnly`, `writeOnly`, `default` or `deprecated` there is lost, as for the `readOnly` the Cryptography Provider API writes beside one. |
204+
| A [`$ref`][js-ref] with siblings | `allOf: [{ $ref }]` beside the siblings, which 3.0 would ignore. A branch of a `oneOf` or `anyOf` beside a `discriminator` that stays, with only annotations beside its `$ref`, such as the `description` the Anthropic and ElevenLabs APIs write for each, becomes the bare `$ref` instead, since 3.0 maps a discriminator only to the `$ref`s among its branches, not to inline schemas, and oapi-codegen stops on the `allOf` there. So does a `$ref` with only annotations beside it to a schema whose `discriminator` stays, such as the `description` the OpenAI and Adyen APIs write beside a property holding a tagged union, or the `examples` the Anthropic API writes there, also beside a `type` the target holds too, as OpenAI writes for an input item, since 3.0 reads an `allOf` holding that `$ref` as one of the schemas the discriminator picks among. openapi-typescript then leaves out its tag, and Hey API pins the tag to the name of the schema around it when the target has no `oneOf`, as for Adyen's base with a `mapping`. In both cases the annotations beside the `$ref` are dropped, so a `readOnly`, `writeOnly`, `default` or `deprecated` there is lost, as for the `readOnly` the Cryptography Provider API writes beside one. |
205205
| [`$defs`][js-defs], and `definitions`, its draft-07 name | Removed. Each `$ref` into it, or into any `items` or `additionalProperties`, where the conversion can put another schema, is replaced by its converted target, where a reference back into a target being inlined becomes `{}`. |
206206
| A [`discriminator`][3.0-schema-discriminator] over `$ref`s into `$defs`, as Pydantic and msgspec write a tagged union | Removed. A discriminator picks only among named components, not the targets that replace those `$ref`s, and its `mapping` into them would dangle, which validators that follow it, such as openapi-schema-validator, reject. |
207207
| Boolean subschemas | `{}` for `true` and `{ not: {} }` for `false`, except in `additionalProperties`, which allows booleans. |

‎packages/downgrader/src/v3.1-to-v3.0.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -362,10 +362,21 @@ function isAnnotatedRef(value: Record<string, unknown>): boolean {
362362
// leaves out the tag, and Hey API pins it to the name of the schema around it
363363
// when the target has no `oneOf`. So a `$ref` to one beside only annotations,
364364
// as OpenAI and Adyen describe a property holding a tagged union, stays the
365-
// bare `$ref`, as a branch does.
366-
function isTaggedRef(ref: string, ctx: Context): boolean {
365+
// bare `$ref`, as a branch does. A `type` the target holds too, as OpenAI and
366+
// the NPP API write beside one, restricts nothing more, so it counts as well,
367+
// unless a 3.0-style `nullable` there lets the target take null in 3.0.
368+
function isTaggedRef(value: Record<string, unknown>, ref: string, ctx: Context): boolean {
369+
if (!hasOnly(value, (key) => key === '$ref' || key === 'type' || isInputAnnotation(key))) {
370+
return false
371+
}
367372
const target = resolvePointer(ref, ctx)
368-
return isRecord(target) && keepsDiscriminator(target, ctx) && !isInlined(ref, ctx)
373+
return (
374+
isRecord(target) &&
375+
(value.type === undefined ||
376+
(jsonKey(value.type) === jsonKey(target.type) && target.nullable !== true)) &&
377+
keepsDiscriminator(target, ctx) &&
378+
!isInlined(ref, ctx)
379+
)
369380
}
370381

371382
function convertSchemaRef(ref: string, ctx: Context, holder: unknown): unknown {
@@ -1529,7 +1540,7 @@ function convertSchema(value: unknown, ctx: Context): unknown {
15291540
if (
15301541
ref !== undefined &&
15311542
(isBareRef(value as Record<string, unknown>) ||
1532-
(isAnnotatedRef(value as Record<string, unknown>) && isTaggedRef(ref, ctx)))
1543+
isTaggedRef(value as Record<string, unknown>, ref, ctx))
15331544
) {
15341545
return convertSchemaRef(ref, ctx, value)
15351546
}

‎packages/downgrader/tests/v3.1-to-v3.0.test.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2258,6 +2258,10 @@ describe('downgradeSchemaV31ToV30', () => {
22582258
discriminator: { propertyName: 'type' },
22592259
},
22602260
Identification: identification,
2261+
// A target that is itself a `$ref` holds no `type` of its own.
2262+
Alias: ref('Identification'),
2263+
// Written 3.0-style, which lets it take null in 3.0.
2264+
Nullable: { ...identification, nullable: true },
22612265
// As Pydantic writes a tagged union, whose discriminator 3.0 removes.
22622266
Pet: {
22632267
oneOf: [ref('Pet/$defs/Cat')],
@@ -2270,7 +2274,12 @@ describe('downgradeSchemaV31ToV30', () => {
22702274
strategy: { ...ref('Strategy'), description: 'The chunking strategy' },
22712275
data: { ...ref('Strategy'), examples: [{ type: 'auto' }], $comment: 'Event data' },
22722276
identification: { ...ref('Identification'), 'title': 'Account', 'x-a': 1 },
2273-
typed: { ...ref('Identification'), type: 'object' },
2277+
// A `type` the target holds too, as OpenAI and the NPP API write.
2278+
typed: { ...ref('Identification'), type: 'object', title: 'Typed' },
2279+
nullable: { ...ref('Identification'), type: ['object', 'null'] },
2280+
other: { ...ref('Identification'), type: 'string' },
2281+
alias: { ...ref('Alias'), type: 'object' },
2282+
nullableTarget: { ...ref('Nullable'), type: 'object' },
22742283
pet: { ...ref('Pet'), description: 'Pet' },
22752284
},
22762285
},
@@ -2283,7 +2292,11 @@ describe('downgradeSchemaV31ToV30', () => {
22832292
strategy: ref('Strategy'),
22842293
data: ref('Strategy'),
22852294
identification: ref('Identification'),
2286-
typed: { type: 'object', allOf: [ref('Identification')] },
2295+
typed: ref('Identification'),
2296+
nullable: { type: 'object', nullable: true, allOf: [ref('Identification')] },
2297+
other: { type: 'string', allOf: [ref('Identification')] },
2298+
alias: { type: 'object', allOf: [ref('Alias')] },
2299+
nullableTarget: { type: 'object', allOf: [ref('Nullable')] },
22872300
pet: { description: 'Pet', allOf: [ref('Pet')] },
22882301
},
22892302
})

0 commit comments

Comments
 (0)