From c874c2f70ba47aa660bf5030b39e8d6902dbdc7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Krzywizna?= Date: Tue, 24 Nov 2026 12:00:16 +0100 Subject: [PATCH 1/3] [SEL-138] Match FSharp.SystemTextJson for per-type options, option elements and skippable option fields - Per-type options: apply WithOverrides first, read [] only with AllowOverride, and inherit the global union encoding when the per-type options do not set it (port of FSharp.SystemTextJson's overrideOptions). - option and voption tuple elements, positional union fields and unwrapped single-field cases allow null. - Record and named union fields follow SkippableOptionFields when deciding whether an option field is required. Each new test asserts the serialized JSON next to the schema and failed before the fix. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +- skills/fsharp-systemtextjson-openapi/SKILL.md | 34 ++--- .../Bootstrap.fs | 2 +- .../CommonHelpers.fs | 27 ++++ .../FsOptions.fs | 29 +++-- .../Record.fs | 21 +--- .../Tuple.fs | 7 +- .../Union.fs | 29 ++--- .../OpenApiCollectionsTests.fs | 2 +- .../OpenApiOptionTests.fs | 119 ++++++++++++++++-- .../OpenApiPerTypeOptionsTests.fs | 46 ++++++- .../OpenApiRecordTests.fs | 6 +- .../OpenApiTestSetup.fs | 32 +++++ .../OpenApiTupleTests.fs | 4 +- .../OpenApiUnionEncodingTests.fs | 2 +- .../OpenApiUnionTests.fs | 14 +-- 16 files changed, 290 insertions(+), 92 deletions(-) diff --git a/README.md b/README.md index a4c5a16..3003702 100644 --- a/README.md +++ b/README.md @@ -8,16 +8,18 @@ schemas then do not match the JSON that FSharp.SystemTextJson writes. This package adds schema and document transformers that read your `JsonFSharpOptions` and describe the real JSON: -- `option` and `voption`: the inner value, and `null` for record and union - fields +- `option` and `voption`: the inner value, and `null` for record fields, + union fields and tuple elements - records: required and optional properties, including `Skippable<'T>` fields + and `SkippableOptionFields` - unions: tags, internal, adjacent and external encodings, named fields, unwrapped cases, fieldless cases as strings, unions of only fieldless cases as string enums, and one component for each case (except string-enum and unwrapped single-case unions) - tuples, F# collections (`list`, `Set`, `Map`), and `JsonObject` - enums: string and number encodings, also when nullable -- per-type options from `[]` +- per-type options from `WithOverrides` and `[]`, + merged with the global options the same way as FSharp.SystemTextJson The package targets .NET 10 and OpenAPI 3.1. diff --git a/skills/fsharp-systemtextjson-openapi/SKILL.md b/skills/fsharp-systemtextjson-openapi/SKILL.md index 619649d..dd488ad 100644 --- a/skills/fsharp-systemtextjson-openapi/SKILL.md +++ b/skills/fsharp-systemtextjson-openapi/SKILL.md @@ -50,31 +50,35 @@ reads. - Giraffe: register `services.AddSingleton(Json.Serializer(jsonOptions))`, where `jsonOptions` has the same settings and `fsOptions` added. -2. To change one type, put `[]` on that type and - call `WithAllowOverride()` on the global options. The transformers read - this attribute. Do not use `JsonFSharpOptions.WithOverrides`: the - serializer applies it, but the transformers do not, so the schema stays - wrong. -3. The attribute does not inherit the global options. Set every option that - the type needs (for example the union tag name) in the attribute. +2. To change one type, use `JsonFSharpOptions.WithOverrides`, or put + `[]` on the type and call `WithAllowOverride()` + on the global options (without it, the attribute is ignored). The + transformers apply both the same way as FSharp.SystemTextJson. +3. Per-type options inherit only the union encoding, and only when they do not + set it. Every other option (for example the union tag name or + `UnwrapOption`) takes the FSharp.SystemTextJson default, not the global + value. Set every option that the type needs. 4. If you add the transformers yourself with `AddOpenApi`, add `fsOptions` to `JsonOptions`, and add the two document transformers `UnionCaseComponentsDocumentTransformer()` and `NullableEnumDocumentTransformer()` last, after your own document transformers. -5. The transformers do not model `WithSkippableOptionFields` or `MapFormat`. - With these options the schema does not match the JSON. +5. The transformers do not model `MapFormat`. With this option the schema + does not match the JSON. ## What the schema shows -- `option` or `voption` record or union field: the inner schema plus `null`, - because `None` and `ValueNone` are written as `null`. Top-level `option` and - `voption`: the inner schema only. +- `option` or `voption` in a record field, a union field or a tuple element: + the inner schema plus `null`, because `None` and `ValueNone` are written as + `null`. Top-level `option` and `voption`: the inner schema only. - With `UnwrapOption` turned off: `option` is `null` or a tagged `Some` object; `voption` is a tagged `ValueSome` or `ValueNone` object. -- Records: a `Skippable<'T>` field is optional. With - `JsonIgnoreCondition.WhenWritingNull`, every field is optional. - `[]` makes a field required. +- Record and named union fields: a `Skippable<'T>` field is optional. An + `option` or `voption` field is optional with + `SkippableOptionFields.Always`, or with `FromJsonSerializerOptions` (the + default) and `JsonIgnoreCondition.WhenWritingNull`. With `WhenWritingNull`, + other fields are optional too. `[]` makes a record field + required. - Unions: the encoding from the options (internal tag, adjacent tag, external tag, untagged, named fields, unwrapped record cases, unwrapped single-field cases, unwrapped single-case unions). With `UnwrapFieldlessTags`, a diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Bootstrap.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Bootstrap.fs index f83abc7..69333cd 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Bootstrap.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Bootstrap.fs @@ -35,7 +35,7 @@ type DependencyExtension() = JsonNodeSchemaTransformer() CollectionsSchemaTransformer() RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) EnumSchemaTransformer() ] diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs index fcd20d3..417d43e 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs @@ -125,3 +125,30 @@ module internal OpenApiSchemaHelpers = SchemaCopy.copyTo normalizedSchema schema return normalizePrimitiveStringCoercion normalizedSchema } + + let getOrCreateFieldSchema + (unwrapOption: bool) + (ctx: OpenApiSchemaTransformerContext) + (ct: CancellationToken) + (t: Type) + : Task = + task { + match t with + | OptionOrValueOptionType innerType when unwrapOption -> + let! innerSchema = getOrCreateDeterministicSchema ctx ct innerType + let optionSchema = OpenApiSchema() + SchemaCopy.copyTo optionSchema innerSchema + addNull optionSchema innerSchema + return optionSchema + | _ -> return! getOrCreateDeterministicSchema ctx ct t + } + + let canSkipField (options: System.Text.Json.JsonSerializerOptions) (fsOptions: JsonFSharpOptions) (t: Type) = + match t with + | OptionOrValueOptionType _ -> + fsOptions.SkippableOptionFields = SkippableOptionFields.Always + || (ignoreNullValues options + && fsOptions.SkippableOptionFields = SkippableOptionFields.FromJsonSerializerOptions) + | _ -> + ignoreNullValues options + || (t.IsGenericType && t.GetGenericTypeDefinition() = typedefof>) diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/FsOptions.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/FsOptions.fs index 0b6e455..f2956ba 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/FsOptions.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/FsOptions.fs @@ -5,14 +5,29 @@ open System.Text.Json.Serialization module internal FsOptions = - let private customOptions (t: Type) = - match t.GetCustomAttributes(typedefof, false) with - | [| atr |] -> - match atr with - | :? IJsonFSharpConverterAttribute as converter -> Some converter.Options + let private tryGetTypeOrGeneric (t: Type) (overrides: Collections.Generic.IDictionary | null) = + match overrides with + | Null -> None + | NonNull overrides -> + match overrides.TryGetValue t with + | true, options -> Some options + | _ when t.IsGenericType -> + match overrides.TryGetValue(t.GetGenericTypeDefinition()) with + | true, options -> Some options + | _ -> None | _ -> None - | _ -> None let getEffectiveFsOptions (t: Type) (fsOptions: JsonFSharpOptions) = - customOptions t |> Option.defaultValue fsOptions + let inheritUnionEncoding (options: JsonFSharpOptions) = + if options.UnionEncoding.HasFlag JsonUnionEncoding.Inherit then + options.WithUnionEncoding(fsOptions.UnionEncoding) + else + options + match tryGetTypeOrGeneric t (fsOptions.Overrides fsOptions) with + | Some options -> inheritUnionEncoding options + | None when fsOptions.AllowOverride -> + match t.GetCustomAttributes(typeof, true) with + | [||] -> fsOptions + | attributes -> inheritUnionEncoding (attributes[0] :?> IJsonFSharpConverterAttribute).Options + | None -> fsOptions diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs index 6bbccb1..16e20f3 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs @@ -62,10 +62,7 @@ type RecordSchemaTransformer(fsOptions: JsonFSharpOptions) = let originalId = schema.Id let originalMetadata = schema.Metadata let fsOptions = FsOptions.getEffectiveFsOptions t fsOptions - let ignoreNulls = OpenApiSchemaHelpers.ignoreNullValues ctx.JsonTypeInfo.Options - let getOrCreateSchema ty = - OpenApiSchemaHelpers.getOrCreateDeterministicSchema ctx ct ty let props = Dictionary(StringComparer.Ordinal) let required = HashSet(StringComparer.Ordinal) @@ -91,27 +88,15 @@ type RecordSchemaTransformer(fsOptions: JsonFSharpOptions) = |> not not explicitlyRequired - && (ignoreNulls || RecordHelpers.isSkippableType p.PropertyType) + && OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options fsOptions p.PropertyType let effectiveType = match p.PropertyType with | RecordHelpers.SkippableType inner -> inner | _ -> p.PropertyType - let propertySchemaTask = - match effectiveType with - | OpenApiSchemaHelpers.OptionOrValueOptionType innerType when unwrapOptionFields -> - task { - let! innerSchema = getOrCreateSchema innerType - - let optionSchema = OpenApiSchema() - SchemaCopy.copyTo optionSchema innerSchema - OpenApiSchemaHelpers.addNull optionSchema innerSchema - return optionSchema - } - | _ -> getOrCreateSchema effectiveType - - let! propertySchema = propertySchemaTask + let! propertySchema = + OpenApiSchemaHelpers.getOrCreateFieldSchema unwrapOptionFields ctx ct effectiveType props[name] <- propertySchema diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs index 3a7808b..4701c1b 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs @@ -8,7 +8,10 @@ open System.Threading.Tasks open Microsoft.AspNetCore.OpenApi open Microsoft.OpenApi -type TupleSchemaTransformer() = +type TupleSchemaTransformer(fsOptions: System.Text.Json.Serialization.JsonFSharpOptions) = + let unwrapOption = + fsOptions.UnionEncoding.HasFlag System.Text.Json.Serialization.JsonUnionEncoding.UnwrapOption + interface IOpenApiSchemaTransformer with member _.TransformAsync(schema: OpenApiSchema, ctx: OpenApiSchemaTransformerContext, ct: CancellationToken) : Task = task { @@ -20,7 +23,7 @@ type TupleSchemaTransformer() = let! elementSchemas = distinctElementTypes - |> Array.map (OpenApiSchemaHelpers.getOrCreateDeterministicSchema ctx ct) + |> Array.map (OpenApiSchemaHelpers.getOrCreateFieldSchema unwrapOption ctx ct) |> Task.WhenAll let elementSchemaRefs = diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs index fc48143..c4c1b5d 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs @@ -174,22 +174,14 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let originalMetadata = schema.Metadata let cases = FSharpType.GetUnionCases t - let ignoreNullValues = OpenApiSchemaHelpers.ignoreNullValues ctx.JsonTypeInfo.Options - let getOrCreateSchema (ty: Type) = OpenApiSchemaHelpers.getOrCreateDeterministicSchema ctx ct ty let getFieldPropertySchema (ty: Type) = - task { - match ty with - | OpenApiSchemaHelpers.OptionOrValueOptionType innerType when unwrapOptionFields -> - let! innerSchema = getOrCreateSchema innerType - let optionSchema = OpenApiSchema() - SchemaCopy.copyTo optionSchema innerSchema - OpenApiSchemaHelpers.addNull optionSchema innerSchema - return optionSchema - | _ -> return! getOrCreateSchema ty - } + OpenApiSchemaHelpers.getOrCreateFieldSchema unwrapOptionFields ctx ct ty + + let canSkipField (ty: Type) = + OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options fsOptions ty let createUnionFieldsObjectSchema (uci: UnionCaseInfo) = task { @@ -203,7 +195,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let! fieldSchema = getFieldPropertySchema fieldInfo.PropertyType props[name] <- fieldSchema - if not ignoreNullValues && not (UnionHelpers.isSkippableType fieldInfo.PropertyType) then + if not (canSkipField fieldInfo.PropertyType) then required.Add(name) |> ignore return @@ -256,8 +248,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = for p in recordProps do let name = UnionHelpers.getPropertyName ctx.JsonTypeInfo.Options p - let canBeSkipped = - ignoreNullValues || UnionHelpers.isSkippableType p.PropertyType + let canBeSkipped = canSkipField p.PropertyType let effectiveType = if UnionHelpers.isSkippableType p.PropertyType then @@ -279,7 +270,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let! fieldSchema = getFieldPropertySchema fieldInfo.PropertyType props[name] <- fieldSchema - if not ignoreNullValues && not (UnionHelpers.isSkippableType fieldInfo.PropertyType) then + if not (canSkipField fieldInfo.PropertyType) then required.Add(name) |> ignore return @@ -330,7 +321,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = || (fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapRecordCases && FSharpType.IsRecord fields[0].PropertyType)) then - getOrCreateSchema fields[0].PropertyType + getFieldPropertySchema fields[0].PropertyType elif fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.NamedFields then createUnionFieldsObjectSchema uci else @@ -350,7 +341,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = else let! payloadSchema = if fields.Length = 1 && fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapSingleFieldCases then - getOrCreateSchema fields[0].PropertyType + getFieldPropertySchema fields[0].PropertyType elif fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.NamedFields then createUnionFieldsObjectSchema uci elif fields.Length = 0 then @@ -397,7 +388,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let! fieldSchemas = distinctFieldTypes - |> Array.map getOrCreateSchema + |> Array.map getFieldPropertySchema |> Task.WhenAll let tagSchema = diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs index 0816cb5..ef4e260 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs @@ -92,7 +92,7 @@ let ``Collections use array and dictionary schemas matching their JSON encoding` OptionSchemaTransformer(fsOptions) CollectionsSchemaTransformer() RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) ]) diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs index 7f05d4f..739a44e 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs @@ -28,6 +28,25 @@ type UnionWithVoption = | WithVoption of maybeV: string voption | WithNumber of n: int +type RecordWithOptionTuple = { [] Pair: string option * int } + +type PositionalOptionUnion = + | PosPair of string option * int + | PosEmpty + +type SingleOptionFieldUnion = + | OnlyOption of string option + | OnlyNumber of int + +type RecordWithNote = + { [] Name: string + [] Note: string option } + +[] +type RecordSkippingNone = + { [] Name: string + [] Note: string option } + let private endpoints : Endpoint list = [ POST [ @@ -78,22 +97,30 @@ let private endpoints : Endpoint list = OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |])) ) ] + POST [ + route "/record-with-option-tuple" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/positional-option-union" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/single-option-field-union" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/record-with-note" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/record-skipping-none" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] ] -let private shippedTransformersFor (fsOptions: JsonFSharpOptions) : IOpenApiSchemaTransformer list = - [ OptionSchemaTransformer(fsOptions) - JsonNodeSchemaTransformer() - CollectionsSchemaTransformer() - RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() - UnionSchemaTransformer(fsOptions) - EnumSchemaTransformer() ] - let private shippedTransformers = shippedTransformersFor fsharpJsonOptions -let private serializeWith (fsOptions: JsonFSharpOptions) value = - JsonSerializer.Serialize(value, fsOptions.ToJsonSerializerOptions()) - let private serialize value = serializeWith fsharpJsonOptions value let private getOptionPropertySchema (document: JsonNode) = @@ -386,3 +413,71 @@ let ``voption property schema matches encoding (WithUnwrapOption disable %valueSomeFieldType.Should().Be("string") } + +let private positionalCases = + [ "internal tag", JsonFSharpOptions.Default().WithUnionInternalTag(), """["PosPair",null,2]""" + "adjacent tag", JsonFSharpOptions.Default(), """{"Case":"PosPair","Fields":[null,2]}""" + "external tag", JsonFSharpOptions.Default().WithUnionExternalTag(), """{"PosPair":[null,2]}""" ] + +[] +let ``option in a tuple element allows null`` () : Task = + task { + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints shippedTransformers) + + let schema = + getRecordPropertySchema builtIn "/record-with-option-tuple" "pair" |> expandSchemaRefs builtIn + + %serialize({ RecordWithOptionTuple.Pair = (None, 1) }).Should().Be("""{"pair":[null,1]}""") + %(allowsNull schema).Should().BeTrue() + } + +[] +let ``option in a positional union field allows null`` () : Task = + task { + for (name, fsOptions, expectedJson) in positionalCases do + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let schema = + getSchemaForPath builtIn "/positional-option-union" |> expandSchemaRefs builtIn + + %(serializeWith fsOptions (PosPair(None, 2))).Should().Be(expectedJson, name) + %(allowsNull schema).Should().BeTrue(name) + } + +[] +let ``option in an unwrapped single-field case allows null`` () : Task = + task { + let fsOptions = JsonFSharpOptions.Default().WithUnionUnwrapSingleFieldCases() + + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let schema = + getSchemaForPath builtIn "/single-option-field-union" |> expandSchemaRefs builtIn + + %(serializeWith fsOptions (OnlyOption None)).Should().Be("""{"Case":"OnlyOption","Fields":null}""") + %(allowsNull schema).Should().BeTrue() + } + +[] +let ``SkippableOptionFields decides whether an option field is required`` () : Task = + task { + let cases = + [ "global Always", fsharpJsonOptions.WithSkippableOptionFields(SkippableOptionFields.Always), "/record-with-note", + serializeWith (fsharpJsonOptions.WithSkippableOptionFields(SkippableOptionFields.Always)) { RecordWithNote.Name = "x"; Note = None }, + """{"name":"x"}""", Set.ofList [ "name" ] + "attribute Always", fsharpJsonOptions, "/record-skipping-none", + serializeWith fsharpJsonOptions { RecordSkippingNone.Name = "x"; Note = None }, + """{"name":"x"}""", Set.ofList [ "name" ] + "default", fsharpJsonOptions, "/record-with-note", + serializeWith fsharpJsonOptions { RecordWithNote.Name = "x"; Note = None }, + """{"name":"x","note":null}""", Set.ofList [ "name"; "note" ] ] + + for (name, fsOptions, path, json, expectedJson, expectedRequired) in cases do + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let record = getSchemaForPath builtIn path |> dereferenceSchema builtIn + + %json.Should().Be(expectedJson, name) + %(requiredNames record).Should().Be(expectedRequired, name) + } + diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiPerTypeOptionsTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiPerTypeOptionsTests.fs index 78cb9c9..147ed9d 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiPerTypeOptionsTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiPerTypeOptionsTests.fs @@ -29,6 +29,15 @@ type ExternalTagUnionPerType = | Fieldless | Pair of string * int +[] +type InheritingShape = + | Circle of radius: float + | Dot + +type OverriddenShape = + | Square of side: float + | NoShape + let private endpoints : Endpoint list = [ POST [ @@ -49,6 +58,14 @@ let private endpoints : Endpoint list = ) ) ] + POST [ + route "/inheriting-shape" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] + POST [ + route "/overridden-shape" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] ] let private getSchemaTypes (schema: JsonNode) = @@ -88,7 +105,7 @@ let ``Per-type JsonFSharpConverterAttribute options shape record and union schem OptionSchemaTransformer(fsOptions) CollectionsSchemaTransformer() RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) ]) @@ -109,3 +126,30 @@ let ``Per-type JsonFSharpConverterAttribute options shape record and union schem %(unionProperties.Contains("Fieldless")).Should().BeTrue() %(unionProperties.Contains("Pair")).Should().BeTrue() } + +let private shapeCases = + let withOverride = + fsharpJsonOptions.WithOverrides( + dict [ typeof, JsonFSharpOptions.InheritUnionEncoding().WithUnionTagName("shape") ] + ) + + [ "attribute inherits the union encoding", fsharpJsonOptions, "/inheriting-shape", + serializeWith fsharpJsonOptions (Circle 1.0), """{"type":"Circle","radius":1}""", "type", "kind" + "WithOverrides applies", withOverride, "/overridden-shape", + serializeWith withOverride (Square 1.0), """{"shape":"Square","side":1}""", "shape", "kind" + "attribute ignored without AllowOverride", fsharpJsonOptions.WithAllowOverride(false), "/inheriting-shape", + serializeWith (fsharpJsonOptions.WithAllowOverride(false)) (Circle 1.0), """{"kind":"Circle","radius":1}""", "kind", "type" ] + +[] +let ``Per-type options merge with the global options like FSharp.SystemTextJson`` () : Task = task { + for (name, fsOptions, path, json, expectedJson, tag, absentTag) in shapeCases do + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let names = getSchemaForPath builtIn path |> expandSchemaRefs builtIn |> collectPropertyNames |> Set.ofSeq + + %json.Should().Be(expectedJson, name) + %(names.Contains tag).Should().BeTrue(name) + %(names.Contains absentTag).Should().BeFalse(name) + %(names.Contains "Fields").Should().BeFalse(name) +} + diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiRecordTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiRecordTests.fs index 4fca3e8..eb123b6 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiRecordTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiRecordTests.fs @@ -95,7 +95,7 @@ let ``Record schema exposes fields, JSON names, and required properties`` () : T OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) ]) let schema = getSchemaForPath builtIn "/record-sample" |> expandSchemaRefs builtIn @@ -125,7 +125,7 @@ let ``Record schema is referenced (not inlined)`` () : Task = task { OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) ]) getSchemaForPath builtIn "/record-sample" |> assertSchemaIsRef @@ -143,7 +143,7 @@ let ``JsonObject record field allows arbitrary object properties`` () : Task = t JsonNodeSchemaTransformer() CollectionsSchemaTransformer() RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) ]) let schema = diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs index 99f94a3..2541fca 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs @@ -227,3 +227,35 @@ let createBuiltInOpenApiApp return app } + +let shippedTransformersFor (fsOptions: JsonFSharpOptions) : IOpenApiSchemaTransformer list = + [ OptionSchemaTransformer(fsOptions) + JsonNodeSchemaTransformer() + CollectionsSchemaTransformer() + RecordSchemaTransformer(fsOptions) + TupleSchemaTransformer(fsOptions) + UnionSchemaTransformer(fsOptions) + EnumSchemaTransformer() ] + +let serializeWith (fsOptions: JsonFSharpOptions) (value: 'T) = + JsonSerializer.Serialize<'T>(value, fsOptions.ToJsonSerializerOptions()) + +let rec allowsNull (node: JsonNode) = + match node with + | :? JsonObject as obj -> + obj + |> Seq.exists (fun kvp -> + match kvp.Key, kvp.Value with + | "type", (:? JsonValue as v) -> v.GetValue() = "null" + | "type", (:? JsonArray as types) -> + types |> Seq.exists (fun v -> not (isNull v) && v.GetValue() = "null") + | _, Null -> false + | _, NonNull value -> allowsNull value) + | :? JsonArray as values -> values |> Seq.exists (fun v -> not (isNull v) && allowsNull v) + | _ -> false + +let requiredNames (schema: JsonNode) = + match schema["required"] with + | :? JsonArray as names -> names |> Seq.map (fun n -> (nonNull n).GetValue()) |> Set.ofSeq + | _ -> Set.empty + diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs index 6b2987c..c2ffa73 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs @@ -52,7 +52,7 @@ let ``Tuple schema is a fixed-length array of its element types`` () : Task = ta OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() + TupleSchemaTransformer(fsOptions) ]) let schema = getSchemaForPath builtIn "/tuple-sample" |> expandSchemaRefs builtIn @@ -81,7 +81,7 @@ let ``Tuple schema is inlined`` () : Task = [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) getSchemaForPath builtIn "/tuple-sample" |> assertSchemaIsInline diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionEncodingTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionEncodingTests.fs index bc35481..f4d8cfa 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionEncodingTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionEncodingTests.fs @@ -39,7 +39,7 @@ let private createTransformers fsOptions = [ OptionSchemaTransformer(fsOptions) :> IOpenApiSchemaTransformer CollectionsSchemaTransformer() :> IOpenApiSchemaTransformer RecordSchemaTransformer(fsOptions) :> IOpenApiSchemaTransformer - TupleSchemaTransformer() :> IOpenApiSchemaTransformer + TupleSchemaTransformer(fsOptions) :> IOpenApiSchemaTransformer UnionSchemaTransformer(fsOptions) :> IOpenApiSchemaTransformer ] let rec private collectPropertyNames (node: JsonNode) = seq { diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionTests.fs index 6e66467..1e5097c 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiUnionTests.fs @@ -443,7 +443,7 @@ let ``Multi-case union schema is referenced (not inlined)`` () : Task = [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) getSchemaForPath builtIn "/union-sample" |> assertSchemaIsRef @@ -463,7 +463,7 @@ let ``Multi-case union branches are referenced (not inlined)`` () : Task = [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) let unionSchema = @@ -496,7 +496,7 @@ let ``Single-case fieldless union schema is inlined as case object`` () : Task = [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) let schema = getResponseSchemaForPath builtIn "/union-single-case-fieldless" 200 @@ -531,7 +531,7 @@ let ``Single-case single-field union schema is unwrapped`` () : Task = [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) let schema = getResponseSchemaForPath builtIn "/union-single-case-single-field" 200 @@ -755,7 +755,7 @@ let ``Generic non-Result unions with nested payloads get stable wrapper and case [ OptionSchemaTransformer(fsOptions) UnionSchemaTransformer(fsOptions) RecordSchemaTransformer(fsOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsOptions) ] ) let wrapperRefResultArray = getResponseSchemaRef builtIn "/union-envelope-result-array" @@ -855,7 +855,7 @@ let ``Optional payload-union property is a single nullable union component`` () [ OptionSchemaTransformer(fsharpJsonOptions) UnionSchemaTransformer(fsharpJsonOptions) RecordSchemaTransformer(fsharpJsonOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsharpJsonOptions) ] ) let unionId = @@ -916,7 +916,7 @@ let ``Optional fieldless-tag union property lists null in its enum`` () : Task = [ OptionSchemaTransformer(fsharpJsonOptions) UnionSchemaTransformer(fsharpJsonOptions) RecordSchemaTransformer(fsharpJsonOptions) - TupleSchemaTransformer() ] + TupleSchemaTransformer(fsharpJsonOptions) ] ) let statusSchema = From c6117bb244cf052f33139f459954fbf792f715af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Krzywizna?= Date: Tue, 24 Nov 2026 12:09:42 +0100 Subject: [PATCH 2/3] [SEL-138] Fix review findings: anyOf for tuple items, per-type option unwrap, record options in unwrapped cases - Tuple and positional case items use anyOf: a value can match more than one element type (a field equal to the case tag, two option elements that are null), which oneOf rejected. - An option or voption field decides UnwrapOption from the options for option<_> or voption<_>, so WithOverrides on option<_> applies to tuple elements and positional fields too. - An unwrapped record case uses the record's own options, layered on the union's, like FSharp.SystemTextJson. - Tests check the specific element schema; each new one fails on the previous commit. Docs name WithOverrideMembers and MapFormat as not supported. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + skills/fsharp-systemtextjson-openapi/SKILL.md | 12 ++-- .../CommonHelpers.fs | 16 +++-- .../Record.fs | 13 ++-- ...tView.FSharp.SystemTextJson.OpenApi.fsproj | 2 +- .../Tuple.fs | 24 ++----- .../Union.fs | 41 +++-------- .../OpenApiCollectionsTests.fs | 2 +- .../OpenApiOptionTests.fs | 71 ++++++++++++++++++- .../OpenApiTestSetup.fs | 30 +++++--- .../OpenApiTupleTests.fs | 2 +- 11 files changed, 128 insertions(+), 86 deletions(-) diff --git a/README.md b/README.md index 3003702..bcb17e5 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ package adds schema and document transformers that read your - enums: string and number encodings, also when nullable - per-type options from `WithOverrides` and `[]`, merged with the global options the same way as FSharp.SystemTextJson + (`WithOverrideMembers` and `MapFormat` are not supported) The package targets .NET 10 and OpenAPI 3.1. diff --git a/skills/fsharp-systemtextjson-openapi/SKILL.md b/skills/fsharp-systemtextjson-openapi/SKILL.md index dd488ad..c333dbd 100644 --- a/skills/fsharp-systemtextjson-openapi/SKILL.md +++ b/skills/fsharp-systemtextjson-openapi/SKILL.md @@ -55,16 +55,18 @@ reads. on the global options (without it, the attribute is ignored). The transformers apply both the same way as FSharp.SystemTextJson. 3. Per-type options inherit only the union encoding, and only when they do not - set it. Every other option (for example the union tag name or - `UnwrapOption`) takes the FSharp.SystemTextJson default, not the global - value. Set every option that the type needs. + set it. Every other option (for example the union tag name) takes the + FSharp.SystemTextJson default, not the global value. Set every option that + the type needs. An `option` or `voption` field follows the options for + `option<_>` or `voption<_>` (global or overridden), never the options of + the record or union that contains it. 4. If you add the transformers yourself with `AddOpenApi`, add `fsOptions` to `JsonOptions`, and add the two document transformers `UnionCaseComponentsDocumentTransformer()` and `NullableEnumDocumentTransformer()` last, after your own document transformers. -5. The transformers do not model `MapFormat`. With this option the schema - does not match the JSON. +5. The transformers do not model `MapFormat` or `WithOverrideMembers`. With + these options the schema does not match the JSON. ## What the schema shows diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs index 417d43e..9f96a62 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs @@ -114,6 +114,9 @@ module internal OpenApiSchemaHelpers = | null -> true | enumValues -> enumValues.Count = 0 + let anyOfSchema (schemas: IOpenApiSchema seq) = + OpenApiSchema(AnyOf = ResizeArray(schemas)) + let getOrCreateDeterministicSchema (ctx: OpenApiSchemaTransformerContext) (ct: CancellationToken) @@ -127,14 +130,16 @@ module internal OpenApiSchemaHelpers = } let getOrCreateFieldSchema - (unwrapOption: bool) + (fsOptions: JsonFSharpOptions) (ctx: OpenApiSchemaTransformerContext) (ct: CancellationToken) (t: Type) : Task = task { match t with - | OptionOrValueOptionType innerType when unwrapOption -> + | OptionOrValueOptionType innerType when + (FsOptions.getEffectiveFsOptions t fsOptions).UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption + -> let! innerSchema = getOrCreateDeterministicSchema ctx ct innerType let optionSchema = OpenApiSchema() SchemaCopy.copyTo optionSchema innerSchema @@ -143,12 +148,13 @@ module internal OpenApiSchemaHelpers = | _ -> return! getOrCreateDeterministicSchema ctx ct t } + let isSkippableType (t: Type) = + t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> + let canSkipField (options: System.Text.Json.JsonSerializerOptions) (fsOptions: JsonFSharpOptions) (t: Type) = match t with | OptionOrValueOptionType _ -> fsOptions.SkippableOptionFields = SkippableOptionFields.Always || (ignoreNullValues options && fsOptions.SkippableOptionFields = SkippableOptionFields.FromJsonSerializerOptions) - | _ -> - ignoreNullValues options - || (t.IsGenericType && t.GetGenericTypeDefinition() = typedefof>) + | _ -> ignoreNullValues options || isSkippableType t diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs index 16e20f3..9c4145b 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs @@ -12,11 +12,8 @@ open Microsoft.OpenApi module private RecordHelpers = - let isSkippableType (t: Type) = - t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> - let (|SkippableType|_|) (t: Type) = - if isSkippableType t then + if OpenApiSchemaHelpers.isSkippableType t then Some(t.GetGenericArguments()[0]) else None @@ -47,8 +44,7 @@ module private RecordHelpers = || (p.GetCustomAttributes(typeof, true) |> Seq.isEmpty |> not)) -type RecordSchemaTransformer(fsOptions: JsonFSharpOptions) = - let unwrapOptionFields = fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption +type RecordSchemaTransformer(globalFsOptions: JsonFSharpOptions) = interface IOpenApiSchemaTransformer with member _.TransformAsync @@ -61,8 +57,7 @@ type RecordSchemaTransformer(fsOptions: JsonFSharpOptions) = // Preserve schema identity so records stay component schemas (not inlined everywhere). let originalId = schema.Id let originalMetadata = schema.Metadata - let fsOptions = FsOptions.getEffectiveFsOptions t fsOptions - + let fsOptions = FsOptions.getEffectiveFsOptions t globalFsOptions let props = Dictionary(StringComparer.Ordinal) let required = HashSet(StringComparer.Ordinal) @@ -96,7 +91,7 @@ type RecordSchemaTransformer(fsOptions: JsonFSharpOptions) = | _ -> p.PropertyType let! propertySchema = - OpenApiSchemaHelpers.getOrCreateFieldSchema unwrapOptionFields ctx ct effectiveType + OpenApiSchemaHelpers.getOrCreateFieldSchema globalFsOptions ctx ct effectiveType props[name] <- propertySchema diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/SelectView.FSharp.SystemTextJson.OpenApi.fsproj b/src/SelectView.FSharp.SystemTextJson.OpenApi/SelectView.FSharp.SystemTextJson.OpenApi.fsproj index 3c897e8..34bc295 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/SelectView.FSharp.SystemTextJson.OpenApi.fsproj +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/SelectView.FSharp.SystemTextJson.OpenApi.fsproj @@ -17,8 +17,8 @@ - + diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs index 4701c1b..18d70cb 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Tuple.fs @@ -2,16 +2,14 @@ namespace SelectView.FSharp.SystemTextJson.OpenApi open System open System.Collections.Generic +open System.Text.Json.Serialization open Microsoft.FSharp.Reflection open System.Threading open System.Threading.Tasks open Microsoft.AspNetCore.OpenApi open Microsoft.OpenApi -type TupleSchemaTransformer(fsOptions: System.Text.Json.Serialization.JsonFSharpOptions) = - let unwrapOption = - fsOptions.UnionEncoding.HasFlag System.Text.Json.Serialization.JsonUnionEncoding.UnwrapOption - +type TupleSchemaTransformer(fsOptions: JsonFSharpOptions) = interface IOpenApiSchemaTransformer with member _.TransformAsync(schema: OpenApiSchema, ctx: OpenApiSchemaTransformerContext, ct: CancellationToken) : Task = task { @@ -23,28 +21,14 @@ type TupleSchemaTransformer(fsOptions: System.Text.Json.Serialization.JsonFSharp let! elementSchemas = distinctElementTypes - |> Array.map (OpenApiSchemaHelpers.getOrCreateFieldSchema unwrapOption ctx ct) + |> Array.map (OpenApiSchemaHelpers.getOrCreateFieldSchema fsOptions ctx ct) |> Task.WhenAll let elementSchemaRefs = elementSchemas |> Array.map (fun schema -> schema :> IOpenApiSchema) - let hasPlainString = - elementSchemaRefs - |> Seq.map OpenApiSchemaHelpers.unwrapReferenceSchema - |> Seq.exists (fun s -> s.Type = Nullable(JsonSchemaType.String) && OpenApiSchemaHelpers.enumIsEmpty s) - - let hasEnumString = - elementSchemaRefs - |> Seq.map OpenApiSchemaHelpers.unwrapReferenceSchema - |> Seq.exists (fun s -> s.Type = Nullable(JsonSchemaType.String) && not (OpenApiSchemaHelpers.enumIsEmpty s)) - - let itemUnionSchema = - if hasPlainString && hasEnumString then - OpenApiSchema(AnyOf = ResizeArray(elementSchemaRefs)) - else - OpenApiSchema(OneOf = ResizeArray(elementSchemaRefs)) + let itemUnionSchema = OpenApiSchemaHelpers.anyOfSchema elementSchemaRefs let tupleSchema = OpenApiSchema( diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs index c4c1b5d..464dba8 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs @@ -22,9 +22,6 @@ module private UnionHelpers = let isFSharpListType (t: Type) = t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> - let isSkippableType (t: Type) = - t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> - let getJsonFieldNames (getAttributes: Type -> obj[]) = getAttributes typeof |> Seq.choose (function @@ -153,13 +150,12 @@ module private UnionCasePromotionPlan = | Null -> () | NonNull metadata -> metadata.Remove(MetadataKey) |> ignore -type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = - let unwrapOptionFields = fsOptions.UnionEncoding.HasFlag JsonUnionEncoding.UnwrapOption +type UnionSchemaTransformer(globalFsOptions: JsonFSharpOptions) = interface IOpenApiSchemaTransformer with member _.TransformAsync(schema: OpenApiSchema, ctx: OpenApiSchemaTransformerContext, ct: CancellationToken) : Task = let t = ctx.JsonTypeInfo.Type - let fsOptions = FsOptions.getEffectiveFsOptions t fsOptions + let fsOptions = FsOptions.getEffectiveFsOptions t globalFsOptions if not (FSharpType.IsUnion(t)) @@ -178,10 +174,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = OpenApiSchemaHelpers.getOrCreateDeterministicSchema ctx ct ty let getFieldPropertySchema (ty: Type) = - OpenApiSchemaHelpers.getOrCreateFieldSchema unwrapOptionFields ctx ct ty - - let canSkipField (ty: Type) = - OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options fsOptions ty + OpenApiSchemaHelpers.getOrCreateFieldSchema globalFsOptions ctx ct ty let createUnionFieldsObjectSchema (uci: UnionCaseInfo) = task { @@ -195,7 +188,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let! fieldSchema = getFieldPropertySchema fieldInfo.PropertyType props[name] <- fieldSchema - if not (canSkipField fieldInfo.PropertyType) then + if not (OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options fsOptions fieldInfo.PropertyType) then required.Add(name) |> ignore return @@ -240,18 +233,20 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = && FSharpType.IsRecord fields[0].PropertyType then let recordType = fields[0].PropertyType + let recordFsOptions = FsOptions.getEffectiveFsOptions recordType fsOptions let recordProps = - UnionHelpers.getRecordProperties fsOptions recordType + UnionHelpers.getRecordProperties recordFsOptions recordType |> Array.filter (fun p -> p.GetCustomAttributes(typeof, true) |> Array.isEmpty) for p in recordProps do let name = UnionHelpers.getPropertyName ctx.JsonTypeInfo.Options p - let canBeSkipped = canSkipField p.PropertyType + let canBeSkipped = + OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options recordFsOptions p.PropertyType let effectiveType = - if UnionHelpers.isSkippableType p.PropertyType then + if OpenApiSchemaHelpers.isSkippableType p.PropertyType then p.PropertyType.GetGenericArguments()[0] else p.PropertyType @@ -270,7 +265,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let! fieldSchema = getFieldPropertySchema fieldInfo.PropertyType props[name] <- fieldSchema - if not (canSkipField fieldInfo.PropertyType) then + if not (OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options fsOptions fieldInfo.PropertyType) then required.Add(name) |> ignore return @@ -397,21 +392,7 @@ type UnionSchemaTransformer(fsOptions: JsonFSharpOptions) = let elementSchemas = Array.append [| tagSchema |] (fieldSchemas |> Array.map (fun x -> x :> IOpenApiSchema)) - let hasPlainString = - elementSchemas - |> Seq.map OpenApiSchemaHelpers.unwrapReferenceSchema - |> Seq.exists (fun s -> s.Type = Nullable(JsonSchemaType.String) && OpenApiSchemaHelpers.enumIsEmpty s) - - let hasEnumString = - elementSchemas - |> Seq.map OpenApiSchemaHelpers.unwrapReferenceSchema - |> Seq.exists (fun s -> s.Type = Nullable(JsonSchemaType.String) && not (OpenApiSchemaHelpers.enumIsEmpty s)) - - let itemUnionSchema = - if hasPlainString && hasEnumString then - OpenApiSchema(AnyOf = ResizeArray(elementSchemas)) - else - OpenApiSchema(OneOf = ResizeArray(elementSchemas)) + let itemUnionSchema = OpenApiSchemaHelpers.anyOfSchema elementSchemas let tupleSchema = OpenApiSchema( diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs index ef4e260..59b993d 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiCollectionsTests.fs @@ -122,7 +122,7 @@ let ``Collections use array and dictionary schemas matching their JSON encoding` %((entryTuple["maxItems"] :?> JsonValue).GetValue()).Should().Be(2) let entryItemTypes = - entryTuple["items"]["oneOf"] :?> JsonArray + entryTuple["items"]["anyOf"] :?> JsonArray |> Seq.collect getSchemaTypes |> Set.ofSeq diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs index 739a44e..7a0150e 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs @@ -47,6 +47,10 @@ type RecordSkippingNone = { [] Name: string [] Note: string option } +type UnwrappedRecordCase = + | Wrapped of RecordSkippingNone + | Bare of n: int + let private endpoints : Endpoint list = [ POST [ @@ -117,6 +121,10 @@ let private endpoints : Endpoint list = route "/record-skipping-none" (text "ok") |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) ] + POST [ + route "/unwrapped-record-case" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] ] let private shippedTransformers = shippedTransformersFor fsharpJsonOptions @@ -427,8 +435,10 @@ let ``option in a tuple element allows null`` () : Task = let schema = getRecordPropertySchema builtIn "/record-with-option-tuple" "pair" |> expandSchemaRefs builtIn + let alternatives = itemAlternatives schema + %serialize({ RecordWithOptionTuple.Pair = (None, 1) }).Should().Be("""{"pair":[null,1]}""") - %(allowsNull schema).Should().BeTrue() + %(alternatives |> List.map schemaTypes |> Set.ofList).Should().Be(Set.ofList [ Set.ofList [ "string"; "null" ]; Set.singleton "integer" ]) } [] @@ -440,8 +450,11 @@ let ``option in a positional union field allows null`` () : Task = let schema = getSchemaForPath builtIn "/positional-option-union" |> expandSchemaRefs builtIn + let alternatives = arraySchemasUnder schema |> List.collect itemAlternatives |> List.map schemaTypes + %(serializeWith fsOptions (PosPair(None, 2))).Should().Be(expectedJson, name) - %(allowsNull schema).Should().BeTrue(name) + %(alternatives |> List.contains (Set.ofList [ "string"; "null" ])).Should().BeTrue(name) + %(alternatives |> List.contains (Set.singleton "integer")).Should().BeTrue(name) } [] @@ -454,8 +467,14 @@ let ``option in an unwrapped single-field case allows null`` () : Task = let schema = getSchemaForPath builtIn "/single-option-field-union" |> expandSchemaRefs builtIn + let fieldsTypes = + getJsonPath schema [ "oneOf" ] :?> JsonArray + |> Seq.map nonNull + |> Seq.find (fun case -> (getJsonPath case [ "properties"; "Case"; "enum" ]).[0].GetValue() = "OnlyOption") + |> fun case -> getJsonPath case [ "properties"; "Fields" ] |> schemaTypes + %(serializeWith fsOptions (OnlyOption None)).Should().Be("""{"Case":"OnlyOption","Fields":null}""") - %(allowsNull schema).Should().BeTrue() + %fieldsTypes.Should().Be(Set.ofList [ "string"; "null" ]) } [] @@ -481,3 +500,49 @@ let ``SkippableOptionFields decides whether an option field is required`` () : T %(requiredNames record).Should().Be(expectedRequired, name) } +[] +let ``a string field equal to the case tag still matches the positional case schema`` () : Task = + task { + let fsOptions = JsonFSharpOptions.Default().WithUnionInternalTag() + + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let caseArrays = getSchemaForPath builtIn "/positional-option-union" |> expandSchemaRefs builtIn |> arraySchemasUnder + + %(serializeWith fsOptions (PosPair(Some "PosPair", 2))).Should().Be("""["PosPair","PosPair",2]""") + %(caseArrays |> List.forall (fun a -> isNull ((nonNull a.["items"]).["oneOf"]))).Should().BeTrue() + } + +[] +let ``an option override applies to tuple elements`` () : Task = + task { + let fsOptions = + fsharpJsonOptions.WithOverrides(dict [ typedefof>, JsonFSharpOptions.Default().WithUnwrapOption(false) ]) + + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints (shippedTransformersFor fsOptions)) + + let schema = + getRecordPropertySchema builtIn "/record-with-option-tuple" "pair" |> expandSchemaRefs builtIn + + let alternatives = itemAlternatives schema |> List.map schemaTypes + + %(serializeWith fsOptions { RecordWithOptionTuple.Pair = (Some "a", 1) }).Should().Be("""{"pair":[{"Case":"Some","Fields":["a"]},1]}""") + %(alternatives |> Set.ofList).Should().Be(Set.ofList [ Set.ofList [ "object"; "null" ]; Set.singleton "integer" ]) + } + +[] +let ``an unwrapped record case uses the record's own SkippableOptionFields`` () : Task = + task { + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints shippedTransformers) + + let caseSchema = + getSchemaForPath builtIn "/unwrapped-record-case" + |> expandSchemaRefs builtIn + |> fun union -> getJsonPath union [ "oneOf" ] :?> JsonArray + |> Seq.map nonNull + |> Seq.find (fun case -> not (isNull (getJsonPath case [ "properties" ]).["name"])) + + %serialize(Wrapped { RecordSkippingNone.Name = "x"; Note = None }).Should().Be("""{"kind":"Wrapped","name":"x"}""") + %(requiredNames caseSchema).Should().Be(Set.ofList [ "kind"; "name" ]) + } + diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs index 2541fca..9fe305d 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTestSetup.fs @@ -240,19 +240,27 @@ let shippedTransformersFor (fsOptions: JsonFSharpOptions) : IOpenApiSchemaTransf let serializeWith (fsOptions: JsonFSharpOptions) (value: 'T) = JsonSerializer.Serialize<'T>(value, fsOptions.ToJsonSerializerOptions()) -let rec allowsNull (node: JsonNode) = +let itemAlternatives (arraySchema: JsonNode) = + match arraySchema["items"] with + | :? JsonObject as items -> + match items["anyOf"] with + | :? JsonArray as alternatives -> alternatives |> Seq.map nonNull |> List.ofSeq + | _ -> [ items ] + | _ -> failwith $"Expected items in {arraySchema.ToJsonString()}" + +let schemaTypes (schema: JsonNode) = + match schema["type"] with + | :? JsonValue as v -> Set.singleton (v.GetValue()) + | :? JsonArray as types -> types |> Seq.map (fun v -> (nonNull v).GetValue()) |> Set.ofSeq + | _ -> Set.empty + +let rec arraySchemasUnder (node: JsonNode) : JsonNode list = match node with | :? JsonObject as obj -> - obj - |> Seq.exists (fun kvp -> - match kvp.Key, kvp.Value with - | "type", (:? JsonValue as v) -> v.GetValue() = "null" - | "type", (:? JsonArray as types) -> - types |> Seq.exists (fun v -> not (isNull v) && v.GetValue() = "null") - | _, Null -> false - | _, NonNull value -> allowsNull value) - | :? JsonArray as values -> values |> Seq.exists (fun v -> not (isNull v) && allowsNull v) - | _ -> false + let self = if schemaTypes node = Set.singleton "array" && not (isNull obj["items"]) then [ node ] else [] + self @ (obj |> Seq.toList |> List.collect (fun kvp -> match kvp.Value with | Null -> [] | NonNull v -> arraySchemasUnder v)) + | :? JsonArray as values -> values |> Seq.toList |> List.collect (fun v -> match v with | Null -> [] | NonNull v -> arraySchemasUnder v) + | _ -> [] let requiredNames (schema: JsonNode) = match schema["required"] with diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs index c2ffa73..20507ce 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiTupleTests.fs @@ -61,7 +61,7 @@ let ``Tuple schema is a fixed-length array of its element types`` () : Task = ta %((schema["minItems"] :?> JsonValue).GetValue()).Should().Be(2) %((schema["maxItems"] :?> JsonValue).GetValue()).Should().Be(2) - let itemAlternatives = schema["items"]["oneOf"] :?> JsonArray + let itemAlternatives = schema["items"]["anyOf"] :?> JsonArray let itemTypes = itemAlternatives |> Seq.collect getSchemaTypes |> Set.ofSeq From 2e07ea402b378c05928f320c5dce60a7f461a741 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Krzywizna?= Date: Tue, 24 Nov 2026 12:12:34 +0100 Subject: [PATCH 3/3] [SEL-138] Review notes: SKILL wording for option fields, tuple of two options test, drop dead helpers Co-Authored-By: Claude Opus 5.5 --- skills/fsharp-systemtextjson-openapi/SKILL.md | 5 +++-- .../CommonHelpers.fs | 16 +++------------- .../Record.fs | 11 +---------- .../Union.fs | 8 +------- .../OpenApiOptionTests.fs | 19 +++++++++++++++++++ 5 files changed, 27 insertions(+), 32 deletions(-) diff --git a/skills/fsharp-systemtextjson-openapi/SKILL.md b/skills/fsharp-systemtextjson-openapi/SKILL.md index c333dbd..6690955 100644 --- a/skills/fsharp-systemtextjson-openapi/SKILL.md +++ b/skills/fsharp-systemtextjson-openapi/SKILL.md @@ -57,8 +57,9 @@ reads. 3. Per-type options inherit only the union encoding, and only when they do not set it. Every other option (for example the union tag name) takes the FSharp.SystemTextJson default, not the global value. Set every option that - the type needs. An `option` or `voption` field follows the options for - `option<_>` or `voption<_>` (global or overridden), never the options of + the type needs. An `option` or `voption` field takes `UnwrapOption` from + the options for `option<_>` or `voption<_>` (global or overridden). + Whether a `None` field is left out follows the `SkippableOptionFields` of the record or union that contains it. 4. If you add the transformers yourself with `AddOpenApi`, add `fsOptions` to `JsonOptions`, and add the two document transformers diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs index 9f96a62..b7ecf39 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/CommonHelpers.fs @@ -101,19 +101,6 @@ module internal OpenApiSchemaHelpers = Enum = ResizeArray([ enumValue ]) ) - let rec unwrapReferenceSchema (schema: IOpenApiSchema) : IOpenApiSchema = - match schema with - | :? OpenApiSchemaReference as schemaReference -> - match schemaReference.Target with - | NonNull target -> unwrapReferenceSchema target - | Null -> schema - | _ -> schema - - let enumIsEmpty (schema: IOpenApiSchema) = - match schema.Enum with - | null -> true - | enumValues -> enumValues.Count = 0 - let anyOfSchema (schemas: IOpenApiSchema seq) = OpenApiSchema(AnyOf = ResizeArray(schemas)) @@ -151,6 +138,9 @@ module internal OpenApiSchemaHelpers = let isSkippableType (t: Type) = t.IsGenericType && t.GetGenericTypeDefinition() = typedefof> + let skippableInner (t: Type) = + if isSkippableType t then t.GetGenericArguments()[0] else t + let canSkipField (options: System.Text.Json.JsonSerializerOptions) (fsOptions: JsonFSharpOptions) (t: Type) = match t with | OptionOrValueOptionType _ -> diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs index 9c4145b..6d41708 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Record.fs @@ -12,12 +12,6 @@ open Microsoft.OpenApi module private RecordHelpers = - let (|SkippableType|_|) (t: Type) = - if OpenApiSchemaHelpers.isSkippableType t then - Some(t.GetGenericArguments()[0]) - else - None - let getRecordProperties (fsOptions: JsonFSharpOptions) (recordType: Type) = let fields = FSharpType.GetRecordFields(recordType, true) @@ -85,10 +79,7 @@ type RecordSchemaTransformer(globalFsOptions: JsonFSharpOptions) = not explicitlyRequired && OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options fsOptions p.PropertyType - let effectiveType = - match p.PropertyType with - | RecordHelpers.SkippableType inner -> inner - | _ -> p.PropertyType + let effectiveType = OpenApiSchemaHelpers.skippableInner p.PropertyType let! propertySchema = OpenApiSchemaHelpers.getOrCreateFieldSchema globalFsOptions ctx ct effectiveType diff --git a/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs b/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs index 464dba8..c8b1e3f 100644 --- a/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs +++ b/src/SelectView.FSharp.SystemTextJson.OpenApi/Union.fs @@ -245,13 +245,7 @@ type UnionSchemaTransformer(globalFsOptions: JsonFSharpOptions) = let canBeSkipped = OpenApiSchemaHelpers.canSkipField ctx.JsonTypeInfo.Options recordFsOptions p.PropertyType - let effectiveType = - if OpenApiSchemaHelpers.isSkippableType p.PropertyType then - p.PropertyType.GetGenericArguments()[0] - else - p.PropertyType - - let! fieldSchema = getFieldPropertySchema effectiveType + let! fieldSchema = getFieldPropertySchema (OpenApiSchemaHelpers.skippableInner p.PropertyType) props[name] <- fieldSchema diff --git a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs index 7a0150e..b38d9fe 100644 --- a/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs +++ b/tests/SelectView.FSharp.SystemTextJson.OpenApi.Tests/OpenApiOptionTests.fs @@ -30,6 +30,8 @@ type UnionWithVoption = type RecordWithOptionTuple = { [] Pair: string option * int } +type RecordWithTwoOptions = { [] Pair: string option * int option } + type PositionalOptionUnion = | PosPair of string option * int | PosEmpty @@ -105,6 +107,10 @@ let private endpoints : Endpoint list = route "/record-with-option-tuple" (text "ok") |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) ] + POST [ + route "/record-with-two-options" (text "ok") + |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) + ] POST [ route "/positional-option-union" (text "ok") |> addOpenApi(OpenApiConfig(requestBody = RequestBody(typeof, contentTypes = [| "application/json" |]))) @@ -511,6 +517,7 @@ let ``a string field equal to the case tag still matches the positional case sch %(serializeWith fsOptions (PosPair(Some "PosPair", 2))).Should().Be("""["PosPair","PosPair",2]""") %(caseArrays |> List.forall (fun a -> isNull ((nonNull a.["items"]).["oneOf"]))).Should().BeTrue() + %(caseArrays |> List.exists (fun a -> itemAlternatives a |> List.map schemaTypes |> List.contains (Set.ofList [ "string"; "null" ]))).Should().BeTrue() } [] @@ -546,3 +553,15 @@ let ``an unwrapped record case uses the record's own SkippableOptionFields`` () %(requiredNames caseSchema).Should().Be(Set.ofList [ "kind"; "name" ]) } +[] +let ``a null that matches two option elements uses anyOf`` () : Task = + task { + let! builtIn = fetchOpenApiJson (fun () -> createBuiltInOpenApiApp endpoints shippedTransformers) + + let schema = + getRecordPropertySchema builtIn "/record-with-two-options" "pair" |> expandSchemaRefs builtIn + + %serialize({ RecordWithTwoOptions.Pair = (None, None) }).Should().Be("""{"pair":[null,null]}""") + %(itemAlternatives schema |> List.map schemaTypes |> Set.ofList).Should().Be(Set.ofList [ Set.ofList [ "string"; "null" ]; Set.ofList [ "integer"; "null" ] ]) + } +