@rspack/dev-server 2.0.0-beta.3 → 2.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/131.js CHANGED
@@ -1,3 +1,4 @@
1
+ import * as __rspack_external_zlib from "zlib";
1
2
  import { __webpack_require__ } from "./rslib-runtime.js";
2
3
  import node_fs, { lstatSync, promises, readFileSync, realpathSync, statSync, unlinkSync } from "node:fs";
3
4
  import { createRequire } from "node:module";
@@ -8,6 +9,94 @@ import { deprecate, promisify, styleText } from "node:util";
8
9
  import ipaddr from "ipaddr.js";
9
10
  import { createServer } from "node:net";
10
11
  import { WebSocketServer } from "ws";
12
+ __webpack_require__.add({
13
+ "./node_modules/.pnpm/http-compression@1.1.2/node_modules/http-compression/src/index.js" (module, __unused_rspack_exports, __webpack_require__) {
14
+ const zlib = __webpack_require__("zlib");
15
+ const MIMES = /text|javascript|\/json|xml/i;
16
+ const noop = ()=>{};
17
+ const getChunkSize = (chunk, enc)=>chunk ? Buffer.byteLength(chunk, enc) : 0;
18
+ module.exports = ({ threshold = 1024, level = {
19
+ brotli: 0,
20
+ gzip: 1
21
+ }, brotli = true, gzip = true, mimes = MIMES } = {})=>{
22
+ const brotliOpts = 'object' == typeof brotli && brotli || {};
23
+ const gzipOpts = 'object' == typeof gzip && gzip || {};
24
+ if (brotli && !zlib.createBrotliCompress) brotli = false;
25
+ return (req, res, next = noop)=>{
26
+ const accept = req.headers['accept-encoding'];
27
+ const encoding = accept && (brotli && accept.match(/\bbr\b/) || gzip && accept.match(/\bgzip\b/) || [])[0];
28
+ if ('HEAD' === req.method || !encoding) return next();
29
+ let compress;
30
+ let pendingStatus;
31
+ let pendingListeners = [];
32
+ let started = false;
33
+ let size = 0;
34
+ function start() {
35
+ started = true;
36
+ size = 0 | res.getHeader('Content-Length') || size;
37
+ const compressible = mimes.test(String(res.getHeader('Content-Type') || 'text/plain'));
38
+ const cleartext = !res.getHeader('Content-Encoding');
39
+ const listeners = pendingListeners || [];
40
+ if (compressible && cleartext && size >= threshold) {
41
+ res.setHeader('Content-Encoding', encoding);
42
+ res.removeHeader('Content-Length');
43
+ compress = 'br' === encoding ? zlib.createBrotliCompress({
44
+ params: Object.assign({
45
+ [zlib.constants.BROTLI_PARAM_QUALITY]: level.brotli,
46
+ [zlib.constants.BROTLI_PARAM_SIZE_HINT]: size
47
+ }, brotliOpts)
48
+ }) : zlib.createGzip(Object.assign({
49
+ level: level.gzip
50
+ }, gzipOpts));
51
+ compress.on('data', (chunk)=>false === write.call(res, chunk) && compress.pause());
52
+ on.call(res, 'drain', ()=>compress.resume());
53
+ compress.on('end', ()=>end.call(res));
54
+ listeners.forEach((p)=>compress.on.apply(compress, p));
55
+ } else {
56
+ pendingListeners = null;
57
+ listeners.forEach((p)=>on.apply(res, p));
58
+ }
59
+ writeHead.call(res, pendingStatus || res.statusCode);
60
+ }
61
+ const { end, write, on, writeHead } = res;
62
+ res.writeHead = function(status, reason, headers) {
63
+ if ('string' != typeof reason) [headers, reason] = [
64
+ reason,
65
+ headers
66
+ ];
67
+ if (headers) for(const i in headers)res.setHeader(i, headers[i]);
68
+ pendingStatus = status;
69
+ return this;
70
+ };
71
+ res.write = function(chunk, enc) {
72
+ size += getChunkSize(chunk, enc);
73
+ if (!started) start();
74
+ if (!compress) return write.apply(this, arguments);
75
+ return compress.write.apply(compress, arguments);
76
+ };
77
+ res.end = function(chunk, enc) {
78
+ if (arguments.length > 0 && 'function' != typeof chunk) size += getChunkSize(chunk, enc);
79
+ if (!started) start();
80
+ if (!compress) return end.apply(this, arguments);
81
+ return compress.end.apply(compress, arguments);
82
+ };
83
+ res.on = function(type, listener) {
84
+ if (pendingListeners && 'drain' === type) if (compress) compress.on(type, listener);
85
+ else pendingListeners.push([
86
+ type,
87
+ listener
88
+ ]);
89
+ else on.call(this, type, listener);
90
+ return this;
91
+ };
92
+ next();
93
+ };
94
+ };
95
+ },
96
+ zlib (module) {
97
+ module.exports = __rspack_external_zlib;
98
+ }
99
+ });
11
100
  var external_node_util_namespaceObject = {};
12
101
  __webpack_require__.r(external_node_util_namespaceObject);
13
102
  __webpack_require__.d(external_node_util_namespaceObject, {
@@ -127,6 +216,8 @@ class WebsocketServer extends servers_BaseServer {
127
216
  });
128
217
  }
