@rsbuild/core 2.2.14 → 2.3.0-rc.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
@@ -13,6 +13,7 @@ import { isPromise, isRegExp } from "node:util/types";
13
13
  import { readFile } from "node:fs/promises";
14
14
  import node_zlib, { constants as external_node_zlib_constants } from "node:zlib";
15
15
  import { once as external_node_events_once } from "node:events";
16
+ import { finished } from "node:stream";
16
17
  import { isIP } from "node:net";
17
18
  import { ALL_INTERFACES_IPV4, IMAGE_EXTENSIONS, ASSETS_DIST_DIR, FONT_DIST_DIR, AUDIO_EXTENSIONS, ensureAbsolutePath, NODE_MODULES_REGEX, FONT_EXTENSIONS, HMR_SOCKET_PATH, WASM_DIST_DIR, VIDEO_EXTENSIONS, BROWSER_LOG_PREFIX, toPosixPath, TRACK_EXTENSIONS, IMAGE_DIST_DIR, RSBUILD_OUTPUTS_PATH, DEFAULT_STACK_TRACE, LOADER_PATH, ASSET_EXTENSIONS, SVG_DIST_DIR, isWindows, COMPILED_PATH, WORKER_QUERY_REGEX, TS_CONFIG_FILE, dedupeNestedPaths, CSS_REGEX, relativeWithin, LAZY_COMPILATION_IDENTIFIER, DEFAULT_BROWSERSLIST, JS_REGEX, MEDIA_DIST_DIR, SCRIPT_REGEX, DEFAULT_WEB_BROWSERSLIST, getCompiledPath, normalizeRuleConditionPath, getPathnameFromUrl, toRelativePath, isDeno, CSS_DIST_DIR, INLINE_QUERY_REGEX, STATIC_PATH, RAW_QUERY_REGEX, PLUGIN_SWC_NAME, CLIENT_PATH, getCommonParentPath, LOCALHOST, JS_DIST_DIR, URL_QUERY_REGEX } from "./1.js";
18
19
  import { cachedImport as cachedImport_cachedImport, getTinyglobby } from "./r.js";
@@ -121,39 +122,6 @@ moduleFactories.add({
121
122
  }
122
123
  module.exports.f = expand;
123
124
  },
124
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ee-first/1.1.1/7d7aff2abffb03f454b885edc2f03bd078376c8cde75af0c324753fee26268de/node_modules/ee-first/index.js" (module) {
125
- function listener(event, done) {
126
- return function onevent(arg1) {
127
- for(var args = Array(arguments.length), i = 0; i < args.length; i++)args[i] = arguments[i];
128
- done('error' === event ? arg1 : null, this, event, args);
129
- };
130
- }
131
- module.exports = function first(stuff, done) {
132
- if (!Array.isArray(stuff)) throw TypeError('arg must be an array of [ee, events...] arrays');
133
- for(var cleanups = [], i = 0; i < stuff.length; i++){
134
- var arr = stuff[i];
135
- if (!Array.isArray(arr) || arr.length < 2) throw TypeError('each array member must be [ee, events...]');
136
- for(var ee = arr[0], j = 1; j < arr.length; j++){
137
- var event = arr[j], fn = listener(event, callback);
138
- ee.on(event, fn), cleanups.push({
139
- ee: ee,
140
- event: event,
141
- fn: fn
142
- });
143
- }
144
- }
145
- function callback() {
146
- cleanup(), done.apply(null, arguments);
147
- }
148
- function cleanup() {
149
- for(var x, i = 0; i < cleanups.length; i++)(x = cleanups[i]).ee.removeListener(x.event, x.fn);
150
- }
151
- function thunk(fn) {
152
- done = fn;
153
- }
154
- return thunk.cancel = cleanup, thunk;
155
- };
156
- },
157
125
  "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/lilconfig/3.1.3/8e9a79516bf61f8427342cef50cdad2cdc2572f42288ba8053b88eadfdc0ebef/node_modules/lilconfig/src/index.js" (module) {
158
126
  let path = __rspack_createRequire_require("path"), fs = __rspack_createRequire_require("fs"), os = __rspack_createRequire_require("os"), url = __rspack_createRequire_require("url"), fsReadFileAsync = fs.promises.readFile;
159
127
  function getDefaultSearchPlaces(name, sync) {
@@ -324,74 +292,8 @@ moduleFactories.add({
324
292
  };
325
293
  };
326
294
  },
327
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/on-finished/2.4.1/cf4b90e733493a0ce70ba421a5b37153ad39360f9513e36b25d2e49f57047a9b/node_modules/on-finished/index.js" (module) {
328
- module.exports = onFinished, module.exports.isFinished = isFinished;
329
- var asyncHooks = tryRequireAsyncHooks(), first = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ee-first/1.1.1/7d7aff2abffb03f454b885edc2f03bd078376c8cde75af0c324753fee26268de/node_modules/ee-first/index.js"), defer = 'function' == typeof setImmediate ? setImmediate : function(fn) {
330
- process.nextTick(fn.bind.apply(fn, arguments));
331
- };
332
- function onFinished(msg, listener) {
333
- return !1 !== isFinished(msg) ? defer(listener, null, msg) : attachListener(msg, wrap(listener)), msg;
334
- }
335
- function isFinished(msg) {
336
- var socket = msg.socket;
337
- return 'boolean' == typeof msg.finished ? !!(msg.finished || socket && !socket.writable) : 'boolean' == typeof msg.complete ? !!(msg.upgrade || !socket || !socket.readable || msg.complete && !msg.readable) : void 0;
338
- }
339
- function attachFinishedListener(msg, callback) {
340
- var eeMsg, eeSocket, finished = !1;
341
- function onFinish(error) {
342
- eeMsg.cancel(), eeSocket.cancel(), finished = !0, callback(error);
343
- }
344
- function onSocket(socket) {
345
- msg.removeListener('socket', onSocket), finished || eeMsg === eeSocket && (eeSocket = first([
346
- [
347
- socket,
348
- 'error',
349
- 'close'
350
- ]
351
- ], onFinish));
352
- }
353
- (eeMsg = eeSocket = first([
354
- [
355
- msg,
356
- 'end',
357
- 'finish'
358
- ]
359
- ], onFinish), msg.socket) ? onSocket(msg.socket) : (msg.on('socket', onSocket), void 0 === msg.socket && patchAssignSocket(msg, onSocket));
360
- }
361
- function attachListener(msg, listener) {
362
- var attached = msg.__onFinished;
363
- attached && attached.queue || (attached = msg.__onFinished = createListener(msg), attachFinishedListener(msg, attached)), attached.queue.push(listener);
364
- }
365
- function createListener(msg) {
366
- function listener(err) {
367
- if (msg.__onFinished === listener && (msg.__onFinished = null), listener.queue) {
368
- var queue = listener.queue;
369
- listener.queue = null;
370
- for(var i = 0; i < queue.length; i++)queue[i](err, msg);
371
- }
372
- }
373
- return listener.queue = [], listener;
374
- }
375
- function patchAssignSocket(res, callback) {
376
- var assignSocket = res.assignSocket;
377
- 'function' == typeof assignSocket && (res.assignSocket = function _assignSocket(socket) {
378
- assignSocket.call(this, socket), callback(socket);
379
- });
380
- }
381
- function tryRequireAsyncHooks() {
382
- try {
383
- return rspackRequire("async_hooks");
384
- } catch (e) {
385
- return {};
386
- }
387
- }
388
- function wrap(fn) {
389
- var res;
390
- return (asyncHooks.AsyncResource && (res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn')), res && res.runInAsyncScope) ? res.runInAsyncScope.bind(res, fn, null) : fn;
391
- }
392
- },
393
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/index.js" (module) {
394
- 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");
395
297
  async function processResult(ctx, result) {
396
298
  let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
397
299
  default: obj
@@ -464,8 +366,8 @@ moduleFactories.add({
464
366
  });
465
367
  };
466
368
  },
