@rsbuild/core 2.3.0-beta.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/m.js CHANGED
@@ -292,8 +292,8 @@ moduleFactories.add({
292
292
  };
293
293
  };
294
294
  },
295
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/index.js" (module) {
296
- let yaml, { resolve } = __rspack_createRequire_require("node:path"), config = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/lilconfig/3.1.3/8e9a79516bf61f8427342cef50cdad2cdc2572f42288ba8053b88eadfdc0ebef/node_modules/lilconfig/src/index.js"), loadOptions = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/options.js"), loadPlugins = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/plugins.js"), req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/req.js");
295
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/5cec47ed0c72adfad7e947f8ff131ef2fb4291b37a63788557685a7ae51d3648/node_modules/postcss-load-config/src/index.js" (module) {
296
+ let yaml, { resolve } = __rspack_createRequire_require("node:path"), config = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/lilconfig/3.1.3/8e9a79516bf61f8427342cef50cdad2cdc2572f42288ba8053b88eadfdc0ebef/node_modules/lilconfig/src/index.js"), loadOptions = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/5cec47ed0c72adfad7e947f8ff131ef2fb4291b37a63788557685a7ae51d3648/node_modules/postcss-load-config/src/options.js"), loadPlugins = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/5cec47ed0c72adfad7e947f8ff131ef2fb4291b37a63788557685a7ae51d3648/node_modules/postcss-load-config/src/plugins.js"), req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/5cec47ed0c72adfad7e947f8ff131ef2fb4291b37a63788557685a7ae51d3648/node_modules/postcss-load-config/src/req.js");
297
297
  async function processResult(ctx, result) {
298
298
  let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
299
299
  default: obj
@@ -366,8 +366,8 @@ moduleFactories.add({
366
366
  });
367
367
  };
368
368
  },