129
218
  }
219
+ const src = __webpack_require__("./node_modules/.pnpm/http-compression@1.1.2/node_modules/http-compression/src/index.js");
220
+ var src_default = /*#__PURE__*/ __webpack_require__.n(src);
130
221
  const { styleText: server_styleText } = external_node_util_namespaceObject;
131
222
  const server_require = createRequire(import.meta.url);
132
223
  if (!process.env.WEBPACK_SERVE) process.env.WEBPACK_SERVE = 'true';
@@ -146,6 +237,7 @@ const getConnect = async ()=>{
146
237
  const { connect } = await import("connect-next");
147
238
  return connect;
148
239
  };
240
+ const getChokidar = memoize(()=>import("chokidar"));
149
241
  const getServeStatic = memoize(()=>server_require('serve-static'));
150
242
  const encodeOverlaySettings = (setting)=>'function' == typeof setting ? encodeURIComponent(setting.toString()) : setting;
151
243
  const DEFAULT_ALLOWED_PROTOCOLS = /^(file|.+-extension):/i;
@@ -261,7 +353,7 @@ class Server {
261
353
  if ('3' === process.versions.pnp) return external_node_path_resolve(dir, '.yarn/.cache/rspack-dev-server');
262
354
  return external_node_path_resolve(dir, 'node_modules/.cache/rspack-dev-server');
263
355
  }
264
- addAdditionalEntries(compiler) {
356
+ #addAdditionalEntries(compiler) {
265
357
  const additionalEntries = [];
266
358
  const isWebTarget = Boolean(compiler.platform.web);
267
359
  if (this.options.client && isWebTarget) {
@@ -312,7 +404,7 @@ class Server {
312
404
  name: void 0
313
405
  }).apply(compiler);
314
406
  }
