@rsbuild/core 1.5.12 → 1.5.13

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.
Files changed (47) hide show
  1. package/compiled/@jridgewell/remapping/index.js +5 -848
  2. package/compiled/@jridgewell/trace-mapping/index.d.ts +194 -0
  3. package/compiled/@jridgewell/trace-mapping/index.js +1408 -0
  4. package/compiled/@jridgewell/trace-mapping/license +19 -0
  5. package/compiled/@jridgewell/trace-mapping/package.json +1 -0
  6. package/compiled/css-loader/index.js +22 -22
  7. package/compiled/html-rspack-plugin/index.js +14 -14
  8. package/compiled/launch-editor-middleware/index.js +3 -3
  9. package/compiled/memfs/index.d.ts +6 -1
  10. package/compiled/memfs/index.js +662 -636
  11. package/compiled/memfs/package.json +1 -1
  12. package/compiled/postcss/index.js +4 -4
  13. package/compiled/postcss-loader/index.js +6 -6
  14. package/compiled/rspack-manifest-plugin/index.js +4 -4
  15. package/dist/client/hmr.js +58 -19
  16. package/dist/index.cjs +426 -373
  17. package/dist/index.js +420 -369
  18. package/dist-types/configChain.d.ts +0 -4
  19. package/dist-types/server/assets-middleware/getFileFromUrl.d.ts +9 -0
  20. package/dist-types/server/assets-middleware/index.d.ts +48 -0
  21. package/dist-types/server/assets-middleware/middleware.d.ts +3 -0
  22. package/dist-types/server/assets-middleware/setupOutputFileSystem.d.ts +4 -0
  23. package/dist-types/server/assets-middleware/setupWriteToDisk.d.ts +15 -0
  24. package/dist-types/server/browserLogs.d.ts +7 -0
  25. package/dist-types/server/{compilationManager.d.ts → buildManager.d.ts} +11 -11
  26. package/dist-types/server/devMiddlewares.d.ts +2 -2
  27. package/dist-types/server/devServer.d.ts +3 -3
  28. package/dist-types/server/middlewares.d.ts +3 -3
  29. package/dist-types/server/socketServer.d.ts +22 -11
  30. package/dist-types/server/watchFiles.d.ts +2 -2
  31. package/dist-types/types/config.d.ts +13 -6
  32. package/dist-types/types/context.d.ts +14 -4
  33. package/dist-types/types/plugin.d.ts +1 -1
  34. package/dist-types/types/rsbuild.d.ts +8 -1
  35. package/package.json +5 -3
  36. package/dist-types/dev-middleware/index.d.ts +0 -53
  37. package/dist-types/dev-middleware/middleware.d.ts +0 -3
  38. package/dist-types/dev-middleware/utils/getFilenameFromUrl.d.ts +0 -7
  39. package/dist-types/dev-middleware/utils/getPaths.d.ts +0 -7
  40. package/dist-types/dev-middleware/utils/ready.d.ts +0 -2
  41. package/dist-types/dev-middleware/utils/setupHooks.d.ts +0 -3
  42. package/dist-types/dev-middleware/utils/setupOutputFileSystem.d.ts +0 -3
  43. package/dist-types/dev-middleware/utils/setupWriteToDisk.d.ts +0 -7
  44. package/dist-types/server/compilationMiddleware.d.ts +0 -36
  45. /package/dist-types/{dev-middleware/utils → server/assets-middleware}/escapeHtml.d.ts +0 -0
  46. /package/dist-types/{dev-middleware/utils → server/assets-middleware}/memorize.d.ts +0 -0
  47. /package/dist-types/{dev-middleware/utils → server/assets-middleware}/parseTokenList.d.ts +0 -0
package/dist/index.cjs CHANGED
@@ -1563,6 +1563,12 @@ var __webpack_modules__ = {
1563
1563
  "use strict";
1564
1564
  module.exports = require("url");
1565
1565
  },
