sheridan-typespec-aspnet 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +11 -4
  2. package/dist/src/emitter.js +104 -5
  3. package/dist/src/lib.d.ts +47 -2
  4. package/dist/src/lib.js +18 -0
  5. package/dist/src/model/collect-types.d.ts +3 -1
  6. package/dist/src/model/collect-types.js +1 -1
  7. package/dist/src/model/collect.js +56 -6
  8. package/dist/src/model/types.d.ts +12 -0
  9. package/dist/src/naming/names.d.ts +1 -1
  10. package/dist/src/naming/names.js +13 -3
  11. package/dist/src/naming/services.d.ts +11 -1
  12. package/dist/src/naming/services.js +18 -3
  13. package/dist/src/render/controllers/controllers.d.ts +20 -0
  14. package/dist/src/render/controllers/controllers.js +559 -0
  15. package/dist/src/render/controllers/results.d.ts +10 -0
  16. package/dist/src/render/controllers/results.js +82 -0
  17. package/dist/src/render/minimal/endpoints.d.ts +14 -0
  18. package/dist/src/render/minimal/endpoints.js +161 -0
  19. package/dist/src/render/minimal/results.d.ts +11 -0
  20. package/dist/src/render/minimal/results.js +90 -0
  21. package/dist/src/render/shared/api-setup.d.ts +9 -1
  22. package/dist/src/render/shared/api-setup.js +165 -11
  23. package/dist/src/render/shared/binding.d.ts +43 -0
  24. package/dist/src/render/shared/binding.js +426 -0
  25. package/dist/src/render/shared/body-formats.d.ts +18 -0
  26. package/dist/src/render/shared/body-formats.js +561 -0
  27. package/dist/src/render/shared/converters.js +57 -4
  28. package/dist/src/render/shared/documentation.d.ts +18 -0
  29. package/dist/src/render/shared/documentation.js +112 -0
  30. package/dist/src/render/shared/headers.d.ts +7 -0
  31. package/dist/src/render/shared/headers.js +52 -0
  32. package/dist/src/render/shared/models.js +5 -23
  33. package/dist/src/render/shared/openapi.d.ts +1 -0
  34. package/dist/src/render/shared/openapi.js +333 -0
  35. package/dist/src/render/shared/parameters.d.ts +3 -0
  36. package/dist/src/render/shared/parameters.js +224 -0
  37. package/dist/src/render/shared/references.d.ts +3 -0
  38. package/dist/src/render/shared/references.js +18 -0
  39. package/dist/src/render/shared/request-selector.d.ts +1 -0
  40. package/dist/src/render/shared/request-selector.js +139 -0
  41. package/dist/src/render/shared/responses.d.ts +55 -0
  42. package/dist/src/render/shared/responses.js +130 -0
  43. package/dist/src/render/shared/routes.d.ts +37 -0
  44. package/dist/src/render/shared/routes.js +274 -0
  45. package/dist/src/render/shared/validation.d.ts +6 -1
  46. package/dist/src/render/shared/validation.js +60 -0
  47. package/dist/src/scaffold/projects.d.ts +1 -1
  48. package/dist/src/scaffold/projects.js +4 -3
  49. package/package.json +2 -2
