sheridan-typespec-aspnet 0.3.0 → 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.
- package/README.md +4 -4
- package/dist/src/emitter.js +72 -41
- package/dist/src/lib.d.ts +17 -2
- package/dist/src/lib.js +6 -0
- package/dist/src/model/collect.js +18 -4
- package/dist/src/model/types.d.ts +2 -0
- package/dist/src/naming/names.d.ts +1 -1
- package/dist/src/naming/names.js +2 -2
- package/dist/src/naming/services.d.ts +3 -3
- package/dist/src/naming/services.js +9 -3
- package/dist/src/render/controllers/controllers.d.ts +20 -0
- package/dist/src/render/controllers/controllers.js +559 -0
- package/dist/src/render/controllers/results.d.ts +10 -0
- package/dist/src/render/controllers/results.js +82 -0
- package/dist/src/render/minimal/endpoints.d.ts +2 -2
- package/dist/src/render/minimal/endpoints.js +23 -1
- package/dist/src/render/minimal/results.js +33 -88
- package/dist/src/render/shared/api-setup.d.ts +4 -1
- package/dist/src/render/shared/api-setup.js +58 -24
- package/dist/src/render/shared/binding.d.ts +11 -1
- package/dist/src/render/shared/binding.js +52 -21
- package/dist/src/render/shared/body-formats.d.ts +18 -0
- package/dist/src/render/shared/body-formats.js +561 -0
- package/dist/src/render/shared/converters.js +57 -4
- package/dist/src/render/shared/documentation.d.ts +18 -0
- package/dist/src/render/shared/documentation.js +112 -0
- package/dist/src/render/shared/openapi.d.ts +1 -1
- package/dist/src/render/shared/openapi.js +88 -3
- package/dist/src/render/shared/request-selector.d.ts +1 -1
- package/dist/src/render/shared/request-selector.js +58 -5
- package/dist/src/render/shared/responses.d.ts +55 -0
- package/dist/src/render/shared/responses.js +130 -0
- package/dist/src/render/shared/routes.js +36 -3
- package/package.json +1 -1
- package/dist/src/render/minimal/documentation.d.ts +0 -4
- package/dist/src/render/minimal/documentation.js +0 -107
|
@@ -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
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare function renderOpenApi(rootNamespace: string): string;
|
|
1
|
+
export declare function renderOpenApi(rootNamespace: string, controllers?: boolean): string;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// What ASP.NET Core cannot read from a handler is told to OpenAPI through endpoint metadata, which
|
|
2
2
|
// a generated transformer applies.
|
|
3
|
-
export function renderOpenApi(rootNamespace) {
|
|
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";
|
|
4
6
|
return `// <auto-generated/>
|
|
5
7
|
// Generated by Sheridan.Typespec.Aspnet. Do not edit.
|
|
6
8
|
#nullable enable
|
|
@@ -13,7 +15,9 @@ using global::System.Collections.Generic;
|
|
|
13
15
|
using global::System.ComponentModel.DataAnnotations;
|
|
14
16
|
using global::System.Linq;
|
|
15
17
|
using global::System.Net.Http;
|
|
18
|
+
using global::System.Text.Json.Nodes;
|
|
16
19
|
using global::System.Text.Json.Serialization;
|
|
20
|
+
using global::System.Text.Json.Serialization.Metadata;
|
|
17
21
|
using global::System.Reflection;
|
|
18
22
|
using global::System.Threading;
|
|
19
23
|
using global::System.Threading.Tasks;
|
|
@@ -37,7 +41,8 @@ internal sealed record DocumentedResponse(
|
|
|
37
41
|
string Status,
|
|
38
42
|
Type? Body = null,
|
|
39
43
|
string? ContentType = null,
|
|
40
|
-
DocumentedHeader[]? Headers = null
|
|
44
|
+
DocumentedHeader[]? Headers = null,
|
|
45
|
+
Type[]? OtherBodies = null);
|
|
41
46
|
|
|
42
47
|
/// <summary>What the spec says of an operation, beyond what its handler shows.</summary>
|
|
43
48
|
internal sealed record DocumentedOperation(
|
|
@@ -100,6 +105,11 @@ internal static class OpenApiSetup
|
|
|
100
105
|
parameter.Schema = await Schema(described.Type);
|
|
101
106
|
}
|
|
102
107
|
|
|
108
|
+
if (described.Required)
|
|
109
|
+
{
|
|
110
|
+
(parameter as OpenApiParameter)!.Required = true;
|
|
111
|
+
}
|
|
112
|
+
|
|
103
113
|
if (parameter.Schema is OpenApiSchema schema)
|
|
104
114
|
{
|
|
105
115
|
Apply(schema, described.Constraints ?? []);
|
|
@@ -119,7 +129,7 @@ internal static class OpenApiSetup
|
|
|
119
129
|
}
|
|
120
130
|
|
|
121
131
|
if (found.SentAs is { } types
|
|
122
|
-
&& operation.RequestBody is OpenApiRequestBody { Content: { Count:
|
|
132
|
+
&& operation.RequestBody is OpenApiRequestBody { Content: { Count: ${listed} } content } bound)
|
|
123
133
|
{
|
|
124
134
|
var only = content.Values.First();
|
|
125
135
|
bound.Content = types.ToDictionary(type => type, _ => only);
|
|
@@ -142,6 +152,33 @@ internal static class OpenApiSetup
|
|
|
142
152
|
}
|
|
143
153
|
}
|
|
144
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
|
+
|
|
145
182
|
foreach (var header in described.Headers ?? [])
|
|
146
183
|
{
|
|
147
184
|
response.Headers ??= new Dictionary<string, IOpenApiHeader>();
|
|
@@ -178,6 +215,28 @@ internal static class OpenApiSetup
|
|
|
178
215
|
schema.Enum = inner.Enum;
|
|
179
216
|
}
|
|
180
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
|
+
|
|
181
240
|
var attributes = context.JsonPropertyInfo?.AttributeProvider?
|
|
182
241
|
.GetCustomAttributes(typeof(ValidationAttribute), true);
|
|
183
242
|
if (attributes is not null)
|
|
@@ -198,6 +257,32 @@ internal static class OpenApiSetup
|
|
|
198
257
|
|
|
199
258
|
}
|
|
200
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
|
+
|
|
201
286
|
private static (JsonSchemaType Type, string Format)? Encoded(string converter) => converter switch
|
|
202
287
|
{
|
|
203
288
|
"UtcDateTimeConverter" or "OffsetDateTimeConverter" => (JsonSchemaType.String, "date-time"),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare function renderRequestSelector(rootNamespace: string): string;
|
|
1
|
+
export declare function renderRequestSelector(rootNamespace: string, controllers?: boolean): string;
|
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
// Chooses between operations that share a verb and route, in either style.
|
|
2
2
|
import { csharpFile } from "./writer.js";
|
|
3
|
-
export function renderRequestSelector(rootNamespace) {
|
|
3
|
+
export function renderRequestSelector(rootNamespace, controllers = false) {
|
|
4
|
+
// Endpoints take a condition as it is; actions can only carry attributes.
|
|
5
|
+
const read = controllers
|
|
6
|
+
? "RequestCondition.Of(candidates[index].Endpoint)"
|
|
7
|
+
: "candidates[index].Endpoint.Metadata.GetMetadata<RequestCondition>()";
|
|
8
|
+
const applies = controllers
|
|
9
|
+
? "RequestCondition.Of(endpoint)"
|
|
10
|
+
: "endpoint.Metadata.GetMetadata<RequestCondition>()";
|
|
11
|
+
const of = controllers
|
|
12
|
+
? ` public static RequestCondition? Of(Endpoint endpoint)
|
|
13
|
+
{
|
|
14
|
+
var values = endpoint.Metadata.GetOrderedMetadata<RequiresValueAttribute>();
|
|
15
|
+
var types = endpoint.Metadata.GetMetadata<RequiresContentTypeAttribute>();
|
|
16
|
+
if (values.Count == 0 && types is null)
|
|
17
|
+
{
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
var required = new RequiredValue[values.Count];
|
|
22
|
+
for (var index = 0; index < required.Length; index++)
|
|
23
|
+
{
|
|
24
|
+
var value = values[index];
|
|
25
|
+
required[index] = new RequiredValue(value.Header, value.Name, value.Value, value.IgnoreCase);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return new RequestCondition(required, types?.ContentTypes ?? global::System.Array.Empty<string>());
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
`
|
|
32
|
+
: "";
|
|
33
|
+
const attributes = controllers
|
|
34
|
+
? `
|
|
35
|
+
|
|
36
|
+
/// <summary>A query value or header a request must carry to reach an action.</summary>
|
|
37
|
+
[global::System.AttributeUsage(global::System.AttributeTargets.Method, AllowMultiple = true)]
|
|
38
|
+
internal sealed class RequiresValueAttribute(bool header, string name, string value, bool ignoreCase)
|
|
39
|
+
: global::System.Attribute
|
|
40
|
+
{
|
|
41
|
+
public bool Header { get; } = header;
|
|
42
|
+
|
|
43
|
+
public string Name { get; } = name;
|
|
44
|
+
|
|
45
|
+
public string Value { get; } = value;
|
|
46
|
+
|
|
47
|
+
public bool IgnoreCase { get; } = ignoreCase;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// <summary>The content types that identify a request for an action.</summary>
|
|
51
|
+
[global::System.AttributeUsage(global::System.AttributeTargets.Method)]
|
|
52
|
+
internal sealed class RequiresContentTypeAttribute(params string[] contentTypes) : global::System.Attribute
|
|
53
|
+
{
|
|
54
|
+
public string[] ContentTypes { get; } = contentTypes;
|
|
55
|
+
}`
|
|
56
|
+
: "";
|
|
4
57
|
return csharpFile(`${rootNamespace}.Routing`, `// Inside the namespace, so that a type of the spec named alike does not hide these.
|
|
5
58
|
using global::Microsoft.AspNetCore.Http;
|
|
6
59
|
using global::Microsoft.AspNetCore.Routing;
|
|
@@ -22,7 +75,7 @@ internal sealed record RequiredValue(bool Header, string Name, string Value, boo
|
|
|
22
75
|
/// <summary>What a request must carry to reach one of the operations sharing a route.</summary>
|
|
23
76
|
internal sealed record RequestCondition(RequiredValue[] Values, string[] ContentTypes)
|
|
24
77
|
{
|
|
25
|
-
public bool IsMetBy(HttpRequest request)
|
|
78
|
+
${of} public bool IsMetBy(HttpRequest request)
|
|
26
79
|
{
|
|
27
80
|
foreach (var value in Values)
|
|
28
81
|
{
|
|
@@ -59,7 +112,7 @@ internal sealed class RequestSelector : MatcherPolicy, IEndpointSelectorPolicy
|
|
|
59
112
|
{
|
|
60
113
|
foreach (var endpoint in endpoints)
|
|
61
114
|
{
|
|
62
|
-
if (
|
|
115
|
+
if (${applies} is not null)
|
|
63
116
|
{
|
|
64
117
|
return true;
|
|
65
118
|
}
|
|
@@ -73,7 +126,7 @@ internal sealed class RequestSelector : MatcherPolicy, IEndpointSelectorPolicy
|
|
|
73
126
|
for (var index = 0; index < candidates.Count; index++)
|
|
74
127
|
{
|
|
75
128
|
if (candidates.IsValidCandidate(index)
|
|
76
|
-
&&
|
|
129
|
+
&& ${read} is { } condition
|
|
77
130
|
&& !condition.IsMetBy(httpContext.Request))
|
|
78
131
|
{
|
|
79
132
|
candidates.SetValidity(index, false);
|
|
@@ -82,5 +135,5 @@ internal sealed class RequestSelector : MatcherPolicy, IEndpointSelectorPolicy
|
|
|
82
135
|
|
|
83
136
|
return global::System.Threading.Tasks.Task.CompletedTask;
|
|
84
137
|
}
|
|
85
|
-
}`);
|
|
138
|
+
}${attributes}`);
|
|
86
139
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { Program } from "@typespec/compiler";
|
|
2
|
+
import type { ApiModel } from "../../model/types.js";
|
|
3
|
+
import type { HeaderWriter } from "./headers.js";
|
|
4
|
+
import type { ResultCase, ServiceContract } from "./services.js";
|
|
5
|
+
/** The result of one case: its type and the expression making it. */
|
|
6
|
+
export interface Result {
|
|
7
|
+
type: string;
|
|
8
|
+
expression: string;
|
|
9
|
+
}
|
|
10
|
+
/** The status of a case: `fixed` is undefined when the service chooses it. */
|
|
11
|
+
export interface Status {
|
|
12
|
+
fixed: number | undefined;
|
|
13
|
+
/** The expression giving the status. */
|
|
14
|
+
code: string;
|
|
15
|
+
}
|
|
16
|
+
/** How a style makes each kind of response. */
|
|
17
|
+
export interface ResultMaker {
|
|
18
|
+
empty(status: Status): Result;
|
|
19
|
+
/**
|
|
20
|
+
* `contentType` is the first sent that names no wildcard. `nullable` is true when the service
|
|
21
|
+
* may give no body.
|
|
22
|
+
*/
|
|
23
|
+
json(status: Status, type: string, body: string, contentType: string | undefined, nullable: boolean): Result;
|
|
24
|
+
text(status: Status, text: string, contentType: string): Result;
|
|
25
|
+
bytes(status: Status, body: string, contentType: string): Result;
|
|
26
|
+
}
|
|
27
|
+
type Operation = ServiceContract["operations"][number];
|
|
28
|
+
export declare function responseWriter(program: Program, model: ApiModel, rootNamespace: string, headers: HeaderWriter, maker: ResultMaker): (operation: Operation, value: string, context: string) => {
|
|
29
|
+
type: string;
|
|
30
|
+
expression: string;
|
|
31
|
+
chosen: ResultCase;
|
|
32
|
+
}[];
|
|
33
|
+
/** The arm of the switch over a service's result that answers one case. */
|
|
34
|
+
export declare function arm(namespace: string, operation: Operation, chosen: ResultCase, value: string, expression: string): string;
|
|
35
|
+
/** How a document keys a status, or undefined when it cannot. */
|
|
36
|
+
export declare const statusKey: (status: Operation["cases"][number]["found"]["response"]["status"]) => string | undefined;
|
|
37
|
+
/** What a document says of one response, whatever the style. */
|
|
38
|
+
export interface DocumentedCase {
|
|
39
|
+
/** Such as "200", "4XX" or "default". */
|
|
40
|
+
key: string;
|
|
41
|
+
found: ResultCase;
|
|
42
|
+
/** The C# type of the body, without the `?` of a reference, and the content type sent. */
|
|
43
|
+
body?: {
|
|
44
|
+
type: string;
|
|
45
|
+
contentType: string;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** The types of the other bodies a status of an operation may have, beside `first`. */
|
|
49
|
+
export declare function otherBodies(model: ApiModel, operation: Operation, key: string, first: string): string[];
|
|
50
|
+
/**
|
|
51
|
+
* The first case of each status that can be named in a document, which has one response for each
|
|
52
|
+
* status.
|
|
53
|
+
*/
|
|
54
|
+
export declare function documentedCases(model: ApiModel, operation: Operation): DocumentedCase[];
|
|
55
|
+
export {};
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { reportDiagnostic } from "../../lib.js";
|
|
2
|
+
import { isReference } from "./references.js";
|
|
3
|
+
import { stringLiteral } from "./writer.js";
|
|
4
|
+
const isText = (type) => type.toLowerCase().startsWith("text/");
|
|
5
|
+
const isJson = (type) => /^application\/(?:[\w.-]+\+)?json$/i.test(type.split(";")[0]);
|
|
6
|
+
export function responseWriter(program, model, rootNamespace, headers, maker) {
|
|
7
|
+
const responses = `global::${rootNamespace}.Responses`;
|
|
8
|
+
function respond(found, value, context, operation) {
|
|
9
|
+
const { response, content } = found.found;
|
|
10
|
+
const member = (name) => found.members.find((m) => m.name === name);
|
|
11
|
+
const fixed = typeof response.status === "number" ? response.status : undefined;
|
|
12
|
+
const status = { fixed, code: fixed === undefined ? `${value}.StatusCode` : String(fixed) };
|
|
13
|
+
const body = content.body && member("Body");
|
|
14
|
+
let result;
|
|
15
|
+
if (!body) {
|
|
16
|
+
result = maker.empty(status);
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
const sent = content.body.contentTypes;
|
|
20
|
+
const contentType = sent.find((t) => !t.includes("*"));
|
|
21
|
+
const sentBody = content.body;
|
|
22
|
+
// A nullable value type is a type of its own, which the result must name.
|
|
23
|
+
const held = sentBody.kind === "single" && isReference(model, sentBody.type)
|
|
24
|
+
? body.type.replace(/\?$/, "")
|
|
25
|
+
: body.type;
|
|
26
|
+
const bare = body.type.replace(/\?$/, "");
|
|
27
|
+
const read = `${value}.Body`;
|
|
28
|
+
if (sent.every(isJson)) {
|
|
29
|
+
result = maker.json(status, held, read, contentType, body.type.endsWith("?"));
|
|
30
|
+
}
|
|
31
|
+
else if (!sent.some(isJson) &&
|
|
32
|
+
(bare === "string" || (bare !== "byte[]" && sent.every(isText)))) {
|
|
33
|
+
// Numbers, dates and the like are written as plain text too.
|
|
34
|
+
const text = bare === "string" || sentBody.kind !== "single"
|
|
35
|
+
? read
|
|
36
|
+
: headers({
|
|
37
|
+
type: sentBody.type,
|
|
38
|
+
wireName: "body",
|
|
39
|
+
source: operation.operation.operation.source,
|
|
40
|
+
}, read, body.type);
|
|
41
|
+
if (text === undefined)
|
|
42
|
+
return undefined;
|
|
43
|
+
result = maker.text(status, text, contentType ?? "text/plain");
|
|
44
|
+
}
|
|
45
|
+
else if (bare === "byte[]" && !sent.some(isJson)) {
|
|
46
|
+
result = maker.bytes(status, read, contentType ?? "application/octet-stream");
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
reportDiagnostic(program, {
|
|
50
|
+
code: "unsupported-type",
|
|
51
|
+
format: { kind: `response body sent as ${sent.join(", ")}` },
|
|
52
|
+
target: operation.operation.operation.source,
|
|
53
|
+
});
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
let { expression } = result;
|
|
58
|
+
content.headers.forEach((header, index) => {
|
|
59
|
+
const name = found.found.headers[index];
|
|
60
|
+
const text = headers(header, `${value}.${name}`, member(name).type);
|
|
61
|
+
if (text === undefined)
|
|
62
|
+
return;
|
|
63
|
+
expression = `${responses}.ResponseHeaders.With(${expression}, ${context}, ${stringLiteral(header.wireName)}, ${text})`;
|
|
64
|
+
});
|
|
65
|
+
return { type: result.type, expression };
|
|
66
|
+
}
|
|
67
|
+
/** Every case of an operation that can be answered. */
|
|
68
|
+
return (operation, value, context) => operation.cases.flatMap((chosen) => {
|
|
69
|
+
const made = respond(chosen, value, context, operation);
|
|
70
|
+
return made ? [{ chosen, ...made }] : [];
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** The arm of the switch over a service's result that answers one case. */
|
|
74
|
+
export function arm(namespace, operation, chosen, value, expression) {
|
|
75
|
+
const held = `global::${namespace}.${operation.operation.result.name}.${chosen.found.name}`;
|
|
76
|
+
const used = expression.includes(`${value}.`);
|
|
77
|
+
return `${held}${used ? ` ${value}` : ""} => ${expression}`;
|
|
78
|
+
}
|
|
79
|
+
/** How a document keys a status, or undefined when it cannot. */
|
|
80
|
+
export const statusKey = (status) => {
|
|
81
|
+
if (status === "default")
|
|
82
|
+
return "default";
|
|
83
|
+
if (typeof status === "number")
|
|
84
|
+
return String(status);
|
|
85
|
+
return status.start % 100 === 0 && status.end === status.start + 99
|
|
86
|
+
? `${status.start / 100}XX`
|
|
87
|
+
: undefined;
|
|
88
|
+
};
|
|
89
|
+
/** The C# type of a case's body, which `typeof` can name. */
|
|
90
|
+
function bodyType(model, chosen) {
|
|
91
|
+
const { content } = chosen.found;
|
|
92
|
+
const body = content.body && chosen.members.find((m) => m.name === "Body");
|
|
93
|
+
if (!body)
|
|
94
|
+
return undefined;
|
|
95
|
+
const reference = content.body.kind === "single" && isReference(model, content.body.type);
|
|
96
|
+
// `typeof` cannot name a nullable reference type.
|
|
97
|
+
return reference ? body.type.replace(/\?$/, "") : body.type;
|
|
98
|
+
}
|
|
99
|
+
/** The types of the other bodies a status of an operation may have, beside `first`. */
|
|
100
|
+
export function otherBodies(model, operation, key, first) {
|
|
101
|
+
const types = operation.cases
|
|
102
|
+
.filter((chosen) => statusKey(chosen.found.response.status) === key)
|
|
103
|
+
.flatMap((chosen) => bodyType(model, chosen) ?? []);
|
|
104
|
+
return [...new Set(types)].filter((type) => type !== first);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The first case of each status that can be named in a document, which has one response for each
|
|
108
|
+
* status.
|
|
109
|
+
*/
|
|
110
|
+
export function documentedCases(model, operation) {
|
|
111
|
+
const found = new Map();
|
|
112
|
+
for (const chosen of operation.cases) {
|
|
113
|
+
const { response, content } = chosen.found;
|
|
114
|
+
const key = statusKey(response.status);
|
|
115
|
+
if (!key || found.has(key))
|
|
116
|
+
continue;
|
|
117
|
+
const type = bodyType(model, chosen);
|
|
118
|
+
found.set(key, {
|
|
119
|
+
key,
|
|
120
|
+
found: chosen,
|
|
121
|
+
...(type && {
|
|
122
|
+
body: {
|
|
123
|
+
type,
|
|
124
|
+
contentType: content.body.contentTypes.find((t) => !t.includes("*")) ?? "application/json",
|
|
125
|
+
},
|
|
126
|
+
}),
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return [...found.values()];
|
|
130
|
+
}
|
|
@@ -8,6 +8,36 @@ function decode(text) {
|
|
|
8
8
|
return text;
|
|
9
9
|
}
|
|
10
10
|
}
|
|
11
|
+
/** A segment of a route that holds only text. */
|
|
12
|
+
function literalSegment(text) {
|
|
13
|
+
return { text: decode(text).replaceAll("{", "{{").replaceAll("}", "}}"), trailing: false };
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The path of a server URL, without its last `/`. A URL that does not start with `/` starts with
|
|
17
|
+
* its host, or with a parameter standing for one.
|
|
18
|
+
*/
|
|
19
|
+
function pathOf(url) {
|
|
20
|
+
const [address] = url.split(/[?#]/);
|
|
21
|
+
const rest = address.replace(/^([^/]*:)?\/\//, "");
|
|
22
|
+
const from = rest !== address || !address.startsWith("/") ? rest.indexOf("/") : 0;
|
|
23
|
+
return from < 0 ? "" : rest.slice(from).replace(/\/+$/, "");
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The segments every route of a service starts with: the path its servers agree on. Nothing is
|
|
27
|
+
* added, with a warning, when they differ or the path holds a parameter.
|
|
28
|
+
*/
|
|
29
|
+
function serverPrefix(program, service) {
|
|
30
|
+
const paths = [...new Set(service.servers.map((server) => pathOf(server.url)))];
|
|
31
|
+
if (paths.length > 1 || paths[0]?.includes("{")) {
|
|
32
|
+
reportDiagnostic(program, {
|
|
33
|
+
code: "server-path-ignored",
|
|
34
|
+
format: { paths: paths.map((path) => `"${path || "/"}"`).join(", ") },
|
|
35
|
+
target: service.source,
|
|
36
|
+
});
|
|
37
|
+
return [];
|
|
38
|
+
}
|
|
39
|
+
return (paths[0] ?? "").split("/").filter(Boolean).map(literalSegment);
|
|
40
|
+
}
|
|
11
41
|
/** Reads the URI template of an operation. Returns what is wrong when ASP.NET Core cannot map it. */
|
|
12
42
|
export function parseRoute(operation) {
|
|
13
43
|
const literal = (text) => text.replaceAll("{", "{{").replaceAll("}", "}}");
|
|
@@ -170,8 +200,11 @@ function differInValue(a, b) {
|
|
|
170
200
|
/** Reads every route, and works out how requests reach operations that share one. */
|
|
171
201
|
export function planRoutes(program, model) {
|
|
172
202
|
const routes = new Map();
|
|
173
|
-
const operations = model.services.flatMap((
|
|
174
|
-
|
|
203
|
+
const operations = model.services.flatMap((service) => {
|
|
204
|
+
const prefix = serverPrefix(program, service);
|
|
205
|
+
return service.groups.flatMap((group) => group.operations.map((operation) => ({ operation, prefix })));
|
|
206
|
+
});
|
|
207
|
+
for (const { operation, prefix } of operations) {
|
|
175
208
|
const route = parseRoute(operation);
|
|
176
209
|
if (typeof route === "string") {
|
|
177
210
|
reportDiagnostic(program, {
|
|
@@ -181,7 +214,7 @@ export function planRoutes(program, model) {
|
|
|
181
214
|
});
|
|
182
215
|
}
|
|
183
216
|
else {
|
|
184
|
-
routes.set(operation, route);
|
|
217
|
+
routes.set(operation, { ...route, segments: [...prefix, ...route.segments] });
|
|
185
218
|
}
|
|
186
219
|
}
|
|
187
220
|
const found = [...routes].map(([operation, route]) => ({
|
package/package.json
CHANGED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import type { ApiModel } from "../../model/types.js";
|
|
2
|
-
import type { ServiceContract } from "../shared/services.js";
|
|
3
|
-
import type { Binding } from "../shared/binding.js";
|
|
4
|
-
export declare function documentationWriter(model: ApiModel, rootNamespace: string, openapi: boolean): (group: string, contract: ServiceContract["operations"][number], binding: Binding, endpoint: string) => string[];
|