1566
+ "../../compiled/@jridgewell/trace-mapping/index.js": function(module) {
1567
+ "use strict";
1568
+ module.exports = import("../compiled/@jridgewell/trace-mapping/index.js").then(function(module) {
1569
+ return module;
1570
+ });
1571
+ },
1566
1572
  "../../compiled/chokidar/index.js": function(module) {
1567
1573
  "use strict";
1568
1574
  module.exports = import("../compiled/chokidar/index.js").then(function(module) {
@@ -2627,6 +2633,8 @@ for(var __webpack_i__ in (()=>{
2627
2633
  let message;
2628
2634
  if ('object' == typeof stats) {
2629
2635
  let fileName = function(stats) {
2636
+ let file = stats.file || stats.moduleName;
2637
+ if (file) return formatFileName(file);
2630
2638
  if (stats.moduleIdentifier) {
2631
2639
  let matched = stats.moduleIdentifier.match(/(?:!|^)([^!]+)$/);
2632
2640
  if (matched) {
@@ -2634,8 +2642,7 @@ for(var __webpack_i__ in (()=>{
2634
2642
  if (fileName) return formatFileName(fileName);
2635
2643
  }
2636
2644
  }
2637
- let file = stats.file || stats.moduleName;
2638
- return file ? formatFileName(file) : '';
2645
+ return '';
2639
2646
  }(stats), mainMessage = stats.message, details = verbose && stats.details ? `\nDetails: ${stats.details}\n` : '', stack = verbose && stats.stack ? `\n${stats.stack}` : '', moduleTrace = function(stats) {
2640
2647
  let traceStr = '';
2641
2648
  if (stats.moduleTrace) for (let trace of stats.moduleTrace)trace.originName && (traceStr += `\n @ ${trace.originName}`);
@@ -3519,6 +3526,7 @@ ${section.body}` : section.body).join("\n\n"));
3519
3526
  dev: {
3520
3527
  hmr: !0,
3521
3528
  liveReload: !0,
3529
+ browserLogs: !0,
3522
3530
  watchFiles: [],
3523
3531
  assetPrefix: DEFAULT_ASSET_PREFIX,
3524
3532
  writeToDisk: !1,
@@ -3868,7 +3876,7 @@ ${section.body}` : section.body).join("\n\n"));
3868
3876
  async function createContext(options, userConfig) {
3869
3877
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = (0, external_node_path_.join)(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
3870
3878
  return {
3871
- version: "1.5.12",
3879
+ version: "1.5.13",
3872
3880
  rootPath,
3873
3881
  distPath: '',
3874
3882
  cachePath,
@@ -3904,7 +3912,11 @@ ${section.body}` : section.body).join("\n\n"));
3904
3912
  ...rsbuildConfig
3905
3913
  },
3906
3914
  originalConfig: userConfig,
3907
- specifiedEnvironments
3915
+ specifiedEnvironments,
3916
+ buildState: {
3917
+ status: 'idle',
3918
+ hasErrors: !1
3919
+ }
3908
3920
  };
3909
3921
  }
3910
3922
  let normalizePluginObject = (plugin)=>{
@@ -4086,7 +4098,6 @@ ${section.body}` : section.body).join("\n\n"));
4086
4098
  STYLUS_RAW: 'stylus-raw',
4087
4099
  STYLUS_INLINE: 'stylus-inline',
4088
4100
  SVG: 'svg',
4089
- PUG: 'pug',
4090
4101
  VUE: 'vue',
4091
4102
  WASM: 'wasm',
4092
4103
  SVELTE: 'svelte'
@@ -4106,7 +4117,6 @@ ${section.body}` : section.body).join("\n\n"));
4106
4117
  LESS: 'less',
4107
4118
  STYLUS: 'stylus',
4108
4119
  URL: 'url',
4109
- PUG: 'pug',
4110
4120
  VUE: 'vue',
4111
4121
  SWC: 'swc',
4112
4122
  SVGR: 'svgr',
@@ -4237,6 +4247,7 @@ ${section.body}` : section.body).join("\n\n"));
4237
4247
  'hmr',
4238
4248
  'client',
4239
4249
  'liveReload',
4250
+ 'browserLogs',
4240
4251
  'writeToDisk',
4241
4252
  'assetPrefix',
4242
4253
  'progressBar',
@@ -4412,7 +4423,7 @@ ${section.body}` : section.body).join("\n\n"));
4412
4423
  async function createCompiler_createCompiler(options) {
4413
4424
  let version;
4414
4425
  index_js_namespaceObject.logger.debug('creating compiler');
4415
- let { context } = options, { rspackConfigs } = await initConfigs(options);
4426
+ let HOOK_NAME = 'rsbuild:compiler', { context } = options, { rspackConfigs } = await initConfigs(options);
4416
4427
  if (await context.hooks.onBeforeCreateCompiler.callBatch({
4417
4428
  bundlerConfigs: rspackConfigs,
4418
4429
  environments: context.environments
@@ -4428,7 +4439,7 @@ ${section.body}` : section.body).join("\n\n"));
4428
4439
  let isMultiCompiler = rspackConfigs.length > 1, compiler = isMultiCompiler ? rspack_rspack(rspackConfigs) : rspack_rspack(rspackConfigs[0]), isVersionLogged = !1, isCompiling = !1, logRspackVersion = ()=>{
4429
4440
  isVersionLogged || (index_js_namespaceObject.logger.debug(`using Rspack v${rspack_rspack.rspackVersion}`), isVersionLogged = !0);
4430
4441
  }, lazyModules = new Set();
4431
- return compiler.hooks.infrastructureLog.tap('rsbuild:compiling', (name, _, args)=>{
4442
+ return compiler.hooks.infrastructureLog.tap(HOOK_NAME, (name, _, args)=>{
4432
4443
  let log = args[0];
4433
4444
  if ('LazyCompilation' === name && 'string' == typeof log && log.startsWith('lazy-compilation-proxy')) {
4434
4445
  let resource = log.split(' ')[0];
@@ -4439,8 +4450,10 @@ ${section.body}` : section.body).join("\n\n"));
4439
4450
  lazyModules.add(relativePath);
4440
4451
  }
4441
4452
  }
4442
- }), compiler.hooks.watchRun.tap('rsbuild:compiling', (compiler)=>{
4443
- logRspackVersion(), isCompiling || function(compiler, context, lazyModules) {
4453
+ }), compiler.hooks.run.tap(HOOK_NAME, ()=>{
4454
+ context.buildState.status = 'building';
4455
+ }), compiler.hooks.watchRun.tap(HOOK_NAME, (compiler)=>{
4456
+ context.buildState.status = 'building', logRspackVersion(), isCompiling || function(compiler, context, lazyModules) {
4444
4457
  let { modifiedFiles } = compiler, changedFiles = modifiedFiles?.size ? Array.from(modifiedFiles) : lazyModules.size ? Array.from(lazyModules) : null;
4445
4458
  if (changedFiles?.length) {
4446
4459
  let fileInfo = formatFileList(changedFiles, context.rootPath);
@@ -4455,28 +4468,30 @@ ${section.body}` : section.body).join("\n\n"));
4455
4468
  }
4456
4469
  index_js_namespaceObject.logger.start('build started...');
4457
4470
  }(compiler, context, lazyModules), lazyModules.size && lazyModules.clear(), isCompiling = !0;
4458
- }), 'build' === context.action && (isMultiCompiler ? compiler.compilers[0] : compiler).hooks.run.tap('rsbuild:run', ()=>{
4471
+ }), compiler.hooks.invalid.tap(HOOK_NAME, ()=>{
4472
+ context.buildState.status = 'idle', context.buildState.hasErrors = !1;
4473
+ }), 'build' === context.action && (isMultiCompiler ? compiler.compilers[0] : compiler).hooks.run.tap(HOOK_NAME, ()=>{
4459
4474
  index_js_namespaceObject.logger.info('build started...'), logRspackVersion();
4460
- }), compiler.hooks.done.tap('rsbuild:done', (stats)=>{
4461
- ((stats)=>{
4462
- let statsOptions = getStatsOptions(compiler), statsJson = stats.toJson({
4463
- children: !0,
4464
- moduleTrace: !0,
4465
- timings: !0,
4466
- preset: 'errors-warnings',
4467
- ...statsOptions
4468
- }), printTime = (c, index)=>{
4469
- if (c.time) {
4470
- let time = prettyTime(c.time / 1000), { name } = rspackConfigs[index], suffix = name && isMultiCompiler ? picocolors_index_js_default().dim(` (${name})`) : '';
4471
- index_js_namespaceObject.logger.ready(`built in ${time}${suffix}`);
4472
- }
4473
- }, hasErrors = stats.hasErrors();
4474
- hasErrors || (isMultiCompiler && statsJson.children?.length ? statsJson.children.forEach((c, index)=>{
4475
- printTime(c, index);
4476
- }) : printTime(statsJson, 0));
4477
- let { message, level } = formatStats(statsJson, hasErrors);
4478
- 'error' === level && index_js_namespaceObject.logger.error(message), 'warning' === level && index_js_namespaceObject.logger.warn(message), isCompiling = !1;
4479
- })(stats);
4475
+ }), compiler.hooks.done.tap(HOOK_NAME, (stats)=>{
4476
+ let hasErrors = stats.hasErrors();
4477
+ context.buildState.hasErrors = hasErrors, context.buildState.status = 'done';
4478
+ let statsOptions = getStatsOptions(compiler), statsJson = stats.toJson({
4479
+ children: !0,
4480
+ moduleTrace: !0,
4481
+ timings: !0,
4482
+ preset: 'errors-warnings',
4483
+ ...statsOptions
4484
+ }), printTime = (c, index)=>{
4485
+ if (c.time) {
4486
+ let time = prettyTime(c.time / 1000), { name } = rspackConfigs[index], suffix = name && isMultiCompiler ? picocolors_index_js_default().dim(` (${name})`) : '';
4487
+ index_js_namespaceObject.logger.ready(`built in ${time}${suffix}`);
4488
+ }
4489
+ };
4490
+ hasErrors || (isMultiCompiler && statsJson.children?.length ? statsJson.children.forEach((c, index)=>{
4491
+ printTime(c, index);
4492
+ }) : printTime(statsJson, 0));
4493
+ let { message, level } = formatStats(statsJson, hasErrors);
4494
+ 'error' === level && index_js_namespaceObject.logger.error(message), 'warning' === level && index_js_namespaceObject.logger.warn(message), isCompiling = !1;
4480
4495
  }), 'dev' === context.action && registerDevHook({
4481
4496
  context,
4482
4497
  compiler,
@@ -5897,75 +5912,74 @@ ${section.body}` : section.body).join("\n\n"));
5897
5912
  }
5898
5913
  };
5899
5914
  }
5900
- }, swc_require = (0, external_node_module_.createRequire)(__rslib_import_meta_url__), builtinSwcLoaderName = 'builtin:swc-loader', isCliShortcutsEnabled = (config)=>config.dev.cliShortcuts && isTTY('stdin');
5901
- async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer, customShortcuts }) {
5902
- let shortcuts = [
5903
- {
5904
- key: 'c',
5905
- description: `${picocolors_index_js_default().bold('c + enter')} ${picocolors_index_js_default().dim('clear console')}`,
5906
- action: ()=>{
5907
- console.clear();
5915
+ }, swc_require = (0, external_node_module_.createRequire)(__rslib_import_meta_url__), builtinSwcLoaderName = 'builtin:swc-loader';
5916
+ async function getLocalhostResolvedAddress() {
5917
+ let { promises: dns } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "node:dns")), [defaultLookup, explicitLookup] = await Promise.all([
5918
+ dns.lookup('localhost'),
5919
+ dns.lookup('localhost', {
5920
+ verbatim: !0
5921
+ })
5922
+ ]);
5923
+ return defaultLookup.family === explicitLookup.family && defaultLookup.address === explicitLookup.address ? void 0 : defaultLookup.address;
5924
+ }
5925
+ async function resolveHostname(host = 'localhost') {
5926
+ var host1;
5927
+ if ('localhost' === host) {
5928
+ let resolvedAddress = await getLocalhostResolvedAddress();
5929
+ if (resolvedAddress) return resolvedAddress;
5930
+ }
5931
+ return void 0 === host || (host1 = host, new Set([
5932
+ '0.0.0.0',
5933
+ '::',
5934
+ '0000:0000:0000:0000:0000:0000:0000:0000'
5935
+ ]).has(host1)) ? 'localhost' : host;
5936
+ }
5937
+ var on_finished = __webpack_require__("../../node_modules/.pnpm/on-finished@2.4.1/node_modules/on-finished/index.js"), on_finished_default = __webpack_require__.n(on_finished), range_parser = __webpack_require__("../../node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js"), range_parser_default = __webpack_require__.n(range_parser);
5938
+ let matchHtmlRegExp = /["'&<>]/, external_node_querystring_namespaceObject = require("node:querystring"), UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
5939
+ function getFileFromUrl(url, outputFileSystem, environments) {
5940
+ let pathname;
5941
+ try {
5942
+ let urlObject = new URL(url, 'http://localhost');
5943
+ urlObject.pathname && (pathname = (0, external_node_querystring_namespaceObject.unescape)(urlObject.pathname));
5944
+ } catch {
5945
+ return;
5946
+ }
5947
+ if (pathname) {
5948
+ if (pathname.includes('\0')) return {
5949
+ errorCode: 400
5950
+ };
5951
+ if (UP_PATH_REGEXP.test(external_node_path_default().normalize(`./${pathname}`))) return {
5952
+ errorCode: 403
5953
+ };
5954
+ for (let distPath of new Set(Object.values(environments).map((env)=>env.distPath))){
5955
+ let fsStats, filename = external_node_path_default().join(distPath, pathname);
5956
+ try {
5957
+ fsStats = outputFileSystem.statSync?.(filename);
5958
+ } catch {
5959
+ continue;
5908
5960
  }
5909
- },
5910
- {
5911
- key: 'o',
5912
- description: `${picocolors_index_js_default().bold('o + enter')} ${picocolors_index_js_default().dim('open in browser')}`,
5913
- action: openPage
5914
- },
5915
- {
5916
- key: 'q',
5917
- description: `${picocolors_index_js_default().bold('q + enter')} ${picocolors_index_js_default().dim('quit process')}`,
5918
- action: async ()=>{
5919
- try {
5920
- await closeServer();
5921
- } finally{
5922
- process.exit(0);
5961
+ if (fsStats) {
5962
+ if (fsStats.isFile()) return {
5963
+ filename,
5964
+ fsStats
5965
+ };
5966
+ if (fsStats.isDirectory()) {
5967
+ filename = external_node_path_default().join(filename, 'index.html');
5968
+ try {
5969
+ fsStats = outputFileSystem.statSync?.(filename);
5970
+ } catch {
5971
+ continue;
5972
+ }
5973
+ if (!fsStats) continue;
5974
+ if (fsStats.isFile()) return {
5975
+ filename,
5976
+ fsStats
5977
+ };
5923
5978
  }
5924
5979
  }
5925
- },
5926
- restartServer ? {
5927
- key: 'r',
5928
- description: `${picocolors_index_js_default().bold('r + enter')} ${picocolors_index_js_default().dim('restart server')}`,
5929
- action: restartServer
5930
- } : null,
5931
- {
5932
- key: 'u',
5933
- description: `${picocolors_index_js_default().bold('u + enter')} ${picocolors_index_js_default().dim('show urls')}`,
5934
- action: printUrls
5935
- }
5936
- ].filter(Boolean);
5937
- if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${picocolors_index_js_default().dim('[rsbuild:config]')} ${picocolors_index_js_default().yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
5938
- help && index_js_namespaceObject.logger.log(!0 === help ? ` ➜ ${picocolors_index_js_default().dim('press')} ${picocolors_index_js_default().bold('h + enter')} ${picocolors_index_js_default().dim('to show shortcuts')}\n` : ` ➜ ${help}\n`);
5939
- let { createInterface } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "node:readline")), rl = createInterface({
5940
- input: process.stdin
5941
- });
5942
- return rl.on('line', (input)=>{
5943
- if ('h' === input) {
5944
- let message = `\n ${picocolors_index_js_default().bold(picocolors_index_js_default().blue('Shortcuts:'))}\n`;
5945
- for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
5946
- index_js_namespaceObject.logger.log(message);
5947
5980
  }
5948
- for (let shortcut of shortcuts)if (input === shortcut.key) return void shortcut.action();
5949
- }), ()=>{
5950
- rl.close();
5951
- };
5952
- }
5953
- var on_finished = __webpack_require__("../../node_modules/.pnpm/on-finished@2.4.1/node_modules/on-finished/index.js"), on_finished_default = __webpack_require__.n(on_finished), range_parser = __webpack_require__("../../node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js"), range_parser_default = __webpack_require__.n(range_parser);
5954
- let matchHtmlRegExp = /["'&<>]/, external_node_querystring_namespaceObject = require("node:querystring");
5955
- function memorize(fn, { cache = new Map() } = {}, callback) {
5956
- return (...arguments_)=>{
5957
- let [key] = arguments_, cacheItem = cache.get(key);
5958
- if (cacheItem) return cacheItem.data;
5959
- let result = fn.apply(void 0, arguments_);
5960
- return callback && (result = callback(result)), cache.set(key, {
5961
- data: result
5962
- }), result;
5963
- };
5981
+ }
5964
5982
  }
5965
- let memoizedParse = memorize(external_node_url_.parse, void 0, (value)=>{
5966
- var input;
5967
- return value.pathname && (input = value.pathname, value.pathname = (0, external_node_querystring_namespaceObject.unescape)(input)), value;
5968
- }), UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
5969
5983
  function parseTokenList(str) {
5970
5984
  let end = 0, start = 0, list = [];
5971
5985
  for(let i = 0, len = str.length; i < len; i++)switch(str.charCodeAt(i)){
@@ -5980,9 +5994,6 @@ ${section.body}` : section.body).join("\n\n"));
5980
5994
  }
5981
5995
  return start !== end && list.push(str.substring(start, end)), list;
5982
5996
  }
5983
- function ready(context, callback) {
5984
- context.state ? callback(context.stats) : context.callbacks.push(callback);
5985
- }
5986
5997
  async function getContentType(str) {
5987
5998
  let { lookup } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "../../compiled/mrmime/index.js")), mime = lookup(str);
5988
5999
  return !!mime && ((mime.startsWith('text/') || 'application/json' === mime || 'application/manifest+json' === mime) && (mime += '; charset=utf-8'), mime);
@@ -6001,58 +6012,113 @@ ${section.body}` : section.body).join("\n\n"));
6001
6012
  404: 'Not Found',
6002
6013
  416: 'Range Not Satisfiable',
6003
6014
  500: 'Internal Server Error'
6004
- }, parseRangeHeaders = memorize((value)=>{
6015
+ }, parseRangeHeaders = function(fn, { cache = new Map() } = {}, callback) {
6016
+ return (...arguments_)=>{
6017
+ let [key] = arguments_, cacheItem = cache.get(key);
6018
+ if (cacheItem) return cacheItem.data;
6019
+ let result = fn.apply(void 0, arguments_);
6020
+ return cache.set(key, {
6021
+ data: result
6022
+ }), result;
6023
+ };
6024
+ }((value)=>{
6005
6025
  let [len, rangeHeader] = value.split('|');
6006
6026
  return range_parser_default()(Number(len), rangeHeader, {
6007
6027
  combine: !0
6008
6028
  });
6009
- });
6010
- async function setupOutputFileSystem(options, compilers) {
6011
- if (!0 !== options.writeToDisk) {
6029
+ }), acceptedMethods = [
6030
+ 'GET',
6031
+ 'HEAD'
6032
+ ];
6033
+ async function setupOutputFileSystem(writeToDisk, compilers) {
6034
+ if (!0 !== writeToDisk) {
6012
6035
  let { createFsFromVolume, Volume } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "../../../compiled/memfs/index.js")), outputFileSystem = createFsFromVolume(new Volume());
6013
6036
  for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
6014
6037
  }
6015
6038
  return compilers[0].outputFileSystem;
6016
6039
  }
6017
- let noop = ()=>{};
6018
- async function devMiddleware(compiler, options = {}) {
6040
+ let noop = ()=>{}, assets_middleware_require = (0, external_node_module_.createRequire)(__rslib_import_meta_url__), assetsMiddleware = async ({ config, compiler, context, socketServer, resolvedPort })=>{
6041
+ var config1, environments, context1, ready, outputFileSystem;
6042
+ let watching, writeToDiskValues, resolvedHost = await resolveHostname(config.server.host), { environments: environments1 } = context;
6043
+ applyToCompiler(compiler, (compiler, index)=>{
6044
+ let environment = Object.values(environments1).find((env)=>env.index === index);
6045
+ if (!environment) return;
6046
+ let token = environment.webSocketToken;
6047
+ token && (!function({ config, compiler, token, resolvedHost, resolvedPort }) {
6048
+ var devConfig;
6049
+ let clientPaths;
6050
+ if (!((compiler)=>{
6051
+ let { target } = compiler.options;
6052
+ return !!target && (Array.isArray(target) ? target.includes('web') : 'web' === target);
6053
+ })(compiler)) return;
6054
+ let clientPaths1 = (devConfig = config.dev, clientPaths = [], (devConfig.hmr || devConfig.liveReload) && (hmrClientPath || (hmrClientPath = assets_middleware_require.resolve('@rsbuild/core/client/hmr')), clientPaths.push(hmrClientPath), devConfig.client?.overlay && (overlayClientPath || (overlayClientPath = assets_middleware_require.resolve('@rsbuild/core/client/overlay')), clientPaths.push(overlayClientPath))), clientPaths);
6055
+ if (!clientPaths1.length) return;
6056
+ let clientConfig = {
6057
+ ...config.dev.client
6058
+ };
6059
+ for (let clientPath of ('<port>' === clientConfig.port && (clientConfig.port = resolvedPort), new compiler.webpack.DefinePlugin({
6060
+ RSBUILD_WEB_SOCKET_TOKEN: JSON.stringify(token),
6061
+ RSBUILD_CLIENT_CONFIG: JSON.stringify(clientConfig),
6062
+ RSBUILD_SERVER_HOST: JSON.stringify(resolvedHost),
6063
+ RSBUILD_SERVER_PORT: JSON.stringify(resolvedPort),
6064
+ RSBUILD_DEV_LIVE_RELOAD: config.dev.liveReload,
6065
+ RSBUILD_DEV_BROWSER_LOGS: config.dev.browserLogs
6066
+ }).apply(compiler), clientPaths1))new compiler.webpack.EntryPlugin(compiler.context, clientPath, {
6067
+ name: void 0
6068
+ }).apply(compiler);
6069
+ }({
6070
+ token,
6071
+ config: environment.config,
6072
+ compiler,
6073
+ resolvedHost,
6074
+ resolvedPort
6075
+ }), (({ compiler, token, socketServer })=>{
6076
+ ((compiler)=>{
6077
+ let { target } = compiler.options;
6078
+ return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
6079
+ })(compiler) || (compiler.hooks.invalid.tap('rsbuild-dev-server', (fileName)=>{
6080
+ if ('string' == typeof fileName && fileName.endsWith('.html')) return void socketServer.sockWrite({
6081
+ type: 'static-changed'
6082
+ }, token);
6083
+ }), compiler.hooks.done.tap('rsbuild-dev-server', (stats)=>{
6084
+ socketServer.onBuildDone(stats, token);
6085
+ }));
6086
+ })({
6087
+ compiler,
6088
+ socketServer,
6089
+ token
6090
+ }));
6091
+ });
6019
6092
  let compilers = helpers_isMultiCompiler(compiler) ? compiler.compilers : [
6020
6093
  compiler
6021
- ], context = {
6022
- state: !1,
6023
- stats: void 0,
6024
- callbacks: [],
6025
- options,
6026
- compilers
6027
- };
6028
- var context1, context2 = context, compiler1 = compiler;
6029
- function invalid() {
6030
- context2.state = !1, context2.stats = void 0;
6031
- }
6032
- compiler1.hooks.watchRun.tap('rsbuild-dev-middleware', invalid), compiler1.hooks.invalid.tap('rsbuild-dev-middleware', invalid), compiler1.hooks.done.tap('rsbuild-dev-middleware', function(stats) {
6033
- context2.state = !0, context2.stats = stats, process.nextTick(()=>{
6034
- let { state, callbacks } = context2;
6035
- state && (context2.callbacks = [], callbacks.forEach((callback)=>{
6036
- callback(stats);
6037
- }));
6094
+ ], callbacks = [];
6095
+ compiler.hooks.done.tap('rsbuild-dev-middleware', ()=>{
6096
+ process.nextTick(()=>{
6097
+ 'done' === context.buildState.status && (callbacks.forEach((callback)=>{
6098
+ callback();
6099
+ }), callbacks.length = 0);
6038
6100
  });
6039
- }), options.writeToDisk && function(context) {
6040
- let { compilers } = context;
6101
+ });
6102
+ let writeToDisk = (config1 = config.dev, 1 === new Set(writeToDiskValues = Object.values(environments = environments1).map((env)=>env.config.dev.writeToDisk)).size ? writeToDiskValues[0] : (filePath, name)=>{
6103
+ let { writeToDisk } = config1;
6104
+ return name && environments[name] && (writeToDisk = environments[name].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
6105
+ });
6106
+ writeToDisk && function(compilers, writeToDisk) {
6041
6107
  for (let compiler of compilers)compiler.hooks.emit.tap('DevMiddleware', ()=>{
6042
6108
  compiler.__hasRsbuildAssetEmittedCallback || (compiler.hooks.assetEmitted.tapAsync('DevMiddleware', (_file, info, callback)=>{
6043
- let { targetPath, content, compilation } = info, { writeToDisk: filter } = context.options;
6044
- if (!(!filter || 'function' != typeof filter || filter(targetPath, compilation.name))) return void callback();
6109
+ let { targetPath, content, compilation } = info;
6110
+ if (!(!writeToDisk || 'function' != typeof writeToDisk || writeToDisk(targetPath, compilation.name))) return void callback();
6045
6111
  let dir = external_node_path_default().dirname(targetPath), name = compiler.options.name ? `Child "${compiler.options.name}": ` : '';
6046
6112
  external_node_fs_default().mkdir(dir, {
6047
6113
  recursive: !0
6048
6114
  }, (mkdirError)=>{
6049
6115
  if (mkdirError) {
6050
- index_js_namespaceObject.logger.error(`[rsbuild-dev-middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
6116
+ index_js_namespaceObject.logger.error(`[rsbuild:middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
6051
6117
  return;
6052
6118
  }
6053
6119
  external_node_fs_default().writeFile(targetPath, content, (writeFileError)=>{
6054
6120
  if (writeFileError) {
6055
- index_js_namespaceObject.logger.error(`[rsbuild-dev-middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
6121
+ index_js_namespaceObject.logger.error(`[rsbuild:middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
6056
6122
  return;
6057
6123
  }
6058
6124
  callback();
@@ -6060,21 +6126,19 @@ ${section.body}` : section.body).join("\n\n"));
6060
6126
  });
6061
6127
  }), compiler.__hasRsbuildAssetEmittedCallback = !0);
