forked from denoland/fresh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.ts
More file actions
312 lines (264 loc) · 7.38 KB
/
router.ts
File metadata and controls
312 lines (264 loc) · 7.38 KB
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
export type Method =
| "HEAD"
| "GET"
| "POST"
| "PATCH"
| "PUT"
| "DELETE"
| "OPTIONS";
export type RouteByMethod<T> = {
[m in Method]: T[];
};
export interface StaticRouteDef<T> {
pattern: string | URLPattern;
byMethod: RouteByMethod<T>;
}
export interface DynamicRouteDef<T> {
pattern: URLPattern;
byMethod: RouteByMethod<T>;
}
function newByMethod<T>(): RouteByMethod<T> {
return {
GET: [],
POST: [],
PATCH: [],
DELETE: [],
PUT: [],
HEAD: [],
OPTIONS: [],
};
}
export interface RouteResult<T> {
params: Record<string, string>;
handlers: T[];
methodMatch: boolean;
pattern: string | null;
}
export interface Router<T> {
add(
method: Method | "ALL",
pathname: string,
handlers: T[],
): void;
match(method: Method, url: URL, init?: T[]): RouteResult<T>;
getAllowedMethods(pattern: string): string[];
}
export const IS_PATTERN = /[*:{}+?()]/;
const EMPTY: string[] = [];
export class UrlPatternRouter<T> implements Router<T> {
#statics = new Map<string, StaticRouteDef<T>>();
#dynamics = new Map<string, DynamicRouteDef<T>>();
#dynamicArr: DynamicRouteDef<T>[] = [];
#allowed = new Map<string, Set<string>>();
getAllowedMethods(pattern: string): string[] {
const allowed = this.#allowed.get(pattern);
if (allowed === undefined) return EMPTY;
return Array.from(allowed);
}
add(
method: Method,
pathname: string,
handlers: T[],
) {
let allowed = this.#allowed.get(pathname);
if (allowed === undefined) {
allowed = new Set();
this.#allowed.set(pathname, allowed);
}
allowed.add(method);
let byMethod: RouteByMethod<T>;
if (IS_PATTERN.test(pathname)) {
let def = this.#dynamics.get(pathname);
if (def === undefined) {
def = {
pattern: new URLPattern({ pathname }),
byMethod: newByMethod(),
};
this.#dynamics.set(pathname, def);
this.#dynamicArr.push(def);
}
byMethod = def.byMethod;
} else {
let def = this.#statics.get(pathname);
if (def === undefined) {
def = {
pattern: pathname,
byMethod: newByMethod(),
};
this.#statics.set(pathname, def);
}
byMethod = def.byMethod;
}
byMethod[method].push(...handlers);
}
match(method: Method, url: URL, init: T[] = []): RouteResult<T> {
const result: RouteResult<T> = {
params: Object.create(null),
handlers: init,
methodMatch: false,
pattern: null,
};
const staticMatch = this.#statics.get(url.pathname);
if (staticMatch !== undefined) {
result.pattern = url.pathname;
let handlers = staticMatch.byMethod[method];
if (method === "HEAD" && handlers.length === 0) {
handlers = staticMatch.byMethod.GET;
}
if (handlers.length > 0) {
result.methodMatch = true;
result.handlers.push(...handlers);
}
return result;
}
for (let i = 0; i < this.#dynamicArr.length; i++) {
const route = this.#dynamicArr[i];
const match = route.pattern.exec(url);
if (match === null) continue;
result.pattern = route.pattern.pathname;
let handlers = route.byMethod[method];
if (method === "HEAD" && handlers.length === 0) {
handlers = route.byMethod.GET;
}
if (handlers.length > 0) {
result.methodMatch = true;
result.handlers.push(...handlers);
// Decode matched params
for (const [key, value] of Object.entries(match.pathname.groups)) {
result.params[key] = value === undefined ? "" : decodeURI(value);
}
}
break;
}
return result;
}
}
/**
* Transform a filesystem URL path to a `path-to-regex` style matcher.
*/
export function pathToPattern(
path: string,
options?: { keepGroups: boolean },
): string {
const parts = path.split("/");
if (parts[parts.length - 1] === "index") {
if (parts.length === 1) {
return "/";
}
parts.pop();
}
let route = "";
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
// Case: /[...foo].tsx
if (part.startsWith("[...") && part.endsWith("]")) {
route += `/:${part.slice(4, part.length - 1)}*`;
continue;
}
// Route groups like /foo/(bar) should not be included in URL
// matching. They are transparent and need to be removed here.
// Case: /foo/(bar) -> /foo
// Case: /foo/(bar)/bob -> /foo/bob
// Case: /(foo)/bar -> /bar
if (!options?.keepGroups && part.startsWith("(") && part.endsWith(")")) {
continue;
}
// Disallow neighbouring params like `/[id][bar].tsx` because
// it's ambiguous where the `id` param ends and `bar` begins.
if (part.includes("][")) {
throw new SyntaxError(
`Invalid route pattern: "${path}". A parameter cannot be followed by another parameter without any characters in between.`,
);
}
// Case: /[[id]].tsx
// Case: /[id].tsx
// Case: /[id]@[bar].tsx
// Case: /[id]-asdf.tsx
// Case: /[id]-asdf[bar].tsx
// Case: /asdf[bar].tsx
let pattern = "";
let groupOpen = 0;
let optional = false;
for (let j = 0; j < part.length; j++) {
const char = part[j];
if (char === "[") {
if (part[j + 1] === "[") {
// Disallow optional dynamic params like `foo-[[bar]]`
if (part[j - 1] !== "/" && !!part[j - 1]) {
throw new SyntaxError(
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
);
}
groupOpen++;
optional = true;
pattern += "{/";
j++;
}
pattern += ":";
groupOpen++;
} else if (char === "]") {
if (part[j + 1] === "]") {
// Disallow optional dynamic params like `[[foo]]-bar`
if (part[j + 2] !== "/" && !!part[j + 2]) {
throw new SyntaxError(
`Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`,
);
}
groupOpen--;
pattern += "}?";
j++;
}
if (--groupOpen < 0) {
throw new SyntaxError(`Invalid route pattern: "${path}"`);
}
} else {
pattern += char;
}
}
route += (optional ? "" : "/") + pattern;
}
// Case: /(group)/index.tsx
if (route === "") {
route = "/";
}
return route;
}
export function patternToSegments(
path: string,
root: string,
includeLast: boolean = false,
): string[] {
const out: string[] = [root];
if (path === "/" || path === "*" || path === "/*") return out;
let start = -1;
for (let i = 0; i < path.length; i++) {
const ch = path[i];
if (ch === "/") {
if (i > 0) {
const raw = path.slice(start + 1, i);
out.push(raw);
}
start = i;
}
}
if (includeLast && start < path.length - 1) {
out.push(path.slice(start + 1));
}
return out;
}
export function mergePath(
basePath: string,
path: string,
isMounting: boolean,
): string {
if (basePath.endsWith("*")) basePath = basePath.slice(0, -1);
if (basePath === "/") basePath = "";
if (path === "*") path = isMounting ? "" : "/*";
else if (path === "/*") path = "/*";
const s = (basePath !== "" && path === "/") ? "" : path;
return basePath + s;
}
export function toRoutePath(path: string): string {
if (path === "") return "*";
return path;
}