@rsbuild/core 1.3.17 → 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
@@ -1032,6 +1032,7 @@ for(var __webpack_i__ in (()=>{
1032
1032
  "use strict";
1033
1033
  let swcHelpersPath, pluginHelper_htmlPlugin, cssExtractPlugin;
1034
1034
  __webpack_require__.r(__webpack_exports__), __webpack_require__.d(__webpack_exports__, {
1035
+ loadEnv: ()=>loadEnv,
1035
1036
  logger: ()=>rslog_index_js_namespaceObject.logger,
1036
1037
  createRsbuild: ()=>createRsbuild,
1037
1038
  rspack: ()=>core_namespaceObject.rspack,
@@ -1041,9 +1042,9 @@ for(var __webpack_i__ in (()=>{
1041
1042
  version: ()=>src_version,
1042
1043
  PLUGIN_SWC_NAME: ()=>PLUGIN_SWC_NAME,
1043
1044
  PLUGIN_CSS_NAME: ()=>PLUGIN_CSS_NAME,
1044
- loadConfig: ()=>config_loadConfig,
1045
1045
  ensureAssetPrefix: ()=>ensureAssetPrefix,
1046
- loadEnv: ()=>loadEnv
1046
+ loadConfig: ()=>config_loadConfig,
1047
+ defaultAllowedOrigins: ()=>defaultAllowedOrigins
1047
1048
  });
1048
1049
  var provider_helpers_namespaceObject = {};
1049
1050
  __webpack_require__.r(provider_helpers_namespaceObject), __webpack_require__.d(provider_helpers_namespaceObject, {
@@ -1593,7 +1594,7 @@ for(var __webpack_i__ in (()=>{
1593
1594
  overlay: !0,
1594
1595
  reconnect: 100
1595
1596
  }
1596
- }), LOCAL_ORIGINS_REGEX = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/, getDefaultServerConfig = ()=>({
1597
+ }), defaultAllowedOrigins = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/, getDefaultServerConfig = ()=>({
1597
1598
  port: 3000,
1598
1599
  host: DEFAULT_DEV_HOST,
1599
1600
  open: !1,
@@ -1603,7 +1604,7 @@ for(var __webpack_i__ in (()=>{
1603
1604
  printUrls: !0,
1604
1605
  strictPort: !1,
1605
1606
  cors: {
1606
- origin: LOCAL_ORIGINS_REGEX
1607
+ origin: defaultAllowedOrigins
1607
1608
  },
1608
1609
  middlewareMode: !1
1609
1610
  }), getDefaultSourceConfig = ()=>({
@@ -2256,13 +2257,14 @@ for(var __webpack_i__ in (()=>{
2256
2257
  }
2257
2258
  }
2258
2259
  async function createContext(options, userConfig) {
2259
- 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;
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';
2260
2261
  return {
2261
- version: "1.3.17",
2262
+ version: "1.3.19",
2262
2263
  rootPath,
2263
2264
  distPath: '',
2264
2265
  cachePath,
2265
- bundlerType: userConfig.provider ? 'webpack' : 'rspack',
2266
+ callerName: options.callerName,
2267
+ bundlerType,
2266
2268
  environments: {},
2267
2269
  hooks: {
2268
2270
  onExit: createAsyncHook(),
@@ -3171,7 +3173,7 @@ for(var __webpack_i__ in (()=>{
3171
3173
  writable: !0
3172
3174
  }) : obj[key] = value, obj;
3173
3175
  }
3174
- let VOID_TAGS = [
3176
+ let entryNameSymbol = Symbol('entryName'), VOID_TAGS = [
3175
3177
  'area',
3176
3178
  'base',
3177
3179
  'br',
@@ -3297,19 +3299,26 @@ for(var __webpack_i__ in (()=>{
3297
3299
  meta: {}
3298
3300
  };
3299
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);
3300
3306
  };
3301
3307
  compiler.hooks.compilation.tap(this.name, (compilation)=>{
3302
3308
  let hooks = getHTMLPlugin().getCompilationHooks(compilation);
3303
3309
  hooks.alterAssetTagGroups.tapPromise(this.name, async (data)=>{
3304
- var _data_plugin_options, _data_plugin_options1;
3305
- let entryName = null == (_data_plugin_options = data.plugin.options) ? void 0 : _data_plugin_options.entryName;
3306
- if (!entryName) return data;
3307
- let { headTags, bodyTags } = data, { favicon, tagConfig, templateContent } = this.options[entryName];
3308
- hasTitle(templateContent) || addTitleTag(headTags, null == (_data_plugin_options1 = data.plugin.options) ? void 0 : _data_plugin_options1.title), favicon && await addFavicon(headTags, favicon, compilation, data.publicPath);
3310
+ let extraData = getExtraDataByPlugin(data.plugin);
3311
+ if (!extraData) return data;
3312
+ let { headTags, bodyTags } = data, { favicon, context, tagConfig, entryName, environment, templateContent } = extraData;
3313
+ if (!hasTitle(templateContent)) {
3314
+ var _data_plugin_options;
3315
+ addTitleTag(headTags, null == (_data_plugin_options = data.plugin.options) ? void 0 : _data_plugin_options.title);
3316
+ }
3317
+ favicon && await addFavicon(headTags, favicon, compilation, data.publicPath);
3309
3318
  let tags = {
3310
3319
  headTags: headTags.map(formatBasicTag),
3311
3320
  bodyTags: bodyTags.map(formatBasicTag)
3312
- }, context = this.getContext(), environment = this.getEnvironment(), [modified] = await context.hooks.modifyHTMLTags.callChain({
3321
+ }, [modified] = await context.hooks.modifyHTMLTags.callChain({
3313
3322
  environment: environment.name,
3314
3323
  args: [
3315
3324
  tags,
@@ -3327,7 +3336,9 @@ for(var __webpack_i__ in (()=>{
3327
3336
  bodyTags: modified.bodyTags.map(fromBasicTag)
3328
3337
  }), tagConfig && applyTagConfig(data, tagConfig, compilation.hash ?? '', entryName), data;
3329
3338
  }), hooks.beforeEmit.tapPromise(this.name, async (data)=>{
3330
- let context = this.getContext(), environment = this.getEnvironment(), [modified] = await context.hooks.modifyHTML.callChain({
3339
+ let extraData = getExtraDataByPlugin(data.plugin);
3340
+ if (!extraData) return data;
3341
+ let { context, environment } = extraData, [modified] = await context.hooks.modifyHTML.callChain({
3331
3342
  environment: environment.name,
3332
3343
  args: [
3333
3344
  data.html,
@@ -3346,8 +3357,8 @@ for(var __webpack_i__ in (()=>{
3346
3357
  });
3347
3358
  });
3348
3359
  }
3349
- constructor(options, getEnvironment, getContext){
3350
- RsbuildHtmlPlugin_define_property(this, "name", void 0), RsbuildHtmlPlugin_define_property(this, "getEnvironment", void 0), RsbuildHtmlPlugin_define_property(this, "options", void 0), RsbuildHtmlPlugin_define_property(this, "getContext", void 0), this.name = 'RsbuildHtmlPlugin', this.options = options, this.getEnvironment = getEnvironment, this.getContext = getContext;
3360
+ constructor(getExtraData){
3361
+ RsbuildHtmlPlugin_define_property(this, "name", void 0), RsbuildHtmlPlugin_define_property(this, "getExtraData", void 0), this.name = 'RsbuildHtmlPlugin', this.getExtraData = getExtraData;
3351
3362
  }
3352
3363
  }
3353
3364
  let getDefaultTemplateContent = (mountId)=>`<!doctype html><html><head></head><body><div id="${mountId}"></div></body></html>`, existTemplatePath = new Set();
@@ -3388,7 +3399,7 @@ for(var __webpack_i__ in (()=>{
3388
3399
  api.modifyBundlerChain(async (chain, { HtmlPlugin, CHAIN_ID, environment })=>{
3389
3400
  let { config, htmlPaths } = environment;
3390
3401
  if (0 === Object.keys(htmlPaths).length) return;
3391
- let assetPrefix = getPublicPathFromChain(chain, !1), entries = chain.entryPoints.entries() || {}, entryNames = Object.keys(entries).filter((entryName)=>!!htmlPaths[entryName]), htmlInfoMap = {}, 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)=>{
3392
3403
  var entryName1, entryName2, config1, assetPrefix1, entryName3, entryName4;
3393
3404
  let entryValue = entries[entryName].values(), chunks = function(entryName, entryValue) {
3394
3405
  let chunks = [
@@ -3447,10 +3458,14 @@ for(var __webpack_i__ in (()=>{
3447
3458
  scriptLoading: config.html.scriptLoading
3448
3459
  };
3449
3460
  templatePath && (pluginOptions.template = templatePath), chunks.length > 1 && (pluginOptions.chunksSortMode = 'manual');
3450
- let htmlInfo = {};
3451
- htmlInfoMap[entryName] = htmlInfo, templateContent && (htmlInfo.templateContent = templateContent);
3461
+ let extraData = {
3462
+ entryName,
3463
+ context,
3464
+ environment
3465
+ };
3466
+ extraDataMap.set(entryName, extraData), templateContent && (extraData.templateContent = templateContent);
3452
3467
  let tagConfig = getTagConfig(environment.config);
3453
- tagConfig && (htmlInfo.tagConfig = tagConfig), entryName3 = entryName, pluginOptions.title = reduceConfigsMergeContext({
3468
+ tagConfig && (extraData.tagConfig = tagConfig), entryName3 = entryName, pluginOptions.title = reduceConfigsMergeContext({
3454
3469
  initial: '',
3455
3470
  config: config.html.title,
3456
3471
  ctx: {
@@ -3464,7 +3479,7 @@ for(var __webpack_i__ in (()=>{
3464
3479
  entryName: entryName4
3465
3480
  }
3466
3481
  }));
3467
- favicon && (htmlInfo.favicon = favicon);
3482
+ favicon && (extraData.favicon = favicon);
3468
3483
  let finalOptions = reduceConfigsWithContext({
3469
3484
  initial: pluginOptions,
3470
3485
  config: 'boolean' == typeof config.tools.htmlPlugin ? {} : config.tools.htmlPlugin,
@@ -3477,12 +3492,13 @@ for(var __webpack_i__ in (()=>{
3477
3492
  }));
3478
3493
  if (entryNames.forEach((entryName, index)=>{
3479
3494
  chain.plugin(`${CHAIN_ID.PLUGIN.HTML}-${entryName}`).use(HtmlPlugin, [
3480
- finalOptions[index]
3495
+ {
3496
+ ...finalOptions[index],
3497
+ [entryNameSymbol]: entryName
3498
+ }
3481
3499
  ]);
3482
3500
  }), chain.plugin('rsbuild-html-plugin').use(RsbuildHtmlPlugin, [
3483
- htmlInfoMap,
3484
- ()=>environment,
3485
- ()=>context
3501
+ (entryName)=>extraDataMap.get(entryName)
3486
3502
  ]), config.html) {
3487
3503
  let { crossorigin } = config.html;
3488
3504
  crossorigin && chain.output.crossOriginLoading(!0 === crossorigin ? 'anonymous' : crossorigin);
@@ -4392,33 +4408,37 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
4392
4408
  }
4393
4409
  });
4394
4410
  }
4395
- }), external_node_inspector_namespaceObject = require("node:inspector");
4396
- var external_node_inspector_default = __webpack_require__.n(external_node_inspector_namespaceObject);
4397
- let stopProfiler = (output, profileSession)=>{
4398
- profileSession && profileSession.post('Profiler.stop', (error, param)=>{
4399
- if (error) return void rslog_index_js_namespaceObject.logger.error('Failed to generate JavaScript CPU profile:', error);
4400
- external_node_fs_default().writeFileSync(output, JSON.stringify(param.profile));
4401
4411
  });
4402
- }, pluginRspackProfile = ()=>({
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 = ()=>({
4403
4429
  name: 'rsbuild:rspack-profile',
4404
4430
  async setup (api) {
4405
- var _process_env_RSPACK_PROFILE;
4406
- let profileSession;
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'), enableCPUProfile = 'ALL' === RSPACK_PROFILE || RSPACK_PROFILE.includes('CPU'), 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), enableCPUProfile && ((profileSession = new (external_node_inspector_default()).Session()).connect(), profileSession.post('Profiler.enable'), profileSession.post('Profiler.start'));
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
- stopProfiler(external_node_path_default().join(profileDir, 'jscpuprofile.json'), profileSession), rslog_index_js_namespaceObject.logger.info(`profile files 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;
@@ -6816,9 +6837,10 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6816
6837
  setup (api) {
6817
6838
  'webpack' !== api.context.bundlerType && (api.modifyRsbuildConfig((config)=>{
6818
6839
  let { moduleFederation } = config;
6819
- if (api.isPluginExists('rsbuild:module-federation-enhanced') && (config.server ||= {}, config.server.cors = !0), (null == moduleFederation ? void 0 : moduleFederation.options) && moduleFederation.options.exposes) {
6820
- var _config_server, _config_dev_client, _originalConfig_dev, _config_server1;
6821
- config.dev ||= {}, config.server ||= {}, config.server.cors = !0, (null == (_config_server = config.server) ? void 0 : _config_server.port) && !(null == (_config_dev_client = config.dev.client) ? void 0 : _config_dev_client.port) && (config.dev.client ||= {}, config.dev.client.port = config.server.port), (null == (_originalConfig_dev = api.getRsbuildConfig('original').dev) ? void 0 : _originalConfig_dev.assetPrefix) === void 0 && config.dev.assetPrefix === (null == (_config_server1 = config.server) ? void 0 : _config_server1.base) && (config.dev.assetPrefix = !0);
6840
+ if ((null == moduleFederation ? void 0 : moduleFederation.options) && moduleFederation.options.exposes) {
6841
+ var _userConfig_server, _config_server, _config_dev_client, _userConfig_dev, _config_server1;
6842
+ let userConfig = api.getRsbuildConfig('original');
6843
+ config.dev ||= {}, config.server ||= {}, (null == (_userConfig_server = userConfig.server) ? void 0 : _userConfig_server.cors) === void 0 && (config.server.cors = !0), (null == (_config_server = config.server) ? void 0 : _config_server.port) && !(null == (_config_dev_client = config.dev.client) ? void 0 : _config_dev_client.port) && (config.dev.client ||= {}, config.dev.client.port = config.server.port), (null == (_userConfig_dev = userConfig.dev) ? void 0 : _userConfig_dev.assetPrefix) === void 0 && config.dev.assetPrefix === (null == (_config_server1 = config.server) ? void 0 : _config_server1.base) && (config.dev.assetPrefix = !0);
6822
6844
  }
6823
6845
  }), api.modifyEnvironmentConfig((config)=>{
6824
6846
  var _config_moduleFederation, _config_performance_chunkSplit, _config_performance;
@@ -6870,6 +6892,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6870
6892
  }
6871
6893
  let resolvedOptions = {
6872
6894
  cwd: process.cwd(),
6895
+ callerName: 'rsbuild',
6873
6896
  ...options,
6874
6897
  rsbuildConfig: config
6875
6898
  }, pluginManager = (plugins = [], {
@@ -6932,6 +6955,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6932
6955
  'distPath',
6933
6956
  'devServer',
6934
6957
  'cachePath',
6958
+ 'callerName',
6935
6959
  'bundlerType'
6936
6960
  ];
6937
6961
  return new Proxy(context, {
@@ -7527,11 +7551,11 @@ ${section.body}` : section.body).join("\n\n"));
7527
7551
  }
7528
7552
  process.title = 'rsbuild-node';
7529
7553
  let { npm_execpath } = process.env;
7530
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && console.log(), rslog_index_js_namespaceObject.logger.greet(` Rsbuild v1.3.17\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`);
7531
7555
  try {
7532
7556
  !function() {
7533
7557
  let cli = cac_dist('rsbuild');
7534
- cli.help(), cli.version("1.3.17"), applyCommonOptions(cli);
7558
+ cli.help(), cli.version("1.3.19"), applyCommonOptions(cli);
7535
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');
7536
7560
  applyServerOptions(devCommand), applyServerOptions(previewCommand), devCommand.action(async (options)=>{
7537
7561
  try {
@@ -7582,11 +7606,12 @@ ${section.body}` : section.body).join("\n\n"));
7582
7606
  rslog_index_js_namespaceObject.logger.error('Failed to start Rsbuild CLI.'), rslog_index_js_namespaceObject.logger.error(err);
7583
7607
  }
7584
7608
  }
7585
- let src_version = "1.3.17";
7586
- })(), exports.PLUGIN_CSS_NAME = __webpack_exports__.PLUGIN_CSS_NAME, exports.PLUGIN_SWC_NAME = __webpack_exports__.PLUGIN_SWC_NAME, exports.createRsbuild = __webpack_exports__.createRsbuild, 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 === [
7609
+ let src_version = "1.3.19";
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 === [
7587
7611
  "PLUGIN_CSS_NAME",
7588
7612
  "PLUGIN_SWC_NAME",
7589
7613
  "createRsbuild",
7614
+ "defaultAllowedOrigins",
7590
7615
  "defineConfig",
7591
7616
  "ensureAssetPrefix",
7592
7617
  "loadConfig",
package/dist/index.js CHANGED
@@ -21,7 +21,6 @@ import * as __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__ from "node:crypto";
21
21
  import * as __WEBPACK_EXTERNAL_MODULE_node_zlib_a5bb16fc__ from "node:zlib";
22
22
  import * as __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__ from "node:child_process";
23
23
  import * as __WEBPACK_EXTERNAL_MODULE_node_net_0373943e__ from "node:net";
24
- import * as __WEBPACK_EXTERNAL_MODULE_node_inspector_dd9822d6__ from "node:inspector";
25
24
  import * as __WEBPACK_EXTERNAL_MODULE_node_assert_3e74d44e__ from "node:assert";
26
25
  import * as __WEBPACK_EXTERNAL_MODULE_node_readline_91c31510__ from "node:readline";
27
26
  import * as __WEBPACK_EXTERNAL_MODULE_node_dns_78d346ee__ from "node:dns";
@@ -1456,7 +1455,7 @@ let configCache = {}, OVERRIDE_PATHS = [
1456
1455
  overlay: !0,
1457
1456
  reconnect: 100
1458
1457
  }
1459
- }), LOCAL_ORIGINS_REGEX = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/, getDefaultServerConfig = ()=>({
1458
+ }), defaultAllowedOrigins = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/, getDefaultServerConfig = ()=>({
1460
1459
  port: 3000,
1461
1460
  host: DEFAULT_DEV_HOST,
1462
1461
  open: !1,
@@ -1466,7 +1465,7 @@ let configCache = {}, OVERRIDE_PATHS = [
1466
1465
  printUrls: !0,
1467
1466
  strictPort: !1,
1468
1467
  cors: {
1469
- origin: LOCAL_ORIGINS_REGEX
1468
+ origin: defaultAllowedOrigins
1470
1469
  },
1471
1470
  middlewareMode: !1
1472
1471
  }), getDefaultSourceConfig = ()=>({
@@ -2115,13 +2114,14 @@ async function updateEnvironmentContext(context, configs) {
2115
2114
  }
2116
2115
  }
2117
2116
  async function createContext(options, userConfig) {
2118
- 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;
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';
2119
2118
  return {
2120
- version: "1.3.17",
2119
+ version: "1.3.19",
2121
2120
  rootPath,
2122
2121
  distPath: '',
2123
2122
  cachePath,
2124
- bundlerType: userConfig.provider ? 'webpack' : 'rspack',
2123
+ callerName: options.callerName,
2124
+ bundlerType,
2125
2125
  environments: {},
2126
2126
  hooks: {
2127
2127
  onExit: createAsyncHook(),
@@ -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,19 +3153,26 @@ 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
- var _data_plugin_options, _data_plugin_options1;
3161
- let entryName = null == (_data_plugin_options = data.plugin.options) ? void 0 : _data_plugin_options.entryName;
3162
- if (!entryName) return data;
3163
- let { headTags, bodyTags } = data, { favicon, tagConfig, templateContent } = this.options[entryName];
3164
- hasTitle(templateContent) || addTitleTag(headTags, null == (_data_plugin_options1 = data.plugin.options) ? void 0 : _data_plugin_options1.title), favicon && await addFavicon(headTags, favicon, compilation, data.publicPath);
3164
+ let extraData = getExtraDataByPlugin(data.plugin);
3165
+ if (!extraData) return data;
3166
+ let { headTags, bodyTags } = data, { favicon, context, tagConfig, entryName, environment, templateContent } = extraData;
3167
+ if (!hasTitle(templateContent)) {
3168
+ var _data_plugin_options;
3169
+ addTitleTag(headTags, null == (_data_plugin_options = data.plugin.options) ? void 0 : _data_plugin_options.title);
3170
+ }
3171
+ favicon && await addFavicon(headTags, favicon, compilation, data.publicPath);
3165
3172
  let tags = {
3166
3173
  headTags: headTags.map(formatBasicTag),
3167
3174
  bodyTags: bodyTags.map(formatBasicTag)
3168
- }, context = this.getContext(), environment = this.getEnvironment(), [modified] = await context.hooks.modifyHTMLTags.callChain({
3175
+ }, [modified] = await context.hooks.modifyHTMLTags.callChain({
3169
3176
  environment: environment.name,
3170
3177
  args: [
3171
3178
  tags,
@@ -3183,7 +3190,9 @@ class RsbuildHtmlPlugin {
3183
3190
  bodyTags: modified.bodyTags.map(fromBasicTag)
3184
3191
  }), tagConfig && applyTagConfig(data, tagConfig, compilation.hash ?? '', entryName), data;
3185
3192
  }), hooks.beforeEmit.tapPromise(this.name, async (data)=>{
3186
- let context = this.getContext(), environment = this.getEnvironment(), [modified] = await context.hooks.modifyHTML.callChain({
3193
+ let extraData = getExtraDataByPlugin(data.plugin);
3194
+ if (!extraData) return data;
3195
+ let { context, environment } = extraData, [modified] = await context.hooks.modifyHTML.callChain({
3187
3196
  environment: environment.name,
3188
3197
  args: [
3189
3198
  data.html,
@@ -3202,8 +3211,8 @@ class RsbuildHtmlPlugin {
3202
3211
  });
3203
3212
  });
3204
3213
  }
3205
- constructor(options, getEnvironment, getContext){
3206
- RsbuildHtmlPlugin_define_property(this, "name", void 0), RsbuildHtmlPlugin_define_property(this, "getEnvironment", void 0), RsbuildHtmlPlugin_define_property(this, "options", void 0), RsbuildHtmlPlugin_define_property(this, "getContext", void 0), this.name = 'RsbuildHtmlPlugin', this.options = options, this.getEnvironment = getEnvironment, this.getContext = getContext;
3214
+ constructor(getExtraData){
3215
+ RsbuildHtmlPlugin_define_property(this, "name", void 0), RsbuildHtmlPlugin_define_property(this, "getExtraData", void 0), this.name = 'RsbuildHtmlPlugin', this.getExtraData = getExtraData;
3207
3216
  }
3208
3217
  }
3209
3218
  let getDefaultTemplateContent = (mountId)=>`<!doctype html><html><head></head><body><div id="${mountId}"></div></body></html>`, existTemplatePath = new Set();
@@ -3244,7 +3253,7 @@ let getTagConfig = (config)=>{
3244
3253
  api.modifyBundlerChain(async (chain, { HtmlPlugin, CHAIN_ID, environment })=>{
3245
3254
  let { config, htmlPaths } = environment;
3246
3255
  if (0 === Object.keys(htmlPaths).length) return;
3247
- let assetPrefix = getPublicPathFromChain(chain, !1), entries = chain.entryPoints.entries() || {}, entryNames = Object.keys(entries).filter((entryName)=>!!htmlPaths[entryName]), htmlInfoMap = {}, 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)=>{
3248
3257
  let entryValue = entries[entryName].values(), chunks = function(entryName, entryValue) {
3249
3258
  let chunks = [
3250
3259
  entryName
@@ -3302,10 +3311,14 @@ let getTagConfig = (config)=>{
3302
3311
  scriptLoading: config.html.scriptLoading
3303
3312
  };
3304
3313
  templatePath && (pluginOptions.template = templatePath), chunks.length > 1 && (pluginOptions.chunksSortMode = 'manual');
3305
- let htmlInfo = {};
3306
- htmlInfoMap[entryName] = htmlInfo, templateContent && (htmlInfo.templateContent = templateContent);
3314
+ let extraData = {
3315
+ entryName,
3316
+ context,
3317
+ environment
3318
+ };
3319
+ extraDataMap.set(entryName, extraData), templateContent && (extraData.templateContent = templateContent);
3307
3320
  let tagConfig = getTagConfig(environment.config);
3308
- tagConfig && (htmlInfo.tagConfig = tagConfig), pluginOptions.title = reduceConfigsMergeContext({
3321
+ tagConfig && (extraData.tagConfig = tagConfig), pluginOptions.title = reduceConfigsMergeContext({
3309
3322
  initial: '',
3310
3323
  config: config.html.title,
3311
3324
  ctx: {
@@ -3319,7 +3332,7 @@ let getTagConfig = (config)=>{
3319
3332
  entryName: entryName
3320
3333
  }
3321
3334
  });
3322
- favicon && (htmlInfo.favicon = favicon);
3335
+ favicon && (extraData.favicon = favicon);
3323
3336
  let finalOptions = reduceConfigsWithContext({
3324
3337
  initial: pluginOptions,
3325
3338
  config: 'boolean' == typeof config.tools.htmlPlugin ? {} : config.tools.htmlPlugin,
@@ -3332,12 +3345,13 @@ let getTagConfig = (config)=>{
3332
3345
  }));
3333
3346
  if (entryNames.forEach((entryName, index)=>{
3334
3347
  chain.plugin(`${CHAIN_ID.PLUGIN.HTML}-${entryName}`).use(HtmlPlugin, [
3335
- finalOptions[index]
3348
+ {
3349
+ ...finalOptions[index],
3350
+ [entryNameSymbol]: entryName
3351
+ }
3336
3352
  ]);
3337
3353
  }), chain.plugin('rsbuild-html-plugin').use(RsbuildHtmlPlugin, [
3338
- htmlInfoMap,
3339
- ()=>environment,
3340
- ()=>context
3354
+ (entryName)=>extraDataMap.get(entryName)
3341
3355
  ]), config.html) {
3342
3356
  let { crossorigin } = config.html;
3343
3357
  crossorigin && chain.output.crossOriginLoading(!0 === crossorigin ? 'anonymous' : crossorigin);
@@ -4244,31 +4258,35 @@ let resourceHints_generateLinks = (options, rel)=>options.map((option)=>({
4244
4258
  }
4245
4259
  });
4246
4260
  }
4247
- }), stopProfiler = (output, profileSession)=>{
4248
- profileSession && profileSession.post('Profiler.stop', (error, param)=>{
4249
- if (error) return void __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.error('Failed to generate JavaScript CPU profile:', error);
4250
- __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.default.writeFileSync(output, JSON.stringify(param.profile));
4251
4261
  });
4252
- }, pluginRspackProfile = ()=>({
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 = ()=>({
4253
4277
  name: 'rsbuild:rspack-profile',
4254
4278
  async setup (api) {
4255
- var _process_env_RSPACK_PROFILE;
4256
- let profileSession;
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'), enableCPUProfile = 'ALL' === RSPACK_PROFILE || RSPACK_PROFILE.includes('CPU'), 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), enableCPUProfile && ((profileSession = new __WEBPACK_EXTERNAL_MODULE_node_inspector_dd9822d6__.default.Session()).connect(), profileSession.post('Profiler.enable'), profileSession.post('Profiler.start'));
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
- stopProfiler(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.default.join(profileDir, 'jscpuprofile.json'), profileSession), __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.info(`profile files 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;
@@ -6653,9 +6672,10 @@ async function applyDefaultPlugins(pluginManager, context) {
6653
6672
  setup (api) {
6654
6673
  'webpack' !== api.context.bundlerType && (api.modifyRsbuildConfig((config)=>{
6655
6674
  let { moduleFederation } = config;
6656
- if (api.isPluginExists('rsbuild:module-federation-enhanced') && (config.server ||= {}, config.server.cors = !0), (null == moduleFederation ? void 0 : moduleFederation.options) && moduleFederation.options.exposes) {
6657
- var _config_server, _config_dev_client, _originalConfig_dev, _config_server1;
6658
- config.dev ||= {}, config.server ||= {}, config.server.cors = !0, (null == (_config_server = config.server) ? void 0 : _config_server.port) && !(null == (_config_dev_client = config.dev.client) ? void 0 : _config_dev_client.port) && (config.dev.client ||= {}, config.dev.client.port = config.server.port), (null == (_originalConfig_dev = api.getRsbuildConfig('original').dev) ? void 0 : _originalConfig_dev.assetPrefix) === void 0 && config.dev.assetPrefix === (null == (_config_server1 = config.server) ? void 0 : _config_server1.base) && (config.dev.assetPrefix = !0);
6675
+ if ((null == moduleFederation ? void 0 : moduleFederation.options) && moduleFederation.options.exposes) {
6676
+ var _userConfig_server, _config_server, _config_dev_client, _userConfig_dev, _config_server1;
6677
+ let userConfig = api.getRsbuildConfig('original');
6678
+ config.dev ||= {}, config.server ||= {}, (null == (_userConfig_server = userConfig.server) ? void 0 : _userConfig_server.cors) === void 0 && (config.server.cors = !0), (null == (_config_server = config.server) ? void 0 : _config_server.port) && !(null == (_config_dev_client = config.dev.client) ? void 0 : _config_dev_client.port) && (config.dev.client ||= {}, config.dev.client.port = config.server.port), (null == (_userConfig_dev = userConfig.dev) ? void 0 : _userConfig_dev.assetPrefix) === void 0 && config.dev.assetPrefix === (null == (_config_server1 = config.server) ? void 0 : _config_server1.base) && (config.dev.assetPrefix = !0);
6659
6679
  }
6660
6680
  }), api.modifyEnvironmentConfig((config)=>{
6661
6681
  var _config_moduleFederation, _config_performance_chunkSplit, _config_performance;
@@ -6707,6 +6727,7 @@ async function createRsbuild(options = {}) {
6707
6727
  }
6708
6728
  let resolvedOptions = {
6709
6729
  cwd: process.cwd(),
6730
+ callerName: 'rsbuild',
6710
6731
  ...options,
6711
6732
  rsbuildConfig: config
6712
6733
  }, pluginManager = (plugins = [], {
@@ -6768,6 +6789,7 @@ async function createRsbuild(options = {}) {
6768
6789
  'distPath',
6769
6790
  'devServer',
6770
6791
  'cachePath',
6792
+ 'callerName',
6771
6793
  'bundlerType'
6772
6794
  ];
6773
6795
  return new Proxy(context, {
@@ -7362,11 +7384,11 @@ async function runCLI() {
7362
7384
  }
7363
7385
  process.title = 'rsbuild-node';
7364
7386
  let { npm_execpath } = process.env;
7365
- (!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.17\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`);
7366
7388
  try {
7367
7389
  !function() {
7368
7390
  let cli = cac_dist('rsbuild');
7369
- cli.help(), cli.version("1.3.17"), applyCommonOptions(cli);
7391
+ cli.help(), cli.version("1.3.19"), applyCommonOptions(cli);
7370
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');
7371
7393
  applyServerOptions(devCommand), applyServerOptions(previewCommand), devCommand.action(async (options)=>{
7372
7394
  try {
@@ -7417,6 +7439,6 @@ async function runCLI() {
7417
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);
7418
7440
  }
7419
7441
  }
7420
- let src_version = "1.3.17";
7442
+ let src_version = "1.3.19";
7421
7443
  var __webpack_exports__logger = __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger, __webpack_exports__rspack = __WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__.rspack;
7422
- export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defineConfig, ensureAssetPrefix, config_loadConfig as loadConfig, loadEnv, mergeRsbuildConfig, runCLI, src_version as version, __webpack_exports__logger as logger, __webpack_exports__rspack as rspack };
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 };
@@ -4,8 +4,18 @@ import type { InspectConfigOptions, InspectConfigResult, NormalizedConfig, Plugi
4
4
  * - localhost
5
5
  * - 127.0.0.1
6
6
  * - [::1]
7
+ *
8
+ * Can be used in `server.cors.origin` config.
9
+ * @example
10
+ * ```ts
11
+ * server: {
12
+ * cors: {
13
+ * origin: [defaultAllowedOrigins, 'https://example.com'],
14
+ * },
15
+ * }
16
+ * ```
7
17
  */
8
- export declare const LOCAL_ORIGINS_REGEX: RegExp;
18
+ export declare const defaultAllowedOrigins: RegExp;
9
19
  export declare function getDefaultEntry(root: string): RsbuildEntry;
10
20
  export declare const withDefaultConfig: (rootPath: string, config: RsbuildConfig) => Promise<RsbuildConfig>;
11
21
  /**
@@ -14,6 +14,7 @@ export type { Rspack };
14
14
  export { logger } from './logger';
15
15
  export { mergeRsbuildConfig } from './mergeConfig';
16
16
  export { ensureAssetPrefix } from './helpers';
17
+ export { defaultAllowedOrigins } from './config';
17
18
  export { PLUGIN_SWC_NAME, PLUGIN_CSS_NAME } from './constants';
18
19
  export type { AppIcon, AppIconItem, AliasStrategy, Build, BuildOptions, BundlerPluginInstance, Charset, ClientConfig, CliShortcut, CleanDistPath, CleanDistPathObject, ConfigChain, ConfigChainWithContext, ConsoleType, CreateCompiler, CreateRsbuildOptions, CrossOrigin, CSSLoaderOptions, CSSModules, CSSModulesLocalsConvention, DataUriLimit, Decorators, DevConfig, DistPathConfig, EnvironmentContext, EnvironmentConfig, FilenameConfig, HistoryApiFallbackContext, HistoryApiFallbackOptions, HtmlConfig, HtmlRspackPlugin, HtmlBasicTag, HtmlFallback, HtmlTagHandler, HtmlTagDescriptor, HtmlTagContext, InspectConfigOptions, InspectConfigResult, InlineChunkConfig, InlineChunkTest, InlineChunkTestFunction, InternalContext, LegalComments, ManifestData, ManifestConfig, ManifestObjectConfig, MetaAttrs, MetaOptions, Minify, ModifyBundlerChainFn, ModifyBundlerChainUtils, ModifyChainUtils, ModifyEnvironmentConfigFn, ModifyEnvironmentConfigUtils, ModifyHTMLContext, ModifyHTMLFn, ModifyHTMLTagsContext, ModifyHTMLTagsFn, ModifyRsbuildConfigUtils, ModifyRspackConfigFn, ModifyRspackConfigUtils, ModifyRsbuildConfigFn, ModifyWebpackChainFn, ModifyWebpackChainUtils, ModifyWebpackConfigFn, ModifyWebpackConfigUtils, ModuleFederationConfig, MergedEnvironmentConfig, NormalizedConfig, NormalizedDevConfig, NormalizedEnvironmentConfig, NormalizedHtmlConfig, NormalizedModuleFederationConfig, NormalizedOutputConfig, NormalizedPerformanceConfig, NormalizedSecurityConfig, NormalizedServerConfig, NormalizedSourceConfig, NormalizedToolsConfig, OnAfterEnvironmentCompileFn, OnBeforeEnvironmentCompileFn, OnCloseBuildFn, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterStartDevServerFn, OnAfterStartProdServerFn, OnBeforeBuildFn, OnBeforeCreateCompilerFn, OnBeforeStartDevServerFn, OnBeforeStartProdServerFn, OnCloseDevServerFn, OnDevCompileDoneFn, OnExitFn, OutputConfig, OutputStructure, PerformanceConfig, PluginManager, Polyfill, PostCSSLoaderOptions, PostCSSOptions, PostCSSPlugin, PreviewOptions, PreconnectOption, ProcessAssetsDescriptor, ProcessAssetsHook, ProcessAssetsHandler, ProxyBypass, ProxyConfig, ProxyFilter, ProxyOptions, PrintUrls, PublicDir, PublicDirOptions, ProgressBarConfig, RequestHandler, ResolveHook, ResolveHandler, ResolvedCreateRsbuildOptions, RsbuildConfig, RsbuildContext, RsbuildEntry, RsbuildEntryDescription, RsbuildInstance, RsbuildMode, RsbuildPlugin, RsbuildPluginAPI, RsbuildPlugins, RsbuildProvider, RsbuildProviderHelpers, RsbuildTarget, RspackChain, RspackRule, ResourceHintsIncludeType, StartDevServerOptions, SriOptions, SriAlgorithm, ScriptInject, ScriptLoading, SecurityConfig, SourceMap, SetupMiddlewaresFn, SetupMiddlewaresServer, ServerConfig, SourceConfig, SplitChunks, StyleLoaderOptions, TransformContext, TransformDescriptor, ToolsConfig, TransformHook, TransformHandler, TransformImport, WatchFiles, } from './types';
19
20
  export type { ChainIdentifier } from './configChain';
@@ -8,16 +8,22 @@ 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;
14
18
  };
15
- export type HtmlInfo = {
19
+ export type HtmlExtraData = {
20
+ entryName: string;
21
+ context: InternalContext;
22
+ environment: EnvironmentContext;
16
23
  favicon?: string;
17
24
  tagConfig?: TagConfig;
18
25
  templateContent?: string;
19
26
  };
20
- export type RsbuildHtmlPluginOptions = Record<string, HtmlInfo>;
21
27
  export type AlterAssetTagGroupsData = {
22
28
  headTags: HtmlTagObject[];
23
29
  bodyTags: HtmlTagObject[];
@@ -28,10 +34,8 @@ export type AlterAssetTagGroupsData = {
28
34
  export declare const hasTitle: (html?: string) => boolean;
29
35
  export declare class RsbuildHtmlPlugin {
30
36
  readonly name: string;
31
- readonly getEnvironment: () => EnvironmentContext;
32
- readonly options: RsbuildHtmlPluginOptions;
33
- readonly getContext: () => InternalContext;
34
- constructor(options: RsbuildHtmlPluginOptions, getEnvironment: () => EnvironmentContext, getContext: () => InternalContext);
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;
@@ -30,6 +30,14 @@ export type RsbuildContext = {
30
30
  * The bundler type, can be `rspack` or `webpack`.
31
31
  */
32
32
  bundlerType: BundlerType;
33
+ /**
34
+ * The name of the framework or tool that is currently invoking Rsbuild,
35
+ * same as the `callerName` option in the `createRsbuild` method.
36
+ * @example
37
+ * - `rslib` is set when Rslib calls Rsbuild.
38
+ * - `rspress` is set when Rspress calls Rsbuild.
39
+ */
40
+ callerName: string;
33
41
  };
34
42
  /** The inner context. */
35
43
  export type InternalContext = RsbuildContext & {
@@ -104,6 +104,13 @@ export type CreateRsbuildOptions = {
104
104
  * @default process.cwd()
105
105
  */
106
106
  cwd?: string;
107
+ /**
108
+ * The name of the framework or tool that is currently invoking Rsbuild.
109
+ * This allows plugins to tailor their behavior based on the calling context.
110
+ * Rsbuild plugins can access this value via `api.context.callerName`.
111
+ * @default 'rsbuild'
112
+ */
113
+ callerName?: string;
107
114
  /**
108
115
  * Only build specified environments.
109
116
  * For example, passing `['web']` will only build the `web` environment.
@@ -122,7 +129,7 @@ export type CreateRsbuildOptions = {
122
129
  */
123
130
  loadEnv?: boolean | LoadEnvOptions;
124
131
  };
125
- export type ResolvedCreateRsbuildOptions = Required<Pick<CreateRsbuildOptions, 'cwd'>> & Pick<CreateRsbuildOptions, 'loadEnv' | 'environment'> & {
132
+ export type ResolvedCreateRsbuildOptions = Required<Pick<CreateRsbuildOptions, 'cwd' | 'callerName'>> & Pick<CreateRsbuildOptions, 'loadEnv' | 'environment'> & {
126
133
  rsbuildConfig: RsbuildConfig;
127
134
  };
128
135
  export type CreateDevServer = (options?: CreateDevServerOptions) => Promise<RsbuildDevServer>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "1.3.17",
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",