@rsbuild/core 2.3.1 → 2.3.3

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/m.js CHANGED
@@ -4,7 +4,7 @@ import { rspackRequire, moduleFactories, compatGetDefaultExport, createFakeNames
4
4
  import { rspack as core_rspack } from "@rspack/core";
5
5
  import node_util, { format as external_node_util_format, promisify, stripVTControlCharacters } from "node:util";
6
6
  import node_path, { dirname, isAbsolute as external_node_path_isAbsolute, join, posix, relative, resolve as external_node_path_resolve, sep } from "node:path";
7
- import { builtinModules, createRequire, createRequire as __rspack_createRequire } from "node:module";
7
+ import { createRequire, isBuiltin, createRequire as __rspack_createRequire } from "node:module";
8
8
  import node_fs, { existsSync, readFileSync } from "node:fs";
9
9
  import node_os, { constants } from "node:os";
10
10
  import node_process from "node:process";
@@ -207,7 +207,7 @@ moduleFactories.add({
207
207
  if ('function' != typeof loader) throw Error('loader is not a function');
208
208
  }
209
209
  module.exports.lilconfig = function lilconfig(name, options) {
210
- let { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache } = getOptions(name, options ?? {}, !1), searchCache = new Map(), loadCache = new Map(), emplace = (c, filepath, res)=>(cache && c.set(filepath, res), res);
210
+ let { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache } = getOptions(name, options ?? {}, !1), searchCache = new Map(), loadCache = new Map(), emplace = (0, (c, filepath, res)=>(cache && c.set(filepath, res), res));
211
211
  return {
212
212
  async search (searchFrom = process.cwd()) {
213
213
  let result = {
@@ -292,8 +292,8 @@ moduleFactories.add({
292
292
  };
293
293
  };
294
294
  },
295
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/3982c00e478b1022695fb90618a4bf86beec38a06e2b0c0a97aeacbed78f1172/node_modules/postcss-load-config/src/index.js" (module) {
296
- let yaml, { resolve } = __rspack_createRequire_require("node:path"), config = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/lilconfig/3.1.3/8e9a79516bf61f8427342cef50cdad2cdc2572f42288ba8053b88eadfdc0ebef/node_modules/lilconfig/src/index.js"), loadOptions = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/3982c00e478b1022695fb90618a4bf86beec38a06e2b0c0a97aeacbed78f1172/node_modules/postcss-load-config/src/options.js"), loadPlugins = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/3982c00e478b1022695fb90618a4bf86beec38a06e2b0c0a97aeacbed78f1172/node_modules/postcss-load-config/src/plugins.js"), req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/3982c00e478b1022695fb90618a4bf86beec38a06e2b0c0a97aeacbed78f1172/node_modules/postcss-load-config/src/req.js");
295
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/index.js" (module) {
296
+ let yaml, { resolve } = __rspack_createRequire_require("node:path"), config = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/lilconfig/3.1.3/8e9a79516bf61f8427342cef50cdad2cdc2572f42288ba8053b88eadfdc0ebef/node_modules/lilconfig/src/index.js"), loadOptions = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/options.js"), loadPlugins = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/plugins.js"), req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/req.js");
297
297
  async function processResult(ctx, result) {
298
298
  let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
299
299
  default: obj
@@ -366,8 +366,8 @@ moduleFactories.add({
366
366
  });
367
367
  };
368
368
  },
369
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/3982c00e478b1022695fb90618a4bf86beec38a06e2b0c0a97aeacbed78f1172/node_modules/postcss-load-config/src/options.js" (module) {
370
- let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/3982c00e478b1022695fb90618a4bf86beec38a06e2b0c0a97aeacbed78f1172/node_modules/postcss-load-config/src/req.js");
369
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/options.js" (module) {
370
+ let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/req.js");
371
371
  module.exports = async function options(config, file) {
372
372
  if (config.parser && 'string' == typeof config.parser) try {
373
373
  config.parser = await req(config.parser, file);
@@ -387,8 +387,8 @@ moduleFactories.add({
387
387
  return config;
388
388
  };
389
389
  },
390
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/3982c00e478b1022695fb90618a4bf86beec38a06e2b0c0a97aeacbed78f1172/node_modules/postcss-load-config/src/plugins.js" (module) {
391
- let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/3982c00e478b1022695fb90618a4bf86beec38a06e2b0c0a97aeacbed78f1172/node_modules/postcss-load-config/src/req.js");
390
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/plugins.js" (module) {
391
+ let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/req.js");
392
392
  async function load(plugin, options, file) {
393
393
  try {
394
394
  if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
@@ -404,7 +404,7 @@ moduleFactories.add({
404
404
  }), list;
405
405
  };
406
406
  },
407
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/3982c00e478b1022695fb90618a4bf86beec38a06e2b0c0a97aeacbed78f1172/node_modules/postcss-load-config/src/req.js" (module) {
407
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/req.js" (module) {
408
408
  let tsx, jiti, { createRequire } = __rspack_createRequire_require("node:module"), { pathToFileURL } = __rspack_createRequire_require("node:url"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
409
409
  module.exports = async function req(name, rootFile = __rspack_import_meta_filename__) {
410
410
  let url = createRequire(rootFile).resolve(name);
@@ -941,16 +941,16 @@ var Command = class {
941
941
  arg.variadic ? actionArgs.push(args.slice(index)) : actionArgs.push(args[index]);
942
942
  }), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
943
943
  }
944
- }, __webpack_modules__ = {}, __webpack_module_cache__ = {};
944
+ }, dist_webpack_modules_ = {}, dist_webpack_module_cache_ = {};
945
945
  function dist_webpack_require_(moduleId) {
946
- var cachedModule = __webpack_module_cache__[moduleId];
946
+ var cachedModule = dist_webpack_module_cache_[moduleId];
947
947
  if (void 0 !== cachedModule) return cachedModule.exports;
948
- var module = __webpack_module_cache__[moduleId] = {
948
+ var module = dist_webpack_module_cache_[moduleId] = {
949
949
  exports: {}
950
950
  };
951
- return __webpack_modules__[moduleId](module, module.exports, dist_webpack_require_), module.exports;
951
+ return dist_webpack_modules_[moduleId](module, module.exports, dist_webpack_require_), module.exports;
952
952
  }
953
- dist_webpack_require_.m = __webpack_modules__, dist_webpack_require_.add = function(modules) {
953
+ dist_webpack_require_.m = dist_webpack_modules_, dist_webpack_require_.add = function(modules) {
954
954
  Object.assign(dist_webpack_require_.m, modules);
955
955
  }, dist_webpack_require_.add({
956
956
  "./node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js" (module) {
@@ -1170,7 +1170,7 @@ dist_webpack_require_.m = __webpack_modules__, dist_webpack_require_.add = funct
1170
1170
  exports.A = void 0;
1171
1171
  let stringify_1 = __webpack_require__("./node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/stringify.js"), quote_1 = __webpack_require__("./node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/quote.js"), ROOT_SENTINEL = Symbol("root");
1172
1172
  function replacerToString(replacer) {
1173
- return replacer ? (value, space, next, key)=>replacer(value, space, (value)=>stringify_1.toString(value, space, next, key), key) : stringify_1.toString;
1173
+ return replacer ? (0, (value, space, next, key)=>replacer(value, space, (value)=>stringify_1.toString(value, space, next, key), key)) : stringify_1.toString;
1174
1174
  }
1175
1175
  exports.A = function stringify(value, replacer, indent, options = {}) {
1176
1176
  let space = "string" == typeof indent ? indent : " ".repeat(indent || 0), path = [], stack = new Set(), tracking = new Map(), unpack = new Map(), valueCount = 0, { maxDepth = 100, references = !1, skipUndefinedProperties = !1, maxValues = 100000 } = options, valueToString = replacerToString(replacer), onNext = (value, key)=>{
@@ -1993,11 +1993,15 @@ class RspackChain extends ChainedMap {
1993
1993
  ]);
1994
1994
  }
1995
1995
  }
1996
- let vendors_require = createRequire(import.meta.url);
1997
- var cjs_0_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/deepmerge/4.3.1/56471899410038644780b3527c5076e78d3f57091a0da3ac0daf6d994929353d/node_modules/deepmerge/dist/cjs.js"));
1996
+ let vendors_require = createRequire(import.meta.url), cjs_0 = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/deepmerge/4.3.1/56471899410038644780b3527c5076e78d3f57091a0da3ac0daf6d994929353d/node_modules/deepmerge/dist/cjs.js");
1997
+ var cjs_0_default = compatGetDefaultExport(cjs_0);
1998
1998
  let setNodeEnv = (env)=>{
1999
1999
  process.env.NODE_ENV = env;
2000
- }, isCI = ()=>!!process.env.CI && 'false' !== process.env.CI, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), objectPrototype = Object.prototype, helpers_getProto = Object.getPrototypeOf, isPlainObject = (obj)=>null !== obj && 'object' == typeof obj && helpers_getProto(obj) === objectPrototype, helpers_castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
2000
+ }, isCI = ()=>!!process.env.CI && 'false' !== process.env.CI, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), objectPrototype = Object.prototype, helpers_getProto = Object.getPrototypeOf, isPlainObject = (obj)=>{
2001
+ if (null === obj || 'object' != typeof obj) return !1;
2002
+ let proto = helpers_getProto(obj);
2003
+ return null === proto || proto === objectPrototype || null === helpers_getProto(proto);
2004
+ }, helpers_castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
2001
2005
  arr
2002
2006
  ], cloneDeep = (value)=>null == value ? value : cjs_0_default()({}, value, {
2003
2007
  isMergeableObject: isPlainObject
@@ -2075,11 +2079,8 @@ function resolveFileName(stats, logger) {
2075
2079
  let file = stats.file || stats.moduleName;
2076
2080
  if (file) return removeLoaderChainDelimiter(file, logger);
2077
2081
  if (stats.moduleIdentifier) {
2078
- let matched = stats.moduleIdentifier.match(/(?:!|^)([^!]+)$/);
2079
- if (matched) {
2080
- let fileName = matched.pop();
2081
- if (fileName) return removeLoaderChainDelimiter(fileName, logger);
2082
- }
2082
+ let fileName = stats.moduleIdentifier.slice(stats.moduleIdentifier.lastIndexOf('!') + 1);
2083
+ if (fileName) return removeLoaderChainDelimiter(fileName, logger);
2083
2084
  }
2084
2085
  return '';
2085
2086
  }
@@ -2091,12 +2092,12 @@ function formatModuleTrace(stats, errorFile, root, level, logger) {
2091
2092
  let formatted = removeLoaderChainDelimiter(errorFile, logger);
2092
2093
  moduleNames[0] !== formatted && moduleNames.unshift(formatted);
2093
2094
  }
2094
- let trace = moduleNames.slice().reverse().map((name)=>formatDiagnosticPath(name, root));
2095
+ let trace = moduleNames.toReversed();
2095
2096
  return trace.length > 4 && !isVerbose(logger) && (trace = [
2096
2097
  ...trace.slice(0, 2),
2097
2098
  `... (${trace.length - 2 - 2} hidden)`,
2098
2099
  ...trace.slice(trace.length - 2)
2099
- ]), color.dim(`Import traces (entry → ${level}):\n ${trace.join('\n ')} ${color.bold(color.red('×'))}`);
2100
+ ]), color.dim(`Import traces (entry → ${level}):\n ${trace.map((name)=>formatDiagnosticPath(name, root)).join('\n ')} ${color.bold(color.red('×'))}`);
2100
2101
  }
