@rsbuild/core 1.4.3 → 1.4.4

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.
@@ -1 +1 @@
1
- {"name":"rslog","version":"1.2.8","types":"index.d.ts","type":"commonjs"}
1
+ {"name":"rslog","version":"1.2.9","license":"MIT","types":"index.d.ts","type":"commonjs"}
@@ -1,4 +1,3 @@
1
- const compilationId = RSBUILD_COMPILATION_NAME;
2
1
  const hmr_config = RSBUILD_CLIENT_CONFIG;
3
2
  const resolvedConfig = RSBUILD_RESOLVED_CLIENT_CONFIG;
4
3
  function formatURL(config) {
@@ -6,18 +5,18 @@ function formatURL(config) {
6
5
  const hostname = config.host || location.hostname;
7
6
  const port = config.port || location.port;
8
7
  const protocol = config.protocol || ('https:' === location.protocol ? 'wss' : 'ws');
9
- const pathname = config.path || '/rsbuild-hmr';
8
+ const pathname = config.path;
10
9
  if ('undefined' != typeof URL) {
11
10
  const url = new URL('http://localhost');
12
11
  url.port = String(port);
13
12
  url.hostname = hostname;
14
13
  url.protocol = protocol;
15
14
  url.pathname = pathname;
16
- url.searchParams.append('compilationId', compilationId);
15
+ url.searchParams.append('token', RSBUILD_WEB_SOCKET_TOKEN);
17
16
  return url.toString();
18
17
  }
19
18
  const colon = -1 === protocol.indexOf(':') ? ':' : '';
20
- return `${protocol}${colon}//${hostname}:${port}${pathname}`;
19
+ return `${protocol}${colon}//${hostname}:${port}${pathname}?token=${RSBUILD_WEB_SOCKET_TOKEN}`;
21
20
  }
22
21
  let isFirstCompilation = true;
23
22
  let lastCompilationHash = null;
@@ -87,7 +86,6 @@ function onOpen() {
87
86
  }
88
87
  function onMessage(e) {
89
88
  const message = JSON.parse(e.data);
90
- if (message.compilationId && message.compilationId !== compilationId) return;
91
89
  switch(message.type){
92
90
  case 'hash':
93
91
  lastCompilationHash = message.data;
package/dist/index.cjs CHANGED
@@ -866,6 +866,12 @@ var __webpack_modules__ = {
866
866
  module.exports = import("node:vm").then(function(module) {
867
867
  return module;
868
868
  });
869
+ },
870
+ "node:zlib": function(module) {
871
+ "use strict";
872
+ module.exports = import("node:zlib").then(function(module) {
873
+ return module;
874
+ });
869
875
  }
870
876
  }, __webpack_module_cache__ = {};
871
877
  function __webpack_require__(moduleId) {
@@ -946,7 +952,7 @@ for(var __webpack_i__ in (()=>{
946
952
  node: [
947
953
  'node >= 16'
948
954
  ]
949
- }, HTML_REGEX = /\.html$/, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
955
+ }, HTML_REGEX = /\.html$/, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, RAW_QUERY_REGEX = /^\?raw$/, INLINE_QUERY_REGEX = /^\?inline$/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
950
956
  'woff',
951
957
  'woff2',
952
958
  'eot',
@@ -2219,7 +2225,7 @@ ${section.body}` : section.body).join("\n\n"));
2219
2225
  }, {});
2220
2226
  async function updateEnvironmentContext(context, configs) {
2221
2227
  for (let [index, [name, config]] of (context.environments ||= {}, Object.entries(configs).entries())){
2222
- let browserslist = await getBrowserslistByEnvironment(context.rootPath, config), { entry = {}, tsconfigPath } = config.source, htmlPaths = getEnvironmentHTMLPaths(entry, config), environmentContext = {
2228
+ let browserslist = await getBrowserslistByEnvironment(context.rootPath, config), { entry = {}, tsconfigPath } = config.source, htmlPaths = getEnvironmentHTMLPaths(entry, config), webSocketToken = 'dev' === context.action ? await helpers_hash(context.rootPath + name) : '', environmentContext = {
2223
2229
  index,
2224
2230
  name,
2225
2231
  distPath: function(cwd, config) {
@@ -2230,7 +2236,8 @@ ${section.body}` : section.body).join("\n\n"));
2230
2236
  browserslist,
2231
2237
  htmlPaths,
2232
2238
  tsconfigPath,
2233
- config
2239
+ config,
2240
+ webSocketToken
2234
2241
  };
2235
2242
  context.environments[name] = new Proxy(environmentContext, {
2236
2243
  get: (target, prop)=>target[prop],
@@ -2241,7 +2248,7 @@ ${section.body}` : section.body).join("\n\n"));
2241
2248
  async function createContext(options, userConfig) {
2242
2249
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = (0, external_node_path_namespaceObject.join)(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
2243
2250
  return {
2244
- version: "1.4.3",
2251
+ version: "1.4.4",
2245
2252
  rootPath,
2246
2253
  distPath: '',
2247
2254
  cachePath,
@@ -2938,7 +2945,7 @@ ${section.body}` : section.body).join("\n\n"));
2938
2945
  let generatorOptions = {
2939
2946
  filename
2940
2947
  };
2941
- !1 === emit && (generatorOptions.emit = !1), rule.oneOf(`${assetType}-asset-url`).type('asset/resource').resourceQuery(/(__inline=false|url)/).set('generator', generatorOptions), rule.oneOf(`${assetType}-asset-inline`).type('asset/inline').resourceQuery(/inline/), rule.oneOf(`${assetType}-asset-raw`).type('asset/source').resourceQuery(/raw/), rule.oneOf(`${assetType}-asset`).type('asset').parser({
2948
+ !1 === emit && (generatorOptions.emit = !1), rule.oneOf(`${assetType}-asset-url`).type('asset/resource').resourceQuery(/^\?(__inline=false|url)$/).set('generator', generatorOptions), rule.oneOf(`${assetType}-asset-inline`).type('asset/inline').resourceQuery(INLINE_QUERY_REGEX), rule.oneOf(`${assetType}-asset-raw`).type('asset/source').resourceQuery(RAW_QUERY_REGEX), rule.oneOf(`${assetType}-asset`).type('asset').parser({
2942
2949
  dataUrlCondition: {
2943
2950
  maxSize
2944
2951
  }
@@ -3874,9 +3881,6 @@ ${section.body}` : section.body).join("\n\n"));
3874
3881
  })
3875
3882
  });
3876
3883
  return addressUrls;
3877
- }, COMPILATION_ID_REGEX = /[^a-zA-Z0-9_-]/g, getCompilationId = (compiler)=>{
3878
- let uniqueName = compiler.options.output.uniqueName ?? '';
3879
- return `${compiler.name ?? ''}_${uniqueName.replace(COMPILATION_ID_REGEX, '_')}`;
3880
3884
  };
3881
3885
  function getServerTerminator(server) {
3882
3886
  let listened = !1, pendingSockets = new Set(), onConnection = (socket)=>{
@@ -4349,13 +4353,15 @@ ${section.body}` : section.body).join("\n\n"));
4349
4353
  }
4350
4354
  let getCompilationMiddleware = async (compiler, options)=>{
4351
4355
  let { default: rsbuildDevMiddleware } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "../../compiled/rsbuild-dev-middleware/index.js")), { clientPaths, callbacks, devConfig, serverConfig } = options, resolvedClientConfig = await getResolvedClientConfig(devConfig.client, serverConfig);
4352
- return applyToCompiler(compiler, (compiler)=>{
4353
- clientPaths && function({ compiler, clientPaths, devConfig, resolvedClientConfig }) {
4356
+ return applyToCompiler(compiler, (compiler, index)=>{
4357
+ var _Object_values_find;
4358
+ let token = null == (_Object_values_find = Object.values(options.environments).find((env)=>env.index === index)) ? void 0 : _Object_values_find.webSocketToken;
4359
+ token && (clientPaths && function({ compiler, clientPaths, devConfig, resolvedClientConfig, token }) {
4354
4360
  if (((compiler)=>{
4355
4361
  let { target } = compiler.options;
4356
4362
  return !!target && (Array.isArray(target) ? target.includes('web') : 'web' === target);
4357
4363
  })(compiler)) for (let clientPath of (new compiler.webpack.DefinePlugin({
4358
- RSBUILD_COMPILATION_NAME: JSON.stringify(getCompilationId(compiler)),
4364
+ RSBUILD_WEB_SOCKET_TOKEN: JSON.stringify(token),
4359
4365
  RSBUILD_CLIENT_CONFIG: JSON.stringify(devConfig.client),
4360
4366
  RSBUILD_RESOLVED_CLIENT_CONFIG: JSON.stringify(resolvedClientConfig),
4361
4367
  RSBUILD_DEV_LIVE_RELOAD: devConfig.liveReload
@@ -4366,19 +4372,26 @@ ${section.body}` : section.body).join("\n\n"));
4366
4372
  compiler,
4367
4373
  clientPaths,
4368
4374
  devConfig,
4369
- resolvedClientConfig
4370
- }), ((compiler, { onDone, onInvalid })=>{
4375
+ resolvedClientConfig,
4376
+ token
4377
+ }), (({ compiler, token, callbacks: { onDone, onInvalid } })=>{
4371
4378
  if (((compiler)=>{
4372
4379
  let { target } = compiler.options;
4373
4380
  return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
4374
4381
  })(compiler)) return;
4375
4382
  let { compile, invalid, done } = compiler.hooks;
4376
4383
  compile.tap('rsbuild-dev-server', ()=>{
4377
- onInvalid(getCompilationId(compiler));
4384
+ onInvalid(token);
4378
4385
  }), invalid.tap('rsbuild-dev-server', (fileName)=>{
4379
- onInvalid(getCompilationId(compiler), fileName);
4380
- }), done.tap('rsbuild-dev-server', onDone);
4381
- })(compiler, callbacks);
4386
+ onInvalid(token, fileName);
4387
+ }), done.tap('rsbuild-dev-server', (stats)=>{
4388
+ onDone(token, stats);
4389
+ });
4390
+ })({
4391
+ compiler,
4392
+ callbacks,
4393
+ token
4394
+ }));
4382
4395
  }), rsbuildDevMiddleware(compiler, {
4383
4396
  etag: 'weak',
4384
4397
  publicPath: '/',
@@ -4424,6 +4437,10 @@ ${section.body}` : section.body).join("\n\n"));
4424
4437
  writable: !0
4425
4438
  }) : obj[key] = value, obj;
4426
4439
  }
4440
+ let parseQueryString = (req)=>{
4441
+ let queryStr = req.url ? req.url.split('?')[1] : '';
4442
+ return queryStr ? Object.fromEntries(new URLSearchParams(queryStr)) : {};
4443
+ };
4427
4444
  class SocketServer {
4428
4445
  clearHeartbeatTimer() {
4429
4446
  this.heartbeatTimer && (clearTimeout(this.heartbeatTimer), this.heartbeatTimer = null);
@@ -4438,51 +4455,44 @@ ${section.body}` : section.body).join("\n\n"));
4438
4455
  }), this.wsServer.on('error', (err)=>{
4439
4456
  index_js_namespaceObject.logger.error(err);
4440
4457
  }), this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref(), this.wsServer.on('connection', (socket, req)=>{
4441
- let queryStr = req.url ? req.url.split('?')[1] : '';
4442
- this.onConnect(socket, queryStr ? Object.fromEntries(new URLSearchParams(queryStr)) : {});
4458
+ let query = parseQueryString(req);
4459
+ this.onConnect(socket, query.token);
4443
4460
  });
4444
4461
  }
4445
- updateStats(stats) {
4446
- let compilationId = getCompilationId(stats.compilation);
4447
- this.stats[compilationId] = stats, this.sockets.length && this.sendStats({
4448
- compilationId
4462
+ updateStats(stats, token) {
4463
+ this.stats[token] = stats, this.sockets.size && this.sendStats({
4464
+ token
4449
4465
  });
4450
4466
  }
4451
- sockWrite({ type, compilationId, data }) {
4452
- for (let socket of this.sockets)this.send(socket, JSON.stringify({
4453
- type,
4454
- data,
4455
- compilationId
4456
- }));
4467
+ sockWrite(message, token) {
4468
+ let messageStr = JSON.stringify(message);
4469
+ if (token) {
4470
+ let socket = this.sockets.get(token);
4471
+ socket && this.send(socket, messageStr);
4472
+ } else for (let socket of this.sockets.values())this.send(socket, messageStr);
4457
4473
  }
4458
- singleWrite(socket, { type, data, compilationId }) {
4459
- this.send(socket, JSON.stringify({
4460
- type,
4461
- data,
4462
- compilationId
4463
- }));
4474
+ singleWrite(socket, message) {
4475
+ this.send(socket, JSON.stringify(message));
4464
4476
  }
4465
4477
  async close() {
4466
4478
  for (let socket of (this.clearHeartbeatTimer(), this.wsServer.removeAllListeners(), this.wsServer.clients))socket.terminate();
4467
- for (let socket of this.sockets)socket.close();
4468
- return this.stats = {}, this.initialChunks = {}, this.sockets.length = 0, new Promise((resolve, reject)=>{
4479
+ for (let socket of this.sockets.values())socket.close();
4480
+ return this.stats = {}, this.initialChunks = {}, this.sockets.clear(), new Promise((resolve, reject)=>{
4469
4481
  this.wsServer.close((err)=>{
4470
4482
  err ? reject(err) : resolve();
4471
4483
  });
4472
4484
  });
4473
4485
  }
4474
- onConnect(socket, params) {
4486
+ onConnect(socket, token) {
4475
4487
  socket.isAlive = !0, socket.on('pong', ()=>{
4476
4488
  socket.isAlive = !0;
4477
- }), this.sockets.push(socket), socket.on('close', ()=>{
4478
- let index = this.sockets.indexOf(socket);
4479
- index >= 0 && this.sockets.splice(index, 1);
4489
+ }), this.sockets.set(token, socket), socket.on('close', ()=>{
4490
+ this.sockets.delete(token);
4480
4491
  }), (this.options.hmr || this.options.liveReload) && this.singleWrite(socket, {
4481
- type: 'hot',
4482
- compilationId: params.compilationId
4492
+ type: 'hot'
4483
4493
  }), this.stats && this.sendStats({
4484
4494
  force: !0,
4485
- compilationId: params.compilationId
4495
+ token
4486
4496
  });
4487
4497
  }
4488
4498
  getStats(name) {
@@ -4507,38 +4517,34 @@ ${section.body}` : section.body).join("\n\n"));
4507
4517
  root: curStats.compilation.compiler.options.context
4508
4518
  } : null;
4509
4519
  }
4510
- sendStats({ force = !1, compilationId }) {
4520
+ sendStats({ force = !1, token }) {
4511
4521
  var a, b;
4512
- let result = this.getStats(compilationId);
4522
+ let result = this.getStats(token);
4513
4523
  if (!result) return null;
4514
4524
  let { statsJson, root } = result, newInitialChunks = new Set();
4515
4525
  if (statsJson.entrypoints) for (let entrypoint of Object.values(statsJson.entrypoints)){
4516
4526
  let chunks = entrypoint.chunks;
4517
4527
  if (Array.isArray(chunks)) for (let chunkName of chunks)chunkName && newInitialChunks.add(String(chunkName));
4518
4528
  }
4519
- let initialChunks = this.initialChunks[compilationId], shouldReload = !!statsJson.entrypoints && !!initialChunks && (a = initialChunks, b = newInitialChunks, !(a.size === b.size && [
4529
+ let initialChunks = this.initialChunks[token], shouldReload = !!statsJson.entrypoints && !!initialChunks && (a = initialChunks, b = newInitialChunks, !(a.size === b.size && [
4520
4530
  ...a
4521
4531
  ].every((value)=>b.has(value))));
4522
- if (this.initialChunks[compilationId] = newInitialChunks, shouldReload) return this.sockWrite({
4523
- type: 'static-changed',
4524
- compilationId
4525
- });
4532
+ if (this.initialChunks[token] = newInitialChunks, shouldReload) return this.sockWrite({
4533
+ type: 'static-changed'
4534
+ }, token);
4526
4535
  if (!force && statsJson && !statsJson.errorsCount && statsJson.assets && statsJson.assets.every((asset)=>!asset.emitted)) return this.sockWrite({
4527
- type: 'ok',
4528
- compilationId
4529
- });
4536
+ type: 'ok'
4537
+ }, token);
4530
4538
  if (this.sockWrite({
4531
4539
  type: 'hash',
4532
- compilationId,
4533
4540
  data: statsJson.hash
4534
- }), statsJson.errorsCount) {
4541
+ }, token), statsJson.errorsCount) {
4535
4542
  let { errors: formattedErrors } = formatStatsMessages({
4536
4543
  errors: getAllStatsErrors(statsJson),
4537
4544
  warnings: []
4538
4545
  });
4539
4546
  return this.sockWrite({
4540
4547
  type: 'errors',
4541
- compilationId,
4542
4548
  data: {
4543
4549
  text: formattedErrors,
4544
4550
  html: function(errors, root) {
@@ -4696,7 +4702,7 @@ ${section.body}` : section.body).join("\n\n"));
4696
4702
  `;
4697
4703
  }(formattedErrors, root)
4698
4704
  }
4699
- });
4705
+ }, token);
4700
4706
  }
4701
4707
  if (statsJson.warningsCount) {
4702
4708
  let { warnings: formattedWarnings } = formatStatsMessages({
@@ -4705,29 +4711,30 @@ ${section.body}` : section.body).join("\n\n"));
4705
4711
  });
4706
4712
  return this.sockWrite({
4707
4713
  type: 'warnings',
4708
- compilationId,
4709
4714
  data: {
4710
4715
  text: formattedWarnings
4711
4716
  }
4712
- });
4717
+ }, token);
4713
4718
  }
4714
4719
  return this.sockWrite({
4715
- type: 'ok',
4716
- compilationId
4717
- });
4720
+ type: 'ok'
4721
+ }, token);
4718
4722
  }
4719
4723
  send(connection, message) {
4720
4724
  1 === connection.readyState && connection.send(message);
4721
4725
  }
4722
- constructor(options){
4723
- socketServer_define_property(this, "wsServer", void 0), socketServer_define_property(this, "sockets", []), socketServer_define_property(this, "options", void 0), socketServer_define_property(this, "stats", void 0), socketServer_define_property(this, "initialChunks", void 0), socketServer_define_property(this, "heartbeatTimer", null), socketServer_define_property(this, "upgrade", (req, sock, head)=>{
4724
- this.wsServer.shouldHandle(req) && this.wsServer.handleUpgrade(req, sock, head, (connection)=>{
4726
+ constructor(options, environments){
4727
+ socketServer_define_property(this, "wsServer", void 0), socketServer_define_property(this, "sockets", new Map()), socketServer_define_property(this, "options", void 0), socketServer_define_property(this, "stats", void 0), socketServer_define_property(this, "initialChunks", void 0), socketServer_define_property(this, "heartbeatTimer", null), socketServer_define_property(this, "environments", void 0), socketServer_define_property(this, "upgrade", (req, socket, head)=>{
4728
+ if (!this.wsServer.shouldHandle(req)) return;
4729
+ let query = parseQueryString(req);
4730
+ if (!Object.values(this.environments).map((env)=>env.webSocketToken).includes(query.token)) return void socket.destroy();
4731
+ this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
4725
4732
  this.wsServer.emit('connection', connection, req);
4726
4733
  });
4727
4734
  }), socketServer_define_property(this, "checkSockets", ()=>{
4728
4735
  for (let socket of this.wsServer.clients)socket.isAlive ? (socket.isAlive = !1, socket.ping(()=>{})) : socket.terminate();
4729
4736
  null !== this.heartbeatTimer && (this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref());
4730
- }), this.options = options, this.stats = {}, this.initialChunks = {};
4737
+ }), this.options = options, this.stats = {}, this.initialChunks = {}, this.environments = environments;
4731
4738
  }
4732
4739
  }
4733
4740
  function compilationManager_define_property(obj, key, value) {
@@ -4760,29 +4767,28 @@ ${section.body}` : section.body).join("\n\n"));
4760
4767
  });
4761
4768
  }
4762
4769
  async setupCompilationMiddleware() {
4763
- let { devConfig, serverConfig, publicPaths } = this, clientPaths = function(devConfig) {
4770
+ let { devConfig, serverConfig, publicPaths, environments } = this, clientPaths = function(devConfig) {
4764
4771
  var _devConfig_client;
4765
4772
  let clientPaths = [];
4766
4773
  return (devConfig.hmr || devConfig.liveReload) && (clientPaths.push(compilationManager_require.resolve('@rsbuild/core/client/hmr')), (null == (_devConfig_client = devConfig.client) ? void 0 : _devConfig_client.overlay) && clientPaths.push(`${compilationManager_require.resolve('@rsbuild/core/client/overlay')}`)), clientPaths;
4767
4774
  }(devConfig), middleware = await getCompilationMiddleware(this.compiler, {
4768
4775
  callbacks: {
4769
- onInvalid: (compilationId, fileName)=>{
4776
+ onInvalid: (token, fileName)=>{
4770
4777
  if ('string' == typeof fileName && HTML_REGEX.test(fileName)) return void this.socketServer.sockWrite({
4771
- type: 'static-changed',
4772
- compilationId
4773
- });
4778
+ type: 'static-changed'
4779
+ }, token);
4774
4780
  this.socketServer.sockWrite({
4775
- type: 'invalid',
4776
- compilationId
4777
- });
4781
+ type: 'invalid'
4782
+ }, token);
4778
4783
  },
4779
- onDone: (stats)=>{
4780
- this.socketServer.updateStats(stats);
4784
+ onDone: (token, stats)=>{
4785
+ this.socketServer.updateStats(stats, token);
4781
4786
  }
4782
4787
  },
4783
4788
  clientPaths,
4784
4789
  devConfig,
4785
- serverConfig
4790
+ serverConfig,
4791
+ environments
4786
4792
  }), { base } = serverConfig, assetPrefixes = publicPaths.map(getPathnameFromUrl).map((prefix)=>base && '/' !== base ? stripBase(prefix, base) : prefix), wrapper = async (req, res, next)=>{
4787
4793
  let { url } = req, assetPrefix = url && assetPrefixes.find((prefix)=>url.startsWith(prefix));
4788
4794
  assetPrefix && '/' !== assetPrefix ? (req.url = url.slice(assetPrefix.length - 1), middleware(req, res, (...args)=>{
@@ -4792,7 +4798,7 @@ ${section.body}` : section.body).join("\n\n"));
4792
4798
  wrapper.close = middleware.close, wrapper.watch = middleware.watch, this.middleware = wrapper;
4793
4799
  }
4794
4800
  constructor({ dev, server, compiler, publicPaths, environments }){
4795
- compilationManager_define_property(this, "middleware", void 0), compilationManager_define_property(this, "outputFileSystem", void 0), compilationManager_define_property(this, "devConfig", void 0), compilationManager_define_property(this, "serverConfig", void 0), compilationManager_define_property(this, "compiler", void 0), compilationManager_define_property(this, "publicPaths", void 0), compilationManager_define_property(this, "socketServer", void 0), compilationManager_define_property(this, "readFileSync", (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : external_node_fs_default().readFileSync(fileName, 'utf-8')), this.devConfig = ((config, environments)=>{
4801
+ compilationManager_define_property(this, "middleware", void 0), compilationManager_define_property(this, "outputFileSystem", void 0), compilationManager_define_property(this, "devConfig", void 0), compilationManager_define_property(this, "serverConfig", void 0), compilationManager_define_property(this, "compiler", void 0), compilationManager_define_property(this, "environments", void 0), compilationManager_define_property(this, "publicPaths", void 0), compilationManager_define_property(this, "socketServer", void 0), compilationManager_define_property(this, "readFileSync", (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : external_node_fs_default().readFileSync(fileName, 'utf-8')), this.devConfig = ((config, environments)=>{
4796
4802
  let writeToDiskValues = Object.values(environments).map((env)=>env.config.dev.writeToDisk);
4797
4803
  return 1 === new Set(writeToDiskValues).size ? {
4798
4804
  ...config,
@@ -4804,11 +4810,13 @@ ${section.body}` : section.body).join("\n\n"));
4804
4810
  return compilationName && environments[compilationName] && (writeToDisk = environments[compilationName].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
4805
4811
  }
4806
4812
  };
4807
- })(dev, environments), this.serverConfig = server, this.compiler = compiler, this.publicPaths = publicPaths, this.outputFileSystem = external_node_fs_default(), this.socketServer = new SocketServer(dev);
4813
+ })(dev, environments), this.serverConfig = server, this.compiler = compiler, this.environments = environments, this.publicPaths = publicPaths, this.outputFileSystem = external_node_fs_default(), this.socketServer = new SocketServer(dev, environments);
4808
4814
  }
