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,161 @@
|
|
|
1
|
+
import { csharpFile, stringLiteral } from "../shared/writer.js";
|
|
2
|
+
const builder = "global::Microsoft.AspNetCore.Builder";
|
|
3
|
+
const routeBuilder = `${builder}.EndpointRouteBuilderExtensions`;
|
|
4
|
+
const groupType = "global::Microsoft.AspNetCore.Routing.RouteGroupBuilder";
|
|
5
|
+
const withTags = "global::Microsoft.AspNetCore.Http.OpenApiRouteHandlerBuilderExtensions.WithTags";
|
|
6
|
+
const withMetadata = `${builder}.RoutingEndpointConventionBuilderExtensions.WithMetadata`;
|
|
7
|
+
const withName = `${builder}.RoutingEndpointConventionBuilderExtensions.WithName`;
|
|
8
|
+
const openApi = "global::Microsoft.AspNetCore.Http.OpenApiRouteHandlerBuilderExtensions";
|
|
9
|
+
const withSummary = `${openApi}.WithSummary`;
|
|
10
|
+
const withDescription = `${openApi}.WithDescription`;
|
|
11
|
+
const mapMethods = {
|
|
12
|
+
get: "MapGet",
|
|
13
|
+
put: "MapPut",
|
|
14
|
+
post: "MapPost",
|
|
15
|
+
patch: "MapPatch",
|
|
16
|
+
delete: "MapDelete",
|
|
17
|
+
};
|
|
18
|
+
const mvc = "global::Microsoft.AspNetCore.Mvc";
|
|
19
|
+
const attributes = {
|
|
20
|
+
route: "FromRoute",
|
|
21
|
+
query: "FromQuery",
|
|
22
|
+
header: "FromHeader",
|
|
23
|
+
body: "FromBody",
|
|
24
|
+
service: "FromServices",
|
|
25
|
+
};
|
|
26
|
+
function declaration({ source, wireName, type, name, attributes: checks, }) {
|
|
27
|
+
const attribute = attributes[source];
|
|
28
|
+
const named = wireName === undefined ? "" : `(Name = ${stringLiteral(wireName)})`;
|
|
29
|
+
const constraints = (checks ?? []).map((check) => `[${check}] `).join("");
|
|
30
|
+
return `${attribute ? `[${mvc}.${attribute}Attribute${named}] ` : ""}${constraints}${type} ${name}`;
|
|
31
|
+
}
|
|
32
|
+
/** A handler that binds the inputs of an operation, calls its service and maps the result. */
|
|
33
|
+
function handler(name, method, { binding, result }) {
|
|
34
|
+
const service = binding.parameters.find((parameter) => parameter.source === "service");
|
|
35
|
+
const list = binding.parameters.map((parameter) => ` ${declaration(parameter)}`);
|
|
36
|
+
const values = binding.values.map((value) => ` ${value}`);
|
|
37
|
+
// Public, so that a handler can be tested on its own. It has no documentation comment, which
|
|
38
|
+
// would replace what the spec says of the operation in OpenAPI.
|
|
39
|
+
return [
|
|
40
|
+
` public static async global::System.Threading.Tasks.Task<${result.type}> ${name}(`,
|
|
41
|
+
`${list.join(",\n")})`,
|
|
42
|
+
" {",
|
|
43
|
+
` var ${binding.result} = await ${service.name}.${method}(`,
|
|
44
|
+
`${values.join(",\n")});`,
|
|
45
|
+
` return ${binding.result} switch`,
|
|
46
|
+
" {",
|
|
47
|
+
...result.arms.map((arm) => ` ${arm},`),
|
|
48
|
+
' null => throw new global::System.InvalidOperationException("The service returned no result."),',
|
|
49
|
+
" };",
|
|
50
|
+
" }",
|
|
51
|
+
].join("\n");
|
|
52
|
+
}
|
|
53
|
+
/** The calls naming and describing the endpoint held in `endpoint`. */
|
|
54
|
+
function describe(endpoint, found) {
|
|
55
|
+
const { name, summary, description, produces, operation } = found;
|
|
56
|
+
const lines = [` ${withName}(${endpoint}, ${stringLiteral(name)});`];
|
|
57
|
+
if (summary)
|
|
58
|
+
lines.push(` ${withSummary}(${endpoint}, ${stringLiteral(summary)});`);
|
|
59
|
+
if (description) {
|
|
60
|
+
lines.push(` ${withDescription}(${endpoint}, ${stringLiteral(description)});`);
|
|
61
|
+
}
|
|
62
|
+
if (!operation)
|
|
63
|
+
return lines;
|
|
64
|
+
lines.push(` ${withMetadata}(`, ` ${endpoint},`, `${[...produces, operation].map((item) => ` ${item}`).join(",\n")});`);
|
|
65
|
+
return lines;
|
|
66
|
+
}
|
|
67
|
+
/** The leading segments every route of a group starts with, which the group's builder takes. */
|
|
68
|
+
function commonPrefix(routes) {
|
|
69
|
+
let length = 0;
|
|
70
|
+
while (routes.every((route) => route[length] !== undefined &&
|
|
71
|
+
!route[length].trailing &&
|
|
72
|
+
route[length].text === routes[0][length].text)) {
|
|
73
|
+
length++;
|
|
74
|
+
}
|
|
75
|
+
return length;
|
|
76
|
+
}
|
|
77
|
+
const template = (segments) => segments.map((segment) => `/${segment.text}`).join("");
|
|
78
|
+
const list = (values) => values.map(stringLiteral).join(", ");
|
|
79
|
+
function condition(rootNamespace, found, bodyType) {
|
|
80
|
+
const { values, contentTypes, accepted } = found;
|
|
81
|
+
const routing = `global::${rootNamespace}.Routing`;
|
|
82
|
+
const written = values.map((v) => `new ${routing}.RequiredValue(${v.in === "header"}, ${stringLiteral(v.name)}, ${stringLiteral(v.value)}, ${v.ignoreCase})`);
|
|
83
|
+
const array = (type, items) => items.length
|
|
84
|
+
? `new ${type}[] { ${items.join(", ")} }`
|
|
85
|
+
: `global::System.Array.Empty<${type}>()`;
|
|
86
|
+
const metadata = [
|
|
87
|
+
`new ${routing}.RequestCondition(`,
|
|
88
|
+
` ${array(`${routing}.RequiredValue`, written)},`,
|
|
89
|
+
` ${array("string", contentTypes.map(stringLiteral))})`,
|
|
90
|
+
];
|
|
91
|
+
// ASP.NET Core answers 415 itself when no operation accepts the content type.
|
|
92
|
+
if (contentTypes.length) {
|
|
93
|
+
metadata[metadata.length - 1] += ",";
|
|
94
|
+
metadata.push(`new global::Microsoft.AspNetCore.Http.Metadata.AcceptsMetadata(new string[] { ${list(accepted)} }, ${bodyType})`);
|
|
95
|
+
}
|
|
96
|
+
return metadata;
|
|
97
|
+
}
|
|
98
|
+
/** Renders the endpoint class of every group. */
|
|
99
|
+
export function renderEndpoints(rootNamespace, services, routing, handle) {
|
|
100
|
+
return services.map((service) => {
|
|
101
|
+
const { name, file, map, handlers } = service.endpoints;
|
|
102
|
+
const routes = service.operations.map((o) => routing.routes.get(o.operation));
|
|
103
|
+
const prefix = commonPrefix(routes.map((route) => route.segments));
|
|
104
|
+
const tags = service.group.tags ?? [service.group.name].filter(Boolean);
|
|
105
|
+
const handled = service.operations.map((_, index) => handle(service, index));
|
|
106
|
+
const mappings = service.operations.map(({ operation }, index) => {
|
|
107
|
+
const pattern = stringLiteral(template(routes[index].segments.slice(prefix)));
|
|
108
|
+
const call = operation.verb === "head"
|
|
109
|
+
? `${routeBuilder}.MapMethods(group, ${pattern}, new string[] { "HEAD" }, ${handlers[index]})`
|
|
110
|
+
: `${routeBuilder}.${mapMethods[operation.verb]}(group, ${pattern}, ${handlers[index]})`;
|
|
111
|
+
const found = routing.conditions.get(operation);
|
|
112
|
+
// Tags of an endpoint replace those of its group, so they are repeated.
|
|
113
|
+
const own = operation.tags && [...new Set([...tags, ...operation.tags])];
|
|
114
|
+
// A body read by hand declares what it takes, unless the condition does.
|
|
115
|
+
const accepts = found?.accepted.length ? [] : handled[index].binding.accepts;
|
|
116
|
+
const lines = [
|
|
117
|
+
` var endpoint${index} = ${call};`,
|
|
118
|
+
...describe(`endpoint${index}`, handled[index].documentation),
|
|
119
|
+
];
|
|
120
|
+
if (own)
|
|
121
|
+
lines.push(` ${withTags}(endpoint${index}, ${list(own)});`);
|
|
122
|
+
if (accepts.length) {
|
|
123
|
+
lines.push(` ${withMetadata}(`, ` endpoint${index},`, ` new global::Microsoft.AspNetCore.Http.Metadata.AcceptsMetadata(new string[] { ${list(accepts)} }, ${handled[index].binding.bodyType}));`);
|
|
124
|
+
}
|
|
125
|
+
const { converted } = handled[index].binding;
|
|
126
|
+
if (converted) {
|
|
127
|
+
lines.push(` global::${rootNamespace}.Requests.BodyFormats.Accept(`, ` endpoint${index},`, ` ${converted.shape},`, ` new string[] { ${list(converted.types)} });`);
|
|
128
|
+
}
|
|
129
|
+
if (found) {
|
|
130
|
+
lines.push(` ${withMetadata}(`, ` endpoint${index},`, condition(rootNamespace, found, handled[index].binding.bodyType)
|
|
131
|
+
.map((line) => ` ${line}`)
|
|
132
|
+
.join("\n") + ");");
|
|
133
|
+
}
|
|
134
|
+
return lines.join("\n");
|
|
135
|
+
});
|
|
136
|
+
const body = [
|
|
137
|
+
`/// <summary>Maps the routes of <c>${service.name}</c>.</summary>`,
|
|
138
|
+
`public static class ${name}`,
|
|
139
|
+
"{",
|
|
140
|
+
" /// <summary>Maps the routes in a group of their own.</summary>",
|
|
141
|
+
" /// <returns>The group, to add conventions to.</returns>",
|
|
142
|
+
` public static ${groupType} ${map}(`,
|
|
143
|
+
` this ${groupType} api)`,
|
|
144
|
+
" {",
|
|
145
|
+
` var group = ${routeBuilder}.MapGroup(api, ${stringLiteral(template(routes[0].segments.slice(0, prefix)))});`,
|
|
146
|
+
...(tags.length ? [` ${withTags}(group, ${list(tags)});`] : []),
|
|
147
|
+
...mappings,
|
|
148
|
+
" return group;",
|
|
149
|
+
" }",
|
|
150
|
+
"",
|
|
151
|
+
// The handlers have no documentation comments, whatever a project asks for.
|
|
152
|
+
"#pragma warning disable CS1591",
|
|
153
|
+
handlers
|
|
154
|
+
.map((name, index) => handler(name, service.operations[index].method, handled[index]))
|
|
155
|
+
.join("\n\n"),
|
|
156
|
+
"#pragma warning restore CS1591",
|
|
157
|
+
"}",
|
|
158
|
+
];
|
|
159
|
+
return { path: file, content: csharpFile(service.namespace, body.join("\n")) };
|
|
160
|
+
});
|
|
161
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Program } from "@typespec/compiler";
|
|
2
|
+
import type { ApiModel } from "../../model/types.js";
|
|
3
|
+
import type { HeaderWriter } from "../shared/headers.js";
|
|
4
|
+
import type { ServiceContract } from "../shared/services.js";
|
|
5
|
+
export interface ResultMapping {
|
|
6
|
+
/** What the handler returns. */
|
|
7
|
+
type: string;
|
|
8
|
+
/** The arms of the switch over the service's result. */
|
|
9
|
+
arms: string[];
|
|
10
|
+
}
|
|
11
|
+
export declare function resultWriter(program: Program, model: ApiModel, rootNamespace: string, headers: HeaderWriter): (operation: ServiceContract["operations"][number], value: string, context: string, namespace: string) => ResultMapping;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { arm, responseWriter } from "../shared/responses.js";
|
|
2
|
+
import { stringLiteral } from "../shared/writer.js";
|
|
3
|
+
const http = "global::Microsoft.AspNetCore.Http";
|
|
4
|
+
const results = `${http}.HttpResults`;
|
|
5
|
+
const typed = `${http}.TypedResults`;
|
|
6
|
+
/** The result types of ASP.NET Core with a body, for the statuses that have one of their own. */
|
|
7
|
+
const withBody = {
|
|
8
|
+
200: "Ok",
|
|
9
|
+
201: "Created",
|
|
10
|
+
202: "Accepted",
|
|
11
|
+
400: "BadRequest",
|
|
12
|
+
404: "NotFound",
|
|
13
|
+
409: "Conflict",
|
|
14
|
+
422: "UnprocessableEntity",
|
|
15
|
+
500: "InternalServerError",
|
|
16
|
+
};
|
|
17
|
+
/** Those without one, and the type each answers with. */
|
|
18
|
+
const withoutBody = {
|
|
19
|
+
200: ["Ok()", "Ok"],
|
|
20
|
+
201: ["Created()", "Created"],
|
|
21
|
+
202: ["Accepted((string?)null)", "Accepted"],
|
|
22
|
+
204: ["NoContent()", "NoContent"],
|
|
23
|
+
400: ["BadRequest()", "BadRequest"],
|
|
24
|
+
401: ["Unauthorized()", "UnauthorizedHttpResult"],
|
|
25
|
+
404: ["NotFound()", "NotFound"],
|
|
26
|
+
409: ["Conflict()", "Conflict"],
|
|
27
|
+
422: ["UnprocessableEntity()", "UnprocessableEntity"],
|
|
28
|
+
};
|
|
29
|
+
/** At most six types fit a `Results<>`, so more are nested in its last place (ADR 0023). */
|
|
30
|
+
function union(types) {
|
|
31
|
+
if (types.length === 1)
|
|
32
|
+
return types[0];
|
|
33
|
+
const held = types.length > 6 ? [...types.slice(0, 5), union(types.slice(5))] : types;
|
|
34
|
+
return `${results}.Results<${held.join(", ")}>`;
|
|
35
|
+
}
|
|
36
|
+
/** An expression of one of the types, cast through each `Results<>` it is nested in. */
|
|
37
|
+
function nested(expression, types, index) {
|
|
38
|
+
if (types.length <= 6 || index < 5)
|
|
39
|
+
return expression;
|
|
40
|
+
const rest = types.slice(5);
|
|
41
|
+
const inner = nested(expression, rest, index - 5);
|
|
42
|
+
return rest.length > 1
|
|
43
|
+
? `(${union(rest)})${inner.startsWith("(") ? inner : `(${inner})`}`
|
|
44
|
+
: inner;
|
|
45
|
+
}
|
|
46
|
+
export function resultWriter(program, model, rootNamespace, headers) {
|
|
47
|
+
const responses = `global::${rootNamespace}.Responses`;
|
|
48
|
+
const maker = {
|
|
49
|
+
empty({ fixed, code }) {
|
|
50
|
+
const known = fixed === undefined ? undefined : withoutBody[fixed];
|
|
51
|
+
return {
|
|
52
|
+
type: `${results}.${known ? known[1] : "StatusCodeHttpResult"}`,
|
|
53
|
+
expression: known ? `${typed}.${known[0]}` : `${typed}.StatusCode(${code})`,
|
|
54
|
+
};
|
|
55
|
+
},
|
|
56
|
+
json({ fixed, code }, held, body, contentType) {
|
|
57
|
+
const own = fixed === undefined ? undefined : withBody[fixed];
|
|
58
|
+
if (own && contentType?.toLowerCase() === "application/json") {
|
|
59
|
+
const uri = own === "Created" || own === "Accepted" ? "(string?)null, " : "";
|
|
60
|
+
return {
|
|
61
|
+
type: `${results}.${own}<${held}>`,
|
|
62
|
+
expression: `${typed}.${own}<${held}>(${uri}${body})`,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
type: `${results}.JsonHttpResult<${held}>`,
|
|
67
|
+
expression: `${typed}.Json<${held}>(${body}, contentType: ${stringLiteral(contentType ?? "application/json")}, statusCode: ${code})`,
|
|
68
|
+
};
|
|
69
|
+
},
|
|
70
|
+
text: ({ code }, text, contentType) => ({
|
|
71
|
+
type: `${results}.ContentHttpResult`,
|
|
72
|
+
expression: `${typed}.Text(${text}, ${stringLiteral(contentType)}, global::System.Text.Encoding.UTF8, ${code})`,
|
|
73
|
+
}),
|
|
74
|
+
bytes({ code }, body, contentType) {
|
|
75
|
+
const type = `${responses}.BytesHttpResult`;
|
|
76
|
+
return { type, expression: `new ${type}(${code}, ${body}, ${stringLiteral(contentType)})` };
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
const respond = responseWriter(program, model, rootNamespace, headers, maker);
|
|
80
|
+
/** Maps every case of an operation. `value` and `context` are free names in the handler. */
|
|
81
|
+
return function map(operation, value, context, namespace) {
|
|
82
|
+
const found = respond(operation, value, context);
|
|
83
|
+
const types = [...new Set(found.map((item) => item.type))];
|
|
84
|
+
const arms = found.map(({ chosen, type, expression }) => arm(namespace, operation, chosen, value, nested(expression, types, types.indexOf(type))));
|
|
85
|
+
return {
|
|
86
|
+
type: types.length ? union(types) : `${results}.NoContent`,
|
|
87
|
+
arms,
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -3,4 +3,12 @@ import { type Registration } from "./stubs.js";
|
|
|
3
3
|
* The three extensions a host calls (ADR 0033). Everything a later feature needs to register or
|
|
4
4
|
* add to the pipeline goes here, so that the host does not change.
|
|
5
5
|
*/
|
|
6
|
-
export declare function renderApiSetup(rootNamespace: string, api: string, required: Registration[]
|
|
6
|
+
export declare function renderApiSetup(rootNamespace: string, api: string, required: Registration[], endpoints?: {
|
|
7
|
+
calls: string[];
|
|
8
|
+
selector: boolean;
|
|
9
|
+
/** True when the generated controllers are to be mapped. */
|
|
10
|
+
controllers?: boolean;
|
|
11
|
+
/** True when handlers or actions check values themselves. */
|
|
12
|
+
checks?: boolean;
|
|
13
|
+
openapi?: boolean;
|
|
14
|
+
}): string;
|
|
@@ -4,7 +4,10 @@ import { csharpFile, stringLiteral } from "./writer.js";
|
|
|
4
4
|
* The three extensions a host calls (ADR 0033). Everything a later feature needs to register or
|
|
5
5
|
* add to the pipeline goes here, so that the host does not change.
|
|
6
6
|
*/
|
|
7
|
-
export function renderApiSetup(rootNamespace, api, required
|
|
7
|
+
export function renderApiSetup(rootNamespace, api, required, endpoints = {
|
|
8
|
+
calls: [],
|
|
9
|
+
selector: false,
|
|
10
|
+
}) {
|
|
8
11
|
const hasServices = required.length > 0;
|
|
9
12
|
const register = [
|
|
10
13
|
` global::${rootNamespace}.Serialization.JsonSetup.AddGeneratedJson(services);`,
|
|
@@ -15,20 +18,96 @@ export function renderApiSetup(rootNamespace, api, required) {
|
|
|
15
18
|
: []),
|
|
16
19
|
];
|
|
17
20
|
register.push(" global::Microsoft.Extensions.DependencyInjection.ProblemDetailsServiceCollectionExtensions.AddProblemDetails(services);");
|
|
21
|
+
const minimal = endpoints.calls.length > 0;
|
|
22
|
+
if (minimal) {
|
|
23
|
+
// A request that cannot be bound then reaches the middleware, which answers it as a problem.
|
|
24
|
+
register.push(" global::Microsoft.Extensions.DependencyInjection.OptionsServiceCollectionExtensions.Configure<global::Microsoft.AspNetCore.Routing.RouteHandlerOptions>(\n services, options => options.ThrowOnBadRequest = true);");
|
|
25
|
+
}
|
|
26
|
+
if (endpoints.controllers) {
|
|
27
|
+
register.push(` global::Microsoft.Extensions.DependencyInjection.MvcCoreMvcBuilderExtensions.AddApplicationPart(
|
|
28
|
+
global::Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddControllers(services),
|
|
29
|
+
typeof(${api}ApiExtensions).Assembly);`);
|
|
30
|
+
}
|
|
31
|
+
// MVC adds no check of its own: the generated controllers check as Minimal APIs do.
|
|
32
|
+
const validation = (minimal || endpoints.controllers) && endpoints.checks;
|
|
33
|
+
if (validation) {
|
|
34
|
+
// Called here, in the assembly whose endpoints take the types to be checked.
|
|
35
|
+
// As deep as JSON is read, so that a deep body is judged rather than a fault.
|
|
36
|
+
register.push(" services.AddValidation(options => options.MaxDepth = 64);");
|
|
37
|
+
}
|
|
38
|
+
if (endpoints.openapi) {
|
|
39
|
+
register.push(` global::${rootNamespace}.Documentation.OpenApiSetup.AddGeneratedOpenApi(services);`);
|
|
40
|
+
}
|
|
41
|
+
if (endpoints.selector) {
|
|
42
|
+
register.push(` global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(
|
|
43
|
+
services,
|
|
44
|
+
global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton<
|
|
45
|
+
global::Microsoft.AspNetCore.Routing.MatcherPolicy,
|
|
46
|
+
global::${rootNamespace}.Routing.RequestSelector>());`);
|
|
47
|
+
}
|
|
48
|
+
const document = endpoints.openapi
|
|
49
|
+
? [
|
|
50
|
+
" // The document describes the API, so only development serves it.",
|
|
51
|
+
" if (global::Microsoft.Extensions.Hosting.HostEnvironmentEnvExtensions.IsDevelopment(app.Environment))",
|
|
52
|
+
" {",
|
|
53
|
+
" global::Microsoft.AspNetCore.Builder.OpenApiEndpointRouteBuilderExtensions.MapOpenApi(app);",
|
|
54
|
+
" }",
|
|
55
|
+
"",
|
|
56
|
+
]
|
|
57
|
+
: [];
|
|
58
|
+
const controllers = endpoints.controllers
|
|
59
|
+
? [
|
|
60
|
+
" global::Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.MapControllers(app);",
|
|
61
|
+
...document,
|
|
62
|
+
].join("\n") + "\n"
|
|
63
|
+
: "";
|
|
64
|
+
const write = (result) => endpoints.controllers
|
|
65
|
+
? `await WriteProblem(context, ${result});`
|
|
66
|
+
: `await ${result}.ExecuteAsync(context);`;
|
|
67
|
+
const writeProblem = endpoints.controllers
|
|
68
|
+
? `
|
|
69
|
+
// MVC writes the problems of its actions its own way, leaving out the errors of a value, so
|
|
70
|
+
// the action is set aside while a problem is written as for a Minimal API endpoint.
|
|
71
|
+
private static async global::System.Threading.Tasks.Task WriteProblem(
|
|
72
|
+
global::Microsoft.AspNetCore.Http.HttpContext context,
|
|
73
|
+
global::Microsoft.AspNetCore.Http.IResult problem)
|
|
74
|
+
{
|
|
75
|
+
var endpoint = global::Microsoft.AspNetCore.Http.EndpointHttpContextExtensions.GetEndpoint(context);
|
|
76
|
+
global::Microsoft.AspNetCore.Http.EndpointHttpContextExtensions.SetEndpoint(context, null);
|
|
77
|
+
try
|
|
78
|
+
{
|
|
79
|
+
await problem.ExecuteAsync(context);
|
|
80
|
+
}
|
|
81
|
+
finally
|
|
82
|
+
{
|
|
83
|
+
global::Microsoft.AspNetCore.Http.EndpointHttpContextExtensions.SetEndpoint(context, endpoint);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
`
|
|
87
|
+
: "";
|
|
88
|
+
const mapped = endpoints.calls.length
|
|
89
|
+
? [
|
|
90
|
+
' var api = global::Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions.MapGroup(app, "");',
|
|
91
|
+
" global::Microsoft.AspNetCore.Builder.RoutingEndpointConventionBuilderExtensions.WithMetadata(api, new GeneratedEndpoint());",
|
|
92
|
+
" global::Microsoft.AspNetCore.Http.EndpointFilterExtensions.AddEndpointFilter(api, Bound);",
|
|
93
|
+
...endpoints.calls.map((call) => ` ${call}(api);`),
|
|
94
|
+
...document,
|
|
95
|
+
].join("\n") + "\n"
|
|
96
|
+
: controllers;
|
|
97
|
+
const summary = ` /// <summary>
|
|
98
|
+
/// Maps the routes of the API, after checking that every service is registered.
|
|
99
|
+
/// </summary>`;
|
|
18
100
|
const isService = "global::Microsoft.Extensions.DependencyInjection.IServiceProviderIsService";
|
|
19
101
|
const application = "global::Microsoft.AspNetCore.Builder.WebApplication";
|
|
20
102
|
const services = "global::Microsoft.Extensions.DependencyInjection.IServiceCollection";
|
|
21
103
|
const map = hasServices
|
|
22
|
-
?
|
|
23
|
-
/// Maps the routes of the API, after checking that every service is registered. No routes are
|
|
24
|
-
/// generated yet.
|
|
25
|
-
/// </summary>
|
|
104
|
+
? `${summary}
|
|
26
105
|
/// <exception cref="global::System.InvalidOperationException">A service is missing.</exception>
|
|
27
106
|
public static ${application} Map${api}Api(
|
|
28
107
|
this ${application} app)
|
|
29
108
|
{
|
|
30
109
|
RequireServices(app.Services);
|
|
31
|
-
return app;
|
|
110
|
+
${mapped} return app;
|
|
32
111
|
}
|
|
33
112
|
|
|
34
113
|
private static void RequireServices(global::System.IServiceProvider provider)
|
|
@@ -56,6 +135,7 @@ ${required
|
|
|
56
135
|
: ` /// <summary>Maps the routes of the API. No routes are generated yet.</summary>
|
|
57
136
|
public static ${application} Map${api}Api(
|
|
58
137
|
this ${application} app) => app;`;
|
|
138
|
+
const usings = validation ? ["global::Microsoft.Extensions.DependencyInjection"] : [];
|
|
59
139
|
return csharpFile(rootNamespace, `/// <summary>Sets up the generated API in a host.</summary>
|
|
60
140
|
public static class ${api}ApiExtensions
|
|
61
141
|
{
|
|
@@ -71,15 +151,49 @@ ${register.join("\n")}
|
|
|
71
151
|
public static ${application} Use${api}Api(
|
|
72
152
|
this ${application} app)
|
|
73
153
|
{
|
|
74
|
-
// Before other middleware, so that
|
|
75
|
-
|
|
154
|
+
// Before other middleware, so that they cover all that follows. In development, ASP.NET
|
|
155
|
+
// Core's developer page shows what failed; elsewhere a problem says nothing of it.
|
|
156
|
+
if (!global::Microsoft.Extensions.Hosting.HostEnvironmentEnvExtensions.IsDevelopment(app.Environment))
|
|
157
|
+
{
|
|
158
|
+
global::Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler(app);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Gives an error without a body, such as an unknown route, a problem as its body.
|
|
162
|
+
global::Microsoft.AspNetCore.Builder.StatusCodePagesExtensions.UseStatusCodePages(app);
|
|
163
|
+
global::Microsoft.AspNetCore.Builder.UseExtensions.Use(app, Answer);
|
|
76
164
|
return app;
|
|
77
165
|
}
|
|
78
166
|
|
|
79
167
|
${map}
|
|
80
168
|
|
|
81
|
-
|
|
82
|
-
|
|
169
|
+
${minimal
|
|
170
|
+
? ` // Runs once a request of the API is bound. What the spec answers without a body keeps none.
|
|
171
|
+
private static global::System.Threading.Tasks.ValueTask<object?> Bound(
|
|
172
|
+
global::Microsoft.AspNetCore.Http.EndpointFilterInvocationContext context,
|
|
173
|
+
global::Microsoft.AspNetCore.Http.EndpointFilterDelegate next)
|
|
174
|
+
{
|
|
175
|
+
context.HttpContext.Items[typeof(GeneratedEndpoint)] = true;
|
|
176
|
+
var pages = context.HttpContext.Features.Get<global::Microsoft.AspNetCore.Diagnostics.IStatusCodePagesFeature>();
|
|
177
|
+
if (pages is not null)
|
|
178
|
+
{
|
|
179
|
+
pages.Enabled = false;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return next(context);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// True for a request of the API that failed before its values were bound.
|
|
186
|
+
private static bool FailedToBind(global::Microsoft.AspNetCore.Http.HttpContext context) =>
|
|
187
|
+
global::Microsoft.AspNetCore.Http.EndpointHttpContextExtensions.GetEndpoint(context)
|
|
188
|
+
?.Metadata.GetMetadata<GeneratedEndpoint>() is not null
|
|
189
|
+
&& !context.Items.ContainsKey(typeof(GeneratedEndpoint));
|
|
190
|
+
|
|
191
|
+
private sealed class GeneratedEndpoint;
|
|
192
|
+
|
|
193
|
+
`
|
|
194
|
+
: ""} // A service stub says it has no implementation yet by throwing, as does reading a request
|
|
195
|
+
// that cannot be read.
|
|
196
|
+
private static async global::System.Threading.Tasks.Task Answer(
|
|
83
197
|
global::Microsoft.AspNetCore.Http.HttpContext context,
|
|
84
198
|
global::Microsoft.AspNetCore.Http.RequestDelegate next)
|
|
85
199
|
{
|
|
@@ -97,6 +211,46 @@ ${map}
|
|
|
97
211
|
global::Microsoft.AspNetCore.Http.ResponseExtensions.Clear(context.Response);
|
|
98
212
|
await global::Microsoft.AspNetCore.Http.Results.Problem(statusCode: 501).ExecuteAsync(context);
|
|
99
213
|
}
|
|
214
|
+
${endpoints.checks
|
|
215
|
+
? ` catch (global::${rootNamespace}.Requests.RequestInvalidException exception)
|
|
216
|
+
when (!context.Response.HasStarted)
|
|
217
|
+
{
|
|
218
|
+
global::Microsoft.AspNetCore.Http.ResponseExtensions.Clear(context.Response);
|
|
219
|
+
var errors = new global::System.Collections.Generic.Dictionary<string, string[]>
|
|
220
|
+
{
|
|
221
|
+
[exception.Name] = new string[] { exception.Message },
|
|
222
|
+
};
|
|
223
|
+
${write("global::Microsoft.AspNetCore.Http.Results.ValidationProblem(errors)")}
|
|
224
|
+
}
|
|
225
|
+
`
|
|
226
|
+
: ""}${minimal
|
|
227
|
+
? ` catch (global::System.NotSupportedException exception)
|
|
228
|
+
when (!context.Response.HasStarted
|
|
229
|
+
&& exception.Source == "System.Text.Json"
|
|
230
|
+
&& FailedToBind(context))
|
|
231
|
+
{
|
|
232
|
+
// JSON naming no kind of an abstract model is the sender's mistake too.
|
|
233
|
+
var logs = (global::Microsoft.Extensions.Logging.ILoggerFactory)context.RequestServices
|
|
234
|
+
.GetService(typeof(global::Microsoft.Extensions.Logging.ILoggerFactory))!;
|
|
235
|
+
global::Microsoft.Extensions.Logging.LoggerExtensions.LogDebug(
|
|
236
|
+
logs.CreateLogger("${rootNamespace}"), exception, "The request cannot be read.");
|
|
237
|
+
global::Microsoft.AspNetCore.Http.ResponseExtensions.Clear(context.Response);
|
|
238
|
+
await global::Microsoft.AspNetCore.Http.Results.Problem(statusCode: 400).ExecuteAsync(context);
|
|
239
|
+
}
|
|
240
|
+
`
|
|
241
|
+
: ""} catch (global::Microsoft.AspNetCore.Http.BadHttpRequestException exception)
|
|
242
|
+
when (!context.Response.HasStarted)
|
|
243
|
+
{
|
|
244
|
+
// The sender's mistake, not a fault to log as an error.
|
|
245
|
+
var logs = (global::Microsoft.Extensions.Logging.ILoggerFactory)context.RequestServices
|
|
246
|
+
.GetService(typeof(global::Microsoft.Extensions.Logging.ILoggerFactory))!;
|
|
247
|
+
global::Microsoft.Extensions.Logging.LoggerExtensions.LogDebug(
|
|
248
|
+
logs.CreateLogger("${rootNamespace}"), exception, "The request cannot be read.");
|
|
249
|
+
global::Microsoft.AspNetCore.Http.ResponseExtensions.Clear(context.Response);
|
|
250
|
+
${endpoints.controllers
|
|
251
|
+
? write("global::Microsoft.AspNetCore.Http.Results.Problem(statusCode: exception.StatusCode)")
|
|
252
|
+
: "await global::Microsoft.AspNetCore.Http.Results.Problem(statusCode: exception.StatusCode)\n .ExecuteAsync(context);"}
|
|
253
|
+
}
|
|
100
254
|
}
|
|
101
|
-
}
|
|
255
|
+
${writeProblem}}`, usings);
|
|
102
256
|
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Program } from "@typespec/compiler";
|
|
2
|
+
import type { ApiModel } from "../../model/types.js";
|
|
3
|
+
import type { OperationName } from "../../naming/services.js";
|
|
4
|
+
import { type BodyShapes } from "./body-formats.js";
|
|
5
|
+
import type { TypeText } from "./services.js";
|
|
6
|
+
export type Source = "route" | "query" | "header" | "body" | "service" | "context" | "cancellation";
|
|
7
|
+
/** A parameter of a handler. */
|
|
8
|
+
export interface HandlerParameter {
|
|
9
|
+
source: Source;
|
|
10
|
+
/** The name on the wire, for a value of the route, query or headers. */
|
|
11
|
+
wireName?: string;
|
|
12
|
+
type: string;
|
|
13
|
+
name: string;
|
|
14
|
+
/** Validation attributes, which ASP.NET Core checks before calling the handler. */
|
|
15
|
+
attributes?: string[];
|
|
16
|
+
}
|
|
17
|
+
export interface Binding {
|
|
18
|
+
parameters: HandlerParameter[];
|
|
19
|
+
/** What the service method is given, in order. */
|
|
20
|
+
values: string[];
|
|
21
|
+
/** Content types of a body that is read by hand, which the endpoint must declare. */
|
|
22
|
+
accepts: string[];
|
|
23
|
+
/** Set when form or XML bodies are turned into JSON: the shape and content types. */
|
|
24
|
+
converted?: {
|
|
25
|
+
shape: string;
|
|
26
|
+
types: string[];
|
|
27
|
+
};
|
|
28
|
+
/** `typeof` the body, which a declared content type is said to hold. */
|
|
29
|
+
bodyType?: string;
|
|
30
|
+
/** The expressions making the constraints of each parameter, by its position. */
|
|
31
|
+
checks: Map<number, string[]>;
|
|
32
|
+
/** How the handler reaches the request's context. */
|
|
33
|
+
context: string;
|
|
34
|
+
/** Names the handler can use for the service's result and a case of it. */
|
|
35
|
+
result: string;
|
|
36
|
+
found: string;
|
|
37
|
+
}
|
|
38
|
+
export declare function bindingWriter(program: Program, model: ApiModel, rootNamespace: string, typeOf: TypeText, shapes: BodyShapes,
|
|
39
|
+
/** A controller holds its service and context, so its actions declare neither. */
|
|
40
|
+
controllers?: boolean): (named: OperationName, service: string, signature: {
|
|
41
|
+
type: string;
|
|
42
|
+
name: string;
|
|
43
|
+
}[], writes: boolean) => Binding;
|