-
Notifications
You must be signed in to change notification settings - Fork 658
/
pages-template-worker.ts
198 lines (176 loc) · 5.5 KB
/
pages-template-worker.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
import { match } from "path-to-regexp";
//note: this explicitly does not include the * character, as pages requires this
const escapeRegex = /[.+?^${}()|[\]\\]/g;
type HTTPMethod =
| "HEAD"
| "OPTIONS"
| "GET"
| "POST"
| "PUT"
| "PATCH"
| "DELETE";
/* TODO: Grab these from @cloudflare/workers-types instead */
type Params<P extends string = string> = Record<P, string | string[]>;
type EventContext<Env, P extends string, Data> = {
request: Request;
functionPath: string;
waitUntil: (promise: Promise<unknown>) => void;
passThroughOnException: () => void;
next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
env: Env & { ASSETS: { fetch: typeof fetch } };
params: Params<P>;
data: Data;
};
declare type PagesFunction<
Env = unknown,
P extends string = string,
Data extends Record<string, unknown> = Record<string, unknown>
> = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
/* end @cloudflare/workers-types */
type RouteHandler = {
routePath: string;
mountPath: string;
method?: HTTPMethod;
modules: PagesFunction[];
middlewares: PagesFunction[];
};
// inject `routes` via ESBuild
declare const routes: RouteHandler[];
// define `__FALLBACK_SERVICE__` via ESBuild
declare const __FALLBACK_SERVICE__: string;
// expect an ASSETS fetcher binding pointing to the asset-server stage
type FetchEnv = {
[name: string]: { fetch: typeof fetch };
ASSETS: { fetch: typeof fetch };
};
type WorkerContext = {
waitUntil: (promise: Promise<unknown>) => void;
passThroughOnException: () => void;
};
function* executeRequest(request: Request) {
const requestPath = new URL(request.url).pathname;
// First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
for (const route of [...routes].reverse()) {
if (route.method && route.method !== request.method) {
continue;
}
// replaces with "\\$&", this prepends a backslash to the matched string, e.g. "[" becomes "\["
const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
end: false,
});
const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
end: false,
});
const matchResult = routeMatcher(requestPath);
const mountMatchResult = mountMatcher(requestPath);
if (matchResult && mountMatchResult) {
for (const handler of route.middlewares.flat()) {
yield {
handler,
params: matchResult.params as Params,
path: mountMatchResult.path,
};
}
}
}
// Then look for the first exact route match and execute its "modules"
for (const route of routes) {
if (route.method && route.method !== request.method) {
continue;
}
const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
end: true,
});
const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
end: false,
});
const matchResult = routeMatcher(requestPath);
const mountMatchResult = mountMatcher(requestPath);
if (matchResult && mountMatchResult && route.modules.length) {
for (const handler of route.modules.flat()) {
yield {
handler,
params: matchResult.params as Params,
path: matchResult.path,
};
}
break;
}
}
}
export default {
async fetch(
originalRequest: Request,
env: FetchEnv,
workerContext: WorkerContext
) {
let request = originalRequest;
const handlerIterator = executeRequest(request);
let data = {}; // arbitrary data the user can set between functions
let isFailOpen = false;
const next = async (input?: RequestInfo, init?: RequestInit) => {
if (input !== undefined) {
let url = input;
if (typeof input === "string") {
url = new URL(input, request.url).toString();
}
request = new Request(url, init);
}
const result = handlerIterator.next();
// Note we can't use `!result.done` because this doesn't narrow to the correct type
if (result.done === false) {
const { handler, params, path } = result.value;
const context = {
request: new Request(request.clone()),
functionPath: path,
next,
params,
get data() {
return data;
},
set data(value) {
if (typeof value !== "object" || value === null) {
throw new Error("context.data must be an object");
}
// user has overriden context.data, so we need to merge it with the existing data
data = value;
},
env,
waitUntil: workerContext.waitUntil.bind(workerContext),
passThroughOnException: () => {
isFailOpen = true;
},
};
const response = await handler(context);
if (!(response instanceof Response)) {
throw new Error("Your Pages function should return a Response");
}
return cloneResponse(response);
} else if (__FALLBACK_SERVICE__) {
// There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
const response = await env[__FALLBACK_SERVICE__].fetch(request);
return cloneResponse(response);
} else {
// There was not fallback service so actually make the request to the origin.
const response = await fetch(request);
return cloneResponse(response);
}
};
try {
return await next();
} catch (error) {
if (isFailOpen) {
const response = await env[__FALLBACK_SERVICE__].fetch(request);
return cloneResponse(response);
}
throw error;
}
},
};
// This makes a Response mutable
const cloneResponse = (response: Response) =>
// https://fetch.spec.whatwg.org/#null-body-status
new Response(
[101, 204, 205, 304].includes(response.status) ? null : response.body,
response
);