@rsbuild/core 1.4.13 → 1.4.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2064,18 +2064,7 @@ let rspackMinVersion = '1.2.4', setNodeEnv = (env)=>{
2064
2064
  arr
2065
2065
  ], cloneDeep = (value)=>null == value ? value : cjs_default()({}, value, {
2066
2066
  isMergeableObject: isPlainObject
2067
- }), isSatisfyRspackVersion = async (originalVersion)=>{
2068
- let version = originalVersion;
2069
- return version.includes('-canary') && (version = version.split('-canary')[0]), !(version && /^[\d.]+$/.test(version)) || ((version1, version2)=>{
2070
- let parts1 = version1.split('.').map(Number), parts2 = version2.split('.').map(Number), len = Math.max(parts1.length, parts2.length);
2071
- for(let i = 0; i < len; i++){
2072
- let item1 = parts1[i] ?? 0, item2 = parts2[i] ?? 0;
2073
- if (item1 > item2) return 1;
2074
- if (item1 < item2) return -1;
2075
- }
2076
- return 0;
2077
- })(version, rspackMinVersion) >= 0;
2078
- }, removeLeadingSlash = (s)=>s.replace(/^\/+/, ''), addTrailingSlash = (s)=>s.endsWith('/') ? s : `${s}/`, formatPublicPath = (publicPath, withSlash = !0)=>'auto' === publicPath ? publicPath : withSlash ? addTrailingSlash(publicPath) : publicPath.replace(/\/+$/, ''), getPublicPathFromChain = (chain, withSlash = !0)=>{
2067
+ }), removeLeadingSlash = (s)=>s.replace(/^\/+/, ''), addTrailingSlash = (s)=>s.endsWith('/') ? s : `${s}/`, formatPublicPath = (publicPath, withSlash = !0)=>'auto' === publicPath ? publicPath : withSlash ? addTrailingSlash(publicPath) : publicPath.replace(/\/+$/, ''), getPublicPathFromChain = (chain, withSlash = !0)=>{
2079
2068
  let publicPath = chain.output.get('publicPath');
2080
2069
  return 'string' == typeof publicPath ? formatPublicPath(publicPath, withSlash) : formatPublicPath(DEFAULT_ASSET_PREFIX, withSlash);
2081
2070
  }, getPublicPathFromCompiler = (compiler)=>{
@@ -2482,7 +2471,7 @@ function createEnvironmentAsyncHook() {
2482
2471
  handler
2483
2472
  });
2484
2473
  },
