-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathServer.js
536 lines (479 loc) Β· 14 KB
/
Server.js
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
// @flow
import type {DevServerOptions, Request, Response} from './types.js.flow';
import type {
BuildSuccessEvent,
BundleGraph,
FilePath,
PluginOptions,
PackagedBundle,
} from '@parcel/types';
import type {Diagnostic} from '@parcel/diagnostic';
import type {FileSystem} from '@parcel/fs';
import type {HTTPServer, FormattedCodeFrame} from '@parcel/utils';
import invariant from 'assert';
import path from 'path';
import url from 'url';
import {
ansiHtml,
createHTTPServer,
resolveConfig,
readConfig,
prettyDiagnostic,
relativePath,
} from '@parcel/utils';
import serverErrors from './serverErrors';
import fs from 'fs';
import ejs from 'ejs';
import connect from 'connect';
import serveHandler from 'serve-handler';
import {createProxyMiddleware} from 'http-proxy-middleware';
import {URL} from 'url';
import fresh from 'fresh';
export function setHeaders(res: Response) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Methods',
'GET, HEAD, PUT, PATCH, POST, DELETE',
);
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Content-Type',
);
res.setHeader('Cache-Control', 'max-age=0, must-revalidate');
}
const SLASH_REGEX = /\//g;
export const SOURCES_ENDPOINT = '/__parcel_source_root';
const TEMPLATE_404 = fs.readFileSync(
path.join(__dirname, 'templates/404.html'),
'utf8',
);
const TEMPLATE_500 = fs.readFileSync(
path.join(__dirname, 'templates/500.html'),
'utf8',
);
type NextFunction = (req: Request, res: Response, next?: (any) => any) => any;
export default class Server {
pending: boolean;
pendingRequests: Array<[Request, Response]>;
middleware: Array<(req: Request, res: Response) => boolean>;
options: DevServerOptions;
rootPath: string;
bundleGraph: BundleGraph<PackagedBundle> | null;
requestBundle: ?(bundle: PackagedBundle) => Promise<BuildSuccessEvent>;
errors: Array<{|
message: string,
stack: ?string,
frames: Array<FormattedCodeFrame>,
hints: Array<string>,
documentation: string,
|}> | null;
stopServer: ?() => Promise<void>;
constructor(options: DevServerOptions) {
this.options = options;
try {
this.rootPath = new URL(options.publicUrl).pathname;
} catch (e) {
this.rootPath = options.publicUrl;
}
this.pending = true;
this.pendingRequests = [];
this.middleware = [];
this.bundleGraph = null;
this.requestBundle = null;
this.errors = null;
}
buildStart() {
this.pending = true;
}
buildSuccess(
bundleGraph: BundleGraph<PackagedBundle>,
requestBundle: (bundle: PackagedBundle) => Promise<BuildSuccessEvent>,
) {
this.bundleGraph = bundleGraph;
this.requestBundle = requestBundle;
this.errors = null;
this.pending = false;
if (this.pendingRequests.length > 0) {
let pendingRequests = this.pendingRequests;
this.pendingRequests = [];
for (let [req, res] of pendingRequests) {
this.respond(req, res);
}
}
}
async buildError(options: PluginOptions, diagnostics: Array<Diagnostic>) {
this.pending = false;
this.errors = await Promise.all(
diagnostics.map(async d => {
let ansiDiagnostic = await prettyDiagnostic(d, options);
return {
message: ansiHtml(ansiDiagnostic.message),
stack: ansiDiagnostic.stack ? ansiHtml(ansiDiagnostic.stack) : null,
frames: ansiDiagnostic.frames.map(f => ({
location: f.location,
code: ansiHtml(f.code),
})),
hints: ansiDiagnostic.hints.map(hint => ansiHtml(hint)),
documentation: d.documentationURL ?? '',
};
}),
);
}
respond(req: Request, res: Response): mixed {
if (this.middleware.some(handler => handler(req, res))) return;
let {pathname} = url.parse(req.originalUrl || req.url);
if (pathname == null) {
pathname = '/';
}
if (this.errors) {
return this.send500(req, res);
} else if (path.extname(pathname) === '') {
// If the URL doesn't start with the public path, or the URL doesn't
// have a file extension, send the main HTML bundle.
return this.sendIndex(req, res);
} else if (pathname.startsWith(SOURCES_ENDPOINT)) {
req.url = pathname.slice(SOURCES_ENDPOINT.length);
return this.serve(
this.options.inputFS,
this.options.projectRoot,
req,
res,
() => this.send404(req, res),
);
} else if (pathname.startsWith(this.rootPath)) {
// Otherwise, serve the file from the dist folder
req.url =
this.rootPath === '/' ? pathname : pathname.slice(this.rootPath.length);
if (req.url[0] !== '/') {
req.url = '/' + req.url;
}
return this.serveBundle(req, res, () => this.sendIndex(req, res));
} else {
return this.send404(req, res);
}
}
sendIndex(req: Request, res: Response) {
if (this.bundleGraph) {
// If the main asset is an HTML file, serve it
let htmlBundleFilePaths = this.bundleGraph
.getBundles()
.filter(bundle => path.posix.extname(bundle.name) === '.html')
.map(bundle => {
return `/${relativePath(
this.options.distDir,
bundle.filePath,
false,
)}`;
});
let indexFilePath = null;
let {pathname: reqURL} = url.parse(req.originalUrl || req.url);
if (!reqURL) {
reqURL = '/';
}
if (htmlBundleFilePaths.length === 1) {
indexFilePath = htmlBundleFilePaths[0];
} else {
let bestMatch = null;
for (let bundle of htmlBundleFilePaths) {
let bundleDir = path.posix.dirname(bundle);
let bundleDirSubdir = bundleDir === '/' ? bundleDir : bundleDir + '/';
let withoutExtension = path.posix.basename(
bundle,
path.posix.extname(bundle),
);
let isIndex = withoutExtension === 'index';
let matchesIsIndex = null;
if (
isIndex &&
(reqURL.startsWith(bundleDirSubdir) || reqURL === bundleDir)
) {
// bundle is /bar/index.html and (/bar or something inside of /bar/** was requested was requested)
matchesIsIndex = true;
} else if (reqURL == path.posix.join(bundleDir, withoutExtension)) {
// bundle is /bar/foo.html and /bar/foo was requested
matchesIsIndex = false;
}
if (matchesIsIndex != null) {
let depth = bundle.match(SLASH_REGEX)?.length ?? 0;
if (
bestMatch == null ||
// This one is more specific (deeper)
bestMatch.depth < depth ||
// This one is just as deep, but the bundle name matches and not just index.html
(bestMatch.depth === depth && bestMatch.isIndex)
) {
bestMatch = {bundle, depth, isIndex: matchesIsIndex};
}
}
}
indexFilePath = bestMatch?.['bundle'] ?? htmlBundleFilePaths[0];
}
if (indexFilePath) {
req.url = indexFilePath;
this.serveBundle(req, res, () => this.send404(req, res));
} else {
this.send404(req, res);
}
} else {
this.send404(req, res);
}
}
async serveBundle(
req: Request,
res: Response,
next: NextFunction,
): Promise<void> {
let bundleGraph = this.bundleGraph;
if (bundleGraph) {
let {pathname} = url.parse(req.url);
if (!pathname) {
this.send500(req, res);
return;
}
let requestedPath = path.normalize(pathname.slice(1));
let bundle = bundleGraph
.getBundles()
.find(
b =>
path.relative(this.options.distDir, b.filePath) === requestedPath,
);
if (!bundle) {
this.serveDist(req, res, next);
return;
}
invariant(this.requestBundle != null);
try {
await this.requestBundle(bundle);
} catch (err) {
this.send500(req, res);
return;
}
this.serveDist(req, res, next);
} else {
this.send404(req, res);
}
}
serveDist(
req: Request,
res: Response,
next: NextFunction,
): Promise<void> | Promise<mixed> {
return this.serve(
this.options.outputFS,
this.options.distDir,
req,
res,
next,
);
}
async serve(
fs: FileSystem,
root: FilePath,
req: Request,
res: Response,
next: NextFunction,
): Promise<mixed> {
if (req.method !== 'GET' && req.method !== 'HEAD') {
// method not allowed
res.statusCode = 405;
res.setHeader('Allow', 'GET, HEAD');
res.setHeader('Content-Length', '0');
res.end();
return;
}
try {
var filePath = url.parse(req.url).pathname || '';
filePath = decodeURIComponent(filePath);
} catch (err) {
return this.sendError(res, 400);
}
filePath = path.normalize('.' + path.sep + filePath);
// malicious path
if (filePath.includes(path.sep + '..' + path.sep)) {
return this.sendError(res, 403);
}
// join / normalize from the root dir
if (!path.isAbsolute(filePath)) {
filePath = path.normalize(path.join(root, filePath));
}
try {
var stat = await fs.stat(filePath);
} catch (err) {
if (err.code === 'ENOENT') {
return next(req, res);
}
return this.sendError(res, 500);
}
// Fall back to next handler if not a file
if (!stat || !stat.isFile()) {
return next(req, res);
}
if (fresh(req.headers, {'last-modified': stat.mtime.toUTCString()})) {
res.statusCode = 304;
res.end();
return;
}
return serveHandler(
req,
res,
{
public: root,
cleanUrls: false,
},
{
lstat: path => fs.stat(path),
realpath: path => fs.realpath(path),
createReadStream: (path, options) => fs.createReadStream(path, options),
readdir: path => fs.readdir(path),
},
);
}
sendError(res: Response, statusCode: number) {
res.statusCode = statusCode;
res.end();
}
send404(req: Request, res: Response) {
res.statusCode = 404;
res.end(TEMPLATE_404);
}
send500(req: Request, res: Response): void | Response {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.writeHead(500);
if (this.errors) {
return res.end(
ejs.render(TEMPLATE_500, {
errors: this.errors,
hmrOptions: this.options.hmrOptions,
}),
);
}
}
logAccessIfVerbose(req: Request) {
this.options.logger.verbose({
message: `Request: ${req.headers.host}${req.originalUrl || req.url}`,
});
}
/**
* Load proxy table from package.json and apply them.
*/
async applyProxyTable(app: any): Promise<Server> {
// avoid skipping project root
const fileInRoot: string = path.join(this.options.projectRoot, 'index');
const configFilePath = await resolveConfig(
this.options.inputFS,
fileInRoot,
[
'.proxyrc.cts',
'.proxyrc.mts',
'.proxyrc.ts',
'.proxyrc.cjs',
'.proxyrc.mjs',
'.proxyrc.js',
'.proxyrc',
'.proxyrc.json',
],
this.options.projectRoot,
);
if (!configFilePath) {
return this;
}
const filename = path.basename(configFilePath);
if (filename === '.proxyrc' || filename === '.proxyrc.json') {
let conf = await readConfig(this.options.inputFS, configFilePath);
if (!conf) {
return this;
}
let cfg = conf.config;
if (typeof cfg !== 'object') {
this.options.logger.warn({
message:
"Proxy table in '.proxyrc' should be of object type. Skipping...",
});
return this;
}
for (const [context, options] of Object.entries(cfg)) {
// each key is interpreted as context, and value as middleware options
app.use(createProxyMiddleware(context, options));
}
} else {
let cfg = await this.options.packageManager.require(
configFilePath,
fileInRoot,
);
if (
// $FlowFixMe
Object.prototype.toString.call(cfg) === '[object Module]'
) {
cfg = cfg.default;
}
if (typeof cfg !== 'function') {
this.options.logger.warn({
message: `Proxy configuration file '${filename}' should export a function. Skipping...`,
});
return this;
}
cfg(app);
}
return this;
}
async start(): Promise<HTTPServer> {
const finalHandler = (req: Request, res: Response) => {
this.logAccessIfVerbose(req);
// Wait for the parcelInstance to finish bundling if needed
if (this.pending) {
this.pendingRequests.push([req, res]);
} else {
this.respond(req, res);
}
};
const app = connect();
app.use((req, res, next) => {
setHeaders(res);
if (req.method === 'OPTIONS') {
res.statusCode = 200;
res.end();
return;
}
next();
});
app.use((req, res, next) => {
if (req.url === '/__parcel_healthcheck') {
res.statusCode = 200;
res.write(`${Date.now()}`);
res.end();
} else {
next();
}
});
await this.applyProxyTable(app);
app.use(finalHandler);
let {server, stop} = await createHTTPServer({
cacheDir: this.options.cacheDir,
https: this.options.https,
inputFS: this.options.inputFS,
listener: app,
outputFS: this.options.outputFS,
host: this.options.host,
});
this.stopServer = stop;
server.listen(this.options.port, this.options.host);
return new Promise((resolve, reject) => {
server.once('error', err => {
this.options.logger.error(
({
message: serverErrors(err, this.options.port),
}: Diagnostic),
);
reject(err);
});
server.once('listening', () => {
resolve(server);
});
});
}
async stop(): Promise<void> {
invariant(this.stopServer != null);
await this.stopServer();
this.stopServer = null;
}
}