diff --git a/.changesets/1794266812-8cefc478.yaml b/.changesets/1794266812-8cefc478.yaml new file mode 100644 index 000000000..06ce173bd --- /dev/null +++ b/.changesets/1794266812-8cefc478.yaml @@ -0,0 +1,10 @@ +id: 1794266812-8cefc478 +features: + - core +targets: + - csharp +type: fix +bump: patch +description: send union-typed fields in form-urlencoded and multipart request bodies +author: 2ynn +date: "2026-11-09" diff --git a/templates/perms.go b/templates/perms.go index 2cc4923d4..8ca8cde1f 100644 --- a/templates/perms.go +++ b/templates/perms.go @@ -492,6 +492,7 @@ var fileMode = map[string]fs.FileMode{ "templates/csharp/tests/primary/ErrorsShould.cs": 0o644, "templates/csharp/tests/primary/EventStreamAdditionalShould.cs": 0o644, "templates/csharp/tests/primary/FlatteningShould.cs": 0o644, + "templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs": 0o644, "templates/csharp/tests/primary/GlobalsAdditionalShould.cs": 0o644, "templates/csharp/tests/primary/HeadersShould.cs": 0o644, "templates/csharp/tests/primary/Helpers.cs": 0o644, diff --git a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl index d9b5a2805..b206a5165 100644 --- a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl +++ b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/RequestBodySerializer.cs.stmpl @@ -7,6 +7,7 @@ namespace {{getScopeNamespace "utils"}} using System.Net.Http; using System.Reflection; using System.Text; + using Newtonsoft.Json.Linq; internal class RequestBodySerializer @@ -195,7 +196,7 @@ namespace {{getScopeNamespace "utils"}} form.Add(key, new List()); } - form[key].Add(Utilities.ValueToString(((IDictionary)request)[key])); + form[key].Add(Utilities.ValueToString(UnwrapUnion(((IDictionary)request)[key]))); } } else if (Utilities.IsList(request)) @@ -207,7 +208,7 @@ namespace {{getScopeNamespace "utils"}} form.Add(requestFieldName, new List()); } - form[requestFieldName].Add(Utilities.ValueToString(item)); + form[requestFieldName].Add(Utilities.ValueToString(UnwrapUnion(item))); } } else @@ -303,26 +304,35 @@ namespace {{getScopeNamespace "utils"}} metadata.Name ?? prop.Name ); } - else if (Utilities.IsList(value)) + else { - var values = new List(); - - foreach (var item in (IList)value) + var formValue = UnwrapUnion(value); + if (formValue == null) { - values.Add(Utilities.ValueToString(item)); + continue; } - foreach (var val in values) + if (Utilities.IsList(formValue)) { - formData.Add(new StringContent(val), metadata.Name ?? prop.Name); + var values = new List(); + + foreach (var item in (IList)formValue) + { + values.Add(Utilities.ValueToString(UnwrapUnion(item))); + } + + foreach (var val in values) + { + formData.Add(new StringContent(val), metadata.Name ?? prop.Name); + } + } + else + { + formData.Add( + new StringContent(Utilities.ValueToString(formValue)), + metadata.Name ?? prop.Name + ); } - } - else - { - formData.Add( - new StringContent(Utilities.ValueToString(value)), - metadata.Name ?? prop.Name - ); } } @@ -348,7 +358,15 @@ namespace {{getScopeNamespace "utils"}} ref Dictionary> form ) { - if (Utilities.IsClass(value)) + if (Utilities.IsUnionWrapper(value.GetType())) + { + var variant = UnwrapUnion(value); + if (variant != null) + { + SerializeFormValue(fieldName, explode, variant, ref form); + } + } + else if (Utilities.IsClass(value)) { if (Utilities.IsDate(value)) { @@ -367,8 +385,8 @@ namespace {{getScopeNamespace "utils"}} foreach (var prop in props) { - var val = {{ templateGetPropValue "value" }}; - if (val == null) + var propValue = {{ templateGetPropValue "value" }}; + if (propValue == null) { continue; } @@ -379,6 +397,32 @@ namespace {{getScopeNamespace "utils"}} continue; } + if (metadata.Json) + { + var json = Utilities.SerializeJSON(propValue); + if (explode) + { + if (!form.ContainsKey(metadata.Name)) + { + form[metadata.Name] = new List(); + } + + form[metadata.Name].Add(json); + } + else + { + items.Add($"{metadata.Name},{json}"); + } + + continue; + } + + var val = UnwrapUnion(propValue); + if (val == null) + { + continue; + } + if (explode) { if (!form.ContainsKey(metadata.Name)) @@ -390,7 +434,7 @@ namespace {{getScopeNamespace "utils"}} { foreach(var item in (IEnumerable)val) { - form[metadata.Name].Add(Utilities.ValueToString(item)); + form[metadata.Name].Add(Utilities.ValueToString(UnwrapUnion(item))); } } else @@ -404,7 +448,7 @@ namespace {{getScopeNamespace "utils"}} { foreach(var item in (IEnumerable)val) { - items.Add($"{metadata.Name},{Utilities.ValueToString(item)}"); + items.Add($"{metadata.Name},{Utilities.ValueToString(UnwrapUnion(item))}"); } } else @@ -446,12 +490,12 @@ namespace {{getScopeNamespace "utils"}} } form[key].Add( - Utilities.ValueToString(((IDictionary)value)[key]) + Utilities.ValueToString(UnwrapUnion(((IDictionary)value)[key])) ); } else { - items.Add($"{key},{Utilities.ValueToString(((IDictionary)value)[key])}"); + items.Add($"{key},{Utilities.ValueToString(UnwrapUnion(((IDictionary)value)[key]))}"); } } @@ -474,11 +518,11 @@ namespace {{getScopeNamespace "utils"}} { if (explode) { - values.Add(Utilities.ValueToString(item)); + values.Add(Utilities.ValueToString(UnwrapUnion(item))); } else { - items.Add(Utilities.ValueToString(item)); + items.Add(Utilities.ValueToString(UnwrapUnion(item))); } } @@ -508,6 +552,48 @@ namespace {{getScopeNamespace "utils"}} } } + private static object? UnwrapUnion(object? value) + { + while (value != null && Utilities.IsUnionWrapper(value.GetType())) + { + value = GetUnionVariantValue(value); + } + + return value; + } + + private static object? GetUnionVariantValue(object union) + { + object? unknownValue = null; + + foreach (var prop in union.GetType().GetProperties()) + { + var metadata = prop.GetCustomAttribute()?.GetFormMetadata(); + if (metadata == null) + { + if (prop.PropertyType == typeof(JToken) && prop.GetValue(union) is JValue raw) + { + unknownValue = raw.Value; + } + + continue; + } + + if (metadata.Name != "") + { + continue; + } + + var val = {{ templateGetPropValue "union" }}; + if (val != null) + { + return val; + } + } + + return unknownValue; + } + private static (string fileName, byte[] content) ExtractFileProperties(PropertyInfo[] fileProps, object fileObject) { byte[]? content = null; diff --git a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/UnionDeserializer.cs.stmpl b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/UnionDeserializer.cs.stmpl index 79e23c59b..0ab088816 100644 --- a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/UnionDeserializer.cs.stmpl +++ b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/UnionDeserializer.cs.stmpl @@ -140,7 +140,7 @@ namespace {{getScopeNamespace "utils"}} private static bool PreCheck(JToken json, Type type) { if (json.Type != JTokenType.Object) return true; - if (IsUnionWrapper(type)) return true; + if (Utilities.IsUnionWrapper(type)) return true; var jo = (JObject)json; foreach (var (prop, attr) in EnumerateJsonProperties(type)) @@ -202,7 +202,7 @@ namespace {{getScopeNamespace "utils"}} return; } - if (IsUnionWrapper(type) && value != null) + if (Utilities.IsUnionWrapper(type) && value != null) { var (variantType, variantValue) = FindActiveVariant(type, value); if (variantValue != null) @@ -392,23 +392,12 @@ namespace {{getScopeNamespace "utils"}} return t; } - // A union wrapper is a class generated by speakeasy that carries the - // [JsonConverter(typeof(Self.SelfConverter))] attribute. Its variant - // properties carry no [JsonProperty] (only [SpeakeasyMetadata]). - private static bool IsUnionWrapper(Type type) - { - var attr = type.GetCustomAttribute(); - if (attr == null) return false; - return attr.ConverterType != null - && attr.ConverterType.DeclaringType == type; - } - {{- if hasAnyOpenUnion}} // True when the value is an open union wrapper that fell back to its Unknown sentinel private static bool IsUnknownUnionValue(Type type, object? value) { - if (value == null || !IsUnionWrapper(type)) return false; + if (value == null || !Utilities.IsUnionWrapper(type)) return false; return value is IOpenUnion openUnion && openUnion.IsUnknown(); } {{- end}} diff --git a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/Utilities.cs.stmpl b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/Utilities.cs.stmpl index 163f96c96..96533e8d8 100644 --- a/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/Utilities.cs.stmpl +++ b/templates/templates/csharp/auxiliary/{{ getSDKTopLevelFolder }}/Utils/Utilities.cs.stmpl @@ -181,6 +181,17 @@ namespace {{getScopeNamespace "utils"}} public static bool IsOpenEnum(object? o) => o is IOpenEnum; + // A union wrapper is a class generated by speakeasy that carries the + // [JsonConverter(typeof(Self.SelfConverter))] attribute. Its variant + // properties carry no [JsonProperty] (only [SpeakeasyMetadata]). + public static bool IsUnionWrapper(Type type) + { + var attr = Attribute.GetCustomAttribute(type, typeof(JsonConverterAttribute)) as JsonConverterAttribute; + if (attr == null) return false; + return attr.ConverterType != null + && attr.ConverterType.DeclaringType == type; + } + public static bool IsClass(object? o) { if (o == null) diff --git a/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs b/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs new file mode 100644 index 000000000..28b75e260 --- /dev/null +++ b/templates/templates/csharp/tests/primary/FormUnionFieldsAdditionalShould.cs @@ -0,0 +1,292 @@ +#nullable enable +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Newtonsoft.Json.Linq; +using Openapi; +using Openapi.Models.Shared; +using Xunit; + +public class FormUnionFieldsAdditionalShould +{ + private const string FormExplodedArrayKeySuffix = "[]"; + + [Fact] + public async Task SendStringEnumAndJsonVariants() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionFieldsAsync(new FormUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateStr("abc"), + StringOrArrayUnion = FormUnionStringOrArray.CreateStr("solo"), + EnumOrBooleanUnion = FormUnionEnumOrBoolean.CreateFormUnionEnum(FormUnionEnum.Second), + ArrayOfUnion = new List() + { + FormUnionStringOrInteger.CreateStr("x"), + FormUnionStringOrInteger.CreateInteger(3), + }, + StringOrArrayOfUnion = FormUnionStringOrArrayOfUnion.CreateStr("plain"), + NullableUnion = FormUnionNullable.CreateNull(), + JsonUnion = FormUnionObjectOrString.CreateFormUnionObject(new FormUnionObject() + { + Label = "x", + Count = 1, + }), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("abc", form["scalarUnion"]); + Assert.Equal("solo", form["stringOrArrayUnion"]); + Assert.Equal("second", form["enumOrBooleanUnion"]); + Assert.Equal( + new List() { "x", "3" }, + form[$"arrayOfUnion{FormExplodedArrayKeySuffix}"] + ); + Assert.Equal("plain", form["stringOrArrayOfUnion"]); + Assert.True(JToken.DeepEquals( + JObject.Parse("{\"label\":\"x\",\"count\":1}"), + JObject.Parse((string)form["jsonUnion"]) + )); + Assert.False(form.ContainsKey("nullableUnion")); + Assert.False(form.ContainsKey("optionalUnion")); + Assert.Equal(6, form.Count); + } + + [Fact] + public async Task SendIntegerArrayAndBooleanVariants() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionFieldsAsync(new FormUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateInteger(42), + StringOrArrayUnion = FormUnionStringOrArray.CreateArrayOfStr(new List() { "a", "b" }), + EnumOrBooleanUnion = FormUnionEnumOrBoolean.CreateBoolean(true), + StringOrArrayOfUnion = FormUnionStringOrArrayOfUnion.CreateArrayOfFormUnionIntegerOrBoolean( + new List() + { + FormUnionIntegerOrBoolean.CreateInteger(1), + FormUnionIntegerOrBoolean.CreateBoolean(true), + } + ), + NullableUnion = FormUnionNullable.CreateInteger(7), + OptionalUnion = FormUnionStringOrInteger.CreateStr("set"), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("42", form["scalarUnion"]); + Assert.Equal( + new List() { "a", "b" }, + form[$"stringOrArrayUnion{FormExplodedArrayKeySuffix}"] + ); + Assert.Equal("true", form["enumOrBooleanUnion"]); + Assert.Equal( + new List() { "1", "true" }, + form[$"stringOrArrayOfUnion{FormExplodedArrayKeySuffix}"] + ); + Assert.Equal("7", form["nullableUnion"]); + Assert.Equal("set", form["optionalUnion"]); + Assert.False(form.ContainsKey("jsonUnion")); + Assert.Equal(6, form.Count); + } + + [Fact] + public async Task SendDefaultValuesAndSingleElementArrays() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionFieldsAsync(new FormUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateInteger(0), + StringOrArrayUnion = FormUnionStringOrArray.CreateArrayOfStr(new List() { "only" }), + EnumOrBooleanUnion = FormUnionEnumOrBoolean.CreateBoolean(false), + ArrayOfUnion = new List() + { + FormUnionStringOrInteger.CreateInteger(0), + }, + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("0", form["scalarUnion"]); + Assert.Equal("only", form["stringOrArrayUnion"]); + Assert.Equal("false", form["enumOrBooleanUnion"]); + Assert.Equal("0", form["arrayOfUnion"]); + Assert.Equal(4, form.Count); + } + + [Theory] + [InlineData("\"raw\"", "raw")] + [InlineData("7", "7")] + [InlineData("true", "true")] + public async Task SendPrimitiveUnknownValueOfOpenUnion(string rawJson, string expected) + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionFieldsAsync(new FormUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateStr("abc"), + OpenUnion = FormUnionOpenStringOrInteger.CreateUnknown(JToken.Parse(rawJson)), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal(expected, form["openUnion"]); + Assert.Equal(2, form.Count); + } + + [Theory] + [InlineData("{\"label\":\"x\"}")] + [InlineData("[1,2]")] + [InlineData("null")] + public async Task OmitNonPrimitiveUnknownValueOfOpenUnion(string rawJson) + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionFieldsAsync(new FormUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateStr("abc"), + OpenUnion = FormUnionOpenStringOrInteger.CreateUnknown(JToken.Parse(rawJson)), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.False(form.ContainsKey("openUnion")); + Assert.Equal(1, form.Count); + } + + [Fact] + public async Task SendUnionPropertyOfWholeBodyUnionVariant() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionBodyAsync( + FormUnionBody.CreateFormUnionBodyLabeled(new FormUnionBodyLabeled() + { + Label = "x", + LabelValue = FormUnionStringOrInteger.CreateInteger(5), + LabelJson = FormUnionObjectOrString.CreateFormUnionObject(new FormUnionObject() + { + Label = "y", + Count = 2, + }), + }) + ); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("x", form["label"]); + Assert.Equal("5", form["labelValue"]); + Assert.True(JToken.DeepEquals( + JObject.Parse("{\"label\":\"y\",\"count\":2}"), + JObject.Parse((string)form["labelJson"]) + )); + Assert.Equal(3, form.Count); + } + + [Fact] + public async Task SendJsonStringVariantOfWholeBodyUnionProperty() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionBodyAsync( + FormUnionBody.CreateFormUnionBodyLabeled(new FormUnionBodyLabeled() + { + Label = "x", + LabelValue = FormUnionStringOrInteger.CreateStr("v"), + LabelJson = FormUnionObjectOrString.CreateStr("s"), + }) + ); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("v", form["labelValue"]); + Assert.Equal("\"s\"", form["labelJson"]); + Assert.Equal(3, form.Count); + } + + [Fact] + public async Task SendUnionValuesOfWholeBodyMapVariant() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostFormUnionBodyAsync( + FormUnionBody.CreateMapOfFormUnionStringOrInteger(new Dictionary() + { + { "first", FormUnionStringOrInteger.CreateStr("x") }, + { "second", FormUnionStringOrInteger.CreateInteger(2) }, + }) + ); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("x", form["first"]); + Assert.Equal("2", form["second"]); + Assert.Equal(2, form.Count); + } + + [Fact] + public async Task SendMultipartUnionParts() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostMultipartUnionFieldsAsync(new MultipartUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateStr("abc"), + StringOrArrayUnion = FormUnionStringOrArray.CreateArrayOfStr(new List() { "a", "b" }), + ArrayOfUnion = new List() + { + FormUnionStringOrInteger.CreateStr("x"), + FormUnionStringOrInteger.CreateInteger(2), + }, + NullableUnion = FormUnionNullable.CreateNull(), + JsonUnion = FormUnionObjectOrString.CreateFormUnionObject(new FormUnionObject() + { + Label = "z", + }), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("abc", form["scalarUnion"]); + Assert.Equal(new List() { "a", "b" }, form["stringOrArrayUnion"]); + Assert.Equal(new List() { "x", "2" }, form["arrayOfUnion"]); + Assert.True(JToken.DeepEquals( + JObject.Parse("{\"label\":\"z\"}"), + JObject.Parse((string)form["jsonUnion"]) + )); + Assert.False(form.ContainsKey("nullableUnion")); + Assert.Equal(4, form.Count); + } + + [Fact] + public async Task SendMultipartIntegerVariants() + { + var sdk = new SDK(serverUrl: Helpers.HttpBinUrl); + + var res = await sdk.RequestBodies.RequestBodyPostMultipartUnionFieldsAsync(new MultipartUnionFields() + { + ScalarUnion = FormUnionStringOrInteger.CreateInteger(0), + NullableUnion = FormUnionNullable.CreateInteger(0), + }); + + Assert.Equal(HttpStatusCode.OK, res.HttpMeta.Response.StatusCode); + var form = res.FormUnionEcho!.Form!; + + Assert.Equal("0", form["scalarUnion"]); + Assert.Equal("0", form["nullableUnion"]); + Assert.Equal(2, form.Count); + } +} diff --git a/tests/specs/fragments/primary/form-union-fields.yaml b/tests/specs/fragments/primary/form-union-fields.yaml new file mode 100644 index 000000000..3114b794d --- /dev/null +++ b/tests/specs/fragments/primary/form-union-fields.yaml @@ -0,0 +1,217 @@ +openapi: 3.1.0 +security: + - apiKeyAuth: [] + - oauth2: [] + - clientCredentials: [read, write] + - customSchemeAppId: [] + - basicHttp: [] + - accessToken: [] + - {} +paths: + /anything/formUnionFields: + post: + operationId: requestBodyPostFormUnionFields + tags: + - requestBodies + description: >- + Exercises form-urlencoded request body fields whose schema is a union. + Each field is encoded as if it had been declared with the type of its + active variant: scalar, enum and array variants, an array of unions, a + union whose array variant holds unions, a nullable union holding null, + an optional union left unset, a union with an object variant + encoded as JSON, and an open union holding an unknown value, encoded + as the raw value when it is a primitive and omitted otherwise. + requestBody: + required: true + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/FormUnionFields" + encoding: + jsonUnion: + contentType: application/json + responses: + "200": + description: The echoed form fields. + content: + application/json: + schema: + $ref: "#/components/schemas/FormUnionEcho" + /anything/formUnionBody: + post: + operationId: requestBodyPostFormUnionBody + tags: + - requestBodies + description: >- + Exercises a form-urlencoded request body whose schema is a union of + objects and a map. A union-typed property of the active object variant + is encoded as its active variant, or as JSON when the union has an + object variant. Union-typed values of the active map variant are + encoded as their active variant. + requestBody: + required: true + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/FormUnionBody" + responses: + "200": + description: The echoed form fields. + content: + application/json: + schema: + $ref: "#/components/schemas/FormUnionEcho" + /anything/multipartUnionFields: + post: + operationId: requestBodyPostMultipartUnionFields + tags: + - requestBodies + description: >- + Exercises multipart request body parts whose schema is a union. Each + part is encoded as its active variant: a scalar variant, an array + variant sent as repeated parts, and an array of unions sent as + repeated parts. A union with an object variant is encoded as JSON. A + nullable union holding null is omitted. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/MultipartUnionFields" + responses: + "200": + description: The echoed form fields. + content: + application/json: + schema: + $ref: "#/components/schemas/FormUnionEcho" +components: + schemas: + FormUnionEcho: + type: object + properties: + form: + type: object + additionalProperties: true + FormUnionFields: + type: object + required: + - scalarUnion + properties: + scalarUnion: + $ref: "#/components/schemas/FormUnionStringOrInteger" + stringOrArrayUnion: + $ref: "#/components/schemas/FormUnionStringOrArray" + enumOrBooleanUnion: + $ref: "#/components/schemas/FormUnionEnumOrBoolean" + arrayOfUnion: + type: array + items: + $ref: "#/components/schemas/FormUnionStringOrInteger" + stringOrArrayOfUnion: + $ref: "#/components/schemas/FormUnionStringOrArrayOfUnion" + nullableUnion: + $ref: "#/components/schemas/FormUnionNullable" + optionalUnion: + $ref: "#/components/schemas/FormUnionStringOrInteger" + jsonUnion: + $ref: "#/components/schemas/FormUnionObjectOrString" + openUnion: + $ref: "#/components/schemas/FormUnionOpenStringOrInteger" + FormUnionStringOrInteger: + oneOf: + - type: string + - type: integer + FormUnionOpenStringOrInteger: + x-speakeasy-unknown-values: allow + oneOf: + - type: string + - type: integer + FormUnionStringOrArray: + oneOf: + - type: string + - type: array + items: + type: string + FormUnionStringOrArrayOfUnion: + oneOf: + - type: string + - type: array + items: + $ref: "#/components/schemas/FormUnionIntegerOrBoolean" + FormUnionIntegerOrBoolean: + oneOf: + - type: integer + - type: boolean + FormUnionBody: + oneOf: + - $ref: "#/components/schemas/FormUnionBodyLabeled" + - $ref: "#/components/schemas/FormUnionBodyCounted" + - $ref: "#/components/schemas/FormUnionBodyMap" + FormUnionBodyLabeled: + type: object + required: + - label + - labelValue + properties: + label: + type: string + labelValue: + $ref: "#/components/schemas/FormUnionStringOrInteger" + labelJson: + $ref: "#/components/schemas/FormUnionObjectOrString" + FormUnionBodyCounted: + type: object + required: + - count + properties: + count: + type: integer + FormUnionBodyMap: + type: object + additionalProperties: + $ref: "#/components/schemas/FormUnionStringOrInteger" + MultipartUnionFields: + type: object + required: + - scalarUnion + properties: + scalarUnion: + $ref: "#/components/schemas/FormUnionStringOrInteger" + stringOrArrayUnion: + $ref: "#/components/schemas/FormUnionStringOrArray" + arrayOfUnion: + type: array + items: + $ref: "#/components/schemas/FormUnionStringOrInteger" + nullableUnion: + $ref: "#/components/schemas/FormUnionNullable" + jsonUnion: + $ref: "#/components/schemas/FormUnionObjectOrString" + FormUnionEnumOrBoolean: + oneOf: + - $ref: "#/components/schemas/FormUnionEnum" + - type: boolean + FormUnionNullable: + oneOf: + - type: string + - type: integer + - type: "null" + FormUnionObjectOrString: + oneOf: + - $ref: "#/components/schemas/FormUnionObject" + - type: string + FormUnionEnum: + type: string + enum: + - first + - second + FormUnionObject: + type: object + required: + - label + properties: + label: + type: string + count: + type: integer diff --git a/zSDKs/sdk-csharp/.speakeasy/gen.lock b/zSDKs/sdk-csharp/.speakeasy/gen.lock index 1e437e959..766db7966 100644 --- a/zSDKs/sdk-csharp/.speakeasy/gen.lock +++ b/zSDKs/sdk-csharp/.speakeasy/gen.lock @@ -1484,7 +1484,7 @@ trackedFiles: src/Speakeasy/OpenAPI/Utils/OptionalNullableJsonConverter.cs: last_write_checksum: sha1:bf8eec6e762302070ff3a32d58ebc04347c8ed79 src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs: - last_write_checksum: sha1:4f68b905a9c9caee72cafe309fb8f991b9e18a7b + last_write_checksum: sha1:38292e65b7616271d7581e557885b96dcfd5b5b5 src/Speakeasy/OpenAPI/Utils/ResponseBodyDeserializer.cs: last_write_checksum: sha1:d466d0e2124070f8010d396be9fa10dd9a7fb9d0 src/Speakeasy/OpenAPI/Utils/Retries/BackoffStrategy.cs: @@ -1512,9 +1512,9 @@ trackedFiles: src/Speakeasy/OpenAPI/Utils/URLBuilder.cs: last_write_checksum: sha1:27aa6dd3713a24f20a7737dfb966c3c673529cb5 src/Speakeasy/OpenAPI/Utils/UnionDeserializer.cs: - last_write_checksum: sha1:9ddf50cc9aee44e22210ad6a12b6001f997487b7 + last_write_checksum: sha1:f50ceb5bd0e472ad8cbd5192adde954d4f4dbf26 src/Speakeasy/OpenAPI/Utils/Utilities.cs: - last_write_checksum: sha1:868a41b840b16955fb0530f8220cf2be15f72967 + last_write_checksum: sha1:c3fd047198f06c29d58dc4f569f5b3f65839550b examples: _operation_with_leading_and_trailing_underscores_: "": diff --git a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs index fd629a3de..0f00f3b97 100644 --- a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs +++ b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/RequestBodySerializer.cs @@ -15,6 +15,7 @@ namespace Speakeasy.OpenAPI.Utils using System.Net.Http; using System.Reflection; using System.Text; + using Newtonsoft.Json.Linq; internal class RequestBodySerializer { @@ -200,7 +201,7 @@ ref form form.Add(key, new List()); } - form[key].Add(Utilities.ValueToString(((IDictionary)request)[key])); + form[key].Add(Utilities.ValueToString(UnwrapUnion(((IDictionary)request)[key]))); } } else if (Utilities.IsList(request)) @@ -212,7 +213,7 @@ ref form form.Add(requestFieldName, new List()); } - form[requestFieldName].Add(Utilities.ValueToString(item)); + form[requestFieldName].Add(Utilities.ValueToString(UnwrapUnion(item))); } } else @@ -308,26 +309,35 @@ private static HttpContent SerializeMultipart(object request, string mediaType) metadata.Name ?? prop.Name ); } - else if (Utilities.IsList(value)) + else { - var values = new List(); - - foreach (var item in (IList)value) + var formValue = UnwrapUnion(value); + if (formValue == null) { - values.Add(Utilities.ValueToString(item)); + continue; } - foreach (var val in values) + if (Utilities.IsList(formValue)) { - formData.Add(new StringContent(val), metadata.Name ?? prop.Name); + var values = new List(); + + foreach (var item in (IList)formValue) + { + values.Add(Utilities.ValueToString(UnwrapUnion(item))); + } + + foreach (var val in values) + { + formData.Add(new StringContent(val), metadata.Name ?? prop.Name); + } + } + else + { + formData.Add( + new StringContent(Utilities.ValueToString(formValue)), + metadata.Name ?? prop.Name + ); } - } - else - { - formData.Add( - new StringContent(Utilities.ValueToString(value)), - metadata.Name ?? prop.Name - ); } } @@ -353,7 +363,15 @@ private static void SerializeFormValue( ref Dictionary> form ) { - if (Utilities.IsClass(value)) + if (Utilities.IsUnionWrapper(value.GetType())) + { + var variant = UnwrapUnion(value); + if (variant != null) + { + SerializeFormValue(fieldName, explode, variant, ref form); + } + } + else if (Utilities.IsClass(value)) { if (Utilities.IsDate(value)) { @@ -372,8 +390,8 @@ ref Dictionary> form foreach (var prop in props) { - var val = Utilities.UnwrapValue(prop.GetValue(value)); - if (val == null) + var propValue = Utilities.UnwrapValue(prop.GetValue(value)); + if (propValue == null) { continue; } @@ -384,6 +402,32 @@ ref Dictionary> form continue; } + if (metadata.Json) + { + var json = Utilities.SerializeJSON(propValue); + if (explode) + { + if (!form.ContainsKey(metadata.Name)) + { + form[metadata.Name] = new List(); + } + + form[metadata.Name].Add(json); + } + else + { + items.Add($"{metadata.Name},{json}"); + } + + continue; + } + + var val = UnwrapUnion(propValue); + if (val == null) + { + continue; + } + if (explode) { if (!form.ContainsKey(metadata.Name)) @@ -395,7 +439,7 @@ ref Dictionary> form { foreach (var item in (IEnumerable)val) { - form[metadata.Name].Add(Utilities.ValueToString(item)); + form[metadata.Name].Add(Utilities.ValueToString(UnwrapUnion(item))); } } else @@ -409,7 +453,7 @@ ref Dictionary> form { foreach (var item in (IEnumerable)val) { - items.Add($"{metadata.Name},{Utilities.ValueToString(item)}"); + items.Add($"{metadata.Name},{Utilities.ValueToString(UnwrapUnion(item))}"); } } else @@ -451,12 +495,12 @@ ref Dictionary> form } form[key].Add( - Utilities.ValueToString(((IDictionary)value)[key]) + Utilities.ValueToString(UnwrapUnion(((IDictionary)value)[key])) ); } else { - items.Add($"{key},{Utilities.ValueToString(((IDictionary)value)[key])}"); + items.Add($"{key},{Utilities.ValueToString(UnwrapUnion(((IDictionary)value)[key]))}"); } } @@ -479,11 +523,11 @@ ref Dictionary> form { if (explode) { - values.Add(Utilities.ValueToString(item)); + values.Add(Utilities.ValueToString(UnwrapUnion(item))); } else { - items.Add(Utilities.ValueToString(item)); + items.Add(Utilities.ValueToString(UnwrapUnion(item))); } } @@ -513,6 +557,48 @@ ref Dictionary> form } } + private static object? UnwrapUnion(object? value) + { + while (value != null && Utilities.IsUnionWrapper(value.GetType())) + { + value = GetUnionVariantValue(value); + } + + return value; + } + + private static object? GetUnionVariantValue(object union) + { + object? unknownValue = null; + + foreach (var prop in union.GetType().GetProperties()) + { + var metadata = prop.GetCustomAttribute()?.GetFormMetadata(); + if (metadata == null) + { + if (prop.PropertyType == typeof(JToken) && prop.GetValue(union) is JValue raw) + { + unknownValue = raw.Value; + } + + continue; + } + + if (metadata.Name != "") + { + continue; + } + + var val = Utilities.UnwrapValue(prop.GetValue(union)); + if (val != null) + { + return val; + } + } + + return unknownValue; + } + private static (string fileName, byte[] content) ExtractFileProperties(PropertyInfo[] fileProps, object fileObject) { byte[]? content = null; diff --git a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/UnionDeserializer.cs b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/UnionDeserializer.cs index 59112fe0e..0acc32f3a 100644 --- a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/UnionDeserializer.cs +++ b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/UnionDeserializer.cs @@ -151,7 +151,7 @@ JsonSerializerSettings settings private static bool PreCheck(JToken json, Type type) { if (json.Type != JTokenType.Object) return true; - if (IsUnionWrapper(type)) return true; + if (Utilities.IsUnionWrapper(type)) return true; var jo = (JObject)json; foreach (var (prop, attr) in EnumerateJsonProperties(type)) @@ -210,7 +210,7 @@ private static void ScoreValue(UnionCandidateScore score, Type type, object? val return; } - if (IsUnionWrapper(type) && value != null) + if (Utilities.IsUnionWrapper(type) && value != null) { var (variantType, variantValue) = FindActiveVariant(type, value); if (variantValue != null) @@ -382,20 +382,10 @@ private static Type UnwrapOptional(Type t) return t; } - // A union wrapper is a class generated by speakeasy that carries the - // [JsonConverter(typeof(Self.SelfConverter))] attribute. Its variant - // properties carry no [JsonProperty] (only [SpeakeasyMetadata]). - private static bool IsUnionWrapper(Type type) - { - var attr = type.GetCustomAttribute(); - if (attr == null) return false; - return attr.ConverterType != null && attr.ConverterType.DeclaringType == type; - } - // True when the value is an open union wrapper that fell back to its Unknown sentinel private static bool IsUnknownUnionValue(Type type, object? value) { - if (value == null || !IsUnionWrapper(type)) return false; + if (value == null || !Utilities.IsUnionWrapper(type)) return false; return value is IOpenUnion openUnion && openUnion.IsUnknown(); } diff --git a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/Utilities.cs b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/Utilities.cs index 2f9dd2839..d22821cb1 100644 --- a/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/Utilities.cs +++ b/zSDKs/sdk-csharp/src/Speakeasy/OpenAPI/Utils/Utilities.cs @@ -149,6 +149,16 @@ public static bool IsModelNamespace(string ns) public static bool IsOpenEnum(object? o) => o is IOpenEnum; + // A union wrapper is a class generated by speakeasy that carries the + // [JsonConverter(typeof(Self.SelfConverter))] attribute. Its variant + // properties carry no [JsonProperty] (only [SpeakeasyMetadata]). + public static bool IsUnionWrapper(Type type) + { + var attr = Attribute.GetCustomAttribute(type, typeof(JsonConverterAttribute)) as JsonConverterAttribute; + if (attr == null) return false; + return attr.ConverterType != null && attr.ConverterType.DeclaringType == type; + } + public static bool IsClass(object? o) { if (o == null)