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.
- package/README.md +16 -3
- package/dist/src/emitter.js +70 -2
- package/dist/src/lib.d.ts +32 -2
- package/dist/src/lib.js +12 -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 +39 -3
- package/dist/src/model/types.d.ts +10 -0
- package/dist/src/naming/names.js +11 -1
- package/dist/src/naming/services.d.ts +10 -0
- package/dist/src/naming/services.js +11 -2
- package/dist/src/render/minimal/documentation.d.ts +4 -0
- package/dist/src/render/minimal/documentation.js +107 -0
- package/dist/src/render/minimal/endpoints.d.ts +14 -0
- package/dist/src/render/minimal/endpoints.js +139 -0
- package/dist/src/render/minimal/results.d.ts +11 -0
- package/dist/src/render/minimal/results.js +145 -0
- package/dist/src/render/shared/api-setup.d.ts +6 -1
- package/dist/src/render/shared/api-setup.js +131 -11
- package/dist/src/render/shared/binding.d.ts +33 -0
- package/dist/src/render/shared/binding.js +395 -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 +248 -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 +86 -0
- package/dist/src/render/shared/routes.d.ts +37 -0
- package/dist/src/render/shared/routes.js +241 -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 +13 -3
package/README.md
CHANGED
|
@@ -1,14 +1,27 @@
|
|
|
1
1
|
# Sheridan.Typespec.Aspnet
|
|
2
2
|
|
|
3
|
-
A [TypeSpec](https://typespec.io) emitter that
|
|
3
|
+
A [TypeSpec](https://typespec.io) emitter that generates ASP.NET Core servers in C#. It generates Minimal APIs; controllers are planned.
|
|
4
4
|
|
|
5
|
-
**Status: early development.**
|
|
5
|
+
**Status: early development.** From a spec, the emitter writes:
|
|
6
|
+
|
|
7
|
+
- C# models, enums and unions, with JSON converters, one JSON setup and validation attributes;
|
|
8
|
+
- a service interface with result types for your code to implement, with a context that gives it the request;
|
|
9
|
+
- with the `minimal` style, routes that bind and validate requests, call your services and send their results, with problem details for failures and an OpenAPI document in development;
|
|
10
|
+
- a solution with a host project that builds and runs, and a stub for each service, registered with dependency injection.
|
|
11
|
+
|
|
12
|
+
Controllers, authentication, versioning, pagination, files and streaming are not generated yet. See the [architecture](docs/architecture.md), the [plan](docs/plan.md) and [issues](https://github.com/two4suited/Sheridan.Typespec.Aspnet/issues).
|
|
13
|
+
|
|
14
|
+
Install it from npm (links to files and issues here need access to the repository):
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install --save-dev sheridan-typespec-aspnet
|
|
18
|
+
```
|
|
6
19
|
|
|
7
20
|

|
|
8
21
|
|
|
9
22
|
## Options
|
|
10
23
|
|
|
11
|
-
Set these under `options: sheridan-typespec-aspnet:` in `tspconfig.yaml`. All are checked. Today `project-name`, `root-namespace`, `collection-type`, `host-output-dir`, `scaffold-host`, `scaffold-tests` and `mocks` change the output;
|
|
24
|
+
Set these under `options: sheridan-typespec-aspnet:` in `tspconfig.yaml`. All are checked. Today `style`, `openapi`, `project-name`, `root-namespace`, `collection-type`, `host-output-dir`, `scaffold-host`, `scaffold-tests` and `mocks` change the output; `skip-format` takes effect when formatting exists.
|
|
12
25
|
|
|
13
26
|
| Option | Values | Default |
|
|
14
27
|
|---|---|---|
|
package/dist/src/emitter.js
CHANGED
|
@@ -1,12 +1,22 @@
|
|
|
1
1
|
import { emitFile, getRelativePathFromDirectory, resolvePath, } from "@typespec/compiler";
|
|
2
2
|
import { collectModel } from "./model/collect.js";
|
|
3
3
|
import { assignNames } from "./naming/names.js";
|
|
4
|
+
import { reportDiagnostic } from "./lib.js";
|
|
4
5
|
import { resolveOptions } from "./options.js";
|
|
6
|
+
import { documentationWriter } from "./render/minimal/documentation.js";
|
|
7
|
+
import { renderEndpoints } from "./render/minimal/endpoints.js";
|
|
8
|
+
import { resultWriter } from "./render/minimal/results.js";
|
|
5
9
|
import { renderApiSetup } from "./render/shared/api-setup.js";
|
|
10
|
+
import { bindingWriter } from "./render/shared/binding.js";
|
|
6
11
|
import { renderConverters } from "./render/shared/converters.js";
|
|
12
|
+
import { headerWriter } from "./render/shared/headers.js";
|
|
7
13
|
import { renderJsonSetup } from "./render/shared/json-setup.js";
|
|
8
14
|
import { renderModels } from "./render/shared/models.js";
|
|
15
|
+
import { renderOpenApi } from "./render/shared/openapi.js";
|
|
16
|
+
import { renderParameters, renderResponses } from "./render/shared/parameters.js";
|
|
9
17
|
import { renderHttpRequestContext, renderRequestContext } from "./render/shared/request-context.js";
|
|
18
|
+
import { renderRequestSelector } from "./render/shared/request-selector.js";
|
|
19
|
+
import { planRoutes } from "./render/shared/routes.js";
|
|
10
20
|
import { renderServices } from "./render/shared/services.js";
|
|
11
21
|
import { hasDeprecations, registrations, renderStubs } from "./render/shared/stubs.js";
|
|
12
22
|
import { renderValidation } from "./render/shared/validation.js";
|
|
@@ -45,15 +55,73 @@ export async function $onEmit(context) {
|
|
|
45
55
|
content: renderHttpRequestContext(options.rootNamespace),
|
|
46
56
|
});
|
|
47
57
|
}
|
|
58
|
+
// Controllers are not generated yet, so their routes are not mapped.
|
|
59
|
+
const routing = options.style === "minimal" ? planRoutes(context.program, model) : undefined;
|
|
60
|
+
const selector = (routing?.conditions.size ?? 0) > 0;
|
|
61
|
+
// A route that cannot be mapped leaves nothing to render.
|
|
62
|
+
if (context.program.hasError()) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (routing) {
|
|
66
|
+
const bind = bindingWriter(context.program, model, options.rootNamespace, services.typeOf);
|
|
67
|
+
const contracts = new Map(services.contracts.map((found) => [found.service, found]));
|
|
68
|
+
const headers = headerWriter(model, options.rootNamespace, (kind, header) => reportDiagnostic(context.program, {
|
|
69
|
+
code: "unsupported-type",
|
|
70
|
+
format: { kind },
|
|
71
|
+
target: header.source,
|
|
72
|
+
}));
|
|
73
|
+
const root = new Set(model.services.flatMap(({ namespace, groups }) => groups.filter((group) => group.kind === "namespace" &&
|
|
74
|
+
[...group.namespace, group.name].join(".") === namespace.join("."))));
|
|
75
|
+
const describe = documentationWriter(model, options.rootNamespace, options.openapi);
|
|
76
|
+
const respond = resultWriter(context.program, model, options.rootNamespace, headers);
|
|
77
|
+
files.push(...renderEndpoints(options.rootNamespace, names.services, routing, (service, index) => {
|
|
78
|
+
const found = contracts.get(service).operations[index];
|
|
79
|
+
const contract = `global::${service.namespace}.${service.name}`;
|
|
80
|
+
const writes = found.cases.some((c) => c.found.content.headers.length > 0);
|
|
81
|
+
const binding = bind(found.operation, contract, found.parameters, writes);
|
|
82
|
+
const contextName = binding.parameters.find((p) => p.source === "context")?.name;
|
|
83
|
+
return {
|
|
84
|
+
binding,
|
|
85
|
+
result: respond(found, binding.found, contextName ?? "", service.namespace),
|
|
86
|
+
// As @typespec/openapi3 does, an operation of the service namespace is named alone.
|
|
87
|
+
describe: (endpoint) => describe(root.has(service.group) ? "" : service.group.name, found, binding, endpoint),
|
|
88
|
+
};
|
|
89
|
+
}));
|
|
90
|
+
if (names.services.length > 0) {
|
|
91
|
+
files.push({ path: "Requests/Parameters.cs", content: renderParameters(options.rootNamespace) }, { path: "Responses/Results.cs", content: renderResponses(options.rootNamespace) });
|
|
92
|
+
}
|
|
93
|
+
if (options.openapi && names.services.length > 0) {
|
|
94
|
+
files.push({
|
|
95
|
+
path: "Documentation/OpenApi.cs",
|
|
96
|
+
content: renderOpenApi(options.rootNamespace),
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
if (context.program.hasError()) {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (selector) {
|
|
104
|
+
files.push({
|
|
105
|
+
path: "Routing/RequestSelector.cs",
|
|
106
|
+
content: renderRequestSelector(options.rootNamespace),
|
|
107
|
+
});
|
|
108
|
+
}
|
|
48
109
|
files.push({
|
|
49
110
|
path: `${projects.api}ApiExtensions.cs`,
|
|
50
|
-
content: renderApiSetup(options.rootNamespace, projects.api, registrations(names, projects.host, options.scaffoldHost)
|
|
111
|
+
content: renderApiSetup(options.rootNamespace, projects.api, registrations(names, projects.host, options.scaffoldHost), {
|
|
112
|
+
calls: routing
|
|
113
|
+
? names.services.map(({ namespace, endpoints }) => `global::${namespace}.${endpoints.name}.${endpoints.map}`)
|
|
114
|
+
: [],
|
|
115
|
+
selector,
|
|
116
|
+
validate: routing !== undefined && names.services.length > 0,
|
|
117
|
+
openapi: options.openapi && routing !== undefined && names.services.length > 0,
|
|
118
|
+
}),
|
|
51
119
|
});
|
|
52
120
|
// Nothing is written when the spec holds something that cannot be generated.
|
|
53
121
|
if (context.program.hasError()) {
|
|
54
122
|
return;
|
|
55
123
|
}
|
|
56
|
-
const project = generatedProject(projects);
|
|
124
|
+
const project = generatedProject(projects, routing !== undefined && options.openapi);
|
|
57
125
|
const folder = resolvePath(context.emitterOutputDir, projects.generated);
|
|
58
126
|
const generated = [
|
|
59
127
|
{ ...project, path: project.path.slice(projects.generated.length + 1) },
|
package/dist/src/lib.d.ts
CHANGED
|
@@ -42,6 +42,12 @@ export declare const $lib: import("@typespec/compiler").TypeSpecLibrary<{
|
|
|
42
42
|
"unsupported-type": {
|
|
43
43
|
readonly default: import("@typespec/compiler").CallableMessage<["kind"]>;
|
|
44
44
|
};
|
|
45
|
+
"unsupported-route": {
|
|
46
|
+
readonly default: import("@typespec/compiler").CallableMessage<["reason"]>;
|
|
47
|
+
};
|
|
48
|
+
"ambiguous-route": {
|
|
49
|
+
readonly default: import("@typespec/compiler").CallableMessage<["operation", "other"]>;
|
|
50
|
+
};
|
|
45
51
|
"versioning-unsupported": {
|
|
46
52
|
readonly default: "Versioned services cannot be generated yet.";
|
|
47
53
|
};
|
|
@@ -70,7 +76,7 @@ export declare const $lib: import("@typespec/compiler").TypeSpecLibrary<{
|
|
|
70
76
|
readonly default: import("@typespec/compiler").CallableMessage<["option"]>;
|
|
71
77
|
};
|
|
72
78
|
}, AspNetEmitterOptions, never>;
|
|
73
|
-
export declare const reportDiagnostic: <C extends "invalid-name" | "invalid-service-name" | "host-inside-generated" | "generated-inside-host" | "reserved-namespace" | "manifest-unreadable" | "stale-file-kept" | "host-reference-stale" | "solution-missing-project" | "unsupported-type" | "versioning-unsupported" | "project-name-required" | "default-project-name" | "name-collision" | "name-too-long" | "unsupported-encoding" | "default-not-applied" | "constraint-not-checked" | "requires-host", M extends keyof {
|
|
79
|
+
export declare const reportDiagnostic: <C extends "invalid-name" | "invalid-service-name" | "host-inside-generated" | "generated-inside-host" | "reserved-namespace" | "manifest-unreadable" | "stale-file-kept" | "host-reference-stale" | "solution-missing-project" | "unsupported-type" | "unsupported-route" | "ambiguous-route" | "versioning-unsupported" | "project-name-required" | "default-project-name" | "name-collision" | "name-too-long" | "unsupported-encoding" | "default-not-applied" | "constraint-not-checked" | "requires-host", M extends keyof {
|
|
74
80
|
"invalid-name": {
|
|
75
81
|
readonly default: import("@typespec/compiler").CallableMessage<["option", "value"]>;
|
|
76
82
|
};
|
|
@@ -101,6 +107,12 @@ export declare const reportDiagnostic: <C extends "invalid-name" | "invalid-serv
|
|
|
101
107
|
"unsupported-type": {
|
|
102
108
|
readonly default: import("@typespec/compiler").CallableMessage<["kind"]>;
|
|
103
109
|
};
|
|
110
|
+
"unsupported-route": {
|
|
111
|
+
readonly default: import("@typespec/compiler").CallableMessage<["reason"]>;
|
|
112
|
+
};
|
|
113
|
+
"ambiguous-route": {
|
|
114
|
+
readonly default: import("@typespec/compiler").CallableMessage<["operation", "other"]>;
|
|
115
|
+
};
|
|
104
116
|
"versioning-unsupported": {
|
|
105
117
|
readonly default: "Versioned services cannot be generated yet.";
|
|
106
118
|
};
|
|
@@ -159,6 +171,12 @@ export declare const reportDiagnostic: <C extends "invalid-name" | "invalid-serv
|
|
|
159
171
|
"unsupported-type": {
|
|
160
172
|
readonly default: import("@typespec/compiler").CallableMessage<["kind"]>;
|
|
161
173
|
};
|
|
174
|
+
"unsupported-route": {
|
|
175
|
+
readonly default: import("@typespec/compiler").CallableMessage<["reason"]>;
|
|
176
|
+
};
|
|
177
|
+
"ambiguous-route": {
|
|
178
|
+
readonly default: import("@typespec/compiler").CallableMessage<["operation", "other"]>;
|
|
179
|
+
};
|
|
162
180
|
"versioning-unsupported": {
|
|
163
181
|
readonly default: "Versioned services cannot be generated yet.";
|
|
164
182
|
};
|
|
@@ -186,7 +204,7 @@ export declare const reportDiagnostic: <C extends "invalid-name" | "invalid-serv
|
|
|
186
204
|
"requires-host": {
|
|
187
205
|
readonly default: import("@typespec/compiler").CallableMessage<["option"]>;
|
|
188
206
|
};
|
|
189
|
-
}, C, M>) => void, createDiagnostic: <C extends "invalid-name" | "invalid-service-name" | "host-inside-generated" | "generated-inside-host" | "reserved-namespace" | "manifest-unreadable" | "stale-file-kept" | "host-reference-stale" | "solution-missing-project" | "unsupported-type" | "versioning-unsupported" | "project-name-required" | "default-project-name" | "name-collision" | "name-too-long" | "unsupported-encoding" | "default-not-applied" | "constraint-not-checked" | "requires-host", M extends keyof {
|
|
207
|
+
}, C, M>) => void, createDiagnostic: <C extends "invalid-name" | "invalid-service-name" | "host-inside-generated" | "generated-inside-host" | "reserved-namespace" | "manifest-unreadable" | "stale-file-kept" | "host-reference-stale" | "solution-missing-project" | "unsupported-type" | "unsupported-route" | "ambiguous-route" | "versioning-unsupported" | "project-name-required" | "default-project-name" | "name-collision" | "name-too-long" | "unsupported-encoding" | "default-not-applied" | "constraint-not-checked" | "requires-host", M extends keyof {
|
|
190
208
|
"invalid-name": {
|
|
191
209
|
readonly default: import("@typespec/compiler").CallableMessage<["option", "value"]>;
|
|
192
210
|
};
|
|
@@ -217,6 +235,12 @@ export declare const reportDiagnostic: <C extends "invalid-name" | "invalid-serv
|
|
|
217
235
|
"unsupported-type": {
|
|
218
236
|
readonly default: import("@typespec/compiler").CallableMessage<["kind"]>;
|
|
219
237
|
};
|
|
238
|
+
"unsupported-route": {
|
|
239
|
+
readonly default: import("@typespec/compiler").CallableMessage<["reason"]>;
|
|
240
|
+
};
|
|
241
|
+
"ambiguous-route": {
|
|
242
|
+
readonly default: import("@typespec/compiler").CallableMessage<["operation", "other"]>;
|
|
243
|
+
};
|
|
220
244
|
"versioning-unsupported": {
|
|
221
245
|
readonly default: "Versioned services cannot be generated yet.";
|
|
222
246
|
};
|
|
@@ -275,6 +299,12 @@ export declare const reportDiagnostic: <C extends "invalid-name" | "invalid-serv
|
|
|
275
299
|
"unsupported-type": {
|
|
276
300
|
readonly default: import("@typespec/compiler").CallableMessage<["kind"]>;
|
|
277
301
|
};
|
|
302
|
+
"unsupported-route": {
|
|
303
|
+
readonly default: import("@typespec/compiler").CallableMessage<["reason"]>;
|
|
304
|
+
};
|
|
305
|
+
"ambiguous-route": {
|
|
306
|
+
readonly default: import("@typespec/compiler").CallableMessage<["operation", "other"]>;
|
|
307
|
+
};
|
|
278
308
|
"versioning-unsupported": {
|
|
279
309
|
readonly default: "Versioned services cannot be generated yet.";
|
|
280
310
|
};
|
package/dist/src/lib.js
CHANGED
|
@@ -122,6 +122,18 @@ export const $lib = createTypeSpecLibrary({
|
|
|
122
122
|
default: paramMessage `This type cannot be generated: ${"kind"}.`,
|
|
123
123
|
},
|
|
124
124
|
},
|
|
125
|
+
"unsupported-route": {
|
|
126
|
+
severity: "error",
|
|
127
|
+
messages: {
|
|
128
|
+
default: paramMessage `This route cannot be generated: ${"reason"}.`,
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
"ambiguous-route": {
|
|
132
|
+
severity: "error",
|
|
133
|
+
messages: {
|
|
134
|
+
default: paramMessage `A request cannot tell "${"operation"}" from "${"other"}", which has the same verb and route. Give each a different Content-Type on a required body, or a different fixed value of the same required query parameter or header.`,
|
|
135
|
+
},
|
|
136
|
+
},
|
|
125
137
|
"versioning-unsupported": {
|
|
126
138
|
severity: "error",
|
|
127
139
|
messages: {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type Model, type ModelProperty, type Namespace, type Program, type Type } from "@typespec/compiler";
|
|
1
|
+
import { type Model, type ModelProperty, type Namespace, type Program, type Scalar, type Type } from "@typespec/compiler";
|
|
2
2
|
import type { Constraints, Documented, EncodingModel, PropertyModel, TypeDeclaration, TypeRef } from "./types.js";
|
|
3
3
|
export declare function namespacePath(namespace: Namespace | undefined): string[];
|
|
4
4
|
export declare function documentation(program: Program, type: Type): Documented;
|
|
@@ -10,6 +10,8 @@ export interface BodyRule {
|
|
|
10
10
|
/** The request phase, such as "Create"; undefined for responses. */
|
|
11
11
|
phase: string | undefined;
|
|
12
12
|
}
|
|
13
|
+
/** The scalar a type holds, looking through `T | null`, arrays and dictionaries. */
|
|
14
|
+
export declare function scalarOf(program: Program, type: Type): Scalar | undefined;
|
|
13
15
|
/** The `@encode` of a property, or of its scalar type or one that type derives from. */
|
|
14
16
|
export declare function encodingOf(program: Program, property: ModelProperty): EncodingModel | undefined;
|
|
15
17
|
/** The `@encode` of the scalar a type holds, or of one that scalar derives from. */
|
|
@@ -26,7 +26,7 @@ function isPlainRecord(program, model) {
|
|
|
26
26
|
return isRecordModelType(program, model) && model.properties.size === 0 && !model.baseModel;
|
|
27
27
|
}
|
|
28
28
|
/** The scalar a type holds, looking through `T | null`, arrays and dictionaries. */
|
|
29
|
-
function scalarOf(program, type) {
|
|
29
|
+
export function scalarOf(program, type) {
|
|
30
30
|
if (type.kind === "Scalar")
|
|
31
31
|
return type;
|
|
32
32
|
if (type.kind === "Model" && type.indexer) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { getFriendlyName, isErrorModel, serializeValueAsJson, } from "@typespec/compiler";
|
|
1
|
+
import { getAllTags, getFriendlyName, getSummary, getTags, isErrorModel, serializeValueAsJson, } from "@typespec/compiler";
|
|
2
2
|
import { getAllHttpServices, getPatchOptions, getServers, isBody, isVisible, resolveRequestVisibility, Visibility, isOverloadSameEndpoint, isSharedRoute, resolveAuthentication, } from "@typespec/http";
|
|
3
3
|
import { reportDiagnostic } from "../lib.js";
|
|
4
|
-
import { constraintsOf, documentation, encodingOf, isExcluded, namespacePath, TypeCollector, } from "./collect-types.js";
|
|
4
|
+
import { constraintsOf, documentation, encodingOf, heldConstraints, isExcluded, namespacePath, scalarOf, TypeCollector, } from "./collect-types.js";
|
|
5
5
|
import { exampleOf, operationExamples } from "./examples.js";
|
|
6
6
|
/** Reads a compiled program into the style-neutral model. Problems are reported as diagnostics. */
|
|
7
7
|
export function collectModel(program) {
|
|
@@ -34,6 +34,7 @@ function collectService(program, collector, service) {
|
|
|
34
34
|
namespace: namespacePath(container.namespace),
|
|
35
35
|
kind: container.kind === "Interface" ? "interface" : "namespace",
|
|
36
36
|
operations: [],
|
|
37
|
+
...tagList(getAllTags(program, container)),
|
|
37
38
|
source: container,
|
|
38
39
|
};
|
|
39
40
|
groups.set(container, group);
|
|
@@ -60,6 +61,9 @@ function collectService(program, collector, service) {
|
|
|
60
61
|
groups: [...groups.values()],
|
|
61
62
|
};
|
|
62
63
|
}
|
|
64
|
+
function tagList(tags) {
|
|
65
|
+
return tags?.length ? { tags: [...tags] } : {};
|
|
66
|
+
}
|
|
63
67
|
function isVersioned(namespace) {
|
|
64
68
|
for (let current = namespace; current; current = current.namespace) {
|
|
65
69
|
if (current.decorators.some((applied) => applied.decorator.name === "$versioned"))
|
|
@@ -103,6 +107,10 @@ function collectOperation(program, collector, operation, group) {
|
|
|
103
107
|
return {
|
|
104
108
|
...documentation(program, operation.operation),
|
|
105
109
|
...operationExamples(program, operation.operation),
|
|
110
|
+
...tagList(getTags(program, operation.operation)),
|
|
111
|
+
...(getSummary(program, operation.operation) && {
|
|
112
|
+
summary: getSummary(program, operation.operation),
|
|
113
|
+
}),
|
|
106
114
|
name,
|
|
107
115
|
verb: operation.verb,
|
|
108
116
|
path: operation.path,
|
|
@@ -114,6 +122,7 @@ function collectOperation(program, collector, operation, group) {
|
|
|
114
122
|
body: requestBody && {
|
|
115
123
|
...requestBody,
|
|
116
124
|
optional: body.property?.optional ?? false,
|
|
125
|
+
...(body.property && withChecks(program, body.property)),
|
|
117
126
|
...(body.property && {
|
|
118
127
|
...documentation(program, body.property),
|
|
119
128
|
name: body.property.name,
|
|
@@ -150,12 +159,38 @@ function collectOperation(program, collector, operation, group) {
|
|
|
150
159
|
function withEncoding(program, property) {
|
|
151
160
|
const encoding = encodingOf(program, property);
|
|
152
161
|
const constraints = constraintsOf(program, property);
|
|
153
|
-
|
|
162
|
+
const held = heldConstraints(program, property.type);
|
|
163
|
+
return {
|
|
164
|
+
...(encoding && { encoding }),
|
|
165
|
+
...(constraints && { constraints }),
|
|
166
|
+
...(held.length && { heldConstraints: held }),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
/** A date and time in a header is an HTTP date unless the spec says otherwise. */
|
|
170
|
+
function headerEncoding(program, property) {
|
|
171
|
+
if (encodingOf(program, property))
|
|
172
|
+
return {};
|
|
173
|
+
for (let scalar = scalarOf(program, property.type); scalar; scalar = scalar.baseScalar) {
|
|
174
|
+
if (scalar.name === "utcDateTime" || scalar.name === "offsetDateTime") {
|
|
175
|
+
return { encoding: { name: "rfc7231", wireType: "string" } };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return {};
|
|
179
|
+
}
|
|
180
|
+
/** The constraints on a property, apart from its encoding. */
|
|
181
|
+
function withChecks(program, property) {
|
|
182
|
+
const constraints = constraintsOf(program, property);
|
|
183
|
+
const held = heldConstraints(program, property.type);
|
|
184
|
+
return {
|
|
185
|
+
...(constraints && { constraints }),
|
|
186
|
+
...(held.length && { heldConstraints: held }),
|
|
187
|
+
};
|
|
154
188
|
}
|
|
155
189
|
function headerParameter(program, collector, wireName, property, usage) {
|
|
156
190
|
return {
|
|
157
191
|
...documentation(program, property),
|
|
158
192
|
...withEncoding(program, property),
|
|
193
|
+
...headerEncoding(program, property),
|
|
159
194
|
...exampleOf(program, property),
|
|
160
195
|
name: property.name,
|
|
161
196
|
wireName,
|
|
@@ -171,6 +206,7 @@ function collectParameter(program, collector, parameter, usage) {
|
|
|
171
206
|
return {
|
|
172
207
|
...documentation(program, property),
|
|
173
208
|
...withEncoding(program, property),
|
|
209
|
+
...(parameter.type === "header" && headerEncoding(program, property)),
|
|
174
210
|
...exampleOf(program, property),
|
|
175
211
|
name: property.name,
|
|
176
212
|
wireName: parameter.name,
|
|
@@ -197,6 +197,8 @@ export interface ParameterModel extends Documented {
|
|
|
197
197
|
explode: boolean;
|
|
198
198
|
encoding?: EncodingModel;
|
|
199
199
|
constraints?: Constraints;
|
|
200
|
+
/** Constraints on what an array parameter holds. */
|
|
201
|
+
heldConstraints?: string[];
|
|
200
202
|
example?: Sample;
|
|
201
203
|
/** Path parameters whose reserved characters, such as "/", are not escaped. */
|
|
202
204
|
allowReserved?: boolean;
|
|
@@ -283,12 +285,18 @@ export interface OperationModel extends Documented {
|
|
|
283
285
|
optional: boolean;
|
|
284
286
|
name?: string;
|
|
285
287
|
doc?: string;
|
|
288
|
+
constraints?: Constraints;
|
|
289
|
+
heldConstraints?: string[];
|
|
286
290
|
}) | undefined;
|
|
287
291
|
responses: ResponseModel[];
|
|
288
292
|
/** Alternatives, any one of which is enough. Empty when the spec says nothing. */
|
|
289
293
|
auth: AuthOptionModel[];
|
|
290
294
|
/** What each `@opExample` returns. */
|
|
291
295
|
examples?: Sample[];
|
|
296
|
+
/** The `@summary` of the operation. */
|
|
297
|
+
summary?: string;
|
|
298
|
+
/** Names given by `@tag` on the operation itself. */
|
|
299
|
+
tags?: string[];
|
|
292
300
|
source: Type;
|
|
293
301
|
}
|
|
294
302
|
/** The operations of one TypeSpec interface, or those declared directly in a namespace. */
|
|
@@ -297,6 +305,8 @@ export interface GroupModel extends Documented {
|
|
|
297
305
|
namespace: string[];
|
|
298
306
|
kind: "interface" | "namespace";
|
|
299
307
|
operations: OperationModel[];
|
|
308
|
+
/** Names given by `@tag` on the group and the namespaces around it. */
|
|
309
|
+
tags?: string[];
|
|
300
310
|
source: Type;
|
|
301
311
|
}
|
|
302
312
|
export interface ServiceModel extends Documented {
|
package/dist/src/naming/names.js
CHANGED
|
@@ -10,7 +10,14 @@ const frameworkTypes = ("Action Array Attribute Boolean Byte CancellationToken C
|
|
|
10
10
|
"Program ServiceCollection WebApplication " +
|
|
11
11
|
"Object Single String System Task TimeOnly TimeSpan Type Uri Value ValueTask").split(" ");
|
|
12
12
|
// Namespaces below the root that hold the emitter's own code.
|
|
13
|
-
const ownNamespaces = [
|
|
13
|
+
const ownNamespaces = [
|
|
14
|
+
"Serialization",
|
|
15
|
+
"Validation",
|
|
16
|
+
"Requests",
|
|
17
|
+
"Responses",
|
|
18
|
+
"Routing",
|
|
19
|
+
"Documentation",
|
|
20
|
+
];
|
|
14
21
|
// Names a record already has, which a property cannot take.
|
|
15
22
|
const recordMembers = new Set("Clone Deconstruct EqualityContract Equals GetHashCode GetType PrintMembers ToString".split(" "));
|
|
16
23
|
// File names that Windows does not allow.
|
|
@@ -60,6 +67,9 @@ export function assignNames(program, model, rootNamespace, setupNames = []) {
|
|
|
60
67
|
namespaces.add(`${rootNamespace}.Serialization`.toLowerCase());
|
|
61
68
|
namespaces.add(`${rootNamespace}.Validation`.toLowerCase());
|
|
62
69
|
namespaces.add(`${rootNamespace}.Requests`.toLowerCase());
|
|
70
|
+
namespaces.add(`${rootNamespace}.Routing`.toLowerCase());
|
|
71
|
+
namespaces.add(`${rootNamespace}.Responses`.toLowerCase());
|
|
72
|
+
namespaces.add(`${rootNamespace}.Documentation`.toLowerCase());
|
|
63
73
|
// A type named like part of the root namespace, or like a common .NET type, would hide it.
|
|
64
74
|
const reserved = new Set([...rootNamespace.split("."), ...frameworkTypes, ...setupNames].map((name) => name.toLowerCase()));
|
|
65
75
|
// Types written by name choose first, so a derived or inline type never takes their name.
|
|
@@ -28,6 +28,16 @@ export interface ServiceName {
|
|
|
28
28
|
name: string;
|
|
29
29
|
file: string;
|
|
30
30
|
operations: OperationName[];
|
|
31
|
+
endpoints: EndpointsName;
|
|
32
|
+
}
|
|
33
|
+
/** The class mapping the routes of a group, and the names inside it. */
|
|
34
|
+
export interface EndpointsName {
|
|
35
|
+
name: string;
|
|
36
|
+
file: string;
|
|
37
|
+
/** The extension method mapping the group. */
|
|
38
|
+
map: string;
|
|
39
|
+
/** The handler for each of `operations`, in order. */
|
|
40
|
+
handlers: string[];
|
|
31
41
|
}
|
|
32
42
|
/**
|
|
33
43
|
* Names the service interfaces, their methods and their result unions. `claim` takes a type name in
|
|
@@ -99,7 +99,7 @@ function caseNames(program, operation, union, describe) {
|
|
|
99
99
|
* a namespace, avoiding every name already used there.
|
|
100
100
|
*/
|
|
101
101
|
export function nameServices(program, model, rootNamespace, namespaceOf, claim, describe) {
|
|
102
|
-
|
|
102
|
+
const services = model.services.flatMap((service) => service.groups.map((group) => {
|
|
103
103
|
const relative = namespaceOf(group.namespace);
|
|
104
104
|
// Operations outside any namespace have a group without a name.
|
|
105
105
|
const groupName = pascalCase(group.name || rootNamespace.split(".").at(-1));
|
|
@@ -123,6 +123,15 @@ export function nameServices(program, model, rootNamespace, namespaceOf, claim,
|
|
|
123
123
|
cases: caseNames(program, operation, result.name, describe),
|
|
124
124
|
};
|
|
125
125
|
});
|
|
126
|
-
|
|
126
|
+
const namespace = [rootNamespace, ...relative].join(".");
|
|
127
|
+
return { group, namespace, name, file, operations, relative, groupName };
|
|
127
128
|
}));
|
|
129
|
+
// Claimed last, so that no interface or result depends on the names of the endpoints.
|
|
130
|
+
return services.map(({ relative, groupName, ...service }) => {
|
|
131
|
+
const claimed = claim(relative, `${groupName}Endpoints`, service.group.source);
|
|
132
|
+
const map = `Map${claimed.name}`;
|
|
133
|
+
const handler = chooser(program, [claimed.name, map]);
|
|
134
|
+
const handlers = service.operations.map((o) => handler(o.method, o.operation.source));
|
|
135
|
+
return { ...service, endpoints: { ...claimed, map, handlers } };
|
|
136
|
+
});
|
|
128
137
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
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[];
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { stringLiteral } from "../shared/writer.js";
|
|
2
|
+
import { isReference } from "../shared/references.js";
|
|
3
|
+
const builder = "global::Microsoft.AspNetCore.Builder";
|
|
4
|
+
const openApi = "global::Microsoft.AspNetCore.Http.OpenApiRouteHandlerBuilderExtensions";
|
|
5
|
+
const routing = `${builder}.RoutingEndpointConventionBuilderExtensions`;
|
|
6
|
+
const statusKey = (status) => {
|
|
7
|
+
if (status === "default")
|
|
8
|
+
return "default";
|
|
9
|
+
if (typeof status === "number")
|
|
10
|
+
return String(status);
|
|
11
|
+
return status.start % 100 === 0 && status.end === status.start + 99
|
|
12
|
+
? `${status.start / 100}XX`
|
|
13
|
+
: undefined;
|
|
14
|
+
};
|
|
15
|
+
/** `typeof` cannot name a nullable reference type. */
|
|
16
|
+
const typeOf = (type, reference) => `typeof(${reference ? type.replace(/\?$/, "") : type})`;
|
|
17
|
+
export function documentationWriter(model, rootNamespace, openapi) {
|
|
18
|
+
const documentation = `global::${rootNamespace}.Documentation`;
|
|
19
|
+
const names = new Set();
|
|
20
|
+
/** The calls naming and describing an endpoint held in `endpoint`. */
|
|
21
|
+
return function describe(group, contract, binding, endpoint) {
|
|
22
|
+
const operation = contract.operation.operation;
|
|
23
|
+
const wanted = group ? `${group}_${operation.name}` : operation.name;
|
|
24
|
+
let name = wanted;
|
|
25
|
+
for (let number = 2; names.has(name.toLowerCase()); number++)
|
|
26
|
+
name = `${wanted}${number}`;
|
|
27
|
+
names.add(name.toLowerCase());
|
|
28
|
+
const lines = [` ${routing}.WithName(${endpoint}, ${stringLiteral(name)});`];
|
|
29
|
+
if (operation.summary) {
|
|
30
|
+
lines.push(` ${openApi}.WithSummary(${endpoint}, ${stringLiteral(operation.summary)});`);
|
|
31
|
+
}
|
|
32
|
+
if (operation.doc) {
|
|
33
|
+
lines.push(` ${openApi}.WithDescription(${endpoint}, ${stringLiteral(operation.doc)});`);
|
|
34
|
+
}
|
|
35
|
+
if (!openapi)
|
|
36
|
+
return lines;
|
|
37
|
+
const array = (type, items) => `new ${documentation}.${type}[] { ${items.join(", ")} }`;
|
|
38
|
+
const metadata = [];
|
|
39
|
+
const responses = new Map();
|
|
40
|
+
for (const found of contract.cases) {
|
|
41
|
+
const { response, content } = found.found;
|
|
42
|
+
const key = statusKey(response.status);
|
|
43
|
+
if (!key || responses.has(key))
|
|
44
|
+
continue;
|
|
45
|
+
const body = content.body && found.members.find((m) => m.name === "Body");
|
|
46
|
+
const sent = content.body?.contentTypes.find((t) => !t.includes("*"));
|
|
47
|
+
const reference = content.body?.kind === "single" && isReference(model, content.body.type);
|
|
48
|
+
const type = body ? typeOf(body.type, reference) : undefined;
|
|
49
|
+
const headers = content.headers.map((header, index) => {
|
|
50
|
+
const member = found.members.find((m) => m.name === found.found.headers[index]);
|
|
51
|
+
const held = isReference(model, header.type);
|
|
52
|
+
return `new ${documentation}.DocumentedHeader(${stringLiteral(header.wireName)}, ${typeOf(member.type.replace(/\?$/, ""), held)}, ${!header.optional})`;
|
|
53
|
+
});
|
|
54
|
+
const parts = [
|
|
55
|
+
stringLiteral(key),
|
|
56
|
+
...(type
|
|
57
|
+
? [`Body: ${type}`, `ContentType: ${stringLiteral(sent ?? "application/json")}`]
|
|
58
|
+
: []),
|
|
59
|
+
...(headers.length ? [`Headers: ${array("DocumentedHeader", headers)}`] : []),
|
|
60
|
+
];
|
|
61
|
+
responses.set(key, `new ${documentation}.DocumentedResponse(${parts.join(", ")})`);
|
|
62
|
+
// A response without a body is added by the transformer, as `void` has no schema.
|
|
63
|
+
if (typeof response.status === "number" && type) {
|
|
64
|
+
const types = `new string[] { ${stringLiteral(sent ?? "application/json")} }`;
|
|
65
|
+
metadata.push(`new global::Microsoft.AspNetCore.Http.ProducesResponseTypeMetadata(${response.status}, ${type}, ${types})`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// Inputs the handler declares as text, or not at all.
|
|
69
|
+
const parameters = operation.parameters.flatMap((input, index) => {
|
|
70
|
+
const given = contract.parameters[index];
|
|
71
|
+
const declared = binding.parameters.find((p) => p.name === given.name);
|
|
72
|
+
const plain = given.type.replace(/\?$/, "");
|
|
73
|
+
const shown = declared?.type.replace(/\?$/, "") === plain;
|
|
74
|
+
if (shown && !declared?.attributes?.length)
|
|
75
|
+
return [];
|
|
76
|
+
const reference = isReference(model, input.type);
|
|
77
|
+
const parts = [
|
|
78
|
+
stringLiteral(input.wireName),
|
|
79
|
+
stringLiteral(input.in),
|
|
80
|
+
...(shown ? [] : [`Type: ${typeOf(plain, reference)}`]),
|
|
81
|
+
...(input.optional || input.default !== undefined ? [] : ["Required: true"]),
|
|
82
|
+
...(binding.checks.get(index)?.length
|
|
83
|
+
? [
|
|
84
|
+
`Constraints: new global::System.ComponentModel.DataAnnotations.ValidationAttribute[] { ${binding.checks.get(index).join(", ")} }`,
|
|
85
|
+
]
|
|
86
|
+
: []),
|
|
87
|
+
];
|
|
88
|
+
return [`new ${documentation}.DocumentedParameter(${parts.join(", ")})`];
|
|
89
|
+
});
|
|
90
|
+
const body = operation.body;
|
|
91
|
+
const byHand = body && !binding.parameters.some((p) => p.source === "body")
|
|
92
|
+
? `new ${documentation}.DocumentedResponse("body", ${typeOf(contract.parameters[operation.parameters.length].type.replace(/\?$/, ""), true)}, ${stringLiteral(body.contentTypes[0])})`
|
|
93
|
+
: undefined;
|
|
94
|
+
// ASP.NET Core says a body it reads is "application/json".
|
|
95
|
+
const types = body && !byHand && body.contentTypes.join() !== "application/json" ? body.contentTypes : [];
|
|
96
|
+
const parts = [
|
|
97
|
+
array("DocumentedResponse", [...responses.values()]),
|
|
98
|
+
...(types.length ? [`SentAs: new string[] { ${types.map(stringLiteral).join(", ")} }`] : []),
|
|
99
|
+
...(parameters.length ? [`Parameters: ${array("DocumentedParameter", parameters)}`] : []),
|
|
100
|
+
...(byHand ? [`Request: ${byHand}`] : []),
|
|
101
|
+
...(operation.deprecated ? ["Deprecated: true"] : []),
|
|
102
|
+
];
|
|
103
|
+
metadata.push(`new ${documentation}.DocumentedOperation(${parts.join(", ")})`);
|
|
104
|
+
lines.push(` ${routing}.WithMetadata(`, ` ${endpoint},`, `${metadata.map((item) => ` ${item}`).join(",\n")});`);
|
|
105
|
+
return lines;
|
|
106
|
+
};
|
|
107
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ServiceName } from "../../naming/services.js";
|
|
2
|
+
import type { Binding } from "../shared/binding.js";
|
|
3
|
+
import type { RenderedFile } from "../shared/models.js";
|
|
4
|
+
import type { Routing } from "../shared/routes.js";
|
|
5
|
+
import type { ResultMapping } from "./results.js";
|
|
6
|
+
/** What a handler reads and answers. */
|
|
7
|
+
export interface Handled {
|
|
8
|
+
binding: Binding;
|
|
9
|
+
result: ResultMapping;
|
|
10
|
+
/** The calls naming and describing the endpoint held in the given variable. */
|
|
11
|
+
describe(endpoint: string): string[];
|
|
12
|
+
}
|
|
13
|
+
/** Renders the endpoint class of every group. */
|
|
14
|
+
export declare function renderEndpoints(rootNamespace: string, services: ServiceName[], routing: Routing, handle: (service: ServiceName, index: number) => Handled): RenderedFile[];
|