-
-
Notifications
You must be signed in to change notification settings - Fork 899
Expand file tree
/
Copy pathrouting.ts
More file actions
201 lines (176 loc) · 5.29 KB
/
Copy pathrouting.ts
File metadata and controls
201 lines (176 loc) · 5.29 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
import type { Nitro, NitroEventHandler, NitroRouteRules } from "nitro/types";
import type { RouterContext } from "rou3";
import type { RouterCompilerOptions } from "rou3/compiler";
import { join } from "pathe";
import { runtimeDir } from "nitro/runtime/meta";
import { addRoute, createRouter, findRoute, findAllRoutes } from "rou3";
import { compileRouterToString } from "rou3/compiler";
import { hash } from "ohash";
const isGlobalMiddleware = (h: NitroEventHandler) =>
!h.method && (!h.route || h.route === "/**");
export function initNitroRouting(nitro: Nitro) {
const envConditions = new Set(
[
nitro.options.dev ? "dev" : "prod",
nitro.options.preset,
nitro.options.preset === "nitro-prerender" ? "prerender" : undefined,
].filter(Boolean) as string[]
);
const matchesEnv = (h: NitroEventHandler) => {
const hEnv = Array.isArray(h.env) ? h.env : [h.env];
const envs = hEnv.filter(Boolean) as string[];
return envs.length === 0 || envs.some((env) => envConditions.has(env));
};
type MaybeArray<T> = T | T[];
const routes = new Router<
MaybeArray<NitroEventHandler & { _importHash: string }>
>();
const routeRules = new Router<NitroRouteRules & { _route: string }>();
const globalMiddleware: (NitroEventHandler & { _importHash: string })[] = [];
const routedMiddleware = new Router<
NitroEventHandler & { _importHash: string }
>();
const sync = () => {
// Update route rules
routeRules._update(
Object.entries(nitro.options.routeRules).map(([route, data]) => ({
route,
method: "",
data: {
...data,
_route: route,
},
}))
);
// Update routes
const _routes = [
...Object.entries(nitro.options.routes).flatMap(([route, handler]) => {
return { ...handler, route, middleware: false };
}),
...nitro.options.handlers,
...nitro.scannedHandlers,
].filter((h) => h && !h.middleware && matchesEnv(h));
if (nitro.options.renderer?.entry) {
_routes.push({
route: "/**",
lazy: true,
handler: nitro.options.renderer?.entry,
});
}
routes._update(
_routes.map((h) => ({
...h,
method: h.method || "",
data: handlerWithImportHash(h),
})),
{ merge: true }
);
// Update middleware
const _middleware = [
...nitro.scannedHandlers,
...nitro.options.handlers,
].filter((h) => h && h.middleware && matchesEnv(h));
if (nitro.options.serveStatic) {
_middleware.unshift({
route: "/**",
middleware: true,
handler: join(runtimeDir, "internal/static"),
});
}
globalMiddleware.splice(
0,
globalMiddleware.length,
..._middleware
.filter((h) => isGlobalMiddleware(h))
.map((m) => handlerWithImportHash(m))
);
routedMiddleware._update(
_middleware
.filter((h) => !isGlobalMiddleware(h))
.map((h) => ({
...h,
method: h.method || "",
data: handlerWithImportHash(h),
}))
);
};
nitro.routing = Object.freeze({
sync,
routes,
routeRules,
globalMiddleware,
routedMiddleware,
});
}
function handlerWithImportHash(h: NitroEventHandler) {
const id =
(h.lazy ? "_lazy_" : "_") + hash(h.handler).replace(/-/g, "").slice(0, 6);
return { ...h, _importHash: id };
}
// --- Router ---
export interface Route<T = unknown> {
route: string;
method: string;
data: T;
}
export class Router<T> {
#routes?: Route<T>[];
#router?: RouterContext<T>;
#compiled?: string;
constructor() {
this._update([]);
}
get routes() {
return this.#routes!;
}
_update(routes: Route<T>[], opts?: { merge?: boolean }) {
this.#routes = routes;
this.#router = createRouter<T>();
this.#compiled = undefined;
for (const route of routes) {
addRoute(this.#router, route.method, route.route, route.data);
}
if (opts?.merge) {
mergeCatchAll(this.#router);
}
}
hasRoutes() {
return this.#routes!.length > 0;
}
compileToString(opts?: RouterCompilerOptions<T>) {
if (this.#compiled) {
return this.#compiled;
}
this.#compiled = compileRouterToString(this.#router!, undefined, opts);
// TODO: Upstream to rou3 compiler
const onlyWildcard =
this.routes.length === 1 &&
this.routes[0].route === "/**" &&
this.routes[0].method === "";
if (onlyWildcard) {
// Optimize for single wildcard route
const data = (opts?.serialize || JSON.stringify)(this.routes[0].data);
this.#compiled = /* js */ `/* @__PURE__ */ (() => {const data=${data};return ((_m, p)=>{return {data,params:{"_":p.slice(1)}};})})()`;
}
return this.#compiled;
}
match(method: string, path: string): undefined | T {
return findRoute(this.#router!, method, path)?.data;
}
matchAll(method: string, path: string): T[] {
// Returns from less specific to more specific matches
return findAllRoutes(this.#router!, method, path).map(
(route) => route.data
);
}
}
function mergeCatchAll(router: RouterContext<unknown>) {
const handlers = router.root?.wildcard?.methods?.[""];
if (!handlers || handlers.length < 2) {
return;
}
handlers.splice(0, handlers.length, {
...handlers[0],
data: handlers.map((h) => h.data),
});
}