6062
6128
  });
6063
- }(context), context.outputFileSystem = await setupOutputFileSystem(options, compilers);
6064
- let instance = (context1 = context, async function(req, res, next) {
6129
+ }(compilers, writeToDisk);
6130
+ let outputFileSystem1 = await setupOutputFileSystem(writeToDisk, compilers), instance = (context1 = context, ready = (callback)=>{
6131
+ 'done' === context.buildState.status ? callback() : callbacks.push(callback);
6132
+ }, outputFileSystem = outputFileSystem1, async function(req, res, next) {
6133
+ let { environments } = context1;
6065
6134
  async function goNext() {
6066
6135
  return new Promise((resolve)=>{
6067
- ready(context1, ()=>{
6068
- res.locals = res.locals || {}, res.locals.webpack = {
6069
- devMiddleware: context1
6070
- }, next(), resolve();
6136
+ ready(()=>{
6137
+ next(), resolve();
6071
6138
  });
6072
6139
  });
6073
6140
  }
6074
- if (req.method && ![
6075
- 'GET',
6076
- 'HEAD'
6077
- ].includes(req.method)) return void await goNext();
6141
+ if (req.method && !acceptedMethods.includes(req.method)) return void await goNext();
6078
6142
  function sendError(status, options) {
6079
6143
  let content = statuses[status] || String(status), document1 = Buffer.from(`<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Error</title>\n</head>\n<body>\n<pre>${function(input) {
6080
6144
  let htmlEntity, match = matchHtmlRegExp.exec(input);
@@ -6116,76 +6180,17 @@ ${section.body}` : section.body).join("\n\n"));
6116
6180
  let byteLength = Buffer.byteLength(document1);
6117
6181
  res.setHeader('Content-Length', byteLength), res.end(document1);
6118
6182
  }
6119
- async function processRequest() {
6120
- var stat, range, offset, filename, outputFileSystem, start, end;
6121
- let bufferOrStream, byteLength, end1, extra = {}, filename1 = function(context, url, extra = {}) {
6122
- let foundFilename, urlObject, paths = function(context) {
6123
- let { stats, options } = context, childStats = stats.stats ? stats.stats : [
6124
- stats
6125
- ], publicPaths = [];
6126
- for (let { compilation } of childStats){
6127
- let outputPath = compilation.getPath(compilation.outputOptions.path || ''), publicPath = options.publicPath ? compilation.getPath(options.publicPath) : compilation.outputOptions.publicPath ? compilation.getPath(compilation.outputOptions.publicPath) : '';
6128
- publicPaths.push({
6129
- outputPath,
6130
- publicPath
6131
- });
6132
- }
6133
- return publicPaths;
6134
- }(context);
6135
- try {
6136
- urlObject = memoizedParse(url, !1, !0);
6137
- } catch (_ignoreError) {
6138
- return;
6139
- }
6140
- for (let { publicPath, outputPath } of paths){
6141
- let filename, publicPathObject;
6142
- try {
6143
- publicPathObject = memoizedParse('auto' !== publicPath && publicPath ? publicPath : '/', !1, !0);
6144
- } catch (_ignoreError) {
6145
- continue;
6146
- }
6147
- let { pathname } = urlObject, { pathname: publicPathPathname } = publicPathObject;
6148
- if (pathname?.startsWith(publicPathPathname)) {
6149
- if (pathname.includes('\u0000')) {
6150
- extra.errorCode = 400;
6151
- return;
6152
- }
6153
- if (UP_PATH_REGEXP.test(external_node_path_.normalize(`./${pathname}`))) {
6154
- extra.errorCode = 403;
6155
- return;
6156
- }
6157
- filename = external_node_path_.join(outputPath, pathname.slice(publicPathPathname.length));
6158
- try {
6159
- extra.stats = context.outputFileSystem.statSync(filename);
6160
- } catch (_ignoreError) {
6161
- continue;
6162
- }
6163
- if (extra.stats.isFile()) {
6164
- foundFilename = filename;
6165
- break;
6166
- }
6167
- if (extra.stats.isDirectory()) {
6168
- filename = external_node_path_.join(filename, 'index.html');
6169
- try {
6170
- extra.stats = context.outputFileSystem.statSync(filename);
6171
- } catch (__ignoreError) {
6172
- continue;
6173
- }
6174
- if (extra.stats.isFile()) {
6175
- foundFilename = filename;
6176
- break;
6177
- }
6178
- }
6179
- }
6180
- }
6181
- return foundFilename;
6182
- }(context1, req.url, extra);
6183
- if (extra.errorCode) {
6184
- 403 === extra.errorCode && index_js_namespaceObject.logger.error(`[rsbuild-dev-middleware] Malicious path "${filename1}".`), sendError(extra.errorCode);
6183
+ ready(async function() {
6184
+ var stat, range, offset, filename, outputFileSystem1, start, end;
6185
+ let bufferOrStream, byteLength, end1;
6186
+ if (!req.url) return void await goNext();
6187
+ let resolved = getFileFromUrl(req.url, outputFileSystem, environments);
6188
+ if (!resolved) return void await goNext();
6189
+ if ('errorCode' in resolved) {
6190
+ 403 === resolved.errorCode && index_js_namespaceObject.logger.error(`[rsbuild:middleware] Malicious path "${req.url}".`), sendError(resolved.errorCode);
6185
6191
  return;
6186
6192
  }
6187
- if (!filename1) return void await goNext();
6188
- let { size } = extra.stats, len = size, offset1 = 0;
6193
+ let { fsStats, filename: filename1 } = resolved, { size } = fsStats, len = size, offset1 = 0;
6189
6194
  if (!res.getHeader('Content-Type')) {
6190
6195
  let contentType = await getContentType(filename1);
6191
6196
  contentType && res.setHeader('Content-Type', contentType);
@@ -6195,8 +6200,8 @@ ${section.body}` : section.body).join("\n\n"));
6195
6200
  let rage = req.headers.range;
6196
6201
  if (rage && BYTES_RANGE_REGEXP.test(rage)) return rage;
6197
6202
  }();
6198
- if (!res.getHeader('ETag') && extra.stats) {
6199
- let mtime, size, hash = (mtime = (stat = extra.stats).mtime.getTime().toString(16), size = stat.size.toString(16), `W/"${size}-${mtime}"`);
6203
+ if (!res.getHeader('ETag') && fsStats) {
6204
+ let mtime, size, hash = (mtime = (stat = fsStats).mtime.getTime().toString(16), size = stat.size.toString(16), `W/"${size}-${mtime}"`);
6200
6205
  res.setHeader('ETag', hash);
6201
6206
  }
6202
6207
  if (req.headers['if-match'] || req.headers['if-unmodified-since'] || req.headers['if-none-match'] || req.headers['if-modified-since']) {
@@ -6259,14 +6264,14 @@ ${section.body}` : section.body).join("\n\n"));
6259
6264
  let lastModified = res.getHeader('Last-Modified');
6260
6265
  return !lastModified || parseHttpDate(lastModified) <= parseHttpDate(ifRange);
6261
6266
  }() && (parsedRanges = []), -1 === parsedRanges) {
6262
- index_js_namespaceObject.logger.error("[rsbuild-dev-middleware] Unsatisfiable range for 'Range' header."), res.setHeader('Content-Range', getValueContentRangeHeader('bytes', size)), sendError(416, {
6267
+ index_js_namespaceObject.logger.error("[rsbuild:middleware] Unsatisfiable range for 'Range' header."), res.setHeader('Content-Range', getValueContentRangeHeader('bytes', size)), sendError(416, {
6263
6268
  headers: {
6264
6269
  'Content-Range': res.getHeader('Content-Range')
6265
6270
  }
6266
6271
  });
6267
6272
  return;
6268
6273
  }
6269
- if (-2 === parsedRanges ? index_js_namespaceObject.logger.error("[rsbuild-dev-middleware] A malformed 'Range' header was provided. A regular response will be sent for this request.") : parsedRanges.length > 1 && index_js_namespaceObject.logger.error("[rsbuild-dev-middleware] A 'Range' header with multiple ranges was provided. Multiple ranges are not supported, so a regular response will be sent for this request."), -2 !== parsedRanges && 1 === parsedRanges.length) {
6274
+ if (-2 === parsedRanges ? index_js_namespaceObject.logger.error("[rsbuild:middleware] A malformed 'Range' header was provided. A regular response will be sent for this request.") : parsedRanges.length > 1 && index_js_namespaceObject.logger.error("[rsbuild:middleware] A 'Range' header with multiple ranges was provided. Multiple ranges are not supported, so a regular response will be sent for this request."), -2 !== parsedRanges && 1 === parsedRanges.length) {
6270
6275
  let offset;
6271
6276
  res.statusCode = 206, res.setHeader('Content-Range', getValueContentRangeHeader('bytes', size, parsedRanges[0])), [offset1, len] = [
6272
6277
  offset = (range = parsedRanges[0]).start,
@@ -6280,14 +6285,14 @@ ${section.body}` : section.body).join("\n\n"));
6280
6285
  ]);
6281
6286
  try {
6282
6287
  let bufferOrStream1;
6283
- ({ bufferOrStream, byteLength } = (filename = filename1, outputFileSystem = context1.outputFileSystem, start = start1, end = end2, {
6284
- bufferOrStream: bufferOrStream1 = outputFileSystem.createReadStream(filename, {
6288
+ ({ bufferOrStream, byteLength } = (filename = filename1, outputFileSystem1 = outputFileSystem, start = start1, end = end2, {
6289
+ bufferOrStream: bufferOrStream1 = outputFileSystem1.createReadStream(filename, {
6285
6290
  start,
6286
6291
  end
6287
6292
  }),
6288
6293
  byteLength: 0 === end ? 0 : end - start + 1
6289
6294
  }));
6290
- } catch (_ignoreError) {
6295
+ } catch {
6291
6296
  await goNext();
6292
6297
  return;
6293
6298
  }
@@ -6313,107 +6318,101 @@ ${section.body}` : section.body).join("\n\n"));
6313
6318
  sendError(500);
6314
6319
  }
6315
6320
  }), bufferOrStream.pipe(res), on_finished_default()(res, cleanup);
6316
- }
6317
- ready(context1, processRequest);
6321
+ });
6318
6322
  });