2101
2102
  function hintUnknownFiles(message) {
2102
2103
  let hint = 'You may need an appropriate loader to handle this file type.';
@@ -2105,37 +2106,45 @@ function hintUnknownFiles(message) {
2105
2106
  for (let plugin of [
2106
2107
  {
2107
2108
  test: /File: .+\.s(c|a)ss/,
2108
- hint: createPluginHint('sass', 'Sass')
2109
+ name: 'sass',
2110
+ keyword: 'Sass'
2109
2111
  },
2110
2112
  {
2111
2113
  test: /File: .+\.less/,
2112
- hint: createPluginHint('less', 'Less')
2114
+ name: 'less',
2115
+ keyword: 'Less'
2113
2116
  },
2114
2117
  {
2115
2118
  test: /File: .+\.styl(us)?/,
2116
- hint: createPluginHint('stylus', 'Stylus')
2119
+ name: 'stylus',
2120
+ keyword: 'Stylus'
2117
2121
  },
2118
2122
  {
2119
2123
  test: /File: .+\.vue?/,
2120
- hint: createPluginHint('vue', 'Vue')
2124
+ name: 'vue',
2125
+ keyword: 'Vue'
2121
2126
  },
2122
2127
  {
2123
2128
  test: /File: .+\.svelte?/,
2124
- hint: createPluginHint('svelte', 'Svelte')
2129
+ name: 'svelte',
2130
+ keyword: 'Svelte'
2125
2131
  },
2126
2132
  {
2127
2133
  test: /File: .+\.mdx/,
2128
- hint: createPluginHint('mdx', 'MDX')
2134
+ name: 'mdx',
2135
+ keyword: 'MDX'
2129
2136
  },
2130
2137
  {
2131
2138
  test: /File: .+\.toml/,
2132
- hint: createPluginHint('toml', 'TOML')
2139
+ name: 'toml',
2140
+ keyword: 'TOML'
2133
2141
  },
2134
2142
  {
2135
2143
  test: /File: .+\.yaml/,
2136
- hint: createPluginHint('yaml', 'YAML')
2144
+ name: 'yaml',
2145
+ keyword: 'YAML'
2137
2146
  }
2138
- ])if (plugin.test.test(message)) return message.replace(hint, plugin.hint);
2147
+ ])if (plugin.test.test(message)) return message.replace(hint, createPluginHint(plugin.name, plugin.keyword));
2139
2148
  return message;
2140
2149
  }
