sheridan-typespec-aspnet 0.2.1 → 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 +10 -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 +2 -2
@@ -0,0 +1,241 @@
1
+ import { reportDiagnostic } from "../../lib.js";
2
+ const expression = /\{([+#./;?&]?)([^}]*)\}/g;
3
+ function decode(text) {
4
+ try {
5
+ return decodeURIComponent(text);
6
+ }
7
+ catch {
8
+ return text;
9
+ }
10
+ }
11
+ /** Reads the URI template of an operation. Returns what is wrong when ASP.NET Core cannot map it. */
12
+ export function parseRoute(operation) {
13
+ const literal = (text) => text.replaceAll("{", "{{").replaceAll("}", "}}");
14
+ const optional = new Set(operation.parameters.filter((p) => p.in === "path" && p.optional).map((p) => p.wireName));
15
+ const names = new Set();
16
+ let path = "";
17
+ let last = 0;
18
+ let problem;
19
+ // Parameters are replaced by markers, so that their text is not read as part of the route.
20
+ const parameters = [];
21
+ for (const found of operation.uriTemplate.matchAll(expression)) {
22
+ const [text, operator, variables] = found;
23
+ path += operation.uriTemplate.slice(last, found.index);
24
+ last = found.index + text.length;
25
+ if (operator === "?" || operator === "&")
26
+ continue;
27
+ if (operator === "#" || operator === "." || operator === ";") {
28
+ return `a path parameter written as "{${operator}…}"`;
29
+ }
30
+ for (const variable of variables.split(",")) {
31
+ const name = decode(variable.replace(/\*$|:\d+$/, ""));
32
+ if (/[{}/?*:=]/.test(name))
33
+ return `a path parameter named "${name}"`;
34
+ if (names.has(name.toLowerCase()))
35
+ problem = `the path parameter "${name}" used twice`;
36
+ names.add(name.toLowerCase());
37
+ const rest = operator === "+";
38
+ const mayBeLeftOut = optional.has(name);
39
+ const marker = `\u0000${parameters.length}\u0000`;
40
+ parameters.push({
41
+ text: `{${rest ? "**" : ""}${name}${mayBeLeftOut && !rest ? "?" : ""}}`,
42
+ trailing: rest || mayBeLeftOut,
43
+ whole: rest || mayBeLeftOut,
44
+ });
45
+ path += operator === "/" ? `/${marker}` : marker;
46
+ }
47
+ }
48
+ path += operation.uriTemplate.slice(last);
49
+ if (problem)
50
+ return problem;
51
+ const mark = path.indexOf("?");
52
+ const query = (mark < 0 ? "" : path.slice(mark + 1))
53
+ .split("&")
54
+ .filter(Boolean)
55
+ .map((pair) => {
56
+ const at = pair.indexOf("=");
57
+ return at < 0 ? [decode(pair), ""] : [decode(pair.slice(0, at)), decode(pair.slice(at + 1))];
58
+ });
59
+ const segments = [];
60
+ for (const part of (mark < 0 ? path : path.slice(0, mark)).split("/").filter(Boolean)) {
61
+ // Odd pieces are the numbers of parameters.
62
+ const pieces = part.split("\u0000");
63
+ const held = pieces.filter((_, index) => index % 2 === 1).map((n) => parameters[Number(n)]);
64
+ if (pieces.some((piece, index) => index > 0 && index < pieces.length - 1 && piece === "")) {
65
+ return "two path parameters with nothing between them";
66
+ }
67
+ if (held.some((p) => p.whole) && (held.length > 1 || pieces[0] || pieces.at(-1))) {
68
+ return "an optional or reserved path parameter that shares its segment";
69
+ }
70
+ segments.push({
71
+ text: pieces
72
+ .map((piece, index) => index % 2 === 1 ? parameters[Number(piece)].text : literal(decode(piece)))
73
+ .join(""),
74
+ trailing: held.some((p) => p.trailing),
75
+ });
76
+ }
77
+ const first = segments.findIndex((segment) => segment.trailing);
78
+ if (first >= 0) {
79
+ const after = segments.slice(first);
80
+ const catchAll = after.findIndex((segment) => segment.text.startsWith("{**"));
81
+ if (after.some((s) => !s.trailing) || (catchAll >= 0 && catchAll !== after.length - 1)) {
82
+ return "an optional or reserved path parameter before the end of the route";
83
+ }
84
+ }
85
+ return { segments, query };
86
+ }
87
+ /**
88
+ * True when ASP.NET Core ranks two routes the same and some path matches both, ignoring case.
89
+ */
90
+ function overlap(a, b) {
91
+ return (a.segments.length === b.segments.length &&
92
+ a.segments.every((segment, index) => {
93
+ const first = shape(segment);
94
+ const second = shape(b.segments[index]);
95
+ if (first.kind !== second.kind)
96
+ return false;
97
+ // Parameters match any text; literal text must agree at both ends.
98
+ const agree = (x, y, ends) => x[ends](y) || y[ends](x);
99
+ if (first.kind === "literal")
100
+ return first.start === second.start;
101
+ return (agree(first.start, second.start, "startsWith") && agree(first.end, second.end, "endsWith"));
102
+ }));
103
+ }
104
+ /** What a segment is, and the literal text it starts and ends with. */
105
+ function shape({ text }) {
106
+ // Doubled braces are literal text, so they are set aside while parameters are found.
107
+ const parts = text
108
+ .toLowerCase()
109
+ .replaceAll("{{", "\u0001")
110
+ .replaceAll("}}", "\u0002")
111
+ .split(/(\{[^{}]*\})/);
112
+ const [start, end] = [parts[0], parts.at(-1)];
113
+ if (parts.length === 1)
114
+ return { kind: "literal", start, end };
115
+ const whole = parts.length === 3 && !start && !end;
116
+ if (!whole)
117
+ return { kind: "complex", start, end };
118
+ return { kind: parts[1].startsWith("{**") ? "catch-all" : "parameter", start, end };
119
+ }
120
+ /** The text a parameter must have, when the spec allows only one. */
121
+ function fixedValue(model, type) {
122
+ if (type.kind === "literal") {
123
+ return {
124
+ value: type.text ?? String(type.value),
125
+ ignoreCase: typeof type.value === "boolean",
126
+ };
127
+ }
128
+ if (type.kind !== "enumMember")
129
+ return undefined;
130
+ const declared = model.types.get(type.enum);
131
+ const member = declared?.kind === "enum" && declared.members.find((m) => m.name === type.member);
132
+ return member ? { value: String(member.value), ignoreCase: false } : undefined;
133
+ }
134
+ function requiredValues(model, operation, route) {
135
+ const written = route.query.map(([name, value]) => ({
136
+ in: "query",
137
+ name,
138
+ value,
139
+ ignoreCase: false,
140
+ }));
141
+ const declared = operation.parameters.flatMap((parameter) => {
142
+ if (parameter.optional || (parameter.in !== "query" && parameter.in !== "header"))
143
+ return [];
144
+ // The content type of a request is compared as such, whatever parameters it carries.
145
+ if (parameter.in === "header" && parameter.wireName.toLowerCase() === "content-type")
146
+ return [];
147
+ const fixed = fixedValue(model, parameter.type);
148
+ return fixed ? [{ in: parameter.in, name: parameter.wireName, ...fixed }] : [];
149
+ });
150
+ return [...written, ...declared];
151
+ }
152
+ /** The content types that identify a request for an operation, when its body must be sent. */
153
+ function identifyingTypes(operation) {
154
+ const { body } = operation;
155
+ if (!body || body.optional)
156
+ return [];
157
+ const types = body.contentTypes.map((type) => type.split(";")[0].trim().toLowerCase());
158
+ return types.some((type) => type.includes("*")) ? [] : types;
159
+ }
160
+ function differInValue(a, b) {
161
+ return a.some((first) => b.some((second) => {
162
+ if (first.in !== second.in || first.name.toLowerCase() !== second.name.toLowerCase()) {
163
+ return false;
164
+ }
165
+ return first.ignoreCase || second.ignoreCase
166
+ ? first.value.toLowerCase() !== second.value.toLowerCase()
167
+ : first.value !== second.value;
168
+ }));
169
+ }
170
+ /** Reads every route, and works out how requests reach operations that share one. */
171
+ export function planRoutes(program, model) {
172
+ const routes = new Map();
173
+ const operations = model.services.flatMap((s) => s.groups.flatMap((group) => group.operations));
174
+ for (const operation of operations) {
175
+ const route = parseRoute(operation);
176
+ if (typeof route === "string") {
177
+ reportDiagnostic(program, {
178
+ code: "unsupported-route",
179
+ format: { reason: route },
180
+ target: operation.source,
181
+ });
182
+ }
183
+ else {
184
+ routes.set(operation, route);
185
+ }
186
+ }
187
+ const found = [...routes].map(([operation, route]) => ({
188
+ operation,
189
+ route,
190
+ values: requiredValues(model, operation, route),
191
+ types: identifyingTypes(operation),
192
+ needsType: false,
193
+ /** Operations whose routes can take the same request, and those that theirs can. */
194
+ set: undefined,
195
+ }));
196
+ found.forEach((second, index) => {
197
+ for (const first of found.slice(0, index)) {
198
+ if (first.operation.verb !== second.operation.verb)
199
+ continue;
200
+ if (!overlap(first.route, second.route))
201
+ continue;
202
+ const set = first.set ?? new Set([first.operation]);
203
+ for (const operation of second.set ?? [second.operation])
204
+ set.add(operation);
205
+ for (const other of found) {
206
+ if (set.has(other.operation))
207
+ other.set = set;
208
+ }
209
+ if (differInValue(first.values, second.values))
210
+ continue;
211
+ const disjoint = first.types.length > 0 &&
212
+ second.types.length > 0 &&
213
+ !first.types.some((type) => second.types.includes(type));
214
+ if (disjoint) {
215
+ first.needsType = second.needsType = true;
216
+ continue;
217
+ }
218
+ reportDiagnostic(program, {
219
+ code: "ambiguous-route",
220
+ format: { operation: second.operation.name, other: first.operation.name },
221
+ target: second.operation.source,
222
+ });
223
+ }
224
+ });
225
+ const conditions = new Map();
226
+ for (const { operation, values, types, needsType, set } of found) {
227
+ if (!set)
228
+ continue;
229
+ // ASP.NET Core takes "+json" types for JSON, so each operation is offered every type of the
230
+ // set, and the condition alone chooses between them.
231
+ const accepted = needsType
232
+ ? found.filter((other) => other.needsType && set.has(other.operation)).flatMap((o) => o.types)
233
+ : [];
234
+ conditions.set(operation, {
235
+ values,
236
+ contentTypes: needsType ? types : [],
237
+ accepted: [...new Set(accepted)],
238
+ });
239
+ }
240
+ return { routes, conditions };
241
+ }
@@ -1,6 +1,11 @@
1
- import type { Constraints } from "../../model/types.js";
1
+ import type { ApiModel, Constraints, TypeRef } from "../../model/types.js";
2
2
  /** Rewrites `$` so that, as in JavaScript, it does not match before a final line break. */
3
3
  export declare function dotNetPattern(pattern: string): string | undefined;
4
+ /** What a value holds, for deciding which constraints apply. */
5
+ export declare function holds(model: ApiModel, ref: TypeRef): Holds;
6
+ export type Holds = "string" | "number" | "array" | "other";
7
+ /** What ASP.NET Core does not look inside, when it holds something to check. */
8
+ export declare function unreached(model: ApiModel, ref: TypeRef): string | undefined;
4
9
  /** The constraints that `validationAttributes` cannot turn into an attribute. */
5
10
  export declare function uncheckedConstraints(constraints: Constraints, holds: "string" | "number" | "array" | "other"): string[];
6
11
  /** The validation attributes a property needs, without brackets. */
@@ -1,3 +1,4 @@
1
+ import { mapScalar } from "./scalars.js";
1
2
  import { stringLiteral } from "./writer.js";
2
3
  // Syntax JavaScript accepts that the .NET engine rejects or reads differently.
3
4
  const javaScriptOnly = /\\u\{|\[\^?\]|\\[pP]\{[^}]*=/;
@@ -16,6 +17,58 @@ export function dotNetPattern(pattern) {
16
17
  return token;
17
18
  });
18
19
  }
20
+ /** What a value holds, for deciding which constraints apply. */
21
+ export function holds(model, ref) {
22
+ if (ref.kind === "nullable")
23
+ return holds(model, ref.type);
24
+ if (ref.kind === "array")
25
+ return "array";
26
+ let name = ref.kind === "scalar" ? ref.name : undefined;
27
+ if (ref.kind === "named") {
28
+ const type = model.types.get(ref.id);
29
+ if (type.kind === "scalar")
30
+ name = type.builtin;
31
+ }
32
+ const mapped = name === undefined ? undefined : mapScalar(name)?.type;
33
+ if (mapped === "string")
34
+ return "string";
35
+ return mapped && /^(s?byte|u?short|u?int|u?long|float|double|decimal)$/.test(mapped)
36
+ ? "number"
37
+ : "other";
38
+ }
39
+ /** True when a model, or one it holds, has a constraint. */
40
+ function constrained(model, ref, seen = new Set()) {
41
+ if (ref.kind === "nullable")
42
+ return constrained(model, ref.type, seen);
43
+ if (ref.kind === "array")
44
+ return constrained(model, ref.element, seen);
45
+ if (ref.kind === "record")
46
+ return constrained(model, ref.value, seen);
47
+ if (ref.kind !== "named" || seen.has(ref.id))
48
+ return false;
49
+ seen.add(ref.id);
50
+ const type = model.types.get(ref.id);
51
+ if (type.kind === "union")
52
+ return type.variants.some((v) => constrained(model, v.type, seen));
53
+ if (type.kind !== "model")
54
+ return false;
55
+ return ((type.base !== undefined && constrained(model, { kind: "named", id: type.base }, seen)) ||
56
+ type.properties.some((p) => p.constraints !== undefined || constrained(model, p.type, seen)));
57
+ }
58
+ /** What ASP.NET Core does not look inside, when it holds something to check. */
59
+ export function unreached(model, ref) {
60
+ if (ref.kind === "nullable")
61
+ return unreached(model, ref.type);
62
+ if (ref.kind === "array")
63
+ return unreached(model, ref.element);
64
+ if (ref.kind === "record") {
65
+ return constrained(model, ref.value) ? "constraints of models in a dictionary" : undefined;
66
+ }
67
+ const type = ref.kind === "named" ? model.types.get(ref.id) : undefined;
68
+ return type?.kind === "union" && constrained(model, ref)
69
+ ? "constraints of models in a union"
70
+ : undefined;
71
+ }
19
72
  /** The constraints that `validationAttributes` cannot turn into an attribute. */
20
73
  export function uncheckedConstraints(constraints, holds) {
21
74
  const applies = {
@@ -51,6 +104,10 @@ export function validationAttributes(constraints, holds, namespace) {
51
104
  found.push(attribute("Pattern", [
52
105
  stringLiteral(pattern),
53
106
  ...(message ? [`ErrorMessage = ${stringLiteral(message)}`] : []),
107
+ // The pattern as the spec writes it, when .NET is given another form.
108
+ ...(pattern === constraints.pattern
109
+ ? []
110
+ : [`Source = ${stringLiteral(constraints.pattern)}`]),
54
111
  ]));
55
112
  }
56
113
  if (constraints.format === "uuid")
@@ -149,6 +206,9 @@ public sealed class PatternAttribute(string pattern)
149
206
 
150
207
  public string Expression { get; } = pattern;
151
208
 
209
+ /// <summary>The pattern of the spec, when it differs from <see cref="Expression"/>.</summary>
210
+ public string? Source { get; set; }
211
+
152
212
  protected override bool Satisfies(object value)
153
213
  {
154
214
  try
@@ -6,7 +6,7 @@ export interface ProjectFile {
6
6
  content: string;
7
7
  }
8
8
  /** The project of the generated code, rewritten on every compile. */
9
- export declare function generatedProject(names: ProjectNames): ProjectFile;
9
+ export declare function generatedProject(names: ProjectNames, openapi?: boolean): ProjectFile;
10
10
  /** The path the host project refers to the generated project by, as written in its file. */
11
11
  export declare function projectReference(reference: string): string;
12
12
  /**
@@ -4,7 +4,7 @@ const xml = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").repl
4
4
  /** A path as an MSBuild item, where some characters would otherwise be read as syntax. */
5
5
  const item = (path) => xml(path.replace(/[%;@$']/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`));
6
6
  /** The project of the generated code, rewritten on every compile. */
7
- export function generatedProject(names) {
7
+ export function generatedProject(names, openapi = false) {
8
8
  return {
9
9
  path: `${names.generated}/${names.generated}.csproj`,
10
10
  content: `<!-- Generated by Sheridan.Typespec.Aspnet. Do not edit. -->
@@ -15,11 +15,12 @@ export function generatedProject(names) {
15
15
  <ImplicitUsings>disable</ImplicitUsings>
16
16
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
17
17
  <!-- Not everything in a spec has a description. -->
18
- <NoWarn>$(NoWarn);CS1591</NoWarn>
18
+ <!-- Code written by the .NET SDK for these types names deprecated ones. -->
19
+ <NoWarn>$(NoWarn);CS1591;CS0612;CS0618</NoWarn>
19
20
  </PropertyGroup>
20
21
  <ItemGroup>
21
22
  <FrameworkReference Include="Microsoft.AspNetCore.App" />
22
- </ItemGroup>
23
+ ${openapi ? ' <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="11.0.0" />\n' : ""} </ItemGroup>
23
24
  </Project>
24
25
  `,
25
26
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sheridan-typespec-aspnet",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "TypeSpec emitter that generates ASP.NET Core servers in C#",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -30,7 +30,7 @@
30
30
  "lint": "oxlint . --deny-warnings",
31
31
  "format": "prettier --write .",
32
32
  "format:check": "prettier --check .",
33
- "smoke": "tsp compile samples/placeholder --emit sheridan-typespec-aspnet --output-dir tsp-output --option sheridan-typespec-aspnet.scaffold-host=false",
33
+ "smoke": "tsp compile samples/placeholder --warn-as-error --emit sheridan-typespec-aspnet --output-dir tsp-output --option sheridan-typespec-aspnet.scaffold-host=false",
34
34
  "typecheck:test": "tsc -p test/tsconfig.json",
35
35
  "test": "npm run build && vitest run",
36
36
  "test:watch": "vitest",