6319
6323
  return instance.watch = ()=>{
6320
- if (compiler.watching) context.watching = compiler.watching;
6324
+ if (compiler.watching) watching = compiler.watching;
6321
6325
  else {
6322
- let errorHandler = (error)=>{
6326
+ let watchOptions = compilers.length > 1 ? compilers.map(({ options })=>options.watchOptions || {}) : compilers[0].options.watchOptions || {};
6327
+ watching = compiler.watch(watchOptions, (error)=>{
6323
6328
  error && (error.message?.includes('× Error:') && (error.message = error.message.replace('× Error:', '').trim()), index_js_namespaceObject.logger.error(error));
6324
- };
6325
- if (compilers.length > 1) {
6326
- let watchOptions = compilers.map((childCompiler)=>childCompiler.options.watchOptions || {});
6327
- context.watching = compiler.watch(watchOptions, errorHandler);
6328
- } else {
6329
- let watchOptions = compilers[0].options.watchOptions || {};
6330
- context.watching = compiler.watch(watchOptions, errorHandler);
6331
- }
6329
+ });
6332
6330
  }
6333
6331
  }, instance.close = (callback = noop)=>{
6334
- context.watching?.close(callback);
6332
+ watching?.close(callback);
6335
6333
  }, instance;
6334
+ };
6335
+ var UNKNOWN_FUNCTION = '<unknown>', chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i, chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/, winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i, geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i, geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i, javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i, nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
6336
+ async function mapSourceMapPosition(rawSourceMap, line, column) {
6337
+ let { default: { TraceMap, originalPositionFor } } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "../../compiled/@jridgewell/trace-mapping/index.js"));
6338
+ return originalPositionFor(new TraceMap(rawSourceMap), {
6339
+ line,
6340
+ column
6341
+ });
6336
6342
  }
