forked from microsoft/typespec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.ts
264 lines (230 loc) · 7.55 KB
/
route.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import {
DecoratorContext,
DiagnosticResult,
Interface,
Namespace,
Operation,
Program,
Type,
createDiagnosticCollector,
validateDecoratorTarget,
} from "@typespec/compiler";
import { HttpStateKeys, createDiagnostic, reportDiagnostic } from "./lib.js";
import { getOperationParameters } from "./parameters.js";
import {
HttpOperation,
HttpOperationParameters,
RouteOptions,
RoutePath,
RouteProducer,
RouteProducerResult,
RouteResolutionOptions,
} from "./types.js";
import { extractParamsFromPath } from "./utils.js";
// The set of allowed segment separator characters
const AllowedSegmentSeparators = ["/", ":"];
function normalizeFragment(fragment: string) {
if (fragment.length > 0 && AllowedSegmentSeparators.indexOf(fragment[0]) < 0) {
// Insert the default separator
fragment = `/${fragment}`;
}
// Trim any trailing slash
return fragment.replace(/\/$/g, "");
}
function buildPath(pathFragments: string[]) {
// Join all fragments with leading and trailing slashes trimmed
const path =
pathFragments.length === 0
? "/"
: pathFragments
.map(normalizeFragment)
.filter((x) => x !== "")
.join("");
// The final path must start with a '/'
return path.length > 0 && path[0] === "/" ? path : `/${path}`;
}
export function resolvePathAndParameters(
program: Program,
operation: Operation,
overloadBase: HttpOperation | undefined,
options: RouteResolutionOptions
): DiagnosticResult<{
path: string;
pathSegments: string[];
parameters: HttpOperationParameters;
}> {
const diagnostics = createDiagnosticCollector();
const { segments, parameters } = diagnostics.pipe(
getRouteSegments(program, operation, overloadBase, options)
);
// Pull out path parameters to verify what's in the path string
const paramByName = new Set(
parameters.parameters.filter(({ type }) => type === "path").map((x) => x.name)
);
// Ensure that all of the parameters defined in the route are accounted for in
// the operation parameters
const routeParams = segments.flatMap(extractParamsFromPath);
for (const routeParam of routeParams) {
if (!paramByName.has(routeParam)) {
diagnostics.add(
createDiagnostic({
code: "missing-path-param",
format: { param: routeParam },
target: operation,
})
);
}
}
return diagnostics.wrap({
path: buildPath(segments),
pathSegments: segments,
parameters,
});
}
function collectSegmentsAndOptions(
program: Program,
source: Interface | Namespace | undefined
): [string[], RouteOptions] {
if (source === undefined) return [[], {}];
const [parentSegments, parentOptions] = collectSegmentsAndOptions(program, source.namespace);
const route = getRoutePath(program, source)?.path;
const options =
source.kind === "Namespace" ? getRouteOptionsForNamespace(program, source) ?? {} : {};
return [[...parentSegments, ...(route ? [route] : [])], { ...parentOptions, ...options }];
}
function getRouteSegments(
program: Program,
operation: Operation,
overloadBase: HttpOperation | undefined,
options: RouteResolutionOptions
): DiagnosticResult<RouteProducerResult> {
const diagnostics = createDiagnosticCollector();
const [parentSegments, parentOptions] = collectSegmentsAndOptions(
program,
operation.interface ?? operation.namespace
);
const routeProducer = getRouteProducer(program, operation) ?? DefaultRouteProducer;
const result = diagnostics.pipe(
routeProducer(program, operation, parentSegments, overloadBase, {
...parentOptions,
...options,
})
);
return diagnostics.wrap(result);
}
/**
* @deprecated DO NOT USE. For internal use only as a workaround.
* @param program Program
* @param target Target namespace
* @param sourceInterface Interface that should be included in namespace.
*/
export function includeInterfaceRoutesInNamespace(
program: Program,
target: Namespace,
sourceInterface: string
) {
let array = program.stateMap(HttpStateKeys.externalInterfaces).get(target);
if (array === undefined) {
array = [];
program.stateMap(HttpStateKeys.externalInterfaces).set(target, array);
}
array.push(sourceInterface);
}
export function DefaultRouteProducer(
program: Program,
operation: Operation,
parentSegments: string[],
overloadBase: HttpOperation | undefined,
options: RouteOptions
): DiagnosticResult<RouteProducerResult> {
const diagnostics = createDiagnosticCollector();
const routePath = getRoutePath(program, operation)?.path;
const segments =
!routePath && overloadBase
? overloadBase.pathSegments
: [...parentSegments, ...(routePath ? [routePath] : [])];
const routeParams = segments.flatMap(extractParamsFromPath);
const parameters: HttpOperationParameters = diagnostics.pipe(
getOperationParameters(program, operation, overloadBase, routeParams, options.paramOptions)
);
// Pull out path parameters to verify what's in the path string
const unreferencedPathParamNames = new Set(
parameters.parameters.filter(({ type }) => type === "path").map((x) => x.name)
);
// Compile the list of all route params that aren't represented in the route
for (const routeParam of routeParams) {
unreferencedPathParamNames.delete(routeParam);
}
// Add any remaining declared path params
for (const paramName of unreferencedPathParamNames) {
segments.push(`{${paramName}}`);
}
return diagnostics.wrap({
segments,
parameters,
});
}
export function setRouteProducer(
program: Program,
operation: Operation,
routeProducer: RouteProducer
): void {
program.stateMap(HttpStateKeys.routeProducer).set(operation, routeProducer);
}
export function getRouteProducer(program: Program, operation: Operation): RouteProducer {
return program.stateMap(HttpStateKeys.routeProducer).get(operation);
}
export function setRoute(context: DecoratorContext, entity: Type, details: RoutePath) {
if (
!validateDecoratorTarget(context, entity, "@route", ["Namespace", "Interface", "Operation"])
) {
return;
}
const state = context.program.stateMap(HttpStateKeys.routes);
if (state.has(entity) && entity.kind === "Namespace") {
const existingPath: string | undefined = state.get(entity);
if (existingPath !== details.path) {
reportDiagnostic(context.program, {
code: "duplicate-route-decorator",
messageId: "namespace",
target: entity,
});
}
} else {
state.set(entity, details.path);
if (entity.kind === "Operation" && details.shared) {
setSharedRoute(context.program, entity as Operation);
}
}
}
export function setSharedRoute(program: Program, operation: Operation) {
program.stateMap(HttpStateKeys.sharedRoutes).set(operation, true);
}
export function isSharedRoute(program: Program, operation: Operation): boolean {
return program.stateMap(HttpStateKeys.sharedRoutes).get(operation) === true;
}
export function getRoutePath(
program: Program,
entity: Namespace | Interface | Operation
): RoutePath | undefined {
const path = program.stateMap(HttpStateKeys.routes).get(entity);
return path
? {
path,
shared: entity.kind === "Operation" && isSharedRoute(program, entity as Operation),
}
: undefined;
}
export function setRouteOptionsForNamespace(
program: Program,
namespace: Namespace,
options: RouteOptions
) {
program.stateMap(HttpStateKeys.routeOptions).set(namespace, options);
}
export function getRouteOptionsForNamespace(
program: Program,
namespace: Namespace
): RouteOptions | undefined {
return program.stateMap(HttpStateKeys.routeOptions).get(namespace);
}