315
- getCompilerOptions() {
407
+ #getCompilerOptions() {
316
408
  if (void 0 !== this.compiler.compilers) {
317
409
  if (1 === this.compiler.compilers.length) return this.compiler.compilers[0].options;
318
410
  const compilerWithDevServer = this.compiler.compilers.find((config)=>config.options.devServer);
@@ -323,14 +415,14 @@ class Server {
323
415
  }
324
416
  return this.compiler.options;
325
417
  }
326
- shouldLogInfrastructureInfo() {
327
- const compilerOptions = this.getCompilerOptions();
418
+ #shouldLogInfrastructureInfo() {
419
+ const compilerOptions = this.#getCompilerOptions();
328
420
  const { level = 'info' } = compilerOptions.infrastructureLogging || {};
329
421
  return 'info' === level || 'log' === level || 'verbose' === level;
330
422
  }
331
- async normalizeOptions() {
423
+ async #normalizeOptions() {
332
424
  const { options } = this;
333
- const compilerOptions = this.getCompilerOptions();
425
+ const compilerOptions = this.#getCompilerOptions();
334
426
  const compilerWatchOptions = compilerOptions.watchOptions;
335
427
  const getWatchOptions = (watchOptions = {})=>{
336
428
  const getPolling = ()=>{
@@ -346,7 +438,7 @@ class Server {
346
438
  };
347
439
  const usePolling = getPolling();
348
440
  const interval = getInterval();
349
- const { poll, ...rest } = watchOptions;
441
+ const { poll: _poll, ...rest } = watchOptions;
350
442
  return {
351
443
  ignoreInitial: true,
352
444
  persistent: true,
@@ -355,8 +447,9 @@ class Server {
355
447
  alwaysStat: true,
356
448
  ignorePermissionErrors: true,
357
449
  usePolling,
358
- interval,
359
- ignored: watchOptions.ignored,
450
+ ...void 0 !== interval ? {
451
+ interval
452
+ } : {},
360
453
  ...rest
361
454
  };
362
455
  };
@@ -367,9 +460,6 @@ class Server {
367
460
  publicPath: [
368
461
  '/'
369
462
  ],
370
- serveIndex: {
371
- icons: true
372
- },
373
463
  watch: getWatchOptions()
374
464
  });
375
465
  let item;
@@ -389,10 +479,6 @@ class Server {
389
479
  publicPath: void 0 !== optionsForStatic.publicPath ? Array.isArray(optionsForStatic.publicPath) ? optionsForStatic.publicPath : [
390
480
  optionsForStatic.publicPath
391
481
  ] : def.publicPath,
392
- serveIndex: void 0 !== optionsForStatic.serveIndex ? 'boolean' == typeof optionsForStatic.serveIndex && optionsForStatic.serveIndex ? def.serveIndex : 'object' == typeof optionsForStatic.serveIndex ? {
393
- ...def.serveIndex,
394
- ...optionsForStatic.serveIndex
395
- } : optionsForStatic.serveIndex : def.serveIndex,
396
482
  watch: void 0 !== optionsForStatic.watch ? 'boolean' == typeof optionsForStatic.watch ? optionsForStatic.watch ? def.watch : false : getWatchOptions(optionsForStatic.watch) : def.watch
397
483
  };
398
484
  }
@@ -708,7 +794,7 @@ class Server {
708
794
  }
709
795
  else options.webSocketServer = false;
710
796
  }
711
- getClientTransport() {
797
+ #getClientTransport() {
712
798
  let clientImplementation;
713
799
  let clientImplementationFound = true;
714
800
  const isKnownWebSocketServerImplementation = this.options.webSocketServer && 'string' == typeof this.options.webSocketServer.type && 'ws' === this.options.webSocketServer.type;
@@ -730,7 +816,7 @@ class Server {
730
816
  if (!clientImplementationFound) throw new Error(`${!isKnownWebSocketServerImplementation ? 'When you use custom web socket implementation you must explicitly specify client.webSocketTransport. ' : ''}client.webSocketTransport must be a string denoting a default implementation (e.g. 'ws') or a full path to a JS file via require.resolve(...) which exports a class `);
731
817
  return clientImplementation;
732
818
  }
733
- getServerTransport() {
819
+ #getServerTransport() {
734
820
  let implementation;
735
821
  let implementationFound = true;
736
822
  switch(typeof this.options.webSocketServer.type){
@@ -759,7 +845,7 @@ class Server {
759
845
  if ('only' === this.options.hot) return server_require.resolve('@rspack/core/hot/only-dev-server');
760
846
  if (this.options.hot) return server_require.resolve('@rspack/core/hot/dev-server');
761
847
  }
762
- setupProgressPlugin() {
848
+ #setupProgressPlugin() {
763
849
  const { ProgressPlugin } = this.compiler.compilers ? this.compiler.compilers[0].webpack : this.compiler.webpack;
764
850
  new ProgressPlugin((percent, msg)=>{
765
851
  const percentValue = Math.floor(100 * percent);
@@ -773,7 +859,7 @@ class Server {
773
859
  if (this.server) this.server.emit('progress-update', payload);
774
860
  }).apply(this.compiler);
775
861
  }
776
- async initialize() {
862
+ async #initialize() {
777
863
  const compilers = isMultiCompiler(this.compiler) ? this.compiler.compilers : [
778
864
  this.compiler
779
865
  ];
@@ -787,19 +873,19 @@ class Server {
787
873
  };
788
874
  }
789
875
  }
790
- this.setupHooks();
791
- await this.setupApp();
792
- await this.createServer();
876
+ this.#setupHooks();
877
+ await this.#setupApp();
878
+ await this.#createServer();
793
879
  if (this.options.webSocketServer) {
794
880
  const compilers = this.compiler.compilers || [
795
881
  this.compiler
796
882
  ];
797
883
  for (const compiler of compilers){
798
884
  if (false === compiler.options.devServer) continue;
799
- this.addAdditionalEntries(compiler);
885
+ this.#addAdditionalEntries(compiler);
800
886
  const { ProvidePlugin, HotModuleReplacementPlugin } = compiler.rspack;
801
887
  new ProvidePlugin({
802
- __rspack_dev_server_client__: this.getClientTransport()
888
+ __rspack_dev_server_client__: this.#getClientTransport()
803
889
  }).apply(compiler);
804
890
  if (this.options.hot) {
805
891
  const HMRPluginExists = compiler.options.plugins.find((plugin)=>plugin && plugin.constructor === HotModuleReplacementPlugin);
@@ -810,11 +896,11 @@ class Server {
810
896
  }
811
897
  }
812
898
  }
813
- if (this.options.client && this.options.client.progress) this.setupProgressPlugin();
899
+ if (this.options.client && this.options.client.progress) this.#setupProgressPlugin();
814
900
  }
815
- this.setupWatchFiles();
816
- this.setupWatchStaticFiles();
817
- await this.setupMiddlewares();
901
+ await this.#setupWatchFiles();
902
+ await this.#setupWatchStaticFiles();
903
+ await this.#setupMiddlewares();
818
904
  if (this.options.setupExitSignals) {
819
905
  const signals = [
820
906
  'SIGINT',
@@ -843,35 +929,35 @@ class Server {
843
929
  const webSocketProxies = this.webSocketProxies;
844
930
  for (const webSocketProxy of webSocketProxies)this.server.on('upgrade', webSocketProxy.upgrade);
845
931
  }
846
- async setupApp() {
932
+ async #setupApp() {
847
933
  this.app = 'function' == typeof this.options.app ? await this.options.app() : (await getConnect())();
848
934
  }
849
- getStats(statsObj) {
935
+ #getStats(statsObj) {
850
936
  const stats = Server.DEFAULT_STATS;
851
- const compilerOptions = this.getCompilerOptions();
937
+ const compilerOptions = this.#getCompilerOptions();
852
938
  if (compilerOptions.stats && compilerOptions.stats.warningsFilter) stats.warningsFilter = compilerOptions.stats.warningsFilter;
853
939
  return statsObj.toJson(stats);
854
940
  }
855
- setupHooks() {
941
+ #setupHooks() {
856
942
  this.compiler.hooks.invalid.tap('rspack-dev-server', ()=>{
857
943
  if (this.webSocketServer) this.sendMessage(this.webSocketServer.clients, 'invalid');
858
944
  });
859
945
  this.compiler.hooks.done.tap('rspack-dev-server', (stats)=>{
860
- if (this.webSocketServer) this.sendStats(this.webSocketServer.clients, this.getStats(stats));
946
+ if (this.webSocketServer) this.#sendStats(this.webSocketServer.clients, this.#getStats(stats));
861
947
  this.stats = stats;
862
948
  });
863
949
  }
864
- setupWatchStaticFiles() {
950
+ async #setupWatchStaticFiles() {
865
951
  const watchFiles = this.options.static;
866
952
  if (watchFiles.length > 0) {
867
- for (const item of watchFiles)if (item.watch) this.watchFiles(item.directory, item.watch);
953
+ for (const item of watchFiles)if (item.watch) await this.watchFiles(item.directory, item.watch);
868
954
  }
869
955
  }
870
- setupWatchFiles() {
956
+ async #setupWatchFiles() {
871
957
  const watchFiles = this.options.watchFiles;
872
- if (watchFiles.length > 0) for (const item of watchFiles)this.watchFiles(item.paths, item.options);
958
+ if (watchFiles.length > 0) for (const item of watchFiles)await this.watchFiles(item.paths, item.options);
873
959
  }
874
- async setupMiddlewares() {
960
+ async #setupMiddlewares() {
875
961
  let middlewares = [];
876
962
  middlewares.push({
877
963
  name: 'host-header-check',
@@ -910,16 +996,13 @@ class Server {
910
996
  next();
911
997
  }
912
998
  });
913
- if (this.options.compress) {
914
- const { default: compression } = await import("compression");
915
- middlewares.push({
916
- name: 'compression',
917
- middleware: compression()
918
- });
919
- }
999
+ if (this.options.compress) middlewares.push({
1000
+ name: 'compression',
1001
+ middleware: src_default()()
1002
+ });
920
1003
  if (void 0 !== this.options.headers) middlewares.push({
921
1004
  name: 'set-headers',
922
- middleware: this.setHeaders.bind(this)
1005
+ middleware: this.#setHeaders.bind(this)
923
1006
  });
924
1007
  middlewares.push({
925
1008
  name: 'webpack-dev-middleware',
@@ -1056,17 +1139,6 @@ class Server {
1056
1139
  middleware: getServeStatic()(staticOption.directory, staticOption.staticOptions)
1057
1140
  });
1058
1141
  }
1059
- if (staticOptions.length > 0) {
1060
- const serveIndex = server_require('serve-index');
1061
- for (const staticOption of staticOptions)for (const publicPath of staticOption.publicPath)if (staticOption.serveIndex) middlewares.push({
1062
- name: 'serve-index',
1063
- path: publicPath,
1064
- middleware: (req, res, next)=>{
1065
- if ('GET' !== req.method && 'HEAD' !== req.method) return next();
1066
- serveIndex(staticOption.directory, staticOption.serveIndex)(req, res, next);
1067
- }
1068
- });
1069
- }
1070
1142
  middlewares.push({
1071
1143
  name: 'options-middleware',
1072
1144
  middleware: (req, res, next)=>{
@@ -1095,7 +1167,7 @@ class Server {
1095
1167
  else if (void 0 !== middleware.path) this.app.use(middleware.path, middleware.middleware);
1096
1168
  else this.app.use(middleware.middleware);
1097
1169
  }
1098
- async createServer() {
1170
+ async #createServer() {
1099
1171
  const { type, options } = this.options.server;
1100
1172
  if ('function' == typeof type) this.server = await type(options, this.app);
1101
1173
  else {
@@ -1116,12 +1188,12 @@ class Server {
1116
1188
  throw error;
1117
1189
  });
1118
1190
  }
1119
- createWebSocketServer() {
1120
- this.webSocketServer = new (this.getServerTransport())(this);
1191
+ #createWebSocketServer() {
1192
+ this.webSocketServer = new (this.#getServerTransport())(this);
1121
1193
  (this.webSocketServer?.implementation).on('connection', (client, request)=>{
1122
1194
  const headers = void 0 !== request ? request.headers : void 0;
1123
1195
  if (!headers) this.logger.warn('webSocketServer implementation must pass headers for the "connection" event');
1124
- if (!headers || !this.isValidHost(headers, 'host') || !this.isValidHost(headers, 'origin') || !this.isSameOrigin(headers)) {
1196
+ if (!headers || !this.isValidHost(headers, 'host') || !this.isValidHost(headers, 'origin') || !this.#isSameOrigin(headers)) {
1125
1197
  this.sendMessage([
1126
1198
  client
1127
1199
  ], 'error', 'Invalid Host/Origin header');
@@ -1152,12 +1224,12 @@ class Server {
1152
1224
  } : overlayConfig);
1153
1225
  }
1154
1226
  if (!this.stats) return;
1155
- this.sendStats([
1227
+ this.#sendStats([
1156
1228
  client
1157
- ], this.getStats(this.stats), true);
1229
+ ], this.#getStats(this.stats), true);
1158
1230
  });
1159
1231
  }
1160
- async openBrowser(defaultOpenTarget) {
1232
+ async #openBrowser(defaultOpenTarget) {
1161
1233
  const { default: open } = await import("./0~open.js").then((mod)=>({
1162
1234
  default: mod.node_modules_open
1163
1235
  }));
@@ -1170,7 +1242,7 @@ class Server {
1170
1242
  });
1171
1243
  }));
1172
1244
  }
1173
- async logStatus() {
1245
+ async #logStatus() {
1174
1246
  const server = this.server;
1175
1247
  if (this.options.ipc) this.logger.info(`Project is running at: "${server?.address()}"`);
1176
1248
  else {
@@ -1219,14 +1291,14 @@ class Server {
1219
1291
  'white',
1220
1292
  'dim'
1221
1293
  ], 'Network:')} ${server_styleText('cyan', networkUrlIPv6)}`);
1222
- if (urlLogs.length && this.shouldLogInfrastructureInfo()) console.log(`${urlLogs.join('\n')}\n`);
1294
+ if (urlLogs.length && this.#shouldLogInfrastructureInfo()) console.log(`${urlLogs.join('\n')}\n`);
1223
1295
  if (this.options.open?.length > 0) {
1224
1296
  const openTarget = prettyPrintURL(this.options.host && '0.0.0.0' !== this.options.host && '::' !== this.options.host ? this.options.host : 'localhost');
1225
- await this.openBrowser(openTarget);
1297
+ await this.#openBrowser(openTarget);
1226
1298
  }
1227
1299
  }
1228
1300
  }
1229
- setHeaders(req, res, next) {
1301
+ #setHeaders(req, res, next) {
1230
1302
  let { headers } = this.options;
1231
1303
  if (headers) {
1232
1304
  if ('function' == typeof headers) headers = headers(req, res, this.middleware ? this.middleware.context : void 0);
@@ -1242,7 +1314,7 @@ class Server {
1242
1314
  }
1243
1315
  next();
1244
1316
  }
1245
- isHostAllowed(value) {
1317
+ #isHostAllowed(value) {
1246
1318
  const { allowedHosts } = this.options;
1247
1319
  if ('all' === allowedHosts) return true;
1248
1320
  if (Array.isArray(allowedHosts) && allowedHosts.length > 0) for (const allowedHost of allowedHosts){
@@ -1259,24 +1331,24 @@ class Server {
1259
1331
  if (DEFAULT_ALLOWED_PROTOCOLS.test(header)) return true;
1260
1332
  const hostname = parseHostnameFromHeader(header);
1261
1333
  if (null === hostname) return false;
1262
- if (this.isHostAllowed(hostname)) return true;
1334
+ if (this.#isHostAllowed(hostname)) return true;
1263
1335
  const isValidHostname = validateHost ? ipaddr.IPv4.isValid(hostname) || ipaddr.IPv6.isValid(hostname) || 'localhost' === hostname || hostname.endsWith('.localhost') || hostname === this.options.host : false;
1264
1336
  return isValidHostname;
1265
1337
  }
1266
- isSameOrigin(headers) {
1338
+ #isSameOrigin(headers) {
1267
1339
  if ('all' === this.options.allowedHosts) return true;
1268
1340
  const originHeader = headers.origin;
1269
1341
  if (!originHeader) return 'all' === this.options.allowedHosts;
1270
1342
  if (DEFAULT_ALLOWED_PROTOCOLS.test(originHeader)) return true;
1271
1343
  const origin = parseHostnameFromHeader(originHeader);
1272
1344
  if (null === origin) return false;
1273
- if (this.isHostAllowed(origin)) return true;
1345
+ if (this.#isHostAllowed(origin)) return true;
1274
1346
  const hostHeader = headers.host;
1275
1347
  if (!hostHeader) return 'all' === this.options.allowedHosts;
1276
1348
  if (DEFAULT_ALLOWED_PROTOCOLS.test(hostHeader)) return true;
1277
1349
  const host = parseHostnameFromHeader(hostHeader);
1278
1350
  if (null === host) return false;
1279
- if (this.isHostAllowed(host)) return true;
1351
+ if (this.#isHostAllowed(host)) return true;
1280
1352
  return origin === host;
1281
1353
  }
1282
1354
  sendMessage(clients, type, data, params) {
@@ -1286,7 +1358,7 @@ class Server {
1286
1358
  params
1287
1359
  }));
1288
1360
  }
1289
- sendStats(clients, stats, force) {
1361
+ #sendStats(clients, stats, force) {
1290
1362
  if (!stats) return;
1291
1363
  const shouldEmit = !force && stats && (!stats.errors || 0 === stats.errors.length) && (!stats.warnings || 0 === stats.warnings.length) && this.currentHash === stats.hash;
1292
1364
  if (shouldEmit) return void this.sendMessage(clients, 'still-ok');
@@ -1304,9 +1376,9 @@ class Server {
1304
1376
  if (stats.errors?.length > 0) this.sendMessage(clients, 'errors', stats.errors);
1305
1377
  } else this.sendMessage(clients, 'ok');
1306
1378
  }
1307
- watchFiles(watchPath, watchOptions) {
1308
- const chokidar = server_require('chokidar');
1309
- const watcher = chokidar.watch(watchPath, watchOptions);
1379
+ async watchFiles(watchPath, watchOptions) {
1380
+ const { watch } = await getChokidar();
1381
+ const watcher = watch(watchPath, watchOptions);
1310
1382
  if (this.options.liveReload) watcher.on('change', (item)=>{
1311
1383
  if (this.webSocketServer) this.sendMessage(this.webSocketServer.clients, 'static-changed', item);
1312
1384
  });
@@ -1316,7 +1388,7 @@ class Server {
1316
1388
  if (this.middleware) this.middleware.invalidate(callback);
1317
1389
  }
1318
1390
  async start() {
1319
- await this.normalizeOptions();
1391
+ await this.#normalizeOptions();
1320
1392
  if (this.options.ipc) await new Promise((resolve, reject)=>{
1321
1393
  const net = server_require('node:net');
1322
1394
  const socket = new net.Socket();
@@ -1339,7 +1411,7 @@ class Server {
1339
1411
  this.options.host = await Server.getHostname(this.options.host);
1340
1412
  this.options.port = await Server.getFreePort(this.options.port, this.options.host);
1341
1413
  }
1342
- await this.initialize();
1414
+ await this.#initialize();
1343
1415
  const listenOptions = this.options.ipc ? {
1344
1416
  path: this.options.ipc
1345
1417
  } : {
@@ -1355,8 +1427,8 @@ class Server {
1355
1427
  const READ_WRITE = 438;
1356
1428
  await promises.chmod(this.options.ipc, READ_WRITE);
1357
1429
  }
1358
- if (this.options.webSocketServer) this.createWebSocketServer();
1359
- await this.logStatus();
1430
+ if (this.options.webSocketServer) this.#createWebSocketServer();
1431
+ await this.#logStatus();
1360
1432
  if ('function' == typeof this.options.onListening) this.options.onListening(this);
1361
1433
  }
1362
1434
  startCallback(callback = ()=>{}) {
@@ -15,6 +15,15 @@ __webpack_require__.m = __webpack_modules__;
15
15
  Object.assign(__webpack_require__.m, modules);
16
16
  };
17
17
  })();
18
+ (()=>{
19
+ __webpack_require__.n = (module)=>{
20
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
21
+ __webpack_require__.d(getter, {
22
+ a: getter
23
+ });
24
+ return getter;
25
+ };
26
+ })();
18
27
  (()=>{
19
28
  var getProto = Object.getPrototypeOf ? (obj)=>Object.getPrototypeOf(obj) : (obj)=>obj.__proto__;
20
29
  var leafPrototypes;
package/dist/server.d.ts CHANGED
@@ -7,9 +7,9 @@
7
7
  * Copyright (c) JS Foundation and other contributors
8
8
  * https://github.com/webpack/webpack-dev-server/blob/main/LICENSE
9
9
  */
10
- import type { BasicApplication, ClientConfiguration, ClientConnection, Compiler, ConnectHistoryApiFallbackOptions, DevMiddlewareContext, DevMiddlewareOptions, DevServer, EXPECTED_ANY, FSWatcher, HTTPServer, Headers, Host, LiteralUnion, Middleware, MultiCompiler, MultiStats, NextFunction, Open, Port, ProxyConfigArray, Request, RequestHandler, Response, ServerConfiguration, ServerType, Socket, Static, Stats, StatsCompilation, StatsOptions, WatchFiles, WatchOptions, WebSocketServerConfiguration, WebSocketServerImplementation } from './types';
10
+ import type { BasicApplication, BasicServer, ClientConfiguration, ClientConnection, Compiler, ConnectHistoryApiFallbackOptions, DevMiddlewareContext, DevMiddlewareOptions, DevServer, EXPECTED_ANY, FSWatcher, HTTPServer, Headers, Host, LiteralUnion, Middleware, MultiCompiler, MultiStats, Open, Port, ProxyConfigArray, Request, RequestHandler, Response, ServerConfiguration, ServerType, Socket, Static, Stats, StatsOptions, WatchFiles, WatchOptions, WebSocketServerConfiguration, WebSocketServerImplementation } from './types';
11
11
  import type { ConnectApplication } from './types';
12
- export interface Configuration<A extends BasicApplication = ConnectApplication, S extends HTTPServer = HTTPServer> {
12
+ export interface Configuration<A extends BasicApplication = ConnectApplication, S extends BasicServer = HTTPServer> {
13
13
  ipc?: boolean | string;
14
14
  host?: Host;
15
15
  port?: Port;
@@ -32,7 +32,8 @@ export interface Configuration<A extends BasicApplication = ConnectApplication,
32
32
  onListening?: (devServer: Server<A, S>) => void;
33
33
  setupMiddlewares?: (middlewares: Middleware[], devServer: Server<A, S>) => Middleware[];
34
34
  }
35
- declare class Server<A extends BasicApplication = ConnectApplication, S extends import('http').Server = HTTPServer> {
35
+ declare class Server<A extends BasicApplication = ConnectApplication, S extends BasicServer = HTTPServer> {
36
+ #private;
36
37
  compiler: Compiler | MultiCompiler;
37
38
  logger: ReturnType<Compiler['getInfrastructureLogger']>;
38
39
  options: Configuration<A, S>;
@@ -57,49 +58,11 @@ declare class Server<A extends BasicApplication = ConnectApplication, S extends
57
58
  static getHostname(hostname: Host): Promise<string>;
58
59
  static getFreePort(port: string, host: string): Promise<string | number>;
59
60
  static findCacheDir(): string;
60
- addAdditionalEntries(compiler: Compiler): void;
61
- /**
62
- * @private
63
- * @returns {Compiler["options"]} compiler options
64
- */
65
- getCompilerOptions(): import("@rspack/core").RspackOptionsNormalized;
66
- shouldLogInfrastructureInfo(): boolean;
67
- normalizeOptions(): Promise<void>;
68
- /**
69
- * @private
70
- * @returns {string} client transport
71
- */
72
- getClientTransport(): string;
73
- getServerTransport(): unknown;
74
61
  getClientEntry(): string;
75
62
  getClientHotEntry(): string | undefined;
76
- setupProgressPlugin(): void;
77
- /**
78
- * @private
79
- * @returns {Promise<void>}
80
- */
81
- initialize(): Promise<void>;
82
- setupApp(): Promise<void>;
83
- getStats(statsObj: Stats | MultiStats): StatsCompilation;
84
- setupHooks(): void;
85
- setupWatchStaticFiles(): void;
86
- setupWatchFiles(): void;
87
- setupMiddlewares(): Promise<void>;
88
- /**
89
- * @private
90
- * @returns {Promise<void>}
91
- */
92
- createServer(): Promise<void>;
93
- createWebSocketServer(): void;
94
- openBrowser(defaultOpenTarget: string): Promise<void>;
95
- logStatus(): Promise<void>;
96
- setHeaders(req: Request, res: Response, next: NextFunction): void;
97
- isHostAllowed(value: string): boolean;
98
63
  isValidHost(headers: Record<string, string | undefined>, headerToCheck: string, validateHost?: boolean): boolean;
99
- isSameOrigin(headers: Record<string, string | undefined>): boolean;
100
64
  sendMessage(clients: ClientConnection[], type: string, data?: EXPECTED_ANY, params?: EXPECTED_ANY): void;
101
- sendStats(clients: ClientConnection[], stats: StatsCompilation, force?: boolean): void;
102
- watchFiles(watchPath: string | string[], watchOptions?: WatchOptions): void;
65
+ watchFiles(watchPath: string | string[], watchOptions?: WatchOptions): Promise<void>;
103
66
  invalidate(callback?: import('webpack-dev-middleware').Callback): void;
104
67
  start(): Promise<void>;
105
68
  startCallback(callback?: (err?: Error) => void): void;
package/dist/types.d.ts CHANGED
@@ -1,22 +1,18 @@
1
1
  import type { Server as HTTPServer, IncomingMessage, ServerResponse } from 'node:http';
2
- export type { HTTPServer, IncomingMessage };
2
+ import type { ServerOptions } from 'node:https';
3
+ import type { FSWatcher, ChokidarOptions as WatchOptions } from 'chokidar';
4
+ import type { Options as ConnectHistoryApiFallbackOptions } from 'connect-history-api-fallback';
5
+ import type { Server as ConnectApplication, IncomingMessage as ConnectIncomingMessage } from 'connect-next';
6
+ import type { Options as HttpProxyMiddlewareOptions, Filter as HttpProxyMiddlewareOptionsFilter, RequestHandler } from 'http-proxy-middleware';
7
+ import type { ServeStaticOptions } from 'serve-static';
8
+ export type { FSWatcher, WatchOptions, RequestHandler, BasicServer, HTTPServer, ServerOptions, IncomingMessage, ConnectApplication, ConnectHistoryApiFallbackOptions, };
9
+ export type { IPv6 } from 'ipaddr.js';
3
10
  export type { Socket } from 'node:net';
4
11
  export type { AddressInfo } from 'node:net';
5
12
  export type { NetworkInterfaceInfo } from 'node:os';
6
13
  export type { Compiler, DevServer, MultiCompiler, MultiStats, Stats, StatsCompilation, StatsOptions, } from '@rspack/core';
7
- import type { FSWatcher, WatchOptions } from 'chokidar';
8
- export type { FSWatcher, WatchOptions };
9
- import type { Server as ConnectApplication, IncomingMessage as ConnectIncomingMessage } from 'connect-next';
10
- export type { ConnectApplication };
11
- import type { Options as ConnectHistoryApiFallbackOptions } from 'connect-history-api-fallback';
12
- export type { ConnectHistoryApiFallbackOptions };
13
- import type { Options as HttpProxyMiddlewareOptions, Filter as HttpProxyMiddlewareOptionsFilter, RequestHandler } from 'http-proxy-middleware';
14
- export type { RequestHandler };
15
- export type { IPv6 } from 'ipaddr.js';
16
- import type { Options as ServeIndexOptions } from 'serve-index';
17
- export type { ServeIndexOptions };
18
- import type { ServeStaticOptions } from 'serve-static';
19
14
  export type EXPECTED_ANY = any;
15
+ type BasicServer = import('node:net').Server | import('node:tls').Server;
20
16
  /** https://github.com/microsoft/TypeScript/issues/29729 */
21
17
  export type LiteralUnion<T extends U, U> = T | (U & Record<never, never>);
22
18
  export type NextFunction = (err?: EXPECTED_ANY) => void;
@@ -24,7 +20,6 @@ export type SimpleHandleFunction = (req: IncomingMessage, res: ServerResponse) =
24
20
  export type NextHandleFunction = (req: IncomingMessage, res: ServerResponse, next: NextFunction) => void;
25
21
  export type ErrorHandleFunction = (err: EXPECTED_ANY, req: IncomingMessage, res: ServerResponse, next: NextFunction) => void;
26
22
  export type HandleFunction = SimpleHandleFunction | NextHandleFunction | ErrorHandleFunction;
27
- export type ServerOptions = import('https').ServerOptions;
28
23
  export type Request<T extends BasicApplication = ConnectApplication> = T extends ConnectApplication ? ConnectIncomingMessage : IncomingMessage;
29
24
  export type Response = ServerResponse;
30
25
  export type DevMiddlewareOptions<T extends Request, U extends Response> = import('webpack-dev-middleware').Options<T, U>;
@@ -35,30 +30,23 @@ export interface WatchFiles {
35
30
  paths: string | string[];
36
31
  options?: WatchOptions & {
37
32
  aggregateTimeout?: number;
38
- ignored?: WatchOptions['ignored'];
39
33
  poll?: number | boolean;
40
34
  };
41
35
  }
42
36
  export interface Static {
43
37
  directory?: string;
44
38
  publicPath?: string | string[];
45
- serveIndex?: boolean | ServeIndexOptions;
46
39
  staticOptions?: ServeStaticOptions;
47
- watch?: boolean | (WatchOptions & {
48
- aggregateTimeout?: number;
49
- ignored?: WatchOptions['ignored'];
50
- poll?: number | boolean;
51
- });
40
+ watch?: boolean | NonNullable<WatchFiles['options']>;
52
41
  }
53
42
  export interface NormalizedStatic {
54
43
  directory: string;
55
44
  publicPath: string[];
56
- serveIndex: false | ServeIndexOptions;
57
45
  staticOptions: ServeStaticOptions;
58
46
  watch: false | WatchOptions;
59
47
  }
60
- export type ServerType<A extends BasicApplication = ConnectApplication, S extends import('http').Server = import('http').Server> = LiteralUnion<'http' | 'https' | 'http2', string> | ((serverOptions: ServerOptions, application: A) => S);
61
- export interface ServerConfiguration<A extends BasicApplication = ConnectApplication, S extends import('http').Server = import('http').Server> {
48
+ export type ServerType<A extends BasicApplication, S extends BasicServer> = LiteralUnion<'http' | 'https' | 'http2', string> | ((serverOptions: ServerOptions, application: A) => S);
49
+ export interface ServerConfiguration<A extends BasicApplication = ConnectApplication, S extends BasicServer = HTTPServer> {
62
50
  type?: ServerType<A, S>;
63
51
  options?: ServerOptions;
64
52
  }
@@ -125,7 +113,6 @@ export interface MiddlewareObject {
125
113
  middleware: MiddlewareHandler;
126
114
  }
127
115
  export type Middleware = MiddlewareObject | MiddlewareHandler;
128
- export type BasicServer = import('net').Server | import('tls').Server;
129
116
  export type OverlayMessageOptions = boolean | ((error: Error) => void);
130
117
  declare function useFn(fn: NextHandleFunction): BasicApplication;
131
118
  declare function useFn(fn: HandleFunction): BasicApplication;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rspack/dev-server",
3
- "version": "2.0.0-beta.3",
3
+ "version": "2.0.0-beta.5",
4
4
  "description": "Development server for rspack",
5
5
  "homepage": "https://rspack.rs",
6
6
  "bugs": "https://github.com/rstackjs/rspack-dev-server/issues",
@@ -46,16 +46,14 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "@types/connect-history-api-fallback": "^1.5.4",
49
- "@types/serve-index": "^1.9.4",
50
49
  "@types/serve-static": "^2.2.0",
51
50
  "@types/ws": "^8.18.1",
52
- "chokidar": "^3.6.0",
53
- "connect-next": "^4.0.0",
51
+ "chokidar": "^5.0.0",
54
52
  "connect-history-api-fallback": "^2.0.0",
53
+ "connect-next": "^4.0.0",
55
54
  "http-proxy-middleware": "^3.0.5",
56
55
  "ipaddr.js": "^2.3.0",
57
56
  "serve-static": "^2.2.1",
58
- "serve-index": "^1.9.2",
59
57
  "webpack-dev-middleware": "^7.4.5",
60
58
  "ws": "^8.19.0"
61
59
  },
@@ -66,17 +64,16 @@
66
64
  "@rspack/core": "2.0.0-beta.5",
67
65
  "@rspack/plugin-react-refresh": "1.6.1",
68
66
  "@rstest/core": "^0.9.0",
69
- "@types/compression": "^1.8.1",
70
67
  "@types/mime-types": "3.0.1",
71
68
  "@types/node": "^24.12.0",
72
69
  "@types/node-forge": "^1.3.14",
73
70
  "@types/trusted-types": "^2.0.7",
74
71
  "@types/ws": "8.18.1",
75
- "express": "^5.2.1",
76
- "compression": "^1.8.1",
77
72
  "cross-env": "^10.1.0",
78
73
  "css-loader": "^7.1.4",
74
+ "express": "^5.2.1",
79
75
  "hono": "^4.12.5",
76
+ "http-compression": "^1.1.2",
80
77
  "http-proxy": "^1.18.1",
81
78
  "launch-editor": "^2.13.1",
82
79
  "nano-staged": "^0.9.0",