6337
- async function getLocalhostResolvedAddress() {
6338
- let { promises: dns } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "node:dns")), [defaultLookup, explicitLookup] = await Promise.all([
6339
- dns.lookup('localhost'),
6340
- dns.lookup('localhost', {
6341
- verbatim: !0
6342
- })
6343
- ]);
6344
- return defaultLookup.family === explicitLookup.family && defaultLookup.address === explicitLookup.address ? void 0 : defaultLookup.address;
6345
- }
6346
- async function resolveHostname(host = 'localhost') {
6347
- var host1;
6348
- if ('localhost' === host) {
6349
- let resolvedAddress = await getLocalhostResolvedAddress();
6350
- if (resolvedAddress) return resolvedAddress;
6351
- }
6352
- return void 0 === host || (host1 = host, new Set([
6353
- '0.0.0.0',
6354
- '::',
6355
- '0000:0000:0000:0000:0000:0000:0000:0000'
6356
- ]).has(host1)) ? 'localhost' : host;
6357
- }
6358
- let compilationMiddleware_require = (0, external_node_module_.createRequire)(__rslib_import_meta_url__), getCompilationMiddleware = async ({ config, compiler, callbacks, environments, resolvedPort })=>{
6359
- var config1, environments1;
6360
- let writeToDiskValues, resolvedHost = await resolveHostname(config.server.host);
6361
- return applyToCompiler(compiler, (compiler, index)=>{
6362
- let environment = Object.values(environments).find((env)=>env.index === index);
6363
- if (!environment) return;
6364
- let token = environment.webSocketToken;
6365
- token && (!function({ config, compiler, token, resolvedHost, resolvedPort }) {
6366
- var devConfig;
6367
- let clientPaths;
6368
- if (!((compiler)=>{
6369
- let { target } = compiler.options;
6370
- return !!target && (Array.isArray(target) ? target.includes('web') : 'web' === target);
6371
- })(compiler)) return;
6372
- let clientPaths1 = (devConfig = config.dev, clientPaths = [], (devConfig.hmr || devConfig.liveReload) && (hmrClientPath || (hmrClientPath = compilationMiddleware_require.resolve('@rsbuild/core/client/hmr')), clientPaths.push(hmrClientPath), devConfig.client?.overlay && (overlayClientPath || (overlayClientPath = compilationMiddleware_require.resolve('@rsbuild/core/client/overlay')), clientPaths.push(overlayClientPath))), clientPaths);
6373
- if (!clientPaths1.length) return;
6374
- let clientConfig = {
6375
- ...config.dev.client
6343
+ let resolveSourceLocation = async (stack, fs, environments)=>{
6344
+ let parsed = stack.split('\n').reduce(function(stack, line) {
6345
+ var line1, parts, line2, parts1, line3, parts2, parseResult = function(line) {
6346
+ var parts = chromeRe.exec(line);
6347
+ if (!parts) return null;
6348
+ var isNative = parts[2] && 0 === parts[2].indexOf('native'), isEval = parts[2] && 0 === parts[2].indexOf('eval'), submatch = chromeEvalRe.exec(parts[2]);
6349
+ return isEval && null != submatch && (parts[2] = submatch[1], parts[3] = submatch[2], parts[4] = submatch[3]), {
6350
+ file: isNative ? null : parts[2],
6351
+ methodName: parts[1] || UNKNOWN_FUNCTION,
6352
+ arguments: isNative ? [
6353
+ parts[2]
6354
+ ] : [],
6355
+ lineNumber: parts[3] ? +parts[3] : null,
6356
+ column: parts[4] ? +parts[4] : null
6376
6357
  };
6377
- for (let clientPath of ('<port>' === clientConfig.port && (clientConfig.port = resolvedPort), new compiler.webpack.DefinePlugin({
6378
- RSBUILD_WEB_SOCKET_TOKEN: JSON.stringify(token),
6379
- RSBUILD_CLIENT_CONFIG: JSON.stringify(clientConfig),
6380
- RSBUILD_SERVER_HOST: JSON.stringify(resolvedHost),
6381
- RSBUILD_SERVER_PORT: JSON.stringify(resolvedPort),
6382
- RSBUILD_DEV_LIVE_RELOAD: config.dev.liveReload
6383
- }).apply(compiler), clientPaths1))new compiler.webpack.EntryPlugin(compiler.context, clientPath, {
6384
- name: void 0
6385
- }).apply(compiler);
6386
- }({
6387
- token,
6388
- config: environment.config,
6389
- compiler,
6390
- resolvedHost,
6391
- resolvedPort
6392
- }), (({ compiler, token, callbacks: { onDone, onInvalid } })=>{
6393
- if (((compiler)=>{
6394
- let { target } = compiler.options;
6395
- return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
6396
- })(compiler)) return;
6397
- let { compile, invalid, done } = compiler.hooks;
6398
- compile.tap('rsbuild-dev-server', ()=>{
6399
- onInvalid(token);
6400
- }), invalid.tap('rsbuild-dev-server', (fileName)=>{
6401
- onInvalid(token, fileName);
6402
- }), done.tap('rsbuild-dev-server', (stats)=>{
6403
- onDone(token, stats);
6404
- });
6405
- })({
6406
- compiler,
6407
- callbacks,
6408
- token
6409
- }));
6410
- }), devMiddleware(compiler, {
6411
- publicPath: '/',
6412
- writeToDisk: (config1 = config.dev, 1 === new Set(writeToDiskValues = Object.values(environments1 = environments).map((env)=>env.config.dev.writeToDisk)).size ? writeToDiskValues[0] : (filePath, name)=>{
6413
- let { writeToDisk } = config1;
6414
- return name && environments1[name] && (writeToDisk = environments1[name].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
6415
- })
6416
- });
6358
+ }(line) || (line1 = line, (parts = winjsRe.exec(line1)) ? {
6359
+ file: parts[2],
6360
+ methodName: parts[1] || UNKNOWN_FUNCTION,
6361
+ arguments: [],
6362
+ lineNumber: +parts[3],
6363
+ column: parts[4] ? +parts[4] : null
6364
+ } : null) || function(line) {
6365
+ var parts = geckoRe.exec(line);
6366
+ if (!parts) return null;
6367
+ var isEval = parts[3] && parts[3].indexOf(' > eval') > -1, submatch = geckoEvalRe.exec(parts[3]);
6368
+ return isEval && null != submatch && (parts[3] = submatch[1], parts[4] = submatch[2], parts[5] = null), {
6369
+ file: parts[3],
6370
+ methodName: parts[1] || UNKNOWN_FUNCTION,
6371
+ arguments: parts[2] ? parts[2].split(',') : [],
6372
+ lineNumber: parts[4] ? +parts[4] : null,
6373
+ column: parts[5] ? +parts[5] : null
6374
+ };
6375
+ }(line) || (line2 = line, (parts1 = nodeRe.exec(line2)) ? {
6376
+ file: parts1[2],
6377
+ methodName: parts1[1] || UNKNOWN_FUNCTION,
6378
+ arguments: [],
6379
+ lineNumber: +parts1[3],
6380
+ column: parts1[4] ? +parts1[4] : null
6381
+ } : null) || (line3 = line, (parts2 = javaScriptCoreRe.exec(line3)) ? {
6382
+ file: parts2[3],
6383
+ methodName: parts2[1] || UNKNOWN_FUNCTION,
6384
+ arguments: [],
6385
+ lineNumber: +parts2[4],
6386
+ column: parts2[5] ? +parts2[5] : null
6387
+ } : null);
6388
+ return parseResult && stack.push(parseResult), stack;
6389
+ }, []);
6390
+ if (!parsed.length) return;
6391
+ let frame = parsed.find((frame)=>null !== frame.file && null !== frame.column && null !== frame.lineNumber && SCRIPT_REGEX.test(frame.file));
6392
+ if (!frame) return;
6393
+ let { file, column, lineNumber } = frame, sourceMapInfo = getFileFromUrl(`${file}.map`, fs, environments);
6394
+ if (!sourceMapInfo || 'errorCode' in sourceMapInfo) return;
6395
+ let readFile = (0, external_node_util_namespaceObject.promisify)(fs.readFile);
6396
+ try {
6397
+ let sourceMap = await readFile(sourceMapInfo.filename);
6398
+ if (sourceMap) return await mapSourceMapPosition(sourceMap.toString(), lineNumber, column);
6399
+ } catch (error) {
6400
+ error instanceof Error && index_js_namespaceObject.logger.debug(`failed to map source map position: ${error.message}`);
6401
+ }
6402
+ }, formatErrorLocation = async (stack, context, fs)=>{
6403
+ let parsed = await resolveSourceLocation(stack, fs, context.environments);
6404
+ if (!parsed) return;
6405
+ let { source, line, column } = parsed;
6406
+ if (!source) return;
6407
+ let rawLocation = external_node_path_default().relative(context.rootPath, source);
6408
+ return null !== line && (rawLocation += null === column ? `:${line}` : `:${line}:${column}`), rawLocation;
6409
+ }, formatBrowserErrorLog = async (message, context, fs)=>{
6410
+ let log = `${picocolors_index_js_default().cyan('[browser]')} ${picocolors_index_js_default().red(message.message)}`;
6411
+ if (message.stack) {
6412
+ let rawLocation = await formatErrorLocation(message.stack, context, fs);
6413
+ rawLocation && (log += picocolors_index_js_default().dim(` (${rawLocation})`));
6414
+ }
6415
+ return log;
6417
6416
  }, styles = {
6418
6417
  1: 'font-weight:bold',
6419
6418
  2: 'opacity:0.5',
@@ -6451,17 +6450,19 @@ ${section.body}` : section.body).join("\n\n"));
6451
6450
  wsServer;
6452
6451
  socketsMap = new Map();
6453
6452
  options;
6453
+ context;
6454
6454
  stats;
6455
6455
  initialChunks;
6456
6456
  heartbeatTimer = null;
6457
- environments;
6458
- constructor(options, environments){
6459
- this.options = options, this.stats = {}, this.initialChunks = {}, this.environments = environments;
6457
+ getOutputFileSystem;
6458
+ reportedBrowserLogs = new Set();
6459
+ constructor(context, options, getOutputFileSystem){
6460
+ this.options = options, this.stats = {}, this.initialChunks = {}, this.context = context, this.getOutputFileSystem = getOutputFileSystem;
6460
6461
  }
6461
6462
  upgrade = (req, socket, head)=>{
6462
6463
  if (!this.wsServer.shouldHandle(req)) return;
6463
6464
  let query = parseQueryString(req);
6464
- Object.values(this.environments).map((env)=>env.webSocketToken).includes(query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
6465
+ Object.values(this.context.environments).map((env)=>env.webSocketToken).includes(query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
6465
6466
  this.wsServer.emit('connection', connection, req);
6466
6467
  }) : socket.destroy();
6467
6468
  };
@@ -6485,8 +6486,8 @@ ${section.body}` : section.body).join("\n\n"));
6485
6486
  this.onConnect(socket, query.token);
6486
6487
  });