369
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/options.js" (module) {
370
- let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/req.js");
369
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/5cec47ed0c72adfad7e947f8ff131ef2fb4291b37a63788557685a7ae51d3648/node_modules/postcss-load-config/src/options.js" (module) {
370
+ let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/5cec47ed0c72adfad7e947f8ff131ef2fb4291b37a63788557685a7ae51d3648/node_modules/postcss-load-config/src/req.js");
371
371
  module.exports = async function options(config, file) {
372
372
  if (config.parser && 'string' == typeof config.parser) try {
373
373
  config.parser = await req(config.parser, file);
@@ -387,8 +387,8 @@ moduleFactories.add({
387
387
  return config;
388
388
  };
389
389
  },
390
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/plugins.js" (module) {
391
- let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/req.js");
390
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/5cec47ed0c72adfad7e947f8ff131ef2fb4291b37a63788557685a7ae51d3648/node_modules/postcss-load-config/src/plugins.js" (module) {
391
+ let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/5cec47ed0c72adfad7e947f8ff131ef2fb4291b37a63788557685a7ae51d3648/node_modules/postcss-load-config/src/req.js");
392
392
  async function load(plugin, options, file) {
393
393
  try {
394
394
  if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
@@ -404,7 +404,7 @@ moduleFactories.add({
404
404
  }), list;
405
405
  };
406
406
  },
407
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/req.js" (module) {
407
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/5cec47ed0c72adfad7e947f8ff131ef2fb4291b37a63788557685a7ae51d3648/node_modules/postcss-load-config/src/req.js" (module) {
408
408
  let tsx, jiti, { createRequire } = __rspack_createRequire_require("node:module"), { pathToFileURL } = __rspack_createRequire_require("node:url"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
409
409
  module.exports = async function req(name, rootFile = __rspack_import_meta_filename__) {
410
410
  let url = createRequire(rootFile).resolve(name);
@@ -2214,6 +2214,20 @@ function getRsbuildStats(statsInstance, compiler, logger, action) {
2214
2214
  let statsOptions = getStatsOptions(compiler, logger, action);
2215
2215
  return statsInstance.toJson(statsOptions);
2216
2216
  }
2217
+ function getEarlyStats(stats) {
2218
+ let entrypoints = Object.create(null);
2219
+ for (let [name, entrypoint] of stats.compilation.entrypoints){
2220
+ let chunks = [];
2221
+ for (let { id } of entrypoint.chunks)null != id && chunks.push(id);
2222
+ entrypoints[name] = {
2223
+ chunks
2224
+ };
2225
+ }
2226
+ return {
2227
+ hash: stats.hash ?? void 0,
2228
+ entrypoints
2229
+ };
2230
+ }
2217
2231
  function formatStats(stats, hasErrors, root, logger) {
2218
2232
  if (hasErrors) return {
2219
2233
  message: formatErrorMessage(getStatsErrors(stats).map((item)=>formatStatsError(item, root, 'error', logger))),
@@ -2784,6 +2798,28 @@ let withDefaultConfig = async (rootPath, userConfig)=>{
2784
2798
  await isFileExists(tsconfigPath) && (config.source.tsconfigPath = tsconfigPath);
2785
2799
  }
2786
2800
  return config;
2801
+ }, normalizePublicDirs = (rootPath, publicDir)=>{
2802
+ if (!1 === publicDir) return [];
2803
+ let defaultConfig = {
2804
+ name: join(rootPath, 'public'),
2805
+ copyOnBuild: 'auto',
2806
+ watch: !1,
2807
+ ignore: []
2808
+ };
2809
+ if (void 0 === publicDir) return [
2810
+ defaultConfig
2811
+ ];
2812
+ let mergeWithDefault = (options)=>{
2813
+ if ('' === options.name) throw Error('[rsbuild:config] `publicDir.name` cannot be empty string.');
2814
+ let merged = {
2815
+ ...defaultConfig,
2816
+ ...options
2817
+ };
2818
+ return external_node_path_isAbsolute(merged.name) || (merged.name = join(rootPath, merged.name)), merged;
2819
+ };
2820
+ return Array.isArray(publicDir) ? publicDir.map((options)=>mergeWithDefault(options)) : [
2821
+ mergeWithDefault(publicDir)
2822
+ ];
2787
2823
  }, restartPorts = new WeakMap(), exitHook_callbacks = new Set(), isCalled = !1, isRegistered = !1;
2788
2824
  function exit(exitCode, type) {
2789
2825
  if (!isCalled) {
@@ -3051,11 +3087,11 @@ function initPluginAPI({ context, pluginManager }) {
3051
3087
  if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environmentContext.name)) return;
3052
3088
  let rule = chain.module.rule(id);
3053
3089
  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);
3054
- let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs');
3055
- rule.use(id).loader(loaderPath).options({
3090
+ let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs'), use = rule.use(id).loader(loaderPath).options({
3056
3091
  id,
3057
3092
  getEnvironment: ()=>environmentContext
3058
3093
  });
3094
+ void 0 !== descriptor.codeFilter && use.set('codeFilter', descriptor.codeFilter);
3059
3095
  }
3060
3096
  });
3061
3097
  },
@@ -3214,7 +3250,7 @@ function createPublicContext(context) {
3214
3250
  async function createContext(options, userConfig, logger, loadConfigResult) {
3215
3251
  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, hooks = initHooks();
3216
3252
  return {
3217
- version: "2.3.0-beta.0",
3253
+ version: "2.3.0",
3218
3254
  rootPath,
3219
3255
  configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3220
3256
  configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
@@ -3720,29 +3756,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
3720
3756
  context,
3721
3757
  pluginManager
3722
3758
  }), await modifyRsbuildConfig(context);
3723
- let normalizedBaseConfig = (config = context.config, rootPath = context.rootPath, config.server ||= {}, config.server.host = 'string' == typeof (host = config.server.host) ? host : !0 === host ? ALL_INTERFACES_IPV4 : LOCALHOST, config.server.publicDir = ((rootPath, publicDir)=>{
3724
- if (!1 === publicDir) return [];
3725
- let defaultConfig = {
3726
- name: join(rootPath, 'public'),
3727
- copyOnBuild: 'auto',
3728
- watch: !1,
3729
- ignore: []
3730
- };
3731
- if (void 0 === publicDir) return [
3732
- defaultConfig
3733
- ];
3734
- let mergeWithDefault = (options)=>{
3735
- if ('' === options.name) throw Error('[rsbuild:config] `publicDir.name` cannot be empty string.');
3736
- let merged = {
3737
- ...defaultConfig,
3738
- ...options
3739
- };
3740
- return external_node_path_isAbsolute(merged.name) || (merged.name = join(rootPath, merged.name)), merged;
3741
- };
3742
- return Array.isArray(publicDir) ? publicDir.map((options)=>mergeWithDefault(options)) : [
3743
- mergeWithDefault(publicDir)
3744
- ];
3745
- })(rootPath, config.server.publicDir), (defaultConfig = createDefaultConfig()).mode = (()=>{
3759
+ let normalizedBaseConfig = (config = context.config, rootPath = context.rootPath, config.server ||= {}, config.server.host = 'string' == typeof (host = config.server.host) ? host : !0 === host ? ALL_INTERFACES_IPV4 : LOCALHOST, config.server.publicDir = normalizePublicDirs(rootPath, config.server.publicDir), (defaultConfig = createDefaultConfig()).mode = (()=>{
3746
3760
  if (config.mode) return config.mode;
3747
3761
  let nodeEnv = process.env.NODE_ENV || '';
3748
3762
  return 'production' === nodeEnv || 'development' === nodeEnv ? nodeEnv : 'none';
@@ -3770,13 +3784,16 @@ async function initRsbuildConfig({ context, pluginManager }) {
3770
3784
  };
3771
3785
  })(normalizedBaseConfig, context.rootPath, context.specifiedEnvironments), tsconfigPaths = new Set();
3772
3786
  for (let [name, config] of Object.entries(mergedEnvironments)){
3773
- let environmentConfig = await modifyEnvironmentConfig(context, config, name), normalizedEnvironmentConfig = {
3787
+ let environmentConfig = await modifyEnvironmentConfig(context, config, name), publicDir = environmentConfig.server?.publicDir, normalizedEnvironmentConfig = {
3774
3788
  ...environmentConfig,
3775
3789
  dev: {
3776
3790
  ...normalizedBaseConfig.dev,
3777
3791
  ...environmentConfig.dev
3778
3792
  },
3779
- server: normalizedBaseConfig.server
3793
+ server: {
3794
+ ...normalizedBaseConfig.server,
3795
+ publicDir: void 0 === publicDir ? normalizedBaseConfig.server.publicDir : normalizePublicDirs(context.rootPath, publicDir)
3796
+ }
3780
3797
  }, { tsconfigPath } = normalizedEnvironmentConfig.source;
3781
3798
  if (tsconfigPath) {
3782
3799
  let absoluteTsconfigPath = ensureAbsolutePath(context.rootPath, tsconfigPath);
@@ -4019,7 +4036,212 @@ async function createCompiler_createCompiler(options) {
4019
4036
  rspackConfigs
4020
4037
  };
4021
4038
  }
4022
- let getChokidar = cachedImport_cachedImport(()=>import("./chokidar.js").then((m)=>m.chokidar_namespaceObject)), DEFAULT_WATCH_FILE_EVENTS = [
4039
+ let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), formatPrefix = (input)=>{
4040
+ let prefix = input;
4041
+ if (prefix?.startsWith('./') && (prefix = prefix.replace('./', '')), !prefix) return '/';
4042
+ let hasLeadingSlash = prefix.startsWith('/'), hasTailSlash = prefix.endsWith('/');
4043
+ return `${hasLeadingSlash ? '' : '/'}${prefix}${hasTailSlash ? '' : '/'}`;
4044
+ }, joinUrlPath = (basePath, pathname)=>'' === basePath ? pathname : '' === pathname ? basePath : addTrailingSlash(basePath) + pathname.replace(/^\/+/, ''), getMoreEntriesMessage = (moreEntries, cliShortcutsEnabled)=>cliShortcutsEnabled ? ` ${color.dim(`... ${moreEntries} more entries, press `)}${color.bold('u + enter')}${color.dim(' to show all')}\n` : ` ${color.dim(`... ${moreEntries} more entries, set `)}${color.bold('server.printUrls.maxRoutes')}${color.dim(' to show more')}\n`, isUrlPathUnderBase = (pathname, base)=>{
4045
+ let basePath = removeTailingSlash(base);
4046
+ return '' === basePath || pathname === basePath || pathname.startsWith(`${basePath}/`);
4047
+ }, removeBasePath = (url, base)=>{
4048
+ let basePath = removeTailingSlash(base);
4049
+ if ('' === basePath || !url.startsWith(basePath)) return url;
4050
+ let nextChar = url[basePath.length];
4051
+ return void 0 === nextChar ? '/' : '/' === nextChar ? url.slice(basePath.length) : '?' === nextChar || '#' === nextChar ? `/${url.slice(basePath.length)}` : url;
4052
+ }, getRoutes = (context)=>{
4053
+ let environmentWithHtml = context.environmentList.filter((item)=>Object.keys(item.htmlPaths).length > 0);
4054
+ if (0 === environmentWithHtml.length) return [];
4055
+ let commonDistPath = getCommonParentPath(environmentWithHtml.map((item)=>item.distPath));
4056
+ return environmentWithHtml.reduce((prev, environmentContext)=>{
4057
+ let { distPath, config } = environmentContext, distPrefix = relative(commonDistPath, distPath).split(sep).join('/'), routes = formatRoutes(environmentContext.htmlPaths, context.normalizedConfig.server.base, posix.join(distPrefix, config.output.distPath.html), config.html.outputStructure);
4058
+ return prev.concat(...routes);
4059
+ }, []);
4060
+ }, formatRoutes = (entry, base, distPathPrefix, outputStructure)=>{
4061
+ let prefix = joinUrlPath(base, formatPrefix(distPathPrefix));
4062
+ return Object.keys(entry).map((entryName)=>({
4063
+ entryName,
4064
+ pathname: prefix + ('index' === entryName && 'nested' !== outputStructure ? '' : entryName)
4065
+ })).sort((a)=>'index' === a.entryName ? -1 : 1);
4066
+ }, formatName = (name)=>name ? `(${name.length > 20 ? `${name.slice(0, 19)}…` : name})` : name;
4067
+ function getURLMessages(urls, routes, { maxRoutes = 10, showAllRoutes, cliShortcutsEnabled }) {
4068
+ let prevName, routeLimit = showAllRoutes ? 1 / 0 : void 0 === maxRoutes ? 10 : 1 / 0 === maxRoutes ? maxRoutes : Math.max(0, Math.floor(maxRoutes)), printableRoutes = 0 === routeLimit ? [] : routes.slice(0, routeLimit), moreEntries = routeLimit > 0 ? routes.length - printableRoutes.length : 0, nameCount = 0;
4069
+ for (let { name } of urls)if (name && ++nameCount > 1) break;
4070
+ let showNames = nameCount > 1;
4071
+ if (routes.length <= 1 || 0 === printableRoutes.length) {
4072
+ let pathname = printableRoutes[0]?.pathname ?? '', items = urls.map(({ label, name, url })=>({
4073
+ label,
4074
+ name: showNames ? formatName(name) : void 0,
4075
+ url: normalizeUrl(`${url}${pathname}`)
4076
+ })), labelWidth = Math.max(10, ...items.map((item)=>item.label.trimEnd().length + 2)), urlWidth = Math.max(0, ...items.map((item)=>item.name ? item.url.length : 0)), message = items.map(({ label, name, url })=>{
4077
+ let prefix = `➜ ${color.dim(label.trimEnd().padEnd(labelWidth))}`, suffix = name ? `${' '.repeat(urlWidth - url.length + 2)}${color.dim(name)}` : '';
4078
+ return ` ${prefix}${color.cyan(url)}${suffix}\n`;
4079
+ }).join('');
4080
+ return moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
4081
+ }
4082
+ let message = '', prevLabel = '', entryWidth = Math.max(...printableRoutes.map((route)=>route.entryName.length));
4083
+ return urls.forEach(({ label, name, url }, index)=>{
4084
+ let shortName = showNames ? formatName(name) : void 0;
4085
+ if (prevLabel !== label || prevName !== shortName) {
4086
+ index > 0 && (message += '\n');
4087
+ let title = shortName ? `${label.trimEnd().slice(0, -1)} ${color.dim(shortName)}:` : label;
4088
+ message += ` ➜ ${title}\n`, prevLabel = label, prevName = shortName;
4089
+ }
4090
+ for (let { entryName, pathname } of printableRoutes)message += ` ${color.dim('-')} ${color.dim(entryName.padEnd(entryWidth + 4))}${color.cyan(normalizeUrl(`${url}${pathname}`))}\n`;
4091
+ }), moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
4092
+ }
4093
+ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, fallbackPathname, showAllRoutes, cliShortcutsEnabled, originalConfig, logger }) {
4094
+ if (!1 === printUrls) return null;
4095
+ let urls = originalUrls, useCustomUrl = isFunction(printUrls);
4096
+ if (useCustomUrl) {
4097
+ let newUrls = printUrls({
4098
+ urls: urls.map((item)=>item.url),
4099
+ port,
4100
+ routes,
4101
+ protocol
4102
+ });
4103
+ if (!newUrls) return null;
4104
+ if (!Array.isArray(newUrls)) throw Error(`${color.dim('[rsbuild:config]')} "server.printUrls" must return an array, but got ${typeof newUrls}.`);
4105
+ urls = newUrls.map((u)=>{
4106
+ let { url, label } = 'string' == typeof u ? {
4107
+ url: u
4108
+ } : u;
4109
+ return {
4110
+ url,
4111
+ label: label ?? getUrlLabel(url)
4112
+ };
4113
+ });
4114
+ }
4115
+ if (0 === urls.length) return null;
4116
+ let printableRoutes = 0 !== routes.length || useCustomUrl || void 0 === fallbackPathname ? routes : [
4117
+ {
4118
+ entryName: 'index',
4119
+ pathname: formatPrefix(fallbackPathname)
4120
+ }
4121
+ ];
4122
+ if (0 === printableRoutes.length && !useCustomUrl) return null;
4123
+ let printUrlsOptions = printUrls && 'object' == typeof printUrls ? printUrls : {}, message = getURLMessages(urls, printableRoutes, {
4124
+ maxRoutes: useCustomUrl ? 1 / 0 : printUrlsOptions.maxRoutes,
4125
+ showAllRoutes,
4126
+ cliShortcutsEnabled
4127
+ });
4128
+ return originalConfig && originalConfig.server?.host === void 0 && (message += ` ➜ ${color.dim('Network:')} ${color.dim('use')} ${color.bold('--host')} ${color.dim('to expose')}\n`), !0 === cliShortcutsEnabled && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
4129
+ }
4130
+ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
4131
+ 'string' == typeof port && (port = Number.parseInt(port, 10)), strictPort && (tryLimits = 1);
4132
+ let { createServer } = await import("node:net"), original = port, found = !1, attempts = 0;
4133
+ for(; !found && attempts <= tryLimits;)try {
4134
+ await new Promise((resolve, reject)=>{
4135
+ let server = createServer();
4136
+ server.unref(), server.on('error', reject), server.listen({
4137
+ port,
4138
+ host
4139
+ }, ()=>{
4140
+ if (0 === port) {
4141
+ let address = server.address();
4142
+ address && 'string' != typeof address && (port = address.port);
4143
+ }
4144
+ found = !0, server.close(resolve);
4145
+ });
4146
+ });
4147
+ } catch (e) {
4148
+ if (!(e instanceof Error) || !('code' in e) || 'EADDRINUSE' !== e.code) throw e;
4149
+ port++, attempts++;
4150
+ }
4151
+ if (!found) throw Error(`${color.dim('[rsbuild:server]')} Failed to find an available port after ${tryLimits + 1} attempts, starting from ${color.yellow(original)}.`);
4152
+ if (0 !== original && port !== original && strictPort) throw Error(`${color.dim('[rsbuild:server]')} Port ${color.yellow(original)} is occupied, please choose another one.`);
4153
+ return port;
4154
+ }, resolvePort = async (config, lastPort)=>{
4155
+ let { host, port: originalPort, strictPort } = config.server, preferredPort = 0 === originalPort ? lastPort : void 0, port = await getPort({
4156
+ host,
4157
+ port: preferredPort ?? originalPort,
4158
+ strictPort: void 0 === preferredPort && strictPort
4159
+ }), portTip = 0 !== originalPort && port !== originalPort ? `port ${originalPort} is in use, ${color.yellow(`using port ${port}.`)}` : void 0;
4160
+ return {
4161
+ port,
4162
+ portTip
4163
+ };
4164
+ }, WILDCARD_HOSTS = new Set([
4165
+ ALL_INTERFACES_IPV4,
4166
+ '::',
4167
+ '0000:0000:0000:0000:0000:0000:0000:0000'
4168
+ ]), LOOPBACK_HOSTS = new Set([
4169
+ LOCALHOST,
4170
+ '127.0.0.1',
4171
+ '::1',
4172
+ '0000:0000:0000:0000:0000:0000:0000:0001'
4173
+ ]), isLoopbackHost = (host)=>LOOPBACK_HOSTS.has(host), getHostInUrl = async (host)=>{
4174
+ if (host === ALL_INTERFACES_IPV4 || host === LOCALHOST) return LOCALHOST;
4175
+ let { isIPv6 } = await import("node:net");
4176
+ return isIPv6(host) ? '::' === host ? '[::1]' : `[${host}]` : host;
4177
+ }, concatUrl = ({ host, port, protocol })=>`${protocol}://${host}:${port}`, LOCAL_LABEL = 'Local: ', NETWORK_LABEL = 'Network: ', getUrlLabel = (url)=>{
4178
+ try {
4179
+ let { hostname } = new URL(url);
4180
+ return isLoopbackHost(hostname) ? LOCAL_LABEL : NETWORK_LABEL;
4181
+ } catch {
4182
+ return NETWORK_LABEL;
4183
+ }
4184
+ }, getAddressUrls = async ({ protocol, port, host })=>{
4185
+ if (host && !WILDCARD_HOSTS.has(host)) {
4186
+ let url = concatUrl({
4187
+ port,
4188
+ host: await getHostInUrl(host),
4189
+ protocol
4190
+ });
4191
+ return [
4192
+ {
4193
+ label: isLoopbackHost(host) ? LOCAL_LABEL : NETWORK_LABEL,
4194
+ url
4195
+ }
4196
+ ];
4197
+ }
4198
+ let urls = [], seen = new Set(), hasLocal = !1;
4199
+ for (let [name, infos] of Object.entries(node_os.networkInterfaces()))for (let info of infos ?? []){
4200
+ let family = info.family;
4201
+ !('IPv4' !== family && 4 !== family || seen.has(info.address)) && (seen.add(info.address), isLoopbackHost(info.address) || info.internal ? hasLocal || (urls.push({
4202
+ label: LOCAL_LABEL,
4203
+ url: concatUrl({
4204
+ host: LOCALHOST,
4205
+ port,
4206
+ protocol
4207
+ })
4208
+ }), hasLocal = !0) : urls.push({
4209
+ label: NETWORK_LABEL,
4210
+ name,
4211
+ url: concatUrl({
4212
+ host: info.address,
4213
+ port,
4214
+ protocol
4215
+ })
4216
+ }));
4217
+ }
4218
+ return urls;
4219
+ };
4220
+ function getServerTerminator(server) {
4221
+ let listened = !1, pendingSockets = new Set(), onConnection = (socket)=>{
4222
+ pendingSockets.add(socket), socket.on('close', ()=>{
4223
+ pendingSockets.delete(socket);
4224
+ });
4225
+ };
4226
+ return server.on('connection', onConnection), server.on('secureConnection', onConnection), server.once('listening', ()=>{
4227
+ listened = !0;
4228
+ }), ()=>new Promise((resolve, reject)=>{
4229
+ for (let socket of pendingSockets)socket.destroy();
4230
+ listened ? server.close((err)=>{
4231
+ err ? reject(err) : resolve();
4232
+ }) : resolve();
4233
+ });
4234
+ }
4235
+ function escapeHtml(text) {
4236
+ return text ? text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;') : '';
4237
+ }
4238
+ let getPublicDirPaths = (config, watchOnly = !1)=>{
4239
+ let paths = new Set();
4240
+ for (let { server } of Object.values(config.environments))for (let { name, watch } of server.publicDir)(!watchOnly || watch) && paths.add(name);
4241
+ return [
4242
+ ...paths
4243
+ ];
4244
+ }, getChokidar = cachedImport_cachedImport(()=>import("./chokidar.js").then((m)=>m.chokidar_namespaceObject)), DEFAULT_WATCH_FILE_EVENTS = [
4023
4245
  'add',
4024
4246
  'change',
4025
4247
  'unlink'
@@ -4027,7 +4249,7 @@ let getChokidar = cachedImport_cachedImport(()=>import("./chokidar.js").then((m)
4027
4249
  async function setupWatchFiles(options) {
4028
4250
  let { config, root, logger, buildManager } = options, { hmr, liveReload } = config.dev;
4029
4251
  if (!hmr && !liveReload || !buildManager) return;
4030
- let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root, logger), serverFilesWatcher = await watchServerFiles(config.server, buildManager, root, logger);
4252
+ let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root, logger), serverFilesWatcher = await watchServerFiles(config, buildManager, root, logger);
4031
4253
  return {
4032
4254
  async close () {
4033
4255
  await Promise.all([
@@ -4049,9 +4271,8 @@ async function watchDevFiles(devConfig, buildManager, root, logger) {
4049
4271
  for (let watcher of watchers)await watcher.close();
4050
4272
  };
4051
4273
  }
4052
- function watchServerFiles({ publicDir }, buildManager, root, logger) {
4053
- if (!publicDir.length) return;
4054
- let watchPaths = publicDir.filter((item)=>item.watch).map((item)=>item.name);
4274
+ function watchServerFiles(config, buildManager, root, logger) {
4275
+ let watchPaths = getPublicDirPaths(config, !0);
4055
4276
  if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), buildManager, root, logger);
4056
4277
  }
4057
4278
  function prepareWatchOptions(paths, options = {}, type, events) {
@@ -4882,7 +5103,7 @@ function parseMinifyOptions(config) {
4882
5103
  cssOptions: minify.cssOptions
4883
5104
  };
4884
5105
  }
4885
- var postcss_load_config_src_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/index.js"));
5106
+ var postcss_load_config_src_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/5cec47ed0c72adfad7e947f8ff131ef2fb4291b37a63788557685a7ae51d3648/node_modules/postcss-load-config/src/index.js"));
4886
5107
  async function getLightningCSSLoaderOptions(config, targets, minify) {
4887
5108
  let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
4888
5109
  targets,
@@ -5069,6 +5290,9 @@ function pluginExternals() {
5069
5290
  }
5070
5291
  };
5071
5292
  }
5293
+ function getAssetNames(compilation) {
5294
+ return compilation.__internal__getAssetFilenames();
5295
+ }
5072
5296
  function createAssetProcessor() {
5073
5297
  let failure, active = 0, waiting = [];
5074
5298
  return async (names, processAsset)=>{
@@ -5177,7 +5401,7 @@ let calcFileSize = (len)=>{
5177
5401
  }, COMPRESSIBLE_REGEX = /\.(?:js|mjs|cjs|jsx|ts|tsx|mts|cts|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i;
5178
5402
  async function getFileSizes(options, compilation, processAssets) {
5179
5403
  if ((!1 === options.detail || 0 === options.detail) && !1 === options.total) return [];
5180
- let { exclude, include } = options, compression = getCompression(options.compressed), fileSizes = [], compilationAssets = compilation.assets, names = Object.getOwnPropertyNames(compilationAssets);
5404
+ let { exclude, include } = options, compression = getCompression(options.compressed), fileSizes = [], compilationAssets = compilation.assets, names = getAssetNames(compilation);
5181
5405
  return await processAssets(names, async (assetName, index)=>{
5182
5406
  let queryIndex, filePath = -1 === (queryIndex = assetName.indexOf('?')) ? assetName : assetName.slice(0, queryIndex);
5183
5407
  if (!exclude && EXCLUDE_ASSET_REGEX.test(filePath)) return;
@@ -5684,205 +5908,6 @@ function getInlineTests(config) {
5684
5908
  styleTests
5685
5909
  };
5686
5910
  }
5687
- let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), formatPrefix = (input)=>{
5688
- let prefix = input;
5689
- if (prefix?.startsWith('./') && (prefix = prefix.replace('./', '')), !prefix) return '/';
5690
- let hasLeadingSlash = prefix.startsWith('/'), hasTailSlash = prefix.endsWith('/');
5691
- return `${hasLeadingSlash ? '' : '/'}${prefix}${hasTailSlash ? '' : '/'}`;
5692
- }, joinUrlPath = (basePath, pathname)=>'' === basePath ? pathname : '' === pathname ? basePath : addTrailingSlash(basePath) + pathname.replace(/^\/+/, ''), getMoreEntriesMessage = (moreEntries, cliShortcutsEnabled)=>cliShortcutsEnabled ? ` ${color.dim(`... ${moreEntries} more entries, press `)}${color.bold('u + enter')}${color.dim(' to show all')}\n` : ` ${color.dim(`... ${moreEntries} more entries, set `)}${color.bold('server.printUrls.maxRoutes')}${color.dim(' to show more')}\n`, isUrlPathUnderBase = (pathname, base)=>{
5693
- let basePath = removeTailingSlash(base);
5694
- return '' === basePath || pathname === basePath || pathname.startsWith(`${basePath}/`);
5695
- }, removeBasePath = (url, base)=>{
5696
- let basePath = removeTailingSlash(base);
5697
- if ('' === basePath || !url.startsWith(basePath)) return url;
5698
- let nextChar = url[basePath.length];
5699
- return void 0 === nextChar ? '/' : '/' === nextChar ? url.slice(basePath.length) : '?' === nextChar || '#' === nextChar ? `/${url.slice(basePath.length)}` : url;
5700
- }, getRoutes = (context)=>{
5701
- let environmentWithHtml = context.environmentList.filter((item)=>Object.keys(item.htmlPaths).length > 0);
5702
- if (0 === environmentWithHtml.length) return [];
5703
- let commonDistPath = getCommonParentPath(environmentWithHtml.map((item)=>item.distPath));
5704
- return environmentWithHtml.reduce((prev, environmentContext)=>{
5705
- let { distPath, config } = environmentContext, distPrefix = relative(commonDistPath, distPath).split(sep).join('/'), routes = formatRoutes(environmentContext.htmlPaths, context.normalizedConfig.server.base, posix.join(distPrefix, config.output.distPath.html), config.html.outputStructure);
5706
- return prev.concat(...routes);
5707
- }, []);
5708
- }, formatRoutes = (entry, base, distPathPrefix, outputStructure)=>{
5709
- let prefix = joinUrlPath(base, formatPrefix(distPathPrefix));
5710
- return Object.keys(entry).map((entryName)=>({
5711
- entryName,
5712
- pathname: prefix + ('index' === entryName && 'nested' !== outputStructure ? '' : entryName)
5713
- })).sort((a)=>'index' === a.entryName ? -1 : 1);
5714
- }, formatName = (name)=>name ? `(${name.length > 20 ? `${name.slice(0, 19)}…` : name})` : name;
5715
- function getURLMessages(urls, routes, { maxRoutes = 10, showAllRoutes, cliShortcutsEnabled }) {
5716
- let prevName, routeLimit = showAllRoutes ? 1 / 0 : void 0 === maxRoutes ? 10 : 1 / 0 === maxRoutes ? maxRoutes : Math.max(0, Math.floor(maxRoutes)), printableRoutes = 0 === routeLimit ? [] : routes.slice(0, routeLimit), moreEntries = routeLimit > 0 ? routes.length - printableRoutes.length : 0, nameCount = 0;
5717
- for (let { name } of urls)if (name && ++nameCount > 1) break;
5718
- let showNames = nameCount > 1;
5719
- if (routes.length <= 1 || 0 === printableRoutes.length) {
5720
- let pathname = printableRoutes[0]?.pathname ?? '', items = urls.map(({ label, name, url })=>({
5721
- label,
5722
- name: showNames ? formatName(name) : void 0,
5723
- url: normalizeUrl(`${url}${pathname}`)
5724
- })), labelWidth = Math.max(10, ...items.map((item)=>item.label.trimEnd().length + 2)), urlWidth = Math.max(0, ...items.map((item)=>item.name ? item.url.length : 0)), message = items.map(({ label, name, url })=>{
5725
- let prefix = `➜ ${color.dim(label.trimEnd().padEnd(labelWidth))}`, suffix = name ? `${' '.repeat(urlWidth - url.length + 2)}${color.dim(name)}` : '';
5726
- return ` ${prefix}${color.cyan(url)}${suffix}\n`;
5727
- }).join('');
5728
- return moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
5729
- }
5730
- let message = '', prevLabel = '', entryWidth = Math.max(...printableRoutes.map((route)=>route.entryName.length));
5731
- return urls.forEach(({ label, name, url }, index)=>{
5732
- let shortName = showNames ? formatName(name) : void 0;
5733
- if (prevLabel !== label || prevName !== shortName) {
5734
- index > 0 && (message += '\n');
5735
- let title = shortName ? `${label.trimEnd().slice(0, -1)} ${color.dim(shortName)}:` : label;
5736
- message += ` ➜ ${title}\n`, prevLabel = label, prevName = shortName;
5737
- }
5738
- for (let { entryName, pathname } of printableRoutes)message += ` ${color.dim('-')} ${color.dim(entryName.padEnd(entryWidth + 4))}${color.cyan(normalizeUrl(`${url}${pathname}`))}\n`;
5739
- }), moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
5740
- }
5741
- function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, fallbackPathname, showAllRoutes, cliShortcutsEnabled, originalConfig, logger }) {
5742
- if (!1 === printUrls) return null;
5743
- let urls = originalUrls, useCustomUrl = isFunction(printUrls);
5744
- if (useCustomUrl) {
5745
- let newUrls = printUrls({
5746
- urls: urls.map((item)=>item.url),
5747
- port,
5748
- routes,
5749
- protocol
5750
- });
5751
- if (!newUrls) return null;
5752
- if (!Array.isArray(newUrls)) throw Error(`${color.dim('[rsbuild:config]')} "server.printUrls" must return an array, but got ${typeof newUrls}.`);
5753
- urls = newUrls.map((u)=>{
5754
- let { url, label } = 'string' == typeof u ? {
5755
- url: u
5756
- } : u;
5757
- return {
5758
- url,
5759
- label: label ?? getUrlLabel(url)
5760
- };
5761
- });
5762
- }
5763
- if (0 === urls.length) return null;
5764
- let printableRoutes = 0 !== routes.length || useCustomUrl || void 0 === fallbackPathname ? routes : [
5765
- {
5766
- entryName: 'index',
5767
- pathname: formatPrefix(fallbackPathname)
5768
- }
5769
- ];
5770
- if (0 === printableRoutes.length && !useCustomUrl) return null;
5771
- let printUrlsOptions = printUrls && 'object' == typeof printUrls ? printUrls : {}, message = getURLMessages(urls, printableRoutes, {
5772
- maxRoutes: useCustomUrl ? 1 / 0 : printUrlsOptions.maxRoutes,
5773
- showAllRoutes,
5774
- cliShortcutsEnabled
5775
- });
5776
- return originalConfig && originalConfig.server?.host === void 0 && (message += ` ➜ ${color.dim('Network:')} ${color.dim('use')} ${color.bold('--host')} ${color.dim('to expose')}\n`), !0 === cliShortcutsEnabled && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
5777
- }
5778
- let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
5779
- 'string' == typeof port && (port = Number.parseInt(port, 10)), strictPort && (tryLimits = 1);
5780
- let { createServer } = await import("node:net"), original = port, found = !1, attempts = 0;
5781
- for(; !found && attempts <= tryLimits;)try {
5782
- await new Promise((resolve, reject)=>{
5783
- let server = createServer();
5784
- server.unref(), server.on('error', reject), server.listen({
5785
- port,
5786
- host
5787
- }, ()=>{
5788
- if (0 === port) {
5789
- let address = server.address();
5790
- address && 'string' != typeof address && (port = address.port);
5791
- }
5792
- found = !0, server.close(resolve);
5793
- });
5794
- });
5795
- } catch (e) {
5796
- if (!(e instanceof Error) || !('code' in e) || 'EADDRINUSE' !== e.code) throw e;
5797
- port++, attempts++;
5798
- }
5799
- if (!found) throw Error(`${color.dim('[rsbuild:server]')} Failed to find an available port after ${tryLimits + 1} attempts, starting from ${color.yellow(original)}.`);
5800
- if (0 !== original && port !== original && strictPort) throw Error(`${color.dim('[rsbuild:server]')} Port ${color.yellow(original)} is occupied, please choose another one.`);
5801
- return port;
5802
- }, resolvePort = async (config, lastPort)=>{
5803
- let { host, port: originalPort, strictPort } = config.server, preferredPort = 0 === originalPort ? lastPort : void 0, port = await getPort({
5804
- host,
5805
- port: preferredPort ?? originalPort,
5806
- strictPort: void 0 === preferredPort && strictPort
5807
- }), portTip = 0 !== originalPort && port !== originalPort ? `port ${originalPort} is in use, ${color.yellow(`using port ${port}.`)}` : void 0;
5808
- return {
5809
- port,
5810
- portTip
5811
- };
5812
- }, WILDCARD_HOSTS = new Set([
5813
- ALL_INTERFACES_IPV4,
5814
- '::',
5815
- '0000:0000:0000:0000:0000:0000:0000:0000'
5816
- ]), LOOPBACK_HOSTS = new Set([
5817
- LOCALHOST,
5818
- '127.0.0.1',
5819
- '::1',
5820
- '0000:0000:0000:0000:0000:0000:0000:0001'
5821
- ]), isLoopbackHost = (host)=>LOOPBACK_HOSTS.has(host), getHostInUrl = async (host)=>{
5822
- if (host === ALL_INTERFACES_IPV4 || host === LOCALHOST) return LOCALHOST;
5823
- let { isIPv6 } = await import("node:net");
5824
- return isIPv6(host) ? '::' === host ? '[::1]' : `[${host}]` : host;
5825
- }, concatUrl = ({ host, port, protocol })=>`${protocol}://${host}:${port}`, LOCAL_LABEL = 'Local: ', NETWORK_LABEL = 'Network: ', getUrlLabel = (url)=>{
5826
- try {
5827
- let { hostname } = new URL(url);
5828
- return isLoopbackHost(hostname) ? LOCAL_LABEL : NETWORK_LABEL;
5829
- } catch {
5830
- return NETWORK_LABEL;
5831
- }
5832
- }, getAddressUrls = async ({ protocol, port, host })=>{
5833
- if (host && host !== ALL_INTERFACES_IPV4) {
5834
- let url = concatUrl({
5835
- port,
5836
- host: await getHostInUrl(host),
5837
- protocol
5838
- });
5839
- return [
5840
- {
5841
- label: isLoopbackHost(host) ? LOCAL_LABEL : NETWORK_LABEL,
5842
- url
5843
- }
5844
- ];
5845
- }
5846
- let urls = [], seen = new Set(), hasLocal = !1;
5847
- for (let [name, infos] of Object.entries(node_os.networkInterfaces()))for (let info of infos ?? []){
5848
- let family = info.family;
5849
- !('IPv4' !== family && 4 !== family || seen.has(info.address)) && (seen.add(info.address), isLoopbackHost(info.address) || info.internal ? hasLocal || (urls.push({
5850
- label: LOCAL_LABEL,
5851
- url: concatUrl({
5852
- host: LOCALHOST,
5853
- port,
5854
- protocol
5855
- })
5856
- }), hasLocal = !0) : urls.push({
5857
- label: NETWORK_LABEL,
5858
- name,
5859
- url: concatUrl({
5860
- host: info.address,
5861
- port,
5862
- protocol
5863
- })
5864
- }));
5865
- }
5866
- return urls;
5867
- };
5868
- function getServerTerminator(server) {
5869
- let listened = !1, pendingSockets = new Set(), onConnection = (socket)=>{
5870
- pendingSockets.add(socket), socket.on('close', ()=>{
5871
- pendingSockets.delete(socket);
5872
- });
5873
- };
5874
- return server.on('connection', onConnection), server.on('secureConnection', onConnection), server.once('listening', ()=>{
5875
- listened = !0;
5876
- }), ()=>new Promise((resolve, reject)=>{
5877
- for (let socket of pendingSockets)socket.destroy();
5878
- listened ? server.close((err)=>{
5879
- err ? reject(err) : resolve();
5880
- }) : resolve();
5881
- });
5882
- }
5883
- function escapeHtml(text) {
5884
- return text ? text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;') : '';
5885
- }
5886
5911
  let supportedChromiumBrowsers = [
5887
5912
  'Google Chrome Canary',
5888
5913
  'Google Chrome Dev',
@@ -5993,7 +6018,7 @@ function doesChunkBelongToHtml({ chunk, htmlPluginData }) {
5993
6018
  let { options } = htmlPluginData.plugin;
5994
6019
  return recursiveChunkEntryNames(chunk).some((chunkName)=>isChunksFiltered(chunkName, options?.chunks, options?.excludeChunks));
5995
6020
  }
5996
- let getManifestPlugin = cachedImport_cachedImport(()=>import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/5e5a5791f2423171b25b8669ed999592c8e86d6947ab7c911dfb27037dbbb5ae/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
6021
+ let getManifestPlugin = cachedImport_cachedImport(()=>import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/819534ca493c81136d506932b020fc441e6eb0c1d104b422659315ed86396fc7/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
5997
6022
  function normalizeManifestObjectConfig(manifest) {
5998
6023
  let defaultOptions = {
5999
6024
  prefix: !0,
@@ -6095,7 +6120,7 @@ function extractChunks(compilation, includeType) {
6095
6120
  ];
6096
6121
  return void 0 === includeType || 'async-chunks' === includeType ? chunks.filter(isAsyncChunk) : 'initial' === includeType ? chunks.filter((chunk)=>!isAsyncChunk(chunk)) : 'all-chunks' === includeType ? chunks : 'all-assets' === includeType ? [
6097
6122
  {
6098
- files: Object.keys(compilation.assets).filter((file)=>!LICENSE_ASSET_REGEX.test(file))
6123
+ files: getAssetNames(compilation).filter((file)=>!LICENSE_ASSET_REGEX.test(file))
6099
6124
  }
6100
6125
  ] : chunks;
6101
6126
  }
@@ -6236,6 +6261,38 @@ async function applyProfile(root, filterValue, traceLayer, traceOutput) {
6236
6261
  let filter = resolveLayer(filterValue);
6237
6262
  return isTerminalTraceOutput(traceOutput) || await ensureFileDir(traceOutput), await core_rspack.experiments.globalTrace.register(filter, traceLayer, traceOutput), traceOutput;
6238
6263
  }
6264
+ let copyPublicDir = async (publicDir, distPaths, ignore)=>{
6265
+ let shouldCopy;
6266
+ if (ignore?.length) {
6267
+ let { globSync } = await getTinyglobby(), ignoredSet = new Set(globSync(ignore, {
6268
+ cwd: publicDir,
6269
+ absolute: !1,
6270
+ dot: !0,
6271
+ onlyFiles: !1
6272
+ }).map((item)=>item.replace(/\\/g, '/').replace(/\/$/, '')));
6273
+ shouldCopy = (source)=>{
6274
+ let relativePath = node_path.relative(publicDir, source);
6275
+ if (!relativePath) return !0;
6276
+ let normalizedPath = relativePath.replace(/\\/g, '/');
6277
+ return !ignoredSet.has(normalizedPath);
6278
+ };
6279
+ }
6280
+ try {
6281
+ await Promise.all(distPaths.map(async (distPath)=>{
6282
+ isDeno && node_fs.existsSync(distPath) && await node_fs.promises.rm(distPath, {
6283
+ recursive: !0,
6284
+ force: !0
6285
+ }), await node_fs.promises.cp(publicDir, distPath, {
6286
+ recursive: !0,
6287
+ dereference: !0,
6288
+ mode: node_fs.constants.COPYFILE_FICLONE,
6289
+ filter: shouldCopy
6290
+ });
6291
+ }));
6292
+ } catch (err) {
6293
+ throw err instanceof Error && (err.message = `Failed to copy public directory '${color.yellow(publicDir)}' to output directory. To disable public directory copying, set \`${color.cyan('server.publicDir: false')}\` in your config.\n${err.message}`), err;
6294
+ }
6295
+ };
6239
6296
  function getForceSplittingGroups(forceSplitting, strategy) {
6240
6297
  let cacheGroups = {};
6241
6298
  for (let [key, regexp] of Array.isArray(forceSplitting) ? forceSplitting.map((regexp, index)=>[
@@ -6518,7 +6575,11 @@ async function getFileFromUrl(url, outputFileSystem, context) {
6518
6575
  for (let [index, distPath] of distPaths.entries()){
6519
6576
  let prefix = publicPathnames[index];
6520
6577
  if (prefix && '/' !== prefix && isUrlPathUnderBase(pathname, prefix)) {
6521
- let candidatePath = node_path.join(distPath, pathname.slice(prefix.length));
6578
+ let relativePathname = pathname.slice(prefix.length);
6579
+ if (hasUpPath && UP_PATH_REGEXP.test(node_path.normalize(`./${relativePathname}`))) return {
6580
+ errorCode: 403
6581
+ };
6582
+ let candidatePath = node_path.join(distPath, relativePathname);
6522
6583
  if (hasUpPath) {
6523
6584
  let relativePath = node_path.relative(distPath, candidatePath);
6524
6585
  if (UP_PATH_REGEXP.test(relativePath)) return {
@@ -6709,21 +6770,21 @@ function sendError(res, code) {
6709
6770
  res.setHeader('Content-Length', byteLength), res.end(document);
6710
6771
  }
6711
6772
  let filterWebEnvironments = (environmentList)=>environmentList.filter((environment)=>isWebTarget(environment.config.output.target));
6712
- function createAssetsMiddleware(context, ready, outputFileSystem) {
6773
+ function createAssetsMiddleware(context, { waitForAssets, waitForBuild }, outputFileSystem) {
6713
6774
  let { logger } = context, webEnvironments = filterWebEnvironments(context.environmentList), assetContext = {
6714
6775
  ...context,
6715
6776
  environmentList: webEnvironments,
6716
6777
  publicPathnames: webEnvironments.map((environment)=>context.publicPathnames[environment.index])
6717
6778
  };
6718
6779
  return async function assetsMiddleware(req, res, next) {
6719
- async function goNext() {
6780
+ function goNext() {
6720
6781
  return new Promise((resolve)=>{
6721
- ready(()=>{
6782
+ waitForBuild(()=>{
6722
6783
  next(), resolve();
6723
6784
  });
6724
6785
  });
6725
6786
  }
6726
- req.method && 'GET' !== req.method && 'HEAD' !== req.method ? await goNext() : ready(async function processRequest() {
6787
+ req.method && 'GET' !== req.method && 'HEAD' !== req.method ? await goNext() : waitForAssets(async function processRequest() {
6727
6788
  let readStream;
6728
6789
  if (!req.url) return void await goNext();
6729
6790
  let resolved = await getFileFromUrl(req.url, outputFileSystem, assetContext);
@@ -6790,10 +6851,32 @@ function createAssetsMiddleware(context, ready, outputFileSystem) {
6790
6851
  });
6791
6852
  };
6792
6853
  }
6854
+ function setupMemoryFileSystemCleanup(fileSystem, compilers) {
6855
+ if (compilers.some((compiler)=>compiler.options.output.clean)) return;
6856
+ let lastSeenByCompiler = compilers.map(()=>new Map());
6857
+ for (let [index, compiler] of compilers.entries()){
6858
+ let lastHash, lastSeen = lastSeenByCompiler[index], generation = 0;
6859
+ compiler.hooks.afterEmit.tap('rsbuild:clean-memory-filesystem', (compilation)=>{
6860
+ if (compilation.errors.length) return;
6861
+ compilation.hash !== lastHash && (generation++, lastHash = compilation.hash);
6862
+ let outputPath = compilation.getPath(compiler.outputPath);
6863
+ for (let name of getAssetNames(compilation)){
6864
+ let queryIndex = name.indexOf('?'), filePath = join(outputPath, -1 === queryIndex ? name : name.slice(0, queryIndex));
6865
+ lastSeen.set(filePath, generation);
6866
+ }
6867
+ for (let [filePath, seen] of lastSeen)if (!(seen >= generation - 1) && (lastSeen.delete(filePath), !lastSeenByCompiler.some((assets)=>assets.has(filePath)))) try {
6868
+ fileSystem.unlinkSync(filePath);
6869
+ } catch (error) {
6870
+ if ('ENOENT' !== error.code) throw error;
6871
+ }
6872
+ });
6873
+ }
6874
+ }
6793
6875
  async function setupOutputFileSystem(writeAllToDisk, compilers) {
6794
6876
  if (!writeAllToDisk) {
6795
6877
  let { createMemoryFileSystem } = await import("./memfs.js"), outputFileSystem = createMemoryFileSystem();
6796
6878
  for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
6879
+ setupMemoryFileSystemCleanup(outputFileSystem, compilers);
6797
6880
  }
6798
6881
  let compiler = compilers.find((compiler)=>!!compiler.outputFileSystem);
6799
6882
  return compiler?.outputFileSystem ?? node_fs;
@@ -6832,7 +6915,10 @@ let noop = ()=>{}, normalizeLiveReload = (liveReload)=>'boolean' == typeof liveR
6832
6915
  } : {
6833
6916
  enabled: !0,
6834
6917
  html: !1 !== liveReload.html
6835
- }, isTsError = (error)=>'message' in error && error.stack?.includes('ts-checker-rspack-plugin');
6918
+ }, isNodeCompiler = (compiler)=>{
6919
+ let { target } = compiler.options;
6920
+ return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
6921
+ }, isTsError = (error)=>'message' in error && error.stack?.includes('ts-checker-rspack-plugin');
6836
6922
  function applyHMREntry({ config, compiler, token, resolvedHost, resolvedPort }) {
6837
6923
  var overlay;
6838
6924
  let overlay1;
@@ -6863,7 +6949,13 @@ init(
6863
6949
  }).apply(compiler);
6864
6950
  }
6865
6951
  let assets_middleware_assetsMiddleware = async ({ config, compiler, context, socketServer, resolvedPort })=>{
6866
- let watching, { logger } = context, resolvedHost = await resolveHostname(config.server.host), { environmentList } = context;
6952
+ let watching, allCompilers, webCompilers, earlyWebUpdates, { logger } = context, resolvedHost = await resolveHostname(config.server.host), { environmentList } = context, { allCompilers: allCompilers1, webCompilers: webCompilers1, earlyWebUpdates: earlyWebUpdates1 } = (earlyWebUpdates = (webCompilers = (allCompilers = compiler_isMultiCompiler(compiler) ? compiler.compilers : [
6953
+ compiler
6954
+ ]).filter((compiler)=>!isNodeCompiler(compiler))).length > 0 && webCompilers.length < allCompilers.length, {
6955
+ allCompilers,
6956
+ webCompilers,
6957
+ earlyWebUpdates
6958
+ });
6867
6959
  applyToCompiler(compiler, (compiler, index)=>{
6868
6960
  let environment = environmentList[index];
6869
6961
  if (!environment) return;
@@ -6874,19 +6966,19 @@ let assets_middleware_assetsMiddleware = async ({ config, compiler, context, soc
6874
6966
  compiler,
6875
6967
  resolvedHost,
6876
6968
  resolvedPort
6877
- }), (({ context, compiler, token, socketServer, liveReload })=>{
6878
- if (((compiler)=>{
6879
- let { target } = compiler.options;
6880
- return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
6881
- })(compiler)) return;
6882
- let errorsCount = null, warningsCount = null;
6883
- compiler.hooks.invalid.tap('rsbuild-dev-server', (fileName)=>{
6884
- errorsCount = null, warningsCount = null, 'string' == typeof fileName && fileName.endsWith('.html') && normalizeLiveReload(liveReload).html && socketServer.sendMessage({
6969
+ }), (({ context, compiler, token, socketServer, liveReload, earlyWebUpdates })=>{
6970
+ if (isNodeCompiler(compiler)) return;
6971
+ let errorsCount = null, warningsCount = null, reset = ()=>{
6972
+ errorsCount = null, warningsCount = null, socketServer.clearEnvironmentStats(token);
6973
+ };
6974
+ compiler.hooks.watchRun.tap('rsbuild-dev-server', reset), compiler.hooks.invalid.tap('rsbuild-dev-server', (fileName)=>{
6975
+ reset(), 'string' == typeof fileName && fileName.endsWith('.html') && normalizeLiveReload(liveReload).html && socketServer.sendMessage({
6885
6976
  type: 'full-reload'
6886
6977
  }, token);
6887
6978
  }), compiler.hooks.done.tap('rsbuild-dev-server', (stats)=>{
6888
6979
  let { errors, warnings } = stats.compilation;
6889
6980
  if (errors.length === errorsCount && warnings.length === warningsCount) return;
6981
+ null === errorsCount && null === warningsCount && earlyWebUpdates && !stats.hasErrors() && socketServer.onEnvironmentDone(token, ()=>getEarlyStats(stats));
6890
6982
  let isRecalled = null !== errorsCount || null !== warningsCount;
6891
6983
  if (errorsCount = errors.length, warningsCount = warnings.length, isRecalled) {
6892
6984
  let tsErrors = errors.filter(isTsError), tsWarnings = warnings.filter(isTsError);
@@ -6914,30 +7006,47 @@ let assets_middleware_assetsMiddleware = async ({ config, compiler, context, soc
6914
7006
  compiler,
6915
7007
  socketServer,
6916
7008
  token,
6917
- liveReload: environment.config.dev.liveReload
7009
+ liveReload: environment.config.dev.liveReload,
7010
+ earlyWebUpdates: earlyWebUpdates1
6918
7011
  }));
6919
7012
  });
6920
- let compilers = compiler_isMultiCompiler(compiler) ? compiler.compilers : [
6921
- compiler
6922
- ], callbacks = [], flushCallbacks = ()=>{
7013
+ let assetCallbacks = [], buildCallbacks = [], flushCallbacks = (callbacks)=>{
6923
7014
  for (let callback of callbacks.splice(0))callback();
7015
+ }, flushAllCallbacks = ()=>{
7016
+ flushCallbacks(assetCallbacks), flushCallbacks(buildCallbacks);
6924
7017
  };
6925
7018
  compiler.hooks.done.tap('rsbuild-dev-middleware', ()=>{
6926
7019
  process.nextTick(()=>{
6927
- 'done' === context.buildState.status && flushCallbacks();
7020
+ 'done' === context.buildState.status && flushAllCallbacks();
6928
7021
  });
6929
7022
  });
7023
+ let compiledWebCompilers = new Set(), isWebReady = ()=>earlyWebUpdates1 && compiledWebCompilers.size === webCompilers1.length;
7024
+ if (earlyWebUpdates1) for (let item of webCompilers1){
7025
+ let reset = ()=>{
7026
+ compiledWebCompilers.delete(item);
7027
+ };
7028
+ item.hooks.invalid.tap('rsbuild-dev-middleware', reset), item.hooks.watchRun.tap('rsbuild-dev-middleware', reset), item.hooks.done.tap('rsbuild-dev-middleware', (stats)=>{
7029
+ !stats.hasErrors() && (compiledWebCompilers.add(item), isWebReady() && process.nextTick(()=>{
7030
+ isWebReady() && flushCallbacks(assetCallbacks);
7031
+ }));
7032
+ });
7033
+ }
6930
7034
  let writeToDiskList = environmentList.map((environment)=>environment.config.dev.writeToDisk);
6931
- writeToDiskList.some(Boolean) && setupWriteToDisk(compilers, writeToDiskList, logger);
6932
- let instance = createAssetsMiddleware(context, (callback)=>{
6933
- 'done' === context.buildState.status || 'failed' === context.buildState.status ? callback() : callbacks.push(callback);
6934
- }, await setupOutputFileSystem(writeToDiskList.every((writeToDisk)=>!0 === writeToDisk), compilers));
7035
+ writeToDiskList.some(Boolean) && setupWriteToDisk(allCompilers1, writeToDiskList, logger);
7036
+ let outputFileSystem = await setupOutputFileSystem(writeToDiskList.every((writeToDisk)=>!0 === writeToDisk), allCompilers1), isBuildReady = ()=>'done' === context.buildState.status || 'failed' === context.buildState.status, instance = createAssetsMiddleware(context, {
7037
+ waitForAssets: (callback)=>{
7038
+ isBuildReady() || isWebReady() ? callback() : assetCallbacks.push(callback);
7039
+ },
7040
+ waitForBuild: (callback)=>{
7041
+ isBuildReady() ? callback() : buildCallbacks.push(callback);
7042
+ }
7043
+ }, outputFileSystem);
6935
7044
  return instance.watch = ()=>{
6936
7045
  if (compiler.watching) watching = compiler.watching;
6937
7046
  else {
6938
- let watchOptions = compilers.length > 1 ? compilers.map(({ options })=>options.watchOptions || {}) : compilers[0].options.watchOptions || {};
7047
+ let watchOptions = allCompilers1.length > 1 ? allCompilers1.map(({ options })=>options.watchOptions || {}) : allCompilers1[0].options.watchOptions || {};
6939
7048
  watching = compiler.watch(watchOptions, (error)=>{
6940
- error && (context.buildState.status = 'failed', context.buildState.hasErrors = !0, process.nextTick(flushCallbacks), error.message?.includes('× Error:') && (error.message = error.message.replace('× Error:', '').trim()), logger.error(error));
7049
+ error && (context.buildState.status = 'failed', context.buildState.hasErrors = !0, process.nextTick(flushAllCallbacks), error.message?.includes('× Error:') && (error.message = error.message.replace('× Error:', '').trim()), logger.error(error));
6941
7050
  });
6942
7051
  }
6943
7052
  }, instance.close = (callback = noop)=>{
@@ -7184,6 +7293,7 @@ class SocketServer {
7184
7293
  getOutputFileSystem;
7185
7294
  reportedBrowserLogs = new Set();
7186
7295
  currentHash = new Map();
7296
+ environmentStats = new Map();
7187
7297
  onSocketConnect;
7188
7298
  constructor(context, options, getOutputFileSystem, onSocketConnect){
7189
7299
  this.context = context, this.options = options, this.getOutputFileSystem = getOutputFileSystem, this.onSocketConnect = onSocketConnect;
@@ -7215,8 +7325,16 @@ class SocketServer {
7215
7325
  this.onConnect(socket, query.token);
7216
7326
  });
7217
7327
  }
7328
+ onEnvironmentDone(token, getStats) {
7329
+ 'done' !== this.context.buildState.status && this.socketsMap.has(token) && (this.environmentStats.set(token, getStats()), this.sendStats({
7330
+ token
7331
+ }));
7332
+ }
7333
+ clearEnvironmentStats(token) {
7334
+ this.environmentStats.delete(token);
7335
+ }
7218
7336
  onBuildDone() {
7219
- if (this.reportedBrowserLogs.clear(), this.ensureInitialChunks(), this.socketsMap.size) for (let token of this.socketsMap.keys())this.sendStats({
7337
+ if (this.environmentStats.clear(), this.reportedBrowserLogs.clear(), this.ensureInitialChunks(), this.socketsMap.size) for (let token of this.socketsMap.keys())this.sendStats({
7220
7338
  token
7221
7339
  });
7222
7340
  }
@@ -7260,7 +7378,7 @@ class SocketServer {
7260
7378
  for (let sockets of this.socketsMap.values())sockets.forEach((socket)=>{
7261
7379
  socket.close();
7262
7380
  });
7263
- return this.socketsMap.clear(), this.initialChunksMap.clear(), this.reportedBrowserLogs.clear(), new Promise((resolve, reject)=>{
7381
+ return this.socketsMap.clear(), this.initialChunksMap.clear(), this.environmentStats.clear(), this.currentHash.clear(), this.reportedBrowserLogs.clear(), new Promise((resolve, reject)=>{
7264
7382
  this.wsServer.close((err)=>{
7265
7383
  err ? reject(err) : resolve();
7266
7384
  });
@@ -7315,11 +7433,12 @@ class SocketServer {
7315
7433
  }
7316
7434
  getInitialChunks(stats) {
7317
7435
  let initialChunks = new Set(), { entrypoints } = stats;
7318
- if (!entrypoints) return initialChunks;
7436
+ if (!entrypoints) return;
7319
7437
  let entryNames = Object.keys(entrypoints);
7320
7438
  for(let entryIndex = 0; entryIndex < entryNames.length; entryIndex++){
7321
7439
  let chunks = entrypoints[entryNames[entryIndex]]?.chunks;
7322
- if (Array.isArray(chunks)) for(let index = 0; index < chunks.length; index++){
7440
+ if (!Array.isArray(chunks)) return;
7441
+ for(let index = 0; index < chunks.length; index++){
7323
7442
  let chunkName = chunks[index];
7324
7443
  void 0 !== chunkName && initialChunks.add('string' == typeof chunkName ? chunkName : String(chunkName));
7325
7444
  }
@@ -7330,10 +7449,19 @@ class SocketServer {
7330
7449
  for (let { webSocketToken } of this.context.environmentList){
7331
7450
  if (this.initialChunksMap.has(webSocketToken)) continue;
7332
7451
  let result = this.getStats(webSocketToken);
7333
- result && this.initialChunksMap.set(webSocketToken, this.getInitialChunks(result.stats));
7452
+ if (result) {
7453
+ let initialChunks = this.getInitialChunks(result.stats);
7454
+ initialChunks && this.initialChunksMap.set(webSocketToken, initialChunks);
7455
+ }
7334
7456
  }
7335
7457
  }
7336
7458
  getStats(token) {
7459
+ let environmentStats = this.environmentStats.get(token);
7460
+ if (environmentStats) return {
7461
+ stats: environmentStats,
7462
+ errors: getStatsErrors(environmentStats),
7463
+ warnings: getStatsWarnings(environmentStats)
7464
+ };
7337
7465
  let { stats } = this.context.buildState, environment = this.getEnvironmentByToken(token);
7338
7466
  if (!stats || !environment) return;
7339
7467
  let currentStats = stats;
@@ -7350,10 +7478,17 @@ class SocketServer {
7350
7478
  sendStats({ force = !1, token }) {
7351
7479
  let result = this.getStats(token);
7352
7480
  if (!result) return null;
7353
- let { stats, errors, warnings } = result, newInitialChunks = this.getInitialChunks(stats), initialChunks = this.initialChunksMap.get(token), shouldReload = stats.entrypoints && initialChunks && !isEqualSet(initialChunks, newInitialChunks);
7354
- if (this.initialChunksMap.set(token, newInitialChunks), shouldReload) return void this.sendMessage({
7481
+ let { stats, errors, warnings } = result, newInitialChunks = this.getInitialChunks(stats), initialChunks = this.initialChunksMap.get(token), shouldReload = newInitialChunks && initialChunks && !isEqualSet(initialChunks, newInitialChunks);
7482
+ if (newInitialChunks && this.initialChunksMap.set(token, newInitialChunks), shouldReload) return void this.sendMessage({
7355
7483
  type: 'full-reload'
7356
7484
  }, token);
7485
+ if (this.environmentStats.has(token)) {
7486
+ stats.hash && (this.currentHash.set(token, stats.hash), this.sendMessage({
7487
+ type: 'early-update',
7488
+ data: stats.hash
7489
+ }, token));
7490
+ return;
7491
+ }
7357
7492
  if (stats.hash) {
7358
7493
  let prevHash = this.currentHash.get(token);
7359
7494
  if (this.currentHash.set(token, stats.hash), !force && 0 === errors.length && 0 === warnings.length && prevHash === stats.hash) return void this.sendMessage({
@@ -7740,7 +7875,7 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer,
7740
7875
  let { compiler } = buildManager;
7741
7876
  (compiler_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.lazyCompilation) : compiler.options.lazyCompilation) && middlewares.use(core_rspack.lazyCompilationMiddleware(compiler));
7742
7877
  }
7743
- if (server.base && '/' !== server.base && middlewares.use(getBaseUrlMiddleware({
7878
+ server.base && '/' !== server.base && middlewares.use(getBaseUrlMiddleware({
7744
7879
  base: server.base
7745
7880
  })), middlewares.use('/__open-in-editor', async (req, res, next)=>{
7746
7881
  try {
@@ -7801,7 +7936,7 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer,
7801
7936
  try {
7802
7937
  for(let key in environments){
7803
7938
  res.write(`<h2>Environment: ${key}</h2>`);
7804
- let list = [], environment = environments[key], stats = await environment.getStats(), assets = Object.keys(stats.compilation.assets);
7939
+ let list = [], environment = environments[key], stats = await environment.getStats(), assets = getAssetNames(stats.compilation);
7805
7940
  for (let asset of (res.write('<ul>'), assets))list.push(`<li><a target="_blank" href="${asset}">${asset}</a></li>`);
7806
7941
  res.write(list?.join('')), res.write('</ul>');
7807
7942
  }
@@ -7823,9 +7958,11 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer,
7823
7958
  context.distPath
7824
7959
  ],
7825
7960
  outputFileSystem: buildManager.outputFileSystem
7826
- })), server.publicDir.length) {
7961
+ }));
7962
+ let publicDirPaths = getPublicDirPaths(config);
7963
+ if (publicDirPaths.length) {
7827
7964
  let { default: sirv } = await import("./sirv.js");
7828
- for (let { name } of server.publicDir){
7965
+ for (let name of publicDirPaths){
7829
7966
  let sirvMiddleware = sirv(name, {
7830
7967
  etag: !0,
7831
7968
  dev: !0
@@ -8512,7 +8649,10 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8512
8649
  server: previewServer,
8513
8650
  environments: context.environments
8514
8651
  });
8515
- let webEnvironments = filterWebEnvironments(context.environmentList), assetsMiddleware = createAssetsMiddleware(context, (callback)=>callback(), node_fs), htmlMiddlewareOptions = {
8652
+ let webEnvironments = filterWebEnvironments(context.environmentList), assetsMiddleware = createAssetsMiddleware(context, {
8653
+ waitForAssets: (callback)=>callback(),
8654
+ waitForBuild: (callback)=>callback()
8655
+ }, node_fs), htmlMiddlewareOptions = {
8516
8656
  assetsMiddleware,
8517
8657
  distPaths: webEnvironments.map((environment)=>environment.distPath),
8518
8658
  outputFileSystem: node_fs
@@ -8937,7 +9077,7 @@ function applyDefaultPlugins(pluginManager, context) {
8937
9077
  {
8938
9078
  name: 'rsbuild:html',
8939
9079
  setup (api) {
8940
- let defaultFavicon;
9080
+ let defaultFaviconCache = new Map();
8941
9081
  api.modifyBundlerChain(async (chain, { HtmlPlugin, CHAIN_ID, environment })=>{
8942
9082
  let { config, htmlPaths } = environment;
8943
9083
  if (0 === Object.keys(htmlPaths).length) return;
@@ -8969,17 +9109,18 @@ function applyDefaultPlugins(pluginManager, context) {
8969
9109
  };
8970
9110
  })(environment.config);
8971
9111
  tagConfig && (extraData.tagConfig = tagConfig), pluginOptions.title = await getTitle(entryName, config);
8972
- let favicon = await getFavicon(entryName, config) || (()=>{
8973
- if (defaultFavicon) return defaultFavicon;
8974
- let { publicDir } = api.getNormalizedConfig().server, extensions = [
9112
+ let favicon = await getFavicon(entryName, config) || ((config)=>{
9113
+ let { publicDir } = config.server, extensions = [
8975
9114
  'ico',
8976
9115
  'png',
8977
9116
  'svg'
8978
- ], publicDirs = Array.from(new Set(publicDir.map(({ name })=>name))), faviconPaths = [];
9117
+ ], publicDirs = Array.from(new Set(publicDir.map(({ name })=>name))), key = JSON.stringify(publicDirs), defaultFavicon = defaultFaviconCache.get(key);
9118
+ if (defaultFavicon) return defaultFavicon;
9119
+ let faviconPaths = [];
8979
9120
  for (let publicDir of publicDirs)for (let ext of extensions)faviconPaths.push(node_path.join(publicDir, `favicon.${ext}`));
8980
9121
  let faviconPath = findExists(faviconPaths);
8981
- return faviconPath && (defaultFavicon = faviconPath), defaultFavicon;
8982
- })();
9122
+ if (faviconPath) return defaultFaviconCache.set(key, faviconPath), faviconPath;
9123
+ })(config);
8983
9124
  favicon && (extraData.favicon = favicon);
8984
9125
  let finalOptions = await reduceConfigsWithContext({
8985
9126
  initial: pluginOptions,
@@ -9693,39 +9834,22 @@ try {
9693
9834
  }
9694
9835
  };
9695
9836
  api.onAfterStartDevServer(onStartServer), api.onAfterStartPreviewServer(onStartServer), api.onBeforeBuild(async ({ isFirstCompile, environments })=>{
9696
- if (isFirstCompile) for (let { name: publicDir, copyOnBuild, ignore } of api.getNormalizedConfig().server.publicDir){
9697
- let shouldCopy;
9837
+ if (!isFirstCompile) return;
9838
+ let groups = new Map();
9839
+ for (let environment of Object.values(environments)){
9840
+ let key = JSON.stringify(environment.config.server.publicDir.map(({ name, copyOnBuild, ignore })=>[
9841
+ name,
9842
+ copyOnBuild,
9843
+ ignore
9844
+ ])), group = groups.get(key);
9845
+ group ? group.push(environment) : groups.set(key, [
9846
+ environment
9847
+ ]);
9848
+ }
9849
+ for (let group of groups.values())for (let { name: publicDir, copyOnBuild, ignore } of group[0].config.server.publicDir){
9698
9850
  if (!1 === copyOnBuild || !node_fs.existsSync(publicDir)) continue;
9699
- let distPaths = dedupeNestedPaths(Object.values(environments).filter(({ config })=>!0 === copyOnBuild || 'auto' === copyOnBuild && 'node' !== config.output.target).map(({ distPath })=>distPath));
9700
- if (ignore?.length) {
9701
- let { globSync } = await getTinyglobby(), ignoredSet = new Set(globSync(ignore, {
9702
- cwd: publicDir,
9703
- absolute: !1,
9704
- dot: !0,
9705
- onlyFiles: !1
9706
- }).map((item)=>item.replace(/\\/g, '/').replace(/\/$/, '')));
9707
- shouldCopy = (source)=>{
9708
- let relativePath = node_path.relative(publicDir, source);
9709
- if (!relativePath) return !0;
9710
- let normalizedPath = relativePath.replace(/\\/g, '/');
9711
- return !ignoredSet.has(normalizedPath);
9712
- };
9713
- }
9714
- try {
9715
- await Promise.all(distPaths.map(async (distPath)=>{
9716
- isDeno && node_fs.existsSync(distPath) && await node_fs.promises.rm(distPath, {
9717
- recursive: !0,
9718
- force: !0
9719
- }), await node_fs.promises.cp(publicDir, distPath, {
9720
- recursive: !0,
9721
- dereference: !0,
9722
- mode: node_fs.constants.COPYFILE_FICLONE,
9723
- filter: shouldCopy
9724
- });
9725
- }));
9726
- } catch (err) {
9727
- throw err instanceof Error && (err.message = `Failed to copy public directory '${color.yellow(publicDir)}' to output directory. To disable public directory copying, set \`${color.cyan('server.publicDir: false')}\` in your config.\n${err.message}`), err;
9728
- }
9851
+ let distPaths = dedupeNestedPaths(group.filter(({ config })=>!0 === copyOnBuild || 'node' !== config.output.target).map(({ distPath })=>distPath));
9852
+ 0 !== distPaths.length && await copyPublicDir(publicDir, distPaths, ignore);
9729
9853
  }
9730
9854
  });
9731
9855
  }
@@ -10293,7 +10417,7 @@ let applyServerOptions = (command)=>{
10293
10417
  };
10294
10418
  function setupCommands(argv) {
10295
10419
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10296
- cli.version("2.3.0-beta.0"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10420
+ cli.version("2.3.0"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10297
10421
  default: 'auto'
10298
10422
  }).option('--dist-path <dir>', 'Set the root directory of output files').option('--source-map', 'Enable source map').option('--env-dir <dir>', 'Set the directory for loading `.env` files').option('--env-mode <mode>', 'Set the env mode to load the `.env.[mode]` file').option('--environment <name>', 'Set the environment name(s) to build', {
10299
10423
  type: [
@@ -10358,7 +10482,7 @@ function setupCommands(argv) {
10358
10482
  }
10359
10483
  function showGreeting() {
10360
10484
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10361
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.3.0-beta.0\n`);
10485
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.3.0\n`);
10362
10486
  }
10363
10487
  function setupLogLevel(argv) {
10364
10488
  if (argv.length <= 3) return;
@@ -10380,5 +10504,5 @@ function runCLI({ argv = process.argv } = {}) {
10380
10504
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10381
10505
  }
10382
10506
  }
10383
- let src_version = "2.3.0-beta.0";
10507
+ let src_version = "2.3.0";
10384
10508
  export { core_rspack as rspack, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger_createLogger as createLogger, mergeRsbuildConfig, mrmime_lookup, runCLI, src_logger as logger, src_version as version };