sheridan-typespec-aspnet 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +16 -3
  2. package/dist/src/emitter.js +70 -2
  3. package/dist/src/lib.d.ts +32 -2
  4. package/dist/src/lib.js +12 -0
  5. package/dist/src/model/collect-types.d.ts +3 -1
  6. package/dist/src/model/collect-types.js +1 -1
  7. package/dist/src/model/collect.js +39 -3
  8. package/dist/src/model/types.d.ts +10 -0
  9. package/dist/src/naming/names.js +11 -1
  10. package/dist/src/naming/services.d.ts +10 -0
  11. package/dist/src/naming/services.js +11 -2
  12. package/dist/src/render/minimal/documentation.d.ts +4 -0
  13. package/dist/src/render/minimal/documentation.js +107 -0
  14. package/dist/src/render/minimal/endpoints.d.ts +14 -0
  15. package/dist/src/render/minimal/endpoints.js +139 -0
  16. package/dist/src/render/minimal/results.d.ts +11 -0
  17. package/dist/src/render/minimal/results.js +145 -0
  18. package/dist/src/render/shared/api-setup.d.ts +6 -1
  19. package/dist/src/render/shared/api-setup.js +131 -11
  20. package/dist/src/render/shared/binding.d.ts +33 -0
  21. package/dist/src/render/shared/binding.js +395 -0
  22. package/dist/src/render/shared/headers.d.ts +7 -0
  23. package/dist/src/render/shared/headers.js +52 -0
  24. package/dist/src/render/shared/models.js +5 -23
  25. package/dist/src/render/shared/openapi.d.ts +1 -0
  26. package/dist/src/render/shared/openapi.js +248 -0
  27. package/dist/src/render/shared/parameters.d.ts +3 -0
  28. package/dist/src/render/shared/parameters.js +224 -0
  29. package/dist/src/render/shared/references.d.ts +3 -0
  30. package/dist/src/render/shared/references.js +18 -0
  31. package/dist/src/render/shared/request-selector.d.ts +1 -0
  32. package/dist/src/render/shared/request-selector.js +86 -0
  33. package/dist/src/render/shared/routes.d.ts +37 -0
  34. package/dist/src/render/shared/routes.js +241 -0
  35. package/dist/src/render/shared/validation.d.ts +6 -1
  36. package/dist/src/render/shared/validation.js +60 -0
  37. package/dist/src/scaffold/projects.d.ts +1 -1
  38. package/dist/src/scaffold/projects.js +4 -3
  39. package/package.json +13 -3