6487
6488
  }
6488
- updateStats(stats, token) {
6489
- this.stats[token] = stats, this.socketsMap.size && this.sendStats({
6489
+ onBuildDone(stats, token) {
6490
+ this.stats[token] = stats, this.reportedBrowserLogs.clear(), this.socketsMap.size && this.sendStats({
6490
6491
  token
6491
6492
  });
6492
6493
  }
@@ -6504,7 +6505,7 @@ ${section.body}` : section.body).join("\n\n"));
6504
6505
  for (let sockets of this.socketsMap.values())sockets.forEach((socket)=>{
6505
6506
  socket.close();
6506
6507
  });
6507
- return this.stats = {}, this.initialChunks = {}, this.socketsMap.clear(), new Promise((resolve, reject)=>{
6508
+ return this.stats = {}, this.initialChunks = {}, this.socketsMap.clear(), this.reportedBrowserLogs.clear(), new Promise((resolve, reject)=>{
6508
6509
  this.wsServer.close((err)=>{
6509
6510
  err ? reject(err) : resolve();
6510
6511
  });
@@ -6513,6 +6514,14 @@ ${section.body}` : section.body).join("\n\n"));
6513
6514
  onConnect(socket, token) {
6514
6515
  socket.isAlive = !0, socket.on('pong', ()=>{
6515
6516
  socket.isAlive = !0;
6517
+ }), socket.on('message', async (data)=>{
6518
+ try {
6519
+ let message = JSON.parse('string' == typeof data ? data : data.toString());
6520
+ if ('client-error' === message.type && 'rspack' === this.context.bundlerType && !this.context.buildState.hasErrors) {
6521
+ let log = await formatBrowserErrorLog(message, this.context, this.getOutputFileSystem());
6522
+ this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), index_js_namespaceObject.logger.error(log));
6523
+ }
6524
+ } catch {}
6516
6525
  });
6517
6526
  let sockets = this.socketsMap.get(token);
6518
6527
  sockets || (sockets = new Set(), this.socketsMap.set(token, sockets)), sockets.add(socket), socket.on('close', ()=>{
@@ -6746,17 +6755,17 @@ ${section.body}` : section.body).join("\n\n"));
6746
6755
  socket.readyState === socket.OPEN && socket.send(message);
6747
6756
  }
6748
6757
  }
6749
- class CompilationManager {
6758
+ class BuildManager {
6750
6759
  middleware;
6751
6760
  outputFileSystem;
6752
- config;
6761
+ socketServer;
6753
6762
  compiler;
6754
- environments;
6763
+ config;
6755
6764
  publicPaths;
6756
- socketServer;
6757
6765
  resolvedPort;
6758
- constructor({ config, compiler, publicPaths, resolvedPort, environments }){
6759
- this.config = config, this.compiler = compiler, this.environments = environments, this.publicPaths = publicPaths, this.resolvedPort = resolvedPort, this.outputFileSystem = external_node_fs_default(), this.socketServer = new SocketServer(config.dev, environments);
6766
+ context;
6767
+ constructor({ config, context, compiler, publicPaths, resolvedPort }){
6768
+ this.config = config, this.context = context, this.compiler = compiler, this.publicPaths = publicPaths, this.resolvedPort = resolvedPort, this.outputFileSystem = external_node_fs_default(), this.socketServer = new SocketServer(context, config.dev, ()=>this.outputFileSystem);
6760
6769
  }
6761
6770
  async init() {
6762
6771
  await this.setupCompilationMiddleware(), await this.socketServer.prepare();
@@ -6779,20 +6788,11 @@ ${section.body}` : section.body).join("\n\n"));
6779
6788
  }