@@ -0,0 +1,112 @@
1
+ import { stringLiteral } from "./writer.js";
2
+ import { isReference } from "./references.js";
3
+ import { documentedCases, otherBodies, statusKey } from "./responses.js";
4
+ /** `typeof` cannot name a nullable reference type. */
5
+ const typeOf = (type, reference) => `typeof(${reference ? type.replace(/\?$/, "") : type})`;
6
+ export function documentationWriter(model, rootNamespace, openapi,
7
+ /** MVC lists more content types for a body than the action takes. */
8
+ controllers = false) {
9
+ const documentation = `global::${rootNamespace}.Documentation`;
10
+ const names = new Set();
11
+ return function describe(group, contract, binding,
12
+ /** True when a content type tells this operation from others of its route. */
13
+ sharesBody = false) {
14
+ const operation = contract.operation.operation;
15
+ const wanted = group ? `${group}_${operation.name}` : operation.name;
16
+ let name = wanted;
17
+ for (let number = 2; names.has(name.toLowerCase()); number++)
18
+ name = `${wanted}${number}`;
19
+ names.add(name.toLowerCase());
20
+ const result = {
21
+ name,
22
+ summary: operation.summary,
23
+ description: operation.doc,
24
+ produces: [],
25
+ };
26
+ if (!openapi)
27
+ return result;
28
+ const array = (type, items) => `new ${documentation}.${type}[] { ${items.join(", ")} }`;
29
+ const responses = documentedCases(model, contract).map(({ key, found, body }) => {
30
+ const { response } = found.found;
31
+ const others = body
32
+ ? otherBodies(model, contract, key, body.type).map((type) => `typeof(${type})`)
33
+ : [];
34
+ // A document has one response for a status, so it holds the headers of every outcome.
35
+ const outcomes = contract.cases.filter((chosen) => statusKey(chosen.found.response.status) === key);
36
+ const declared = outcomes.flatMap((chosen) => chosen.found.content.headers.map((header, index) => ({ chosen, header, index })));
37
+ const headers = declared
38
+ .filter(({ header }, at) => declared.findIndex((other) => other.header.wireName === header.wireName) === at)
39
+ .map(({ chosen, header, index }) => {
40
+ const name = chosen.found.headers[index];
41
+ const member = chosen.members.find((m) => m.name === name);
42
+ const held = isReference(model, header.type);
43
+ const always = !header.optional &&
44
+ outcomes.every((outcome) => outcome.found.content.headers.some((h) => h.wireName === header.wireName));
45
+ return `new ${documentation}.DocumentedHeader(${stringLiteral(header.wireName)}, ${typeOf(member.type.replace(/\?$/, ""), held)}, ${always})`;
46
+ });
47
+ const parts = [
48
+ stringLiteral(key),
49
+ ...(body
50
+ ? [`Body: typeof(${body.type})`, `ContentType: ${stringLiteral(body.contentType)}`]
51
+ : []),
52
+ ...(headers.length ? [`Headers: ${array("DocumentedHeader", headers)}`] : []),
53
+ // ASP.NET Core reads each body of a status from what a handler returns, but not from the
54
+ // attributes of an action.
55
+ ...(controllers && others.length
56
+ ? [`OtherBodies: new global::System.Type[] { ${others.join(", ")} }`]
57
+ : []),
58
+ ];
59
+ // A response without a body is added by the transformer, as `void` has no schema.
60
+ if (typeof response.status === "number" && body) {
61
+ const types = `new string[] { ${stringLiteral(body.contentType)} }`;
62
+ result.produces.push(`new global::Microsoft.AspNetCore.Http.ProducesResponseTypeMetadata(${response.status}, typeof(${body.type}), ${types})`);
63
+ }
64
+ return `new ${documentation}.DocumentedResponse(${parts.join(", ")})`;
65
+ });
66
+ // Inputs the handler declares as text, or not at all.
67
+ const parameters = operation.parameters.flatMap((input, index) => {
68
+ const given = contract.parameters[index];
69
+ // OpenAPI says which content types a body takes with the body.
70
+ if (binding.converted && input.wireName.toLowerCase() === "content-type")
71
+ return [];
72
+ const declared = binding.parameters.find((p) => p.name === given.name);
73
+ const plain = given.type.replace(/\?$/, "");
74
+ const shown = declared?.type.replace(/\?$/, "") === plain;
75
+ const required = !input.optional && input.default === undefined;
76
+ // MVC does not say that a value read by a binder must be sent.
77
+ const unsaid = controllers && required && input.in !== "path";
78
+ if (shown && !declared?.attributes?.length && !unsaid)
79
+ return [];
80
+ const reference = isReference(model, input.type);
81
+ const parts = [
82
+ stringLiteral(input.wireName),
83
+ stringLiteral(input.in),
84
+ ...(shown ? [] : [`Type: ${typeOf(plain, reference)}`]),
85
+ ...(input.optional || input.default !== undefined ? [] : ["Required: true"]),
86
+ ...(binding.checks.get(index)?.length
87
+ ? [
88
+ `Constraints: new global::System.ComponentModel.DataAnnotations.ValidationAttribute[] { ${binding.checks.get(index).join(", ")} }`,
89
+ ]
90
+ : []),
91
+ ];
92
+ return [`new ${documentation}.DocumentedParameter(${parts.join(", ")})`];
93
+ });
94
+ const body = operation.body;
95
+ const byHand = body && !binding.parameters.some((p) => p.source === "body")
96
+ ? `new ${documentation}.DocumentedResponse("body", ${typeOf(contract.parameters[operation.parameters.length].type.replace(/\?$/, ""), true)}, ${stringLiteral(body.contentTypes[0])})`
97
+ : undefined;
98
+ // ASP.NET Core says a body it reads is "application/json", or for a controller also others.
99
+ const listed = controllers || body?.contentTypes.join() !== "application/json";
100
+ // Operations sharing a route have one entry, which lists what any of them takes.
101
+ const types = body && !byHand && listed && !(controllers && sharesBody) ? body.contentTypes : [];
102
+ const parts = [
103
+ array("DocumentedResponse", responses),
104
+ ...(types.length ? [`SentAs: new string[] { ${types.map(stringLiteral).join(", ")} }`] : []),
105
+ ...(parameters.length ? [`Parameters: ${array("DocumentedParameter", parameters)}`] : []),
106
+ ...(byHand ? [`Request: ${byHand}`] : []),
107
+ ...(operation.deprecated ? ["Deprecated: true"] : []),
108
+ ];
109
+ result.operation = `new ${documentation}.DocumentedOperation(${parts.join(", ")})`;
110
+ return result;
111
+ };
112
+ }
@@ -0,0 +1,7 @@
1
+ import type { ApiModel, ParameterModel } from "../../model/types.js";
2
+ /**
3
+ * An expression giving the text of a header, or null when there is nothing to send. Undefined when
4
+ * the header cannot be written, which is reported when the result is named.
5
+ */
6
+ export type HeaderWriter = (header: Pick<ParameterModel, "type" | "encoding" | "wireName" | "source">, value: string, type: string) => string | undefined;
7
+ export declare function headerWriter(model: ApiModel, rootNamespace: string, refuse: (what: string, header: Pick<ParameterModel, "source">) => void): HeaderWriter;
@@ -0,0 +1,52 @@
1
+ import { mapScalar } from "./scalars.js";
2
+ const bare = (ref) => (ref.kind === "nullable" ? bare(ref.type) : ref);
3
+ export function headerWriter(model, rootNamespace, refuse) {
4
+ const parameters = `global::${rootNamespace}.Requests.Parameters`;
5
+ /** The converter of an encoded value, when its type has none of its own. */
6
+ function converter(ref, header) {
7
+ const value = bare(ref);
8
+ let builtin = value.kind === "scalar" ? value.name : undefined;
9
+ if (value.kind === "named") {
10
+ const declared = model.types.get(value.id);
11
+ if (declared.kind === "scalar")
12
+ builtin = declared.builtin;
13
+ }
14
+ const name = builtin &&
15
+ mapScalar(builtin, header.encoding)
16
+ ?.attributes.map((a) => /^JsonConverter\(typeof\((\w+)\)\)$/.exec(a)?.[1])
17
+ .find(Boolean);
18
+ return name ? `global::${rootNamespace}.Serialization.${name}` : undefined;
19
+ }
20
+ function holdsRecordsOrLists(ref) {
21
+ const value = bare(ref);
22
+ if (value.kind === "named") {
23
+ const kind = model.types.get(value.id).kind;
24
+ return kind === "model";
25
+ }
26
+ return ["array", "record", "tuple", "unknown"].includes(value.kind);
27
+ }
28
+ return (header, value, type) => {
29
+ const ref = bare(header.type);
30
+ const item = ref.kind === "array" ? bare(ref.element) : ref;
31
+ if (holdsRecordsOrLists(item)) {
32
+ refuse(`${item.kind} written as text in "${header.wireName}"`, header);
33
+ return undefined;
34
+ }
35
+ const used = converter(item, header);
36
+ const itemType = ref.kind === "array" ? undefined : type;
37
+ const write = (text, held) => used
38
+ ? `${parameters}.Write<${held}, ${used}>(${text})`
39
+ : `${parameters}.Write<${held}>(${text})`;
40
+ if (ref.kind !== "array") {
41
+ return itemType.replace(/\?$/, "") === "string" ? value : write(value, itemType);
42
+ }
43
+ // The item type is that of the member, without its brackets.
44
+ const element = type
45
+ .replace(/\?$/, "")
46
+ .replace(/^global::System\.Collections\.Generic\.IEnumerable<(.*)>$/, "$1[]")
47
+ .replace(/\[\]$/, "");
48
+ return element === "string"
49
+ ? `${parameters}.Join(${value})`
50
+ : `${parameters}.Join(${value}, item => ${write("item", element)})`;
51
+ };
52
+ }
@@ -4,7 +4,7 @@ import { pascalCase } from "../../naming/identifiers.js";
4
4
  import { memberFor, renderChoice, shapeOf } from "./choices.js";