@@ -0,0 +1,139 @@
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 mapMethods = {
8
+ get: "MapGet",
9
+ put: "MapPut",
10
+ post: "MapPost",
11
+ patch: "MapPatch",
12
+ delete: "MapDelete",
13
+ };
14
+ const mvc = "global::Microsoft.AspNetCore.Mvc";
15
+ const attributes = {
16
+ route: "FromRoute",
17
+ query: "FromQuery",
18
+ header: "FromHeader",
19
+ body: "FromBody",
20
+ service: "FromServices",
21
+ };
22
+ function declaration({ source, wireName, type, name, attributes: checks, }) {
23
+ const attribute = attributes[source];
24
+ const named = wireName === undefined ? "" : `(Name = ${stringLiteral(wireName)})`;
25
+ const constraints = (checks ?? []).map((check) => `[${check}] `).join("");
26
+ return `${attribute ? `[${mvc}.${attribute}Attribute${named}] ` : ""}${constraints}${type} ${name}`;
27
+ }
28
+ /** A handler that binds the inputs of an operation, calls its service and maps the result. */
29
+ function handler(name, method, { binding, result }) {
30
+ const service = binding.parameters.find((parameter) => parameter.source === "service");
31
+ const list = binding.parameters.map((parameter) => ` ${declaration(parameter)}`);
32
+ const values = binding.values.map((value) => ` ${value}`);
33
+ // Public, so that a handler can be tested on its own. It has no documentation comment, which
34
+ // would replace what the spec says of the operation in OpenAPI.
35
+ return [
36
+ ` public static async global::System.Threading.Tasks.Task<${result.type}> ${name}(`,
37
+ `${list.join(",\n")})`,
38
+ " {",
39
+ ` var ${binding.result} = await ${service.name}.${method}(`,
40
+ `${values.join(",\n")});`,
41
+ ` return ${binding.result} switch`,
42
+ " {",
43
+ ...result.arms.map((arm) => ` ${arm},`),
44
+ ' null => throw new global::System.InvalidOperationException("The service returned no result."),',
45
+ " };",
46
+ " }",
47
+ ].join("\n");
48
+ }
49
+ /** The leading segments every route of a group starts with, which the group's builder takes. */
50
+ function commonPrefix(routes) {
51
+ let length = 0;
52
+ while (routes.every((route) => route[length] !== undefined &&
53
+ !route[length].trailing &&
54
+ route[length].text === routes[0][length].text)) {
55
+ length++;
56
+ }
57
+ return length;
58
+ }
59
+ const template = (segments) => segments.map((segment) => `/${segment.text}`).join("");
60
+ const list = (values) => values.map(stringLiteral).join(", ");
61
+ function condition(rootNamespace, found, bodyType) {
62
+ const { values, contentTypes, accepted } = found;
63
+ const routing = `global::${rootNamespace}.Routing`;
64
+ const written = values.map((v) => `new ${routing}.RequiredValue(${v.in === "header"}, ${stringLiteral(v.name)}, ${stringLiteral(v.value)}, ${v.ignoreCase})`);
65
+ const array = (type, items) => items.length
66
+ ? `new ${type}[] { ${items.join(", ")} }`
67
+ : `global::System.Array.Empty<${type}>()`;
68
+ const metadata = [
69
+ `new ${routing}.RequestCondition(`,
70
+ ` ${array(`${routing}.RequiredValue`, written)},`,
71
+ ` ${array("string", contentTypes.map(stringLiteral))})`,
72
+ ];
73
+ // ASP.NET Core answers 415 itself when no operation accepts the content type.
74
+ if (contentTypes.length) {
75
+ metadata[metadata.length - 1] += ",";
76
+ metadata.push(`new global::Microsoft.AspNetCore.Http.Metadata.AcceptsMetadata(new string[] { ${list(accepted)} }, ${bodyType})`);
77
+ }
78
+ return metadata;
79
+ }
80
+ /** Renders the endpoint class of every group. */
81
+ export function renderEndpoints(rootNamespace, services, routing, handle) {
82
+ return services.map((service) => {
83
+ const { name, file, map, handlers } = service.endpoints;
84
+ const routes = service.operations.map((o) => routing.routes.get(o.operation));
85
+ const prefix = commonPrefix(routes.map((route) => route.segments));
86
+ const tags = service.group.tags ?? [service.group.name].filter(Boolean);
87
+ const handled = service.operations.map((_, index) => handle(service, index));
88
+ const mappings = service.operations.map(({ operation }, index) => {
89
+ const pattern = stringLiteral(template(routes[index].segments.slice(prefix)));
90
+ const call = operation.verb === "head"
91
+ ? `${routeBuilder}.MapMethods(group, ${pattern}, new string[] { "HEAD" }, ${handlers[index]})`
92
+ : `${routeBuilder}.${mapMethods[operation.verb]}(group, ${pattern}, ${handlers[index]})`;
93
+ const found = routing.conditions.get(operation);
94
+ // Tags of an endpoint replace those of its group, so they are repeated.
95
+ const own = operation.tags && [...new Set([...tags, ...operation.tags])];
96
+ // A body read by hand declares what it takes, unless the condition does.
97
+ const accepts = found?.accepted.length ? [] : handled[index].binding.accepts;
98
+ const lines = [
99
+ ` var endpoint${index} = ${call};`,
100
+ ...handled[index].describe(`endpoint${index}`),
101
+ ];
102
+ if (own)
103
+ lines.push(` ${withTags}(endpoint${index}, ${list(own)});`);
104
+ if (accepts.length) {
105
+ lines.push(` ${withMetadata}(`, ` endpoint${index},`, ` new global::Microsoft.AspNetCore.Http.Metadata.AcceptsMetadata(new string[] { ${list(accepts)} }, ${handled[index].binding.bodyType}));`);
106
+ }
107
+ if (found) {
108
+ lines.push(` ${withMetadata}(`, ` endpoint${index},`, condition(rootNamespace, found, handled[index].binding.bodyType)
109
+ .map((line) => ` ${line}`)
110
+ .join("\n") + ");");
111
+ }
112
+ return lines.join("\n");
113
+ });
114
+ const body = [
115
+ `/// <summary>Maps the routes of <c>${service.name}</c>.</summary>`,
116
+ `public static class ${name}`,
117
+ "{",
118
+ " /// <summary>Maps the routes in a group of their own.</summary>",
119
+ " /// <returns>The group, to add conventions to.</returns>",
120
+ ` public static ${groupType} ${map}(`,
121
+ ` this ${groupType} api)`,
122
+ " {",
123
+ ` var group = ${routeBuilder}.MapGroup(api, ${stringLiteral(template(routes[0].segments.slice(0, prefix)))});`,
124
+ ...(tags.length ? [` ${withTags}(group, ${list(tags)});`] : []),
125
+ ...mappings,
126
+ " return group;",
127
+ " }",
128
+ "",
129
+ // The handlers have no documentation comments, whatever a project asks for.
130
+ "#pragma warning disable CS1591",
131
+ handlers
132
+ .map((name, index) => handler(name, service.operations[index].method, handled[index]))
133
+ .join("\n\n"),
134
+ "#pragma warning restore CS1591",
135
+ "}",
136
+ ];
137
+ return { path: file, content: csharpFile(service.namespace, body.join("\n")) };
138
+ });
139
+ }
@@ -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,145 @@
1
+ import { reportDiagnostic } from "../../lib.js";
2
+ import { isReference } from "../shared/references.js";
3
+ import { stringLiteral } from "../shared/writer.js";
4
+ const http = "global::Microsoft.AspNetCore.Http";
5
+ const results = `${http}.HttpResults`;
6
+ const typed = `${http}.TypedResults`;
7
+ /** The result types of ASP.NET Core with a body, for the statuses that have one of their own. */
8
+ const withBody = {
9
+ 200: "Ok",
10
+ 201: "Created",
11
+ 202: "Accepted",
12
+ 400: "BadRequest",
13
+ 404: "NotFound",
14
+ 409: "Conflict",
15
+ 422: "UnprocessableEntity",
16
+ 500: "InternalServerError",
17
+ };
18
+ /** Those without one, and the type each answers with. */
19
+ const withoutBody = {
20
+ 200: ["Ok()", "Ok"],
21
+ 201: ["Created()", "Created"],
22
+ 202: ["Accepted((string?)null)", "Accepted"],
23
+ 204: ["NoContent()", "NoContent"],
24
+ 400: ["BadRequest()", "BadRequest"],
25
+ 401: ["Unauthorized()", "UnauthorizedHttpResult"],
26
+ 404: ["NotFound()", "NotFound"],
27
+ 409: ["Conflict()", "Conflict"],
28
+ 422: ["UnprocessableEntity()", "UnprocessableEntity"],
29
+ };
30
+ const isText = (type) => type.toLowerCase().startsWith("text/");
31
+ const isJson = (type) => /^application\/(?:[\w.-]+\+)?json$/i.test(type.split(";")[0]);
32
+ /** At most six types fit a `Results<>`, so more are nested in its last place (ADR 0023). */
33
+ function union(types) {
34
+ if (types.length === 1)
35
+ return types[0];
36
+ const held = types.length > 6 ? [...types.slice(0, 5), union(types.slice(5))] : types;
37
+ return `${results}.Results<${held.join(", ")}>`;
38
+ }
39
+ /** An expression of one of the types, cast through each `Results<>` it is nested in. */
40
+ function nested(expression, types, index) {
41
+ if (types.length <= 6 || index < 5)
42
+ return expression;
43
+ const rest = types.slice(5);
44
+ const inner = nested(expression, rest, index - 5);
45
+ return rest.length > 1
46
+ ? `(${union(rest)})${inner.startsWith("(") ? inner : `(${inner})`}`
47
+ : inner;
48
+ }
49
+ export function resultWriter(program, model, rootNamespace, headers) {
50
+ const responses = `global::${rootNamespace}.Responses`;
51
+ /** The result of one case: its type and the expression making it. */
52
+ function respond(found, value, context, operation) {
53
+ const { response, content } = found.found;
54
+ const member = (name) => found.members.find((m) => m.name === name);
55
+ const fixed = typeof response.status === "number" ? response.status : undefined;
56
+ const status = fixed === undefined ? `${value}.StatusCode` : String(fixed);
57
+ const body = content.body && member("Body");
58
+ let type;
59
+ let expression;
60
+ if (!body) {
61
+ const known = fixed === undefined ? undefined : withoutBody[fixed];
62
+ type = `${results}.${known ? known[1] : "StatusCodeHttpResult"}`;
63
+ expression = known ? `${typed}.${known[0]}` : `${typed}.StatusCode(${status})`;
64
+ }
65
+ else {
66
+ const sent = content.body.contentTypes;
67
+ const contentType = sent.find((t) => !t.includes("*"));
68
+ const sentBody = content.body;
69
+ // A nullable value type is a type of its own, which the result must name.
70
+ const held = sentBody.kind === "single" && isReference(model, sentBody.type)
71
+ ? body.type.replace(/\?$/, "")
72
+ : body.type;
73
+ const bare = body.type.replace(/\?$/, "");
74
+ const read = `${value}.Body`;
75
+ if (sent.every(isJson)) {
76
+ const own = fixed === undefined ? undefined : withBody[fixed];
77
+ if (own && contentType?.toLowerCase() === "application/json") {
78
+ type = `${results}.${own}<${held}>`;
79
+ const uri = own === "Created" || own === "Accepted" ? "(string?)null, " : "";
80
+ expression = `${typed}.${own}<${held}>(${uri}${read})`;
81
+ }
82
+ else {
83
+ type = `${results}.JsonHttpResult<${held}>`;
84
+ expression = `${typed}.Json<${held}>(${read}, contentType: ${stringLiteral(contentType ?? "application/json")}, statusCode: ${status})`;
85
+ }
86
+ }
87
+ else if (!sent.some(isJson) &&
88
+ (bare === "string" || (bare !== "byte[]" && sent.every(isText)))) {
89
+ // Numbers, dates and the like are written as plain text too.
90
+ const text = bare === "string" || sentBody.kind !== "single"
91
+ ? read
92
+ : headers({
93
+ type: sentBody.type,
94
+ wireName: "body",
95
+ source: operation.operation.operation.source,
96
+ }, read, body.type);
97
+ if (text === undefined)
98
+ return undefined;
99
+ type = `${results}.ContentHttpResult`;
100
+ const named = stringLiteral(contentType ?? "text/plain");
101
+ expression = `${typed}.Text(${text}, ${named}, global::System.Text.Encoding.UTF8, ${status})`;
102
+ }
103
+ else if (bare === "byte[]" && !sent.some(isJson)) {
104
+ type = `${responses}.BytesHttpResult`;
105
+ const named = stringLiteral(contentType ?? "application/octet-stream");
106
+ expression = `new ${type}(${status}, ${read}, ${named})`;
107
+ }
108
+ else {
109
+ reportDiagnostic(program, {
110
+ code: "unsupported-type",
111
+ format: { kind: `response body sent as ${sent.join(", ")}` },
112
+ target: operation.operation.operation.source,
113
+ });
114
+ return undefined;
115
+ }
116
+ }
117
+ content.headers.forEach((header, index) => {
118
+ const name = found.found.headers[index];
119
+ const text = headers(header, `${value}.${name}`, member(name).type);
120
+ if (text === undefined)
121
+ return;
122
+ expression = `${responses}.ResponseHeaders.With(${expression}, ${context}, ${stringLiteral(header.wireName)}, ${text})`;
123
+ });
124
+ return { type, expression };
125
+ }
126
+ /** Maps every case of an operation. `value` and `context` are free names in the handler. */
127
+ return function map(operation, value, context, namespace) {
128
+ const found = operation.cases.flatMap((chosen) => {
129
+ const made = respond(chosen, value, context, operation);
130
+ return made ? [{ chosen, ...made }] : [];
131
+ });
132
+ const types = [...new Set(found.map((item) => item.type))];
133
+ const { name } = operation.operation.result;
134
+ const arms = found.map(({ chosen, type, expression }) => {
135
+ const held = `global::${namespace}.${name}.${chosen.found.name}`;
136
+ const made = nested(expression, types, types.indexOf(type));
137
+ const used = made.includes(`${value}.`);
138
+ return `${held}${used ? ` ${value}` : ""} => ${made}`;
139
+ });
140
+ return {
141
+ type: types.length ? union(types) : `${results}.NoContent`,
142
+ arms,
143
+ };
144
+ };
145
+ }
@@ -3,4 +3,9 @@ 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[]): string;
6
+ export declare function renderApiSetup(rootNamespace: string, api: string, required: Registration[], endpoints?: {
7
+ calls: string[];
8
+ selector: boolean;
9
+ validate?: boolean;
10
+ openapi?: boolean;
11
+ }): 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,63 @@ 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.validate) {
27
+ // Called here, in the assembly whose endpoints take the types to be checked.
28
+ // As deep as JSON is read, so that a deep body is judged rather than a fault.
29
+ register.push(" services.AddValidation(options => options.MaxDepth = 64);");
30
+ }
31
+ if (endpoints.openapi) {
32
+ register.push(` global::${rootNamespace}.Documentation.OpenApiSetup.AddGeneratedOpenApi(services);`);
33
+ }
34
+ if (endpoints.selector) {
35
+ register.push(` global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(
36
+ services,
37
+ global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton<
38
+ global::Microsoft.AspNetCore.Routing.MatcherPolicy,
39
+ global::${rootNamespace}.Routing.RequestSelector>());`);
40
+ }
41
+ const mapped = endpoints.calls.length
42
+ ? [
43
+ ' var api = global::Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions.MapGroup(app, "");',
44
+ " global::Microsoft.AspNetCore.Builder.RoutingEndpointConventionBuilderExtensions.WithMetadata(api, new GeneratedEndpoint());",
45
+ " global::Microsoft.AspNetCore.Http.EndpointFilterExtensions.AddEndpointFilter(api, Bound);",
46
+ ...endpoints.calls.map((call) => ` ${call}(api);`),
47
+ ...(endpoints.openapi
48
+ ? [
49
+ " // The document describes the API, so only development serves it.",
50
+ " if (global::Microsoft.Extensions.Hosting.HostEnvironmentEnvExtensions.IsDevelopment(app.Environment))",
51
+ " {",
52
+ " global::Microsoft.AspNetCore.Builder.OpenApiEndpointRouteBuilderExtensions.MapOpenApi(app);",
53
+ " }",
54
+ "",
55
+ ]
56
+ : []),
57
+ ].join("\n") + "\n"
58
+ : "";
59
+ const summary = endpoints.calls.length
60
+ ? ` /// <summary>
61
+ /// Maps the routes of the API, after checking that every service is registered.
62
+ /// </summary>`
63
+ : ` /// <summary>
64
+ /// Maps the routes of the API, after checking that every service is registered. No routes are
65
+ /// generated for this style yet.
66
+ /// </summary>`;
18
67
  const isService = "global::Microsoft.Extensions.DependencyInjection.IServiceProviderIsService";