6780
6789
  readFileSync = (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : external_node_fs_default().readFileSync(fileName, 'utf-8');
6781
6790
  async setupCompilationMiddleware() {
6782
- let { config, publicPaths, environments } = this, middleware = await getCompilationMiddleware({
6791
+ let { config, context, publicPaths } = this, middleware = await assetsMiddleware({
6783
6792
  config,
6793
+ context,
6784
6794
  compiler: this.compiler,
6785
- callbacks: {
6786
- onInvalid: (token, fileName)=>{
6787
- if ('string' == typeof fileName && fileName.endsWith('.html')) return void this.socketServer.sockWrite({
6788
- type: 'static-changed'
6789
- }, token);
6790
- },
6791
- onDone: (token, stats)=>{
6792
- this.socketServer.updateStats(stats, token);
6793
- }
6794
- },
6795
- environments,
6795
+ socketServer: this.socketServer,
6796
6796
  resolvedPort: this.resolvedPort
6797
6797
  }), { base } = config.server, assetPrefixes = publicPaths.map(getPathnameFromUrl).map((prefix)=>base && '/' !== base ? stripBase(prefix, base) : prefix), wrapper = (req, res, next)=>{
6798
6798
  let { url } = req, assetPrefix = url && assetPrefixes.find((prefix)=>url.startsWith(prefix));
@@ -6803,6 +6803,59 @@ ${section.body}` : section.body).join("\n\n"));
6803
6803
  wrapper.close = middleware.close, wrapper.watch = middleware.watch, this.middleware = wrapper;
6804
6804
  }
6805
6805
  }
6806
+ let isCliShortcutsEnabled = (config)=>config.dev.cliShortcuts && isTTY('stdin');
6807
+ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer, customShortcuts }) {
6808
+ let shortcuts = [
6809
+ {
6810
+ key: 'c',
6811
+ description: `${picocolors_index_js_default().bold('c + enter')} ${picocolors_index_js_default().dim('clear console')}`,
6812
+ action: ()=>{
6813
+ console.clear();
6814
+ }
6815
+ },
6816
+ {
6817
+ key: 'o',
6818
+ description: `${picocolors_index_js_default().bold('o + enter')} ${picocolors_index_js_default().dim('open in browser')}`,
6819
+ action: openPage
6820
+ },
6821
+ {
6822
+ key: 'q',
6823
+ description: `${picocolors_index_js_default().bold('q + enter')} ${picocolors_index_js_default().dim('quit process')}`,
6824
+ action: async ()=>{
6825
+ try {
6826
+ await closeServer();
6827
+ } finally{
6828
+ process.exit(0);
6829
+ }
6830
+ }
6831
+ },
6832
+ restartServer ? {
6833
+ key: 'r',
6834
+ description: `${picocolors_index_js_default().bold('r + enter')} ${picocolors_index_js_default().dim('restart server')}`,
6835
+ action: restartServer
6836
+ } : null,
6837
+ {
6838
+ key: 'u',
6839
+ description: `${picocolors_index_js_default().bold('u + enter')} ${picocolors_index_js_default().dim('show urls')}`,
6840
+ action: printUrls
6841
+ }
6842
+ ].filter(Boolean);
6843
+ if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${picocolors_index_js_default().dim('[rsbuild:config]')} ${picocolors_index_js_default().yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
6844
+ help && index_js_namespaceObject.logger.log(!0 === help ? ` ➜ ${picocolors_index_js_default().dim('press')} ${picocolors_index_js_default().bold('h + enter')} ${picocolors_index_js_default().dim('to show shortcuts')}\n` : ` ➜ ${help}\n`);
6845
+ let { createInterface } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "node:readline")), rl = createInterface({
6846
+ input: process.stdin
6847
+ });
6848
+ return rl.on('line', (input)=>{
6849
+ if ('h' === input) {
6850
+ let message = `\n ${picocolors_index_js_default().bold(picocolors_index_js_default().blue('Shortcuts:'))}\n`;
6851
+ for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
6852
+ index_js_namespaceObject.logger.log(message);
6853
+ }
6854
+ for (let shortcut of shortcuts)if (input === shortcut.key) return void shortcut.action();
6855
+ }), ()=>{
6856
+ rl.close();
6857
+ };
6858
+ }
6806
6859
  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)=>{
6807
6860
  let gzip, writeHeadStatus;
6808
6861
  if (filter && !filter(req, res)) return void next();
@@ -6970,7 +7023,7 @@ ${section.body}` : section.body).join("\n\n"));
6970
7023
  for (let middleware of proxyMiddlewares)'function' == typeof middleware.upgrade && middleware.upgrade(req, socket, head);
6971
7024
  }
6972
7025
  };
6973
- }, applyDefaultMiddlewares = async ({ config, compilationManager, context, devServerAPI, middlewares, pwd, postCallbacks })=>{
7026
+ }, applyDefaultMiddlewares = async ({ config, buildManager, context, devServerAPI, middlewares, pwd, postCallbacks })=>{
6974
7027
  let upgradeEvents = [], { server } = config;
6975
7028
  if (server.cors) {
6976
7029
  let { default: corsMiddleware } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "../../compiled/cors/index.js"));
@@ -6985,8 +7038,8 @@ ${section.body}` : section.body).join("\n\n"));
6985
7038
  for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.push(middleware);
6986
7039
  }
6987
7040
  let { compress } = server;
6988
- if (compress && middlewares.push(gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && 'rspack' === context.bundlerType && compilationManager) {
6989
- let { compiler } = compilationManager;
7041
+ if (compress && middlewares.push(gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && 'rspack' === context.bundlerType && buildManager) {
7042
+ let { compiler } = buildManager;
6990
7043
  (helpers_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.experiments?.lazyCompilation || childCompiler.options.lazyCompilation) : compiler.options.experiments?.lazyCompilation || compiler.options.lazyCompilation) && middlewares.push(rspack_rspack.experiments.lazyCompilationMiddleware(compiler));
6991
7044
  }
6992
7045
  server.base && '/' !== server.base && middlewares.push(getBaseMiddleware({
@@ -7056,25 +7109,25 @@ ${section.body}` : section.body).join("\n\n"));
7056
7109
  }
7057
7110
  })({
7058
7111
  environments: devServerAPI.environments
7059
- })), compilationManager && (middlewares.push(compilationManager.middleware), upgradeEvents.push(compilationManager.socketServer.upgrade), middlewares.push((req, res, next)=>{
7112
+ })), buildManager && (middlewares.push(buildManager.middleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.push((req, res, next)=>{
7060
7113
  req.url?.endsWith('.hot-update.json') && 'OPTIONS' !== req.method ? (res.statusCode = 404, res.end()) : next();
7061
- })), compilationManager && middlewares.push((({ distPath, compilationManager })=>async (req, res, next)=>{
7114
+ })), buildManager && middlewares.push((({ distPath, buildManager })=>async (req, res, next)=>{
7062
7115
  if (!maybeHTMLRequest(req)) return void next();
7063
7116
  let pathname = req.url.replace(postfixRE, ''), rewrite = (newUrl)=>{
7064
- req.url = newUrl, compilationManager.middleware(req, res, (...args)=>{
7117
+ req.url = newUrl, buildManager.middleware(req, res, (...args)=>{
7065
7118
  next(...args);
7066
7119
  });
7067
7120
  };
7068
7121
  if (pathname.endsWith('/')) {
7069
7122
  let newUrl = `${pathname}index.html`, filePath = external_node_path_default().join(distPath, newUrl);
7070
- if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) return void rewrite(newUrl);
7123
+ if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
7071
7124
  } else if (!external_node_path_default().extname(pathname)) {
7072
7125
  let newUrl = `${pathname}.html`, filePath = external_node_path_default().join(distPath, newUrl);
7073
- if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) return void rewrite(newUrl);
7126
+ if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
7074
7127
  }
7075
7128
  next();
7076
7129
  })({
7077
- compilationManager,
7130
+ buildManager,
7078
7131
  distPath: context.distPath
7079
7132
  })), normalizePublicDirs(server?.publicDir))){
7080
7133
  let { default: sirv } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "../../compiled/sirv/index.js")), { name } = publicDir, assetMiddleware = sirv((0, external_node_path_.isAbsolute)(name) ? name : (0, external_node_path_.join)(pwd, name), {
@@ -7084,28 +7137,28 @@ ${section.body}` : section.body).join("\n\n"));
7084
7137
  middlewares.push(assetMiddleware);
7085
7138
  }
7086
7139
  for (let callback of postCallbacks)callback();
7087
- return compilationManager && middlewares.push((({ htmlFallback, distPath, compilationManager })=>async (req, res, next)=>{
7140
+ return buildManager && middlewares.push((({ htmlFallback, distPath, buildManager })=>async (req, res, next)=>{
7088
7141
  if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url || 'index' !== htmlFallback) return void next();
7089
7142
  let filePath = external_node_path_default().join(distPath, 'index.html');
7090
- if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) {
7143
+ if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) {
7091
7144
  let newUrl = '/index.html';
7092
- 'verbose' === index_js_namespaceObject.logger.level && index_js_namespaceObject.logger.debug(` ${req.method} ${req.url} ${picocolors_index_js_default().yellow('fallback to')} ${newUrl}`), req.url = newUrl, compilationManager.middleware(req, res, (...args)=>{
7145
+ 'verbose' === index_js_namespaceObject.logger.level && index_js_namespaceObject.logger.debug(` ${req.method} ${req.url} ${picocolors_index_js_default().yellow('fallback to')} ${newUrl}`), req.url = newUrl, buildManager.middleware(req, res, (...args)=>{
7093
7146
  next(...args);
7094
7147
  });
7095
7148
  return;
7096
7149
  }
7097
7150
  next();
7098
7151
  })({
7099
- compilationManager,
7152
+ buildManager,
7100
7153
  distPath: context.distPath,
7101
7154
  htmlFallback: server.htmlFallback
7102
- })), server.historyApiFallback && (middlewares.push(historyApiFallbackMiddleware(!0 === server.historyApiFallback ? {} : server.historyApiFallback)), compilationManager?.middleware && middlewares.push(compilationManager.middleware)), middlewares.push(faviconFallbackMiddleware), {
7155
+ })), server.historyApiFallback && (middlewares.push(historyApiFallbackMiddleware(!0 === server.historyApiFallback ? {} : server.historyApiFallback)), buildManager?.middleware && middlewares.push(buildManager.middleware)), middlewares.push(faviconFallbackMiddleware), {
7103
7156
  onUpgrade: (...args)=>{
7104
7157
  for (let cb of upgradeEvents)cb(...args);
7105
7158
  }
7106
7159
  };
7107
7160
  }, getDevMiddlewares = async (options)=>{
7108
- let middlewares = [], { compilationManager } = options;
7161
+ let middlewares = [], { buildManager } = options;
7109
7162
  'verbose' === index_js_namespaceObject.logger.level && middlewares.push(getRequestLoggerMiddleware());
7110
7163
  let { before, after } = ((config, devServerAPI)=>{
7111
7164
  let setupMiddlewares = config.dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
@@ -7128,7 +7181,7 @@ ${section.body}` : section.body).join("\n\n"));
7128
7181
  });