5
5
  import { discriminatorValue, lineage } from "./hierarchy.js";
6
6
  import { mapScalar, numberLiteral, systemTypes } from "./scalars.js";
7
- import { uncheckedConstraints, validationAttributes } from "./validation.js";
7
+ import { uncheckedConstraints, validationAttributes, holds, unreached } from "./validation.js";
8
8
  import { csharpFile, docComment, stringLiteral } from "./writer.js";
9
9
  const json = "global::System.Text.Json";
10
10
  const collections = "global::System.Collections.Generic";
@@ -172,25 +172,6 @@ export function renderModels(program, model, names, options) {
172
172
  required: false,
173
173
  };
174
174
  }
175
- /** What a property holds, for deciding which constraints apply. */
176
- function holds(ref) {
177
- if (ref.kind === "nullable")
178
- return holds(ref.type);
179
- if (ref.kind === "array")
180
- return "array";
181
- let name = ref.kind === "scalar" ? ref.name : undefined;
182
- if (ref.kind === "named") {
183
- const type = model.types.get(ref.id);
184
- if (type.kind === "scalar")
185
- name = type.builtin;
186
- }
187
- const mapped = name === undefined ? undefined : mapScalar(name)?.type;
188
- if (mapped === "string")
189
- return "string";
190
- return mapped && /^(s?byte|u?short|u?int|u?long|float|double|decimal)$/.test(mapped)
191
- ? "number"
192
- : "other";
193
- }
194
175
  const reported = new Map();