4809
4815
  }
4810
- let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i, gzipMiddleware = ({ level = external_node_zlib_default().constants.Z_BEST_SPEED } = {})=>(req, res, next)=>{
4811
- let gzip, writeHeadStatus, accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
4816
+ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i, gzipMiddleware = ({ filter, level = external_node_zlib_default().constants.Z_BEST_SPEED } = {})=>(req, res, next)=>{
4817
+ let gzip, writeHeadStatus;
4818
+ if (filter && !1 === filter(req, res)) return void next();
4819
+ let accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
4812
4820
  if ('HEAD' === req.method || !encoding) return void next();
4813
4821
  let started = !1, { end, write, on, writeHead } = res, listeners = [], start = ()=>{
4814
4822
  if (!started) {
@@ -4932,7 +4940,8 @@ ${section.body}` : section.body).join("\n\n"));
4932
4940
  let { middlewares: proxyMiddlewares, upgrade } = await createProxyMiddleware(server.proxy);
4933
4941
  for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.push(middleware);
4934
4942
  }
4935
- if (server.compress && middlewares.push(gzipMiddleware()), 'dev' === context.action && 'rspack' === context.bundlerType && compilationManager) {
4943
+ let { compress } = server;
4944
+ if (compress && middlewares.push(gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && 'rspack' === context.bundlerType && compilationManager) {
4936
4945
  let { compiler } = compilationManager;
4937
4946
  (()=>{
4938
4947
  var _compiler_options_experiments;
@@ -5692,9 +5701,14 @@ ${section.body}` : section.body).join("\n\n"));
5692
5701
  for (let middleware of middlewares)this.middlewares.use(middleware);
5693
5702
  this.app.on('upgrade', upgrade);
5694
5703
  }
5695
- if (compress && this.middlewares.use(gzipMiddleware({
5696
- level: 6
5697
- })), base && '/' !== base && this.middlewares.use(getBaseMiddleware({
5704
+ if (compress) {
5705
+ let { constants } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "node:zlib"));
5706
+ this.middlewares.use(gzipMiddleware({
5707
+ level: constants.Z_DEFAULT_COMPRESSION,
5708
+ ...'object' == typeof compress ? compress : void 0
5709
+ }));
5710
+ }
5711
+ if (base && '/' !== base && this.middlewares.use(getBaseMiddleware({
5698
5712
  base
5699
5713
  })), await this.applyStaticAssetMiddleware(), historyApiFallback) {
5700
5714
  let { default: connectHistoryApiFallback } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "../../compiled/connect-history-api-fallback/index.js")), historyApiFallbackMiddleware = connectHistoryApiFallback(!0 === historyApiFallback ? {} : historyApiFallback);
@@ -6482,8 +6496,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6482
6496
  rule.test(CSS_REGEX).type("javascript/auto").dependency({
6483
6497
  not: 'url'
6484
6498
  }).resourceQuery({
6485
- not: /raw|inline/
6486
- }), inlineRule.test(CSS_REGEX).type("javascript/auto").resourceQuery(/inline/), chain.module.rule(CHAIN_ID.RULE.CSS_RAW).test(CSS_REGEX).type('asset/source').resourceQuery(/raw/);
6499
+ not: [
6500
+ RAW_QUERY_REGEX,
6501
+ INLINE_QUERY_REGEX
6502
+ ]
6503
+ }), inlineRule.test(CSS_REGEX).type("javascript/auto").resourceQuery(INLINE_QUERY_REGEX), chain.module.rule(CHAIN_ID.RULE.CSS_RAW).test(CSS_REGEX).type('asset/source').resourceQuery(RAW_QUERY_REGEX);
6487
6504
  let emitCss = config1.output.emitCss ?? 'web' === target;