2141
2150
  function formatStatsError(stats, root, level = 'error', logger) {
@@ -2143,11 +2152,11 @@ function formatStatsError(stats, root, level = 'error', logger) {
2143
2152
  if (!fileName) return '';
2144
2153
  let DATA_URI_PREFIX = "data:text/javascript,";
2145
2154
  if (fileName.startsWith(DATA_URI_PREFIX)) {
2146
- let snippet = fileName.replace(DATA_URI_PREFIX, '');
2155
+ let snippet = fileName.slice(DATA_URI_PREFIX.length);
2147
2156
  return snippet.length > 30 && (snippet = `${snippet.slice(0, 30)}...`), `File: ${color.cyan('data-uri virtual module')} ${color.dim(`(${snippet})`)}\n`;
2148
2157
  }
2149
2158
  let prefix = root + sep;
2150
- return (fileName = fileName.startsWith(prefix) ? fileName.replace(prefix, `.${sep}`) : formatDiagnosticPath(fileName, root), /:\d+:\d+/.test(fileName)) ? `File: ${color.cyan(fileName)}\n` : stats.loc ? `File: ${color.cyan(`${fileName}:${stats.loc}`)}\n` : `File: ${color.cyan(`${fileName}:1:1`)}\n`;
2159
+ return (fileName = fileName.startsWith(prefix) ? `.${sep}${fileName.slice(prefix.length)}` : formatDiagnosticPath(fileName, root), /:\d+:\d+/.test(fileName)) ? `File: ${color.cyan(fileName)}\n` : stats.loc ? `File: ${color.cyan(`${fileName}:${stats.loc}`)}\n` : `File: ${color.cyan(`${fileName}:1:1`)}\n`;
2151
2160
  })(fileName, stats, root)}${stats.message}`, verbose = isVerbose(logger);
2152
2161
  if (verbose && (stats.details && (message += `\nDetails: ${stats.details}\n`), stats.stack && (message += `\n${stats.stack}`)), 'error' === level || isVerbose(logger)) {
2153
2162
  let moduleTrace = formatModuleTrace(stats, fileName, root, level, logger);
@@ -2174,7 +2183,7 @@ function formatStatsError(stats, root, level = 'error', logger) {
2174
2183
  let matchArray = stripVTControlCharacters(message).match(/Can't resolve '(\w+)'/);
2175
2184
  if (!matchArray) return message;
2176
2185
  let moduleName = matchArray[1];
2177
- return moduleName && builtinModules.includes(moduleName) ? getTips(moduleName) : message;
2186
+ return moduleName && isBuiltin(moduleName) ? getTips(moduleName) : message;
2178
2187
  })(message = hintUnknownFiles(message)))).split('\n');
2179
2188
  return (message = (lines = lines.filter((line, index, arr)=>0 === index || '' !== line.trim() || line.trim() !== arr[index - 1].trim())).join('\n')).trim();
2180
2189
  }
@@ -2243,7 +2252,11 @@ function formatStats(stats, hasErrors, root, logger) {
2243
2252
  }
2244
2253
  return {};
2245
2254
  }
2246
- let removeLoaderChainDelimiter = (moduleId, logger)=>isVerbose(logger) ? moduleId : moduleId.split('!=!')[0];
2255
+ let removeLoaderChainDelimiter = (moduleId, logger)=>{
2256
+ if (isVerbose(logger)) return moduleId;
2257
+ let index = moduleId.indexOf('!=!');
2258
+ return -1 === index ? moduleId : moduleId.slice(0, index);
2259
+ };
2247
2260
  function createEnvironmentAsyncHook() {
2248
2261
  let preGroup = [], postGroup = [], defaultGroup = [], tapEnvironment = ({ environment, handler: cb })=>{
2249
2262
  isFunction(cb) ? defaultGroup.push({
@@ -2379,19 +2392,20 @@ let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompile, isWa
2379
2392
  if (compiler_isMultiCompiler(compiler)) {
2380
2393
  let { compilers } = compiler, compilerStats = [], doneCompilers = 0;
2381
2394
  for(let index = 0; index < compilers.length; index++){
2382
- let compiler = compilers[index], compilerIndex = index, compilerDone = !1;
2395
+ let compiler = compilers[index], compilerDone = !1, generation = 0, compilationGeneration = 0;
2383
2396
  compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
2384
- !compilerDone && (compilerDone = !0, doneCompilers++), compilerStats[compilerIndex] = stats;
2385
- let lastCompilerDone = doneCompilers === compilers.length;
2386
- await onEnvironmentDone(index, stats), lastCompilerDone && await onDone(new MultiStatsCtor(compilerStats));
2397
+ let currentGeneration = compilationGeneration;
2398
+ await onEnvironmentDone(index, stats), currentGeneration === generation && (!compilerDone && (compilerDone = !0, doneCompilers++), compilerStats[index] = stats, doneCompilers === compilers.length && await onDone(new MultiStatsCtor(compilerStats)));
2387
2399
  });
2388
2400
  let resetDoneState = ()=>{
2389
- compilerDone && (compilerDone = !1, doneCompilers--);
2401
+ generation++, compilerDone && (compilerDone = !1, doneCompilers--);
2390
2402
  };
2391
2403
  compiler.hooks.invalid.tap('rsbuild:done', resetDoneState), compiler.hooks.watchRun.tap({
2392
2404
  name: 'rsbuild:done',
2393
2405
  stage: -1 / 0
2394
- }, resetDoneState);
2406
+ }, ()=>{
2407
+ resetDoneState(), compilationGeneration = generation;
2408
+ });
2395
2409
  }
2396
2410
  } else compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
2397
2411
  await onEnvironmentDone(0, stats), await onDone(stats);
@@ -2528,7 +2542,7 @@ async function pathExists(path) {
2528
2542
  async function isFileExists(file) {
2529
2543
  return node_fs.promises.access(file, node_fs.constants.F_OK).then(()=>!0).catch(()=>!1);
2530
2544
  }
2531
- async function fileExistsByCompilation({ inputFileSystem }, filePath) {
2545
+ function fileExistsByCompilation({ inputFileSystem }, filePath) {
2532
2546
  return new Promise((resolve)=>{
2533
2547
  inputFileSystem ? inputFileSystem.stat(filePath, (err, stats)=>{
2534
2548
  err ? resolve(!1) : resolve(!!stats?.isFile());
@@ -2583,11 +2597,12 @@ let OVERRIDE_PATHS = new Set([
2583
2597
  'customLogger'
2584
2598
  ]), merge = (x, y, path = '')=>{
2585
2599
  if (((key)=>{
2600
+ let realKey = key;
2586
2601
  if (key.startsWith('environments.')) {
2587
- let realKey = key.split('.').slice(2).join('.');
2588
- return OVERRIDE_PATHS.has(realKey);
2602
+ let index = key.indexOf('.', 13);
2603
+ realKey = -1 === index ? '' : key.slice(index + 1);
2589
2604
  }
2590
- return OVERRIDE_PATHS.has(key) || key.startsWith('output.filename.');
2605
+ return OVERRIDE_PATHS.has(realKey) || realKey.startsWith('output.filename.');
2591
2606
  })(path)) return y ?? x;
2592
2607
  if (void 0 === x) return isPlainObject(y) ? cloneDeep(y) : y;
2593
2608
  if (void 0 === y) return isPlainObject(x) ? cloneDeep(x) : x;
@@ -2873,7 +2888,11 @@ let isEnvironmentMatch = (pluginEnvironment, specifiedEnvironment)=>pluginEnviro
2873
2888
  function createPluginManager(logger) {
2874
2889
  let plugins = [];
2875
2890
  return {
2876
- getPlugins: (options = {})=>plugins.filter((plugin)=>isEnvironmentMatch(plugin.environment, options.environment)).map(({ instance })=>instance),
2891
+ getPlugins: (options = {})=>{
2892
+ let result = [];
2893
+ for (let plugin of plugins)isEnvironmentMatch(plugin.environment, options.environment) && result.push(plugin.instance);
2894
+ return result;
2895
+ },
2877
2896
  getAllPluginsWithMeta: ()=>plugins,
2878
2897
  addPlugins: (newPlugins, options)=>{
2879
2898
  let { before, environment } = options || {};
@@ -2902,11 +2921,6 @@ async function initPlugins({ context, pluginManager }) {
2902
2921
  let plugins = pluginManager.getAllPluginsWithMeta();
2903
2922
  plugins = ((plugins)=>{
2904
2923
  let allLines = [], pluginNames = new Set(plugins.map((item)=>item.instance.name));
2905
- function getPlugin(name) {
2906
- let targets = plugins.filter((item)=>item.instance.name === name);
2907
- if (!targets.length) throw Error(`${color.dim('[rsbuild:plugin]')} Plugin "${color.yellow(name)}" not existed`);
2908
- return targets;
2909
- }
2910
2924
  for (let plugin of plugins){
2911
2925
  if (plugin.instance.pre) for (let pre of plugin.instance.pre)pre && pluginNames.has(pre) && allLines.push([
2912
2926
  pre,
@@ -2917,10 +2931,23 @@ async function initPlugins({ context, pluginManager }) {
2917
2931
  post
2918
2932
  ]);
2919
2933
  }
2920
- let endPoints = new Set(allLines.map((line)=>line[1])), zeroEndPoints = plugins.filter((item)=>!endPoints.has(item.instance.name)), sortedPoint = [], sortedPluginNames = new Set();
2921
- for(; zeroEndPoints.length;){
2922
- let { name } = zeroEndPoints[0].instance, pluginInstances = getPlugin(name);
2923
- sortedPoint.push(...pluginInstances), sortedPluginNames.add(name), endPoints = new Set((allLines = allLines.filter((line)=>line[0] !== name)).map((line)=>line[1])), zeroEndPoints = plugins.filter((item)=>!sortedPluginNames.has(item.instance.name) && !endPoints.has(item.instance.name));
2934
+ if (0 === allLines.length && pluginNames.size === plugins.length) return plugins.slice();
2935
+ let pluginsByName = new Map();
2936
+ for (let plugin of plugins){
2937
+ let { name } = plugin.instance, group = pluginsByName.get(name);
2938
+ group ? group.push(plugin) : pluginsByName.set(name, [
2939
+ plugin
2940
+ ]);
2941
+ }
2942
+ function getPlugin(name) {
2943
+ let targets = pluginsByName.get(name) ?? [];
2944
+ if (!targets.length) throw Error(`${color.dim('[rsbuild:plugin]')} Plugin "${color.yellow(name)}" not existed`);
2945
+ return targets;
2946
+ }
2947
+ let endPoints = new Set(allLines.map((line)=>line[1])), zeroEndPoint = plugins.find((item)=>!endPoints.has(item.instance.name)), sortedPoint = [], sortedPluginNames = new Set();
2948
+ for(; zeroEndPoint;){
2949
+ let { name } = zeroEndPoint.instance, pluginInstances = getPlugin(name);
2950
+ sortedPoint.push(...pluginInstances), sortedPluginNames.add(name), endPoints = new Set((allLines = allLines.filter((line)=>line[0] !== name)).map((line)=>line[1])), zeroEndPoint = plugins.find((item)=>!sortedPluginNames.has(item.instance.name) && !endPoints.has(item.instance.name));
2924
2951
  }
2925
2952
  if (allLines.length) {
2926
2953
  let restInRingPoints = {};
@@ -3033,7 +3060,7 @@ function initPluginAPI({ context, pluginManager }) {
3033
3060
  }, GLOBAL_EXPOSED_KEY = Symbol('global-exposed'), exposed = new Map(), expose = (id, api, options)=>{
3034
3061
  let exposedAPIs = exposed.get(id) ?? new Map(), key = options?.environment ?? GLOBAL_EXPOSED_KEY;
3035
3062
  exposedAPIs.set(key, api), exposed.set(id, exposedAPIs);
3036
- }, transformId = 0, transformer = {}, processAssetsFns = [], resolveFns = [];
3063
+ }, transformId = 0, transformer = {}, preTransformIds = new Set(), processAssetsFns = [], resolveFns = [];
3037
3064
  hooks.modifyBundlerChain.tap((chain, { target, environment })=>{
3038
3065
  let pluginName = 'RsbuildCorePlugin';
3039
3066
  chain.plugin(pluginName).use(class {
@@ -3077,39 +3104,43 @@ function initPluginAPI({ context, pluginManager }) {
3077
3104
  context: publicContext,
3078
3105
  expose,
3079
3106
  logger: context.logger,
3080
- transform: (descriptor, handler)=>{
3107
+ transform: (0, (descriptor, handler)=>{
3081
3108
  let id = `rsbuild-transform-${transformId++}`;
3082
- transformer[id] = handler, hooks.modifyBundlerChain.tapEnvironment({
3109
+ transformer[id] = handler, void 0 !== descriptor.as && 'pre' === descriptor.order && preTransformIds.add(id), hooks.modifyBundlerChain.tapEnvironment({
3083
3110
  environment: environment,
3084
3111
  handler: (chain, { target, environment: environmentContext })=>{
3085
3112
  if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environmentContext.name)) return;
3086
3113
  let rule = chain.module.rule(id);
3087
- descriptor.test && rule.test(descriptor.test), descriptor.resourceQuery && rule.resourceQuery(descriptor.resourceQuery), descriptor.layer && rule.layer(descriptor.layer), descriptor.issuerLayer && rule.issuerLayer(descriptor.issuerLayer), descriptor.issuer && rule.issuer(descriptor.issuer), descriptor.with && rule.with(descriptor.with), descriptor.mimetype && rule.mimetype(descriptor.mimetype), descriptor.order && 'default' !== descriptor.order ? rule.enforce(descriptor.order) : descriptor.enforce && rule.enforce(descriptor.enforce);
3088
- let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs'), use = rule.use(id).loader(loaderPath).options({
3114
+ if (preTransformIds.has(id)) {
3115
+ let firstRuleName = chain.module.rules.order().order.find((name)=>!preTransformIds.has(name));
3116
+ firstRuleName && rule.before(firstRuleName);
3117
+ }
3118
+ void 0 !== descriptor.as && rule.set('as', descriptor.as), descriptor.test && rule.test(descriptor.test), descriptor.resourceQuery && rule.resourceQuery(descriptor.resourceQuery), descriptor.layer && rule.layer(descriptor.layer), descriptor.issuerLayer && rule.issuerLayer(descriptor.issuerLayer), descriptor.issuer && rule.issuer(descriptor.issuer), descriptor.with && rule.with(descriptor.with), descriptor.mimetype && rule.mimetype(descriptor.mimetype), descriptor.order && 'default' !== descriptor.order ? rule.enforce(descriptor.order) : descriptor.enforce && rule.enforce(descriptor.enforce);
3119
+ let loaderName = descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs', loaderPath = join(LOADER_PATH, loaderName), use = rule.use(id).loader(loaderPath).options({
3089
3120
  id,
3090
3121
  getEnvironment: ()=>environmentContext
3091
3122
  });
3092
3123
  void 0 !== descriptor.codeFilter && use.set('codeFilter', descriptor.codeFilter);
3093
3124
  }
3094
3125
  });
3095
- },
3096
- useExposed: (id)=>{
3126
+ }),
3127
+ useExposed: (0, (id)=>{
3097
3128
  let exposedAPIs = exposed.get(id);
3098
3129
  if (exposedAPIs) return void 0 !== environment && exposedAPIs.has(environment) ? exposedAPIs.get(environment) : exposedAPIs.get(GLOBAL_EXPOSED_KEY);
3099
- },
3100
- processAssets: (descriptor, handler)=>{
3130
+ }),
3131
+ processAssets: (0, (descriptor, handler)=>{
3101
3132
  processAssetsFns.push({
3102
3133
  environment: environment,
3103
3134
  descriptor,
3104
3135
  handler
3105
3136
  });
3106
- },
3107
- resolve: (handler)=>{
3137
+ }),
3138
+ resolve: (0, (handler)=>{
3108
3139
  resolveFns.push({
3109
3140
  environment: environment,
3110
3141
  handler
3111
3142
  });
3112
- },
3143
+ }),
3113
3144
  getRsbuildConfig,
3114
3145
  getNormalizedConfig,
3115
3146
  isPluginExists: pluginManager.isPluginExists,
@@ -3175,7 +3206,8 @@ function initPluginAPI({ context, pluginManager }) {
3175
3206
  });
3176
3207
  }
3177
3208
  function getAbsoluteDistPath(cwd, config) {
3178
- return ensureAbsolutePath(cwd, config.output?.distPath?.root ?? "dist");
3209
+ let dirRoot = config.output?.distPath?.root ?? "dist";
3210
+ return ensureAbsolutePath(cwd, dirRoot);
3179
3211
  }
3180
3212
  let browsersListCache = new Map();
3181
3213
  function getBrowserslist(path) {
@@ -3258,7 +3290,7 @@ async function createContext(options, userConfig, logger, loadConfigResult) {
3258
3290
  return config;
3259
3291
  })(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, hooks = initHooks();
3260
3292
  return {
3261
- version: "2.3.1",
3293
+ version: "2.3.3",
3262
3294
  rootPath,
3263
3295
  configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3264
3296
  configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
@@ -3346,7 +3378,7 @@ async function emitConfigFiles({ bundlerConfigs, environmentConfigs, extraConfig
3346
3378
  };
3347
3379
  }),
3348
3380
  ...bundlerConfigs.map(({ name, content })=>{
3349
- let outputFilePath = join(outputPath, `rspack.config.${name}.mjs`);
3381
+ let outputFile = `rspack.config.${name}.mjs`, outputFilePath = join(outputPath, outputFile);
3350
3382
  return node_fs.existsSync(outputFilePath) && (outputFilePath = outputFilePath.replace(/\.mjs$/, `.${Date.now()}.mjs`)), {
3351
3383
  path: outputFilePath,
3352
3384
  label: `Rspack Config (${name})`,
@@ -3691,11 +3723,12 @@ function getConfigUtils(getCurrentConfig, chainUtils) {
3691
3723
  };
3692
3724
  }
3693
3725
  function getChainUtils(target, environment, environments) {
3726
+ let nodeEnv = process.env.NODE_ENV || '';
3694
3727
  return {
3695
3728
  rspack: core_rspack,
3696
3729
  environment,
3697
3730
  environments,
3698
- env: process.env.NODE_ENV || '',
3731
+ env: nodeEnv,
3699
3732
  target,
3700
3733
  isDev: 'development' === environment.config.mode,
3701
3734
  isProd: 'production' === environment.config.mode,
@@ -3800,6 +3833,9 @@ async function initRsbuildConfig({ context, pluginManager }) {
3800
3833
  },
3801
3834
  server: {
3802
3835
  ...normalizedBaseConfig.server,
3836
+ ...pick(environmentConfig.server ?? {}, [
3837
+ 'serveAssets'
3838
+ ]),
3803
3839
  publicDir: void 0 === publicDir ? normalizedBaseConfig.server.publicDir : normalizePublicDirs(context.rootPath, publicDir)
3804
3840
  }
3805
3841
  }, { tsconfigPath } = normalizedEnvironmentConfig.source;
@@ -3868,14 +3904,14 @@ function cutPath(originalFilePath, root) {
3868
3904
  return parts.length > 3 ? parts.slice(-3).join(sep) : parts.join(sep);
3869
3905
  }
3870
3906
  function isLikelyFile(filePath) {
3871
- return (filePath.split(sep).pop() || '').includes('.');
3907
+ return filePath.slice(filePath.lastIndexOf(sep) + 1).includes('.');
3872
3908
  }
3873
3909
  function formatFileList(paths, rootPath) {
3874
3910
  let files = paths.filter(isLikelyFile);
3875
3911
  0 === files.length && paths.length > 0 && (files = [
3876
3912
  paths[0]
3877
3913
  ]);
3878
- let fileInfo = files.slice(0, 1).map((file)=>cutPath(file, rootPath)).join(', ');
3914
+ let fileInfo = files.length ? cutPath(files[0], rootPath) : '';
3879
3915
  return files.length > 1 ? `${fileInfo} and ${files.length - 1} more` : fileInfo;
3880
3916
  }
3881
3917
  function printBuildLog(compiler, context, lazyModules) {
@@ -3901,9 +3937,9 @@ async function createCompiler_createCompiler(options) {
3901
3937
  bundlerConfigs: rspackConfigs,
3902
3938
  environments: context.environments
3903
3939
  }), (version = core_rspack.rspackVersion).includes('-canary') && (version = version.split('-canary')[0]), !(!(version && /^[\d.]+$/.test(version)) || ((version1, version2)=>{
3904
- let parts1 = version1.split('.').map(Number), parts2 = version2.split('.').map(Number), len = Math.max(parts1.length, parts2.length);
3940
+ let parts1 = version1.split('.'), parts2 = version2.split('.'), len = Math.max(parts1.length, parts2.length);
3905
3941
  for(let i = 0; i < len; i++){
3906
- let item1 = parts1[i] ?? 0, item2 = parts2[i] ?? 0;
3942
+ let item1 = Number(parts1[i] ?? 0), item2 = Number(parts2[i] ?? 0);
3907
3943
  if (item1 > item2) return 1;
3908
3944
  if (item1 < item2) return -1;
3909
3945
  }
@@ -3983,7 +4019,7 @@ async function createCompiler_createCompiler(options) {
3983
4019
  let isFirstCompile = !0, { environmentList } = context;
3984
4020
  onBeforeCompile({
3985
4021
  compiler,
3986
- beforeEnvironmentCompile: async (buildIndex)=>{
4022
+ beforeEnvironmentCompile: (buildIndex)=>{
3987
4023
  let environment = environmentList[buildIndex];
3988
4024
  return context.hooks.onBeforeEnvironmentCompile.callBatch({
3989
4025
  environment: environment.name,
@@ -3997,7 +4033,7 @@ async function createCompiler_createCompiler(options) {
3997
4033
  ]
3998
4034
  });
3999
4035
  },
4000
- beforeCompile: async ()=>context.hooks.onBeforeDevCompile.callBatch({
4036
+ beforeCompile: ()=>context.hooks.onBeforeDevCompile.callBatch({
4001
4037
  bundlerConfigs,
4002
4038
  environments: context.environments,
4003
4039
  isFirstCompile,
@@ -4057,20 +4093,20 @@ let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), formatPrefix = (inp
4057
4093
  if ('' === basePath || !url.startsWith(basePath)) return url;
4058
4094
  let nextChar = url[basePath.length];
4059
4095
  return void 0 === nextChar ? '/' : '/' === nextChar ? url.slice(basePath.length) : '?' === nextChar || '#' === nextChar ? `/${url.slice(basePath.length)}` : url;
4060
- }, getRoutes = (context)=>{
4061
- let environmentWithHtml = context.environmentList.filter((item)=>Object.keys(item.htmlPaths).length > 0);
4096
+ }, isServingAssets = (config)=>config.server.serveAssets ?? isWebTarget(config.output.target), getRoutes = (context)=>{
4097
+ let environmentWithHtml = context.environmentList.filter((item)=>isServingAssets(item.config) && Object.keys(item.htmlPaths).length > 0);
4062
4098
  if (0 === environmentWithHtml.length) return [];
4063
4099
  let commonDistPath = getCommonParentPath(environmentWithHtml.map((item)=>item.distPath));
4064
4100
  return environmentWithHtml.reduce((prev, environmentContext)=>{
4065
4101
  let { distPath, config } = environmentContext, distPrefix = relative(commonDistPath, distPath).split(sep).join('/'), routes = formatRoutes(environmentContext.htmlPaths, context.normalizedConfig.server.base, posix.join(distPrefix, config.output.distPath.html), config.html.outputStructure);
4066
- return prev.concat(...routes);
4102
+ return prev.concat(routes);
4067
4103
  }, []);
4068
4104
  }, formatRoutes = (entry, base, distPathPrefix, outputStructure)=>{
4069
- let prefix = joinUrlPath(base, formatPrefix(distPathPrefix));
4070
- return Object.keys(entry).map((entryName)=>({
4105
+ let prefix = joinUrlPath(base, formatPrefix(distPathPrefix)), entryNames = Object.keys(entry), index = entryNames.indexOf('index');
4106
+ return index > 0 && (entryNames.splice(index, 1), entryNames.unshift('index')), entryNames.map((entryName)=>({
4071
4107
  entryName,
4072
4108
  pathname: prefix + ('index' === entryName && 'nested' !== outputStructure ? '' : entryName)
4073
- })).sort((a)=>'index' === a.entryName ? -1 : 1);
4109
+ }));
4074
4110
  }, formatName = (name)=>name ? `(${name.length > 20 ? `${name.slice(0, 19)}…` : name})` : name;
4075
4111
  function getURLMessages(urls, routes, { maxRoutes = 10, showAllRoutes, cliShortcutsEnabled }) {
4076
4112
  let prevName, routeLimit = showAllRoutes ? 1 / 0 : void 0 === maxRoutes ? 10 : 1 / 0 === maxRoutes ? maxRoutes : Math.max(0, Math.floor(maxRoutes)), printableRoutes = 0 === routeLimit ? [] : routes.slice(0, routeLimit), moreEntries = routeLimit > 0 ? routes.length - printableRoutes.length : 0, nameCount = 0;
@@ -4420,8 +4456,8 @@ function loadEnv({ cwd = process.cwd(), mode = process.env.NODE_ENV || '', prefi
4420
4456
  });
4421
4457
  let publicVars = {}, rawPublicVars = {};
4422
4458
  for (let key of Object.keys(processEnv))if (prefixes.some((prefix)=>key.startsWith(prefix))) {
4423
- let val = processEnv[key];
4424
- publicVars[`import.meta.env.${key}`] = JSON.stringify(val), publicVars[`process.env.${key}`] = JSON.stringify(val), rawPublicVars[key] = val;
4459
+ let val = processEnv[key], serialized = JSON.stringify(val);
4460
+ publicVars[`import.meta.env.${key}`] = serialized, publicVars[`process.env.${key}`] = serialized, rawPublicVars[key] = val;
4425
4461
  }
4426
4462
  let cleaned = !1;
4427
4463
  return {
@@ -5018,8 +5054,9 @@ function parseMinifyOptions(config) {
5018
5054
  cssOptions: minify.cssOptions
5019
5055
  };
5020
5056
  }
5021
- var postcss_load_config_src_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/3982c00e478b1022695fb90618a4bf86beec38a06e2b0c0a97aeacbed78f1172/node_modules/postcss-load-config/src/index.js"));
5022
- async function getLightningCSSLoaderOptions(config, targets, minify) {
5057
+ let postcss_load_config_src = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/index.js");
5058
+ var postcss_load_config_src_default = compatGetDefaultExport(postcss_load_config_src);
5059
+ function getLightningCSSLoaderOptions(config, targets, minify) {
5023
5060
  let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
5024
5061
  targets,
5025
5062
  errorRecovery: !0
@@ -5225,7 +5262,7 @@ let EXCLUDE_ASSET_REGEX = /\.(?:map|LICENSE\.txt|d\.(?:ts|mts|cts))$/, isSignifi
5225
5262
  label: (diff > 0 ? color.red : color.green)(label),
5226
5263
  length: label.length
5227
5264
  };
5228
- }, getAssetColor = (size)=>size > 300000 ? color.red : size > 100000 ? color.yellow : (input)=>input;
5265
+ }, getAssetColor = (size)=>size > 300000 ? color.red : size > 100000 ? color.yellow : (0, (input)=>input);
5229
5266
  function getHeader(maxFileLength, maxSizeLength, fileHeader, compressionHeader) {
5230
5267
  let lengths = [
5231
5268
  maxFileLength,
@@ -5699,7 +5736,7 @@ async function getMetaTags(entryName, config, templateContent) {
5699
5736
  return templateContent && metaTags.charset && /<meta\b(?:[^>"']|"[^"]*"|'[^']*')*?\scharset\s*=/i.test(templateContent) && delete metaTags.charset, metaTags;
5700
5737
  }
5701
5738
  function getTemplateParameters(entryName, config, assetPrefix) {
5702
- return async (compilation, assets, assetTags, pluginOptions)=>{
5739
+ return (compilation, assets, assetTags, pluginOptions)=>{
5703
5740
  let { mountId, templateParameters } = config.html, rspackConfig = compilation.options;
5704
5741
  return reduceConfigsWithContext({
5705
5742
  initial: {
@@ -5742,10 +5779,12 @@ function updateSourceMappingURL({ source, compilation, publicPath, type, config
5742
5779
  }
5743
5780
  function getMatchedAsset(name, assets, tests) {
5744
5781
  let asset;
5745
- if (tests.some((test)=>isFunction(test) ? !!(asset ??= assets[name]) && test({
5782
+ for (let test of tests)if (isFunction(test)) {
5783
+ if ((asset ??= assets[name]) && test({
5746
5784
  name,
5747
5785
  size: asset.size()
5748
- }) : test.exec(name))) return asset ?? assets[name];
5786
+ })) return asset;
5787
+ } else if (test.test(name)) return asset ?? assets[name];
5749
5788
  }
5750
5789
  function getInlineTests(config) {
5751
5790
  let isProd = 'production' === config.mode, { inlineStyles, inlineScripts } = config.output, scriptTests = [], styleTests = [];
@@ -5843,18 +5882,22 @@ let getServerUrlFromClientConfig = async (config, context)=>{
5843
5882
  let protocol = client.protocol ? `${'wss' === client.protocol ? 'https' : 'http'}:` : '', hostname = await getHostInUrl(client.host || devServer.hostname), port = client.port && '<port>' !== client.port ? client.port : devServer.port;
5844
5883
  return `${protocol}//${hostname}:${port}`;