195
176
  /** True once for each place in the spec, however many body shapes repeat it. */
196
177
  function firstReport(what, target) {
@@ -212,13 +193,14 @@ export function renderModels(program, model, names, options) {
212
193
  }
213
194
  function checks(property, required) {
214
195
  const namespace = `global::${options.rootNamespace}.Validation`;
215
- const found = validationAttributes(property.constraints ?? {}, holds(property.type), namespace);
196
+ const found = validationAttributes(property.constraints ?? {}, holds(model, property.type), namespace);
216
197
  reportUnchecked([
217
- ...uncheckedConstraints(property.constraints ?? {}, holds(property.type)),
198
+ ...uncheckedConstraints(property.constraints ?? {}, holds(model, property.type)),
218
199
  ...(property.heldConstraints ?? []),
200
+ ...[unreached(model, property.type) ?? []].flat(),
219
201
  ], property.source);
220
202
  // JSON can still send null for a reference that C# says is never null.
221
- const kind = holds(property.type);
203
+ const kind = holds(model, property.type);
222
204
  const target = property.type.kind === "named" ? model.types.get(property.type.id) : undefined;
223
205
  const reference = kind === "string" ||
224
206
  kind === "array" ||
@@ -0,0 +1 @@
1
+ export declare function renderOpenApi(rootNamespace: string, controllers?: boolean): string;
@@ -0,0 +1,333 @@
1
+ // What ASP.NET Core cannot read from a handler is told to OpenAPI through endpoint metadata, which
2
+ // a generated transformer applies.
3
+ export function renderOpenApi(rootNamespace, controllers = false) {
4
+ // MVC lists several content types for a body, where a Minimal API endpoint lists one.
5
+ const listed = controllers ? "> 0" : "1";
6
+ return `// <auto-generated/>
7
+ // Generated by Sheridan.Typespec.Aspnet. Do not edit.
8
+ #nullable enable
9
+
10
+ namespace ${rootNamespace}.Documentation;
11
+
12
+ // Inside the namespace, so that a type in the spec cannot hide these.
13
+ using global::System;
14
+ using global::System.Collections.Generic;
15
+ using global::System.ComponentModel.DataAnnotations;
16
+ using global::System.Linq;
17
+ using global::System.Net.Http;
18
+ using global::System.Text.Json.Nodes;
19
+ using global::System.Text.Json.Serialization;
20
+ using global::System.Text.Json.Serialization.Metadata;
21
+ using global::System.Reflection;
22
+ using global::System.Threading;
23
+ using global::System.Threading.Tasks;
24
+ using global::Microsoft.AspNetCore.OpenApi;
25
+ using global::Microsoft.Extensions.DependencyInjection;
26
+ using global::Microsoft.OpenApi;
27
+ using global::${rootNamespace}.Validation;
28
+
29
+ /// <summary>A value of a request, described where the handler does not say it all.</summary>
30
+ internal sealed record DocumentedParameter(
31
+ string Name,
32
+ string In,
33
+ Type? Type = null,
34
+ bool Required = false,
35
+ ValidationAttribute[]? Constraints = null);
36
+
37
+ internal sealed record DocumentedHeader(string Name, Type Type, bool Required);
38
+
39
+ /// <summary>A response of the spec, keyed by its status, such as "200", "4XX" or "default".</summary>
40
+ internal sealed record DocumentedResponse(
41
+ string Status,
42
+ Type? Body = null,
43
+ string? ContentType = null,
44
+ DocumentedHeader[]? Headers = null,
45
+ Type[]? OtherBodies = null);
46
+
47
+ /// <summary>What the spec says of an operation, beyond what its handler shows.</summary>
48
+ internal sealed record DocumentedOperation(
49
+ DocumentedResponse[] Responses,
50
+ DocumentedParameter[]? Parameters = null,
51
+ DocumentedResponse? Request = null,
52
+ bool Deprecated = false,
53
+ string[]? SentAs = null);
54
+
55
+ internal static class OpenApiSetup
56
+ {
57
+ public static IServiceCollection AddGeneratedOpenApi(IServiceCollection services) =>
58
+ services.AddOpenApi(options =>
59
+ {
60
+ options.AddOperationTransformer(Describe);
61
+ options.AddSchemaTransformer(Constrain);
62
+ });
63
+
64
+ private static async Task Describe(
65
+ OpenApiOperation operation,
66
+ OpenApiOperationTransformerContext context,
67
+ CancellationToken cancellationToken)
68
+ {
69
+ var found = context.Description.ActionDescriptor.EndpointMetadata
70
+ .OfType<DocumentedOperation>()
71
+ .LastOrDefault();
72
+ if (found is null)
73
+ {
74
+ return;
75
+ }
76
+
77
+ if (found.Deprecated)
78
+ {
79
+ operation.Deprecated = true;
80
+ }
81
+
82
+ async Task<OpenApiSchema> Schema(Type type) =>
83
+ await context.GetOrCreateSchemaAsync(type, cancellationToken: cancellationToken);
84
+
85
+ foreach (var described in found.Parameters ?? [])
86
+ {
87
+ var location = Enum.Parse<ParameterLocation>(described.In, true);
88
+ operation.Parameters ??= new List<IOpenApiParameter>();
89
+ var parameter = operation.Parameters.OfType<OpenApiParameter>().FirstOrDefault(
90
+ p => p.In == location
91
+ && string.Equals(p.Name, described.Name, StringComparison.OrdinalIgnoreCase));
92
+ if (parameter is null)
93
+ {
94
+ parameter = new OpenApiParameter
95
+ {
96
+ Name = described.Name,
97
+ In = location,
98
+ Required = described.Required,
99
+ };
100
+ operation.Parameters.Add(parameter);
101
+ }
102
+
103
+ if (described.Type is not null)
104
+ {
105
+ parameter.Schema = await Schema(described.Type);
106
+ }
107
+
108
+ if (described.Required)
109
+ {
110
+ (parameter as OpenApiParameter)!.Required = true;
111
+ }
112
+
113
+ if (parameter.Schema is OpenApiSchema schema)
114
+ {
115
+ Apply(schema, described.Constraints ?? []);
116
+ }
117
+ }
118
+
119
+ if (found.Request is { Body: { } sent } request)
120
+ {
121
+ operation.RequestBody = new OpenApiRequestBody
122
+ {
123
+ Required = true,
124
+ Content = new Dictionary<string, IOpenApiMediaType>
125
+ {
126
+ [request.ContentType!] = new OpenApiMediaType { Schema = await Schema(sent) },
127
+ },
128
+ };
129
+ }
130
+
131
+ if (found.SentAs is { } types
132
+ && operation.RequestBody is OpenApiRequestBody { Content: { Count: ${listed} } content } bound)
133
+ {
134
+ var only = content.Values.First();
135
+ bound.Content = types.ToDictionary(type => type, _ => only);
136
+ }
137
+
138
+ var responses = new OpenApiResponses();
139
+ foreach (var described in found.Responses)
140
+ {
141
+ // What ASP.NET Core described is kept, and the rest added.
142
+ var response = operation.Responses?.GetValueOrDefault(described.Status) as OpenApiResponse;
143
+ if (response is null)
144
+ {
145
+ response = new OpenApiResponse { Description = described.Status };
146
+ if (described.Body is not null)
147
+ {
148
+ response.Content = new Dictionary<string, IOpenApiMediaType>
149
+ {
150
+ [described.ContentType!] = new OpenApiMediaType { Schema = await Schema(described.Body) },
151
+ };
152
+ }
153
+ }
154
+
155
+ // MVC says a default response may be sent in several ways, where the spec names one.
156
+ else if (described.ContentType is { } only
157
+ && response.Content is { Count: > 1 } sentIn
158
+ && sentIn.TryGetValue(only, out var kept))
159
+ {
160
+ response.Content = new Dictionary<string, IOpenApiMediaType> { [only] = kept };
161
+ }
162
+
163
+ if (string.IsNullOrEmpty(response.Description))
164
+ {
165
+ response.Description = described.Status;
166
+ }
167
+
168
+ if (described.OtherBodies is { } others
169
+ && response.Content is { } bodies
170
+ && bodies.TryGetValue(described.ContentType!, out var held)
171
+ && held is OpenApiMediaType media)
172
+ {
173
+ var either = new List<IOpenApiSchema> { media.Schema! };
174
+ foreach (var other in others)
175
+ {
176
+ either.Add(await Schema(other));
177
+ }
178
+
179
+ media.Schema = new OpenApiSchema { AnyOf = either };
180
+ }
181
+
182
+ foreach (var header in described.Headers ?? [])
183
+ {
184
+ response.Headers ??= new Dictionary<string, IOpenApiHeader>();
185
+ response.Headers[header.Name] = new OpenApiHeader
186
+ {
187
+ Required = header.Required,
188
+ Schema = await Schema(header.Type),
189
+ };
190
+ }
191
+
192
+ responses[described.Status] = response;
193
+ }
194
+
195
+ operation.Responses = responses;
196
+ }
197
+
198
+ private static async Task Constrain(
199
+ OpenApiSchema schema,
200
+ OpenApiSchemaTransformerContext context,
201
+ CancellationToken cancellationToken)
202
+ {
203
+ // A merge-patch property is described as the value it may hold.
204
+ var held = context.JsonTypeInfo.Type;
205
+ if (held.IsGenericType && held.Namespace == typeof(global::${rootNamespace}.Serialization.JsonSetup).Namespace
206
+ && held.Name is "Optional\`1" or "OptionalNullable\`1")
207
+ {
208
+ var inner = await context.GetOrCreateSchemaAsync(
209
+ held.GetGenericArguments()[0], cancellationToken: cancellationToken);
210
+ schema.Type = inner.Type;
211
+ schema.Format = inner.Format;
212
+ schema.Items = inner.Items;
213
+ schema.Properties = inner.Properties;
214
+ schema.Required = inner.Required;
215
+ schema.Enum = inner.Enum;
216
+ }
217
+
218
+ // OpenAPI cannot see the names an enum's converter reads, so they are listed here.
219
+ ListNames(schema, held);
220
+
221
+ // Nor does it describe such an enum inside a list or a dictionary.
222
+ if (context.JsonTypeInfo is
223
+ {
224
+ Kind: JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary,
225
+ ElementType: { } element,
226
+ }
227
+ && IsNamedEnum(Nullable.GetUnderlyingType(element) ?? element))
228
+ {
229
+ var item = await context.GetOrCreateSchemaAsync(element, cancellationToken: cancellationToken);
230
+ if (context.JsonTypeInfo.Kind == JsonTypeInfoKind.Dictionary)
231
+ {
232
+ schema.AdditionalProperties = item;
233
+ }
234
+ else
235
+ {
236
+ schema.Items = item;
237
+ }
238
+ }
239
+
240
+ var attributes = context.JsonPropertyInfo?.AttributeProvider?
241
+ .GetCustomAttributes(typeof(ValidationAttribute), true);
242
+ if (attributes is not null)
243
+ {
244
+ Apply(schema, attributes.OfType<ValidationAttribute>());
245
+ }
246
+
247
+ var converter = context.JsonPropertyInfo?.AttributeProvider?
248
+ .GetCustomAttributes(typeof(JsonConverterAttribute), true)
249
+ .OfType<JsonConverterAttribute>()
250
+ .FirstOrDefault()?.ConverterType?.Name;
251
+ // A converter of an encoding hides the type from OpenAPI.
252
+ if (schema.Type is null && converter is not null && Encoded(converter) is { } encoded)
253
+ {
254
+ schema.Type = encoded.Type;
255
+ schema.Format = encoded.Format;
256
+ }
257
+
258
+ }
259
+
260
+ private static bool IsNamedEnum(Type type) =>
261
+ type.GetCustomAttribute<JsonConverterAttribute>()?.ConverterType is { IsGenericType: true } converter
262
+ && converter.GetGenericTypeDefinition() == typeof(global::${rootNamespace}.Serialization.StringEnumConverter<>);
263
+
264
+ // A nullable enum lists null too. An enum has one schema, which all its uses share.
265
+ private static void ListNames(OpenApiSchema schema, Type held)
266
+ {
267
+ var type = Nullable.GetUnderlyingType(held) ?? held;
268
+ if (!IsNamedEnum(type))
269
+ {
270
+ return;
271
+ }
272
+
273
+ var converter = type.GetCustomAttribute<JsonConverterAttribute>()!.ConverterType!;
274
+ var names = (IEnumerable<string>)converter
275
+ .GetProperty("Names", BindingFlags.Static | BindingFlags.NonPublic)!
276
+ .GetValue(null)!;
277
+ var values = names.Select(name => (JsonNode)name).ToList();
278
+ if (type != held)
279
+ {
280
+ values.Add(null!);
281
+ }
282
+
283
+ schema.Enum = values;
284
+ }
285
+
286
+ private static (JsonSchemaType Type, string Format)? Encoded(string converter) => converter switch
287
+ {
288
+ "UtcDateTimeConverter" or "OffsetDateTimeConverter" => (JsonSchemaType.String, "date-time"),
289
+ "Rfc7231DateTimeConverter" => (JsonSchemaType.String, "http-date"),
290
+ "UnixTimestampConverter" or "UnixTimestamp32Converter" => (JsonSchemaType.Integer, "unixtime"),
291
+ "Iso8601DurationConverter" => (JsonSchemaType.String, "duration"),
292
+ "SecondsDurationConverter" or "MillisecondsDurationConverter" => (JsonSchemaType.Number, "double"),
293
+ "WholeSecondsDurationConverter" or "WholeMillisecondsDurationConverter" => (JsonSchemaType.Integer, "int64"),
294
+ "Base64UrlConverter" => (JsonSchemaType.String, "base64url"),
295
+ "StringBooleanConverter" => (JsonSchemaType.String, "boolean"),
296
+ _ => null,
297
+ };
298
+
299
+ private static void Apply(OpenApiSchema schema, IEnumerable<ValidationAttribute> attributes)
300
+ {
301
+ foreach (var attribute in attributes)
302
+ {
303
+ switch (attribute)
304
+ {
305
+ case TextLengthAttribute text:
306
+ schema.MinLength = text.Minimum > 0 ? text.Minimum : null;
307
+ schema.MaxLength = text.Maximum < int.MaxValue ? text.Maximum : null;
308
+ break;
309
+ case PatternAttribute pattern:
310
+ schema.Pattern = pattern.Source ?? pattern.Expression;
311
+ break;
312
+ case UuidAttribute:
313
+ schema.Format = "uuid";
314
+ break;
315
+ case global::${rootNamespace}.Validation.EmailAttribute:
316
+ schema.Format = "email";
317
+ break;
318
+ case ItemCountAttribute items:
319
+ schema.MinItems = items.Minimum > 0 ? items.Minimum : null;
320
+ schema.MaxItems = items.Maximum < int.MaxValue ? items.Maximum : null;
321
+ break;
322
+ case NumberRangeAttribute range:
323
+ schema.Minimum = range.Minimum ?? schema.Minimum;
324
+ schema.Maximum = range.Maximum ?? schema.Maximum;
325
+ schema.ExclusiveMinimum = range.ExclusiveMinimum;
326
+ schema.ExclusiveMaximum = range.ExclusiveMaximum;
327
+ break;
328
+ }
329
+ }
330
+ }
331
+ }
332
+ `;
333
+ }
@@ -0,0 +1,3 @@
1
+ export declare function renderParameters(rootNamespace: string): string;
2
+ /** The generated helpers that send what ASP.NET Core's results do not. */
3
+ export declare function renderResponses(rootNamespace: string): string;