7129
7182
  return middlewares.push(...after), {
7130
7183
  close: async ()=>{
7131
- await compilationManager?.close();
7184
+ await buildManager?.close();
7132
7185
  },
7133
7186
  onUpgrade,
7134
7187
  middlewares
@@ -7405,14 +7458,14 @@ ${section.body}` : section.body).join("\n\n"));
7405
7458
  return createServer(middlewares);
7406
7459
  };
7407
7460
  async function setupWatchFiles(options) {
7408
- let { config, root, compilationManager } = options, { hmr, liveReload } = config.dev;
7409
- if (!hmr && !liveReload || !compilationManager) return;
7410
- let closeDevFilesWatcher = await watchDevFiles(config.dev, compilationManager, root), serverFilesWatcher = await function(serverConfig, compilationManager, root) {
7461
+ let { config, root, buildManager } = options, { hmr, liveReload } = config.dev;
7462
+ if (!hmr && !liveReload || !buildManager) return;
7463
+ let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root), serverFilesWatcher = await function(serverConfig, buildManager, root) {
7411
7464
  let publicDirs = normalizePublicDirs(serverConfig.publicDir);
7412
7465
  if (!publicDirs.length) return;
7413
7466
  let watchPaths = publicDirs.filter((item)=>item.watch).map((item)=>item.name);
7414
- if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), compilationManager, root);
7415
- }(config.server, compilationManager, root);
7467
+ if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), buildManager, root);
7468
+ }(config.server, buildManager, root);
7416
7469
  return {
7417
7470
  async close () {
7418
7471
  await Promise.all([
@@ -7422,12 +7475,12 @@ ${section.body}` : section.body).join("\n\n"));
7422
7475
  }
7423
7476
  };
7424
7477
  }
7425
- async function watchDevFiles(devConfig, compilationManager, root) {
7478
+ async function watchDevFiles(devConfig, buildManager, root) {
7426
7479
  let { watchFiles } = devConfig;
7427
7480
  if (!watchFiles) return;
7428
7481
  let watchers = [];
7429
7482
  for (let { paths, options, type } of helpers_castArray(watchFiles)){
7430
- let watchOptions = prepareWatchOptions(paths, options, type), watcher = await startWatchFiles(watchOptions, compilationManager, root);
7483
+ let watchOptions = prepareWatchOptions(paths, options, type), watcher = await startWatchFiles(watchOptions, buildManager, root);
7431
7484
  watcher && watchers.push(watcher);
7432
7485
  }
7433
7486
  return async ()=>{
@@ -7458,11 +7511,11 @@ ${section.body}` : section.body).join("\n\n"));
7458
7511
  }
7459
7512
  return chokidar.watch(Array.from(watchFiles), options);
7460
7513
  }
7461
- async function startWatchFiles({ paths, options, type = 'reload-page' }, compilationManager, root) {
7514
+ async function startWatchFiles({ paths, options, type = 'reload-page' }, buildManager, root) {
7462
7515
  if ('reload-page' !== type) return;
7463
7516
  let watcher = await createChokidar(paths, root, options);
7464
7517
  return watcher.on('change', ()=>{
7465
- compilationManager.socketServer.sockWrite({
7518
+ buildManager.socketServer.sockWrite({
7466
7519
  type: 'static-changed'
7467
7520
  });
7468
7521
  }), watcher;
@@ -7496,14 +7549,14 @@ ${section.body}` : section.body).join("\n\n"));
7496
7549
  });
7497
7550
  let publicPaths = helpers_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
7498
7551
  getPublicPathFromCompiler(compiler)
7499
- ], compilationManager = new CompilationManager({
7552
+ ], buildManager = new BuildManager({
7553
+ context,
7500
7554
  config,
7501
7555
  compiler,
7502
7556
  publicPaths: publicPaths,
7503
- resolvedPort: port,
7504
- environments: context.environments
7557
+ resolvedPort: port
7505
7558
  });
7506
- return await compilationManager.init(), compilationManager;
7559
+ return await buildManager.init(), buildManager;
7507
7560
  }, protocol = https ? 'https' : 'http', urls = await getAddressUrls({
7508
7561
  protocol,
7509
7562
  port,
@@ -7552,21 +7605,21 @@ ${section.body}` : section.body).join("\n\n"));
7552
7605
  name,
7553
7606
  {
7554
7607
  getStats: async ()=>{
7555
- if (!compilationManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('getStats')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
7608
+ if (!buildManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('getStats')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
7556
7609
  return await waitLastCompileDone, lastStats[environment.index];
7557
7610
  },
7558
7611
  context: environment,
7559
7612
  loadBundle: async (entryName)=>{
7560
- if (!compilationManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('loadBundle')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
7613
+ if (!buildManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('loadBundle')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
7561
7614
  return await waitLastCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
7562
- readFileSync: compilationManager.readFileSync,
7615
+ readFileSync: buildManager.readFileSync,
7563
7616
  environment
7564
7617
  });
7565
7618
  },
7566
7619
  getTransformedHtml: async (entryName)=>{
7567
- if (!compilationManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('getTransformedHtml')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
7620
+ if (!buildManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('getTransformedHtml')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
7568
7621
  return await waitLastCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
7569
- readFileSync: compilationManager.readFileSync,
7622
+ readFileSync: buildManager.readFileSync,
7570
7623
  environment
7571
7624
  });
7572
7625
  }
@@ -7579,7 +7632,7 @@ ${section.body}` : section.body).join("\n\n"));
7579
7632
  middlewares,
7580
7633
  environments: environmentAPI,
7581
7634
  httpServer,
7582
- sockWrite: (type, data)=>compilationManager?.socketServer.sockWrite({
7635
+ sockWrite: (type, data)=>buildManager?.socketServer.sockWrite({
7583
7636
  type,
7584
7637
  data
7585
7638
  }),
@@ -7620,20 +7673,20 @@ ${section.body}` : section.body).join("\n\n"));
7620
7673
  environments: context.environments
7621
7674
  })).filter((item)=>'function' == typeof item);
7622
7675
  runCompile ? context.hooks.onBeforeCreateCompiler.tap(beforeCreateCompiler) : await beforeCreateCompiler();
7623
- let compilationManager = runCompile ? await startCompile() : void 0;
7676
+ let buildManager = runCompile ? await startCompile() : void 0;
7624
7677
  for (let item of (fileWatcher = await setupWatchFiles({
7625
7678
  config,
7626
- compilationManager,
7679
+ buildManager,
7627
7680
  root
7628
7681
  }), (devMiddlewares = await getDevMiddlewares({
7629
7682
  pwd: root,
7630
- compilationManager,
7683
+ buildManager,
7631
7684
  config,
7632
7685
  devServerAPI,
7633
7686
  context,
7634
7687
  postCallbacks
7635
7688
  })).middlewares))Array.isArray(item) ? middlewares.use(...item) : middlewares.use(item);
7636
- return compilationManager?.watch(), index_js_namespaceObject.logger.debug('create dev server done'), devServerAPI;
7689
+ return buildManager?.watch(), index_js_namespaceObject.logger.debug('create dev server done'), devServerAPI;
7637
7690
  }
7638
7691
  let rspackProvider = ({ context, pluginManager, rsbuildOptions })=>{
7639
7692
  let createCompiler = async ()=>(await createCompiler_createCompiler({
@@ -7830,7 +7883,7 @@ ${section.body}` : section.body).join("\n\n"));
7830
7883
  let plugins, context1, envs = options.loadEnv ? loadEnv({
7831
7884
  cwd: options.cwd,
7832
7885
  ...'boolean' == typeof options.loadEnv ? {} : options.loadEnv
7833
- }) : null, config = isFunction(options.rsbuildConfig) ? await options.rsbuildConfig() : options.rsbuildConfig || {};
7886
+ }) : null, configOrFactory = options.config ?? options.rsbuildConfig, config = isFunction(configOrFactory) ? await configOrFactory() : configOrFactory || {};
7834
7887
  config.logLevel && !isDebug() && (index_js_namespaceObject.logger.level = config.logLevel), function(config, envs) {
7835
7888
  if (null !== envs && (config.source ||= {}, config.source.define = {
7836
7889
  ...envs.publicVars,
@@ -9791,7 +9844,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9791
9844
  var cwd, envDir;
9792
9845
  let cwd1 = process.cwd(), root = commonOpts.root ? ensureAbsolutePath(cwd1, commonOpts.root) : cwd1, rsbuild = await createRsbuild({
9793
9846
  cwd: root,
9794
- rsbuildConfig: ()=>init_loadConfig(root),
9847
+ config: ()=>init_loadConfig(root),
9795
9848
  environment: commonOpts.environment,
9796
9849
  loadEnv: !1 !== commonOpts.env && {
9797
9850
  cwd: (cwd = root, (envDir = commonOpts.envDir) ? external_node_path_default().isAbsolute(envDir) ? envDir : external_node_path_default().join(cwd, envDir) : cwd),
@@ -9892,11 +9945,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9892
9945
  }
9893
9946
  !function() {
9894
9947
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
9895
- index_js_namespaceObject.logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.5.12\n`);
9948
+ index_js_namespaceObject.logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.5.13\n`);
9896
9949
  }();
9897
9950
  try {
9898
9951
  let cli, devDescription, devCommand, buildCommand, previewCommand, inspectCommand;
9899
- (cli = ((name = "")=>new CAC(name))('rsbuild')).version("1.5.12"), 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)', {
9952
+ (cli = ((name = "")=>new CAC(name))('rsbuild')).version("1.5.13"), 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)', {
9900
9953
  default: 'jiti'
9901
9954
  }).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', {
9902
9955
  type: [
@@ -9953,7 +10006,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9953
10006
  index_js_namespaceObject.logger.error('Failed to start Rsbuild CLI.'), index_js_namespaceObject.logger.error(err);
9954
10007
  }
9955
10008
  }
9956
- let src_version = "1.5.12";
10009
+ let src_version = "1.5.13";
9957
10010
  })(), 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 === [
9958
10011
  "PLUGIN_CSS_NAME",
9959
10012
  "PLUGIN_SWC_NAME",