2485
- callChain: async ({ environment, args: params })=>{
2474
+ callChain: async ({ environment, args: params, afterEach })=>{
2486
2475
  for (let callback of [
2487
2476
  ...preGroup,
2488
2477
  ...defaultGroup,
@@ -2490,7 +2479,7 @@ function createEnvironmentAsyncHook() {
2490
2479
  ]){
2491
2480
  if (environment && callback.environment && callback.environment !== environment) continue;
2492
2481
  let result = await callback.handler(...params);
2493
- void 0 !== result && (params[0] = result);
2482
+ void 0 !== result && (params[0] = result), afterEach && afterEach(params);
2494
2483
  }
2495
2484
  return params;
2496
2485
  },
@@ -3045,54 +3034,7 @@ let mapProcessAssetsStage = (compiler, stage)=>{
3045
3034
  default:
3046
3035
  throw Error(`${picocolors.dim('[rsbuild]')} Invalid process assets stage: ${stage}`);
3047
3036
  }
3048
- }, browsersListCache = new Map();
3049
- async function getBrowserslist(path) {
3050
- let env = process.env.NODE_ENV, cacheKey = path + env;
3051
- if (browsersListCache.has(cacheKey)) return browsersListCache.get(cacheKey);
3052
- let result = function(opts) {
3053
- if (opts.config) return pickEnv(parsePackageOrReadConfig(opts.config), opts);
3054
- if (opts.path) {
3055
- let config = function(from) {
3056
- let resolved, fromDir = isFile(from = node_path.resolve(from)) ? node_path.dirname(from) : from;
3057
- if (fromDir in configCache) return configCache[fromDir];
3058
- let configFile = eachParent(from, (dir)=>{
3059
- let pkgBrowserslist, config = node_path.join(dir, 'browserslist'), pkg = node_path.join(dir, 'package.json'), rc = node_path.join(dir, '.browserslistrc');
3060
- if (isFile(pkg)) try {
3061
- pkgBrowserslist = parsePackage(pkg);
3062
- } catch (e) {
3063
- if (e instanceof BrowserslistError) throw e;
3064
- console.warn(`[Browserslist] Could not parse ${pkg}. Ignoring it.`);
3065
- }
3066
- if (isFile(config) && pkgBrowserslist) throw new BrowserslistError(`${dir} contains both browserslist and package.json with browsers`);
3067
- if (isFile(rc) && pkgBrowserslist) throw new BrowserslistError(`${dir} contains both .browserslistrc and package.json with browsers`);
3068
- if (isFile(config) && isFile(rc)) throw new BrowserslistError(`${dir} contains both .browserslistrc and browserslist`);
3069
- return isFile(config) ? config : isFile(rc) ? rc : pkgBrowserslist ? pkg : void 0;
3070
- });
3071
- configFile && (resolved = parsePackageOrReadConfig(configFile));
3072
- let configDir = configFile && node_path.dirname(configFile);
3073
- return eachParent(from, (dir)=>{
3074
- if (resolved && (configCache[dir] = resolved), dir === configDir) return null;
3075
- }), resolved;
3076
- }(opts.path);
3077
- if (!config) return;
3078
- return pickEnv(config, opts);
3079
- }
3080
- }({
3081
- path,
3082
- env
3083
- });
3084
- return result ? (browsersListCache.set(cacheKey, result), result) : null;
3085
- }
3086
- async function getBrowserslistByEnvironment(path, config) {
3087
- let { target, overrideBrowserslist } = config.output;
3088
- if (Array.isArray(overrideBrowserslist)) return overrideBrowserslist;
3089
- if ('web' === target || 'web-worker' === target) {
3090
- let browserslistrc = await getBrowserslist(path);
3091
- if (browserslistrc) return browserslistrc;
3092
- }
3093
- return DEFAULT_BROWSERSLIST[target];
3094
- }
3095
- let getEnvironmentHTMLPaths = (entry, config)=>'web' !== config.output.target || !1 === config.tools.htmlPlugin ? {} : Object.keys(entry).reduce((prev, key)=>{
3037
+ }, browsersListCache = new Map(), getEnvironmentHTMLPaths = (entry, config)=>'web' !== config.output.target || !1 === config.tools.htmlPlugin ? {} : Object.keys(entry).reduce((prev, key)=>{
3096
3038
  let entryValue = entry[key];
3097
3039
  return ('string' == typeof entryValue || Array.isArray(entryValue) || !1 !== entryValue.html) && (prev[key] = function(entryName, config) {
3098
3040
  let filename;
@@ -3103,7 +3045,51 @@ let getEnvironmentHTMLPaths = (entry, config)=>'web' !== config.output.target ||
3103
3045
  }, {});
3104
3046
  async function updateEnvironmentContext(context, configs) {
3105
3047
  for (let [index, [name, config]] of (context.environments ||= {}, Object.entries(configs).entries())){
3106
- let browserslist = await getBrowserslistByEnvironment(context.rootPath, config), { entry = {}, tsconfigPath } = config.source, htmlPaths = getEnvironmentHTMLPaths(entry, config), webSocketToken = 'dev' === context.action ? await helpers_hash(context.rootPath + name) : '', environmentContext = {
3048
+ let browserslist = function(path, config) {
3049
+ let { target, overrideBrowserslist } = config.output;
3050
+ if (Array.isArray(overrideBrowserslist)) return overrideBrowserslist;
3051
+ if ('web' === target || 'web-worker' === target) {
3052
+ let browserslistrc = function(path) {
3053
+ let env = process.env.NODE_ENV, cacheKey = path + env;
3054
+ if (browsersListCache.has(cacheKey)) return browsersListCache.get(cacheKey);
3055
+ let result = function(opts) {
3056
+ if (opts.config) return pickEnv(parsePackageOrReadConfig(opts.config), opts);
3057
+ if (opts.path) {
3058
+ let config = function(from) {
3059
+ let resolved, fromDir = isFile(from = node_path.resolve(from)) ? node_path.dirname(from) : from;
3060
+ if (fromDir in configCache) return configCache[fromDir];
3061
+ let configFile = eachParent(from, (dir)=>{
3062
+ let pkgBrowserslist, config = node_path.join(dir, 'browserslist'), pkg = node_path.join(dir, 'package.json'), rc = node_path.join(dir, '.browserslistrc');
3063
+ if (isFile(pkg)) try {
3064
+ pkgBrowserslist = parsePackage(pkg);
3065
+ } catch (e) {
3066
+ if (e instanceof BrowserslistError) throw e;
3067
+ console.warn(`[Browserslist] Could not parse ${pkg}. Ignoring it.`);
3068
+ }
3069
+ if (isFile(config) && pkgBrowserslist) throw new BrowserslistError(`${dir} contains both browserslist and package.json with browsers`);
3070
+ if (isFile(rc) && pkgBrowserslist) throw new BrowserslistError(`${dir} contains both .browserslistrc and package.json with browsers`);
3071
+ if (isFile(config) && isFile(rc)) throw new BrowserslistError(`${dir} contains both .browserslistrc and browserslist`);
3072
+ return isFile(config) ? config : isFile(rc) ? rc : pkgBrowserslist ? pkg : void 0;
3073
+ });
3074
+ configFile && (resolved = parsePackageOrReadConfig(configFile));
3075
+ let configDir = configFile && node_path.dirname(configFile);
3076
+ return eachParent(from, (dir)=>{
3077
+ if (resolved && (configCache[dir] = resolved), dir === configDir) return null;
3078
+ }), resolved;
3079
+ }(opts.path);
3080
+ if (!config) return;
3081
+ return pickEnv(config, opts);
3082
+ }
3083
+ }({
3084
+ path,
3085
+ env
3086
+ });
3087
+ return result ? (browsersListCache.set(cacheKey, result), result) : null;
3088
+ }(path);
3089
+ if (browserslistrc) return browserslistrc;
3090
+ }
3091
+ return DEFAULT_BROWSERSLIST[target];
3092
+ }(context.rootPath, config), { entry = {}, tsconfigPath } = config.source, htmlPaths = getEnvironmentHTMLPaths(entry, config), webSocketToken = 'dev' === context.action ? await helpers_hash(context.rootPath + name) : '', environmentContext = {
3107
3093
  index,
3108
3094
  name,
3109
3095
  distPath: function(cwd, config) {
@@ -3126,7 +3112,7 @@ async function updateEnvironmentContext(context, configs) {
3126
3112
  async function createContext(options, userConfig) {
3127
3113
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
3128
3114
  return {
3129
- version: "1.4.13",
3115
+ version: "1.4.15",
3130
3116
  rootPath,
3131
3117
  distPath: '',
3132
3118
  cachePath,
@@ -3403,16 +3389,16 @@ let configChain_CHAIN_ID = {
3403
3389
  async function modifyRspackConfig(context, rspackConfig, chainUtils) {
3404
3390
  var _utils_environment_config_tools;
3405
3391
  logger.debug('modify Rspack config');
3406
- let currentConfig = rspackConfig, proxiedConfig = new Proxy({}, {
3407
- get: (_, prop)=>currentConfig[prop],
3408
- set: (_, prop, value)=>(currentConfig[prop] = value, !0)
3409
- }), utils = await getConfigUtils(proxiedConfig, chainUtils);
3392
+ let currentConfig = rspackConfig, utils = getConfigUtils(()=>currentConfig, chainUtils);
3410
3393
  if ([currentConfig] = await context.hooks.modifyRspackConfig.callChain({
3411
3394
  environment: utils.environment.name,
3412
3395
  args: [
3413
3396
  rspackConfig,
3414
3397
  utils
3415
- ]
3398
+ ],
3399
+ afterEach: ([config])=>{
3400
+ currentConfig = config;
3401
+ }
3416
3402
  }), null == (_utils_environment_config_tools = utils.environment.config.tools) ? void 0 : _utils_environment_config_tools.rspack) {
3417
3403
  let toolsRspackConfig = utils.environment.config.tools.rspack;
3418
3404
  currentConfig = await reduceConfigsAsyncWithContext({
@@ -3424,27 +3410,28 @@ async function modifyRspackConfig(context, rspackConfig, chainUtils) {
3424
3410
  }
3425
3411
  return logger.debug('modify Rspack config done'), currentConfig;
3426
3412
  }
3427
- async function getConfigUtils(config, chainUtils) {
3413
+ function getConfigUtils(getCurrentConfig, chainUtils) {
3428
3414
  return {
3429
3415
  ...chainUtils,
3430
3416
  mergeConfig: webpack_merge_dist.merge,
3431
3417
  addRules (rules) {
3432
- let ruleArr = helpers_castArray(rules);
3418
+ let config = getCurrentConfig(), ruleArr = helpers_castArray(rules);
3433
3419
  config.module || (config.module = {}), config.module.rules || (config.module.rules = []), config.module.rules.unshift(...ruleArr);
3434
3420
  },
3435
3421
  appendRules (rules) {
3436
- let ruleArr = helpers_castArray(rules);
3422
+ let config = getCurrentConfig(), ruleArr = helpers_castArray(rules);
3437
3423
  config.module || (config.module = {}), config.module.rules || (config.module.rules = []), config.module.rules.push(...ruleArr);
3438
3424
  },
3439
3425
  prependPlugins (plugins) {
3440
- let pluginArr = helpers_castArray(plugins);
3426
+ let config = getCurrentConfig(), pluginArr = helpers_castArray(plugins);
3441
3427
  config.plugins || (config.plugins = []), config.plugins.unshift(...pluginArr);
3442
3428
  },
3443
3429
  appendPlugins (plugins) {
3444
- let pluginArr = helpers_castArray(plugins);
3430
+ let config = getCurrentConfig(), pluginArr = helpers_castArray(plugins);
3445
3431
  config.plugins || (config.plugins = []), config.plugins.push(...pluginArr);
3446
3432
  },
3447
3433
  removePlugin (pluginName) {
3434
+ let config = getCurrentConfig();
3448
3435
  config.plugins && (config.plugins = config.plugins.filter((plugin)=>!plugin || (plugin.name || plugin.constructor.name) !== pluginName));
3449
3436
  }
3450
3437
  };
@@ -3486,6 +3473,7 @@ async function generateRspackConfig({ target, context, environment }) {
3486
3473
  }
3487
3474
  let allowedEnvironmentDevKeys = [
3488
3475
  'hmr',
3476
+ 'client',
3489
3477
  'liveReload',
3490
3478
  'writeToDisk',
3491
3479
  'assetPrefix',
@@ -3514,6 +3502,10 @@ async function modifyEnvironmentConfig(context, config, name) {
3514
3502
  });
3515
3503
  return logger.debug(`modify Rsbuild environment(${name}) config done`), modified;
3516
3504
  }
3505
+ let createEnvironmentNotFoundError = (environments = [])=>{
3506
+ let envList = picocolors.yellow(environments.join(','));
3507
+ return Error(`${picocolors.dim('[rsbuild:config]')} The current build is specified to run only in the ${envList} environment, but the configuration of the specified environment was not found.`);
3508
+ };
3517
3509
  async function initRsbuildConfig({ context, pluginManager }) {
3518
3510
  if (context.normalizedConfig) return context.normalizedConfig;
3519
3511
  await initPlugins({
@@ -3533,7 +3525,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
3533
3525
  watchFiles
3534
3526
  ]), mergedConfig;
3535
3527
  })(context.config), environments = {}, mergedEnvironments = ((normalizedConfig, rootPath, specifiedEnvironments)=>{
3536
- let defaultEntry, { environments, dev, server: _server, provider: _provider, ...rsbuildSharedConfig } = normalizedConfig, isEnvironmentEnabled = (name)=>!specifiedEnvironments || specifiedEnvironments.includes(name), applyEnvironmentDefaultConfig = (config)=>{
3528
+ let defaultEntry, { environments, dev, server: _server, provider: _provider, ...baseConfig } = normalizedConfig, isEnvironmentEnabled = (name)=>!specifiedEnvironments || specifiedEnvironments.includes(name), applyEnvironmentDefaultConfig = (config)=>{
3537
3529
  config.source.entry && 0 !== Object.keys(config.source.entry).length || (config.source.entry = (defaultEntry || (defaultEntry = function(root) {
3538
3530
  let entryFile = findExists([
3539
3531
  'ts',
@@ -3552,24 +3544,24 @@ async function initRsbuildConfig({ context, pluginManager }) {
3552
3544
  let isServer = 'node' === config.output.target;
3553
3545
  return void 0 === config.output.distPath.js && (config.output.distPath.js = isServer ? '' : 'static/js'), config;
3554
3546
  };
3555
- if (environments && Object.keys(environments).length) {
3547
+ if (environments && Object.keys(environments).length > 0) {
3556
3548
  let resolvedEnvironments = Object.fromEntries(Object.entries(environments).filter(([name])=>isEnvironmentEnabled(name)).map(([name, config])=>[
3557
3549
  name,
3558
3550
  applyEnvironmentDefaultConfig({
3559
3551
  ...mergeRsbuildConfig({
3560
- ...rsbuildSharedConfig,
3552
+ ...baseConfig,
3561
3553
  dev: pick(dev, allowedEnvironmentDevKeys)
3562
3554
  }, config)
3563
3555
  })
3564
3556
  ]));
3565
- if (!Object.keys(resolvedEnvironments).length) throw Error(`${picocolors.dim('[rsbuild:config]')} The current build is specified to run only in the ${picocolors.yellow(null == specifiedEnvironments ? void 0 : specifiedEnvironments.join(','))} environment, but the configuration of the specified environment was not found.`);
3557
+ if (0 === Object.keys(resolvedEnvironments).length) throw createEnvironmentNotFoundError(specifiedEnvironments);
3566
3558
  return resolvedEnvironments;
3567
3559
  }
3568
- let defaultEnvironmentName = rsbuildSharedConfig.output.target.replace(/[-_](\w)/g, (_, c)=>c.toUpperCase());
3569
- if (!isEnvironmentEnabled(defaultEnvironmentName)) throw Error(`${picocolors.dim('[rsbuild:config]')} The current build is specified to run only in the ${picocolors.yellow(null == specifiedEnvironments ? void 0 : specifiedEnvironments.join(','))} environment, but the configuration of the specified environment was not found.`);
3560
+ let defaultEnvironmentName = baseConfig.output.target.replace(/[-_](\w)/g, (_, c)=>c.toUpperCase());
3561
+ if (!isEnvironmentEnabled(defaultEnvironmentName)) throw createEnvironmentNotFoundError(specifiedEnvironments);
3570
3562
  return {
3571
3563
  [defaultEnvironmentName]: applyEnvironmentDefaultConfig({
3572
- ...rsbuildSharedConfig,
3564
+ ...baseConfig,
3573
3565
  dev: pick(dev, allowedEnvironmentDevKeys)
3574
3566
  })
3575
3567
  };
@@ -3671,12 +3663,21 @@ function formatFileList(paths, rootPath) {
3671
3663
  return files.length > 1 ? `${fileInfo} and ${files.length - 1} more` : fileInfo;
3672
3664
  }
3673
3665
  async function createCompiler_createCompiler(options) {
3666
+ let version;
3674
3667
  logger.debug('create compiler');
3675
3668
  let { context } = options, { rspackConfigs } = await initConfigs(options);
3676
3669
  if (await context.hooks.onBeforeCreateCompiler.callBatch({
3677
3670
  bundlerConfigs: rspackConfigs,
3678
3671
  environments: context.environments
3679
- }), !await isSatisfyRspackVersion(rspack_rspack.rspackVersion)) throw Error(`${picocolors.dim('[rsbuild]')} The current Rspack version does not meet the requirements, the minimum supported version of Rspack is ${picocolors.green(rspackMinVersion)}`);
3672
+ }), (version = rspack_rspack.rspackVersion).includes('-canary') && (version = version.split('-canary')[0]), !(!(version && /^[\d.]+$/.test(version)) || ((version1, version2)=>{
3673
+ let parts1 = version1.split('.').map(Number), parts2 = version2.split('.').map(Number), len = Math.max(parts1.length, parts2.length);
3674
+ for(let i = 0; i < len; i++){
3675
+ let item1 = parts1[i] ?? 0, item2 = parts2[i] ?? 0;
3676
+ if (item1 > item2) return 1;
3677
+ if (item1 < item2) return -1;
3678
+ }
3679
+ return 0;
3680
+ })(version, rspackMinVersion) >= 0)) throw Error(`${picocolors.dim('[rsbuild]')} The current Rspack version does not meet the requirements, the minimum supported version of Rspack is ${picocolors.green(rspackMinVersion)}`);
3680
3681
  let isMultiCompiler = rspackConfigs.length > 1, compiler = isMultiCompiler ? rspack_rspack(rspackConfigs) : rspack_rspack(rspackConfigs[0]), isVersionLogged = !1, isCompiling = !1, logRspackVersion = ()=>{
3681
3682
  isVersionLogged || (logger.debug(`use Rspack v${rspack_rspack.rspackVersion}`), isVersionLogged = !0);
3682
3683
  };
@@ -5148,19 +5149,7 @@ let MODULE_PATH_REGEX = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\
5148
5149
  }
5149
5150
  };
5150
5151
  }
5151
- }, swc_require = createRequire(import.meta.url), builtinSwcLoaderName = 'builtin:swc-loader';
5152
- async function applyCoreJs(swcConfig, polyfillMode) {
5153
- let coreJsPath = swc_require.resolve('core-js/package.json'), version = ((corejsPkgPath)=>{
5154
- try {
5155
- let rawJson = node_fs.readFileSync(corejsPkgPath, 'utf-8'), { version } = JSON.parse(rawJson), [major, minor] = version.split('.');
5156
- return `${major}.${minor}`;
5157
- } catch {
5158
- return '3';
5159
- }
5160
- })(coreJsPath), coreJsDir = node_path.dirname(coreJsPath);
5161
- return swcConfig.env.coreJs = version, 'usage' === polyfillMode && (swcConfig.env.shippedProposals = !0), coreJsDir;
5162
- }
5163
- let isCliShortcutsEnabled = (devConfig)=>devConfig.cliShortcuts && isTTY('stdin');
5152
+ }, swc_require = createRequire(import.meta.url), builtinSwcLoaderName = 'builtin:swc-loader', isCliShortcutsEnabled = (config)=>config.dev.cliShortcuts && isTTY('stdin');
5164
5153
  async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer, customShortcuts }) {
5165
5154
  let shortcuts = [
5166
5155
  {
@@ -5233,21 +5222,13 @@ async function resolveHostname(host = 'localhost') {
5233
5222
  '0000:0000:0000:0000:0000:0000:0000:0000'
5234
5223
  ]).has(host) ? 'localhost' : host;
5235
5224
  }
5236
- async function getResolvedClientConfig(clientConfig, serverConfig) {
5237
- let resolvedHost = await resolveHostname(serverConfig.host);
5238
- return {
5239
- ...clientConfig,
5240
- host: resolvedHost,
5241
- port: serverConfig.port
5242
- };
5243
- }
5244
- let compilationMiddleware_require = createRequire(import.meta.url), getCompilationMiddleware = async (compiler, options)=>{
5245
- let { default: rsbuildDevMiddleware } = await import("../compiled/rsbuild-dev-middleware/index.js"), { callbacks, devConfig, serverConfig } = options, resolvedClientConfig = await getResolvedClientConfig(devConfig.client, serverConfig);
5225
+ let compilationMiddleware_require = createRequire(import.meta.url), getCompilationMiddleware = async ({ config, compiler, callbacks, environments, resolvedPort })=>{
5226
+ let { default: rsbuildDevMiddleware } = await import("../compiled/rsbuild-dev-middleware/index.js"), resolvedHost = await resolveHostname(config.server.host);
5246
5227
  return applyToCompiler(compiler, (compiler, index)=>{
5247
- let environment = Object.values(options.environments).find((env)=>env.index === index);
5228
+ let environment = Object.values(environments).find((env)=>env.index === index);
5248
5229
  if (!environment) return;
5249
5230
  let token = environment.webSocketToken;
5250
- token && (!function({ config, compiler, devConfig, resolvedClientConfig, token }) {
5231
+ token && (!function({ config, compiler, token, resolvedHost, resolvedPort }) {
5251
5232
  if (!((compiler)=>{
5252
5233
  let { target } = compiler.options;
5253
5234
  return !!target && (Array.isArray(target) ? target.includes('web') : 'web' === target);
@@ -5257,20 +5238,25 @@ let compilationMiddleware_require = createRequire(import.meta.url), getCompilati
5257
5238
  let clientPaths = [];
5258
5239
  return (devConfig.hmr || devConfig.liveReload) && (hmrClientPath || (hmrClientPath = compilationMiddleware_require.resolve('@rsbuild/core/client/hmr')), clientPaths.push(hmrClientPath), (null == (_devConfig_client = devConfig.client) ? void 0 : _devConfig_client.overlay) && (overlayClientPath || (overlayClientPath = compilationMiddleware_require.resolve('@rsbuild/core/client/overlay')), clientPaths.push(overlayClientPath))), clientPaths;
5259
5240
  }(config.dev);
5260
- if (clientPaths.length) for (let clientPath of (new compiler.webpack.DefinePlugin({
5241
+ if (!clientPaths.length) return;
5242
+ let clientConfig = {
5243
+ ...config.dev.client
5244
+ };
5245
+ for (let clientPath of ('<port>' === clientConfig.port && (clientConfig.port = resolvedPort), new compiler.webpack.DefinePlugin({
5261
5246
  RSBUILD_WEB_SOCKET_TOKEN: JSON.stringify(token),
5262
- RSBUILD_CLIENT_CONFIG: JSON.stringify(devConfig.client),
5263
- RSBUILD_RESOLVED_CLIENT_CONFIG: JSON.stringify(resolvedClientConfig),
5264
- RSBUILD_DEV_LIVE_RELOAD: devConfig.liveReload
5247
+ RSBUILD_CLIENT_CONFIG: JSON.stringify(clientConfig),
5248
+ RSBUILD_SERVER_HOST: JSON.stringify(resolvedHost),
5249
+ RSBUILD_SERVER_PORT: JSON.stringify(resolvedPort),
5250
+ RSBUILD_DEV_LIVE_RELOAD: config.dev.liveReload
5265
5251
  }).apply(compiler), clientPaths))new compiler.webpack.EntryPlugin(compiler.context, clientPath, {
5266
5252
  name: void 0
5267
5253
  }).apply(compiler);
5268
5254
  }({
5269
- compiler,
5270
- devConfig,
5271
- resolvedClientConfig,
5272
5255
  token,
5273
- config: environment.config
5256
+ config: environment.config,
5257
+ compiler,
5258
+ resolvedHost,
5259
+ resolvedPort
5274
5260
  }), (({ compiler, token, callbacks: { onDone, onInvalid } })=>{
5275
5261
  if (((compiler)=>{
5276
5262
  let { target } = compiler.options;
@@ -5294,7 +5280,13 @@ let compilationMiddleware_require = createRequire(import.meta.url), getCompilati
5294
5280
  publicPath: '/',
5295
5281
  stats: !1,
5296
5282
  serverSideRender: !0,
5297
- writeToDisk: devConfig.writeToDisk
5283
+ writeToDisk: ((config, environments)=>{
5284
+ let writeToDiskValues = Object.values(environments).map((env)=>env.config.dev.writeToDisk);
5285
+ return 1 === new Set(writeToDiskValues).size ? writeToDiskValues[0] : (filePath, name)=>{
5286
+ let { writeToDisk } = config;
5287
+ return name && environments[name] && (writeToDisk = environments[name].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
5288
+ };
5289
+ })(config.dev, environments)
5298
5290
  });
5299
5291
  }, styles = {
5300
5292
  1: 'font-weight:bold',
@@ -5659,7 +5651,9 @@ class CompilationManager {
5659
5651
  });
5660
5652
  }
5661
5653
  async setupCompilationMiddleware() {
5662
- let { devConfig, serverConfig, publicPaths, environments } = this, middleware = await getCompilationMiddleware(this.compiler, {
5654
+ let { config, publicPaths, environments } = this, middleware = await getCompilationMiddleware({
5655
+ config,
5656
+ compiler: this.compiler,
5663
5657
  callbacks: {
5664
5658
  onInvalid: (token, fileName)=>{
5665
5659
  if ('string' == typeof fileName && fileName.endsWith('.html')) return void this.socketServer.sockWrite({
@@ -5670,10 +5664,9 @@ class CompilationManager {
5670
5664
  this.socketServer.updateStats(stats, token);
5671
5665
  }
5672
5666
  },
5673
- devConfig,
5674
- serverConfig,
5675
- environments
5676
- }), { base } = serverConfig, assetPrefixes = publicPaths.map(getPathnameFromUrl).map((prefix)=>base && '/' !== base ? stripBase(prefix, base) : prefix), wrapper = async (req, res, next)=>{
5667
+ environments,
5668
+ resolvedPort: this.resolvedPort
5669
+ }), { base } = config.server, assetPrefixes = publicPaths.map(getPathnameFromUrl).map((prefix)=>base && '/' !== base ? stripBase(prefix, base) : prefix), wrapper = (req, res, next)=>{
5677
5670
  let { url } = req, assetPrefix = url && assetPrefixes.find((prefix)=>url.startsWith(prefix));
5678
5671
  assetPrefix && '/' !== assetPrefix ? (req.url = url.slice(assetPrefix.length - 1), middleware(req, res, (...args)=>{
5679
5672
  req.url = url, next(...args);
@@ -5681,20 +5674,8 @@ class CompilationManager {
5681
5674
  };
5682
5675
  wrapper.close = middleware.close, wrapper.watch = middleware.watch, this.middleware = wrapper;
5683
5676
  }
5684
- constructor({ dev, server, compiler, publicPaths, environments }){
5685
- compilationManager_define_property(this, "middleware", void 0), compilationManager_define_property(this, "outputFileSystem", void 0), compilationManager_define_property(this, "devConfig", void 0), compilationManager_define_property(this, "serverConfig", void 0), compilationManager_define_property(this, "compiler", void 0), compilationManager_define_property(this, "environments", void 0), compilationManager_define_property(this, "publicPaths", void 0), compilationManager_define_property(this, "socketServer", void 0), compilationManager_define_property(this, "readFileSync", (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : node_fs.readFileSync(fileName, 'utf-8')), this.devConfig = ((config, environments)=>{
5686
- let writeToDiskValues = Object.values(environments).map((env)=>env.config.dev.writeToDisk);
5687
- return 1 === new Set(writeToDiskValues).size ? {
5688
- ...config,
5689
- writeToDisk: writeToDiskValues[0]
5690
- } : {
5691
- ...config,
5692
- writeToDisk (filePath, compilationName) {
5693
- let { writeToDisk } = config;
5694
- return compilationName && environments[compilationName] && (writeToDisk = environments[compilationName].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
5695
- }
5696
- };
5697
- })(dev, environments), this.serverConfig = server, this.compiler = compiler, this.environments = environments, this.publicPaths = publicPaths, this.outputFileSystem = node_fs, this.socketServer = new SocketServer(dev, environments);
5677
+ constructor({ config, compiler, publicPaths, resolvedPort, environments }){
5678
+ compilationManager_define_property(this, "middleware", void 0), compilationManager_define_property(this, "outputFileSystem", void 0), compilationManager_define_property(this, "config", void 0), compilationManager_define_property(this, "compiler", void 0), compilationManager_define_property(this, "environments", void 0), compilationManager_define_property(this, "publicPaths", void 0), compilationManager_define_property(this, "socketServer", void 0), compilationManager_define_property(this, "resolvedPort", void 0), compilationManager_define_property(this, "readFileSync", (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : node_fs.readFileSync(fileName, 'utf-8')), this.config = config, this.compiler = compiler, this.environments = environments, this.publicPaths = publicPaths, this.resolvedPort = resolvedPort, this.outputFileSystem = node_fs, this.socketServer = new SocketServer(config.dev, environments);
5698
5679
  }
5699
5680
  }
5700
5681
  let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i, gzipMiddleware = ({ filter, level = node_zlib.constants.Z_BEST_SPEED } = {})=>(req, res, next)=>{
@@ -5810,7 +5791,7 @@ let faviconFallbackMiddleware = (req, res, next)=>{
5810
5791
  if (!req.url || !req.headers || 'GET' !== req.method && 'HEAD' !== req.method) return !1;
5811
5792
  let { accept } = req.headers;
5812
5793
  return 'string' == typeof accept && (accept.includes('text/html') || accept.includes('*/*'));
5813
- }, postfixRE = /[?#].*$/, getUrlPathname = (url)=>url.replace(postfixRE, ''), getBaseMiddleware = ({ base })=>async (req, res, next)=>{
5794
+ }, postfixRE = /[?#].*$/, getUrlPathname = (url)=>url.replace(postfixRE, ''), getBaseMiddleware = ({ base })=>(req, res, next)=>{
5814
5795
  var _req_headers_accept;
5815
5796
  let url = req.url, pathname = getUrlPathname(url);
5816
5797
  if (pathname.startsWith(base)) {
@@ -5868,8 +5849,8 @@ let faviconFallbackMiddleware = (req, res, next)=>{
5868
5849
  for (let middleware of proxyMiddlewares)'function' == typeof middleware.upgrade && middleware.upgrade(req, socket, head);
5869
5850
  }
5870
5851
  };
5871
- }, applyDefaultMiddlewares = async ({ devServerAPI, middlewares, server, compilationManager, context, pwd, postCallbacks })=>{
5872
- let upgradeEvents = [];
5852
+ }, applyDefaultMiddlewares = async ({ config, compilationManager, context, devServerAPI, middlewares, pwd, postCallbacks })=>{
5853
+ let upgradeEvents = [], { server } = config;
5873
5854
  if (server.cors) {
5874
5855
  let { default: corsMiddleware } = await import("../compiled/cors/index.js");
5875
5856
  middlewares.push(corsMiddleware('boolean' == typeof server.cors ? {} : server.cors));
@@ -6010,8 +5991,8 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6010
5991
  }, getDevMiddlewares = async (options)=>{
6011
5992
  let middlewares = [], { compilationManager } = options;
6012
5993
  'verbose' === logger.level && middlewares.push(await getRequestLoggerMiddleware());
6013
- let { before, after } = ((dev, devServerAPI)=>{
6014
- let setupMiddlewares = dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
5994
+ let { before, after } = ((config, devServerAPI)=>{
5995
+ let setupMiddlewares = config.dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
6015
5996
  'sockWrite',
6016
5997
  'environments'
6017
5998
  ]), before = [], after = [];
@@ -6023,7 +6004,7 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6023
6004
  before,
6024
6005
  after
6025
6006
  };
6026
- })(options.dev, options.devServerAPI);
6007
+ })(options.config, options.devServerAPI);
6027
6008
  middlewares.push(...before);
6028
6009
  let { onUpgrade } = await applyDefaultMiddlewares({
6029
6010
  ...options,
@@ -6241,7 +6222,10 @@ class BasicRunnerFactory {
6241
6222
  }) : this[key] = value, this.name = name;
6242
6223
  }
6243
6224
  }
6244
- let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>new BasicRunnerFactory(bundlePath).create(runnerFactoryOptions).run(bundlePath), loadBundle = async (stats, entryName, utils)=>{
6225
+ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
6226
+ let runner = new BasicRunnerFactory(bundlePath).create(runnerFactoryOptions);
6227
+ return await runner.run(bundlePath);
6228
+ }, loadBundle = async (stats, entryName, utils)=>{
6245
6229
  let { chunks, entrypoints, outputPath } = stats.toJson({
6246
6230
  all: !1,
6247
6231
  chunks: !0,
@@ -6266,11 +6250,6 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>new BasicRunne
6266
6250
  readFileSync: utils.readFileSync,
6267
6251
  isBundleOutput: (modulePath)=>allChunkFiles.includes(modulePath)
6268
6252
  });
6269
- }, getTransformedHtml = async (entryName, utils)=>{
6270
- let { htmlPaths, distPath } = utils.environment, htmlPath = htmlPaths[entryName];
6271
- if (!htmlPath) throw Error(`${picocolors.dim('[rsbuild:getTransformedHtml]')} Failed to get HTML file by entryName: ${picocolors.yellow(entryName)}`);
6272
- let fileName = join(distPath, htmlPath);
6273
- return utils.readFileSync(fileName);
6274
6253
  }, createCacheableFunction = (getter)=>{
6275
6254
  let cache = new WeakMap();
6276
6255
  return async (stats, entryName, utils)=>{
@@ -6323,14 +6302,14 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>new BasicRunne
6323
6302
  return createServer(middlewares);
6324
6303
  };
6325
6304
  async function setupWatchFiles(options) {
6326
- let { dev, server, root, compilationManager } = options, { hmr, liveReload } = dev;
6305
+ let { config, root, compilationManager } = options, { hmr, liveReload } = config.dev;
6327
6306
  if (!hmr && !liveReload || !compilationManager) return;
6328
- let closeDevFilesWatcher = await watchDevFiles(dev, compilationManager, root), serverFilesWatcher = await function(serverConfig, compilationManager, root) {
6307
+ let closeDevFilesWatcher = await watchDevFiles(config.dev, compilationManager, root), serverFilesWatcher = await function(serverConfig, compilationManager, root) {
6329
6308
  let publicDirs = normalizePublicDirs(serverConfig.publicDir);
6330
6309
  if (!publicDirs.length) return;
6331
6310
  let watchPaths = publicDirs.filter((item)=>item.watch).map((item)=>item.name);
6332
6311
  if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), compilationManager, root);
6333
- }(server, compilationManager, root);
6312
+ }(config.server, compilationManager, root);
6334
6313
  return {
6335
6314
  async close () {
6336
6315
  await Promise.all([
@@ -6383,12 +6362,11 @@ async function startWatchFiles({ paths, options, type = 'reload-page' }, compila
6383
6362
  }), watcher;
6384
6363
  }
6385
6364
  async function devServer_createDevServer(options, createCompiler, config, { compiler: customCompiler, getPortSilently, runCompile = !0 } = {}) {
6386
- var config1;
6387
6365
  let lastStats, fileWatcher, devMiddlewares;
6388
6366
  logger.debug('create dev server');
6389
6367
  let { port, host, https, portTip } = await getServerConfig({
6390
6368
  config
6391
- }), { middlewareMode } = config.server, { context } = options, devConfig = (config1 = config.dev, '<port>' === config1.client.port && (config1.client.port = String(port)), config1), routes = getRoutes(context), root = context.rootPath;
6369
+ }), { middlewareMode } = config.server, { context } = options, routes = getRoutes(context), root = context.rootPath;
6392
6370
  context.devServer = {
6393
6371
  hostname: host,
6394
6372
  port,
@@ -6413,13 +6391,10 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
6413
6391
  let publicPaths = helpers_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
6414
6392
  getPublicPathFromCompiler(compiler)
6415
6393
  ], compilationManager = new CompilationManager({
6416
- dev: devConfig,
6417
- server: {
6418
- ...config.server,
6419
- port
6420
- },
6421
- publicPaths: publicPaths,
6394
+ config,
6422
6395
  compiler,
6396
+ publicPaths: publicPaths,
6397
+ resolvedPort: port,
6423
6398
  environments: context.environments
6424
6399
  });
6425
6400
  return await compilationManager.init(), compilationManager;
@@ -6427,7 +6402,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
6427
6402
  protocol,
6428
6403
  port,
6429
6404
  host
6430
- }), cliShortcutsEnabled = isCliShortcutsEnabled(devConfig), printUrls = ()=>printServerURLs({
6405
+ }), cliShortcutsEnabled = isCliShortcutsEnabled(config), printUrls = ()=>printServerURLs({
6431
6406
  urls,
6432
6407
  port,
6433
6408
  routes,
@@ -6449,7 +6424,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
6449
6424
  middlewareMode || registerCleanup(closeServer);
6450
6425
  let beforeCreateCompiler = async ()=>{
6451
6426
  if (printUrls(), cliShortcutsEnabled) {
6452
- let shortcutsOptions = 'boolean' == typeof devConfig.cliShortcuts ? {} : devConfig.cliShortcuts, cleanup = await setupCliShortcuts({
6427
+ let shortcutsOptions = 'boolean' == typeof config.dev.cliShortcuts ? {} : config.dev.cliShortcuts, cleanup = await setupCliShortcuts({
6453
6428
  openPage,
6454
6429
  closeServer,
6455
6430
  printUrls,
@@ -6462,7 +6437,12 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
6462
6437
  context.hooks.onCloseDevServer.tap(cleanup);
6463
6438
  }
6464
6439
  !getPortSilently && portTip && logger.info(portTip);
6465
- }, cacheableLoadBundle = createCacheableFunction(loadBundle), cacheableTransformedHtml = createCacheableFunction((_stats, entryName, utils)=>getTransformedHtml(entryName, utils)), environmentAPI = Object.fromEntries(Object.entries(context.environments).map(([name, environment])=>[
6440
+ }, cacheableLoadBundle = createCacheableFunction(loadBundle), cacheableTransformedHtml = createCacheableFunction((_stats, entryName, utils)=>((entryName, utils)=>{
6441
+ let { htmlPaths, distPath } = utils.environment, htmlPath = htmlPaths[entryName];
6442
+ if (!htmlPath) throw Error(`${picocolors.dim('[rsbuild:getTransformedHtml]')} Failed to get HTML file by entryName: ${picocolors.yellow(entryName)}`);
6443
+ let fileName = join(distPath, htmlPath);
6444
+ return utils.readFileSync(fileName);
6445
+ })(entryName, utils)), environmentAPI = Object.fromEntries(Object.entries(context.environments).map(([name, environment])=>[
6466
6446
  name,
6467
6447
  {
6468
6448
  getStats: async ()=>{
@@ -6536,22 +6516,20 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
6536
6516
  runCompile ? context.hooks.onBeforeCreateCompiler.tap(beforeCreateCompiler) : await beforeCreateCompiler();
6537
6517
  let compilationManager = runCompile ? await startCompile() : void 0;
6538
6518
  for (let item of (fileWatcher = await setupWatchFiles({
6539
- dev: devConfig,
6540
- server: config.server,
6519
+ config,
6541
6520
  compilationManager,
6542
6521
  root
6543
6522
  }), (devMiddlewares = await getDevMiddlewares({
6544
6523
  pwd: root,
6545
6524
  compilationManager,
6546
- dev: devConfig,
6525
+ config,
6547
6526
  devServerAPI,
6548
6527
  context,
6549
- server: config.server,
6550
6528
  postCallbacks
6551
6529
  })).middlewares))Array.isArray(item) ? middlewares.use(...item) : middlewares.use(item);
6552
6530
  return null == compilationManager || compilationManager.watch(), logger.debug('create dev server done'), devServerAPI;
6553
6531
  }
6554
- let rspackProvider = async ({ context, pluginManager, rsbuildOptions })=>{
6532
+ let rspackProvider = ({ context, pluginManager, rsbuildOptions })=>{
6555
6533
  let createCompiler = async ()=>(await createCompiler_createCompiler({
6556
6534
  context,
6557
6535
  pluginManager,
@@ -6587,7 +6565,12 @@ let rspackProvider = async ({ context, pluginManager, rsbuildOptions })=>{
6587
6565
  pluginManager,
6588
6566
  rsbuildOptions
6589
6567
  }, options),
6590
- async initConfigs () {
6568
+ async initConfigs (options) {
6569
+ if (context.action && (null == options ? void 0 : options.action) && context.action !== options.action) throw Error(`\
6570
+ [rsbuild] initConfigs() can only be called with the same action type.
6571
+ - Expected: ${context.action}
6572
+ - Actual: ${null == options ? void 0 : options.action}`);
6573
+ (null == options ? void 0 : options.action) && (context.action = options.action);
6591
6574
  let { rspackConfigs } = await initConfigs({
6592
6575
  context,
6593
6576
  pluginManager,
@@ -6700,7 +6683,7 @@ async function startProdServer(context, config, { getPortSilently } = {}) {
6700
6683
  protocol,
6701
6684
  port,
6702
6685
  host
6703
- }), cliShortcutsEnabled = isCliShortcutsEnabled(config.dev), cleanupGracefulShutdown = setupGracefulShutdown(), closeServer = async ()=>{
6686
+ }), cliShortcutsEnabled = isCliShortcutsEnabled(config), cleanupGracefulShutdown = setupGracefulShutdown(), closeServer = async ()=>{
6704
6687
  removeCleanup(closeServer), cleanupGracefulShutdown(), await Promise.all([
6705
6688
  server.close(),
6706
6689
  serverTerminator()
@@ -6741,153 +6724,443 @@ async function startProdServer(context, config, { getPortSilently } = {}) {
6741
6724
  });
6742
6725
  });
6743
6726
  }
6744
- async function applyDefaultPlugins(pluginManager, context) {
6745
- pluginManager.addPlugins([
6746
- {
6747
- name: 'rsbuild:basic',
6748
- setup (api) {
6749
- api.modifyBundlerChain((chain, { isDev, target, bundler, environment, CHAIN_ID })=>{
6750
- let { config } = environment;
6751
- chain.name(environment.name);
6752
- let devtool = ((config)=>{
6753
- let { sourceMap } = config.output, isProd = 'production' === config.mode;
6754
- return !1 !== sourceMap && (!0 === sourceMap ? isProd ? 'source-map' : 'cheap-module-source-map' : void 0 === sourceMap.js ? !isProd && 'cheap-module-source-map' : sourceMap.js);
6755
- })(config);
6756
- chain.devtool(devtool);
6757
- let { sourceMap } = config.output;
6758
- !devtool && 'object' == typeof sourceMap && sourceMap.css && chain.plugin('source-map-css').use(bundler.SourceMapDevToolPlugin, [
6759
- {
6760
- test: /\.css$/,
6761
- filename: '[file].map[query]'
6762
- }
6763
- ]), chain.context(api.context.rootPath), chain.mode(environment.config.mode), chain.infrastructureLogging({
6764
- level: 'error'
6765
- }), chain.watchOptions({
6766
- aggregateTimeout: 0
6767
- }), chain.performance.hints(!1), chain.module.parser.merge({
6768
- javascript: {
6769
- exportsPresence: 'error',
6770
- typeReexportsPresence: 'tolerant'
6771
- }
6772
- }), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(bundler.HotModuleReplacementPlugin), isDev && chain.output.devtoolModuleFilenameTemplate((info)=>toPosixPath(info.absoluteResourcePath)), 'rspack' === api.context.bundlerType && chain.experiments({
6773
- ...chain.get('experiments'),
6774
- typeReexportsPresence: !0,
6775
- rspackFuture: {
6776
- bundlerInfo: {
6777
- force: !1
6778
- }
6779
- }
6780
- }), process.env.RSPACK_CONFIG_VALIDATE ||= 'loose-silent';
6781
- });
6727
+ async function createRsbuild(options = {}) {
6728
+ let plugins, envs = options.loadEnv ? loadEnv({
6729
+ cwd: options.cwd,
6730
+ ...'boolean' == typeof options.loadEnv ? {} : options.loadEnv
6731
+ }) : null, config = isFunction(options.rsbuildConfig) ? await options.rsbuildConfig() : options.rsbuildConfig || {};
6732
+ config.logLevel && (logger.level = config.logLevel), function(config, envs) {
6733
+ var _config_performance;
6734
+ if (null !== envs && (config.source ||= {}, config.source.define = {
6735
+ ...envs.publicVars,
6736
+ ...config.source.define
6737
+ }, 0 !== envs.filePaths.length && (config.dev ||= {}, config.dev.watchFiles = [
6738
+ ...config.dev.watchFiles ? helpers_castArray(config.dev.watchFiles) : [],
6739
+ {
6740
+ paths: envs.filePaths,
6741
+ type: 'reload-server'
6782
6742
  }
6783
- },
6784
- {
6785
- name: 'rsbuild:entry',
6786
- setup (api) {
6787
- api.modifyBundlerChain(async (chain, { environment, isServer })=>{
6788
- let { config, entry } = environment, { preEntry } = config.source, injectCoreJsEntry = 'entry' === config.output.polyfill && !isServer;
6789
- for (let entryName of Object.keys(entry)){
6790
- let entryPoint = chain.entry(entryName), addEntry = (item)=>{
6791
- if ('object' == typeof item && 'html' in item) {
6792
- let { html: _html, ...rest } = item;
6793
- entryPoint.add(rest);
6794
- } else entryPoint.add(item);
6795
- };
6796
- preEntry.forEach(addEntry), injectCoreJsEntry && addEntry(createVirtualModule('import "core-js";')), helpers_castArray(entry[entryName]).forEach(addEntry);
6743
+ ], null == (_config_performance = config.performance) ? void 0 : _config_performance.buildCache))) {
6744
+ let { buildCache } = config.performance;
6745
+ !0 === buildCache ? config.performance.buildCache = {
6746
+ buildDependencies: envs.filePaths
6747
+ } : (buildCache.buildDependencies ||= [], buildCache.buildDependencies.push(...envs.filePaths));
6748
+ }
6749
+ }(config, envs);
6750
+ let resolvedOptions = {
6751
+ cwd: process.cwd(),
6752
+ callerName: 'rsbuild',
6753
+ ...options,
6754
+ rsbuildConfig: config
6755
+ }, pluginManager = (plugins = [], {
6756
+ getPlugins: (options = {})=>plugins.filter((plugin)=>isEnvironmentMatch(plugin.environment, options.environment)).map(({ instance })=>instance),
6757
+ getAllPluginsWithMeta: ()=>plugins,
6758
+ addPlugins: (newPlugins, options)=>{
6759
+ let { before, environment } = options || {};
6760
+ for (let newPlugin of newPlugins)if (newPlugin) {
6761
+ let type = typeof newPlugin;
6762
+ if ('object' !== type || null === newPlugin) throw Error(`${picocolors.dim('[rsbuild:plugin]')} Expect Rsbuild plugin instance to be an object, but got ${picocolors.yellow(type)}.`);
6763
+ if (!isFunction(newPlugin.setup)) {
6764
+ if (isFunction(newPlugin.apply)) {
6765
+ let { name = 'SomeWebpackPlugin' } = newPlugin.constructor || {};
6766
+ throw Error([
6767
+ `${picocolors.yellow(name)} looks like a webpack or Rspack plugin, please use ${picocolors.yellow('`tools.rspack`')} to register it:`,
6768
+ picocolors.green(`
6769
+ // rsbuild.config.ts
6770
+ export default {
6771
+ tools: {
6772
+ rspack: {
6773
+ plugins: [new ${name}()]
6774
+ }
6775
+ }
6776
+ };
6777
+ `)
6778
+ ].join('\n'));
6797
6779
  }
6798
- }), api.onBeforeCreateCompiler(({ bundlerConfigs })=>{
6799
- if (bundlerConfigs.every((config)=>!config.entry)) throw Error(`${picocolors.dim('[rsbuild:config]')} Could not find any entry module, please make sure that ${picocolors.yellow('src/index.(ts|js|tsx|jsx|mts|cts|mjs|cjs)')} exists, or customize entry through the ${picocolors.yellow('source.entry')} configuration.`);
6800
- });
6801
- }
6802
- },
6803
- {
6804
- name: 'rsbuild:cache',
6805
- setup (api) {
6806
- let cacheEnabled = !1;
6807
- api.modifyBundlerChain(async (chain, { environment, env })=>{
6808
- let { config } = environment, { bundlerType } = api.context, buildCache = config.performance.buildCache ?? 'webpack' === bundlerType;
6809
- if (!1 === buildCache) return;
6810
- cacheEnabled = !0;
6811
- let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = function({ cacheDirectory }, context) {
6812
- return cacheDirectory ? external_node_path_isAbsolute(cacheDirectory) ? cacheDirectory : join(context.rootPath, cacheDirectory) : join(context.cachePath, context.bundlerType);
6813
- }(cacheConfig, context), buildDependencies = await getBuildDependencies(context, config, environment, cacheConfig.buildDependencies ? {
6814
- userBuildDependencies: cacheConfig.buildDependencies
6815
- } : {});
6816
- 'webpack' === bundlerType && await validateWebpackCache(cacheDirectory, buildDependencies);
6817
- let cacheVersion = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length ? `${environment.name}-${env}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : `${environment.name}-${env}`;
6818
- 'rspack' === bundlerType ? (chain.cache(!0), chain.experiments({
6819
- ...chain.get('experiments'),
6820
- cache: {
6821
- type: 'persistent',
6822
- version: cacheVersion,
6823
- storage: {
6824
- type: 'filesystem',
6825
- directory: cacheDirectory
6826
- },
6827
- buildDependencies: Object.values(buildDependencies).flat()
6828
- }
6829
- })) : chain.cache({
6830
- name: cacheVersion,
6831
- type: 'filesystem',
6832
- cacheDirectory,
6833
- buildDependencies
6780
+ throw Error(`${picocolors.dim('[rsbuild:plugin]')} Expect the setup function of Rsbuild plugin to be a function, but got ${picocolors.yellow(type)}.`);
6781
+ }
6782
+ if (before) {
6783
+ let index = plugins.findIndex((item)=>item.instance.name === before);
6784
+ -1 === index ? (logger.warn(`Plugin "${before}" does not exist.`), plugins.push({
6785
+ environment,
6786
+ instance: newPlugin
6787
+ })) : plugins.splice(index, 0, {
6788
+ environment,
6789
+ instance: newPlugin
6834
6790
  });
6835
- }), api.onAfterCreateCompiler(()=>{
6836
- cacheEnabled && 'rspack' === api.context.bundlerType && logger.debug('Rspack persistent cache enabled');
6791
+ } else plugins.push({
6792
+ environment,
6793
+ instance: newPlugin
6837
6794
  });
6838
6795
  }
6839
6796
  },
6840
- {
6841
- name: 'rsbuild:target',
6842
- setup (api) {
6843
- api.modifyBundlerChain({
6844
- order: 'pre',
6845
- handler: async (chain, { target, environment })=>{
6846
- if ('node' === target) return void chain.target('node');
6847
- let { browserslist } = environment, isDefaultBrowserslist = browserslist.join(',') === DEFAULT_WEB_BROWSERSLIST.join(',');
6848
- if ('web-worker' === target) return void chain.target(isDefaultBrowserslist ? [
6849
- 'webworker',
6850
- 'es2017'
6851
- ] : [
6852
- 'webworker',
6853
- 'es5'
6854
- ]);
6855
- let esQuery = isDefaultBrowserslist ? 'es2017' : `browserslist:${browserslist.join(',')}`;
6856
- chain.target([
6857
- 'web',
6858
- esQuery
6859
- ]);
6860
- }
6861
- });
6862
- }
6797
+ removePlugins: (pluginNames, options = {})=>{
6798
+ plugins = plugins.filter((plugin)=>!(pluginNames.includes(plugin.instance.name) && (!options.environment || plugin.environment === options.environment)));
6863
6799
  },
6864
- {
6865
- name: 'rsbuild:output',
6866
- setup (api) {
6867
- api.modifyBundlerChain(async (chain, { CHAIN_ID, isDev, isProd, isServer, environment, rspack })=>{
6868
- var jsAsync;
6869
- let { distPath, config } = environment, publicPath = function({ isDev, config, context }) {
6870
- var _context_devServer, _context_devServer1, _context_devServer2;
6871
- let { dev, output, server } = config, publicPath = DEFAULT_ASSET_PREFIX;
6872
- if (isDev) {
6873
- if ('string' == typeof dev.assetPrefix) publicPath = dev.assetPrefix;
6874
- else if (dev.assetPrefix) {
6875
- let protocol = (null == (_context_devServer1 = context.devServer) ? void 0 : _context_devServer1.https) ? 'https' : 'http', hostname = (null == (_context_devServer2 = context.devServer) ? void 0 : _context_devServer2.hostname) || DEFAULT_DEV_HOST;
6876
- publicPath = hostname === DEFAULT_DEV_HOST ? `${protocol}://localhost:<port>/` : `${protocol}://${hostname}:<port>/`, server.base && '/' !== server.base && (publicPath = urlJoin(publicPath, server.base));
6877
- }
6878
- } else 'string' == typeof output.assetPrefix && (publicPath = output.assetPrefix);
6879
- let defaultPort = server.port ?? 3000;
6880
- return formatPublicPath(replacePortPlaceholder(publicPath, isDev ? (null == (_context_devServer = context.devServer) ? void 0 : _context_devServer.port) ?? defaultPort : defaultPort));
6881
- }({
6882
- config,
6883
- isDev,
6884
- context: api.context
6885
- }), jsPath = config.output.distPath.js, jsAsyncPath = void 0 !== (jsAsync = config.output.distPath.jsAsync) ? jsAsync : isServer ? jsPath : jsPath ? `${jsPath}/async` : 'async', jsFilename = getFilename(config, 'js', isProd, isServer), isJsFilenameFn = 'function' == typeof jsFilename;
6886
- if (chain.output.path(distPath).filename(isJsFilenameFn ? (...args)=>{
6887
- let name = jsFilename(...args);
6888
- return posix.join(jsPath, name);
6889
- } : posix.join(jsPath, jsFilename)).chunkFilename(isJsFilenameFn ? (...args)=>{
6890
- let name = jsFilename(...args);
6800
+ isPluginExists: (pluginName, options = {})=>plugins.some((plugin)=>plugin.instance.name === pluginName && isEnvironmentMatch(plugin.environment, options.environment))
6801
+ }), context = await createContext(resolvedOptions, config), getPluginAPI = function({ context, pluginManager }) {
6802
+ let { hooks } = context, publicContext = function(context) {
6803
+ let exposedKeys = [
6804
+ 'action',
6805
+ 'version',
6806
+ 'rootPath',
6807
+ 'distPath',
6808
+ 'devServer',
6809
+ 'cachePath',
6810
+ 'callerName',
6811
+ 'bundlerType'
6812
+ ];
6813
+ return new Proxy(context, {
6814
+ get (target, prop) {
6815
+ if (exposedKeys.includes(prop)) return target[prop];
6816
+ },
6817
+ set: (_, prop)=>(logger.error(`Context is readonly, you can not assign to the "context.${prop}" prop.`), !0)
6818
+ });
6819
+ }(context);
6820
+ function getNormalizedConfig(options) {
6821
+ if (context.normalizedConfig) {
6822
+ if (null == options ? void 0 : options.environment) {
6823
+ let config = context.normalizedConfig.environments[options.environment];
6824
+ if (!config) throw Error(`${picocolors.dim('[rsbuild]')} Cannot find normalized config by environment: ${options.environment}.`);
6825
+ return config;
6826
+ }
6827
+ return context.normalizedConfig;
6828
+ }
6829
+ throw Error(`${picocolors.dim('[rsbuild]')} Cannot access normalized config until ${picocolors.yellow('modifyRsbuildConfig')} is called.`);
6830
+ }
6831
+ let getRsbuildConfig = (type = 'current')=>{
6832
+ switch(type){
6833
+ case 'original':
6834
+ return context.originalConfig;
6835
+ case 'current':
6836
+ return context.config;
6837
+ case 'normalized':
6838
+ return getNormalizedConfig();
6839
+ }
6840
+ throw Error(`${picocolors.dim('[rsbuild]')} ${picocolors.yellow('getRsbuildConfig')} get an invalid type param.`);
6841
+ }, exposed = [], expose = (id, api)=>{
6842
+ exposed.push({
6843
+ id,
6844
+ api
6845
+ });
6846
+ }, useExposed = (id)=>{
6847
+ let matched = exposed.find((item)=>item.id === id);
6848
+ if (matched) return matched.api;
6849
+ }, transformId = 0, transformer = {}, processAssetsFns = [], resolveFns = [];
6850
+ hooks.modifyBundlerChain.tap((chain, { target, environment })=>{
6851
+ let pluginName = 'RsbuildCorePlugin';
6852
+ chain.plugin(pluginName).use(class {
6853
+ apply(compiler) {
6854
+ for (let { handler, environment: pluginEnvironment } of (compiler.__rsbuildTransformer = transformer, resolveFns))(!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compiler.hooks.compilation.tap(pluginName, (compilation, { normalModuleFactory })=>{
6855
+ normalModuleFactory.hooks.resolve.tapPromise(pluginName, async (resolveData)=>handler({
6856
+ compiler,
6857
+ compilation,
6858
+ environment,
6859
+ resolveData
6860
+ }));
6861
+ });
6862
+ compiler.hooks.thisCompilation.tap(pluginName, (compilation)=>{
6863
+ compilation.hooks.childCompiler.tap(pluginName, (childCompiler)=>{
6864
+ childCompiler.__rsbuildTransformer = transformer;
6865
+ });
6866
+ let { sources } = compiler.webpack;
6867
+ for (let { descriptor, handler, environment: pluginEnvironment } of processAssetsFns)(!descriptor.targets || descriptor.targets.includes(target)) && (!descriptor.environments || descriptor.environments.includes(environment.name)) && (!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compilation.hooks.processAssets.tapPromise({
6868
+ name: pluginName,
6869
+ stage: mapProcessAssetsStage(compiler, descriptor.stage)
6870
+ }, async (assets)=>handler({
6871
+ assets,
6872
+ compiler,
6873
+ compilation,
6874
+ environment,
6875
+ sources
6876
+ }));
6877
+ });
6878
+ }
6879
+ constructor(){
6880
+ var key;
6881
+ (key = "name") in this ? Object.defineProperty(this, key, {
6882
+ value: pluginName,
6883
+ enumerable: !0,
6884
+ configurable: !0,
6885
+ writable: !0
6886
+ }) : this[key] = pluginName;
6887
+ }
6888
+ });
6889
+ });
6890
+ let onExitListened = !1, onExit = (cb)=>{
6891
+ if (!onExitListened) {
6892
+ var onExit;
6893
+ onExit = (exitCode)=>{
6894
+ hooks.onExit.callBatch({
6895
+ exitCode
6896
+ });
6897
+ }, exitHook_callbacks.add(onExit), isRegistered || (isRegistered = !0, node_process.on('SIGINT', ()=>{
6898
+ exit(external_node_os_constants.signals.SIGINT + 128, 'SIGINT');
6899
+ }), node_process.once('SIGTERM', ()=>{
6900
+ exit(external_node_os_constants.signals.SIGTERM + 128, 'SIGTERM');
6901
+ }), node_process.once('exit', (exitCode)=>{
6902
+ exit(exitCode, 'exit');
6903
+ })), onExitListened = !0;
6904
+ }
6905
+ hooks.onExit.tap(cb);
6906
+ };
6907
+ return (environment)=>({
6908
+ context: publicContext,
6909
+ expose,
6910
+ logger: logger,
6911
+ transform: (descriptor, handler)=>{
6912
+ let id = `rsbuild-transform-${transformId++}`;
6913
+ transformer[id] = handler, hooks.modifyBundlerChain.tapEnvironment({
6914
+ environment: environment,
6915
+ handler: (chain, { target, environment })=>{
6916
+ if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environment.name)) return;
6917
+ let rule = chain.module.rule(id);
6918
+ descriptor.test && rule.test(descriptor.test), descriptor.resourceQuery && rule.resourceQuery(descriptor.resourceQuery), descriptor.layer && rule.layer(descriptor.layer), descriptor.issuerLayer && rule.issuerLayer(descriptor.issuerLayer), descriptor.issuer && rule.issuer(descriptor.issuer), descriptor.with && rule.with(descriptor.with), descriptor.mimetype && rule.mimetype(descriptor.mimetype), descriptor.order && 'default' !== descriptor.order ? rule.enforce(descriptor.order) : descriptor.enforce && rule.enforce(descriptor.enforce);
6919
+ let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs');
6920
+ rule.use(id).loader(loaderPath).options({
6921
+ id,
6922
+ getEnvironment: ()=>environment
6923
+ });
6924
+ }
6925
+ });
6926
+ },
6927
+ useExposed,
6928
+ processAssets: (descriptor, handler)=>{
6929
+ processAssetsFns.push({
6930
+ environment: environment,
6931
+ descriptor,
6932
+ handler
6933
+ });
6934
+ },
6935
+ resolve: (handler)=>{
6936
+ resolveFns.push({
6937
+ environment: environment,
6938
+ handler
6939
+ });
6940
+ },
6941
+ getRsbuildConfig,
6942
+ getNormalizedConfig,
6943
+ isPluginExists: pluginManager.isPluginExists,
6944
+ onExit,
6945
+ onAfterBuild: hooks.onAfterBuild.tap,
6946
+ onCloseBuild: hooks.onCloseBuild.tap,
6947
+ onBeforeBuild: hooks.onBeforeBuild.tap,
6948
+ onCloseDevServer: hooks.onCloseDevServer.tap,
6949
+ onDevCompileDone: hooks.onDevCompileDone.tap,
6950
+ onAfterCreateCompiler: hooks.onAfterCreateCompiler.tap,
6951
+ onAfterStartDevServer: hooks.onAfterStartDevServer.tap,
6952
+ onBeforeCreateCompiler: hooks.onBeforeCreateCompiler.tap,
6953
+ onBeforeStartDevServer: hooks.onBeforeStartDevServer.tap,
6954
+ onAfterStartProdServer: hooks.onAfterStartProdServer.tap,
6955
+ onBeforeStartProdServer: hooks.onBeforeStartProdServer.tap,
6956
+ modifyRsbuildConfig: hooks.modifyRsbuildConfig.tap,
6957
+ modifyHTML: (handler)=>{
6958
+ hooks.modifyHTML.tapEnvironment({
6959
+ environment,
6960
+ handler
6961
+ });
6962
+ },
6963
+ modifyHTMLTags: (handler)=>{
6964
+ hooks.modifyHTMLTags.tapEnvironment({
6965
+ environment,
6966
+ handler
6967
+ });
6968
+ },
6969
+ modifyBundlerChain: (handler)=>{
6970
+ hooks.modifyBundlerChain.tapEnvironment({
6971
+ environment,
6972
+ handler
6973
+ });
6974
+ },
6975
+ modifyRspackConfig: (handler)=>{
6976
+ hooks.modifyRspackConfig.tapEnvironment({
6977
+ environment,
6978
+ handler
6979
+ });
6980
+ },
6981
+ modifyWebpackChain: (handler)=>{
6982
+ hooks.modifyWebpackChain.tapEnvironment({
6983
+ environment,
6984
+ handler
6985
+ });
6986
+ },
6987
+ modifyWebpackConfig: (handler)=>{
6988
+ hooks.modifyWebpackConfig.tapEnvironment({
6989
+ environment,
6990
+ handler
6991
+ });
6992
+ },
6993
+ modifyEnvironmentConfig: (handler)=>{
6994
+ hooks.modifyEnvironmentConfig.tapEnvironment({
6995
+ environment,
6996
+ handler
6997
+ });
6998
+ },
6999
+ onAfterEnvironmentCompile: (handler)=>{
7000
+ hooks.onAfterEnvironmentCompile.tapEnvironment({
7001
+ environment,
7002
+ handler
7003
+ });
7004
+ },
7005
+ onBeforeEnvironmentCompile: (handler)=>{
7006
+ hooks.onBeforeEnvironmentCompile.tapEnvironment({
7007
+ environment,
7008
+ handler
7009
+ });
7010
+ }
7011
+ });
7012
+ }({
7013
+ context,
7014
+ pluginManager
7015
+ });
7016
+ context.getPluginAPI = getPluginAPI;
7017
+ let globalPluginAPI = getPluginAPI();
7018
+ logger.debug('add default plugins'), pluginManager.addPlugins([
7019
+ {
7020
+ name: 'rsbuild:basic',
7021
+ setup (api) {
7022
+ api.modifyBundlerChain((chain, { isDev, target, bundler, environment, CHAIN_ID })=>{
7023
+ let { config } = environment;
7024
+ chain.name(environment.name);
7025
+ let devtool = ((config)=>{
7026
+ let { sourceMap } = config.output, isProd = 'production' === config.mode;
7027
+ return !1 !== sourceMap && (!0 === sourceMap ? isProd ? 'source-map' : 'cheap-module-source-map' : void 0 === sourceMap.js ? !isProd && 'cheap-module-source-map' : sourceMap.js);
7028
+ })(config);
7029
+ chain.devtool(devtool);
7030
+ let { sourceMap } = config.output;
7031
+ !devtool && 'object' == typeof sourceMap && sourceMap.css && chain.plugin('source-map-css').use(bundler.SourceMapDevToolPlugin, [
7032
+ {
7033
+ test: /\.css$/,
7034
+ filename: '[file].map[query]'
7035
+ }
7036
+ ]), chain.context(api.context.rootPath), chain.mode(environment.config.mode), chain.infrastructureLogging({
7037
+ level: 'error'
7038
+ }), chain.watchOptions({
7039
+ aggregateTimeout: 0
7040
+ }), chain.performance.hints(!1), chain.module.parser.merge({
7041
+ javascript: {
7042
+ exportsPresence: 'error',
7043
+ typeReexportsPresence: 'tolerant'
7044
+ }
7045
+ }), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(bundler.HotModuleReplacementPlugin), isDev && chain.output.devtoolModuleFilenameTemplate((info)=>toPosixPath(info.absoluteResourcePath)), 'rspack' === api.context.bundlerType && chain.experiments({
7046
+ ...chain.get('experiments'),
7047
+ typeReexportsPresence: !0,
7048
+ rspackFuture: {
7049
+ bundlerInfo: {
7050
+ force: !1
7051
+ }
7052
+ }
7053
+ }), process.env.RSPACK_CONFIG_VALIDATE ||= 'loose-silent';
7054
+ });
7055
+ }
7056
+ },
7057
+ {
7058
+ name: 'rsbuild:entry',
7059
+ setup (api) {
7060
+ api.modifyBundlerChain((chain, { environment, isServer })=>{
7061
+ let { config, entry } = environment, { preEntry } = config.source, injectCoreJsEntry = 'entry' === config.output.polyfill && !isServer;
7062
+ for (let entryName of Object.keys(entry)){
7063
+ let entryPoint = chain.entry(entryName), addEntry = (item)=>{
7064
+ if ('object' == typeof item && 'html' in item) {
7065
+ let { html: _html, ...rest } = item;
7066
+ entryPoint.add(rest);
7067
+ } else entryPoint.add(item);
7068
+ };
7069
+ preEntry.forEach(addEntry), injectCoreJsEntry && addEntry(createVirtualModule('import "core-js";')), helpers_castArray(entry[entryName]).forEach(addEntry);
7070
+ }
7071
+ }), api.onBeforeCreateCompiler(({ bundlerConfigs })=>{
7072
+ if (bundlerConfigs.every((config)=>!config.entry)) throw Error(`${picocolors.dim('[rsbuild:config]')} Could not find any entry module, please make sure that ${picocolors.yellow('src/index.(ts|js|tsx|jsx|mts|cts|mjs|cjs)')} exists, or customize entry through the ${picocolors.yellow('source.entry')} configuration.`);
7073
+ });
7074
+ }
7075
+ },
7076
+ {
7077
+ name: 'rsbuild:cache',
7078
+ setup (api) {
7079
+ let cacheEnabled = !1;
7080
+ api.modifyBundlerChain(async (chain, { environment, env })=>{
7081
+ let { config } = environment, { bundlerType } = api.context, buildCache = config.performance.buildCache ?? 'webpack' === bundlerType;
7082
+ if (!1 === buildCache) return;
7083
+ cacheEnabled = !0;
7084
+ let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = function({ cacheDirectory }, context) {
7085
+ return cacheDirectory ? external_node_path_isAbsolute(cacheDirectory) ? cacheDirectory : join(context.rootPath, cacheDirectory) : join(context.cachePath, context.bundlerType);
7086
+ }(cacheConfig, context), buildDependencies = await getBuildDependencies(context, config, environment, cacheConfig.buildDependencies ? {
7087
+ userBuildDependencies: cacheConfig.buildDependencies
7088
+ } : {});
7089
+ 'webpack' === bundlerType && await validateWebpackCache(cacheDirectory, buildDependencies);
7090
+ let cacheVersion = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length ? `${environment.name}-${env}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : `${environment.name}-${env}`;
7091
+ 'rspack' === bundlerType ? (chain.cache(!0), chain.experiments({
7092
+ ...chain.get('experiments'),
7093
+ cache: {
7094
+ type: 'persistent',
7095
+ version: cacheVersion,
7096
+ storage: {
7097
+ type: 'filesystem',
7098
+ directory: cacheDirectory
7099
+ },
7100
+ buildDependencies: Object.values(buildDependencies).flat()
7101
+ }
7102
+ })) : chain.cache({
7103
+ name: cacheVersion,
7104
+ type: 'filesystem',
7105
+ cacheDirectory,
7106
+ buildDependencies
7107
+ });
7108
+ }), api.onAfterCreateCompiler(()=>{
7109
+ cacheEnabled && 'rspack' === api.context.bundlerType && logger.debug('Rspack persistent cache enabled');
7110
+ });
7111
+ }
7112
+ },
7113
+ {
7114
+ name: 'rsbuild:target',
7115
+ setup (api) {
7116
+ api.modifyBundlerChain({
7117
+ order: 'pre',
7118
+ handler: (chain, { target, environment })=>{
7119
+ if ('node' === target) return void chain.target('node');
7120
+ let { browserslist } = environment, isDefaultBrowserslist = browserslist.join(',') === DEFAULT_WEB_BROWSERSLIST.join(',');
7121
+ if ('web-worker' === target) return void chain.target(isDefaultBrowserslist ? [
7122
+ 'webworker',
7123
+ 'es2017'
7124
+ ] : [
7125
+ 'webworker',
7126
+ 'es5'
7127
+ ]);
7128
+ let esQuery = isDefaultBrowserslist ? 'es2017' : `browserslist:${browserslist.join(',')}`;
7129
+ chain.target([
7130
+ 'web',
7131
+ esQuery
7132
+ ]);
7133
+ }
7134
+ });
7135
+ }
7136
+ },
7137
+ {
7138
+ name: 'rsbuild:output',
7139
+ setup (api) {
7140
+ api.modifyBundlerChain((chain, { CHAIN_ID, isDev, isProd, isServer, environment, rspack })=>{
7141
+ var jsAsync;
7142
+ let { distPath, config } = environment, publicPath = function({ isDev, config, context }) {
7143
+ var _context_devServer, _context_devServer1, _context_devServer2;
7144
+ let { dev, output, server } = config, publicPath = DEFAULT_ASSET_PREFIX;
7145
+ if (isDev) {
7146
+ if ('string' == typeof dev.assetPrefix) publicPath = dev.assetPrefix;
7147
+ else if (dev.assetPrefix) {
7148
+ let protocol = (null == (_context_devServer1 = context.devServer) ? void 0 : _context_devServer1.https) ? 'https' : 'http', hostname = (null == (_context_devServer2 = context.devServer) ? void 0 : _context_devServer2.hostname) || DEFAULT_DEV_HOST;
7149
+ publicPath = hostname === DEFAULT_DEV_HOST ? `${protocol}://localhost:<port>/` : `${protocol}://${hostname}:<port>/`, server.base && '/' !== server.base && (publicPath = urlJoin(publicPath, server.base));
7150
+ }
7151
+ } else 'string' == typeof output.assetPrefix && (publicPath = output.assetPrefix);
7152
+ let defaultPort = server.port ?? 3000;
7153
+ return formatPublicPath(replacePortPlaceholder(publicPath, isDev ? (null == (_context_devServer = context.devServer) ? void 0 : _context_devServer.port) ?? defaultPort : defaultPort));
7154
+ }({
7155
+ config,
7156
+ isDev,
7157
+ context: api.context
7158
+ }), jsPath = config.output.distPath.js, jsAsyncPath = void 0 !== (jsAsync = config.output.distPath.jsAsync) ? jsAsync : isServer ? jsPath : jsPath ? `${jsPath}/async` : 'async', jsFilename = getFilename(config, 'js', isProd, isServer), isJsFilenameFn = 'function' == typeof jsFilename;
7159
+ if (chain.output.path(distPath).filename(isJsFilenameFn ? (...args)=>{
7160
+ let name = jsFilename(...args);
7161
+ return posix.join(jsPath, name);
7162
+ } : posix.join(jsPath, jsFilename)).chunkFilename(isJsFilenameFn ? (...args)=>{
7163
+ let name = jsFilename(...args);
6891
7164
  return posix.join(jsAsyncPath, name);
6892
7165
  } : posix.join(jsAsyncPath, jsFilename)).publicPath(publicPath).pathinfo(!1).hashFunction('xxhash64'), isServer && chain.output.library({
6893
7166
  type: 'commonjs2',
@@ -7328,7 +7601,7 @@ async function applyDefaultPlugins(pluginManager, context) {
7328
7601
  {
7329
7602
  name: 'rsbuild:wasm',
7330
7603
  setup (api) {
7331
- api.modifyBundlerChain(async (chain, { CHAIN_ID, environment, isProd })=>{
7604
+ api.modifyBundlerChain((chain, { CHAIN_ID, environment, isProd })=>{
7332
7605
  let { config } = environment, distPath = config.output.distPath.wasm, filename = posix.join(distPath, getFilename(config, 'wasm', isProd));
7333
7606
  chain.experiments({
7334
7607
  ...chain.get('experiments'),
@@ -7342,7 +7615,7 @@ async function applyDefaultPlugins(pluginManager, context) {
7342
7615
  {
7343
7616
  name: 'rsbuild:moment',
7344
7617
  setup (api) {
7345
- api.modifyBundlerChain(async (chain, { environment, bundler })=>{
7618
+ api.modifyBundlerChain((chain, { environment, bundler })=>{
7346
7619
  let { config } = environment;
7347
7620
  config.performance.removeMomentLocale && chain.plugin('remove-moment-locale').use(bundler.IgnorePlugin, [
7348
7621
  {
@@ -7538,7 +7811,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7538
7811
  name: 'rsbuild:minimize',
7539
7812
  setup (api) {
7540
7813
  let isRspack = 'rspack' === api.context.bundlerType;
7541
- api.modifyBundlerChain(async (chain, { environment, CHAIN_ID, rspack })=>{
7814
+ api.modifyBundlerChain((chain, { environment, CHAIN_ID, rspack })=>{
7542
7815
  let { config } = environment, { minifyJs, minifyCss, jsOptions, cssOptions } = parseMinifyOptions(config);
7543
7816
  if (chain.optimization.minimize(minifyJs || minifyCss), minifyJs && isRspack && chain.optimization.minimizer(CHAIN_ID.MINIMIZER.JS).use(rspack.SwcJsMinimizerRspackPlugin, [
7544
7817
  ((config, jsOptions)=>{
@@ -7591,7 +7864,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7591
7864
  {
7592
7865
  name: 'rsbuild:progress',
7593
7866
  setup (api) {
7594
- 'webpack' !== api.context.bundlerType && api.modifyBundlerChain(async (chain, { CHAIN_ID, environment, rspack })=>{
7867
+ 'webpack' !== api.context.bundlerType && api.modifyBundlerChain((chain, { CHAIN_ID, environment, rspack })=>{
7595
7868
  let { config } = environment, options = config.dev.progressBar;
7596
7869
  if (!options) return;
7597
7870
  let prefix = !0 !== options && void 0 !== options.id ? options.id : environment.name;
@@ -7609,7 +7882,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7609
7882
  setup (api) {
7610
7883
  api.modifyBundlerChain({
7611
7884
  order: 'pre',
7612
- handler: async (chain, { CHAIN_ID, isDev, target, environment })=>{
7885
+ handler: (chain, { CHAIN_ID, isDev, target, environment })=>{
7613
7886
  let { config, browserslist } = environment, cacheRoot = node_path.join(api.context.cachePath, '.swc'), rule = chain.module.rule(CHAIN_ID.RULE.JS).test(SCRIPT_REGEX).type("javascript/auto").dependency({
7614
7887
  not: 'url'
7615
7888
  }).resourceQuery({
@@ -7692,7 +7965,17 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7692
7965
  if ('off' === polyfillMode) swcConfig.env.mode = void 0;
7693
7966
  else {
7694
7967
  swcConfig.env.mode = polyfillMode;
7695
- let coreJsDir = await applyCoreJs(swcConfig, polyfillMode);
7968
+ let coreJsDir = function(swcConfig, polyfillMode) {
7969
+ let coreJsPath = swc_require.resolve('core-js/package.json'), version = ((corejsPkgPath)=>{
7970
+ try {
7971
+ let rawJson = node_fs.readFileSync(corejsPkgPath, 'utf-8'), { version } = JSON.parse(rawJson), [major, minor] = version.split('.');
7972
+ return `${major}.${minor}`;
7973
+ } catch {
7974
+ return '3';
7975
+ }
7976
+ })(coreJsPath), coreJsDir = node_path.dirname(coreJsPath);
7977
+ return swcConfig.env.coreJs = version, 'usage' === polyfillMode && (swcConfig.env.shippedProposals = !0), coreJsDir;
7978
+ }(swcConfig, polyfillMode);
7696
7979
  for (let item of [
7697
7980
  rule,
7698
7981
  dataUriRule
@@ -7895,7 +8178,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7895
8178
  headTags,
7896
8179
  bodyTags
7897
8180
  };
7898
- }), api.modifyBundlerChain(async (chain, { CHAIN_ID, environment })=>{
8181
+ }), api.modifyBundlerChain((chain, { CHAIN_ID, environment })=>{
7899
8182
  let { config, htmlPaths } = environment;
7900
8183
  if (0 === Object.keys(htmlPaths).length) return;
7901
8184
  let { performance: { preload, prefetch } } = config, HTMLCount = chain.entryPoints.values().length, excludes = ((config)=>{
@@ -7982,7 +8265,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7982
8265
  {
7983
8266
  name: 'rsbuild:server',
7984
8267
  setup (api) {
7985
- let onStartServer = async ({ port, routes })=>{
8268
+ let onStartServer = ({ port, routes })=>{
7986
8269
  let config = api.getNormalizedConfig();
7987
8270
  if (config.server.open) {
7988
8271
  var _api_context_devServer;
@@ -8116,7 +8399,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8116
8399
  ...config.source.include || [],
8117
8400
  /@module-federation[\\/]/
8118
8401
  ]);
8119
- }), api.modifyBundlerChain(async (chain, { CHAIN_ID, target, environment })=>{
8402
+ }), api.modifyBundlerChain((chain, { CHAIN_ID, target, environment })=>{
8120
8403
  var _config_moduleFederation;
8121
8404
  let { config } = environment;
8122
8405
  if (!(null == (_config_moduleFederation = config.moduleFederation) ? void 0 : _config_moduleFederation.options) || 'web' !== target) return;
@@ -8131,7 +8414,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8131
8414
  },
8132
8415
  {
8133
8416
  name: 'rsbuild:rspack-profile',
8134
- async setup (api) {
8417
+ setup (api) {
8135
8418
  let traceOutput;
8136
8419
  if ('webpack' === api.context.bundlerType) return;
8137
8420
  let { RSPACK_PROFILE } = process.env;
@@ -8194,344 +8477,51 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8194
8477
  enabled: !0,
8195
8478
  hashFuncNames: [
8196
8479
  algorithm
8197
- ],
8198
- htmlPlugin: node_path.join(COMPILED_PATH, 'html-rspack-plugin/index.js')
8199
- }
8200
- ]);
8201
- });
8202
- }
8203
- },
8204
- {
8205
- name: 'rsbuild:nonce',
8206
- setup (api) {
8207
- api.onAfterCreateCompiler(({ compiler, environments })=>{
8208
- let nonces = Object.values(environments).map((environment)=>{
8209
- let { nonce } = environment.config.security;
8210
- return nonce;
8211
- });
8212
- if (!nonces.some((nonce)=>!!nonce)) return;
8213
- let environmentList = Object.values(environments);
8214
- applyToCompiler(compiler, (compiler, index)=>{
8215
- let nonce = nonces[index], environment = environmentList.find((item)=>item.index === index);
8216
- if (!Object.keys((null == environment ? void 0 : environment.htmlPaths) ?? {}).length || !nonce) return;
8217
- let injectCode = createVirtualModule(`__webpack_nonce__ = "${nonce}";`);
8218
- new compiler.webpack.EntryPlugin(compiler.context, injectCode, {
8219
- name: void 0
8220
- }).apply(compiler);
8221
- });
8222
- }), api.modifyHTMLTags({
8223
- order: 'post',
8224
- handler: ({ headTags, bodyTags }, { environment })=>{
8225
- let { config } = environment, { nonce } = config.security, allTags = [
8226
- ...headTags,
8227
- ...bodyTags
8228
- ];
8229
- if (nonce) for (let tag of allTags){
8230
- var _tag_attrs, _tag_attrs1;
8231
- ("script" === tag.tag || 'style' === tag.tag || 'link' === tag.tag && (null == (_tag_attrs = tag.attrs) ? void 0 : _tag_attrs.rel) === 'preload' && (null == (_tag_attrs1 = tag.attrs) ? void 0 : _tag_attrs1.as) === "script") && (tag.attrs ??= {}, tag.attrs.nonce = nonce);
8232
- }
8233
- return {
8234
- headTags,
8235
- bodyTags
8236
- };
8237
- }
8238
- });
8239
- }
8240
- }
8241
- ]);
8242
- }
8243
- async function createRsbuild(options = {}) {
8244
- let plugins, envs = options.loadEnv ? loadEnv({
8245
- cwd: options.cwd,
8246
- ...'boolean' == typeof options.loadEnv ? {} : options.loadEnv
8247
- }) : null, config = isFunction(options.rsbuildConfig) ? await options.rsbuildConfig() : options.rsbuildConfig || {};
8248
- config.logLevel && (logger.level = config.logLevel), function(config, envs) {
8249
- var _config_performance;
8250
- if (null !== envs && (config.source ||= {}, config.source.define = {
8251
- ...envs.publicVars,
8252
- ...config.source.define
8253
- }, 0 !== envs.filePaths.length && (config.dev ||= {}, config.dev.watchFiles = [
8254
- ...config.dev.watchFiles ? helpers_castArray(config.dev.watchFiles) : [],
8255
- {
8256
- paths: envs.filePaths,
8257
- type: 'reload-server'
8258
- }
8259
- ], null == (_config_performance = config.performance) ? void 0 : _config_performance.buildCache))) {
8260
- let { buildCache } = config.performance;
8261
- !0 === buildCache ? config.performance.buildCache = {
8262
- buildDependencies: envs.filePaths
8263
- } : (buildCache.buildDependencies ||= [], buildCache.buildDependencies.push(...envs.filePaths));
8264
- }
8265
- }(config, envs);
8266
- let resolvedOptions = {
8267
- cwd: process.cwd(),
8268
- callerName: 'rsbuild',
8269
- ...options,
8270
- rsbuildConfig: config
8271
- }, pluginManager = (plugins = [], {
8272
- getPlugins: (options = {})=>plugins.filter((plugin)=>isEnvironmentMatch(plugin.environment, options.environment)).map(({ instance })=>instance),
8273
- getAllPluginsWithMeta: ()=>plugins,
8274
- addPlugins: (newPlugins, options)=>{
8275
- let { before, environment } = options || {};
8276
- for (let newPlugin of newPlugins)if (newPlugin) {
8277
- let type = typeof newPlugin;
8278
- if ('object' !== type || null === newPlugin) throw Error(`${picocolors.dim('[rsbuild:plugin]')} Expect Rsbuild plugin instance to be an object, but got ${picocolors.yellow(type)}.`);
8279
- if (!isFunction(newPlugin.setup)) {
8280
- if (isFunction(newPlugin.apply)) {
8281
- let { name = 'SomeWebpackPlugin' } = newPlugin.constructor || {};
8282
- throw Error([
8283
- `${picocolors.yellow(name)} looks like a webpack or Rspack plugin, please use ${picocolors.yellow('`tools.rspack`')} to register it:`,
8284
- picocolors.green(`
8285
- // rsbuild.config.ts
8286
- export default {
8287
- tools: {
8288
- rspack: {
8289
- plugins: [new ${name}()]
8290
- }
8291
- }
8292
- };
8293
- `)
8294
- ].join('\n'));
8295
- }
8296
- throw Error(`${picocolors.dim('[rsbuild:plugin]')} Expect the setup function of Rsbuild plugin to be a function, but got ${picocolors.yellow(type)}.`);
8297
- }
8298
- if (before) {
8299
- let index = plugins.findIndex((item)=>item.instance.name === before);
8300
- -1 === index ? (logger.warn(`Plugin "${before}" does not exist.`), plugins.push({
8301
- environment,
8302
- instance: newPlugin
8303
- })) : plugins.splice(index, 0, {
8304
- environment,
8305
- instance: newPlugin
8306
- });
8307
- } else plugins.push({
8308
- environment,
8309
- instance: newPlugin
8480
+ ],
8481
+ htmlPlugin: node_path.join(COMPILED_PATH, 'html-rspack-plugin/index.js')
8482
+ }
8483
+ ]);
8310
8484
  });
8311
8485
  }
8312
8486
  },
8313
- removePlugins: (pluginNames, options = {})=>{
8314
- plugins = plugins.filter((plugin)=>!(pluginNames.includes(plugin.instance.name) && (!options.environment || plugin.environment === options.environment)));
8315
- },
8316
- isPluginExists: (pluginName, options = {})=>plugins.some((plugin)=>plugin.instance.name === pluginName && isEnvironmentMatch(plugin.environment, options.environment))
8317
- }), context = await createContext(resolvedOptions, config), getPluginAPI = function({ context, pluginManager }) {
8318
- let { hooks } = context, publicContext = function(context) {
8319
- let exposedKeys = [
8320
- 'action',
8321
- 'version',
8322
- 'rootPath',
8323
- 'distPath',
8324
- 'devServer',
8325
- 'cachePath',
8326
- 'callerName',
8327
- 'bundlerType'
8328
- ];
8329
- return new Proxy(context, {
8330
- get (target, prop) {
8331
- if (exposedKeys.includes(prop)) return target[prop];
8332
- },
8333
- set: (_, prop)=>(logger.error(`Context is readonly, you can not assign to the "context.${prop}" prop.`), !0)
8334
- });
8335
- }(context);
8336
- function getNormalizedConfig(options) {
8337
- if (context.normalizedConfig) {
8338
- if (null == options ? void 0 : options.environment) {
8339
- let config = context.normalizedConfig.environments[options.environment];
8340
- if (!config) throw Error(`${picocolors.dim('[rsbuild]')} Cannot find normalized config by environment: ${options.environment}.`);
8341
- return config;
8342
- }
8343
- return context.normalizedConfig;
8344
- }
8345
- throw Error(`${picocolors.dim('[rsbuild]')} Cannot access normalized config until ${picocolors.yellow('modifyRsbuildConfig')} is called.`);
8346
- }
8347
- let getRsbuildConfig = (type = 'current')=>{
8348
- switch(type){
8349
- case 'original':
8350
- return context.originalConfig;
8351
- case 'current':
8352
- return context.config;
8353
- case 'normalized':
8354
- return getNormalizedConfig();
8355
- }
8356
- throw Error(`${picocolors.dim('[rsbuild]')} ${picocolors.yellow('getRsbuildConfig')} get an invalid type param.`);
8357
- }, exposed = [], expose = (id, api)=>{
8358
- exposed.push({
8359
- id,
8360
- api
8361
- });
8362
- }, useExposed = (id)=>{
8363
- let matched = exposed.find((item)=>item.id === id);
8364
- if (matched) return matched.api;
8365
- }, transformId = 0, transformer = {}, processAssetsFns = [], resolveFns = [];
8366
- hooks.modifyBundlerChain.tap((chain, { target, environment })=>{
8367
- let pluginName = 'RsbuildCorePlugin';
8368
- chain.plugin(pluginName).use(class {
8369
- apply(compiler) {
8370
- for (let { handler, environment: pluginEnvironment } of (compiler.__rsbuildTransformer = transformer, resolveFns))(!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compiler.hooks.compilation.tap(pluginName, (compilation, { normalModuleFactory })=>{
8371
- normalModuleFactory.hooks.resolve.tapPromise(pluginName, async (resolveData)=>handler({
8372
- compiler,
8373
- compilation,
8374
- environment,
8375
- resolveData
8376
- }));
8377
- });
8378
- compiler.hooks.thisCompilation.tap(pluginName, (compilation)=>{
8379
- compilation.hooks.childCompiler.tap(pluginName, (childCompiler)=>{
8380
- childCompiler.__rsbuildTransformer = transformer;
8381
- });
8382
- let { sources } = compiler.webpack;
8383
- for (let { descriptor, handler, environment: pluginEnvironment } of processAssetsFns)(!descriptor.targets || descriptor.targets.includes(target)) && (!descriptor.environments || descriptor.environments.includes(environment.name)) && (!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compilation.hooks.processAssets.tapPromise({
8384
- name: pluginName,
8385
- stage: mapProcessAssetsStage(compiler, descriptor.stage)
8386
- }, async (assets)=>handler({
8387
- assets,
8388
- compiler,
8389
- compilation,
8390
- environment,
8391
- sources
8392
- }));
8487
+ {
8488
+ name: 'rsbuild:nonce',
8489
+ setup (api) {
8490
+ api.onAfterCreateCompiler(({ compiler, environments })=>{
8491
+ let nonces = Object.values(environments).map((environment)=>{
8492
+ let { nonce } = environment.config.security;
8493
+ return nonce;
8393
8494
  });
8394
- }
8395
- constructor(){
8396
- var key;
8397
- (key = "name") in this ? Object.defineProperty(this, key, {
8398
- value: pluginName,
8399
- enumerable: !0,
8400
- configurable: !0,
8401
- writable: !0
8402
- }) : this[key] = pluginName;
8403
- }
8404
- });
8405
- });
8406
- let onExitListened = !1, onExit = (cb)=>{
8407
- if (!onExitListened) {
8408
- var onExit;
8409
- onExit = (exitCode)=>{
8410
- hooks.onExit.callBatch({
8411
- exitCode
8495
+ if (!nonces.some((nonce)=>!!nonce)) return;
8496
+ let environmentList = Object.values(environments);
8497
+ applyToCompiler(compiler, (compiler, index)=>{
8498
+ let nonce = nonces[index], environment = environmentList.find((item)=>item.index === index);
8499
+ if (!Object.keys((null == environment ? void 0 : environment.htmlPaths) ?? {}).length || !nonce) return;
8500
+ let injectCode = createVirtualModule(`__webpack_nonce__ = "${nonce}";`);
8501
+ new compiler.webpack.EntryPlugin(compiler.context, injectCode, {
8502
+ name: void 0
8503
+ }).apply(compiler);
8412
8504
  });
8413
- }, exitHook_callbacks.add(onExit), isRegistered || (isRegistered = !0, node_process.on('SIGINT', ()=>{
8414
- exit(external_node_os_constants.signals.SIGINT + 128, 'SIGINT');
8415
- }), node_process.once('SIGTERM', ()=>{
8416
- exit(external_node_os_constants.signals.SIGTERM + 128, 'SIGTERM');
8417
- }), node_process.once('exit', (exitCode)=>{
8418
- exit(exitCode, 'exit');
8419
- })), onExitListened = !0;
8420
- }
8421
- hooks.onExit.tap(cb);
8422
- };
8423
- return (environment)=>({
8424
- context: publicContext,
8425
- expose,
8426
- logger: logger,
8427
- transform: (descriptor, handler)=>{
8428
- let id = `rsbuild-transform-${transformId++}`;
8429
- transformer[id] = handler, hooks.modifyBundlerChain.tapEnvironment({
8430
- environment: environment,
8431
- handler: (chain, { target, environment })=>{
8432
- if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environment.name)) return;
8433
- let rule = chain.module.rule(id);
8434
- descriptor.test && rule.test(descriptor.test), descriptor.resourceQuery && rule.resourceQuery(descriptor.resourceQuery), descriptor.layer && rule.layer(descriptor.layer), descriptor.issuerLayer && rule.issuerLayer(descriptor.issuerLayer), descriptor.issuer && rule.issuer(descriptor.issuer), descriptor.with && rule.with(descriptor.with), descriptor.mimetype && rule.mimetype(descriptor.mimetype), descriptor.order && 'default' !== descriptor.order ? rule.enforce(descriptor.order) : descriptor.enforce && rule.enforce(descriptor.enforce);
8435
- let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs');
8436
- rule.use(id).loader(loaderPath).options({
8437
- id,
8438
- getEnvironment: ()=>environment
8439
- });
8505
+ }), api.modifyHTMLTags({
8506
+ order: 'post',
8507
+ handler: ({ headTags, bodyTags }, { environment })=>{
8508
+ let { config } = environment, { nonce } = config.security, allTags = [
8509
+ ...headTags,
8510
+ ...bodyTags
8511
+ ];
8512
+ if (nonce) for (let tag of allTags){
8513
+ var _tag_attrs, _tag_attrs1;
8514
+ ("script" === tag.tag || 'style' === tag.tag || 'link' === tag.tag && (null == (_tag_attrs = tag.attrs) ? void 0 : _tag_attrs.rel) === 'preload' && (null == (_tag_attrs1 = tag.attrs) ? void 0 : _tag_attrs1.as) === "script") && (tag.attrs ??= {}, tag.attrs.nonce = nonce);
8440
8515
  }
8441
- });
8442
- },
8443
- useExposed,
8444
- processAssets: (descriptor, handler)=>{
8445
- processAssetsFns.push({
8446
- environment: environment,
8447
- descriptor,
8448
- handler
8449
- });
8450
- },
8451
- resolve: (handler)=>{
8452
- resolveFns.push({
8453
- environment: environment,
8454
- handler
8455
- });
8456
- },
8457
- getRsbuildConfig,
8458
- getNormalizedConfig,
8459
- isPluginExists: pluginManager.isPluginExists,
8460
- onExit,
8461
- onAfterBuild: hooks.onAfterBuild.tap,
8462
- onCloseBuild: hooks.onCloseBuild.tap,
8463
- onBeforeBuild: hooks.onBeforeBuild.tap,
8464
- onCloseDevServer: hooks.onCloseDevServer.tap,
8465
- onDevCompileDone: hooks.onDevCompileDone.tap,
8466
- onAfterCreateCompiler: hooks.onAfterCreateCompiler.tap,
8467
- onAfterStartDevServer: hooks.onAfterStartDevServer.tap,
8468
- onBeforeCreateCompiler: hooks.onBeforeCreateCompiler.tap,
8469
- onBeforeStartDevServer: hooks.onBeforeStartDevServer.tap,
8470
- onAfterStartProdServer: hooks.onAfterStartProdServer.tap,
8471
- onBeforeStartProdServer: hooks.onBeforeStartProdServer.tap,
8472
- modifyRsbuildConfig: hooks.modifyRsbuildConfig.tap,
8473
- modifyHTML: (handler)=>{
8474
- hooks.modifyHTML.tapEnvironment({
8475
- environment,
8476
- handler
8477
- });
8478
- },
8479
- modifyHTMLTags: (handler)=>{
8480
- hooks.modifyHTMLTags.tapEnvironment({
8481
- environment,
8482
- handler
8483
- });
8484
- },
8485
- modifyBundlerChain: (handler)=>{
8486
- hooks.modifyBundlerChain.tapEnvironment({
8487
- environment,
8488
- handler
8489
- });
8490
- },
8491
- modifyRspackConfig: (handler)=>{
8492
- hooks.modifyRspackConfig.tapEnvironment({
8493
- environment,
8494
- handler
8495
- });
8496
- },
8497
- modifyWebpackChain: (handler)=>{
8498
- hooks.modifyWebpackChain.tapEnvironment({
8499
- environment,
8500
- handler
8501
- });
8502
- },
8503
- modifyWebpackConfig: (handler)=>{
8504
- hooks.modifyWebpackConfig.tapEnvironment({
8505
- environment,
8506
- handler
8507
- });
8508
- },
8509
- modifyEnvironmentConfig: (handler)=>{
8510
- hooks.modifyEnvironmentConfig.tapEnvironment({
8511
- environment,
8512
- handler
8513
- });
8514
- },
8515
- onAfterEnvironmentCompile: (handler)=>{
8516
- hooks.onAfterEnvironmentCompile.tapEnvironment({
8517
- environment,
8518
- handler
8519
- });
8520
- },
8521
- onBeforeEnvironmentCompile: (handler)=>{
8522
- hooks.onBeforeEnvironmentCompile.tapEnvironment({
8523
- environment,
8524
- handler
8525
- });
8526
- }
8527
- });
8528
- }({
8529
- context,
8530
- pluginManager
8531
- });
8532
- context.getPluginAPI = getPluginAPI;
8533
- let globalPluginAPI = getPluginAPI();
8534
- logger.debug('add default plugins'), await applyDefaultPlugins(pluginManager, context), logger.debug('add default plugins done');
8516
+ return {
8517
+ headTags,
8518
+ bodyTags
8519
+ };
8520
+ }
8521
+ });
8522
+ }
8523
+ }
8524
+ ]), logger.debug('add default plugins done');
8535
8525
  let provider = config.provider || rspackProvider, providerInstance = await provider({
8536
8526
  context,
8537
8527
  pluginManager,
@@ -8790,7 +8780,7 @@ async function watchFilesForRestart({ files, rsbuild, isBuildWatch, watchOptions
8790
8780
  let applyServerOptions = (command)=>{
8791
8781
  command.option('-o, --open [url]', 'open the page in browser on startup').option('--port <port>', 'specify a port number for server to listen').option('--host <host>', 'specify the host that the server listens to');
8792
8782
  };
8793
- async function runCLI() {
8783
+ function runCLI() {
8794
8784
  if (!process.env.NODE_ENV) {
8795
8785
  let command = process.argv[2];
8796
8786
  process.env.NODE_ENV = [
@@ -8809,11 +8799,11 @@ async function runCLI() {
8809
8799
  ].includes(level) && (logger.level = level);
8810
8800
  }
8811
8801
  let { npm_execpath } = process.env;
8812
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.13\n`);
8802
+ (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.15\n`);
8813
8803
  try {
8814
8804
  !function() {
8815
8805
  let cli = ((name = "")=>new CAC(name))('rsbuild');
8816
- cli.help(), cli.version("1.4.13"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
8806
+ cli.help(), cli.version("1.4.15"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
8817
8807
  default: 'jiti'
8818
8808
  }).option('-r, --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('-m, --mode <mode>', 'specify the build mode, can be `development`, `production` or `none`').option('--log-level <level>', 'specify the log level, can be `info`, `warn`, `error` or `silent`').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file').option('--environment <name>', 'specify the name of environment to build', {
8819
8809
  type: [
@@ -8871,5 +8861,5 @@ async function runCLI() {
8871
8861
  logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
8872
8862
  }
8873
8863
  }
8874
- let src_version = "1.4.13";
8864
+ let src_version = "1.4.15";
8875
8865
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger, mergeRsbuildConfig, rspack_rspack as rspack, runCLI, src_version as version };