6488
6505
  if (emitCss) if (config1.output.injectStyles) {
6489
6506
  let styleLoaderOptions = reduceConfigs({
@@ -6666,9 +6683,9 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6666
6683
  let { config, browserslist } = environment, cacheRoot = external_node_path_default().join(api.context.cachePath, '.swc'), rule = chain.module.rule(CHAIN_ID.RULE.JS).test(SCRIPT_REGEX).type("javascript/auto").dependency({
6667
6684
  not: 'url'
6668
6685
  }).resourceQuery({
6669
- not: /raw/
6686
+ not: RAW_QUERY_REGEX
6670
6687
  });
6671
- chain.module.rule(CHAIN_ID.RULE.JS_RAW).test(SCRIPT_REGEX).type('asset/source').resourceQuery(/raw/);
6688
+ chain.module.rule(CHAIN_ID.RULE.JS_RAW).test(SCRIPT_REGEX).type('asset/source').resourceQuery(RAW_QUERY_REGEX);
6672
6689
  let dataUriRule = chain.module.rule(CHAIN_ID.RULE.JS_DATA_URI).mimetype({
6673
6690
  or: [
6674
6691
  "text/javascript",
@@ -7845,11 +7862,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7845
7862
  ].includes(level) && (index_js_namespaceObject.logger.level = level);
7846
7863
  }
7847
7864
  let { npm_execpath } = process.env;
7848
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && index_js_namespaceObject.logger.log(), index_js_namespaceObject.logger.greet(` Rsbuild v1.4.3\n`);
7865
+ (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && index_js_namespaceObject.logger.log(), index_js_namespaceObject.logger.greet(` Rsbuild v1.4.4\n`);
7849
7866
  try {
7850
7867
  !function() {
7851
7868
  let cli = ((name = "")=>new CAC(name))('rsbuild');
7852
- cli.help(), cli.version("1.4.3"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7869
+ cli.help(), cli.version("1.4.4"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7853
7870
  default: 'jiti'
7854
7871
  }).option('-r, --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('-m, --mode <mode>', 'specify the build mode, can be `development`, `production` or `none`').option('--log-level <level>', 'specify the log level, can be `info`, `warn`, `error` or `silent`').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file').option('--environment <name>', 'specify the name of environment to build', {
7855
7872
  type: [
@@ -7907,7 +7924,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7907
7924
  index_js_namespaceObject.logger.error('Failed to start Rsbuild CLI.'), index_js_namespaceObject.logger.error(err);
7908
7925
  }
7909
7926
  }
7910
- let src_version = "1.4.3";
7927
+ let src_version = "1.4.4";
7911
7928
  })(), exports.PLUGIN_CSS_NAME = __webpack_exports__.PLUGIN_CSS_NAME, exports.PLUGIN_SWC_NAME = __webpack_exports__.PLUGIN_SWC_NAME, exports.createRsbuild = __webpack_exports__.createRsbuild, exports.defaultAllowedOrigins = __webpack_exports__.defaultAllowedOrigins, exports.defineConfig = __webpack_exports__.defineConfig, exports.ensureAssetPrefix = __webpack_exports__.ensureAssetPrefix, exports.loadConfig = __webpack_exports__.loadConfig, exports.loadEnv = __webpack_exports__.loadEnv, exports.logger = __webpack_exports__.logger, exports.mergeRsbuildConfig = __webpack_exports__.mergeRsbuildConfig, exports.rspack = __webpack_exports__.rspack, exports.runCLI = __webpack_exports__.runCLI, exports.version = __webpack_exports__.version, __webpack_exports__)-1 === [
7912
7929
  "PLUGIN_CSS_NAME",
7913
7930
  "PLUGIN_SWC_NAME",
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import picocolors from "../compiled/picocolors/index.js";
8
8
  import node_fs, { existsSync } from "node:fs";
9
9
  import { EventEmitter } from "events";
10
10
  import { createRequire } from "node:module";
11
- import node_os, { constants } from "node:os";
11
+ import node_os, { constants as external_node_os_constants } from "node:os";
12
12
  import node_process from "node:process";
13
13
  import rspack_chain from "../compiled/rspack-chain/index.js";
14
14
  import { isPromise, isRegExp } from "node:util/types";
@@ -777,7 +777,7 @@ let constants_filename = fileURLToPath(import.meta.url), constants_dirname = dir
777
777
  node: [
778
778
  'node >= 16'
779
779
  ]
780
- }, HTML_REGEX = /\.html$/, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
780
+ }, HTML_REGEX = /\.html$/, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, RAW_QUERY_REGEX = /^\?raw$/, INLINE_QUERY_REGEX = /^\?inline$/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
781
781
  'woff',
782
782
  'woff2',
783
783
  'eot',
@@ -2040,7 +2040,7 @@ let getEnvironmentHTMLPaths = (entry, config)=>'web' !== config.output.target ||
2040
2040
  }, {});
2041
2041
  async function updateEnvironmentContext(context, configs) {
2042
2042
  for (let [index, [name, config]] of (context.environments ||= {}, Object.entries(configs).entries())){
2043
- let browserslist = await getBrowserslistByEnvironment(context.rootPath, config), { entry = {}, tsconfigPath } = config.source, htmlPaths = getEnvironmentHTMLPaths(entry, config), environmentContext = {
2043
+ let browserslist = await getBrowserslistByEnvironment(context.rootPath, config), { entry = {}, tsconfigPath } = config.source, htmlPaths = getEnvironmentHTMLPaths(entry, config), webSocketToken = 'dev' === context.action ? await helpers_hash(context.rootPath + name) : '', environmentContext = {
2044
2044
  index,
2045
2045
  name,
2046
2046
  distPath: function(cwd, config) {
@@ -2051,7 +2051,8 @@ async function updateEnvironmentContext(context, configs) {
2051
2051
  browserslist,
2052
2052
  htmlPaths,
2053
2053
  tsconfigPath,
2054
- config
2054
+ config,
2055
+ webSocketToken
2055
2056
  };
2056
2057
  context.environments[name] = new Proxy(environmentContext, {
2057
2058
  get: (target, prop)=>target[prop],
@@ -2062,7 +2063,7 @@ async function updateEnvironmentContext(context, configs) {
2062
2063
  async function createContext(options, userConfig) {
2063
2064
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
2064
2065
  return {
2065
- version: "1.4.3",
2066
+ version: "1.4.4",
2066
2067
  rootPath,
2067
2068
  distPath: '',
2068
2069
  cachePath,
@@ -2751,7 +2752,7 @@ let chainStaticAssetRule = ({ emit, rule, maxSize, filename, assetType })=>{
2751
2752
  let generatorOptions = {
2752
2753
  filename
2753
2754
  };
2754
- !1 === emit && (generatorOptions.emit = !1), rule.oneOf(`${assetType}-asset-url`).type('asset/resource').resourceQuery(/(__inline=false|url)/).set('generator', generatorOptions), rule.oneOf(`${assetType}-asset-inline`).type('asset/inline').resourceQuery(/inline/), rule.oneOf(`${assetType}-asset-raw`).type('asset/source').resourceQuery(/raw/), rule.oneOf(`${assetType}-asset`).type('asset').parser({
2755
+ !1 === emit && (generatorOptions.emit = !1), rule.oneOf(`${assetType}-asset-url`).type('asset/resource').resourceQuery(/^\?(__inline=false|url)$/).set('generator', generatorOptions), rule.oneOf(`${assetType}-asset-inline`).type('asset/inline').resourceQuery(INLINE_QUERY_REGEX), rule.oneOf(`${assetType}-asset-raw`).type('asset/source').resourceQuery(RAW_QUERY_REGEX), rule.oneOf(`${assetType}-asset`).type('asset').parser({
2755
2756
  dataUrlCondition: {
2756
2757
  maxSize
2757
2758
  }
@@ -3685,9 +3686,6 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
3685
3686
  })
3686
3687
  });
3687
3688
  return addressUrls;
3688
- }, COMPILATION_ID_REGEX = /[^a-zA-Z0-9_-]/g, getCompilationId = (compiler)=>{
3689
- let uniqueName = compiler.options.output.uniqueName ?? '';
3690
- return `${compiler.name ?? ''}_${uniqueName.replace(COMPILATION_ID_REGEX, '_')}`;
3691
3689
  };
3692
3690
  function getServerTerminator(server) {
3693
3691
  let listened = !1, pendingSockets = new Set(), onConnection = (socket)=>{
@@ -4155,13 +4153,15 @@ async function getResolvedClientConfig(clientConfig, serverConfig) {
4155
4153
  }
4156
4154
  let getCompilationMiddleware = async (compiler, options)=>{
4157
4155
  let { default: rsbuildDevMiddleware } = await import("../compiled/rsbuild-dev-middleware/index.js"), { clientPaths, callbacks, devConfig, serverConfig } = options, resolvedClientConfig = await getResolvedClientConfig(devConfig.client, serverConfig);
4158
- return applyToCompiler(compiler, (compiler)=>{
4159
- clientPaths && function({ compiler, clientPaths, devConfig, resolvedClientConfig }) {
4156
+ return applyToCompiler(compiler, (compiler, index)=>{
4157
+ var _Object_values_find;
4158
+ let token = null == (_Object_values_find = Object.values(options.environments).find((env)=>env.index === index)) ? void 0 : _Object_values_find.webSocketToken;
4159
+ token && (clientPaths && function({ compiler, clientPaths, devConfig, resolvedClientConfig, token }) {
4160
4160
  if (((compiler)=>{
4161
4161
  let { target } = compiler.options;
4162
4162
  return !!target && (Array.isArray(target) ? target.includes('web') : 'web' === target);
4163
4163
  })(compiler)) for (let clientPath of (new compiler.webpack.DefinePlugin({
4164
- RSBUILD_COMPILATION_NAME: JSON.stringify(getCompilationId(compiler)),
4164
+ RSBUILD_WEB_SOCKET_TOKEN: JSON.stringify(token),
4165
4165
  RSBUILD_CLIENT_CONFIG: JSON.stringify(devConfig.client),
4166
4166
  RSBUILD_RESOLVED_CLIENT_CONFIG: JSON.stringify(resolvedClientConfig),
4167
4167
  RSBUILD_DEV_LIVE_RELOAD: devConfig.liveReload
@@ -4172,19 +4172,26 @@ let getCompilationMiddleware = async (compiler, options)=>{
4172
4172
  compiler,
4173
4173
  clientPaths,
4174
4174
  devConfig,
4175
- resolvedClientConfig
4176
- }), ((compiler, { onDone, onInvalid })=>{
4175
+ resolvedClientConfig,
4176
+ token
4177
+ }), (({ compiler, token, callbacks: { onDone, onInvalid } })=>{
4177
4178
  if (((compiler)=>{
4178
4179
  let { target } = compiler.options;
4179
4180
  return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
4180
4181
  })(compiler)) return;
4181
4182
  let { compile, invalid, done } = compiler.hooks;
4182
4183
  compile.tap('rsbuild-dev-server', ()=>{
4183
- onInvalid(getCompilationId(compiler));
4184
+ onInvalid(token);
4184
4185
  }), invalid.tap('rsbuild-dev-server', (fileName)=>{
4185
- onInvalid(getCompilationId(compiler), fileName);
4186
- }), done.tap('rsbuild-dev-server', onDone);
4187
- })(compiler, callbacks);
4186
+ onInvalid(token, fileName);
4187
+ }), done.tap('rsbuild-dev-server', (stats)=>{
4188
+ onDone(token, stats);
4189
+ });
4190
+ })({
4191
+ compiler,
4192
+ callbacks,
4193
+ token
4194
+ }));
4188
4195
  }), rsbuildDevMiddleware(compiler, {
4189
4196
  etag: 'weak',
4190
4197
  publicPath: '/',
@@ -4230,6 +4237,10 @@ function socketServer_define_property(obj, key, value) {
4230
4237
  writable: !0
4231
4238
  }) : obj[key] = value, obj;
4232
4239
  }
4240
+ let parseQueryString = (req)=>{
4241
+ let queryStr = req.url ? req.url.split('?')[1] : '';
4242
+ return queryStr ? Object.fromEntries(new URLSearchParams(queryStr)) : {};
4243
+ };
4233
4244
  class SocketServer {
4234
4245
  clearHeartbeatTimer() {
4235
4246
  this.heartbeatTimer && (clearTimeout(this.heartbeatTimer), this.heartbeatTimer = null);
@@ -4244,51 +4255,44 @@ class SocketServer {
4244
4255
  }), this.wsServer.on('error', (err)=>{
4245
4256
  logger.error(err);
4246
4257
  }), this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref(), this.wsServer.on('connection', (socket, req)=>{
4247
- let queryStr = req.url ? req.url.split('?')[1] : '';
4248
- this.onConnect(socket, queryStr ? Object.fromEntries(new URLSearchParams(queryStr)) : {});
4258
+ let query = parseQueryString(req);
4259
+ this.onConnect(socket, query.token);
4249
4260
  });
4250
4261
  }
4251
- updateStats(stats) {
4252
- let compilationId = getCompilationId(stats.compilation);
4253
- this.stats[compilationId] = stats, this.sockets.length && this.sendStats({
4254
- compilationId
4262
+ updateStats(stats, token) {
4263
+ this.stats[token] = stats, this.sockets.size && this.sendStats({
4264
+ token
4255
4265
  });
4256
4266
  }
4257
- sockWrite({ type, compilationId, data }) {
4258
- for (let socket of this.sockets)this.send(socket, JSON.stringify({
4259
- type,
4260
- data,
4261
- compilationId
4262
- }));
4267
+ sockWrite(message, token) {
4268
+ let messageStr = JSON.stringify(message);
4269
+ if (token) {
4270
+ let socket = this.sockets.get(token);
4271
+ socket && this.send(socket, messageStr);
4272
+ } else for (let socket of this.sockets.values())this.send(socket, messageStr);
4263
4273
  }
4264
- singleWrite(socket, { type, data, compilationId }) {
4265
- this.send(socket, JSON.stringify({
4266
- type,
4267
- data,
4268
- compilationId
4269
- }));
4274
+ singleWrite(socket, message) {
4275
+ this.send(socket, JSON.stringify(message));
4270
4276
  }
4271
4277
  async close() {
4272
4278
  for (let socket of (this.clearHeartbeatTimer(), this.wsServer.removeAllListeners(), this.wsServer.clients))socket.terminate();
4273
- for (let socket of this.sockets)socket.close();
4274
- return this.stats = {}, this.initialChunks = {}, this.sockets.length = 0, new Promise((resolve, reject)=>{
4279
+ for (let socket of this.sockets.values())socket.close();
4280
+ return this.stats = {}, this.initialChunks = {}, this.sockets.clear(), new Promise((resolve, reject)=>{
4275
4281
  this.wsServer.close((err)=>{
4276
4282
  err ? reject(err) : resolve();
4277
4283
  });
4278
4284
  });
4279
4285
  }
4280
- onConnect(socket, params) {
4286
+ onConnect(socket, token) {
4281
4287
  socket.isAlive = !0, socket.on('pong', ()=>{
4282
4288
  socket.isAlive = !0;
4283
- }), this.sockets.push(socket), socket.on('close', ()=>{
4284
- let index = this.sockets.indexOf(socket);
4285
- index >= 0 && this.sockets.splice(index, 1);
4289
+ }), this.sockets.set(token, socket), socket.on('close', ()=>{
4290
+ this.sockets.delete(token);
4286
4291
  }), (this.options.hmr || this.options.liveReload) && this.singleWrite(socket, {
4287
- type: 'hot',
4288
- compilationId: params.compilationId
4292
+ type: 'hot'
4289
4293
  }), this.stats && this.sendStats({
4290
4294
  force: !0,
4291
- compilationId: params.compilationId
4295
+ token
4292
4296
  });
4293
4297
  }
4294
4298
  getStats(name) {
@@ -4313,37 +4317,33 @@ class SocketServer {
4313
4317
  root: curStats.compilation.compiler.options.context
4314
4318
  } : null;
4315
4319
  }
4316
- sendStats({ force = !1, compilationId }) {
4317
- let result = this.getStats(compilationId);
4320
+ sendStats({ force = !1, token }) {
4321
+ let result = this.getStats(token);
4318
4322
  if (!result) return null;
4319
4323
  let { statsJson, root } = result, newInitialChunks = new Set();
4320
4324
  if (statsJson.entrypoints) for (let entrypoint of Object.values(statsJson.entrypoints)){
4321
4325
  let chunks = entrypoint.chunks;
4322
4326
  if (Array.isArray(chunks)) for (let chunkName of chunks)chunkName && newInitialChunks.add(String(chunkName));
4323
4327
  }
4324
- let initialChunks = this.initialChunks[compilationId], shouldReload = !!statsJson.entrypoints && !!initialChunks && !(initialChunks.size === newInitialChunks.size && [
4328
+ let initialChunks = this.initialChunks[token], shouldReload = !!statsJson.entrypoints && !!initialChunks && !(initialChunks.size === newInitialChunks.size && [
4325
4329
  ...initialChunks
4326
4330
  ].every((value)=>newInitialChunks.has(value)));
4327
- if (this.initialChunks[compilationId] = newInitialChunks, shouldReload) return this.sockWrite({
4328
- type: 'static-changed',
4329
- compilationId
4330
- });
4331
+ if (this.initialChunks[token] = newInitialChunks, shouldReload) return this.sockWrite({
4332
+ type: 'static-changed'
4333
+ }, token);
4331
4334
  if (!force && statsJson && !statsJson.errorsCount && statsJson.assets && statsJson.assets.every((asset)=>!asset.emitted)) return this.sockWrite({
4332
- type: 'ok',
4333
- compilationId
4334
- });
4335
+ type: 'ok'
4336
+ }, token);
4335
4337
  if (this.sockWrite({
4336
4338
  type: 'hash',
4337
- compilationId,
4338
4339
  data: statsJson.hash
4339
- }), statsJson.errorsCount) {
4340
+ }, token), statsJson.errorsCount) {
4340
4341
  let { errors: formattedErrors } = formatStatsMessages({
4341
4342
  errors: getAllStatsErrors(statsJson),
4342
4343
  warnings: []
4343
4344
  });
4344
4345
  return this.sockWrite({
4345
4346
  type: 'errors',
4346
- compilationId,
4347
4347
  data: {
4348
4348
  text: formattedErrors,
4349
4349
  html: function(errors, root) {
@@ -4501,7 +4501,7 @@ class SocketServer {
4501
4501
  `;
4502
4502
  }(formattedErrors, root)
4503
4503
  }
4504
- });
4504
+ }, token);
4505
4505
  }
4506
4506
  if (statsJson.warningsCount) {
4507
4507
  let { warnings: formattedWarnings } = formatStatsMessages({
@@ -4510,29 +4510,30 @@ class SocketServer {
4510
4510
  });
4511
4511
  return this.sockWrite({
4512
4512
  type: 'warnings',
4513
- compilationId,
4514
4513
  data: {
4515
4514
  text: formattedWarnings
4516
4515
  }
4517
- });
4516
+ }, token);
4518
4517
  }
4519
4518
  return this.sockWrite({
4520
- type: 'ok',
4521
- compilationId
4522
- });
4519
+ type: 'ok'
4520
+ }, token);
4523
4521
  }
4524
4522
  send(connection, message) {
4525
4523
  1 === connection.readyState && connection.send(message);
4526
4524
  }
4527
- constructor(options){
4528
- socketServer_define_property(this, "wsServer", void 0), socketServer_define_property(this, "sockets", []), socketServer_define_property(this, "options", void 0), socketServer_define_property(this, "stats", void 0), socketServer_define_property(this, "initialChunks", void 0), socketServer_define_property(this, "heartbeatTimer", null), socketServer_define_property(this, "upgrade", (req, sock, head)=>{
4529
- this.wsServer.shouldHandle(req) && this.wsServer.handleUpgrade(req, sock, head, (connection)=>{
4525
+ constructor(options, environments){
4526
+ socketServer_define_property(this, "wsServer", void 0), socketServer_define_property(this, "sockets", new Map()), socketServer_define_property(this, "options", void 0), socketServer_define_property(this, "stats", void 0), socketServer_define_property(this, "initialChunks", void 0), socketServer_define_property(this, "heartbeatTimer", null), socketServer_define_property(this, "environments", void 0), socketServer_define_property(this, "upgrade", (req, socket, head)=>{
4527
+ if (!this.wsServer.shouldHandle(req)) return;
4528
+ let query = parseQueryString(req);
4529
+ if (!Object.values(this.environments).map((env)=>env.webSocketToken).includes(query.token)) return void socket.destroy();
4530
+ this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
4530
4531
  this.wsServer.emit('connection', connection, req);
4531
4532
  });
4532
4533
  }), socketServer_define_property(this, "checkSockets", ()=>{
4533
4534
  for (let socket of this.wsServer.clients)socket.isAlive ? (socket.isAlive = !1, socket.ping(()=>{})) : socket.terminate();
4534
4535
  null !== this.heartbeatTimer && (this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref());
4535
- }), this.options = options, this.stats = {}, this.initialChunks = {};
4536
+ }), this.options = options, this.stats = {}, this.initialChunks = {}, this.environments = environments;
4536
4537
  }
4537
4538
  }
4538
4539
  function compilationManager_define_property(obj, key, value) {
@@ -4565,29 +4566,28 @@ class CompilationManager {
4565
4566
  });
4566
4567
  }
4567
4568
  async setupCompilationMiddleware() {
4568
- let { devConfig, serverConfig, publicPaths } = this, clientPaths = function(devConfig) {
4569
+ let { devConfig, serverConfig, publicPaths, environments } = this, clientPaths = function(devConfig) {
4569
4570
  var _devConfig_client;
4570
4571
  let clientPaths = [];
4571
4572
  return (devConfig.hmr || devConfig.liveReload) && (clientPaths.push(compilationManager_require.resolve('@rsbuild/core/client/hmr')), (null == (_devConfig_client = devConfig.client) ? void 0 : _devConfig_client.overlay) && clientPaths.push(`${compilationManager_require.resolve('@rsbuild/core/client/overlay')}`)), clientPaths;
4572
4573
  }(devConfig), middleware = await getCompilationMiddleware(this.compiler, {
4573
4574
  callbacks: {
4574
- onInvalid: (compilationId, fileName)=>{
4575
+ onInvalid: (token, fileName)=>{
4575
4576
  if ('string' == typeof fileName && HTML_REGEX.test(fileName)) return void this.socketServer.sockWrite({
4576
- type: 'static-changed',
4577
- compilationId
4578
- });
4577
+ type: 'static-changed'
4578
+ }, token);
4579
4579
  this.socketServer.sockWrite({
4580
- type: 'invalid',
4581
- compilationId
4582
- });
4580
+ type: 'invalid'
4581
+ }, token);
4583
4582
  },
4584
- onDone: (stats)=>{
4585
- this.socketServer.updateStats(stats);
4583
+ onDone: (token, stats)=>{
4584
+ this.socketServer.updateStats(stats, token);
4586
4585
  }
4587
4586
  },
4588
4587
  clientPaths,
4589
4588
  devConfig,
4590
- serverConfig
4589
+ serverConfig,
4590
+ environments
4591
4591
  }), { base } = serverConfig, assetPrefixes = publicPaths.map(getPathnameFromUrl).map((prefix)=>base && '/' !== base ? stripBase(prefix, base) : prefix), wrapper = async (req, res, next)=>{
4592
4592
  let { url } = req, assetPrefix = url && assetPrefixes.find((prefix)=>url.startsWith(prefix));
4593
4593
  assetPrefix && '/' !== assetPrefix ? (req.url = url.slice(assetPrefix.length - 1), middleware(req, res, (...args)=>{
@@ -4597,7 +4597,7 @@ class CompilationManager {
4597
4597
  wrapper.close = middleware.close, wrapper.watch = middleware.watch, this.middleware = wrapper;
4598
4598
  }
4599
4599
  constructor({ dev, server, compiler, publicPaths, environments }){
4600
- compilationManager_define_property(this, "middleware", void 0), compilationManager_define_property(this, "outputFileSystem", void 0), compilationManager_define_property(this, "devConfig", void 0), compilationManager_define_property(this, "serverConfig", void 0), compilationManager_define_property(this, "compiler", void 0), compilationManager_define_property(this, "publicPaths", void 0), compilationManager_define_property(this, "socketServer", void 0), compilationManager_define_property(this, "readFileSync", (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : node_fs.readFileSync(fileName, 'utf-8')), this.devConfig = ((config, environments)=>{
4600
+ compilationManager_define_property(this, "middleware", void 0), compilationManager_define_property(this, "outputFileSystem", void 0), compilationManager_define_property(this, "devConfig", void 0), compilationManager_define_property(this, "serverConfig", void 0), compilationManager_define_property(this, "compiler", void 0), compilationManager_define_property(this, "environments", void 0), compilationManager_define_property(this, "publicPaths", void 0), compilationManager_define_property(this, "socketServer", void 0), compilationManager_define_property(this, "readFileSync", (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : node_fs.readFileSync(fileName, 'utf-8')), this.devConfig = ((config, environments)=>{
4601
4601
  let writeToDiskValues = Object.values(environments).map((env)=>env.config.dev.writeToDisk);
4602
4602
  return 1 === new Set(writeToDiskValues).size ? {
4603
4603
  ...config,
@@ -4609,11 +4609,13 @@ class CompilationManager {
4609
4609
  return compilationName && environments[compilationName] && (writeToDisk = environments[compilationName].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
4610
4610
  }
4611
4611
  };
4612
- })(dev, environments), this.serverConfig = server, this.compiler = compiler, this.publicPaths = publicPaths, this.outputFileSystem = node_fs, this.socketServer = new SocketServer(dev);
4612
+ })(dev, environments), this.serverConfig = server, this.compiler = compiler, this.environments = environments, this.publicPaths = publicPaths, this.outputFileSystem = node_fs, this.socketServer = new SocketServer(dev, environments);
4613
4613
  }
4614
4614
  }
4615
- let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i, gzipMiddleware = ({ level = node_zlib.constants.Z_BEST_SPEED } = {})=>(req, res, next)=>{
4616
- let gzip, writeHeadStatus, accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
4615
+ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i, gzipMiddleware = ({ filter, level = node_zlib.constants.Z_BEST_SPEED } = {})=>(req, res, next)=>{
4616
+ let gzip, writeHeadStatus;
4617
+ if (filter && !1 === filter(req, res)) return void next();
4618
+ let accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
4617
4619
  if ('HEAD' === req.method || !encoding) return void next();
4618
4620
  let started = !1, { end, write, on, writeHead } = res, listeners = [], start = ()=>{
4619
4621
  if (!started) {
@@ -4737,7 +4739,8 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
4737
4739
  let { middlewares: proxyMiddlewares, upgrade } = await createProxyMiddleware(server.proxy);
4738
4740
  for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.push(middleware);
4739
4741
  }
4740
- if (server.compress && middlewares.push(gzipMiddleware()), 'dev' === context.action && 'rspack' === context.bundlerType && compilationManager) {
4742
+ let { compress } = server;
4743
+ if (compress && middlewares.push(gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && 'rspack' === context.bundlerType && compilationManager) {
4741
4744
  var _compiler_options_experiments;
4742
4745
  let { compiler } = compilationManager;
4743
4746
  (helpers_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>{
@@ -5155,7 +5158,7 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>new BasicRunne
5155
5158
  }, shutdownRefCount = 0, setupGracefulShutdown = ()=>{
5156
5159
  shutdownRefCount++;
5157
5160
  let onSigterm = ()=>{
5158
- handleTermination(constants.signals.SIGTERM + 128);
5161
+ handleTermination(external_node_os_constants.signals.SIGTERM + 128);
5159
5162
  };
5160
5163
  process.once('SIGTERM', onSigterm);
5161
5164
  let isCI = 'true' === process.env.CI, onStdinEnd = ()=>{
@@ -5488,9 +5491,14 @@ class RsbuildProdServer {
5488
5491
  for (let middleware of middlewares)this.middlewares.use(middleware);
5489
5492
  this.app.on('upgrade', upgrade);
5490
5493
  }
5491
- if (compress && this.middlewares.use(gzipMiddleware({
5492
- level: 6
5493
- })), base && '/' !== base && this.middlewares.use(getBaseMiddleware({
5494
+ if (compress) {
5495
+ let { constants } = await import("node:zlib");
5496
+ this.middlewares.use(gzipMiddleware({
5497
+ level: constants.Z_DEFAULT_COMPRESSION,
5498
+ ...'object' == typeof compress ? compress : void 0
5499
+ }));
5500
+ }
5501
+ if (base && '/' !== base && this.middlewares.use(getBaseMiddleware({
5494
5502
  base
5495
5503
  })), await this.applyStaticAssetMiddleware(), historyApiFallback) {
5496
5504
  let { default: connectHistoryApiFallback } = await import("../compiled/connect-history-api-fallback/index.js"), historyApiFallbackMiddleware = connectHistoryApiFallback(!0 === historyApiFallback ? {} : historyApiFallback);
@@ -6276,8 +6284,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6276
6284
  rule.test(CSS_REGEX).type("javascript/auto").dependency({
6277
6285
  not: 'url'
6278
6286
  }).resourceQuery({
6279
- not: /raw|inline/
6280
- }), inlineRule.test(CSS_REGEX).type("javascript/auto").resourceQuery(/inline/), chain.module.rule(CHAIN_ID.RULE.CSS_RAW).test(CSS_REGEX).type('asset/source').resourceQuery(/raw/);
6287
+ not: [
6288
+ RAW_QUERY_REGEX,
6289
+ INLINE_QUERY_REGEX
6290
+ ]
6291
+ }), inlineRule.test(CSS_REGEX).type("javascript/auto").resourceQuery(INLINE_QUERY_REGEX), chain.module.rule(CHAIN_ID.RULE.CSS_RAW).test(CSS_REGEX).type('asset/source').resourceQuery(RAW_QUERY_REGEX);
6281
6292
  let emitCss = config.output.emitCss ?? 'web' === target;
6282
6293
  if (emitCss) if (config.output.injectStyles) {
6283
6294
  let styleLoaderOptions = reduceConfigs({
@@ -6459,9 +6470,9 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6459
6470
  let { config, browserslist } = environment, cacheRoot = node_path.join(api.context.cachePath, '.swc'), rule = chain.module.rule(CHAIN_ID.RULE.JS).test(SCRIPT_REGEX).type("javascript/auto").dependency({
6460
6471
  not: 'url'
6461
6472
  }).resourceQuery({
6462
- not: /raw/
6473
+ not: RAW_QUERY_REGEX
6463
6474
  });
6464
- chain.module.rule(CHAIN_ID.RULE.JS_RAW).test(SCRIPT_REGEX).type('asset/source').resourceQuery(/raw/);
6475
+ chain.module.rule(CHAIN_ID.RULE.JS_RAW).test(SCRIPT_REGEX).type('asset/source').resourceQuery(RAW_QUERY_REGEX);
6465
6476
  let dataUriRule = chain.module.rule(CHAIN_ID.RULE.JS_DATA_URI).mimetype({
6466
6477
  or: [
6467
6478
  "text/javascript",
@@ -7254,9 +7265,9 @@ async function createRsbuild(options = {}) {
7254
7265
  exitCode
7255
7266
  });
7256
7267
  }, exitHook_callbacks.add(onExit), isRegistered || (isRegistered = !0, node_process.on('SIGINT', ()=>{
7257
- exit(constants.signals.SIGINT + 128, 'SIGINT');
7268
+ exit(external_node_os_constants.signals.SIGINT + 128, 'SIGINT');
7258
7269
  }), node_process.once('SIGTERM', ()=>{
7259
- exit(constants.signals.SIGTERM + 128, 'SIGTERM');
7270
+ exit(external_node_os_constants.signals.SIGTERM + 128, 'SIGTERM');
7260
7271
  }), node_process.once('exit', (exitCode)=>{
7261
7272
  exit(exitCode, 'exit');
7262
7273
  })), onExitListened = !0;
@@ -7634,11 +7645,11 @@ async function runCLI() {
7634
7645
  ].includes(level) && (logger.level = level);
7635
7646
  }
7636
7647
  let { npm_execpath } = process.env;
7637
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.3\n`);
7648
+ (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.4\n`);
7638
7649
  try {
7639
7650
  !function() {
7640
7651
  let cli = ((name = "")=>new CAC(name))('rsbuild');
7641
- cli.help(), cli.version("1.4.3"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7652
+ cli.help(), cli.version("1.4.4"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7642
7653
  default: 'jiti'
7643
7654
  }).option('-r, --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('-m, --mode <mode>', 'specify the build mode, can be `development`, `production` or `none`').option('--log-level <level>', 'specify the log level, can be `info`, `warn`, `error` or `silent`').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file').option('--environment <name>', 'specify the name of environment to build', {
7644
7655
  type: [
@@ -7696,5 +7707,5 @@ async function runCLI() {
7696
7707
  logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
7697
7708
  }
7698
7709
  }
7699
- let src_version = "1.4.3";
7710
+ let src_version = "1.4.4";
7700
7711
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger, mergeRsbuildConfig, rspack, runCLI, src_version as version };
@@ -28,6 +28,8 @@ export declare const HTML_REGEX: RegExp;
28
28
  export declare const JS_REGEX: RegExp;
29
29
  export declare const SCRIPT_REGEX: RegExp;
30
30
  export declare const CSS_REGEX: RegExp;
31
+ export declare const RAW_QUERY_REGEX: RegExp;
32
+ export declare const INLINE_QUERY_REGEX: RegExp;
31
33
  export declare const NODE_MODULES_REGEX: RegExp;
32
34
  export declare const PLUGIN_SWC_NAME = "rsbuild:swc";
33
35
  export declare const PLUGIN_CSS_NAME = "rsbuild:css";
@@ -19,4 +19,4 @@ export { type Logger, logger } from './logger';
19
19
  export { mergeRsbuildConfig } from './mergeConfig';
20
20
  export type { RsbuildDevServer } from './server/devServer';
21
21
  export type { StartServerResult } from './server/helper';
22
- export type { AliasStrategy, AppIcon, AppIconItem, Build, BuildOptions, BundlerPluginInstance, Charset, CleanDistPath, CleanDistPathObject, ClientConfig, CliShortcut, ConfigChain, ConfigChainWithContext, ConsoleType, CreateCompiler, CreateRsbuildOptions, CrossOrigin, CSSLoaderOptions, CSSModules, CSSModulesLocalsConvention, DataUriLimit, Decorators, DevConfig, DistPathConfig, EnvironmentConfig, EnvironmentContext, FilenameConfig, HistoryApiFallbackContext, HistoryApiFallbackOptions, HtmlBasicTag, HtmlConfig, HtmlFallback, HtmlRspackPlugin, HtmlTagContext, HtmlTagDescriptor, HtmlTagHandler, InlineChunkConfig, InlineChunkTest, InlineChunkTestFunction, InspectConfigOptions, InspectConfigResult, InternalContext, LegalComments, LogLevel, ManifestConfig, ManifestData, ManifestObjectConfig, MergedEnvironmentConfig, MetaAttrs, MetaOptions, Minify, ModifyBundlerChainFn, ModifyBundlerChainUtils, ModifyChainUtils, ModifyEnvironmentConfigFn, ModifyEnvironmentConfigUtils, ModifyHTMLContext, ModifyHTMLFn, ModifyHTMLTagsContext, ModifyHTMLTagsFn, ModifyRsbuildConfigFn, ModifyRsbuildConfigUtils, ModifyRspackConfigFn, ModifyRspackConfigUtils, ModifyWebpackChainFn, ModifyWebpackChainUtils, ModifyWebpackConfigFn, ModifyWebpackConfigUtils, ModuleFederationConfig, NormalizedConfig, NormalizedDevConfig, NormalizedEnvironmentConfig, NormalizedHtmlConfig, NormalizedModuleFederationConfig, NormalizedOutputConfig, NormalizedPerformanceConfig, NormalizedSecurityConfig, NormalizedServerConfig, NormalizedSourceConfig, NormalizedToolsConfig, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterEnvironmentCompileFn, OnAfterStartDevServerFn, OnAfterStartProdServerFn, OnBeforeBuildFn, OnBeforeCreateCompilerFn, OnBeforeEnvironmentCompileFn, OnBeforeStartDevServerFn, OnBeforeStartProdServerFn, OnCloseBuildFn, OnCloseDevServerFn, OnDevCompileDoneFn, OnExitFn, OutputConfig, OutputStructure, PerformanceConfig, PluginManager, Polyfill, PostCSSLoaderOptions, PostCSSOptions, PostCSSPlugin, PreconnectOption, PreviewOptions, PrintUrls, ProcessAssetsDescriptor, ProcessAssetsHandler, ProcessAssetsHook, ProgressBarConfig, ProxyBypass, ProxyConfig, ProxyFilter, ProxyOptions, PublicDir, PublicDirOptions, RequestHandler, ResolvedCreateRsbuildOptions, ResolveHandler, ResolveHook, ResourceHintsIncludeType, RsbuildConfig, RsbuildContext, RsbuildEntry, RsbuildEntryDescription, RsbuildInstance, RsbuildMode, RsbuildPlugin, RsbuildPluginAPI, RsbuildPlugins, RsbuildProvider, RsbuildProviderHelpers, RsbuildTarget, RspackChain, RspackRule, ScriptInject, ScriptLoading, SecurityConfig, ServerConfig, SetupMiddlewaresContext, SetupMiddlewaresFn, SourceConfig, SourceMap, SplitChunks, SriAlgorithm, SriOptions, StartDevServerOptions, StyleLoaderOptions, ToolsConfig, TransformContext, TransformDescriptor, TransformHandler, TransformHook, TransformImport, WatchFiles, } from './types';
22
+ export type { AliasStrategy, AppIcon, AppIconItem, Build, BuildOptions, BundlerPluginInstance, Charset, CleanDistPath, CleanDistPathObject, ClientConfig, CliShortcut, CompressOptions, ConfigChain, ConfigChainWithContext, ConsoleType, CreateCompiler, CreateRsbuildOptions, CrossOrigin, CSSLoaderOptions, CSSModules, CSSModulesLocalsConvention, DataUriLimit, Decorators, DevConfig, DistPathConfig, EnvironmentConfig, EnvironmentContext, FilenameConfig, HistoryApiFallbackContext, HistoryApiFallbackOptions, HtmlBasicTag, HtmlConfig, HtmlFallback, HtmlRspackPlugin, HtmlTagContext, HtmlTagDescriptor, HtmlTagHandler, InlineChunkConfig, InlineChunkTest, InlineChunkTestFunction, InspectConfigOptions, InspectConfigResult, InternalContext, LegalComments, LogLevel, ManifestConfig, ManifestData, ManifestObjectConfig, MergedEnvironmentConfig, MetaAttrs, MetaOptions, Minify, ModifyBundlerChainFn, ModifyBundlerChainUtils, ModifyChainUtils, ModifyEnvironmentConfigFn, ModifyEnvironmentConfigUtils, ModifyHTMLContext, ModifyHTMLFn, ModifyHTMLTagsContext, ModifyHTMLTagsFn, ModifyRsbuildConfigFn, ModifyRsbuildConfigUtils, ModifyRspackConfigFn, ModifyRspackConfigUtils, ModifyWebpackChainFn, ModifyWebpackChainUtils, ModifyWebpackConfigFn, ModifyWebpackConfigUtils, ModuleFederationConfig, NormalizedConfig, NormalizedDevConfig, NormalizedEnvironmentConfig, NormalizedHtmlConfig, NormalizedModuleFederationConfig, NormalizedOutputConfig, NormalizedPerformanceConfig, NormalizedSecurityConfig, NormalizedServerConfig, NormalizedSourceConfig, NormalizedToolsConfig, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterEnvironmentCompileFn, OnAfterStartDevServerFn, OnAfterStartProdServerFn, OnBeforeBuildFn, OnBeforeCreateCompilerFn, OnBeforeEnvironmentCompileFn, OnBeforeStartDevServerFn, OnBeforeStartProdServerFn, OnCloseBuildFn, OnCloseDevServerFn, OnDevCompileDoneFn, OnExitFn, OutputConfig, OutputStructure, PerformanceConfig, PluginManager, Polyfill, PostCSSLoaderOptions, PostCSSOptions, PostCSSPlugin, PreconnectOption, PreviewOptions, PrintUrls, ProcessAssetsDescriptor, ProcessAssetsHandler, ProcessAssetsHook, ProgressBarConfig, ProxyBypass, ProxyConfig, ProxyFilter, ProxyOptions, PublicDir, PublicDirOptions, RequestHandler, ResolvedCreateRsbuildOptions, ResolveHandler, ResolveHook, ResourceHintsIncludeType, RsbuildConfig, RsbuildContext, RsbuildEntry, RsbuildEntryDescription, RsbuildInstance, RsbuildMode, RsbuildPlugin, RsbuildPluginAPI, RsbuildPlugins, RsbuildProvider, RsbuildProviderHelpers, RsbuildTarget, RspackChain, RspackRule, ScriptInject, ScriptLoading, SecurityConfig, ServerConfig, SetupMiddlewaresContext, SetupMiddlewaresFn, SourceConfig, SourceMap, SplitChunks, SriAlgorithm, SriOptions, StartDevServerOptions, StyleLoaderOptions, ToolsConfig, TransformContext, TransformDescriptor, TransformHandler, TransformHook, TransformImport, WatchFiles, } from './types';
@@ -1,11 +1,11 @@
1
- import type { EnvironmentContext, DevConfig as OriginDevConfig, Rspack, ServerConfig } from '../types';
1
+ import type { EnvironmentContext, NormalizedDevConfig, NormalizedServerConfig, Rspack } from '../types';
2
2
  import { type CompilationMiddleware } from './compilationMiddleware';
3
3
  import { SocketServer } from './socketServer';
4
4
  type Options = {
5
5
  publicPaths: string[];
6
6
  environments: Record<string, EnvironmentContext>;
7
- dev: OriginDevConfig;
8
- server: ServerConfig;
7
+ dev: NormalizedDevConfig;
8
+ server: NormalizedServerConfig;
9
9
  compiler: Rspack.Compiler | Rspack.MultiCompiler;
10
10
  };
11
11
  /**
@@ -19,6 +19,7 @@ export declare class CompilationManager {
19
19
  private devConfig;
20
20
  private serverConfig;
21
21
  compiler: Rspack.Compiler | Rspack.MultiCompiler;
22
+ private environments;
22
23
  private publicPaths;
23
24
  socketServer: SocketServer;
24
25
  constructor({ dev, server, compiler, publicPaths, environments }: Options);
@@ -1,16 +1,20 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
- import type { Compiler, MultiCompiler } from '@rspack/core';
3
- import type { DevConfig, NextFunction, ServerConfig } from '../types';
2
+ import type { Compiler, MultiCompiler, Stats } from '@rspack/core';
3
+ import type { DevConfig, EnvironmentContext, NextFunction, ServerConfig } from '../types';
4
4
  export declare const isClientCompiler: (compiler: {
5
5
  options: {
6
6
  target?: Compiler["options"]["target"];
7
7
  };
8
8
  }) => boolean;
9
- type ServerCallbacks = {
10
- onInvalid: (compilationId?: string, fileName?: string | null) => void;
11
- onDone: (stats: any) => void;
9
+ export type ServerCallbacks = {
10
+ onInvalid: (token: string, fileName?: string | null) => void;
11
+ onDone: (token: string, stats: Stats) => void;
12
12
  };
13
- export declare const setupServerHooks: (compiler: Compiler, { onDone, onInvalid }: ServerCallbacks) => void;
13
+ export declare const setupServerHooks: ({ compiler, token, callbacks: { onDone, onInvalid }, }: {
14
+ compiler: Compiler;
15
+ token: string;
16
+ callbacks: ServerCallbacks;
17
+ }) => void;
14
18
  type Middleware = (req: IncomingMessage, res: ServerResponse, next: NextFunction) => Promise<void>;
15
19
  export type CompilationMiddlewareOptions = {
16
20
  /**
@@ -23,6 +27,7 @@ export type CompilationMiddlewareOptions = {
23
27
  callbacks: ServerCallbacks;
24
28
  devConfig: DevConfig;
25
29
  serverConfig: ServerConfig;
30
+ environments: Record<string, EnvironmentContext>;
26
31
  };
27
32
  export type CompilationMiddleware = Middleware & {
28
33
  close: (callback: (err: Error | null | undefined) => void) => any;
@@ -1,4 +1,2 @@
1
- import type { RequestHandler } from '../types';
2
- export declare const gzipMiddleware: ({ level, }?: {
3
- level?: number;
4
- }) => RequestHandler;
1
+ import type { CompressOptions, RequestHandler } from '../types';
2
+ export declare const gzipMiddleware: ({ filter, level, }?: CompressOptions) => RequestHandler;
@@ -1,7 +1,7 @@
1
1
  import type { IncomingMessage, Server } from 'node:http';
2
2
  import type { Http2SecureServer } from 'node:http2';
3
3
  import type { Socket } from 'node:net';
4
- import type { InternalContext, NormalizedConfig, OutputStructure, PrintUrls, Routes, RsbuildEntry, Rspack } from '../types';
4
+ import type { InternalContext, NormalizedConfig, OutputStructure, PrintUrls, Routes, RsbuildEntry } from '../types';
5
5
  /**
6
6
  * It used to subscribe http upgrade event
7
7
  */
@@ -71,7 +71,6 @@ export declare const getAddressUrls: ({ protocol, port, host, }: {
71
71
  port: number;
72
72
  host?: string;
73
73
  }) => Promise<AddressUrl[]>;
74
- export declare const getCompilationId: (compiler: Rspack.Compiler | Rspack.Compilation) => string;
75
74
  export declare function getServerTerminator(server: Server | Http2SecureServer): () => Promise<void>;
76
75
  /**
77
76
  * Escape HTML characters
@@ -1,10 +1,9 @@
1
1
  import type { IncomingMessage } from 'node:http';
2
2
  import type { Socket } from 'node:net';
3
- import type { DevConfig, Rspack } from '../types';
3
+ import type { DevConfig, EnvironmentContext, Rspack } from '../types';
4
4
  import type { SockWriteType } from './devServer';
5
5
  interface SocketMessage {
6
6
  type: SockWriteType;
7
- compilationId?: string;
8
7
  data?: Record<string, any> | string | boolean;
9
8
  }
10
9
  export declare class SocketServer {
@@ -14,13 +13,20 @@ export declare class SocketServer {
14
13
  private stats;
15
14
  private initialChunks;
16
15
  private heartbeatTimer;
17
- constructor(options: DevConfig);
18
- upgrade: (req: IncomingMessage, sock: Socket, head: any) => void;
16
+ private environments;
17
+ constructor(options: DevConfig, environments: Record<string, EnvironmentContext>);
18
+ upgrade: (req: IncomingMessage, socket: Socket, head: Buffer) => void;
19
19
  private checkSockets;
20
20
  private clearHeartbeatTimer;
21
21
  prepare(): Promise<void>;
22
- updateStats(stats: Rspack.Stats): void;
23
- sockWrite({ type, compilationId, data }: SocketMessage): void;
22
+ updateStats(stats: Rspack.Stats, token: string): void;
23
+ /**
24
+ * Write message to each socket
25
+ * @param message - The message to send
26
+ * @param token - The token of the socket to send the message to,
27
+ * if not provided, the message will be sent to all sockets
28
+ */
29
+ sockWrite(message: SocketMessage, token?: string): void;
24
30
  private singleWrite;
25
31
  close(): Promise<void>;
26
32
  private onConnect;
@@ -298,6 +298,28 @@ export type PublicDirOptions = {
298
298
  watch?: boolean;
299
299
  };
300
300
  export type PublicDir = false | PublicDirOptions | PublicDirOptions[];
301
+ /**
302
+ * The options for `server.compress`.
303
+ */
304
+ export type CompressOptions = {
305
+ /**
306
+ * A function that determines whether a response should be compressed.
307
+ * @param req - The incoming HTTP request
308
+ * @param res - The outgoing HTTP response
309
+ * @returns `true` to compress the response, `false` to skip compression
310
+ */
311
+ filter?: (req: IncomingMessage, res: ServerResponse) => boolean;
312
+ /**
313
+ * The level of zlib compression to apply to responses.
314
+ * A higher level will result in better compression, but will take longer to complete.
315
+ * A lower level will result in less compression, but will be much faster.
316
+ * This is an integer in the range of 0 (no compression) to 9 (maximum compression).
317
+ * @default
318
+ * - 1 (fastest) for dev server (also known as `zlib.constants.Z_BEST_SPEED`)
319
+ * - 6 for preview server (also known as `zlib.constants.Z_DEFAULT_COMPRESSION`)
320
+ */
321
+ level?: number;
322
+ };
301
323
  export interface ServerConfig {
302
324
  /**
303
325
  * Configure the base path of the server.
@@ -306,9 +328,10 @@ export interface ServerConfig {
306
328
  base?: string;
307
329
  /**
308
330
  * Whether to enable gzip compression for served static assets.
331
+ * Pass an object to customize the compression behavior.
309
332
  * @default true
310
333
  */
311
- compress?: boolean;
334
+ compress?: boolean | CompressOptions;
312
335
  /**
313
336
  * Serving static files from the directory (by default 'public' directory)
314
337
  */
@@ -157,6 +157,12 @@ export type EnvironmentContext = {
157
157
  * `onDevCompileDone` and `onAfterEnvironmentCompile` or via the environment API
158
158
  */
159
159
  manifest?: Record<string, unknown> | ManifestData;
160
+ /**
161
+ * WebSocket authentication token, used to authenticate WebSocket connections and
162
+ * prevent unauthorized access. Only available in the development mode, and is
163
+ * an empty string in the production mode.
164
+ */
165
+ webSocketToken: string;
160
166
  };
161
167
  export type ModifyChainUtils = {
162
168
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "1.4.3",
3
+ "version": "1.4.4",
4
4
  "description": "The Rspack-based build tool.",
5
5
  "homepage": "https://rsbuild.rs",
6
6
  "bugs": {
@@ -56,7 +56,7 @@
56
56
  "@rslib/core": "0.10.4",
57
57
  "@types/connect": "3.4.38",
58
58
  "@types/cors": "^2.8.19",
59
- "@types/node": "^22.15.34",
59
+ "@types/node": "^22.16.0",
60
60
  "@types/on-finished": "2.3.5",
61
61
  "@types/webpack-bundle-analyzer": "4.7.0",
62
62
  "@types/ws": "^8.18.1",
@@ -82,7 +82,7 @@
82
82
  "prebundle": "1.3.4",
83
83
  "reduce-configs": "^1.1.0",
84
84
  "rsbuild-dev-middleware": "0.3.0",
85
- "rslog": "^1.2.8",
85
+ "rslog": "^1.2.9",
86
86
  "rspack-chain": "^1.2.6",
87
87
  "rspack-manifest-plugin": "5.0.3",
88
88
  "sirv": "^3.0.1",
package/types.d.ts CHANGED
@@ -233,6 +233,9 @@ declare module '*?url' {
233
233
  * @example
234
234
  * import logo from './logo.svg?inline'
235
235
  * console.log(logo) // 'data:image/svg+xml;base64,...'
236
+ *
237
+ * import inlineCss from './style.css?inline';
238
+ * console.log(inlineCss); // Compiled CSS content
236
239
  */
237
240
  declare module '*?inline' {
238
241
  const content: string;
@@ -241,10 +244,17 @@ declare module '*?inline' {
241
244
 
242
245
  /**
243
246
  * Imports the raw content of the file as a string.
244
- * @note Only works for static assets and CSS files by default.
247
+ * @note Only works for static assets, CSS files, and scripts
248
+ * (JS, TS, JSX, TSX) by default.
245
249
  * @example
246
250
  * import raw from './logo.svg?raw'
247
251
  * console.log(raw) // '<svg viewBox="0 0 24 24">...</svg>'
252
+ *
253
+ * import rawJs from './script.js?raw'
254
+ * console.log(rawJs) // 'console.log("Hello world");'
255
+ *
256
+ * import rawCss from './style.css?raw'
257
+ * console.log(rawCss) // 'body { background: red; }'
248
258
  */
249
259
  declare module '*?raw' {
250
260
  const content: string;