467
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/options.js" (module) {
468
- 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");
469
371
  module.exports = async function options(config, file) {
470
372
  if (config.parser && 'string' == typeof config.parser) try {
471
373
  config.parser = await req(config.parser, file);
@@ -485,8 +387,8 @@ moduleFactories.add({
485
387
  return config;
486
388
  };
487
389
  },
488
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/cbcc4ffbb08c543cea9a1ac750ccfc742d666712f0530b683d312c61ffd50060/node_modules/postcss-load-config/src/plugins.js" (module) {
489
- 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");
490
392
  async function load(plugin, options, file) {
491
393
  try {
492
394
  if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
@@ -502,7 +404,7 @@ moduleFactories.add({
502
404
  }), list;
503
405
  };
504
406
  },
505
- "../../../../../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) {
506
408
  let tsx, jiti, { createRequire } = __rspack_createRequire_require("node:module"), { pathToFileURL } = __rspack_createRequire_require("node:url"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
507
409
  module.exports = async function req(name, rootFile = __rspack_import_meta_filename__) {
508
410
  let url = createRequire(rootFile).resolve(name);
@@ -531,9 +433,6 @@ moduleFactories.add({
531
433
  throw Error(`'tsx' or 'jiti' is required for the TypeScript configuration files. Make sure it is installed\nError: ${importError.map((error)=>error.message).join('\n')}`);
532
434
  };
533
435
  },
534
- async_hooks (module) {
535
- module.exports = __rspack_createRequire_require("async_hooks");
536
- },
537
436
  process (module) {
538
437
  module.exports = __rspack_createRequire_require("process");
539
438
  },
@@ -2429,6 +2328,7 @@ function initHooks() {
2429
2328
  onBeforeDevCompile: createAsyncHook(),
2430
2329
  onAfterDevCompile: createAsyncHook(),
2431
2330
  onCloseDevServer: createAsyncHook(),
2331
+ onClosePreviewServer: createAsyncHook(),
2432
2332
  onAfterStartDevServer: createAsyncHook(),
2433
2333
  onBeforeStartDevServer: createAsyncHook(),
2434
2334
  onAfterStartPreviewServer: createAsyncHook(),
@@ -2884,6 +2784,28 @@ let withDefaultConfig = async (rootPath, userConfig)=>{
2884
2784
  await isFileExists(tsconfigPath) && (config.source.tsconfigPath = tsconfigPath);
2885
2785
  }
2886
2786
  return config;
2787
+ }, normalizePublicDirs = (rootPath, publicDir)=>{
2788
+ if (!1 === publicDir) return [];
2789
+ let defaultConfig = {
2790
+ name: join(rootPath, 'public'),
2791
+ copyOnBuild: 'auto',
2792
+ watch: !1,
2793
+ ignore: []
2794
+ };
2795
+ if (void 0 === publicDir) return [
2796
+ defaultConfig
2797
+ ];
2798
+ let mergeWithDefault = (options)=>{
2799
+ if ('' === options.name) throw Error('[rsbuild:config] `publicDir.name` cannot be empty string.');
2800
+ let merged = {
2801
+ ...defaultConfig,
2802
+ ...options
2803
+ };
2804
+ return external_node_path_isAbsolute(merged.name) || (merged.name = join(rootPath, merged.name)), merged;
2805
+ };
2806
+ return Array.isArray(publicDir) ? publicDir.map((options)=>mergeWithDefault(options)) : [
2807
+ mergeWithDefault(publicDir)
2808
+ ];
2887
2809
  }, restartPorts = new WeakMap(), exitHook_callbacks = new Set(), isCalled = !1, isRegistered = !1;
2888
2810
  function exit(exitCode, type) {
2889
2811
  if (!isCalled) {
@@ -3151,11 +3073,11 @@ function initPluginAPI({ context, pluginManager }) {
3151
3073
  if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environmentContext.name)) return;
3152
3074
  let rule = chain.module.rule(id);
3153
3075
  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);
3154
- let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs');
3155
- rule.use(id).loader(loaderPath).options({
3076
+ let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs'), use = rule.use(id).loader(loaderPath).options({
3156
3077
  id,
3157
3078
  getEnvironment: ()=>environmentContext
3158
3079
  });
3080
+ void 0 !== descriptor.codeFilter && use.set('codeFilter', descriptor.codeFilter);
3159
3081
  }
3160
3082
  });
3161
3083
  },
