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.
- package/README.md +11 -4
- package/dist/src/emitter.js +104 -5
- package/dist/src/lib.d.ts +47 -2
- package/dist/src/lib.js +18 -0
- package/dist/src/model/collect-types.d.ts +3 -1
- package/dist/src/model/collect-types.js +1 -1
- package/dist/src/model/collect.js +56 -6
- package/dist/src/model/types.d.ts +12 -0
- package/dist/src/naming/names.d.ts +1 -1
- package/dist/src/naming/names.js +13 -3
- package/dist/src/naming/services.d.ts +11 -1
- package/dist/src/naming/services.js +18 -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 +14 -0
- package/dist/src/render/minimal/endpoints.js +161 -0
- package/dist/src/render/minimal/results.d.ts +11 -0
- package/dist/src/render/minimal/results.js +90 -0
- package/dist/src/render/shared/api-setup.d.ts +9 -1
- package/dist/src/render/shared/api-setup.js +165 -11
- package/dist/src/render/shared/binding.d.ts +43 -0
- package/dist/src/render/shared/binding.js +426 -0
- 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/headers.d.ts +7 -0
- package/dist/src/render/shared/headers.js +52 -0
- package/dist/src/render/shared/models.js +5 -23
- package/dist/src/render/shared/openapi.d.ts +1 -0
- package/dist/src/render/shared/openapi.js +333 -0
- package/dist/src/render/shared/parameters.d.ts +3 -0
- package/dist/src/render/shared/parameters.js +224 -0
- package/dist/src/render/shared/references.d.ts +3 -0
- package/dist/src/render/shared/references.js +18 -0
- package/dist/src/render/shared/request-selector.d.ts +1 -0
- package/dist/src/render/shared/request-selector.js +139 -0
- 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.d.ts +37 -0
- package/dist/src/render/shared/routes.js +274 -0
- package/dist/src/render/shared/validation.d.ts +6 -1
- package/dist/src/render/shared/validation.js +60 -0
- package/dist/src/scaffold/projects.d.ts +1 -1
- package/dist/src/scaffold/projects.js +4 -3
- package/package.json +2 -2
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// The generated helpers that read request values ASP.NET Core does not read as the spec writes them.
|
|
2
|
+
export function renderParameters(rootNamespace) {
|
|
3
|
+
return `// <auto-generated/>
|
|
4
|
+
// Generated by Sheridan.Typespec.Aspnet. Do not edit.
|
|
5
|
+
#nullable enable
|
|
6
|
+
|
|
7
|
+
namespace ${rootNamespace}.Requests;
|
|
8
|
+
|
|
9
|
+
// Inside the namespace, so that a type in the spec cannot hide these.
|
|
10
|
+
using global::System;
|
|
11
|
+
using global::System.Collections.Generic;
|
|
12
|
+
using global::System.ComponentModel.DataAnnotations;
|
|
13
|
+
using global::System.Linq;
|
|
14
|
+
using global::System.IO;
|
|
15
|
+
using global::System.Text;
|
|
16
|
+
using global::System.Text.Json;
|
|
17
|
+
using global::System.Text.Json.Serialization;
|
|
18
|
+
using global::System.Threading;
|
|
19
|
+
using global::System.Threading.Tasks;
|
|
20
|
+
using global::Microsoft.AspNetCore.Http;
|
|
21
|
+
|
|
22
|
+
/// <summary>A value of a request that breaks a constraint of the spec.</summary>
|
|
23
|
+
internal sealed class RequestInvalidException(string name, string message) : Exception(message)
|
|
24
|
+
{
|
|
25
|
+
public string Name { get; } = name;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/// <summary>Reads values of a request. What cannot be read is answered with 400.</summary>
|
|
29
|
+
internal static class Parameters
|
|
30
|
+
{
|
|
31
|
+
private static readonly JsonSerializerOptions Options = Create(null);
|
|
32
|
+
|
|
33
|
+
/// <summary>Reads text as the JSON of the type is read: a number as it is, else a string.</summary>
|
|
34
|
+
public static T Value<T>(string text, bool number, string name) =>
|
|
35
|
+
Read<T>(text, number, name, Options);
|
|
36
|
+
|
|
37
|
+
/// <summary>Reads text with the converter of an encoding.</summary>
|
|
38
|
+
public static T Value<T, TConverter>(string text, bool number, string name)
|
|
39
|
+
where TConverter : JsonConverter, new() =>
|
|
40
|
+
Read<T>(text, number, name, Converted<TConverter>.Options);
|
|
41
|
+
|
|
42
|
+
/// <summary>Reads a value from text already at hand.</summary>
|
|
43
|
+
public static T With<T>(string text, Converter<string, T> read) => read(text);
|
|
44
|
+
|
|
45
|
+
public static T[] List<T>(string[] items, Converter<string, T> read) =>
|
|
46
|
+
Array.ConvertAll(items, read);
|
|
47
|
+
|
|
48
|
+
/// <summary>The items of a list written as one value, separated by commas.</summary>
|
|
49
|
+
public static string[] Split(string text, bool trim) =>
|
|
50
|
+
text.Length == 0
|
|
51
|
+
? []
|
|
52
|
+
: text.Split(',', trim ? StringSplitOptions.TrimEntries : StringSplitOptions.None);
|
|
53
|
+
|
|
54
|
+
/// <summary>The items of a list of HTTP dates, each of which holds one comma.</summary>
|
|
55
|
+
public static string[] SplitDates(string text)
|
|
56
|
+
{
|
|
57
|
+
var parts = Split(text, false);
|
|
58
|
+
var dates = new string[(parts.Length + 1) / 2];
|
|
59
|
+
for (var index = 0; index < dates.Length; index++)
|
|
60
|
+
{
|
|
61
|
+
var first = index * 2;
|
|
62
|
+
dates[index] = first + 1 < parts.Length
|
|
63
|
+
? $"{parts[first]},{parts[first + 1]}".Trim()
|
|
64
|
+
: parts[first];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return dates;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// <summary>The text of a value as JSON writes it, or null for none.</summary>
|
|
71
|
+
public static string? Write<T>(T value) => Text(value, Options);
|
|
72
|
+
|
|
73
|
+
/// <summary>The text of a value written with the converter of an encoding.</summary>
|
|
74
|
+
public static string? Write<T, TConverter>(T value)
|
|
75
|
+
where TConverter : JsonConverter, new() =>
|
|
76
|
+
Text(value, Converted<TConverter>.Options);
|
|
77
|
+
|
|
78
|
+
/// <summary>A list written as one value, separated by commas.</summary>
|
|
79
|
+
public static string? Join(IEnumerable<string?>? items) =>
|
|
80
|
+
items is null ? null : string.Join(", ", items.Where(item => item is not null));
|
|
81
|
+
|
|
82
|
+
public static string? Join<T>(IEnumerable<T>? items, Func<T, string?> write) =>
|
|
83
|
+
items is null ? null : Join(items.Select(write));
|
|
84
|
+
|
|
85
|
+
private static string? Text<T>(T value, JsonSerializerOptions options)
|
|
86
|
+
{
|
|
87
|
+
var json = JsonSerializer.Serialize(value, options);
|
|
88
|
+
return json.StartsWith('"')
|
|
89
|
+
? JsonSerializer.Deserialize<string>(json)
|
|
90
|
+
: json == "null" ? null : json;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/// <summary>Returns a value that meets every constraint on it. An absent value does.</summary>
|
|
94
|
+
public static T Check<T>(T value, string name, params ValidationAttribute[] constraints)
|
|
95
|
+
{
|
|
96
|
+
foreach (var constraint in constraints)
|
|
97
|
+
{
|
|
98
|
+
if (!constraint.IsValid(value))
|
|
99
|
+
{
|
|
100
|
+
throw new RequestInvalidException(name, constraint.FormatErrorMessage(name));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
public static string Required(string? text, string name) =>
|
|
108
|
+
text ?? throw new BadHttpRequestException($"The value \\"{name}\\" is required.");
|
|
109
|
+
|
|
110
|
+
/// <summary>The body as text, or null when none was sent and none is required.</summary>
|
|
111
|
+
public static async Task<string> Text(HttpRequest request, bool optional, CancellationToken cancellationToken)
|
|
112
|
+
{
|
|
113
|
+
var bytes = await Bytes(request, optional, cancellationToken);
|
|
114
|
+
if (bytes is null)
|
|
115
|
+
{
|
|
116
|
+
return null!;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
var charset = request.GetTypedHeaders().ContentType?.Encoding;
|
|
120
|
+
using var reader = new StreamReader(new MemoryStream(bytes), charset ?? Encoding.UTF8);
|
|
121
|
+
return await reader.ReadToEndAsync(cancellationToken);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/// <summary>The body as bytes, or null when none was sent and none is required.</summary>
|
|
125
|
+
public static async Task<byte[]> Bytes(HttpRequest request, bool optional, CancellationToken cancellationToken)
|
|
126
|
+
{
|
|
127
|
+
using var buffer = new MemoryStream();
|
|
128
|
+
await request.Body.CopyToAsync(buffer, cancellationToken);
|
|
129
|
+
return optional && buffer.Length == 0 && request.ContentType is null ? null! : buffer.ToArray();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private static T Read<T>(string text, bool number, string name, JsonSerializerOptions options)
|
|
133
|
+
{
|
|
134
|
+
try
|
|
135
|
+
{
|
|
136
|
+
var json = number ? text : JsonSerializer.Serialize(text);
|
|
137
|
+
if (JsonSerializer.Deserialize<T>(json, options) is { } value)
|
|
138
|
+
{
|
|
139
|
+
return value;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
catch (Exception error) when (error is JsonException or FormatException
|
|
143
|
+
or InvalidOperationException or ArgumentException or NotSupportedException or OverflowException)
|
|
144
|
+
{
|
|
145
|
+
throw new BadHttpRequestException($"The value \\"{name}\\" is not valid.", error);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
throw new BadHttpRequestException($"The value \\"{name}\\" is not valid.");
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private static JsonSerializerOptions Create(JsonConverter? converter)
|
|
152
|
+
{
|
|
153
|
+
var options = new JsonSerializerOptions();
|
|
154
|
+
global::${rootNamespace}.Serialization.JsonSetup.Configure(options);
|
|
155
|
+
if (converter is not null)
|
|
156
|
+
{
|
|
157
|
+
options.Converters.Add(converter);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return options;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private static class Converted<TConverter>
|
|
164
|
+
where TConverter : JsonConverter, new()
|
|
165
|
+
{
|
|
166
|
+
public static readonly JsonSerializerOptions Options = Create(new TConverter());
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
`;
|
|
170
|
+
}
|
|
171
|
+
/** The generated helpers that send what ASP.NET Core's results do not. */
|
|
172
|
+
export function renderResponses(rootNamespace) {
|
|
173
|
+
return `// <auto-generated/>
|
|
174
|
+
// Generated by Sheridan.Typespec.Aspnet. Do not edit.
|
|
175
|
+
#nullable enable
|
|
176
|
+
|
|
177
|
+
namespace ${rootNamespace}.Responses;
|
|
178
|
+
|
|
179
|
+
// Inside the namespace, so that a type in the spec cannot hide these.
|
|
180
|
+
using global::System.Threading.Tasks;
|
|
181
|
+
using global::Microsoft.AspNetCore.Http;
|
|
182
|
+
|
|
183
|
+
/// <summary>Adds a declared header to a result.</summary>
|
|
184
|
+
public static class ResponseHeaders
|
|
185
|
+
{
|
|
186
|
+
/// <summary>Sets a header, unless it has no value, and returns the result.</summary>
|
|
187
|
+
public static TResult With<TResult>(TResult result, HttpContext context, string name, string? value)
|
|
188
|
+
{
|
|
189
|
+
if (value is not null)
|
|
190
|
+
{
|
|
191
|
+
context.Response.Headers[name] = value;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return result;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/// <summary>A body of bytes with any status.</summary>
|
|
199
|
+
public sealed class BytesHttpResult(int statusCode, byte[]? body, string contentType)
|
|
200
|
+
: IResult, IStatusCodeHttpResult, IContentTypeHttpResult
|
|
201
|
+
{
|
|
202
|
+
public int StatusCode { get; } = statusCode;
|
|
203
|
+
|
|
204
|
+
int? IStatusCodeHttpResult.StatusCode => StatusCode;
|
|
205
|
+
|
|
206
|
+
public byte[]? Body { get; } = body;
|
|
207
|
+
|
|
208
|
+
public string ContentType { get; } = contentType;
|
|
209
|
+
|
|
210
|
+
public async Task ExecuteAsync(HttpContext httpContext)
|
|
211
|
+
{
|
|
212
|
+
httpContext.Response.StatusCode = StatusCode;
|
|
213
|
+
if (Body is null)
|
|
214
|
+
{
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
httpContext.Response.ContentType = ContentType;
|
|
219
|
+
httpContext.Response.ContentLength = Body.Length;
|
|
220
|
+
await httpContext.Response.Body.WriteAsync(Body, httpContext.RequestAborted);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
`;
|
|
224
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** True when C# holds the type by reference, so that `?` does not make another type of it. */
|
|
2
|
+
export function isReference(model, ref) {
|
|
3
|
+
if (ref.kind === "nullable")
|
|
4
|
+
return isReference(model, ref.type);
|
|
5
|
+
if (ref.kind === "array" || ref.kind === "record")
|
|
6
|
+
return true;
|
|
7
|
+
if (ref.kind === "literal")
|
|
8
|
+
return typeof ref.value === "string";
|
|
9
|
+
const builtinReference = (name) => ["string", "bytes", "url"].includes(name ?? "");
|
|
10
|
+
if (ref.kind === "scalar")
|
|
11
|
+
return builtinReference(ref.name);
|
|
12
|
+
if (ref.kind !== "named")
|
|
13
|
+
return false;
|
|
14
|
+
const declared = model.types.get(ref.id);
|
|
15
|
+
if (declared.kind === "scalar")
|
|
16
|
+
return builtinReference(declared.builtin);
|
|
17
|
+
return declared.kind === "model";
|
|
18
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function renderRequestSelector(rootNamespace: string, controllers?: boolean): string;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Chooses between operations that share a verb and route, in either style.
|
|
2
|
+
import { csharpFile } from "./writer.js";
|
|
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
|
+
: "";
|
|
57
|
+
return csharpFile(`${rootNamespace}.Routing`, `// Inside the namespace, so that a type of the spec named alike does not hide these.
|
|
58
|
+
using global::Microsoft.AspNetCore.Http;
|
|
59
|
+
using global::Microsoft.AspNetCore.Routing;
|
|
60
|
+
using global::Microsoft.AspNetCore.Routing.Matching;
|
|
61
|
+
|
|
62
|
+
/// <summary>A query value or header a request must carry.</summary>
|
|
63
|
+
internal sealed record RequiredValue(bool Header, string Name, string Value, bool IgnoreCase)
|
|
64
|
+
{
|
|
65
|
+
public bool IsIn(HttpRequest request)
|
|
66
|
+
{
|
|
67
|
+
var found = Header ? request.Headers[Name] : request.Query[Name];
|
|
68
|
+
var comparison = IgnoreCase
|
|
69
|
+
? global::System.StringComparison.OrdinalIgnoreCase
|
|
70
|
+
: global::System.StringComparison.Ordinal;
|
|
71
|
+
return found.Count == 1 && string.Equals(found[0], Value, comparison);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/// <summary>What a request must carry to reach one of the operations sharing a route.</summary>
|
|
76
|
+
internal sealed record RequestCondition(RequiredValue[] Values, string[] ContentTypes)
|
|
77
|
+
{
|
|
78
|
+
${of} public bool IsMetBy(HttpRequest request)
|
|
79
|
+
{
|
|
80
|
+
foreach (var value in Values)
|
|
81
|
+
{
|
|
82
|
+
if (!value.IsIn(request))
|
|
83
|
+
{
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (ContentTypes.Length == 0)
|
|
89
|
+
{
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
var sent = request.ContentType?.Split(';')[0].Trim();
|
|
94
|
+
foreach (var type in ContentTypes)
|
|
95
|
+
{
|
|
96
|
+
if (string.Equals(type, sent, global::System.StringComparison.OrdinalIgnoreCase))
|
|
97
|
+
{
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/// <summary>Leaves only the operations whose condition a request meets.</summary>
|
|
107
|
+
internal sealed class RequestSelector : MatcherPolicy, IEndpointSelectorPolicy
|
|
108
|
+
{
|
|
109
|
+
public override int Order => 0;
|
|
110
|
+
|
|
111
|
+
public bool AppliesToEndpoints(global::System.Collections.Generic.IReadOnlyList<Endpoint> endpoints)
|
|
112
|
+
{
|
|
113
|
+
foreach (var endpoint in endpoints)
|
|
114
|
+
{
|
|
115
|
+
if (${applies} is not null)
|
|
116
|
+
{
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
public global::System.Threading.Tasks.Task ApplyAsync(HttpContext httpContext, CandidateSet candidates)
|
|
125
|
+
{
|
|
126
|
+
for (var index = 0; index < candidates.Count; index++)
|
|
127
|
+
{
|
|
128
|
+
if (candidates.IsValidCandidate(index)
|
|
129
|
+
&& ${read} is { } condition
|
|
130
|
+
&& !condition.IsMetBy(httpContext.Request))
|
|
131
|
+
{
|
|
132
|
+
candidates.SetValidity(index, false);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return global::System.Threading.Tasks.Task.CompletedTask;
|
|
137
|
+
}
|
|
138
|
+
}${attributes}`);
|
|
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
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Program } from "@typespec/compiler";
|
|
2
|
+
import type { ApiModel, OperationModel } from "../../model/types.js";
|
|
3
|
+
export interface Segment {
|
|
4
|
+
/** As written in an ASP.NET Core route template. */
|
|
5
|
+
text: string;
|
|
6
|
+
/** True for an optional parameter or a catch-all, which only the end of a route can hold. */
|
|
7
|
+
trailing: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface Route {
|
|
10
|
+
segments: Segment[];
|
|
11
|
+
/** Query values written into the route, such as `?kind=a`. */
|
|
12
|
+
query: [name: string, value: string][];
|
|
13
|
+
}
|
|
14
|
+
/** A value a request must carry to reach an operation. */
|
|
15
|
+
export interface RequiredValue {
|
|
16
|
+
in: "query" | "header";
|
|
17
|
+
name: string;
|
|
18
|
+
value: string;
|
|
19
|
+
ignoreCase: boolean;
|
|
20
|
+
}
|
|
21
|
+
/** What tells an operation apart from the others of its verb and route. */
|
|
22
|
+
export interface Condition {
|
|
23
|
+
values: RequiredValue[];
|
|
24
|
+
/** Empty when the content type does not matter. */
|
|
25
|
+
contentTypes: string[];
|
|
26
|
+
/** The content types of every operation told apart by one, this one included. */
|
|
27
|
+
accepted: string[];
|
|
28
|
+
}
|
|
29
|
+
/** Reads the URI template of an operation. Returns what is wrong when ASP.NET Core cannot map it. */
|
|
30
|
+
export declare function parseRoute(operation: OperationModel): Route | string;
|
|
31
|
+
export interface Routing {
|
|
32
|
+
routes: Map<OperationModel, Route>;
|
|
33
|
+
/** For operations sharing a verb and route. */
|
|
34
|
+
conditions: Map<OperationModel, Condition>;
|
|
35
|
+
}
|
|
36
|
+
/** Reads every route, and works out how requests reach operations that share one. */
|
|
37
|
+
export declare function planRoutes(program: Program, model: ApiModel): Routing;
|