19
68
  const application = "global::Microsoft.AspNetCore.Builder.WebApplication";
20
69
  const services = "global::Microsoft.Extensions.DependencyInjection.IServiceCollection";
21
70
  const map = hasServices
22
- ? ` /// <summary>
23
- /// Maps the routes of the API, after checking that every service is registered. No routes are
24
- /// generated yet.
25
- /// </summary>
71
+ ? `${summary}
26
72
  /// <exception cref="global::System.InvalidOperationException">A service is missing.</exception>
27
73
  public static ${application} Map${api}Api(
28
74
  this ${application} app)
29
75
  {
30
76
  RequireServices(app.Services);
31
- return app;
77
+ ${mapped} return app;
32
78
  }
33
79
 
34
80
  private static void RequireServices(global::System.IServiceProvider provider)
@@ -56,6 +102,7 @@ ${required
56
102
  : ` /// <summary>Maps the routes of the API. No routes are generated yet.</summary>
57
103
  public static ${application} Map${api}Api(
58
104
  this ${application} app) => app;`;
105
+ const usings = endpoints.validate ? ["global::Microsoft.Extensions.DependencyInjection"] : [];
59
106
  return csharpFile(rootNamespace, `/// <summary>Sets up the generated API in a host.</summary>
60
107
  public static class ${api}ApiExtensions
61
108
  {
@@ -71,15 +118,49 @@ ${register.join("\n")}
71
118
  public static ${application} Use${api}Api(
72
119
  this ${application} app)
73
120
  {
74
- // Before other middleware, so that it covers all that follows.
75
- global::Microsoft.AspNetCore.Builder.UseExtensions.Use(app, NotImplemented);
121
+ // Before other middleware, so that they cover all that follows. In development, ASP.NET
122
+ // Core's developer page shows what failed; elsewhere a problem says nothing of it.
123
+ if (!global::Microsoft.Extensions.Hosting.HostEnvironmentEnvExtensions.IsDevelopment(app.Environment))
124
+ {
125
+ global::Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler(app);
126
+ }
127
+
128
+ // Gives an error without a body, such as an unknown route, a problem as its body.
129
+ global::Microsoft.AspNetCore.Builder.StatusCodePagesExtensions.UseStatusCodePages(app);
130
+ global::Microsoft.AspNetCore.Builder.UseExtensions.Use(app, Answer);
76
131
  return app;
77
132
  }
78
133
 
79
134
  ${map}
80
135
 
81
- // A service stub says it has no implementation yet by throwing this.
82
- private static async global::System.Threading.Tasks.Task NotImplemented(
136
+ ${minimal
137
+ ? ` // Runs once a request of the API is bound. What the spec answers without a body keeps none.
138
+ private static global::System.Threading.Tasks.ValueTask<object?> Bound(
139
+ global::Microsoft.AspNetCore.Http.EndpointFilterInvocationContext context,
140
+ global::Microsoft.AspNetCore.Http.EndpointFilterDelegate next)
141
+ {
142
+ context.HttpContext.Items[typeof(GeneratedEndpoint)] = true;
143
+ var pages = context.HttpContext.Features.Get<global::Microsoft.AspNetCore.Diagnostics.IStatusCodePagesFeature>();
144
+ if (pages is not null)
145
+ {
146
+ pages.Enabled = false;
147
+ }
148
+
149
+ return next(context);
150
+ }
151
+
152
+ // True for a request of the API that failed before its values were bound.
153
+ private static bool FailedToBind(global::Microsoft.AspNetCore.Http.HttpContext context) =>
154
+ global::Microsoft.AspNetCore.Http.EndpointHttpContextExtensions.GetEndpoint(context)
155
+ ?.Metadata.GetMetadata<GeneratedEndpoint>() is not null
156
+ && !context.Items.ContainsKey(typeof(GeneratedEndpoint));
157
+
158
+ private sealed class GeneratedEndpoint;
159
+
160
+ `
161
+ : ""} // A service stub says it has no implementation yet by throwing, as does reading a request
162
+ // that cannot be read.
163
+ private static async global::System.Threading.Tasks.Task Answer(
83
164
  global::Microsoft.AspNetCore.Http.HttpContext context,
84
165
  global::Microsoft.AspNetCore.Http.RequestDelegate next)
85
166
  {
@@ -97,6 +178,45 @@ ${map}
97
178
  global::Microsoft.AspNetCore.Http.ResponseExtensions.Clear(context.Response);
98
179
  await global::Microsoft.AspNetCore.Http.Results.Problem(statusCode: 501).ExecuteAsync(context);
99
180
  }
181
+ ${endpoints.validate
182
+ ? ` catch (global::${rootNamespace}.Requests.RequestInvalidException exception)
183
+ when (!context.Response.HasStarted)
184
+ {
185
+ global::Microsoft.AspNetCore.Http.ResponseExtensions.Clear(context.Response);
186
+ var errors = new global::System.Collections.Generic.Dictionary<string, string[]>
187
+ {
188
+ [exception.Name] = new string[] { exception.Message },
189
+ };
190
+ await global::Microsoft.AspNetCore.Http.Results.ValidationProblem(errors).ExecuteAsync(context);
191
+ }
192
+ `
193
+ : ""}${minimal
194
+ ? ` catch (global::System.NotSupportedException exception)
195
+ when (!context.Response.HasStarted
196
+ && exception.Source == "System.Text.Json"
197
+ && FailedToBind(context))
198
+ {
199
+ // JSON naming no kind of an abstract model is the sender's mistake too.
200
+ var logs = (global::Microsoft.Extensions.Logging.ILoggerFactory)context.RequestServices
201
+ .GetService(typeof(global::Microsoft.Extensions.Logging.ILoggerFactory))!;
202
+ global::Microsoft.Extensions.Logging.LoggerExtensions.LogDebug(
203
+ logs.CreateLogger("${rootNamespace}"), exception, "The request cannot be read.");
204
+ global::Microsoft.AspNetCore.Http.ResponseExtensions.Clear(context.Response);
205
+ await global::Microsoft.AspNetCore.Http.Results.Problem(statusCode: 400).ExecuteAsync(context);
206
+ }
207
+ `
208
+ : ""} catch (global::Microsoft.AspNetCore.Http.BadHttpRequestException exception)
209
+ when (!context.Response.HasStarted)
210
+ {
211
+ // The sender's mistake, not a fault to log as an error.
212
+ var logs = (global::Microsoft.Extensions.Logging.ILoggerFactory)context.RequestServices
213
+ .GetService(typeof(global::Microsoft.Extensions.Logging.ILoggerFactory))!;
214
+ global::Microsoft.Extensions.Logging.LoggerExtensions.LogDebug(
215
+ logs.CreateLogger("${rootNamespace}"), exception, "The request cannot be read.");
216
+ global::Microsoft.AspNetCore.Http.ResponseExtensions.Clear(context.Response);
217
+ await global::Microsoft.AspNetCore.Http.Results.Problem(statusCode: exception.StatusCode)
218
+ .ExecuteAsync(context);
219
+ }
100
220
  }
101
- }`);
221
+ }`, usings);
102
222
  }
@@ -0,0 +1,33 @@
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 { TypeText } from "./services.js";
5
+ export type Source = "route" | "query" | "header" | "body" | "service" | "context" | "cancellation";
6
+ /** A parameter of a handler. */
7
+ export interface HandlerParameter {
8
+ source: Source;
9
+ /** The name on the wire, for a value of the route, query or headers. */
10
+ wireName?: string;
11
+ type: string;
12
+ name: string;
13
+ /** Validation attributes, which ASP.NET Core checks before calling the handler. */
14
+ attributes?: string[];
15
+ }
16
+ export interface Binding {
17
+ parameters: HandlerParameter[];
18
+ /** What the service method is given, in order. */
19
+ values: string[];
20
+ /** Content types of a body that is read by hand, which the endpoint must declare. */
21
+ accepts: string[];
22
+ /** `typeof` the body, which a declared content type is said to hold. */
23
+ bodyType?: string;
24
+ /** The expressions making the constraints of each parameter, by its position. */
25
+ checks: Map<number, string[]>;
26
+ /** Names the handler can use for the service's result and a case of it. */
27
+ result: string;
28
+ found: string;
29
+ }
30
+ export declare function bindingWriter(program: Program, model: ApiModel, rootNamespace: string, typeOf: TypeText): (named: OperationName, service: string, signature: {
31
+ type: string;
32
+ name: string;
33
+ }[], writes: boolean) => Binding;