@rsbuild/core 1.3.18 → 1.3.19

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.
@@ -15,7 +15,7 @@ declare namespace e {
15
15
  }
16
16
  interface CorsOptions {
17
17
  /**
18
- * @default '*''
18
+ * @default '*'
19
19
  */
20
20
  origin?: StaticOrigin | CustomOrigin | undefined;
21
21
  /**
@@ -90,7 +90,6 @@ function onMessage(e) {
90
90
  lastCompilationHash = message.data;
91
91
  if (clearOverlay && isUpdateAvailable()) clearOverlay();
92
92
  break;
93
- case 'still-ok':
94
93
  case 'ok':
95
94
  handleSuccess();
96
95
  break;
package/dist/index.cjs CHANGED
@@ -2259,7 +2259,7 @@ for(var __webpack_i__ in (()=>{
2259
2259
  async function createContext(options, userConfig) {
2260
2260
  let { cwd } = options, rootPath = userConfig.root ? getAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = (0, external_node_path_namespaceObject.join)(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
2261
2261
  return {
2262
- version: "1.3.18",
2262
+ version: "1.3.19",
2263
2263
  rootPath,
2264
2264
  distPath: '',
2265
2265
  cachePath,
@@ -3173,7 +3173,7 @@ for(var __webpack_i__ in (()=>{
3173
3173
  writable: !0
3174
3174
  }) : obj[key] = value, obj;
3175
3175
  }
3176
- let VOID_TAGS = [
3176
+ let entryNameSymbol = Symbol('entryName'), VOID_TAGS = [
3177
3177
  'area',
3178
3178
  'base',
3179
3179
  'br',
@@ -3299,11 +3299,15 @@ for(var __webpack_i__ in (()=>{
3299
3299
  meta: {}
3300
3300
  };
3301
3301
  href.endsWith('.svg') && (tag.attributes.type = 'image/svg+xml'), headTags.unshift(tag);
3302
+ }, getExtraDataByPlugin = (plugin)=>{
3303
+ if (!plugin.options) return;
3304
+ let entryName = plugin.options[entryNameSymbol];
3305
+ if (entryName) return this.getExtraData(entryName);
3302
3306
  };
3303
3307
  compiler.hooks.compilation.tap(this.name, (compilation)=>{
3304
3308
  let hooks = getHTMLPlugin().getCompilationHooks(compilation);
3305
3309
  hooks.alterAssetTagGroups.tapPromise(this.name, async (data)=>{
3306
- let extraData = this.getExtraData(data.plugin);
3310
+ let extraData = getExtraDataByPlugin(data.plugin);
3307
3311
  if (!extraData) return data;
3308
3312
  let { headTags, bodyTags } = data, { favicon, context, tagConfig, entryName, environment, templateContent } = extraData;
3309
3313
  if (!hasTitle(templateContent)) {
@@ -3332,7 +3336,7 @@ for(var __webpack_i__ in (()=>{
3332
3336
  bodyTags: modified.bodyTags.map(fromBasicTag)
3333
3337
  }), tagConfig && applyTagConfig(data, tagConfig, compilation.hash ?? '', entryName), data;
3334
3338
  }), hooks.beforeEmit.tapPromise(this.name, async (data)=>{
3335
- let extraData = this.getExtraData(data.plugin);
3339
+ let extraData = getExtraDataByPlugin(data.plugin);
3336
3340
  if (!extraData) return data;
3337
3341
  let { context, environment } = extraData, [modified] = await context.hooks.modifyHTML.callChain({
3338
3342
  environment: environment.name,
@@ -3395,7 +3399,7 @@ for(var __webpack_i__ in (()=>{
3395
3399
  api.modifyBundlerChain(async (chain, { HtmlPlugin, CHAIN_ID, environment })=>{
3396
3400
  let { config, htmlPaths } = environment;
3397
3401
  if (0 === Object.keys(htmlPaths).length) return;
3398
- let assetPrefix = getPublicPathFromChain(chain, !1), entries = chain.entryPoints.entries() || {}, entryNames = Object.keys(entries).filter((entryName)=>!!htmlPaths[entryName]), extraDataList = [], finalOptions = await Promise.all(entryNames.map(async (entryName)=>{
3402
+ let assetPrefix = getPublicPathFromChain(chain, !1), entries = chain.entryPoints.entries() || {}, entryNames = Object.keys(entries).filter((entryName)=>!!htmlPaths[entryName]), extraDataMap = new Map(), finalOptions = await Promise.all(entryNames.map(async (entryName)=>{
3399
3403
  var entryName1, entryName2, config1, assetPrefix1, entryName3, entryName4;
3400
3404
  let entryValue = entries[entryName].values(), chunks = function(entryName, entryValue) {
3401
3405
  let chunks = [
@@ -3459,7 +3463,7 @@ for(var __webpack_i__ in (()=>{
3459
3463
  context,
3460
3464
  environment
3461
3465
  };
3462
- extraDataList.push(extraData), templateContent && (extraData.templateContent = templateContent);
3466
+ extraDataMap.set(entryName, extraData), templateContent && (extraData.templateContent = templateContent);
3463
3467
  let tagConfig = getTagConfig(environment.config);
3464
3468
  tagConfig && (extraData.tagConfig = tagConfig), entryName3 = entryName, pluginOptions.title = reduceConfigsMergeContext({
3465
3469
  initial: '',
@@ -3485,12 +3489,16 @@ for(var __webpack_i__ in (()=>{
3485
3489
  }
3486
3490
  });
3487
3491
  return finalOptions.template || finalOptions.templateContent || (pluginOptions.template = '', pluginOptions.templateContent = templateContent), finalOptions;
3488
- })), extraDataMap = new WeakMap();
3492
+ }));
3489
3493
  if (entryNames.forEach((entryName, index)=>{
3490
- let pluginInstance = new HtmlPlugin(finalOptions[index]), extraData = extraDataList.find((item)=>item.entryName === entryName);
3491
- chain.plugin(`${CHAIN_ID.PLUGIN.HTML}-${entryName}`).use(pluginInstance), extraData && extraDataMap.set(pluginInstance, extraData);
3494
+ chain.plugin(`${CHAIN_ID.PLUGIN.HTML}-${entryName}`).use(HtmlPlugin, [
3495
+ {
3496
+ ...finalOptions[index],
3497
+ [entryNameSymbol]: entryName
3498
+ }
3499
+ ]);
3492
3500
  }), chain.plugin('rsbuild-html-plugin').use(RsbuildHtmlPlugin, [
3493
- (pluginInstance)=>extraDataMap.get(pluginInstance)
3501
+ (entryName)=>extraDataMap.get(entryName)
3494
3502
  ]), config.html) {
3495
3503
  let { crossorigin } = config.html;
3496
3504
  crossorigin && chain.output.crossOriginLoading(!0 === crossorigin ? 'anonymous' : crossorigin);
@@ -4400,25 +4408,37 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
4400
4408
  }
4401
4409
  });
4402
4410
  }
4403
- }), pluginRspackProfile = ()=>({
4411
+ });
4412
+ async function ensureFileDir(outputFilePath) {
4413
+ let dir = external_node_path_default().dirname(outputFilePath);
4414
+ await external_node_fs_default().promises.mkdir(dir, {
4415
+ recursive: !0
4416
+ });
4417
+ }
4418
+ async function applyProfile(root, filterValue, traceLayer = 'chrome', traceOutput) {
4419
+ var value;
4420
+ if ('chrome' !== traceLayer && 'logger' !== traceLayer) throw Error(`unsupported trace layer: ${traceLayer}`);
4421
+ if (!traceOutput) {
4422
+ let timestamp = Date.now(), defaultOutputDir = external_node_path_default().join(root, `.rspack-profile-${timestamp}-${process.pid}`), defaultRustTraceChromeOutput = external_node_path_default().join(defaultOutputDir, 'trace.json');
4423
+ traceOutput = 'chrome' === traceLayer ? defaultRustTraceChromeOutput : 'stdout';
4424
+ }
4425
+ let filter = "OVERVIEW" === (value = filterValue) ? 'info' : "ALL" === value ? 'trace' : value;
4426
+ return await ensureFileDir(traceOutput), await core_default().experiments.globalTrace.register(filter, traceLayer, traceOutput), traceOutput;
4427
+ }
4428
+ let pluginRspackProfile = ()=>({
4404
4429
  name: 'rsbuild:rspack-profile',
4405
4430
  async setup (api) {
4406
- var _process_env_RSPACK_PROFILE;
4431
+ let traceOutput;
4407
4432
  if ('webpack' === api.context.bundlerType) return;
4408
- let RSPACK_PROFILE = null == (_process_env_RSPACK_PROFILE = process.env.RSPACK_PROFILE) ? void 0 : _process_env_RSPACK_PROFILE.toUpperCase();
4433
+ let { RSPACK_PROFILE } = process.env;
4409
4434
  if (!RSPACK_PROFILE) return;
4410
- let timestamp = Date.now(), profileDirName = `rspack-profile-${timestamp}`, enableProfileTrace = 'ALL' === RSPACK_PROFILE || RSPACK_PROFILE.includes('TRACE'), onStart = async ()=>{
4411
- let profileDir = external_node_path_default().join(api.context.distPath, profileDirName), traceFilePath = external_node_path_default().join(profileDir, 'trace.json');
4412
- await isFileExists(profileDir) || await external_node_fs_default().promises.mkdir(profileDir, {
4413
- recursive: !0
4414
- }), enableProfileTrace && core_default().experiments.globalTrace.register('trace', 'chrome', traceFilePath);
4435
+ let onStart = async ()=>{
4436
+ traceOutput = await applyProfile(api.context.rootPath, RSPACK_PROFILE, process.env.RSPACK_TRACE_LAYER, process.env.RSPACK_TRACE_OUTPUT);
4415
4437
  };
4416
4438
  api.onBeforeBuild(({ isFirstCompile })=>{
4417
4439
  isFirstCompile && onStart();
4418
4440
  }), api.onBeforeStartDevServer(onStart), api.onExit(()=>{
4419
- enableProfileTrace && core_default().experiments.globalTrace.cleanup();
4420
- let profileDir = external_node_path_default().join(api.context.distPath, profileDirName);
4421
- rslog_index_js_namespaceObject.logger.info(`profile file saved to ${index_js_default().cyan(profileDir)}`);
4441
+ traceOutput && (core_default().experiments.globalTrace.cleanup(), rslog_index_js_namespaceObject.logger.info(`profile file saved to ${index_js_default().cyan(traceOutput)}`));
4422
4442
  });
4423
4443
  }
4424
4444
  }), pluginServer = ()=>({
@@ -5446,7 +5466,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
5446
5466
  compilationId
5447
5467
  });
5448
5468
  if (!force && statsJson && !statsJson.errorsCount && statsJson.assets && statsJson.assets.every((asset)=>!asset.emitted)) return this.sockWrite({
5449
- type: 'still-ok',
5469
+ type: 'ok',
5450
5470
  compilationId
5451
5471
  });
5452
5472
  if (this.sockWrite({
@@ -5918,14 +5938,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
5918
5938
  for (let middleware of proxyMiddlewares)'function' == typeof middleware.upgrade && middleware.upgrade(req, socket, head);
5919
5939
  }
5920
5940
  };
5921
- }, applySetupMiddlewares = (dev, environments, compilationManager)=>{
5922
- let setupMiddlewares = dev.setupMiddlewares || [], serverOptions = {
5923
- sockWrite: (type, data)=>null == compilationManager ? void 0 : compilationManager.socketServer.sockWrite({
5924
- type,
5925
- data
5926
- }),
5927
- environments
5928
- }, before = [], after = [];
5941
+ }, applySetupMiddlewares = (dev, devServerAPI)=>{
5942
+ let setupMiddlewares = dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
5943
+ 'sockWrite',
5944
+ 'environments'
5945
+ ]), before = [], after = [];
5929
5946
  for (let handler of setupMiddlewares)handler({
5930
5947
  unshift: (...handlers)=>before.unshift(...handlers),
5931
5948
  push: (...handlers)=>after.push(...handlers)
@@ -5934,7 +5951,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
5934
5951
  before,
5935
5952
  after
5936
5953
  };
5937
- }, applyDefaultMiddlewares = async ({ dev, middlewares, server, compilationManager, context, pwd, environments, postCallbacks })=>{
5954
+ }, applyDefaultMiddlewares = async ({ dev, devServerAPI, middlewares, server, compilationManager, context, pwd, postCallbacks })=>{
5938
5955
  let upgradeEvents = [];
5939
5956
  if (server.cors) {
5940
5957
  let { default: corsMiddleware } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "../../compiled/cors/index.js"));
@@ -5960,7 +5977,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
5960
5977
  '/__open-in-editor',
5961
5978
  launchEditorMiddleware()
5962
5979
  ]), middlewares.push(viewingServedFilesMiddleware({
5963
- environments
5980
+ environments: devServerAPI.environments
5964
5981
  })), compilationManager && (middlewares.push(compilationManager.middleware), upgradeEvents.push(compilationManager.socketServer.upgrade), middlewares.push((req, res, next)=>{
5965
5982
  var _req_url;
5966
5983
  (null == (_req_url = req.url) ? void 0 : _req_url.endsWith('.hot-update.json')) && 'OPTIONS' !== req.method ? (res.statusCode = 404, res.end()) : next();
@@ -5989,9 +6006,9 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
5989
6006
  }
5990
6007
  };
5991
6008
  }, getDevMiddlewares = async (options)=>{
5992
- let middlewares = [], { environments, compilationManager } = options;
6009
+ let middlewares = [], { compilationManager } = options;
5993
6010
  'verbose' === rslog_index_js_namespaceObject.logger.level && middlewares.push(await getRequestLoggerMiddleware());
5994
- let { before, after } = applySetupMiddlewares(options.dev, environments, compilationManager);
6011
+ let { before, after } = applySetupMiddlewares(options.dev, options.devServerAPI);
5995
6012
  middlewares.push(...before);
5996
6013
  let { onUpgrade } = await applyDefaultMiddlewares({
5997
6014
  ...options,
@@ -6399,6 +6416,10 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6399
6416
  middlewares,
6400
6417
  environments: environmentAPI,
6401
6418
  httpServer,
6419
+ sockWrite: (type, data)=>null == compilationManager ? void 0 : compilationManager.socketServer.sockWrite({
6420
+ type,
6421
+ data
6422
+ }),
6402
6423
  listen: async ()=>{
6403
6424
  if (!httpServer) throw Error('[rsbuild:server] Can not listen dev server as `server.middlewareMode` is enabled.');
6404
6425
  let serverTerminator = getServerTerminator(httpServer);
@@ -6446,9 +6467,9 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6446
6467
  pwd: root,
6447
6468
  compilationManager,
6448
6469
  dev: devConfig,
6470
+ devServerAPI,
6449
6471
  context,
6450
6472
  server: config.server,
6451
- environments: environmentAPI,
6452
6473
  postCallbacks
6453
6474
  })).middlewares))Array.isArray(item) ? middlewares.use(...item) : middlewares.use(item);
6454
6475
  return rslog_index_js_namespaceObject.logger.debug('create dev server done'), devServerAPI;
@@ -7530,11 +7551,11 @@ ${section.body}` : section.body).join("\n\n"));
7530
7551
  }
7531
7552
  process.title = 'rsbuild-node';
7532
7553
  let { npm_execpath } = process.env;
7533
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && console.log(), rslog_index_js_namespaceObject.logger.greet(` Rsbuild v1.3.18\n`);
7554
+ (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && console.log(), rslog_index_js_namespaceObject.logger.greet(` Rsbuild v1.3.19\n`);
7534
7555
  try {
7535
7556
  !function() {
7536
7557
  let cli = cac_dist('rsbuild');
7537
- cli.help(), cli.version("1.3.18"), applyCommonOptions(cli);
7558
+ cli.help(), cli.version("1.3.19"), applyCommonOptions(cli);
7538
7559
  let devCommand = cli.command('', 'starting the dev server').alias('dev'), buildCommand = cli.command('build', 'build the app for production'), previewCommand = cli.command('preview', 'preview the production build locally'), inspectCommand = cli.command('inspect', 'inspect the Rspack and Rsbuild configs');
7539
7560
  applyServerOptions(devCommand), applyServerOptions(previewCommand), devCommand.action(async (options)=>{
7540
7561
  try {
@@ -7585,7 +7606,7 @@ ${section.body}` : section.body).join("\n\n"));
7585
7606
  rslog_index_js_namespaceObject.logger.error('Failed to start Rsbuild CLI.'), rslog_index_js_namespaceObject.logger.error(err);
7586
7607
  }
7587
7608
  }
7588
- let src_version = "1.3.18";
7609
+ let src_version = "1.3.19";
7589
7610
  })(), 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 === [
7590
7611
  "PLUGIN_CSS_NAME",
7591
7612
  "PLUGIN_SWC_NAME",
package/dist/index.js CHANGED
@@ -2116,7 +2116,7 @@ async function updateEnvironmentContext(context, configs) {
2116
2116
  async function createContext(options, userConfig) {
2117
2117
  let { cwd } = options, rootPath = userConfig.root ? getAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
2118
2118
  return {
2119
- version: "1.3.18",
2119
+ version: "1.3.19",
2120
2120
  rootPath,
2121
2121
  distPath: '',
2122
2122
  cachePath,
@@ -3027,7 +3027,7 @@ function RsbuildHtmlPlugin_define_property(obj, key, value) {
3027
3027
  writable: !0
3028
3028
  }) : obj[key] = value, obj;
3029
3029
  }
3030
- let VOID_TAGS = [
3030
+ let entryNameSymbol = Symbol('entryName'), VOID_TAGS = [
3031
3031
  'area',
3032
3032
  'base',
3033
3033
  'br',
@@ -3153,11 +3153,15 @@ class RsbuildHtmlPlugin {
3153
3153
  meta: {}
3154
3154
  };
3155
3155
  href.endsWith('.svg') && (tag.attributes.type = 'image/svg+xml'), headTags.unshift(tag);
3156
+ }, getExtraDataByPlugin = (plugin)=>{
3157
+ if (!plugin.options) return;
3158
+ let entryName = plugin.options[entryNameSymbol];
3159
+ if (entryName) return this.getExtraData(entryName);
3156
3160
  };
3157
3161
  compiler.hooks.compilation.tap(this.name, (compilation)=>{
3158
3162
  let hooks = getHTMLPlugin().getCompilationHooks(compilation);
3159
3163
  hooks.alterAssetTagGroups.tapPromise(this.name, async (data)=>{
3160
- let extraData = this.getExtraData(data.plugin);
3164
+ let extraData = getExtraDataByPlugin(data.plugin);
3161
3165
  if (!extraData) return data;
3162
3166
  let { headTags, bodyTags } = data, { favicon, context, tagConfig, entryName, environment, templateContent } = extraData;
3163
3167
  if (!hasTitle(templateContent)) {
@@ -3186,7 +3190,7 @@ class RsbuildHtmlPlugin {
3186
3190
  bodyTags: modified.bodyTags.map(fromBasicTag)
3187
3191
  }), tagConfig && applyTagConfig(data, tagConfig, compilation.hash ?? '', entryName), data;
3188
3192
  }), hooks.beforeEmit.tapPromise(this.name, async (data)=>{
3189
- let extraData = this.getExtraData(data.plugin);
3193
+ let extraData = getExtraDataByPlugin(data.plugin);
3190
3194
  if (!extraData) return data;
3191
3195
  let { context, environment } = extraData, [modified] = await context.hooks.modifyHTML.callChain({
3192
3196
  environment: environment.name,
@@ -3249,7 +3253,7 @@ let getTagConfig = (config)=>{
3249
3253
  api.modifyBundlerChain(async (chain, { HtmlPlugin, CHAIN_ID, environment })=>{
3250
3254
  let { config, htmlPaths } = environment;
3251
3255
  if (0 === Object.keys(htmlPaths).length) return;
3252
- let assetPrefix = getPublicPathFromChain(chain, !1), entries = chain.entryPoints.entries() || {}, entryNames = Object.keys(entries).filter((entryName)=>!!htmlPaths[entryName]), extraDataList = [], finalOptions = await Promise.all(entryNames.map(async (entryName)=>{
3256
+ let assetPrefix = getPublicPathFromChain(chain, !1), entries = chain.entryPoints.entries() || {}, entryNames = Object.keys(entries).filter((entryName)=>!!htmlPaths[entryName]), extraDataMap = new Map(), finalOptions = await Promise.all(entryNames.map(async (entryName)=>{
3253
3257
  let entryValue = entries[entryName].values(), chunks = function(entryName, entryValue) {
3254
3258
  let chunks = [
3255
3259
  entryName
@@ -3312,7 +3316,7 @@ let getTagConfig = (config)=>{
3312
3316
  context,
3313
3317
  environment
3314
3318
  };
3315
- extraDataList.push(extraData), templateContent && (extraData.templateContent = templateContent);
3319
+ extraDataMap.set(entryName, extraData), templateContent && (extraData.templateContent = templateContent);
3316
3320
  let tagConfig = getTagConfig(environment.config);
3317
3321
  tagConfig && (extraData.tagConfig = tagConfig), pluginOptions.title = reduceConfigsMergeContext({
3318
3322
  initial: '',
@@ -3338,12 +3342,16 @@ let getTagConfig = (config)=>{
3338
3342
  }
3339
3343
  });
3340
3344
  return finalOptions.template || finalOptions.templateContent || (pluginOptions.template = '', pluginOptions.templateContent = templateContent), finalOptions;
3341
- })), extraDataMap = new WeakMap();
3345
+ }));
3342
3346
  if (entryNames.forEach((entryName, index)=>{
3343
- let pluginInstance = new HtmlPlugin(finalOptions[index]), extraData = extraDataList.find((item)=>item.entryName === entryName);
3344
- chain.plugin(`${CHAIN_ID.PLUGIN.HTML}-${entryName}`).use(pluginInstance), extraData && extraDataMap.set(pluginInstance, extraData);
3347
+ chain.plugin(`${CHAIN_ID.PLUGIN.HTML}-${entryName}`).use(HtmlPlugin, [
3348
+ {
3349
+ ...finalOptions[index],
3350
+ [entryNameSymbol]: entryName
3351
+ }
3352
+ ]);
3345
3353
  }), chain.plugin('rsbuild-html-plugin').use(RsbuildHtmlPlugin, [
3346
- (pluginInstance)=>extraDataMap.get(pluginInstance)
3354
+ (entryName)=>extraDataMap.get(entryName)
3347
3355
  ]), config.html) {
3348
3356
  let { crossorigin } = config.html;
3349
3357
  crossorigin && chain.output.crossOriginLoading(!0 === crossorigin ? 'anonymous' : crossorigin);
@@ -4250,25 +4258,35 @@ let resourceHints_generateLinks = (options, rel)=>options.map((option)=>({
4250
4258
  }
4251
4259
  });
4252
4260
  }
4253
- }), pluginRspackProfile = ()=>({
4261
+ });
4262
+ async function ensureFileDir(outputFilePath) {
4263
+ let dir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.dirname(outputFilePath);
4264
+ await __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.default.promises.mkdir(dir, {
4265
+ recursive: !0
4266
+ });
4267
+ }
4268
+ async function applyProfile(root, filterValue, traceLayer = 'chrome', traceOutput) {
4269
+ if ('chrome' !== traceLayer && 'logger' !== traceLayer) throw Error(`unsupported trace layer: ${traceLayer}`);
4270
+ if (!traceOutput) {
4271
+ let timestamp = Date.now(), defaultOutputDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.join(root, `.rspack-profile-${timestamp}-${process.pid}`), defaultRustTraceChromeOutput = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.join(defaultOutputDir, 'trace.json');
4272
+ traceOutput = 'chrome' === traceLayer ? defaultRustTraceChromeOutput : 'stdout';
4273
+ }
4274
+ return await ensureFileDir(traceOutput), await __WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__.default.experiments.globalTrace.register("OVERVIEW" === filterValue ? 'info' : "ALL" === filterValue ? 'trace' : filterValue, traceLayer, traceOutput), traceOutput;
4275
+ }
4276
+ let pluginRspackProfile = ()=>({
4254
4277
  name: 'rsbuild:rspack-profile',
4255
4278
  async setup (api) {
4256
- var _process_env_RSPACK_PROFILE;
4279
+ let traceOutput;
4257
4280
  if ('webpack' === api.context.bundlerType) return;
4258
- let RSPACK_PROFILE = null == (_process_env_RSPACK_PROFILE = process.env.RSPACK_PROFILE) ? void 0 : _process_env_RSPACK_PROFILE.toUpperCase();
4281
+ let { RSPACK_PROFILE } = process.env;
4259
4282
  if (!RSPACK_PROFILE) return;
4260
- let timestamp = Date.now(), profileDirName = `rspack-profile-${timestamp}`, enableProfileTrace = 'ALL' === RSPACK_PROFILE || RSPACK_PROFILE.includes('TRACE'), onStart = async ()=>{
4261
- let profileDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.join(api.context.distPath, profileDirName), traceFilePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.join(profileDir, 'trace.json');
4262
- await isFileExists(profileDir) || await __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.default.promises.mkdir(profileDir, {
4263
- recursive: !0
4264
- }), enableProfileTrace && __WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__.default.experiments.globalTrace.register('trace', 'chrome', traceFilePath);
4283
+ let onStart = async ()=>{
4284
+ traceOutput = await applyProfile(api.context.rootPath, RSPACK_PROFILE, process.env.RSPACK_TRACE_LAYER, process.env.RSPACK_TRACE_OUTPUT);
4265
4285
  };
4266
4286
  api.onBeforeBuild(({ isFirstCompile })=>{
4267
4287
  isFirstCompile && onStart();
4268
4288
  }), api.onBeforeStartDevServer(onStart), api.onExit(()=>{
4269
- enableProfileTrace && __WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__.default.experiments.globalTrace.cleanup();
4270
- let profileDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.join(api.context.distPath, profileDirName);
4271
- __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.info(`profile file saved to ${__WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js_ea7a20e9__.default.cyan(profileDir)}`);
4289
+ traceOutput && (__WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__.default.experiments.globalTrace.cleanup(), __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.info(`profile file saved to ${__WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js_ea7a20e9__.default.cyan(traceOutput)}`));
4272
4290
  });
4273
4291
  }
4274
4292
  }), pluginServer = ()=>({
@@ -5288,7 +5306,7 @@ class SocketServer {
5288
5306
  compilationId
5289
5307
  });
5290
5308
  if (!force && statsJson && !statsJson.errorsCount && statsJson.assets && statsJson.assets.every((asset)=>!asset.emitted)) return this.sockWrite({
5291
- type: 'still-ok',
5309
+ type: 'ok',
5292
5310
  compilationId
5293
5311
  });
5294
5312
  if (this.sockWrite({
@@ -5760,14 +5778,11 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
5760
5778
  for (let middleware of proxyMiddlewares)'function' == typeof middleware.upgrade && middleware.upgrade(req, socket, head);
5761
5779
  }
5762
5780
  };
5763
- }, applySetupMiddlewares = (dev, environments, compilationManager)=>{
5764
- let setupMiddlewares = dev.setupMiddlewares || [], serverOptions = {
5765
- sockWrite: (type, data)=>null == compilationManager ? void 0 : compilationManager.socketServer.sockWrite({
5766
- type,
5767
- data
5768
- }),
5769
- environments
5770
- }, before = [], after = [];
5781
+ }, applySetupMiddlewares = (dev, devServerAPI)=>{
5782
+ let setupMiddlewares = dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
5783
+ 'sockWrite',
5784
+ 'environments'
5785
+ ]), before = [], after = [];
5771
5786
  for (let handler of setupMiddlewares)handler({
5772
5787
  unshift: (...handlers)=>before.unshift(...handlers),
5773
5788
  push: (...handlers)=>after.push(...handlers)
@@ -5776,7 +5791,7 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
5776
5791
  before,
5777
5792
  after
5778
5793
  };
5779
- }, applyDefaultMiddlewares = async ({ dev, middlewares, server, compilationManager, context, pwd, environments, postCallbacks })=>{
5794
+ }, applyDefaultMiddlewares = async ({ dev, devServerAPI, middlewares, server, compilationManager, context, pwd, postCallbacks })=>{
5780
5795
  let upgradeEvents = [];
5781
5796
  if (server.cors) {
5782
5797
  let { default: corsMiddleware } = await import("../compiled/cors/index.js");
@@ -5802,7 +5817,7 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
5802
5817
  '/__open-in-editor',
5803
5818
  launchEditorMiddleware()
5804
5819
  ]), middlewares.push(viewingServedFilesMiddleware({
5805
- environments
5820
+ environments: devServerAPI.environments
5806
5821
  })), compilationManager && (middlewares.push(compilationManager.middleware), upgradeEvents.push(compilationManager.socketServer.upgrade), middlewares.push((req, res, next)=>{
5807
5822
  var _req_url;
5808
5823
  (null == (_req_url = req.url) ? void 0 : _req_url.endsWith('.hot-update.json')) && 'OPTIONS' !== req.method ? (res.statusCode = 404, res.end()) : next();
@@ -5831,9 +5846,9 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
5831
5846
  }
5832
5847
  };
5833
5848
  }, getDevMiddlewares = async (options)=>{
5834
- let middlewares = [], { environments, compilationManager } = options;
5849
+ let middlewares = [], { compilationManager } = options;
5835
5850
  'verbose' === __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.level && middlewares.push(await getRequestLoggerMiddleware());
5836
- let { before, after } = applySetupMiddlewares(options.dev, environments, compilationManager);
5851
+ let { before, after } = applySetupMiddlewares(options.dev, options.devServerAPI);
5837
5852
  middlewares.push(...before);
5838
5853
  let { onUpgrade } = await applyDefaultMiddlewares({
5839
5854
  ...options,
@@ -6236,6 +6251,10 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
6236
6251
  middlewares,
6237
6252
  environments: environmentAPI,
6238
6253
  httpServer,
6254
+ sockWrite: (type, data)=>null == compilationManager ? void 0 : compilationManager.socketServer.sockWrite({
6255
+ type,
6256
+ data
6257
+ }),
6239
6258
  listen: async ()=>{
6240
6259
  if (!httpServer) throw Error('[rsbuild:server] Can not listen dev server as `server.middlewareMode` is enabled.');
6241
6260
  let serverTerminator = getServerTerminator(httpServer);
@@ -6283,9 +6302,9 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
6283
6302
  pwd: root,
6284
6303
  compilationManager,
6285
6304
  dev: devConfig,
6305
+ devServerAPI,
6286
6306
  context,
6287
6307
  server: config.server,
6288
- environments: environmentAPI,
6289
6308
  postCallbacks
6290
6309
  })).middlewares))Array.isArray(item) ? middlewares.use(...item) : middlewares.use(item);
6291
6310
  return __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.debug('create dev server done'), devServerAPI;
@@ -7365,11 +7384,11 @@ async function runCLI() {
7365
7384
  }
7366
7385
  process.title = 'rsbuild-node';
7367
7386
  let { npm_execpath } = process.env;
7368
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && console.log(), __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.greet(` Rsbuild v1.3.18\n`);
7387
+ (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && console.log(), __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.greet(` Rsbuild v1.3.19\n`);
7369
7388
  try {
7370
7389
  !function() {
7371
7390
  let cli = cac_dist('rsbuild');
7372
- cli.help(), cli.version("1.3.18"), applyCommonOptions(cli);
7391
+ cli.help(), cli.version("1.3.19"), applyCommonOptions(cli);
7373
7392
  let devCommand = cli.command('', 'starting the dev server').alias('dev'), buildCommand = cli.command('build', 'build the app for production'), previewCommand = cli.command('preview', 'preview the production build locally'), inspectCommand = cli.command('inspect', 'inspect the Rspack and Rsbuild configs');
7374
7393
  applyServerOptions(devCommand), applyServerOptions(previewCommand), devCommand.action(async (options)=>{
7375
7394
  try {
@@ -7420,6 +7439,6 @@ async function runCLI() {
7420
7439
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.error('Failed to start Rsbuild CLI.'), __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.error(err);
7421
7440
  }
7422
7441
  }
7423
- let src_version = "1.3.18";
7442
+ let src_version = "1.3.19";
7424
7443
  var __webpack_exports__logger = __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger, __webpack_exports__rspack = __WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__.rspack;
7425
7444
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, config_loadConfig as loadConfig, loadEnv, mergeRsbuildConfig, runCLI, src_version as version, __webpack_exports__logger as logger, __webpack_exports__rspack as rspack };
@@ -1,4 +1,4 @@
1
- import type { Compiler, RspackPluginInstance } from '@rspack/core';
1
+ import type { Compiler } from '@rspack/core';
2
2
  import type { HtmlRspackPlugin, InternalContext } from '../types';
3
3
  import type { EnvironmentContext, HtmlTag, HtmlTagDescriptor } from '../types';
4
4
  type HtmlTagObject = HtmlRspackPlugin.HtmlTagObject;
@@ -8,6 +8,10 @@ export type TagConfig = {
8
8
  append?: HtmlTag['append'];
9
9
  publicPath?: HtmlTag['publicPath'];
10
10
  };
11
+ /**
12
+ * A unique identifier for providing extra data to RsbuildHtmlPlugin
13
+ */
14
+ export declare const entryNameSymbol: unique symbol;
11
15
  export declare const FILE_ATTRS: {
12
16
  link: string;
13
17
  script: string;
@@ -30,8 +34,8 @@ export type AlterAssetTagGroupsData = {
30
34
  export declare const hasTitle: (html?: string) => boolean;
31
35
  export declare class RsbuildHtmlPlugin {
32
36
  readonly name: string;
33
- readonly getExtraData: (pluginInstance: RspackPluginInstance) => HtmlExtraData | undefined;
34
- constructor(getExtraData: (pluginInstance: RspackPluginInstance) => HtmlExtraData | undefined);
37
+ readonly getExtraData: (entryName: string) => HtmlExtraData | undefined;
38
+ constructor(getExtraData: (entryName: string) => HtmlExtraData | undefined);
35
39
  apply(compiler: Compiler): void;
36
40
  }
37
41
  export {};
@@ -1,12 +1,13 @@
1
- import type { DevConfig, EnvironmentAPI, InternalContext, RequestHandler, ServerConfig } from '../types';
1
+ import type { DevConfig, InternalContext, RequestHandler, ServerConfig } from '../types';
2
2
  import type { CompilationManager } from './compilationManager';
3
+ import type { RsbuildDevServer } from './devServer';
3
4
  import type { UpgradeEvent } from './helper';
4
5
  export type RsbuildDevMiddlewareOptions = {
5
6
  pwd: string;
6
7
  dev: DevConfig;
8
+ devServerAPI: RsbuildDevServer;
7
9
  server: ServerConfig;
8
10
  context: InternalContext;
9
- environments: EnvironmentAPI;
10
11
  compilationManager?: CompilationManager;
11
12
  /**
12
13
  * Callbacks returned by the `onBeforeStartDevServer` hook.
@@ -3,6 +3,8 @@ import type { Http2SecureServer } from 'node:http2';
3
3
  import type Connect from '../../compiled/connect/index.js';
4
4
  import type { CreateCompiler, CreateDevServerOptions, EnvironmentAPI, InternalContext, NormalizedConfig } from '../types';
5
5
  type HTTPServer = Server | Http2SecureServer;
6
+ export type SockWriteType = 'static-changed' | (string & {});
7
+ export type SockWrite = (type: SockWriteType, data?: string | boolean | Record<string, any>) => void;
6
8
  export type RsbuildDevServer = {
7
9
  /**
8
10
  * The `connect` app instance.
@@ -59,6 +61,12 @@ export type RsbuildDevServer = {
59
61
  * Open URL in the browser after starting the server.
60
62
  */
61
63
  open: () => Promise<void>;
64
+ /**
65
+ * Allows middleware to send some message to HMR client, and then the HMR
66
+ * client will take different actions depending on the message type.
67
+ * - `static-changed`: The page will reload.
68
+ */
69
+ sockWrite: SockWrite;
62
70
  };
63
71
  export declare function createDevServer<Options extends {
64
72
  context: InternalContext;
@@ -1,8 +1,9 @@
1
1
  import type { IncomingMessage } from 'node:http';
2
2
  import type { Socket } from 'node:net';
3
3
  import type { DevConfig, Rspack } from '../types';
4
+ import type { SockWriteType } from './devServer';
4
5
  interface SocketMessage {
5
- type: string;
6
+ type: SockWriteType;
6
7
  compilationId?: string;
7
8
  data?: Record<string, any> | string | boolean;
8
9
  }
@@ -8,6 +8,7 @@ import type { Options as HttpProxyOptions, Filter as ProxyFilter } from '../../c
8
8
  import type RspackChain from '../../compiled/rspack-chain';
9
9
  import type { FileDescriptor } from '../../compiled/rspack-manifest-plugin';
10
10
  import type { BundleAnalyzerPlugin } from '../../compiled/webpack-bundle-analyzer/index.js';
11
+ import type { RsbuildDevServer } from '../server/devServer';
11
12
  import type { ModifyBundlerChainUtils, ModifyChainUtils, Routes } from './hooks';
12
13
  import type { ModifyWebpackChainUtils, ModifyWebpackConfigUtils, RsbuildPlugins } from './plugin';
13
14
  import type { RsbuildEntry, RsbuildMode, RsbuildTarget } from './rsbuild';
@@ -1209,10 +1210,7 @@ export type EnvironmentAPI = {
1209
1210
  getTransformedHtml: (entryName: string) => Promise<string>;
1210
1211
  };
1211
1212
  };
1212
- export type SetupMiddlewaresServer = {
1213
- sockWrite: (type: string, data?: string | boolean | Record<string, any>) => void;
1214
- environments: EnvironmentAPI;
1215
- };
1213
+ export type SetupMiddlewaresServer = Pick<RsbuildDevServer, 'sockWrite' | 'environments'>;
1216
1214
  export type SetupMiddlewaresFn = (middlewares: {
1217
1215
  unshift: (...handlers: RequestHandler[]) => void;
1218
1216
  push: (...handlers: RequestHandler[]) => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "1.3.18",
3
+ "version": "1.3.19",
4
4
  "description": "The Rspack-based build tool.",
5
5
  "homepage": "https://rsbuild.dev",
6
6
  "bugs": {
@@ -53,10 +53,10 @@
53
53
  "jiti": "^2.4.2"
54
54
  },
55
55
  "devDependencies": {
56
- "@rslib/core": "0.6.8",
56
+ "@rslib/core": "0.6.9",
57
57
  "@types/connect": "3.4.38",
58
- "@types/cors": "^2.8.17",
59
- "@types/node": "^22.15.3",
58
+ "@types/cors": "^2.8.18",
59
+ "@types/node": "^22.15.17",
60
60
  "@types/on-finished": "2.3.4",
61
61
  "@types/webpack-bundle-analyzer": "4.7.0",
62
62
  "@types/ws": "^8.18.1",