1
|
'use strict';
|
2
|
|
3
|
/* eslint-disable
|
4
|
no-shadow,
|
5
|
no-undefined,
|
6
|
func-names
|
7
|
*/
|
8
|
const fs = require('fs');
|
9
|
const path = require('path');
|
10
|
const tls = require('tls');
|
11
|
const url = require('url');
|
12
|
const http = require('http');
|
13
|
const https = require('https');
|
14
|
const ip = require('ip');
|
15
|
const semver = require('semver');
|
16
|
const killable = require('killable');
|
17
|
const chokidar = require('chokidar');
|
18
|
const express = require('express');
|
19
|
const httpProxyMiddleware = require('http-proxy-middleware');
|
20
|
const historyApiFallback = require('connect-history-api-fallback');
|
21
|
const compress = require('compression');
|
22
|
const serveIndex = require('serve-index');
|
23
|
const webpack = require('webpack');
|
24
|
const webpackDevMiddleware = require('webpack-dev-middleware');
|
25
|
const validateOptions = require('schema-utils');
|
26
|
const isAbsoluteUrl = require('is-absolute-url');
|
27
|
const normalizeOptions = require('./utils/normalizeOptions');
|
28
|
const updateCompiler = require('./utils/updateCompiler');
|
29
|
const createLogger = require('./utils/createLogger');
|
30
|
const getCertificate = require('./utils/getCertificate');
|
31
|
const status = require('./utils/status');
|
32
|
const createDomain = require('./utils/createDomain');
|
33
|
const runBonjour = require('./utils/runBonjour');
|
34
|
const routes = require('./utils/routes');
|
35
|
const getSocketServerImplementation = require('./utils/getSocketServerImplementation');
|
36
|
const schema = require('./options.json');
|
37
|
|
38
|
// Workaround for node ^8.6.0, ^9.0.0
|
39
|
// DEFAULT_ECDH_CURVE is default to prime256v1 in these version
|
40
|
// breaking connection when certificate is not signed with prime256v1
|
41
|
// change it to auto allows OpenSSL to select the curve automatically
|
42
|
// See https://github.com/nodejs/node/issues/16196 for more information
|
43
|
if (semver.satisfies(process.version, '8.6.0 - 9')) {
|
44
|
tls.DEFAULT_ECDH_CURVE = 'auto';
|
45
|
}
|
46
|
|
47
|
if (!process.env.WEBPACK_DEV_SERVER) {
|
48
|
process.env.WEBPACK_DEV_SERVER = true;
|
49
|
}
|
50
|
|
51
|
class Server {
|
52
|
constructor(compiler, options = {}, _log) {
|
53
|
if (options.lazy && !options.filename) {
|
54
|
throw new Error("'filename' option must be set in lazy mode.");
|
55
|
}
|
56
|
|
57
|
validateOptions(schema, options, 'webpack Dev Server');
|
58
|
|
59
|
this.compiler = compiler;
|
60
|
this.options = options;
|
61
|
|
62
|
this.log = _log || createLogger(options);
|
63
|
|
64
|
if (this.options.transportMode !== undefined) {
|
65
|
this.log.warn(
|
66
|
'transportMode is an experimental option, meaning its usage could potentially change without warning'
|
67
|
);
|
68
|
}
|
69
|
|
70
|
normalizeOptions(this.compiler, this.options);
|
71
|
|
72
|
updateCompiler(this.compiler, this.options);
|
73
|
|
74
|
this.heartbeatInterval = 30000;
|
75
|
// this.SocketServerImplementation is a class, so it must be instantiated before use
|
76
|
this.socketServerImplementation = getSocketServerImplementation(
|
77
|
this.options
|
78
|
);
|
79
|
|
80
|
this.originalStats =
|
81
|
this.options.stats && Object.keys(this.options.stats).length
|
82
|
? this.options.stats
|
83
|
: {};
|
84
|
|
85
|
this.sockets = [];
|
86
|
this.contentBaseWatchers = [];
|
87
|
|
88
|
// TODO this.<property> is deprecated (remove them in next major release.) in favor this.options.<property>
|
89
|
this.hot = this.options.hot || this.options.hotOnly;
|
90
|
this.headers = this.options.headers;
|
91
|
this.progress = this.options.progress;
|
92
|
|
93
|
this.serveIndex = this.options.serveIndex;
|
94
|
|
95
|
this.clientOverlay = this.options.overlay;
|
96
|
this.clientLogLevel = this.options.clientLogLevel;
|
97
|
|
98
|
this.publicHost = this.options.public;
|
99
|
this.allowedHosts = this.options.allowedHosts;
|
100
|
this.disableHostCheck = !!this.options.disableHostCheck;
|
101
|
|
102
|
this.watchOptions = options.watchOptions || {};
|
103
|
|
104
|
// Replace leading and trailing slashes to normalize path
|
105
|
this.sockPath = `/${
|
106
|
this.options.sockPath
|
107
|
? this.options.sockPath.replace(/^\/|\/$/g, '')
|
108
|
: 'sockjs-node'
|
109
|
}`;
|
110
|
|
111
|
if (this.progress) {
|
112
|
this.setupProgressPlugin();
|
113
|
}
|
114
|
|
115
|
this.setupHooks();
|
116
|
this.setupApp();
|
117
|
this.setupCheckHostRoute();
|
118
|
this.setupDevMiddleware();
|
119
|
|
120
|
// set express routes
|
121
|
routes(this.app, this.middleware, this.options);
|
122
|
|
123
|
// Keep track of websocket proxies for external websocket upgrade.
|
124
|
this.websocketProxies = [];
|
125
|
|
126
|
this.setupFeatures();
|
127
|
this.setupHttps();
|
128
|
this.createServer();
|
129
|
|
130
|
killable(this.listeningApp);
|
131
|
|
132
|
// Proxy websockets without the initial http request
|
133
|
// https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade
|
134
|
this.websocketProxies.forEach(function(wsProxy) {
|
135
|
this.listeningApp.on('upgrade', wsProxy.upgrade);
|
136
|
}, this);
|
137
|
}
|
138
|
|
139
|
setupProgressPlugin() {
|
140
|
// for CLI output
|
141
|
new webpack.ProgressPlugin({
|
142
|
profile: !!this.options.profile,
|
143
|
}).apply(this.compiler);
|
144
|
|
145
|
// for browser console output
|
146
|
new webpack.ProgressPlugin((percent, msg, addInfo) => {
|
147
|
percent = Math.floor(percent * 100);
|
148
|
|
149
|
if (percent === 100) {
|
150
|
msg = 'Compilation completed';
|
151
|
}
|
152
|
|
153
|
if (addInfo) {
|
154
|
msg = `${msg} (${addInfo})`;
|
155
|
}
|
156
|
|
157
|
this.sockWrite(this.sockets, 'progress-update', { percent, msg });
|
158
|
}).apply(this.compiler);
|
159
|
}
|
160
|
|
161
|
setupApp() {
|
162
|
// Init express server
|
163
|
// eslint-disable-next-line new-cap
|
164
|
this.app = new express();
|
165
|
}
|
166
|
|
167
|
setupHooks() {
|
168
|
// Listening for events
|
169
|
const invalidPlugin = () => {
|
170
|
this.sockWrite(this.sockets, 'invalid');
|
171
|
};
|
172
|
|
173
|
const addHooks = (compiler) => {
|
174
|
const { compile, invalid, done } = compiler.hooks;
|
175
|
|
176
|
compile.tap('webpack-dev-server', invalidPlugin);
|
177
|
invalid.tap('webpack-dev-server', invalidPlugin);
|
178
|
done.tap('webpack-dev-server', (stats) => {
|
179
|
this._sendStats(this.sockets, this.getStats(stats));
|
180
|
this._stats = stats;
|
181
|
});
|
182
|
};
|
183
|
|
184
|
if (this.compiler.compilers) {
|
185
|
this.compiler.compilers.forEach(addHooks);
|
186
|
} else {
|
187
|
addHooks(this.compiler);
|
188
|
}
|
189
|
}
|
190
|
|
191
|
setupCheckHostRoute() {
|
192
|
this.app.all('*', (req, res, next) => {
|
193
|
if (this.checkHost(req.headers)) {
|
194
|
return next();
|
195
|
}
|
196
|
|
197
|
res.send('Invalid Host header');
|
198
|
});
|
199
|
}
|
200
|
|
201
|
setupDevMiddleware() {
|
202
|
// middleware for serving webpack bundle
|
203
|
this.middleware = webpackDevMiddleware(
|
204
|
this.compiler,
|
205
|
Object.assign({}, this.options, { logLevel: this.log.options.level })
|
206
|
);
|
207
|
}
|
208
|
|
209
|
setupCompressFeature() {
|
210
|
this.app.use(compress());
|
211
|
}
|
212
|
|
213
|
setupProxyFeature() {
|
214
|
/**
|
215
|
* Assume a proxy configuration specified as:
|
216
|
* proxy: {
|
217
|
* 'context': { options }
|
218
|
* }
|
219
|
* OR
|
220
|
* proxy: {
|
221
|
* 'context': 'target'
|
222
|
* }
|
223
|
*/
|
224
|
if (!Array.isArray(this.options.proxy)) {
|
225
|
if (Object.prototype.hasOwnProperty.call(this.options.proxy, 'target')) {
|
226
|
this.options.proxy = [this.options.proxy];
|
227
|
} else {
|
228
|
this.options.proxy = Object.keys(this.options.proxy).map((context) => {
|
229
|
let proxyOptions;
|
230
|
// For backwards compatibility reasons.
|
231
|
const correctedContext = context
|
232
|
.replace(/^\*$/, '**')
|
233
|
.replace(/\/\*$/, '');
|
234
|
|
235
|
if (typeof this.options.proxy[context] === 'string') {
|
236
|
proxyOptions = {
|
237
|
context: correctedContext,
|
238
|
target: this.options.proxy[context],
|
239
|
};
|
240
|
} else {
|
241
|
proxyOptions = Object.assign({}, this.options.proxy[context]);
|
242
|
proxyOptions.context = correctedContext;
|
243
|
}
|
244
|
|
245
|
proxyOptions.logLevel = proxyOptions.logLevel || 'warn';
|
246
|
|
247
|
return proxyOptions;
|
248
|
});
|
249
|
}
|
250
|
}
|
251
|
|
252
|
const getProxyMiddleware = (proxyConfig) => {
|
253
|
const context = proxyConfig.context || proxyConfig.path;
|
254
|
|
255
|
// It is possible to use the `bypass` method without a `target`.
|
256
|
// However, the proxy middleware has no use in this case, and will fail to instantiate.
|
257
|
if (proxyConfig.target) {
|
258
|
return httpProxyMiddleware(context, proxyConfig);
|
259
|
}
|
260
|
};
|
261
|
/**
|
262
|
* Assume a proxy configuration specified as:
|
263
|
* proxy: [
|
264
|
* {
|
265
|
* context: ...,
|
266
|
* ...options...
|
267
|
* },
|
268
|
* // or:
|
269
|
* function() {
|
270
|
* return {
|
271
|
* context: ...,
|
272
|
* ...options...
|
273
|
* };
|
274
|
* }
|
275
|
* ]
|
276
|
*/
|
277
|
this.options.proxy.forEach((proxyConfigOrCallback) => {
|
278
|
let proxyMiddleware;
|
279
|
|
280
|
let proxyConfig =
|
281
|
typeof proxyConfigOrCallback === 'function'
|
282
|
? proxyConfigOrCallback()
|
283
|
: proxyConfigOrCallback;
|
284
|
|
285
|
proxyMiddleware = getProxyMiddleware(proxyConfig);
|
286
|
|
287
|
if (proxyConfig.ws) {
|
288
|
this.websocketProxies.push(proxyMiddleware);
|
289
|
}
|
290
|
|
291
|
const handle = (req, res, next) => {
|
292
|
if (typeof proxyConfigOrCallback === 'function') {
|
293
|
const newProxyConfig = proxyConfigOrCallback();
|
294
|
|
295
|
if (newProxyConfig !== proxyConfig) {
|
296
|
proxyConfig = newProxyConfig;
|
297
|
proxyMiddleware = getProxyMiddleware(proxyConfig);
|
298
|
}
|
299
|
}
|
300
|
|
301
|
// - Check if we have a bypass function defined
|
302
|
// - In case the bypass function is defined we'll retrieve the
|
303
|
// bypassUrl from it otherwise bypassUrl would be null
|
304
|
const isByPassFuncDefined = typeof proxyConfig.bypass === 'function';
|
305
|
const bypassUrl = isByPassFuncDefined
|
306
|
? proxyConfig.bypass(req, res, proxyConfig)
|
307
|
: null;
|
308
|
|
309
|
if (typeof bypassUrl === 'boolean') {
|
310
|
// skip the proxy
|
311
|
req.url = null;
|
312
|
next();
|
313
|
} else if (typeof bypassUrl === 'string') {
|
314
|
// byPass to that url
|
315
|
req.url = bypassUrl;
|
316
|
next();
|
317
|
} else if (proxyMiddleware) {
|
318
|
return proxyMiddleware(req, res, next);
|
319
|
} else {
|
320
|
next();
|
321
|
}
|
322
|
};
|
323
|
|
324
|
this.app.use(handle);
|
325
|
// Also forward error requests to the proxy so it can handle them.
|
326
|
this.app.use((error, req, res, next) => handle(req, res, next));
|
327
|
});
|
328
|
}
|
329
|
|
330
|
setupHistoryApiFallbackFeature() {
|
331
|
const fallback =
|
332
|
typeof this.options.historyApiFallback === 'object'
|
333
|
? this.options.historyApiFallback
|
334
|
: null;
|
335
|
|
336
|
// Fall back to /index.html if nothing else matches.
|
337
|
this.app.use(historyApiFallback(fallback));
|
338
|
}
|
339
|
|
340
|
setupStaticFeature() {
|
341
|
const contentBase = this.options.contentBase;
|
342
|
const contentBasePublicPath = this.options.contentBasePublicPath;
|
343
|
|
344
|
if (Array.isArray(contentBase)) {
|
345
|
contentBase.forEach((item) => {
|
346
|
this.app.use(contentBasePublicPath, express.static(item));
|
347
|
});
|
348
|
} else if (isAbsoluteUrl(String(contentBase))) {
|
349
|
this.log.warn(
|
350
|
'Using a URL as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.'
|
351
|
);
|
352
|
|
353
|
this.log.warn(
|
354
|
'proxy: {\n\t"*": "<your current contentBase configuration>"\n}'
|
355
|
);
|
356
|
|
357
|
// Redirect every request to contentBase
|
358
|
this.app.get('*', (req, res) => {
|
359
|
res.writeHead(302, {
|
360
|
Location: contentBase + req.path + (req._parsedUrl.search || ''),
|
361
|
});
|
362
|
|
363
|
res.end();
|
364
|
});
|
365
|
} else if (typeof contentBase === 'number') {
|
366
|
this.log.warn(
|
367
|
'Using a number as contentBase is deprecated and will be removed in the next major version. Please use the proxy option instead.'
|
368
|
);
|
369
|
|
370
|
this.log.warn(
|
371
|
'proxy: {\n\t"*": "//localhost:<your current contentBase configuration>"\n}'
|
372
|
);
|
373
|
|
374
|
// Redirect every request to the port contentBase
|
375
|
this.app.get('*', (req, res) => {
|
376
|
res.writeHead(302, {
|
377
|
Location: `//localhost:${contentBase}${req.path}${req._parsedUrl
|
378
|
.search || ''}`,
|
379
|
});
|
380
|
|
381
|
res.end();
|
382
|
});
|
383
|
} else {
|
384
|
// route content request
|
385
|
this.app.use(
|
386
|
contentBasePublicPath,
|
387
|
express.static(contentBase, this.options.staticOptions)
|
388
|
);
|
389
|
}
|
390
|
}
|
391
|
|
392
|
setupServeIndexFeature() {
|
393
|
const contentBase = this.options.contentBase;
|
394
|
const contentBasePublicPath = this.options.contentBasePublicPath;
|
395
|
|
396
|
if (Array.isArray(contentBase)) {
|
397
|
contentBase.forEach((item) => {
|
398
|
this.app.use(contentBasePublicPath, (req, res, next) => {
|
399
|
// serve-index doesn't fallthrough non-get/head request to next middleware
|
400
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
401
|
return next();
|
402
|
}
|
403
|
|
404
|
serveIndex(item)(req, res, next);
|
405
|
});
|
406
|
});
|
407
|
} else if (
|
408
|
typeof contentBase !== 'number' &&
|
409
|
!isAbsoluteUrl(String(contentBase))
|
410
|
) {
|
411
|
this.app.use(contentBasePublicPath, (req, res, next) => {
|
412
|
// serve-index doesn't fallthrough non-get/head request to next middleware
|
413
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
414
|
return next();
|
415
|
}
|
416
|
|
417
|
serveIndex(contentBase)(req, res, next);
|
418
|
});
|
419
|
}
|
420
|
}
|
421
|
|
422
|
setupWatchStaticFeature() {
|
423
|
const contentBase = this.options.contentBase;
|
424
|
|
425
|
if (isAbsoluteUrl(String(contentBase)) || typeof contentBase === 'number') {
|
426
|
throw new Error('Watching remote files is not supported.');
|
427
|
} else if (Array.isArray(contentBase)) {
|
428
|
contentBase.forEach((item) => {
|
429
|
if (isAbsoluteUrl(String(item)) || typeof item === 'number') {
|
430
|
throw new Error('Watching remote files is not supported.');
|
431
|
}
|
432
|
this._watch(item);
|
433
|
});
|
434
|
} else {
|
435
|
this._watch(contentBase);
|
436
|
}
|
437
|
}
|
438
|
|
439
|
setupBeforeFeature() {
|
440
|
// Todo rename onBeforeSetupMiddleware in next major release
|
441
|
// Todo pass only `this` argument
|
442
|
this.options.before(this.app, this, this.compiler);
|
443
|
}
|
444
|
|
445
|
setupMiddleware() {
|
446
|
this.app.use(this.middleware);
|
447
|
}
|
448
|
|
449
|
setupAfterFeature() {
|
450
|
// Todo rename onAfterSetupMiddleware in next major release
|
451
|
// Todo pass only `this` argument
|
452
|
this.options.after(this.app, this, this.compiler);
|
453
|
}
|
454
|
|
455
|
setupHeadersFeature() {
|
456
|
this.app.all('*', this.setContentHeaders.bind(this));
|
457
|
}
|
458
|
|
459
|
setupMagicHtmlFeature() {
|
460
|
this.app.get('*', this.serveMagicHtml.bind(this));
|
461
|
}
|
462
|
|
463
|
setupSetupFeature() {
|
464
|
this.log.warn(
|
465
|
'The `setup` option is deprecated and will be removed in v4. Please update your config to use `before`'
|
466
|
);
|
467
|
|
468
|
this.options.setup(this.app, this);
|
469
|
}
|
470
|
|
471
|
setupFeatures() {
|
472
|
const features = {
|
473
|
compress: () => {
|
474
|
if (this.options.compress) {
|
475
|
this.setupCompressFeature();
|
476
|
}
|
477
|
},
|
478
|
proxy: () => {
|
479
|
if (this.options.proxy) {
|
480
|
this.setupProxyFeature();
|
481
|
}
|
482
|
},
|
483
|
historyApiFallback: () => {
|
484
|
if (this.options.historyApiFallback) {
|
485
|
this.setupHistoryApiFallbackFeature();
|
486
|
}
|
487
|
},
|
488
|
// Todo rename to `static` in future major release
|
489
|
contentBaseFiles: () => {
|
490
|
this.setupStaticFeature();
|
491
|
},
|
492
|
// Todo rename to `serveIndex` in future major release
|
493
|
contentBaseIndex: () => {
|
494
|
this.setupServeIndexFeature();
|
495
|
},
|
496
|
// Todo rename to `watchStatic` in future major release
|
497
|
watchContentBase: () => {
|
498
|
this.setupWatchStaticFeature();
|
499
|
},
|
500
|
before: () => {
|
501
|
if (typeof this.options.before === 'function') {
|
502
|
this.setupBeforeFeature();
|
503
|
}
|
504
|
},
|
505
|
middleware: () => {
|
506
|
// include our middleware to ensure
|
507
|
// it is able to handle '/index.html' request after redirect
|
508
|
this.setupMiddleware();
|
509
|
},
|
510
|
after: () => {
|
511
|
if (typeof this.options.after === 'function') {
|
512
|
this.setupAfterFeature();
|
513
|
}
|
514
|
},
|
515
|
headers: () => {
|
516
|
this.setupHeadersFeature();
|
517
|
},
|
518
|
magicHtml: () => {
|
519
|
this.setupMagicHtmlFeature();
|
520
|
},
|
521
|
setup: () => {
|
522
|
if (typeof this.options.setup === 'function') {
|
523
|
this.setupSetupFeature();
|
524
|
}
|
525
|
},
|
526
|
};
|
527
|
|
528
|
const runnableFeatures = [];
|
529
|
|
530
|
// compress is placed last and uses unshift so that it will be the first middleware used
|
531
|
if (this.options.compress) {
|
532
|
runnableFeatures.push('compress');
|
533
|
}
|
534
|
|
535
|
runnableFeatures.push('setup', 'before', 'headers', 'middleware');
|
536
|
|
537
|
if (this.options.proxy) {
|
538
|
runnableFeatures.push('proxy', 'middleware');
|
539
|
}
|
540
|
|
541
|
if (this.options.contentBase !== false) {
|
542
|
runnableFeatures.push('contentBaseFiles');
|
543
|
}
|
544
|
|
545
|
if (this.options.historyApiFallback) {
|
546
|
runnableFeatures.push('historyApiFallback', 'middleware');
|
547
|
|
548
|
if (this.options.contentBase !== false) {
|
549
|
runnableFeatures.push('contentBaseFiles');
|
550
|
}
|
551
|
}
|
552
|
|
553
|
// checking if it's set to true or not set (Default : undefined => true)
|
554
|
this.serveIndex = this.serveIndex || this.serveIndex === undefined;
|
555
|
|
556
|
if (this.options.contentBase && this.serveIndex) {
|
557
|
runnableFeatures.push('contentBaseIndex');
|
558
|
}
|
559
|
|
560
|
if (this.options.watchContentBase) {
|
561
|
runnableFeatures.push('watchContentBase');
|
562
|
}
|
563
|
|
564
|
runnableFeatures.push('magicHtml');
|
565
|
|
566
|
if (this.options.after) {
|
567
|
runnableFeatures.push('after');
|
568
|
}
|
569
|
|
570
|
(this.options.features || runnableFeatures).forEach((feature) => {
|
571
|
features[feature]();
|
572
|
});
|
573
|
}
|
574
|
|
575
|
setupHttps() {
|
576
|
// if the user enables http2, we can safely enable https
|
577
|
if (this.options.http2 && !this.options.https) {
|
578
|
this.options.https = true;
|
579
|
}
|
580
|
|
581
|
if (this.options.https) {
|
582
|
// for keep supporting CLI parameters
|
583
|
if (typeof this.options.https === 'boolean') {
|
584
|
this.options.https = {
|
585
|
ca: this.options.ca,
|
586
|
pfx: this.options.pfx,
|
587
|
key: this.options.key,
|
588
|
cert: this.options.cert,
|
589
|
passphrase: this.options.pfxPassphrase,
|
590
|
requestCert: this.options.requestCert || false,
|
591
|
};
|
592
|
}
|
593
|
|
594
|
for (const property of ['ca', 'pfx', 'key', 'cert']) {
|
595
|
const value = this.options.https[property];
|
596
|
const isBuffer = value instanceof Buffer;
|
597
|
|
598
|
if (value && !isBuffer) {
|
599
|
let stats = null;
|
600
|
|
601
|
try {
|
602
|
stats = fs.lstatSync(fs.realpathSync(value)).isFile();
|
603
|
} catch (error) {
|
604
|
// ignore error
|
605
|
}
|
606
|
|
607
|
// It is file
|
608
|
this.options.https[property] = stats
|
609
|
? fs.readFileSync(path.resolve(value))
|
610
|
: value;
|
611
|
}
|
612
|
}
|
613
|
|
614
|
let fakeCert;
|
615
|
|
616
|
if (!this.options.https.key || !this.options.https.cert) {
|
617
|
fakeCert = getCertificate(this.log);
|
618
|
}
|
619
|
|
620
|
this.options.https.key = this.options.https.key || fakeCert;
|
621
|
this.options.https.cert = this.options.https.cert || fakeCert;
|
622
|
|
623
|
// note that options.spdy never existed. The user was able
|
624
|
// to set options.https.spdy before, though it was not in the
|
625
|
// docs. Keep options.https.spdy if the user sets it for
|
626
|
// backwards compatibility, but log a deprecation warning.
|
627
|
if (this.options.https.spdy) {
|
628
|
// for backwards compatibility: if options.https.spdy was passed in before,
|
629
|
// it was not altered in any way
|
630
|
this.log.warn(
|
631
|
'Providing custom spdy server options is deprecated and will be removed in the next major version.'
|
632
|
);
|
633
|
} else {
|
634
|
// if the normal https server gets this option, it will not affect it.
|
635
|
this.options.https.spdy = {
|
636
|
protocols: ['h2', 'http/1.1'],
|
637
|
};
|
638
|
}
|
639
|
}
|
640
|
}
|
641
|
|
642
|
createServer() {
|
643
|
if (this.options.https) {
|
644
|
// Only prevent HTTP/2 if http2 is explicitly set to false
|
645
|
const isHttp2 = this.options.http2 !== false;
|
646
|
|
647
|
// `spdy` is effectively unmaintained, and as a consequence of an
|
648
|
// implementation that extensively relies on Node’s non-public APIs, broken
|
649
|
// on Node 10 and above. In those cases, only https will be used for now.
|
650
|
// Once express supports Node's built-in HTTP/2 support, migrating over to
|
651
|
// that should be the best way to go.
|
652
|
// The relevant issues are:
|
653
|
// - https://github.com/nodejs/node/issues/21665
|
654
|
// - https://github.com/webpack/webpack-dev-server/issues/1449
|
655
|
// - https://github.com/expressjs/express/issues/3388
|
656
|
if (semver.gte(process.version, '10.0.0') || !isHttp2) {
|
657
|
if (this.options.http2) {
|
658
|
// the user explicitly requested http2 but is not getting it because
|
659
|
// of the node version.
|
660
|
this.log.warn(
|
661
|
'HTTP/2 is currently unsupported for Node 10.0.0 and above, but will be supported once Express supports it'
|
662
|
);
|
663
|
}
|
664
|
this.listeningApp = https.createServer(this.options.https, this.app);
|
665
|
} else {
|
666
|
// The relevant issues are:
|
667
|
// https://github.com/spdy-http2/node-spdy/issues/350
|
668
|
// https://github.com/webpack/webpack-dev-server/issues/1592
|
669
|
this.listeningApp = require('spdy').createServer(
|
670
|
this.options.https,
|
671
|
this.app
|
672
|
);
|
673
|
}
|
674
|
} else {
|
675
|
this.listeningApp = http.createServer(this.app);
|
676
|
}
|
677
|
}
|
678
|
|
679
|
createSocketServer() {
|
680
|
const SocketServerImplementation = this.socketServerImplementation;
|
681
|
this.socketServer = new SocketServerImplementation(this);
|
682
|
|
683
|
this.socketServer.onConnection((connection, headers) => {
|
684
|
if (!connection) {
|
685
|
return;
|
686
|
}
|
687
|
|
688
|
if (!headers) {
|
689
|
this.log.warn(
|
690
|
'transportMode.server implementation must pass headers to the callback of onConnection(f) ' +
|
691
|
'via f(connection, headers) in order for clients to pass a headers security check'
|
692
|
);
|
693
|
}
|
694
|
|
695
|
if (!headers || !this.checkHost(headers) || !this.checkOrigin(headers)) {
|
696
|
this.sockWrite([connection], 'error', 'Invalid Host/Origin header');
|
697
|
|
698
|
this.socketServer.close(connection);
|
699
|
|
700
|
return;
|
701
|
}
|
702
|
|
703
|
this.sockets.push(connection);
|
704
|
|
705
|
this.socketServer.onConnectionClose(connection, () => {
|
706
|
const idx = this.sockets.indexOf(connection);
|
707
|
|
708
|
if (idx >= 0) {
|
709
|
this.sockets.splice(idx, 1);
|
710
|
}
|
711
|
});
|
712
|
|
713
|
if (this.clientLogLevel) {
|
714
|
this.sockWrite([connection], 'log-level', this.clientLogLevel);
|
715
|
}
|
716
|
|
717
|
if (this.hot) {
|
718
|
this.sockWrite([connection], 'hot');
|
719
|
}
|
720
|
|
721
|
// TODO: change condition at major version
|
722
|
if (this.options.liveReload !== false) {
|
723
|
this.sockWrite([connection], 'liveReload', this.options.liveReload);
|
724
|
}
|
725
|
|
726
|
if (this.progress) {
|
727
|
this.sockWrite([connection], 'progress', this.progress);
|
728
|
}
|
729
|
|
730
|
if (this.clientOverlay) {
|
731
|
this.sockWrite([connection], 'overlay', this.clientOverlay);
|
732
|
}
|
733
|
|
734
|
if (!this._stats) {
|
735
|
return;
|
736
|
}
|
737
|
|
738
|
this._sendStats([connection], this.getStats(this._stats), true);
|
739
|
});
|
740
|
}
|
741
|
|
742
|
showStatus() {
|
743
|
const suffix =
|
744
|
this.options.inline !== false || this.options.lazy === true
|
745
|
? '/'
|
746
|
: '/webpack-dev-server/';
|
747
|
const uri = `${createDomain(this.options, this.listeningApp)}${suffix}`;
|
748
|
|
749
|
status(
|
750
|
uri,
|
751
|
this.options,
|
752
|
this.log,
|
753
|
this.options.stats && this.options.stats.colors
|
754
|
);
|
755
|
}
|
756
|
|
757
|
listen(port, hostname, fn) {
|
758
|
this.hostname = hostname;
|
759
|
|
760
|
return this.listeningApp.listen(port, hostname, (err) => {
|
761
|
this.createSocketServer();
|
762
|
|
763
|
if (this.options.bonjour) {
|
764
|
runBonjour(this.options);
|
765
|
}
|
766
|
|
767
|
this.showStatus();
|
768
|
|
769
|
if (fn) {
|
770
|
fn.call(this.listeningApp, err);
|
771
|
}
|
772
|
|
773
|
if (typeof this.options.onListening === 'function') {
|
774
|
this.options.onListening(this);
|
775
|
}
|
776
|
});
|
777
|
}
|
778
|
|
779
|
close(cb) {
|
780
|
this.sockets.forEach((socket) => {
|
781
|
this.socketServer.close(socket);
|
782
|
});
|
783
|
|
784
|
this.sockets = [];
|
785
|
|
786
|
this.contentBaseWatchers.forEach((watcher) => {
|
787
|
watcher.close();
|
788
|
});
|
789
|
|
790
|
this.contentBaseWatchers = [];
|
791
|
|
792
|
this.listeningApp.kill(() => {
|
793
|
this.middleware.close(cb);
|
794
|
});
|
795
|
}
|
796
|
|
797
|
static get DEFAULT_STATS() {
|
798
|
return {
|
799
|
all: false,
|
800
|
hash: true,
|
801
|
assets: true,
|
802
|
warnings: true,
|
803
|
errors: true,
|
804
|
errorDetails: false,
|
805
|
};
|
806
|
}
|
807
|
|
808
|
getStats(statsObj) {
|
809
|
const stats = Server.DEFAULT_STATS;
|
810
|
|
811
|
if (this.originalStats.warningsFilter) {
|
812
|
stats.warningsFilter = this.originalStats.warningsFilter;
|
813
|
}
|
814
|
|
815
|
return statsObj.toJson(stats);
|
816
|
}
|
817
|
|
818
|
use() {
|
819
|
// eslint-disable-next-line
|
820
|
this.app.use.apply(this.app, arguments);
|
821
|
}
|
822
|
|
823
|
setContentHeaders(req, res, next) {
|
824
|
if (this.headers) {
|
825
|
// eslint-disable-next-line
|
826
|
for (const name in this.headers) {
|
827
|
res.setHeader(name, this.headers[name]);
|
828
|
}
|
829
|
}
|
830
|
|
831
|
next();
|
832
|
}
|
833
|
|
834
|
checkHost(headers) {
|
835
|
return this.checkHeaders(headers, 'host');
|
836
|
}
|
837
|
|
838
|
checkOrigin(headers) {
|
839
|
return this.checkHeaders(headers, 'origin');
|
840
|
}
|
841
|
|
842
|
checkHeaders(headers, headerToCheck) {
|
843
|
// allow user to opt-out this security check, at own risk
|
844
|
if (this.disableHostCheck) {
|
845
|
return true;
|
846
|
}
|
847
|
|
848
|
if (!headerToCheck) {
|
849
|
headerToCheck = 'host';
|
850
|
}
|
851
|
|
852
|
// get the Host header and extract hostname
|
853
|
// we don't care about port not matching
|
854
|
const hostHeader = headers[headerToCheck];
|
855
|
|
856
|
if (!hostHeader) {
|
857
|
return false;
|
858
|
}
|
859
|
|
860
|
// use the node url-parser to retrieve the hostname from the host-header.
|
861
|
const hostname = url.parse(
|
862
|
// if hostHeader doesn't have scheme, add // for parsing.
|
863
|
/^(.+:)?\/\//.test(hostHeader) ? hostHeader : `//${hostHeader}`,
|
864
|
false,
|
865
|
true
|
866
|
).hostname;
|
867
|
// always allow requests with explicit IPv4 or IPv6-address.
|
868
|
// A note on IPv6 addresses:
|
869
|
// hostHeader will always contain the brackets denoting
|
870
|
// an IPv6-address in URLs,
|
871
|
// these are removed from the hostname in url.parse(),
|
872
|
// so we have the pure IPv6-address in hostname.
|
873
|
// always allow localhost host, for convenience (hostname === 'localhost')
|
874
|
// allow hostname of listening address (hostname === this.hostname)
|
875
|
const isValidHostname =
|
876
|
ip.isV4Format(hostname) ||
|
877
|
ip.isV6Format(hostname) ||
|
878
|
hostname === 'localhost' ||
|
879
|
hostname === this.hostname;
|
880
|
|
881
|
if (isValidHostname) {
|
882
|
return true;
|
883
|
}
|
884
|
// always allow localhost host, for convenience
|
885
|
// allow if hostname is in allowedHosts
|
886
|
if (this.allowedHosts && this.allowedHosts.length) {
|
887
|
for (let hostIdx = 0; hostIdx < this.allowedHosts.length; hostIdx++) {
|
888
|
const allowedHost = this.allowedHosts[hostIdx];
|
889
|
|
890
|
if (allowedHost === hostname) {
|
891
|
return true;
|
892
|
}
|
893
|
|
894
|
// support "." as a subdomain wildcard
|
895
|
// e.g. ".example.com" will allow "example.com", "www.example.com", "subdomain.example.com", etc
|
896
|
if (allowedHost[0] === '.') {
|
897
|
// "example.com" (hostname === allowedHost.substring(1))
|
898
|
// "*.example.com" (hostname.endsWith(allowedHost))
|
899
|
if (
|
900
|
hostname === allowedHost.substring(1) ||
|
901
|
hostname.endsWith(allowedHost)
|
902
|
) {
|
903
|
return true;
|
904
|
}
|
905
|
}
|
906
|
}
|
907
|
}
|
908
|
|
909
|
// also allow public hostname if provided
|
910
|
if (typeof this.publicHost === 'string') {
|
911
|
const idxPublic = this.publicHost.indexOf(':');
|
912
|
const publicHostname =
|
913
|
idxPublic >= 0 ? this.publicHost.substr(0, idxPublic) : this.publicHost;
|
914
|
|
915
|
if (hostname === publicHostname) {
|
916
|
return true;
|
917
|
}
|
918
|
}
|
919
|
|
920
|
// disallow
|
921
|
return false;
|
922
|
}
|
923
|
|
924
|
// eslint-disable-next-line
|
925
|
sockWrite(sockets, type, data) {
|
926
|
sockets.forEach((socket) => {
|
927
|
this.socketServer.send(socket, JSON.stringify({ type, data }));
|
928
|
});
|
929
|
}
|
930
|
|
931
|
serveMagicHtml(req, res, next) {
|
932
|
const _path = req.path;
|
933
|
|
934
|
try {
|
935
|
const isFile = this.middleware.fileSystem
|
936
|
.statSync(this.middleware.getFilenameFromUrl(`${_path}.js`))
|
937
|
.isFile();
|
938
|
|
939
|
if (!isFile) {
|
940
|
return next();
|
941
|
}
|
942
|
// Serve a page that executes the javascript
|
943
|
const queries = req._parsedUrl.search || '';
|
944
|
const responsePage = `<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body><script type="text/javascript" charset="utf-8" src="${_path}.js${queries}"></script></body></html>`;
|
945
|
res.send(responsePage);
|
946
|
} catch (err) {
|
947
|
return next();
|
948
|
}
|
949
|
}
|
950
|
|
951
|
// send stats to a socket or multiple sockets
|
952
|
_sendStats(sockets, stats, force) {
|
953
|
const shouldEmit =
|
954
|
!force &&
|
955
|
stats &&
|
956
|
(!stats.errors || stats.errors.length === 0) &&
|
957
|
stats.assets &&
|
958
|
stats.assets.every((asset) => !asset.emitted);
|
959
|
|
960
|
if (shouldEmit) {
|
961
|
return this.sockWrite(sockets, 'still-ok');
|
962
|
}
|
963
|
|
964
|
this.sockWrite(sockets, 'hash', stats.hash);
|
965
|
|
966
|
if (stats.errors.length > 0) {
|
967
|
this.sockWrite(sockets, 'errors', stats.errors);
|
968
|
} else if (stats.warnings.length > 0) {
|
969
|
this.sockWrite(sockets, 'warnings', stats.warnings);
|
970
|
} else {
|
971
|
this.sockWrite(sockets, 'ok');
|
972
|
}
|
973
|
}
|
974
|
|
975
|
_watch(watchPath) {
|
976
|
// duplicate the same massaging of options that watchpack performs
|
977
|
// https://github.com/webpack/watchpack/blob/master/lib/DirectoryWatcher.js#L49
|
978
|
// this isn't an elegant solution, but we'll improve it in the future
|
979
|
const usePolling = this.watchOptions.poll ? true : undefined;
|
980
|
const interval =
|
981
|
typeof this.watchOptions.poll === 'number'
|
982
|
? this.watchOptions.poll
|
983
|
: undefined;
|
984
|
|
985
|
const watchOptions = {
|
986
|
ignoreInitial: true,
|
987
|
persistent: true,
|
988
|
followSymlinks: false,
|
989
|
atomic: false,
|
990
|
alwaysStat: true,
|
991
|
ignorePermissionErrors: true,
|
992
|
ignored: this.watchOptions.ignored,
|
993
|
usePolling,
|
994
|
interval,
|
995
|
};
|
996
|
|
997
|
const watcher = chokidar.watch(watchPath, watchOptions);
|
998
|
// disabling refreshing on changing the content
|
999
|
if (this.options.liveReload !== false) {
|
1000
|
watcher.on('change', () => {
|
1001
|
this.sockWrite(this.sockets, 'content-changed');
|
1002
|
});
|
1003
|
}
|
1004
|
this.contentBaseWatchers.push(watcher);
|
1005
|
}
|
1006
|
|
1007
|
invalidate(callback) {
|
1008
|
if (this.middleware) {
|
1009
|
this.middleware.invalidate(callback);
|
1010
|
}
|
1011
|
}
|
1012
|
}
|
1013
|
|
1014
|
// Export this logic,
|
1015
|
// so that other implementations,
|
1016
|
// like task-runners can use it
|
1017
|
Server.addDevServerEntrypoints = require('./utils/addEntries');
|
1018
|
|
1019
|
module.exports = Server;
|