-
Notifications
You must be signed in to change notification settings - Fork 151
/
proxy.ts
293 lines (255 loc) · 8.38 KB
/
proxy.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
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
import { URL, URLSearchParams } from 'url';
import { Route, isHandler, HandleValue } from '@vercel/routing-utils';
import isURL from './util/is-url';
import { resolveRouteParameters } from './util/resolve-route-parameters';
import { RouteResult, HTTPHeaders } from './types';
// Since we have no replacement for url.parse, thanks Node.js
// https://github.com/nodejs/node/issues/12682
const baseUrl = 'http://n';
function parseUrl(url: string) {
const _url = new URL(url, baseUrl);
return {
pathname: _url.pathname,
searchParams: _url.searchParams,
};
}
/**
* Appends URLSearchParams from param 2 to param 1.
* Basically Object.assign for URLSearchParams
* @param param1
* @param param2
*/
function appendURLSearchParams(
param1: URLSearchParams,
param2: URLSearchParams
) {
for (const [key, value] of param2.entries()) {
param1.append(key, value);
}
return param1;
}
export class Proxy {
routes: Route[];
lambdaRoutes: Set<string>;
staticRoutes: Set<string>;
constructor(routes: Route[], lambdaRoutes: string[], staticRoutes: string[]) {
this.routes = routes;
this.lambdaRoutes = new Set<string>(lambdaRoutes);
this.staticRoutes = new Set<string>(staticRoutes);
}
/**
* Checks if the requested path matches a static file from the filesystem
*
* @param requestedFilePath - Path to the potential file. Could include a
* querystring.
* @returns Absolute path to the file that is matched, otherwise null
*/
private _checkFileSystem(
requestedFilePathWithPossibleQuerystring: string
): string | null {
// Make sure the querystring is removed from the requested file before
// doing the lookup
const querystringStartPos = requestedFilePathWithPossibleQuerystring.indexOf(
'?'
);
const requestedFilePath =
querystringStartPos === -1
? requestedFilePathWithPossibleQuerystring
: requestedFilePathWithPossibleQuerystring.substring(
0,
querystringStartPos
);
// 1: Check if the original filePath is present
if (this.staticRoutes.has(requestedFilePath)) {
return requestedFilePath;
}
// 2: The last character in the requested filePath is a `/`
if (requestedFilePath.charAt(requestedFilePath.length - 1) === '/') {
// 2.1: Remove trailing `/`
const requestedFilePathWithoutTrailingSlash = requestedFilePath.slice(
0,
-1
);
if (this.staticRoutes.has(requestedFilePathWithoutTrailingSlash)) {
return requestedFilePathWithoutTrailingSlash;
}
// 2.2: Replace trailing `/` with `/index`
const requestedFilePathWithIndexExtension = `${requestedFilePath}index`;
if (this.staticRoutes.has(requestedFilePathWithIndexExtension)) {
return requestedFilePathWithIndexExtension;
}
}
// requestedFilePath does not match a static route
return null;
}
route(reqUrl: string) {
const parsedUrl = parseUrl(reqUrl);
let { searchParams, pathname: reqPathname = '/' } = parsedUrl;
let result: RouteResult | undefined;
let status: number | undefined;
let isContinue = false;
let phase: HandleValue | undefined;
let combinedHeaders: HTTPHeaders = {};
let target: undefined | 'filesystem' | 'lambda';
/**
* Set the route result target as filesystem
*/
function setTargetFilesystem(dest: string) {
result = {
found: true,
target: 'filesystem',
dest,
headers: combinedHeaders,
continue: false,
isDestUrl: false,
status,
phase,
};
}
for (let routeIndex = 0; routeIndex < this.routes.length; routeIndex++) {
/**
* This is how the routing basically works:
* (For reference see: https://vercel.com/docs/configuration#routes)
*
* 1. Checks if the route is an exact match to a route in the
* S3 filesystem (e.g. /test.html -> s3://test.html)
* --> true: returns found in filesystem
* 2.
*
*/
const routeConfig = this.routes[routeIndex];
//////////////////////////////////////////////////////////////////////////
// Phase 1: Check for handler
if (isHandler(routeConfig)) {
phase = routeConfig.handle;
// Check if the path is a static file that should be served from the
// filesystem
if (routeConfig.handle === 'filesystem') {
const filePath = this._checkFileSystem(reqPathname);
// Check if the route matches a route from the filesystem
if (filePath !== null) {
setTargetFilesystem(filePath);
break;
}
}
continue;
}
// Skip resource phase entirely because we don't support it
if (phase === 'resource') {
continue;
}
// Special case to allow redirect to kick in when a continue route was touched before
if (phase === 'error' && isContinue) {
break;
}
//////////////////////////////////////////////////////////////////////////
// Phase 2: Check for source
const { src, headers } = routeConfig;
// Note: Routes are case-insensitive
// TODO: Performance: Cache matcher results
const matcher = new RegExp(src, 'i');
const match = matcher.exec(reqPathname);
if (match !== null) {
const keys = Object.keys(match.groups ?? {});
isContinue = false;
// The path that should be sent to the target system (lambda or filesystem)
let destPath: string = reqPathname;
if (routeConfig.status) {
status = routeConfig.status;
}
if (routeConfig.dest) {
// Rewrite dynamic routes
// e.g. /posts/1234 -> /posts/[id]?id=1234
destPath = resolveRouteParameters(routeConfig.dest, match, keys);
}
if (headers) {
for (const originalKey in headers) {
const originalValue = headers[originalKey];
const value = resolveRouteParameters(originalValue, match, keys);
combinedHeaders[originalKey] = value;
}
}
if (routeConfig.continue) {
reqPathname = destPath;
isContinue = true;
}
// Check for external rewrite
const isDestUrl = isURL(destPath);
if (isDestUrl) {
result = {
found: true,
dest: destPath,
continue: isContinue,
userDest: false,
isDestUrl,
status: status,
uri_args: searchParams,
matched_route: routeConfig,
matched_route_idx: routeIndex,
phase,
headers: combinedHeaders,
target: 'url',
};
if (isContinue) {
continue;
}
break;
}
if (routeConfig.check && phase !== 'hit') {
if (this.lambdaRoutes.has(destPath)) {
target = 'lambda';
} else {
// Check if the path matches a route from the filesystem
const filePath = this._checkFileSystem(destPath);
if (filePath !== null) {
setTargetFilesystem(filePath);
break;
}
// When it is not a lambda route we cut the url_args
// for the next iteration
const nextUrl = parseUrl(destPath);
reqPathname = nextUrl.pathname!;
appendURLSearchParams(searchParams, nextUrl.searchParams);
continue;
}
}
if (destPath.charAt(0) !== '/') {
destPath = `/${destPath}`;
}
const destParsed = parseUrl(destPath);
appendURLSearchParams(searchParams, destParsed.searchParams);
result = {
found: true,
dest: destParsed.pathname || '/',
continue: isContinue,
userDest: Boolean(routeConfig.dest),
isDestUrl,
status: status,
uri_args: searchParams,
matched_route: routeConfig,
matched_route_idx: routeIndex,
phase,
headers: combinedHeaders,
target,
};
if (isContinue) {
continue;
}
break;
}
}
if (!result) {
result = {
found: false,
dest: reqPathname,
continue: isContinue,
status,
isDestUrl: false,
uri_args: searchParams,
phase,
headers: combinedHeaders,
};
}
return result;
}
}