5845
5884
  };
5846
- function recursiveChunkGroup(chunkGroup, visited = new Set()) {
5847
- if (visited.has(chunkGroup)) return [];
5885
+ function recursiveChunkGroup(chunkGroup, visited, names) {
5886
+ if (visited.has(chunkGroup)) return;
5848
5887
  visited.add(chunkGroup);
5849
5888
  let parents = chunkGroup.getParents();
5850
- return parents.length ? parents.flatMap((chunkParent)=>recursiveChunkGroup(chunkParent, visited)) : [
5851
- chunkGroup.name
5852
- ];
5889
+ if (!parents.length) {
5890
+ let { name } = chunkGroup;
5891
+ name && names.add(name);
5892
+ return;
5893
+ }
5894
+ for (let parent of parents)recursiveChunkGroup(parent, visited, names);
5853
5895
  }
5854
5896
  function recursiveChunkEntryNames(chunk) {
5855
- let [...chunkGroups] = chunk.groupsIterable;
5897
+ let names = new Set(), visited = new Set();
5898
+ for (let chunkGroup of chunk.groupsIterable)recursiveChunkGroup(chunkGroup, visited, names);
5856
5899
  return [
5857
- ...new Set(chunkGroups.flatMap((chunkGroup)=>recursiveChunkGroup(chunkGroup)).filter((name)=>!!name))
5900
+ ...names
5858
5901
  ];
5859
5902
  }
5860
5903
  function isChunksFiltered(chunkName, includeChunks, excludeChunks) {
@@ -5864,7 +5907,7 @@ function doesChunkBelongToHtml({ chunk, htmlPluginData }) {
5864
5907
  let { options } = htmlPluginData.plugin;
5865
5908
  return recursiveChunkEntryNames(chunk).some((chunkName)=>isChunksFiltered(chunkName, options?.chunks, options?.excludeChunks));
5866
5909
  }
5867
- let getManifestPlugin = cachedImport_cachedImport(()=>import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/962a610493ec402e318fb90e15abdb8e0c048f9453227ea9c1af410588c46571/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
5910
+ let getManifestPlugin = cachedImport_cachedImport(()=>import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/17497e64d22a6c2a8eb2700029cf278579ead3c64963d770513f8f60bb2e2fa4/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
5868
5911
  function normalizeManifestObjectConfig(manifest) {
5869
5912
  let defaultOptions = {
5870
5913
  prefix: !0,
@@ -5904,13 +5947,13 @@ function pluginModuleFederation() {
5904
5947
  }
5905
5948
  };
5906
5949
  }
5907
- function getPublicPath({ isDev, config, context }) {
5950
+ async function getPublicPath({ isDev, config, context }) {
5908
5951
  let { dev, output, server } = config, publicPath = "/";
5909
5952
  if (isDev) {
5910
5953
  if ('string' == typeof dev.assetPrefix) publicPath = dev.assetPrefix;
5911
5954
  else if (dev.assetPrefix) {
5912
- let protocol = context.devServer?.https ? 'https' : 'http', hostname = context.devServer?.hostname || LOCALHOST;
5913
- publicPath = hostname === ALL_INTERFACES_IPV4 ? `${protocol}://localhost:<port>/` : `${protocol}://${hostname}:<port>/`, server.base && '/' !== server.base && (publicPath = urlJoin(publicPath, server.base));
5955
+ let protocol = context.devServer?.https ? 'https' : 'http', host = context.devServer?.hostname || LOCALHOST, hostname = WILDCARD_HOSTS.has(host) ? LOCALHOST : await getHostInUrl(host);
5956
+ publicPath = `${protocol}://${hostname}:<port>/`, server.base && '/' !== server.base && (publicPath = urlJoin(publicPath, server.base));
5914
5957
  }
5915
5958
  } else 'string' == typeof output.assetPrefix && (publicPath = output.assetPrefix);
5916
5959
  let defaultPort = server.port ?? 3000;
@@ -6009,6 +6052,7 @@ function generateLinks(options, type, compilation, data, HTMLCount, isDev) {
6009
6052
  chunk.auxiliaryFiles ?? []
6010
6053
  ])for (let file of files)isDev && file.endsWith('.hot-update.js') || file.endsWith('.map') || uniqueFiles.add(file);
6011
6054
  let sortedFilteredFiles = ((files, include, exclude)=>{
6055
+ if (!include && !exclude) return files;
6012
6056
  let includeRegExp = [], excludeRegExp = [], includeFn = [], excludeFn = [];
6013
6057
  if (include) for (let item of helpers_castArray(include))'string' == typeof item ? includeRegExp.push(new RegExp(item)) : isFunction(item) ? includeFn.push(item) : includeRegExp.push(item);
6014
6058
  if (exclude) for (let item of helpers_castArray(exclude))'string' == typeof item ? excludeRegExp.push(new RegExp(item)) : isFunction(item) ? excludeFn.push(item) : excludeRegExp.push(item);
@@ -6495,7 +6539,7 @@ function getContentType(str) {
6495
6539
  }
6496
6540
  let BYTES_RANGE_REGEXP = /^ *bytes/i;
6497
6541
  function getValueContentRangeHeader(type, size, range) {
6498
- return `${type} ${range ? `${range.start}-${range.end}` : '*'}:${size}`.replace(':', '/');
6542
+ return `${type} ${range ? `${range.start}-${range.end}` : '*'}/${size}`;
6499
6543
  }
6500
6544
  function parseHttpDate(date) {
6501
6545
  let timestamp = date && Date.parse(date);
@@ -6610,12 +6654,11 @@ function sendError(res, code) {
6610
6654
  let byteLength = Buffer.byteLength(document);
6611
6655
  res.setHeader('Content-Length', byteLength), res.end(document);
6612
6656
  }
6613
- let filterWebEnvironments = (environmentList)=>environmentList.filter((environment)=>isWebTarget(environment.config.output.target));
6614
6657
  function createAssetsMiddleware(context, { waitForAssets, waitForBuild }, outputFileSystem) {
6615
- let { logger } = context, webEnvironments = filterWebEnvironments(context.environmentList), assetContext = {
6658
+ let { logger } = context, servedEnvironments = context.environmentList.filter((environment)=>isServingAssets(environment.config)), assetContext = {
6616
6659
  ...context,
6617
- environmentList: webEnvironments,
6618
- publicPathnames: webEnvironments.map((environment)=>context.publicPathnames[environment.index])
6660
+ environmentList: servedEnvironments,
6661
+ publicPathnames: servedEnvironments.map((environment)=>context.publicPathnames[environment.index])
6619
6662
  };
6620
6663
  return async function assetsMiddleware(req, res, next) {
6621
6664
  function goNext() {
@@ -6707,7 +6750,7 @@ function setupMemoryFileSystemCleanup(fileSystem, compilers) {
6707
6750
  compilation.hash !== lastHash && (generation++, lastHash = compilation.hash);
6708
6751
  let outputPath = compilation.getPath(compiler.outputPath);
6709
6752
  for (let name of getAssetNames(compilation)){
6710
- let queryIndex = name.indexOf('?'), filePath = join(outputPath, -1 === queryIndex ? name : name.slice(0, queryIndex));
6753
+ let queryIndex = name.indexOf('?'), filename = -1 === queryIndex ? name : name.slice(0, queryIndex), filePath = join(outputPath, filename);
6711
6754
  lastSeen.set(filePath, generation);
6712
6755
  }
6713
6756
  for (let [filePath, seen] of lastSeen)if (!(seen >= generation - 1) && (lastSeen.delete(filePath), !lastSeenByCompiler.some((assets)=>assets.has(filePath)))) try {
@@ -6980,12 +7023,12 @@ let closeCode = [
6980
7023
  49
6981
7024
  ];
6982
7025
  function ansiHTML(text) {
6983
- let ansiCodes = [], ret = text.replace(/\x1B\[([0-9;]+)m/g, (_match, sequences)=>{
7026
+ let openSpans = 0, ret = text.replace(/\x1B\[([0-9;]+)m/g, (_match, sequences)=>{
6984
7027
  let style = '';
6985
7028
  for (let seq of sequences.split(';'))styles[seq] && (style += `${styles[seq]};`);
6986
- return style ? (ansiCodes.push(sequences), `<span style="${style}">`) : closeCode.includes(Number(sequences)) && ansiCodes.length > 0 ? (ansiCodes.pop(), '</span>') : '';
7029
+ return style ? (openSpans++, `<span style="${style}">`) : closeCode.includes(Number(sequences)) && openSpans > 0 ? (openSpans--, '</span>') : '';
6987
7030
  });
6988
- return ansiCodes.length > 0 && (ret += Array(ansiCodes.length + 1).join('</span>')), ret;
7031
+ return openSpans > 0 && (ret += '</span>'.repeat(openSpans)), ret;
6989
7032
  }
6990
7033
  function formatDisplayPath(filePath, isAbsolute, root) {
6991
7034
  if (NODE_MODULES_REGEX.test(filePath)) for (let needle of [
@@ -7039,7 +7082,7 @@ class SocketServer {
7039
7082
  upgrade = (req, socket, head)=>{
7040
7083
  if (!this.wsServer.shouldHandle(req)) return;
7041
7084
  let query = parseQueryString(req);
7042
- this.context.environmentList.map(({ webSocketToken })=>webSocketToken).includes(query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
7085
+ this.context.environmentList.some(({ webSocketToken })=>webSocketToken === query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
7043
7086
  this.wsServer.emit('connection', connection, req);
7044
7087
  }) : socket.destroy();
7045
7088
  };
@@ -7284,7 +7327,7 @@ class BuildManager {
7284
7327
  allCompilers,
7285
7328
  webCompilers,
7286
7329
  earlyWebUpdates
7287
- });
7330
+ }), canServeWebAssetsEarly = earlyWebUpdates1 && !environmentList.some((environment)=>isServingAssets(environment.config) && !isWebTarget(environment.config.output.target));
7288
7331
  applyToCompiler(compiler, (compiler, index)=>{
7289
7332
  let environment = environmentList[index];
7290
7333
  if (!environment) return;
@@ -7348,8 +7391,8 @@ class BuildManager {
7348
7391
  'done' === context.buildState.status && flushAllCallbacks();
7349
7392
  });
7350
7393
  });
7351
- let compiledWebCompilers = new Set(), isWebReady = ()=>earlyWebUpdates1 && compiledWebCompilers.size === webCompilers1.length;
7352
- if (earlyWebUpdates1) for (let item of webCompilers1){
7394
+ let compiledWebCompilers = new Set(), isWebReady = ()=>canServeWebAssetsEarly && compiledWebCompilers.size === webCompilers1.length;
7395
+ if (canServeWebAssetsEarly) for (let item of webCompilers1){
7353
7396
  let reset = ()=>{
7354
7397
  compiledWebCompilers.delete(item);
7355
7398
  };
@@ -7466,11 +7509,12 @@ function gzipMiddleware_gzipMiddleware({ filter, level = node_zlib.constants.Z_B
7466
7509
  let start = ()=>{
7467
7510
  if (started) return;
7468
7511
  if (started = !0, ((res)=>{
7512
+ let index;
7469
7513
  if (res.getHeader('Content-Encoding')) return !1;
7470
7514
  let contentType = res.getHeader('Content-Type');
7471
7515
  if (!contentType) return !1;
7472
7516
  let contentTypeValue = String(contentType);
7473
- if (!CONTENT_TYPE_REGEX.test(contentTypeValue) || 'text/event-stream' === contentTypeValue.split(';', 1)[0].trim().toLowerCase()) return !1;
7517
+ if (!CONTENT_TYPE_REGEX.test(contentTypeValue) || 'text/event-stream' === (-1 === (index = contentTypeValue.indexOf(';')) ? contentTypeValue : contentTypeValue.slice(0, index)).trim().toLowerCase()) return !1;
7474
7518
  let size = res.getHeader('Content-Length');
7475
7519
  return void 0 === size || Number(size) > 1024;
7476
7520
  })(res)) {
@@ -7572,7 +7616,7 @@ let faviconFallbackMiddleware = (req, res, next)=>{
7572
7616
  }, getRequestLoggerMiddleware = (logger)=>(req, res, next)=>{
7573
7617
  let _startAt = process.hrtime();
7574
7618
  finished(res, ()=>{
7575
- let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = status >= 500 ? color.red : status >= 400 ? color.yellow : status >= 300 ? color.cyan : status >= 200 ? color.green : (res)=>res, endAt = process.hrtime(), totalTime = (endAt[0] - _startAt[0]) * 1e3 + (endAt[1] - _startAt[1]) * 1e-6;
7619
+ let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = status >= 500 ? color.red : status >= 400 ? color.yellow : status >= 300 ? color.cyan : status >= 200 ? color.green : (0, (res)=>res), endAt = process.hrtime(), totalTime = (endAt[0] - _startAt[0]) * 1e3 + (endAt[1] - _startAt[1]) * 1e-6;
7576
7620
  logger.debug(`${statusColor(status)} ${method} ${url} ${color.dim(`${totalTime.toFixed(3)} ms`)}`);
7577
7621
  }), next();
7578
7622
  }, notFoundMiddleware = (_req, res, _next)=>{
@@ -7583,7 +7627,7 @@ let faviconFallbackMiddleware = (req, res, next)=>{
7583
7627
  return;
7584
7628
  }
7585
7629
  next();
7586
- }, middlewares_isFileExists = async (filePath, outputFileSystem)=>new Promise((resolve)=>{
7630
+ }, middlewares_isFileExists = (filePath, outputFileSystem)=>new Promise((resolve)=>{
7587
7631
  outputFileSystem.stat(filePath, (_error, stats)=>{
7588
7632
  resolve(!!stats?.isFile());
7589
7633
  });
@@ -7703,11 +7747,10 @@ let isModuleNamespaceObject = (moduleExports)=>'[object Module]' === Object.prot
7703
7747
  let normalizedModuleExports = null !== moduleExports && ('object' == typeof moduleExports || 'function' == typeof moduleExports) ? moduleExports : {
7704
7748
  default: moduleExports
7705
7749
  }, exports = [
7706
- ...new Set([
7707
- 'default',
7708
- ...Object.keys(normalizedModuleExports)
7709
- ])
7710
- ], syntheticModule = new SyntheticModule(exports, ()=>{
7750
+ 'default'
7751
+ ];
7752
+ for (let name of Object.keys(normalizedModuleExports))'default' !== name && exports.push(name);
7753
+ let syntheticModule = new SyntheticModule(exports, ()=>{
7711
7754
  for (let name of exports)if ('default' === name) {
7712
7755
  let defaultExport = isModuleNamespaceObject(normalizedModuleExports) && 'default' in normalizedModuleExports ? normalizedModuleExports.default : moduleExports;
7713
7756
  syntheticModule.setExport(name, defaultExport);
@@ -7732,7 +7775,14 @@ class BasicRunner {
7732
7775
  }
7733
7776
  getRequire() {
7734
7777
  let entryRequire = this.requirers.get('entry');
7735
- return (currentDirectory, modulePath, context = {})=>entryRequire(currentDirectory, Array.isArray(modulePath) ? modulePath : modulePath.split('?')[0], context);
7778
+ return (currentDirectory, modulePath, context = {})=>{
7779
+ let p = modulePath;
7780
+ if ('string' == typeof modulePath) {
7781
+ let index = modulePath.indexOf('?');
7782
+ -1 !== index && (p = modulePath.slice(0, index));
7783
+ }
7784
+ return entryRequire(currentDirectory, p, context);
7785
+ };
7736
7786
  }
7737
7787
  getFile(modulePath, currentDirectory) {
7738
7788
  if (Array.isArray(modulePath)) return {
@@ -8289,7 +8339,9 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8289
8339
  })(options.config, options.devServer, logger);
8290
8340
  for (let middleware of before)middlewares.use(middleware);
8291
8341
  let { onUpgrade } = await (async ({ config, buildManager, context, devServer, middlewares, postCallbacks })=>{
8292
- let launchEditorHandlerPromise, upgradeEvents = [], { server } = config, { logger } = context;
8342
+ let launchEditorHandlerPromise, upgradeEvents = [], { server } = config, { logger } = context, servedEnvironments = context.environmentList.filter((environment)=>isServingAssets(environment.config)), distPaths = [
8343
+ ...new Set(servedEnvironments.map((environment)=>environment.distPath))
8344
+ ];
8293
8345
  if (server.cors) {
8294
8346
  let { default: corsMiddleware } = await import("./cors.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/cors/2.8.6/abeeebb4dd5e2293f01aa9f4c01ff28ab19103cfa7a845442d515e16cf051f35/node_modules/cors/lib/index.js", 23));
8295
8347
  middlewares.use(corsMiddleware('boolean' == typeof server.cors ? {} : server.cors));
@@ -8377,7 +8429,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8377
8429
  logger.error(err), res.writeHead(500), res.end('Failed to list the files');
8378
8430
  }
8379
8431
  })({
8380
- environments: devServer.environments,
8432
+ environments: pick(devServer.environments, servedEnvironments.map((environment)=>environment.name)),
8381
8433
  logger
8382
8434
  })), buildManager && (middlewares.use(buildManager.assetsMiddleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.use(function hotUpdateJsonFallbackMiddleware(req, res, next) {
8383
8435
  let url = req.url;
@@ -8386,9 +8438,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8386
8438
  url.endsWith('.hot-update.json', end) || url.endsWith('.hot-update.json.mjs', end) ? notFoundMiddleware(req, res, next) : next();
8387
8439
  })), buildManager && middlewares.use(getHtmlCompletionMiddleware({
8388
8440
  assetsMiddleware: buildManager.assetsMiddleware,
8389
- distPaths: [
8390
- context.distPath
8391
- ],
8441
+ distPaths,
8392
8442
  outputFileSystem: buildManager.outputFileSystem
8393
8443
  }));
8394
8444
  let publicDirPaths = getPublicDirPaths(config);
@@ -8407,9 +8457,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8407
8457
  for (let callback of postCallbacks)await callback();
8408
8458
  return server.historyApiFallback && (middlewares.use(historyApiFallback_historyApiFallbackMiddleware(logger, !0 === server.historyApiFallback ? {} : server.historyApiFallback)), buildManager?.assetsMiddleware && middlewares.use(buildManager.assetsMiddleware)), buildManager && server.htmlFallback && middlewares.use(getHtmlFallbackMiddleware({
8409
8459
  assetsMiddleware: buildManager.assetsMiddleware,
8410
- distPaths: [
8411
- context.distPath
8412
- ],
8460
+ distPaths,
8413
8461
  logger,
8414
8462
  outputFileSystem: buildManager.outputFileSystem
8415
8463
  })), middlewares.use(faviconFallbackMiddleware), {
@@ -8490,12 +8538,14 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8490
8538
  server: previewServer,
8491
8539
  environments: context.environments
8492
8540
  });
8493
- let webEnvironments = filterWebEnvironments(context.environmentList), assetsMiddleware = createAssetsMiddleware(context, {
8541
+ let servedEnvironments = context.environmentList.filter((environment)=>isServingAssets(environment.config)), assetsMiddleware = createAssetsMiddleware(context, {
8494
8542
  waitForAssets: (callback)=>callback(),
8495
8543
  waitForBuild: (callback)=>callback()
8496
8544
  }, node_fs), htmlMiddlewareOptions = {
8497
8545
  assetsMiddleware,
8498
- distPaths: webEnvironments.map((environment)=>environment.distPath),
8546
+ distPaths: [
8547
+ ...new Set(servedEnvironments.map((environment)=>environment.distPath))
8548
+ ],
8499
8549
  outputFileSystem: node_fs
8500
8550
  };
8501
8551
  if (isVerbose(logger) && middlewares.use(getRequestLoggerMiddleware(logger)), cors) {
@@ -8606,11 +8656,7 @@ function applyDefaultPlugins(pluginManager, context) {
8606
8656
  name: 'rsbuild:source-map',
8607
8657
  setup (api) {
8608
8658
  let normalizeExtractOptions = (extract = {})=>{
8609
- let hasLegacyJs = 'js' in extract, hasFlatFields = [
8610
- 'test',
8611
- 'include',
8612
- 'exclude'
8613
- ].some((key)=>void 0 !== extract[key]);
8659
+ let hasLegacyJs = 'js' in extract, hasFlatFields = void 0 !== extract.test || void 0 !== extract.include || void 0 !== extract.exclude;
8614
8660
  if (!1 === extract.js) return !1;
8615
8661
  if (hasLegacyJs && !hasFlatFields) {
8616
8662
  var target;
@@ -8675,11 +8721,14 @@ function applyDefaultPlugins(pluginManager, context) {
8675
8721
  api.modifyBundlerChain(async (chain, { environment, env })=>{
8676
8722
  let { config } = environment, { buildCache = !1 } = config.performance;
8677
8723
  if (!1 === buildCache) return;
8678
- cacheEnabled = !0;
8679
- let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = getCacheDirectory(cacheConfig, context), buildDependencies = await getBuildDependencies(context, environment, cacheConfig.buildDependencies), cacheVersion = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length ? `${environment.name}-${env}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : `${environment.name}-${env}`;
8724
+ 'new' === process.env.RSBUILD_E2E_CACHE && chain.experiments({
8725
+ ...chain.get('experiments'),
8726
+ newCache: !0
8727
+ }), cacheEnabled = !0;
8728
+ let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = getCacheDirectory(cacheConfig, context), buildDependencies = await getBuildDependencies(context, environment, cacheConfig.buildDependencies), useDigest = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length, cacheVersion = `rsbuild-2.3.3-${environment.name}-${env}`;
8680
8729
  chain.cache({
8681
8730
  type: 'persistent',
8682
- version: cacheVersion,
8731
+ version: useDigest ? `${cacheVersion}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : cacheVersion,
8683
8732
  storage: {
8684
8733
  type: 'filesystem',
8685
8734
  directory: cacheDirectory
@@ -8718,9 +8767,9 @@ function applyDefaultPlugins(pluginManager, context) {
8718
8767
  {
8719
8768
  name: 'rsbuild:output',
8720
8769
  setup (api) {
8721
- api.modifyBundlerChain((chain, { CHAIN_ID, isDev, isProd, isServer, environment, rspack, target })=>{
8770
+ api.modifyBundlerChain(async (chain, { CHAIN_ID, isDev, isProd, isServer, environment, rspack, target })=>{
8722
8771
  var jsAsync;
8723
- let { distPath, config } = environment, publicPath = getPublicPath({
8772
+ let { distPath, config } = environment, publicPath = await getPublicPath({
8724
8773
  config,
8725
8774
  isDev,
8726
8775
  context: api.context
@@ -9692,10 +9741,8 @@ try {
9692
9741
  bodyTags
9693
9742
  };
9694
9743
  }), api.modifyBundlerChain((chain, { CHAIN_ID, environment, isDev })=>{
9695
- let { config, htmlPaths } = environment;
9696
- if (0 === Object.keys(htmlPaths).length) return;
9697
- let { performance: { preload, prefetch } } = config;
9698
- if (!preload && !prefetch) return;
9744
+ let { config, htmlPaths } = environment, { performance: { preload, prefetch } } = config;
9745
+ if (!preload && !prefetch || 0 === Object.keys(htmlPaths).length) return;
9699
9746
  let HTMLCount = chain.entryPoints.values().length, excludes = ((config)=>{
9700
9747
  let { scriptTests, styleTests } = getInlineTests(config);
9701
9748
  return [
@@ -9776,7 +9823,7 @@ try {
9776
9823
  fileName: manifestOptions.filename,
9777
9824
  filter,
9778
9825
  writeToFileEmit: isDev && !0 !== writeToDisk,
9779
- generate: (_seed, files, entries, { compilation })=>{
9826
+ generate: (0, (_seed, files, entries, { compilation })=>{
9780
9827
  let chunkEntries = new Map(), filePathByName = new Map(), licenseMap = new Map(), publicPath = getPublicPathFromCompiler(compilation), integrity = {}, allFiles = files.map((file)=>{
9781
9828
  if (filePathByName.has(file.name) || filePathByName.set(file.name, file.path), file.integrity && (integrity[file.path] = file.integrity), file.chunk) for (let entryName of recursiveChunkEntryNames(file.chunk)){
9782
9829
  let chunkFiles = chunkEntries.get(entryName);
@@ -9832,7 +9879,7 @@ try {
9832
9879
  throw Error(`${color.dim('[rsbuild:manifest]')} \`manifest.generate\` function must return a valid manifest object.`);
9833
9880
  }
9834
9881
  return environment.manifest = manifestData, manifestData;
9835
- }
9882
+ })
9836
9883
  };
9837
9884
  manifestOptions.prefix || (pluginOptions.publicPath = ''), chain.plugin(CHAIN_ID.PLUGIN.MANIFEST).use(RspackManifestPlugin, [
9838
9885
  pluginOptions
@@ -9936,11 +9983,15 @@ try {
9936
9983
  }), api.modifyHTMLTags({
9937
9984
  order: 'post',
9938
9985
  handler: ({ headTags, bodyTags }, { environment })=>{
9939
- let { config } = environment, { nonce } = config.security, allTags = [
9986
+ let { config } = environment, { nonce } = config.security;
9987
+ if (!nonce) return {
9988
+ headTags,
9989
+ bodyTags
9990
+ };
9991
+ for (let tag of [
9940
9992
  ...headTags,
9941
9993
  ...bodyTags
9942
- ];
9943
- if (nonce) for (let tag of allTags)isNonceTag(tag) && (tag.attrs ??= {}, tag.attrs.nonce = nonce);
9994
+ ])isNonceTag(tag) && (tag.attrs ??= {}, tag.attrs.nonce = nonce);
9944
9995
  return {
9945
9996
  headTags,
9946
9997
  bodyTags
@@ -9977,6 +10028,14 @@ async function createRsbuild(options = {}) {
9977
10028
  ...'boolean' == typeof options.loadEnv ? {} : options.loadEnv
9978
10029
  }) : null, configOrFactory = options.config ?? options.rsbuildConfig, config = isFunction(configOrFactory) ? await configOrFactory() : configOrFactory;
9979
10030
  isLoadConfigResult(config) && (loadConfigResult = config, config = config.content), config ||= {};
10031
+ let e2eCache = process.env.RSBUILD_E2E_CACHE;
10032
+ ('new' === e2eCache || 'legacy' === e2eCache) && config.performance?.buildCache === void 0 && (config = {
10033
+ ...config,
10034
+ performance: {
10035
+ ...config.performance,
10036
+ buildCache: !0
10037
+ }
10038
+ });
9980
10039
  let logger = config.customLogger ?? logger_createLogger({
9981
10040
  ...src_logger.options,
9982
10041
  level: src_logger.level
@@ -10008,13 +10067,13 @@ async function createRsbuild(options = {}) {
10008
10067
  let isFirstCompile = !0, { environmentList } = context;
10009
10068
  onBeforeCompile({
10010
10069
  compiler,
10011
- beforeCompile: async ()=>context.hooks.onBeforeBuild.callBatch({
10070
+ beforeCompile: ()=>context.hooks.onBeforeBuild.callBatch({
10012
10071
  bundlerConfigs: rspackConfigs,
10013
10072
  environments: context.environments,
10014
10073
  isWatch,
10015
10074
  isFirstCompile
10016
10075
  }),
10017
- beforeEnvironmentCompile: async (buildIndex)=>{
10076
+ beforeEnvironmentCompile: (buildIndex)=>{
10018
10077
  let environment = environmentList[buildIndex];
10019
10078
  return context.hooks.onBeforeEnvironmentCompile.callBatch({
10020
10079
  environment: environment.name,
@@ -10419,7 +10478,7 @@ let applyServerOptions = (command)=>{
10419
10478
  };
10420
10479
  function setupCommands(argv) {
10421
10480
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10422
- cli.version("2.3.1"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10481
+ cli.version("2.3.3"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10423
10482
  default: 'auto'
10424
10483
  }).option('--dist-path <dir>', 'Set the root directory of output files').option('--source-map', 'Enable source map').option('--env-dir <dir>', 'Set the directory for loading `.env` files').option('--env-mode <mode>', 'Set the env mode to load the `.env.[mode]` file').option('--environment <name>', 'Set the environment name(s) to build', {
10425
10484
  type: [
@@ -10484,7 +10543,7 @@ function setupCommands(argv) {
10484
10543
  }
10485
10544
  function showGreeting() {
10486
10545
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10487
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.3.1\n`);
10546
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.3.3\n`);
10488
10547
  }
10489
10548
  function setupLogLevel(argv) {
10490
10549
  if (argv.length <= 3) return;
@@ -10506,5 +10565,5 @@ function runCLI({ argv = process.argv } = {}) {
10506
10565
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10507
10566
  }
10508
10567
  }
10509
- let src_version = "2.3.1";
10568
+ let src_version = "2.3.3";
10510
10569
  export { core_rspack as rspack, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger_createLogger as createLogger, mergeRsbuildConfig, mrmime_lookup, runCLI, src_logger as logger, src_version as version };