@@ -3185,6 +3107,7 @@ function initPluginAPI({ context, pluginManager }) {
3185
3107
  onCloseBuild: hooks.onCloseBuild.tap,
3186
3108
  onBeforeBuild: hooks.onBeforeBuild.tap,
3187
3109
  onCloseDevServer: hooks.onCloseDevServer.tap,
3110
+ onClosePreviewServer: hooks.onClosePreviewServer.tap,
3188
3111
  onBeforeDevCompile: hooks.onBeforeDevCompile.tap,
3189
3112
  onAfterDevCompile: hooks.onAfterDevCompile.tap,
3190
3113
  onDevCompileDone: hooks.onAfterDevCompile.tap,
@@ -3313,7 +3236,7 @@ function createPublicContext(context) {
3313
3236
  async function createContext(options, userConfig, logger, loadConfigResult) {
3314
3237
  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();
3315
3238
  return {
3316
- version: "2.2.14",
3239
+ version: "2.3.0-rc.0",
3317
3240
  rootPath,
3318
3241
  configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3319
3242
  configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
@@ -3819,29 +3742,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
3819
3742
  context,
3820
3743
  pluginManager
3821
3744
  }), await modifyRsbuildConfig(context);
3822
- 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)=>{
3823
- if (!1 === publicDir) return [];
3824
- let defaultConfig = {
3825
- name: join(rootPath, 'public'),
3826
- copyOnBuild: 'auto',
3827
- watch: !1,
3828
- ignore: []
3829
- };
3830
- if (void 0 === publicDir) return [
3831
- defaultConfig
3832
- ];
3833
- let mergeWithDefault = (options)=>{
3834
- if ('' === options.name) throw Error('[rsbuild:config] `publicDir.name` cannot be empty string.');
3835
- let merged = {
3836
- ...defaultConfig,
3837
- ...options
3838
- };
3839
- return external_node_path_isAbsolute(merged.name) || (merged.name = join(rootPath, merged.name)), merged;
3840
- };
3841
- return Array.isArray(publicDir) ? publicDir.map((options)=>mergeWithDefault(options)) : [
3842
- mergeWithDefault(publicDir)
3843
- ];
3844
- })(rootPath, config.server.publicDir), (defaultConfig = createDefaultConfig()).mode = (()=>{
3745
+ 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 = (()=>{
3845
3746
  if (config.mode) return config.mode;
3846
3747
  let nodeEnv = process.env.NODE_ENV || '';
3847
3748
  return 'production' === nodeEnv || 'development' === nodeEnv ? nodeEnv : 'none';
@@ -3869,13 +3770,16 @@ async function initRsbuildConfig({ context, pluginManager }) {
3869
3770
  };
3870
3771
  })(normalizedBaseConfig, context.rootPath, context.specifiedEnvironments), tsconfigPaths = new Set();
3871
3772
  for (let [name, config] of Object.entries(mergedEnvironments)){
3872
- let environmentConfig = await modifyEnvironmentConfig(context, config, name), normalizedEnvironmentConfig = {
3773
+ let environmentConfig = await modifyEnvironmentConfig(context, config, name), publicDir = environmentConfig.server?.publicDir, normalizedEnvironmentConfig = {
3873
3774
  ...environmentConfig,
3874
3775
  dev: {
3875
3776
  ...normalizedBaseConfig.dev,
3876
3777
  ...environmentConfig.dev
3877
3778
  },
3878
- server: normalizedBaseConfig.server
3779
+ server: {
3780
+ ...normalizedBaseConfig.server,
3781
+ publicDir: void 0 === publicDir ? normalizedBaseConfig.server.publicDir : normalizePublicDirs(context.rootPath, publicDir)
3782
+ }
3879
3783
  }, { tsconfigPath } = normalizedEnvironmentConfig.source;
3880
3784
  if (tsconfigPath) {
3881
3785
  let absoluteTsconfigPath = ensureAbsolutePath(context.rootPath, tsconfigPath);
@@ -4010,7 +3914,7 @@ async function createCompiler_createCompiler(options) {
4010
3914
  }), compiler.hooks.watchRun.tap(HOOK_NAME, (compiler)=>{
4011
3915
  startTime = Date.now(), context.buildState.status = 'building', logRspackVersion(), isCompiling || printBuildLog(compiler, context, lazyModules), lazyModules.size && lazyModules.clear(), isCompiling = !0;
4012
3916
  }), compiler.hooks.invalid.tap(HOOK_NAME, ()=>{
4013
- hasFatalError = !1, context.buildState.stats = null, context.buildState.status = 'idle', context.buildState.hasErrors = !1;
3917
+ hasFatalError = !1, context.buildState.stats = null, context.buildState.status = 'idle', context.buildState.hasErrors = !1, context.socketServer?.clearEnvironmentStats();
4014
3918
  }), compilers))item.hooks.failed.tap(HOOK_NAME, ()=>{
4015
3919
  hasFatalError = !0, context.buildState.hasErrors = !0, finishFatalBuild();
4016
3920
  }), item.hooks.afterDone.tap(HOOK_NAME, finishFatalBuild), item.hooks.watchClose.tap(HOOK_NAME, finishFatalBuild);
@@ -4118,7 +4022,212 @@ async function createCompiler_createCompiler(options) {
4118
4022
  rspackConfigs
4119
4023
  };
4120
4024
  }
4121
- let getChokidar = cachedImport_cachedImport(()=>import("./chokidar.js").then((m)=>m.chokidar_namespaceObject)), DEFAULT_WATCH_FILE_EVENTS = [
4025
+ let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), formatPrefix = (input)=>{
4026
+ let prefix = input;
4027
+ if (prefix?.startsWith('./') && (prefix = prefix.replace('./', '')), !prefix) return '/';
4028
+ let hasLeadingSlash = prefix.startsWith('/'), hasTailSlash = prefix.endsWith('/');
4029
+ return `${hasLeadingSlash ? '' : '/'}${prefix}${hasTailSlash ? '' : '/'}`;
4030
+ }, 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)=>{
4031
+ let basePath = removeTailingSlash(base);
4032
+ return '' === basePath || pathname === basePath || pathname.startsWith(`${basePath}/`);
4033
+ }, removeBasePath = (url, base)=>{
4034
+ let basePath = removeTailingSlash(base);
4035
+ if ('' === basePath || !url.startsWith(basePath)) return url;
4036
+ let nextChar = url[basePath.length];
4037
+ return void 0 === nextChar ? '/' : '/' === nextChar ? url.slice(basePath.length) : '?' === nextChar || '#' === nextChar ? `/${url.slice(basePath.length)}` : url;
4038
+ }, getRoutes = (context)=>{
4039
+ let environmentWithHtml = context.environmentList.filter((item)=>Object.keys(item.htmlPaths).length > 0);
4040
+ if (0 === environmentWithHtml.length) return [];
4041
+ let commonDistPath = getCommonParentPath(environmentWithHtml.map((item)=>item.distPath));
4042
+ return environmentWithHtml.reduce((prev, environmentContext)=>{
4043
+ 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);
4044
+ return prev.concat(...routes);
4045
+ }, []);
4046
+ }, formatRoutes = (entry, base, distPathPrefix, outputStructure)=>{
4047
+ let prefix = joinUrlPath(base, formatPrefix(distPathPrefix));
4048
+ return Object.keys(entry).map((entryName)=>({
4049
+ entryName,
4050
+ pathname: prefix + ('index' === entryName && 'nested' !== outputStructure ? '' : entryName)
4051
+ })).sort((a)=>'index' === a.entryName ? -1 : 1);
4052
+ }, formatName = (name)=>name ? `(${name.length > 20 ? `${name.slice(0, 19)}…` : name})` : name;
4053
+ function getURLMessages(urls, routes, { maxRoutes = 10, showAllRoutes, cliShortcutsEnabled }) {
4054
+ 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;
4055
+ for (let { name } of urls)if (name && ++nameCount > 1) break;
4056
+ let showNames = nameCount > 1;
4057
+ if (routes.length <= 1 || 0 === printableRoutes.length) {
4058
+ let pathname = printableRoutes[0]?.pathname ?? '', items = urls.map(({ label, name, url })=>({
4059
+ label,
4060
+ name: showNames ? formatName(name) : void 0,
4061
+ url: normalizeUrl(`${url}${pathname}`)
4062
+ })), 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 })=>{
4063
+ let prefix = `➜ ${color.dim(label.trimEnd().padEnd(labelWidth))}`, suffix = name ? `${' '.repeat(urlWidth - url.length + 2)}${color.dim(name)}` : '';
4064
+ return ` ${prefix}${color.cyan(url)}${suffix}\n`;
4065
+ }).join('');
4066
+ return moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
4067
+ }
4068
+ let message = '', prevLabel = '', entryWidth = Math.max(...printableRoutes.map((route)=>route.entryName.length));
4069
+ return urls.forEach(({ label, name, url }, index)=>{
4070
+ let shortName = showNames ? formatName(name) : void 0;
4071
+ if (prevLabel !== label || prevName !== shortName) {
4072
+ index > 0 && (message += '\n');
4073
+ let title = shortName ? `${label.trimEnd().slice(0, -1)} ${color.dim(shortName)}:` : label;
4074
+ message += ` ➜ ${title}\n`, prevLabel = label, prevName = shortName;
4075
+ }
4076
+ for (let { entryName, pathname } of printableRoutes)message += ` ${color.dim('-')} ${color.dim(entryName.padEnd(entryWidth + 4))}${color.cyan(normalizeUrl(`${url}${pathname}`))}\n`;
4077
+ }), moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
4078
+ }
4079
+ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, fallbackPathname, showAllRoutes, cliShortcutsEnabled, originalConfig, logger }) {
4080
+ if (!1 === printUrls) return null;
4081
+ let urls = originalUrls, useCustomUrl = isFunction(printUrls);
4082
+ if (useCustomUrl) {
4083
+ let newUrls = printUrls({
4084
+ urls: urls.map((item)=>item.url),
4085
+ port,
4086
+ routes,
4087
+ protocol
4088
+ });
4089
+ if (!newUrls) return null;
4090
+ if (!Array.isArray(newUrls)) throw Error(`${color.dim('[rsbuild:config]')} "server.printUrls" must return an array, but got ${typeof newUrls}.`);
4091
+ urls = newUrls.map((u)=>{
4092
+ let { url, label } = 'string' == typeof u ? {
4093
+ url: u
4094
+ } : u;
4095
+ return {
4096
+ url,
4097
+ label: label ?? getUrlLabel(url)
4098
+ };
4099
+ });
4100
+ }
4101
+ if (0 === urls.length) return null;
4102
+ let printableRoutes = 0 !== routes.length || useCustomUrl || void 0 === fallbackPathname ? routes : [
4103
+ {
4104
+ entryName: 'index',
4105
+ pathname: formatPrefix(fallbackPathname)
4106
+ }
4107
+ ];
4108
+ if (0 === printableRoutes.length && !useCustomUrl) return null;
4109
+ let printUrlsOptions = printUrls && 'object' == typeof printUrls ? printUrls : {}, message = getURLMessages(urls, printableRoutes, {
4110
+ maxRoutes: useCustomUrl ? 1 / 0 : printUrlsOptions.maxRoutes,
4111
+ showAllRoutes,
4112
+ cliShortcutsEnabled
4113
+ });
4114
+ 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;
4115
+ }
4116
+ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
4117
+ 'string' == typeof port && (port = Number.parseInt(port, 10)), strictPort && (tryLimits = 1);
4118
+ let { createServer } = await import("node:net"), original = port, found = !1, attempts = 0;
4119
+ for(; !found && attempts <= tryLimits;)try {
4120
+ await new Promise((resolve, reject)=>{
4121
+ let server = createServer();
4122
+ server.unref(), server.on('error', reject), server.listen({
4123
+ port,
4124
+ host
4125
+ }, ()=>{
4126
+ if (0 === port) {
4127
+ let address = server.address();
4128
+ address && 'string' != typeof address && (port = address.port);
4129
+ }
4130
+ found = !0, server.close(resolve);
4131
+ });
4132
+ });
4133
+ } catch (e) {
4134
+ if (!(e instanceof Error) || !('code' in e) || 'EADDRINUSE' !== e.code) throw e;
4135
+ port++, attempts++;
4136
+ }
4137
+ if (!found) throw Error(`${color.dim('[rsbuild:server]')} Failed to find an available port after ${tryLimits + 1} attempts, starting from ${color.yellow(original)}.`);
4138
+ if (0 !== original && port !== original && strictPort) throw Error(`${color.dim('[rsbuild:server]')} Port ${color.yellow(original)} is occupied, please choose another one.`);
4139
+ return port;
4140
+ }, resolvePort = async (config, lastPort)=>{
4141
+ let { host, port: originalPort, strictPort } = config.server, preferredPort = 0 === originalPort ? lastPort : void 0, port = await getPort({
4142
+ host,
4143
+ port: preferredPort ?? originalPort,
4144
+ strictPort: void 0 === preferredPort && strictPort
4145
+ }), portTip = 0 !== originalPort && port !== originalPort ? `port ${originalPort} is in use, ${color.yellow(`using port ${port}.`)}` : void 0;
4146
+ return {
4147
+ port,
4148
+ portTip
4149
+ };
4150
+ }, WILDCARD_HOSTS = new Set([
4151
+ ALL_INTERFACES_IPV4,
4152
+ '::',
4153
+ '0000:0000:0000:0000:0000:0000:0000:0000'
4154
+ ]), LOOPBACK_HOSTS = new Set([
4155
+ LOCALHOST,
4156
+ '127.0.0.1',
4157
+ '::1',
4158
+ '0000:0000:0000:0000:0000:0000:0000:0001'
4159
+ ]), isLoopbackHost = (host)=>LOOPBACK_HOSTS.has(host), getHostInUrl = async (host)=>{
4160
+ if (host === ALL_INTERFACES_IPV4 || host === LOCALHOST) return LOCALHOST;
4161
+ let { isIPv6 } = await import("node:net");
4162
+ return isIPv6(host) ? '::' === host ? '[::1]' : `[${host}]` : host;
4163
+ }, concatUrl = ({ host, port, protocol })=>`${protocol}://${host}:${port}`, LOCAL_LABEL = 'Local: ', NETWORK_LABEL = 'Network: ', getUrlLabel = (url)=>{
4164
+ try {
4165
+ let { hostname } = new URL(url);
4166
+ return isLoopbackHost(hostname) ? LOCAL_LABEL : NETWORK_LABEL;
4167
+ } catch {
4168
+ return NETWORK_LABEL;
4169
+ }
4170
+ }, getAddressUrls = async ({ protocol, port, host })=>{
4171
+ if (host && !WILDCARD_HOSTS.has(host)) {
4172
+ let url = concatUrl({
4173
+ port,
4174
+ host: await getHostInUrl(host),
4175
+ protocol
4176
+ });
4177
+ return [
4178
+ {
4179
+ label: isLoopbackHost(host) ? LOCAL_LABEL : NETWORK_LABEL,
4180
+ url
4181
+ }
4182
+ ];
4183
+ }
4184
+ let urls = [], seen = new Set(), hasLocal = !1;
4185
+ for (let [name, infos] of Object.entries(node_os.networkInterfaces()))for (let info of infos ?? []){
4186
+ let family = info.family;
4187
+ !('IPv4' !== family && 4 !== family || seen.has(info.address)) && (seen.add(info.address), isLoopbackHost(info.address) || info.internal ? hasLocal || (urls.push({
4188
+ label: LOCAL_LABEL,
4189
+ url: concatUrl({
4190
+ host: LOCALHOST,
4191
+ port,
4192
+ protocol
4193
+ })
4194
+ }), hasLocal = !0) : urls.push({
4195
+ label: NETWORK_LABEL,
4196
+ name,
4197
+ url: concatUrl({
4198
+ host: info.address,
4199
+ port,
4200
+ protocol
4201
+ })
4202
+ }));
4203
+ }
4204
+ return urls;
4205
+ };
4206
+ function getServerTerminator(server) {
4207
+ let listened = !1, pendingSockets = new Set(), onConnection = (socket)=>{
4208
+ pendingSockets.add(socket), socket.on('close', ()=>{
4209
+ pendingSockets.delete(socket);
4210
+ });
4211
+ };
4212
+ return server.on('connection', onConnection), server.on('secureConnection', onConnection), server.once('listening', ()=>{
4213
+ listened = !0;
4214
+ }), ()=>new Promise((resolve, reject)=>{
4215
+ for (let socket of pendingSockets)socket.destroy();
4216
+ listened ? server.close((err)=>{
4217
+ err ? reject(err) : resolve();
4218
+ }) : resolve();
4219
+ });
4220
+ }
4221
+ function escapeHtml(text) {
4222
+ return text ? text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;') : '';
4223
+ }
4224
+ let getPublicDirPaths = (config, watchOnly = !1)=>{
4225
+ let paths = new Set();
4226
+ for (let { server } of Object.values(config.environments))for (let { name, watch } of server.publicDir)(!watchOnly || watch) && paths.add(name);
4227
+ return [
4228
+ ...paths
4229
+ ];
4230
+ }, getChokidar = cachedImport_cachedImport(()=>import("./chokidar.js").then((m)=>m.chokidar_namespaceObject)), DEFAULT_WATCH_FILE_EVENTS = [
4122
4231
  'add',
4123
4232
  'change',
4124
4233
  'unlink'
@@ -4126,7 +4235,7 @@ let getChokidar = cachedImport_cachedImport(()=>import("./chokidar.js").then((m)
4126
4235
  async function setupWatchFiles(options) {
4127
4236
  let { config, root, logger, buildManager } = options, { hmr, liveReload } = config.dev;
4128
4237
  if (!hmr && !liveReload || !buildManager) return;
4129
- let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root, logger), serverFilesWatcher = await watchServerFiles(config.server, buildManager, root, logger);
4238
+ let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root, logger), serverFilesWatcher = await watchServerFiles(config, buildManager, root, logger);
4130
4239
  return {
4131
4240
  async close () {
4132
4241
  await Promise.all([
@@ -4148,9 +4257,8 @@ async function watchDevFiles(devConfig, buildManager, root, logger) {
4148
4257
  for (let watcher of watchers)await watcher.close();
4149
4258
  };
4150
4259
  }
4151
- function watchServerFiles({ publicDir }, buildManager, root, logger) {
4152
- if (!publicDir.length) return;
4153
- let watchPaths = publicDir.filter((item)=>item.watch).map((item)=>item.name);
4260
+ function watchServerFiles(config, buildManager, root, logger) {
4261
+ let watchPaths = getPublicDirPaths(config, !0);
4154
4262
  if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), buildManager, root, logger);
4155
4263
  }
4156
4264
  function prepareWatchOptions(paths, options = {}, type, events) {
@@ -4981,7 +5089,7 @@ function parseMinifyOptions(config) {
4981
5089
  cssOptions: minify.cssOptions
4982
5090
  };
4983
5091
  }
4984
- 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"));
5092
+ 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"));
4985
5093
  async function getLightningCSSLoaderOptions(config, targets, minify) {
4986
5094
  let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
4987
5095
  targets,
@@ -5168,6 +5276,9 @@ function pluginExternals() {
5168
5276
  }
5169
5277
  };
5170
5278
  }
5279
+ function getAssetNames(compilation) {
5280
+ return compilation.__internal__getAssetFilenames();
5281
+ }
5171
5282
  function createAssetProcessor() {
5172
5283
  let failure, active = 0, waiting = [];
5173
5284
  return async (names, processAsset)=>{
@@ -5275,8 +5386,8 @@ let calcFileSize = (len)=>{
5275
5386
  return `${val.toFixed(val < 1 ? 2 : 1)} kB`;
5276
5387
  }, COMPRESSIBLE_REGEX = /\.(?:js|mjs|cjs|jsx|ts|tsx|mts|cts|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i;
5277
5388
  async function getFileSizes(options, compilation, processAssets) {
5278
- if (!1 === options.detail && !1 === options.total) return [];
5279
- let { exclude, include } = options, compression = getCompression(options.compressed), fileSizes = [], compilationAssets = compilation.assets, names = Object.getOwnPropertyNames(compilationAssets);
5389
+ if ((!1 === options.detail || 0 === options.detail) && !1 === options.total) return [];
5390
+ let { exclude, include } = options, compression = getCompression(options.compressed), fileSizes = [], compilationAssets = compilation.assets, names = getAssetNames(compilation);
5280
5391
  return await processAssets(names, async (assetName, index)=>{
5281
5392
  let queryIndex, filePath = -1 === (queryIndex = assetName.indexOf('?')) ? assetName : assetName.slice(0, queryIndex);
5282
5393
  if (!exclude && EXCLUDE_ASSET_REGEX.test(filePath)) return;
@@ -5297,7 +5408,7 @@ async function getFileSizes(options, compilation, processAssets) {
5297
5408
  }), fileSizes.filter(Boolean);
5298
5409
  }
5299
5410
  function printFileSizes(options, fileSizes, rootPath, distPath, environmentName, previousSizes, saveSnapshot) {
5300
- let logs = [], compression = getCompression(options.compressed), prev = previousSizes?.[environmentName], showDetail = !1 !== options.detail, showDiff = !1 !== options.diff && null !== previousSizes, prevType = prev?.compressionType ?? (!!prev?.totalGzipSize && 'gzip'), showCompressedDiff = showDiff && prevType === compression.type, showTotal = !1 !== options.total;
5411
+ let logs = [], compression = getCompression(options.compressed), prev = previousSizes?.[environmentName], detailLimit = 'number' == typeof options.detail ? Math.max(0, Math.floor(options.detail)) : 1 / 0, showDetail = !1 !== options.detail && detailLimit > 0, showDiff = !1 !== options.diff && null !== previousSizes, prevType = prev?.compressionType ?? (!!prev?.totalGzipSize && 'gzip'), showCompressedDiff = showDiff && prevType === compression.type, showTotal = !1 !== options.total;
5301
5412
  if (!showTotal && !showDetail) return {
5302
5413
  logs
5303
5414
  };
@@ -5393,16 +5504,17 @@ function printFileSizes(options, fileSizes, rootPath, distPath, environmentName,
5393
5504
  totalBrotliSize: options.compressed && 'brotli' === compression.type ? totalCompressedSize : void 0
5394
5505
  }) : null;
5395
5506
  if (showDetail) {
5396
- let maxFileLength = Math.max(showTotal ? totalSizeTitle.length : 0, fileHeader.length), maxSizeLength = totalSizeLabelLength, hasCompressedSize = !1;
5397
- for (let asset of assets)asset.filenameLength > maxFileLength && (maxFileLength = asset.filenameLength), asset.sizeLabelLength > maxSizeLength && (maxSizeLength = asset.sizeLabelLength), null !== asset.compressedSize && (hasCompressedSize = !0);
5398
- let showCompressedHeader = !!(options.compressed && hasCompressedSize);
5399
- for (let asset of (logs.push(getHeader(maxFileLength, maxSizeLength, fileHeader, showCompressedHeader && compression.header)), assets)){
5507
+ let displayedAssets = assets.slice(Math.max(0, assets.length - detailLimit)), maxFileLength = Math.max(showTotal ? totalSizeTitle.length : 0, fileHeader.length), maxSizeLength = totalSizeLabelLength;
5508
+ for (let asset of displayedAssets)asset.filenameLength > maxFileLength && (maxFileLength = asset.filenameLength), asset.sizeLabelLength > maxSizeLength && (maxSizeLength = asset.sizeLabelLength);
5509
+ let showCompressedHeader = !!(options.compressed && (showTotal ? assets : displayedAssets).some((asset)=>null !== asset.compressedSize));
5510
+ for (let asset of (logs.push(getHeader(maxFileLength, maxSizeLength, fileHeader, showCompressedHeader && compression.header)), displayedAssets)){
5400
5511
  let { sizeLabel, filenameLabel } = asset, { sizeLabelLength, compressedSizeLabel, filenameLength } = asset;
5401
5512
  sizeLabelLength < maxSizeLength && (sizeLabel += ' '.repeat(maxSizeLength - sizeLabelLength)), filenameLength < maxFileLength && (filenameLabel += ' '.repeat(maxFileLength - filenameLength));
5402
5513
  let log = `${filenameLabel} ${sizeLabel}`;
5403
5514
  compressedSizeLabel && (log += ` ${compressedSizeLabel}`), logs.push(log);
5404
5515
  }
5405
- if (showTotal) {
5516
+ let hiddenCount = assets.length - displayedAssets.length;
5517
+ if (hiddenCount > 0 && logs.push(color.dim(`... ${hiddenCount} more ${1 === hiddenCount ? 'file' : 'files'} not shown`)), showTotal) {
5406
5518
  logs.push('');
5407
5519
  let customTotal = getCustomTotal();
5408
5520
  if (customTotal) logs.push(customTotal);
@@ -5782,205 +5894,6 @@ function getInlineTests(config) {
5782
5894
  styleTests
5783
5895
  };
5784
5896
  }
5785
- let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), formatPrefix = (input)=>{
5786
- let prefix = input;
5787
- if (prefix?.startsWith('./') && (prefix = prefix.replace('./', '')), !prefix) return '/';
5788
- let hasLeadingSlash = prefix.startsWith('/'), hasTailSlash = prefix.endsWith('/');
5789
- return `${hasLeadingSlash ? '' : '/'}${prefix}${hasTailSlash ? '' : '/'}`;
5790
- }, 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)=>{
5791
- let basePath = removeTailingSlash(base);
5792
- return '' === basePath || pathname === basePath || pathname.startsWith(`${basePath}/`);
5793
- }, removeBasePath = (url, base)=>{
5794
- let basePath = removeTailingSlash(base);
5795
- if ('' === basePath || !url.startsWith(basePath)) return url;
5796
- let nextChar = url[basePath.length];
5797
- return void 0 === nextChar ? '/' : '/' === nextChar ? url.slice(basePath.length) : '?' === nextChar || '#' === nextChar ? `/${url.slice(basePath.length)}` : url;
5798
- }, getRoutes = (context)=>{
5799
- let environmentWithHtml = context.environmentList.filter((item)=>Object.keys(item.htmlPaths).length > 0);
5800
- if (0 === environmentWithHtml.length) return [];
5801
- let commonDistPath = getCommonParentPath(environmentWithHtml.map((item)=>item.distPath));
5802
- return environmentWithHtml.reduce((prev, environmentContext)=>{
5803
- 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);
5804
- return prev.concat(...routes);
5805
- }, []);
5806
- }, formatRoutes = (entry, base, distPathPrefix, outputStructure)=>{
5807
- let prefix = joinUrlPath(base, formatPrefix(distPathPrefix));
5808
- return Object.keys(entry).map((entryName)=>({
5809
- entryName,
5810
- pathname: prefix + ('index' === entryName && 'nested' !== outputStructure ? '' : entryName)
5811
- })).sort((a)=>'index' === a.entryName ? -1 : 1);
5812
- }, formatName = (name)=>name ? `(${name.length > 20 ? `${name.slice(0, 19)}…` : name})` : name;
5813
- function getURLMessages(urls, routes, { maxRoutes = 10, showAllRoutes, cliShortcutsEnabled }) {
5814
- 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;
5815
- for (let { name } of urls)if (name && ++nameCount > 1) break;
5816
- let showNames = nameCount > 1;
5817
- if (routes.length <= 1 || 0 === printableRoutes.length) {
5818
- let pathname = printableRoutes[0]?.pathname ?? '', items = urls.map(({ label, name, url })=>({
5819
- label,
5820
- name: showNames ? formatName(name) : void 0,
5821
- url: normalizeUrl(`${url}${pathname}`)
5822
- })), 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 })=>{
5823
- let prefix = `➜ ${color.dim(label.trimEnd().padEnd(labelWidth))}`, suffix = name ? `${' '.repeat(urlWidth - url.length + 2)}${color.dim(name)}` : '';
5824
- return ` ${prefix}${color.cyan(url)}${suffix}\n`;
5825
- }).join('');
5826
- return moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
5827
- }
5828
- let message = '', prevLabel = '', entryWidth = Math.max(...printableRoutes.map((route)=>route.entryName.length));
5829
- return urls.forEach(({ label, name, url }, index)=>{
5830
- let shortName = showNames ? formatName(name) : void 0;
5831
- if (prevLabel !== label || prevName !== shortName) {
5832
- index > 0 && (message += '\n');
5833
- let title = shortName ? `${label.trimEnd().slice(0, -1)} ${color.dim(shortName)}:` : label;
5834
- message += ` ➜ ${title}\n`, prevLabel = label, prevName = shortName;
5835
- }
5836
- for (let { entryName, pathname } of printableRoutes)message += ` ${color.dim('-')} ${color.dim(entryName.padEnd(entryWidth + 4))}${color.cyan(normalizeUrl(`${url}${pathname}`))}\n`;
5837
- }), moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
5838
- }
5839
- function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, fallbackPathname, showAllRoutes, cliShortcutsEnabled, originalConfig, logger }) {
5840
- if (!1 === printUrls) return null;
5841
- let urls = originalUrls, useCustomUrl = isFunction(printUrls);
5842
- if (useCustomUrl) {
5843
- let newUrls = printUrls({
5844
- urls: urls.map((item)=>item.url),
5845
- port,
5846
- routes,
5847
- protocol
5848
- });
5849
- if (!newUrls) return null;
5850
- if (!Array.isArray(newUrls)) throw Error(`${color.dim('[rsbuild:config]')} "server.printUrls" must return an array, but got ${typeof newUrls}.`);
5851
- urls = newUrls.map((u)=>{
5852
- let { url, label } = 'string' == typeof u ? {
5853
- url: u
5854
- } : u;
5855
- return {
5856
- url,
5857
- label: label ?? getUrlLabel(url)
5858
- };
5859
- });
5860
- }
5861
- if (0 === urls.length) return null;
5862
- let printableRoutes = 0 !== routes.length || useCustomUrl || void 0 === fallbackPathname ? routes : [
5863
- {
5864
- entryName: 'index',
5865
- pathname: formatPrefix(fallbackPathname)
5866
- }
5867
- ];
5868
- if (0 === printableRoutes.length && !useCustomUrl) return null;
5869
- let printUrlsOptions = printUrls && 'object' == typeof printUrls ? printUrls : {}, message = getURLMessages(urls, printableRoutes, {
5870
- maxRoutes: useCustomUrl ? 1 / 0 : printUrlsOptions.maxRoutes,
5871
- showAllRoutes,
5872
- cliShortcutsEnabled
5873
- });
5874
- 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;
5875
- }
5876
- let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
5877
- 'string' == typeof port && (port = Number.parseInt(port, 10)), strictPort && (tryLimits = 1);
5878
- let { createServer } = await import("node:net"), original = port, found = !1, attempts = 0;
5879
- for(; !found && attempts <= tryLimits;)try {
5880
- await new Promise((resolve, reject)=>{
5881
- let server = createServer();
5882
- server.unref(), server.on('error', reject), server.listen({
5883
- port,
5884
- host
5885
- }, ()=>{
5886
- if (0 === port) {
5887
- let address = server.address();
5888
- address && 'string' != typeof address && (port = address.port);
5889
- }
5890
- found = !0, server.close(resolve);
5891
- });
5892
- });
5893
- } catch (e) {
5894
- if (!(e instanceof Error) || !('code' in e) || 'EADDRINUSE' !== e.code) throw e;
5895
- port++, attempts++;
5896
- }
5897
- if (!found) throw Error(`${color.dim('[rsbuild:server]')} Failed to find an available port after ${tryLimits + 1} attempts, starting from ${color.yellow(original)}.`);
5898
- if (0 !== original && port !== original && strictPort) throw Error(`${color.dim('[rsbuild:server]')} Port ${color.yellow(original)} is occupied, please choose another one.`);
5899
- return port;
5900
- }, resolvePort = async (config, lastPort)=>{
5901
- let { host, port: originalPort, strictPort } = config.server, preferredPort = 0 === originalPort ? lastPort : void 0, port = await getPort({
5902
- host,
5903
- port: preferredPort ?? originalPort,
5904
- strictPort: void 0 === preferredPort && strictPort
5905
- }), portTip = 0 !== originalPort && port !== originalPort ? `port ${originalPort} is in use, ${color.yellow(`using port ${port}.`)}` : void 0;
5906
- return {
5907
- port,
5908
- portTip
5909
- };
5910
- }, WILDCARD_HOSTS = new Set([
5911
- ALL_INTERFACES_IPV4,
5912
- '::',
5913
- '0000:0000:0000:0000:0000:0000:0000:0000'
5914
- ]), LOOPBACK_HOSTS = new Set([
5915
- LOCALHOST,
5916
- '127.0.0.1',
5917
- '::1',
5918
- '0000:0000:0000:0000:0000:0000:0000:0001'
5919
- ]), isLoopbackHost = (host)=>LOOPBACK_HOSTS.has(host), getHostInUrl = async (host)=>{
5920
- if (host === ALL_INTERFACES_IPV4 || host === LOCALHOST) return LOCALHOST;
5921
- let { isIPv6 } = await import("node:net");
5922
- return isIPv6(host) ? '::' === host ? '[::1]' : `[${host}]` : host;
5923
- }, concatUrl = ({ host, port, protocol })=>`${protocol}://${host}:${port}`, LOCAL_LABEL = 'Local: ', NETWORK_LABEL = 'Network: ', getUrlLabel = (url)=>{
5924
- try {
5925
- let { hostname } = new URL(url);
5926
- return isLoopbackHost(hostname) ? LOCAL_LABEL : NETWORK_LABEL;
5927
- } catch {
5928
- return NETWORK_LABEL;
5929
- }
5930
- }, getAddressUrls = async ({ protocol, port, host })=>{
5931
- if (host && host !== ALL_INTERFACES_IPV4) {
5932
- let url = concatUrl({
5933
- port,
5934
- host: await getHostInUrl(host),
5935
- protocol
5936
- });
5937
- return [
5938
- {
5939
- label: isLoopbackHost(host) ? LOCAL_LABEL : NETWORK_LABEL,
5940
- url
5941
- }
5942
- ];
5943
- }
5944
- let urls = [], seen = new Set(), hasLocal = !1;
5945
- for (let [name, infos] of Object.entries(node_os.networkInterfaces()))for (let info of infos ?? []){
5946
- let family = info.family;
5947
- !('IPv4' !== family && 4 !== family || seen.has(info.address)) && (seen.add(info.address), isLoopbackHost(info.address) || info.internal ? hasLocal || (urls.push({
5948
- label: LOCAL_LABEL,
5949
- url: concatUrl({
5950
- host: LOCALHOST,
5951
- port,
5952
- protocol
5953
- })
5954
- }), hasLocal = !0) : urls.push({
5955
- label: NETWORK_LABEL,
5956
- name,
5957
- url: concatUrl({
5958
- host: info.address,
5959
- port,
5960
- protocol
5961
- })
5962
- }));
5963
- }
5964
- return urls;
5965
- };
5966
- function getServerTerminator(server) {
5967
- let listened = !1, pendingSockets = new Set(), onConnection = (socket)=>{
5968
- pendingSockets.add(socket), socket.on('close', ()=>{
5969
- pendingSockets.delete(socket);
5970
- });
5971
- };
5972
- return server.on('connection', onConnection), server.on('secureConnection', onConnection), server.once('listening', ()=>{
5973
- listened = !0;
5974
- }), ()=>new Promise((resolve, reject)=>{
5975
- for (let socket of pendingSockets)socket.destroy();
5976
- listened ? server.close((err)=>{
5977
- err ? reject(err) : resolve();
5978
- }) : resolve();
5979
- });
5980
- }
5981
- function escapeHtml(text) {
5982
- return text ? text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;') : '';
5983
- }
5984
5897
  let supportedChromiumBrowsers = [
5985
5898
  'Google Chrome Canary',
5986
5899
  'Google Chrome Dev',
@@ -6091,7 +6004,7 @@ function doesChunkBelongToHtml({ chunk, htmlPluginData }) {
6091
6004
  let { options } = htmlPluginData.plugin;
6092
6005
  return recursiveChunkEntryNames(chunk).some((chunkName)=>isChunksFiltered(chunkName, options?.chunks, options?.excludeChunks));
6093
6006
  }
6094
- 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/cbeeb1bf16831c5d12121244c2e0e825d7a61324a587214ca9e44e464c6b1496/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
6007
+ 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/5d29cc83887df39016e8cad6b1c60b4fe006f49047c680407d40dcd6e311784e/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
6095
6008
  function normalizeManifestObjectConfig(manifest) {
6096
6009
  let defaultOptions = {
6097
6010
  prefix: !0,
@@ -6193,7 +6106,7 @@ function extractChunks(compilation, includeType) {
6193
6106
  ];
6194
6107
  return void 0 === includeType || 'async-chunks' === includeType ? chunks.filter(isAsyncChunk) : 'initial' === includeType ? chunks.filter((chunk)=>!isAsyncChunk(chunk)) : 'all-chunks' === includeType ? chunks : 'all-assets' === includeType ? [
6195
6108
  {
6196
- files: Object.keys(compilation.assets).filter((file)=>!LICENSE_ASSET_REGEX.test(file))
6109
+ files: getAssetNames(compilation).filter((file)=>!LICENSE_ASSET_REGEX.test(file))
6197
6110
  }
6198
6111
  ] : chunks;
6199
6112
  }
@@ -6334,6 +6247,38 @@ async function applyProfile(root, filterValue, traceLayer, traceOutput) {
6334
6247
  let filter = resolveLayer(filterValue);
6335
6248
  return isTerminalTraceOutput(traceOutput) || await ensureFileDir(traceOutput), await core_rspack.experiments.globalTrace.register(filter, traceLayer, traceOutput), traceOutput;
6336
6249
  }
6250
+ let copyPublicDir = async (publicDir, distPaths, ignore)=>{
6251
+ let shouldCopy;
6252
+ if (ignore?.length) {
6253
+ let { globSync } = await getTinyglobby(), ignoredSet = new Set(globSync(ignore, {
6254
+ cwd: publicDir,
6255
+ absolute: !1,
6256
+ dot: !0,
6257
+ onlyFiles: !1
6258
+ }).map((item)=>item.replace(/\\/g, '/').replace(/\/$/, '')));
6259
+ shouldCopy = (source)=>{
6260
+ let relativePath = node_path.relative(publicDir, source);
6261
+ if (!relativePath) return !0;
6262
+ let normalizedPath = relativePath.replace(/\\/g, '/');
6263
+ return !ignoredSet.has(normalizedPath);
6264
+ };
6265
+ }
6266
+ try {
6267
+ await Promise.all(distPaths.map(async (distPath)=>{
6268
+ isDeno && node_fs.existsSync(distPath) && await node_fs.promises.rm(distPath, {
6269
+ recursive: !0,
6270
+ force: !0
6271
+ }), await node_fs.promises.cp(publicDir, distPath, {
6272
+ recursive: !0,
6273
+ dereference: !0,
6274
+ mode: node_fs.constants.COPYFILE_FICLONE,
6275
+ filter: shouldCopy
6276
+ });
6277
+ }));
6278
+ } catch (err) {
6279
+ 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;
6280
+ }
6281
+ };
6337
6282
  function getForceSplittingGroups(forceSplitting, strategy) {
6338
6283
  let cacheGroups = {};
6339
6284
  for (let [key, regexp] of Array.isArray(forceSplitting) ? forceSplitting.map((regexp, index)=>[
@@ -6616,7 +6561,11 @@ async function getFileFromUrl(url, outputFileSystem, context) {
6616
6561
  for (let [index, distPath] of distPaths.entries()){
6617
6562
  let prefix = publicPathnames[index];
6618
6563
  if (prefix && '/' !== prefix && isUrlPathUnderBase(pathname, prefix)) {
6619
- let candidatePath = node_path.join(distPath, pathname.slice(prefix.length));
6564
+ let relativePathname = pathname.slice(prefix.length);
6565
+ if (hasUpPath && UP_PATH_REGEXP.test(node_path.normalize(`./${relativePathname}`))) return {
6566
+ errorCode: 403
6567
+ };
6568
+ let candidatePath = node_path.join(distPath, relativePathname);
6620
6569
  if (hasUpPath) {
6621
6570
  let relativePath = node_path.relative(distPath, candidatePath);
6622
6571
  if (UP_PATH_REGEXP.test(relativePath)) return {
@@ -6669,7 +6618,6 @@ function parseTokenList(str) {
6669
6618
  }
6670
6619
  return start !== end && list.push(str.substring(start, end)), list;
6671
6620
  }
6672
- var on_finished_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/on-finished/2.4.1/cf4b90e733493a0ce70ba421a5b37153ad39360f9513e36b25d2e49f57047a9b/node_modules/on-finished/index.js"));
6673
6621
  function getEtag(stat) {
6674
6622
  let mtime = stat.mtime.getTime().toString(16), size = stat.size.toString(16);
6675
6623
  return `W/"${size}-${mtime}"`;
@@ -6808,21 +6756,21 @@ function sendError(res, code) {
6808
6756
  res.setHeader('Content-Length', byteLength), res.end(document);
6809
6757
  }
6810
6758
  let filterWebEnvironments = (environmentList)=>environmentList.filter((environment)=>isWebTarget(environment.config.output.target));
6811
- function createAssetsMiddleware(context, ready, outputFileSystem) {
6759
+ function createAssetsMiddleware(context, { waitForAssets, waitForBuild }, outputFileSystem) {
6812
6760
  let { logger } = context, webEnvironments = filterWebEnvironments(context.environmentList), assetContext = {
6813
6761
  ...context,
6814
6762
  environmentList: webEnvironments,
6815
6763
  publicPathnames: webEnvironments.map((environment)=>context.publicPathnames[environment.index])
6816
6764
  };
6817
6765
  return async function assetsMiddleware(req, res, next) {
6818
- async function goNext() {
6766
+ function goNext() {
6819
6767
  return new Promise((resolve)=>{
6820
- ready(()=>{
6768
+ waitForBuild(()=>{
6821
6769
  next(), resolve();
6822
6770
  });
6823
6771
  });
6824
6772
  }
6825
- req.method && 'GET' !== req.method && 'HEAD' !== req.method ? await goNext() : ready(async function processRequest() {
6773
+ req.method && 'GET' !== req.method && 'HEAD' !== req.method ? await goNext() : waitForAssets(async function processRequest() {
6826
6774
  let readStream;
6827
6775
  if (!req.url) return void await goNext();
6828
6776
  let resolved = await getFileFromUrl(req.url, outputFileSystem, assetContext);
@@ -6885,14 +6833,36 @@ function createAssetsMiddleware(context, ready, outputFileSystem) {
6885
6833
  default:
6886
6834
  sendError(res, 500);
6887
6835
  }
6888
- }), readStream.pipe(res), on_finished_default()(res, cleanup);
6836
+ }), readStream.pipe(res), finished(res, cleanup);
6889
6837
  });
6890
6838
  };
6891
6839
  }
6840
+ function setupMemoryFileSystemCleanup(fileSystem, compilers) {
6841
+ if (compilers.some((compiler)=>compiler.options.output.clean)) return;
6842
+ let lastSeenByCompiler = compilers.map(()=>new Map());
6843
+ for (let [index, compiler] of compilers.entries()){
6844
+ let lastHash, lastSeen = lastSeenByCompiler[index], generation = 0;
6845
+ compiler.hooks.afterEmit.tap('rsbuild:clean-memory-filesystem', (compilation)=>{
6846
+ if (compilation.errors.length) return;
6847
+ compilation.hash !== lastHash && (generation++, lastHash = compilation.hash);
6848
+ let outputPath = compilation.getPath(compiler.outputPath);
6849
+ for (let name of getAssetNames(compilation)){
6850
+ let queryIndex = name.indexOf('?'), filePath = join(outputPath, -1 === queryIndex ? name : name.slice(0, queryIndex));
6851
+ lastSeen.set(filePath, generation);
6852
+ }
6853
+ for (let [filePath, seen] of lastSeen)if (!(seen >= generation - 1) && (lastSeen.delete(filePath), !lastSeenByCompiler.some((assets)=>assets.has(filePath)))) try {
6854
+ fileSystem.unlinkSync(filePath);
6855
+ } catch (error) {
6856
+ if ('ENOENT' !== error.code) throw error;
6857
+ }
6858
+ });
6859
+ }
6860
+ }
6892
6861
  async function setupOutputFileSystem(writeAllToDisk, compilers) {
6893
6862
  if (!writeAllToDisk) {
6894
6863
  let { createMemoryFileSystem } = await import("./memfs.js"), outputFileSystem = createMemoryFileSystem();
6895
6864
  for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
6865
+ setupMemoryFileSystemCleanup(outputFileSystem, compilers);
6896
6866
  }
6897
6867
  let compiler = compilers.find((compiler)=>!!compiler.outputFileSystem);
6898
6868
  return compiler?.outputFileSystem ?? node_fs;
@@ -6931,7 +6901,10 @@ let noop = ()=>{}, normalizeLiveReload = (liveReload)=>'boolean' == typeof liveR
6931
6901
  } : {
6932
6902
  enabled: !0,
6933
6903
  html: !1 !== liveReload.html
6934
- }, isTsError = (error)=>'message' in error && error.stack?.includes('ts-checker-rspack-plugin');
6904
+ }, isNodeCompiler = (compiler)=>{
6905
+ let { target } = compiler.options;
6906
+ return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
6907
+ }, isTsError = (error)=>'message' in error && error.stack?.includes('ts-checker-rspack-plugin');
6935
6908
  function applyHMREntry({ config, compiler, token, resolvedHost, resolvedPort }) {
6936
6909
  var overlay;
6937
6910
  let overlay1;
@@ -6962,7 +6935,13 @@ init(
6962
6935
  }).apply(compiler);
6963
6936
  }
6964
6937
  let assets_middleware_assetsMiddleware = async ({ config, compiler, context, socketServer, resolvedPort })=>{
6965
- let watching, { logger } = context, resolvedHost = await resolveHostname(config.server.host), { environmentList } = context;
6938
+ 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 : [
6939
+ compiler
6940
+ ]).filter((compiler)=>!isNodeCompiler(compiler))).length > 0 && webCompilers.length < allCompilers.length, {
6941
+ allCompilers,
6942
+ webCompilers,
6943
+ earlyWebUpdates
6944
+ });
6966
6945
  applyToCompiler(compiler, (compiler, index)=>{
6967
6946
  let environment = environmentList[index];
6968
6947
  if (!environment) return;
@@ -6973,11 +6952,8 @@ let assets_middleware_assetsMiddleware = async ({ config, compiler, context, soc
6973
6952
  compiler,
6974
6953
  resolvedHost,
6975
6954
  resolvedPort
6976
- }), (({ context, compiler, token, socketServer, liveReload })=>{
6977
- if (((compiler)=>{
6978
- let { target } = compiler.options;
6979
- return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
6980
- })(compiler)) return;
6955
+ }), (({ context, compiler, token, socketServer, liveReload, earlyWebUpdates })=>{
6956
+ if (isNodeCompiler(compiler)) return;
6981
6957
  let errorsCount = null, warningsCount = null;
6982
6958
  compiler.hooks.invalid.tap('rsbuild-dev-server', (fileName)=>{
6983
6959
  errorsCount = null, warningsCount = null, 'string' == typeof fileName && fileName.endsWith('.html') && normalizeLiveReload(liveReload).html && socketServer.sendMessage({
@@ -6986,6 +6962,7 @@ let assets_middleware_assetsMiddleware = async ({ config, compiler, context, soc
6986
6962
  }), compiler.hooks.done.tap('rsbuild-dev-server', (stats)=>{
6987
6963
  let { errors, warnings } = stats.compilation;
6988
6964
  if (errors.length === errorsCount && warnings.length === warningsCount) return;
6965
+ null === errorsCount && null === warningsCount && earlyWebUpdates && !stats.hasErrors() && socketServer.onEnvironmentDone(token, ()=>getRsbuildStats(stats, compiler, context.logger, context.action));
6989
6966
  let isRecalled = null !== errorsCount || null !== warningsCount;
6990
6967
  if (errorsCount = errors.length, warningsCount = warnings.length, isRecalled) {
6991
6968
  let tsErrors = errors.filter(isTsError), tsWarnings = warnings.filter(isTsError);
@@ -7013,30 +6990,47 @@ let assets_middleware_assetsMiddleware = async ({ config, compiler, context, soc
7013
6990
  compiler,
7014
6991
  socketServer,
7015
6992
  token,
7016
- liveReload: environment.config.dev.liveReload
6993
+ liveReload: environment.config.dev.liveReload,
6994
+ earlyWebUpdates: earlyWebUpdates1
7017
6995
  }));
7018
6996
  });
7019
- let compilers = compiler_isMultiCompiler(compiler) ? compiler.compilers : [
7020
- compiler
7021
- ], callbacks = [], flushCallbacks = ()=>{
6997
+ let assetCallbacks = [], buildCallbacks = [], flushCallbacks = (callbacks)=>{
7022
6998
  for (let callback of callbacks.splice(0))callback();
6999
+ }, flushAllCallbacks = ()=>{
7000
+ flushCallbacks(assetCallbacks), flushCallbacks(buildCallbacks);
7023
7001
  };
7024
7002
  compiler.hooks.done.tap('rsbuild-dev-middleware', ()=>{
7025
7003
  process.nextTick(()=>{
7026
- 'done' === context.buildState.status && flushCallbacks();
7004
+ 'done' === context.buildState.status && flushAllCallbacks();
7027
7005
  });
7028
7006
  });
7007
+ let compiledWebCompilers = new Set(), isWebReady = ()=>earlyWebUpdates1 && compiledWebCompilers.size === webCompilers1.length;
7008
+ if (earlyWebUpdates1) for (let item of webCompilers1){
7009
+ let reset = ()=>{
7010
+ compiledWebCompilers.delete(item);
7011
+ };
7012
+ item.hooks.invalid.tap('rsbuild-dev-middleware', reset), item.hooks.watchRun.tap('rsbuild-dev-middleware', reset), item.hooks.done.tap('rsbuild-dev-middleware', (stats)=>{
7013
+ !stats.hasErrors() && (compiledWebCompilers.add(item), isWebReady() && process.nextTick(()=>{
7014
+ isWebReady() && flushCallbacks(assetCallbacks);
7015
+ }));
7016
+ });
7017
+ }
7029
7018
  let writeToDiskList = environmentList.map((environment)=>environment.config.dev.writeToDisk);
7030
- writeToDiskList.some(Boolean) && setupWriteToDisk(compilers, writeToDiskList, logger);
7031
- let instance = createAssetsMiddleware(context, (callback)=>{
7032
- 'done' === context.buildState.status || 'failed' === context.buildState.status ? callback() : callbacks.push(callback);
7033
- }, await setupOutputFileSystem(writeToDiskList.every((writeToDisk)=>!0 === writeToDisk), compilers));
7019
+ writeToDiskList.some(Boolean) && setupWriteToDisk(allCompilers1, writeToDiskList, logger);
7020
+ let outputFileSystem = await setupOutputFileSystem(writeToDiskList.every((writeToDisk)=>!0 === writeToDisk), allCompilers1), isBuildReady = ()=>'done' === context.buildState.status || 'failed' === context.buildState.status, instance = createAssetsMiddleware(context, {
7021
+ waitForAssets: (callback)=>{
7022
+ isBuildReady() || isWebReady() ? callback() : assetCallbacks.push(callback);
7023
+ },
7024
+ waitForBuild: (callback)=>{
7025
+ isBuildReady() ? callback() : buildCallbacks.push(callback);
7026
+ }
7027
+ }, outputFileSystem);
7034
7028
  return instance.watch = ()=>{
7035
7029
  if (compiler.watching) watching = compiler.watching;
7036
7030
  else {
7037
- let watchOptions = compilers.length > 1 ? compilers.map(({ options })=>options.watchOptions || {}) : compilers[0].options.watchOptions || {};
7031
+ let watchOptions = allCompilers1.length > 1 ? allCompilers1.map(({ options })=>options.watchOptions || {}) : allCompilers1[0].options.watchOptions || {};
7038
7032
  watching = compiler.watch(watchOptions, (error)=>{
7039
- 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));
7033
+ 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));
7040
7034
  });
7041
7035
  }
7042
7036
  }, instance.close = (callback = noop)=>{
@@ -7283,6 +7277,7 @@ class SocketServer {
7283
7277
  getOutputFileSystem;
7284
7278
  reportedBrowserLogs = new Set();
7285
7279
  currentHash = new Map();
7280
+ environmentStats = new Map();
7286
7281
  onSocketConnect;
7287
7282
  constructor(context, options, getOutputFileSystem, onSocketConnect){
7288
7283
  this.context = context, this.options = options, this.getOutputFileSystem = getOutputFileSystem, this.onSocketConnect = onSocketConnect;
@@ -7314,8 +7309,16 @@ class SocketServer {
7314
7309
  this.onConnect(socket, query.token);
7315
7310
  });
7316
7311
  }
7312
+ onEnvironmentDone(token, getStats) {
7313
+ 'done' !== this.context.buildState.status && this.socketsMap.has(token) && (this.environmentStats.set(token, getStats()), this.sendStats({
7314
+ token
7315
+ }));
7316
+ }
7317
+ clearEnvironmentStats() {
7318
+ this.environmentStats.clear();
7319
+ }
7317
7320
  onBuildDone() {
7318
- if (this.reportedBrowserLogs.clear(), this.ensureInitialChunks(), this.socketsMap.size) for (let token of this.socketsMap.keys())this.sendStats({
7321
+ if (this.environmentStats.clear(), this.reportedBrowserLogs.clear(), this.ensureInitialChunks(), this.socketsMap.size) for (let token of this.socketsMap.keys())this.sendStats({
7319
7322
  token
7320
7323
  });
7321
7324
  }
@@ -7433,6 +7436,12 @@ class SocketServer {
7433
7436
  }
7434
7437
  }
7435
7438
  getStats(token) {
7439
+ let environmentStats = this.environmentStats.get(token);
7440
+ if (environmentStats) return {
7441
+ stats: environmentStats,
7442
+ errors: getStatsErrors(environmentStats),
7443
+ warnings: getStatsWarnings(environmentStats)
7444
+ };
7436
7445
  let { stats } = this.context.buildState, environment = this.getEnvironmentByToken(token);
7437
7446
  if (!stats || !environment) return;
7438
7447
  let currentStats = stats;
@@ -7453,6 +7462,13 @@ class SocketServer {
7453
7462
  if (this.initialChunksMap.set(token, newInitialChunks), shouldReload) return void this.sendMessage({
7454
7463
  type: 'full-reload'
7455
7464
  }, token);
7465
+ if (this.environmentStats.has(token)) {
7466
+ stats.hash && (this.currentHash.set(token, stats.hash), this.sendMessage({
7467
+ type: 'early-update',
7468
+ data: stats.hash
7469
+ }, token));
7470
+ return;
7471
+ }
7456
7472
  if (stats.hash) {
7457
7473
  let prevHash = this.currentHash.get(token);
7458
7474
  if (this.currentHash.set(token, stats.hash), !force && 0 === errors.length && 0 === warnings.length && prevHash === stats.hash) return void this.sendMessage({
@@ -7694,7 +7710,7 @@ let faviconFallbackMiddleware = (req, res, next)=>{
7694
7710
  '/favicon.ico' === req.url ? (res.statusCode = 204, res.end()) : next();
7695
7711
  }, getRequestLoggerMiddleware = (logger)=>(req, res, next)=>{
7696
7712
  let _startAt = process.hrtime();
7697
- on_finished_default()(res, ()=>{
7713
+ finished(res, ()=>{
7698
7714
  let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = status >= 500 ? color.red : status >= 400 ? color.yellow : status >= 300 ? color.cyan : status >= 200 ? color.green : (res)=>res, endAt = process.hrtime(), totalTime = (endAt[0] - _startAt[0]) * 1e3 + (endAt[1] - _startAt[1]) * 1e-6;
7699
7715
  logger.debug(`${statusColor(status)} ${method} ${url} ${color.dim(`${totalTime.toFixed(3)} ms`)}`);
7700
7716
  }), next();
@@ -7839,7 +7855,7 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer,
7839
7855
  let { compiler } = buildManager;
7840
7856
  (compiler_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.lazyCompilation) : compiler.options.lazyCompilation) && middlewares.use(core_rspack.lazyCompilationMiddleware(compiler));
7841
7857
  }
7842
- if (server.base && '/' !== server.base && middlewares.use(getBaseUrlMiddleware({
7858
+ server.base && '/' !== server.base && middlewares.use(getBaseUrlMiddleware({
7843
7859
  base: server.base
7844
7860
  })), middlewares.use('/__open-in-editor', async (req, res, next)=>{
7845
7861
  try {
@@ -7900,7 +7916,7 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer,
7900
7916
  try {
7901
7917
  for(let key in environments){
7902
7918
  res.write(`<h2>Environment: ${key}</h2>`);
7903
- let list = [], environment = environments[key], stats = await environment.getStats(), assets = Object.keys(stats.compilation.assets);
7919
+ let list = [], environment = environments[key], stats = await environment.getStats(), assets = getAssetNames(stats.compilation);
7904
7920
  for (let asset of (res.write('<ul>'), assets))list.push(`<li><a target="_blank" href="${asset}">${asset}</a></li>`);
7905
7921
  res.write(list?.join('')), res.write('</ul>');
7906
7922
  }
@@ -7922,9 +7938,11 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer,
7922
7938
  context.distPath
7923
7939
  ],
7924
7940
  outputFileSystem: buildManager.outputFileSystem
7925
- })), server.publicDir.length) {
7941
+ }));
7942
+ let publicDirPaths = getPublicDirPaths(config);
7943
+ if (publicDirPaths.length) {
7926
7944
  let { default: sirv } = await import("./sirv.js");
7927
- for (let { name } of server.publicDir){
7945
+ for (let name of publicDirPaths){
7928
7946
  let sirvMiddleware = sirv(name, {
7929
7947
  etag: !0,
7930
7948
  dev: !0
@@ -8577,7 +8595,7 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8577
8595
  serverConfig,
8578
8596
  middlewares
8579
8597
  }), cleanupGracefulShutdown = setupGracefulShutdown(), serverTerminator = getServerTerminator(httpServer), closingPromise = null, closeServer = async ()=>(closingPromise || (closingPromise = (async ()=>{
8580
- removeCleanup(closeServer), cleanupGracefulShutdown(), cleanupCliShortcuts?.(), await serverTerminator();
8598
+ removeCleanup(closeServer), cleanupGracefulShutdown(), cleanupCliShortcuts?.(), await serverTerminator(), await context.hooks.onClosePreviewServer.callBatch();
8581
8599
  })()), closingPromise), printUrls = (options)=>printServerURLs({
8582
8600
  urls,
8583
8601
  port,
@@ -8611,7 +8629,10 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8611
8629
  server: previewServer,
8612
8630
  environments: context.environments
8613
8631
  });
8614
- let webEnvironments = filterWebEnvironments(context.environmentList), assetsMiddleware = createAssetsMiddleware(context, (callback)=>callback(), node_fs), htmlMiddlewareOptions = {
8632
+ let webEnvironments = filterWebEnvironments(context.environmentList), assetsMiddleware = createAssetsMiddleware(context, {
8633
+ waitForAssets: (callback)=>callback(),
8634
+ waitForBuild: (callback)=>callback()
8635
+ }, node_fs), htmlMiddlewareOptions = {
8615
8636
  assetsMiddleware,
8616
8637
  distPaths: webEnvironments.map((environment)=>environment.distPath),
8617
8638
  outputFileSystem: node_fs
@@ -9036,7 +9057,7 @@ function applyDefaultPlugins(pluginManager, context) {
9036
9057
  {
9037
9058
  name: 'rsbuild:html',
9038
9059
  setup (api) {
9039
- let defaultFavicon;
9060
+ let defaultFaviconCache = new Map();
9040
9061
  api.modifyBundlerChain(async (chain, { HtmlPlugin, CHAIN_ID, environment })=>{
9041
9062
  let { config, htmlPaths } = environment;
9042
9063
  if (0 === Object.keys(htmlPaths).length) return;
@@ -9068,17 +9089,18 @@ function applyDefaultPlugins(pluginManager, context) {
9068
9089
  };
9069
9090
  })(environment.config);
9070
9091
  tagConfig && (extraData.tagConfig = tagConfig), pluginOptions.title = await getTitle(entryName, config);
9071
- let favicon = await getFavicon(entryName, config) || (()=>{
9072
- if (defaultFavicon) return defaultFavicon;
9073
- let { publicDir } = api.getNormalizedConfig().server, extensions = [
9092
+ let favicon = await getFavicon(entryName, config) || ((config)=>{
9093
+ let { publicDir } = config.server, extensions = [
9074
9094
  'ico',
9075
9095
  'png',
9076
9096
  'svg'
9077
- ], publicDirs = Array.from(new Set(publicDir.map(({ name })=>name))), faviconPaths = [];
9097
+ ], publicDirs = Array.from(new Set(publicDir.map(({ name })=>name))), key = JSON.stringify(publicDirs), defaultFavicon = defaultFaviconCache.get(key);
9098
+ if (defaultFavicon) return defaultFavicon;
9099
+ let faviconPaths = [];
9078
9100
  for (let publicDir of publicDirs)for (let ext of extensions)faviconPaths.push(node_path.join(publicDir, `favicon.${ext}`));
9079
9101
  let faviconPath = findExists(faviconPaths);
9080
- return faviconPath && (defaultFavicon = faviconPath), defaultFavicon;
9081
- })();
9102
+ if (faviconPath) return defaultFaviconCache.set(key, faviconPath), faviconPath;
9103
+ })(config);
9082
9104
  favicon && (extraData.favicon = favicon);
9083
9105
  let finalOptions = await reduceConfigsWithContext({
9084
9106
  initial: pluginOptions,
@@ -9792,39 +9814,22 @@ try {
9792
9814
  }
9793
9815
  };
9794
9816
  api.onAfterStartDevServer(onStartServer), api.onAfterStartPreviewServer(onStartServer), api.onBeforeBuild(async ({ isFirstCompile, environments })=>{
9795
- if (isFirstCompile) for (let { name: publicDir, copyOnBuild, ignore } of api.getNormalizedConfig().server.publicDir){
9796
- let shouldCopy;
9817
+ if (!isFirstCompile) return;
9818
+ let groups = new Map();
9819
+ for (let environment of Object.values(environments)){
9820
+ let key = JSON.stringify(environment.config.server.publicDir.map(({ name, copyOnBuild, ignore })=>[
9821
+ name,
9822
+ copyOnBuild,
9823
+ ignore
9824
+ ])), group = groups.get(key);
9825
+ group ? group.push(environment) : groups.set(key, [
9826
+ environment
9827
+ ]);
9828
+ }
9829
+ for (let group of groups.values())for (let { name: publicDir, copyOnBuild, ignore } of group[0].config.server.publicDir){
9797
9830
  if (!1 === copyOnBuild || !node_fs.existsSync(publicDir)) continue;
9798
- let distPaths = dedupeNestedPaths(Object.values(environments).filter(({ config })=>!0 === copyOnBuild || 'auto' === copyOnBuild && 'node' !== config.output.target).map(({ distPath })=>distPath));
9799
- if (ignore?.length) {
9800
- let { globSync } = await getTinyglobby(), ignoredSet = new Set(globSync(ignore, {
9801
- cwd: publicDir,
9802
- absolute: !1,
9803
- dot: !0,
9804
- onlyFiles: !1
9805
- }).map((item)=>item.replace(/\\/g, '/').replace(/\/$/, '')));
9806
- shouldCopy = (source)=>{
9807
- let relativePath = node_path.relative(publicDir, source);
9808
- if (!relativePath) return !0;
9809
- let normalizedPath = relativePath.replace(/\\/g, '/');
9810
- return !ignoredSet.has(normalizedPath);
9811
- };
9812
- }
9813
- try {
9814
- await Promise.all(distPaths.map(async (distPath)=>{
9815
- isDeno && node_fs.existsSync(distPath) && await node_fs.promises.rm(distPath, {
9816
- recursive: !0,
9817
- force: !0
9818
- }), await node_fs.promises.cp(publicDir, distPath, {
9819
- recursive: !0,
9820
- dereference: !0,
9821
- mode: node_fs.constants.COPYFILE_FICLONE,
9822
- filter: shouldCopy
9823
- });
9824
- }));
9825
- } catch (err) {
9826
- 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;
9827
- }
9831
+ let distPaths = dedupeNestedPaths(group.filter(({ config })=>!0 === copyOnBuild || 'node' !== config.output.target).map(({ distPath })=>distPath));
9832
+ 0 !== distPaths.length && await copyPublicDir(publicDir, distPaths, ignore);
9828
9833
  }
9829
9834
  });
9830
9835
  }
@@ -10167,6 +10172,7 @@ async function createRsbuild(options = {}) {
10167
10172
  'onBeforeStartPreviewServer',
10168
10173
  'onCloseBuild',
10169
10174
  'onCloseDevServer',
10175
+ 'onClosePreviewServer',
10170
10176
  'onDevCompileDone',
10171
10177
  'onExit',
10172
10178
  'onRestart'
@@ -10391,7 +10397,7 @@ let applyServerOptions = (command)=>{
10391
10397
  };
10392
10398
  function setupCommands(argv) {
10393
10399
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10394
- cli.version("2.2.14"), 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)', {
10400
+ cli.version("2.3.0-rc.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)', {
10395
10401
  default: 'auto'
10396
10402
  }).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', {
10397
10403
  type: [
@@ -10456,7 +10462,7 @@ function setupCommands(argv) {
10456
10462
  }
10457
10463
  function showGreeting() {
10458
10464
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10459
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.14\n`);
10465
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.3.0-rc.0\n`);
10460
10466
  }
10461
10467
  function setupLogLevel(argv) {
10462
10468
  if (argv.length <= 3) return;
@@ -10478,5 +10484,5 @@ function runCLI({ argv = process.argv } = {}) {
10478
10484
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10479
10485
  }
10480
10486
  }
10481
- let src_version = "2.2.14";
10487
+ let src_version = "2.3.0-rc.0";
10482
10488
  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 };