@rsbuild/core 2.1.6 → 2.1.7

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/711.js CHANGED
@@ -386,8 +386,8 @@ __webpack_require__.add({
386
386
  return (asyncHooks.AsyncResource && (res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn')), res && res.runInAsyncScope) ? res.runInAsyncScope.bind(res, fn, null) : fn;
387
387
  }
388
388
  },
389
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/index.js" (module, __unused_rspack_exports, __webpack_require__) {
390
- let yaml, { resolve } = __webpack_require__("node:path?435f"), config = __webpack_require__("../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js"), loadOptions = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/options.js"), loadPlugins = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/plugins.js"), req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/req.js");
389
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/index.js" (module, __unused_rspack_exports, __webpack_require__) {
390
+ let yaml, { resolve } = __webpack_require__("node:path?435f"), config = __webpack_require__("../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js"), loadOptions = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/options.js"), loadPlugins = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/plugins.js"), req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/req.js");
391
391
  async function processResult(ctx, result) {
392
392
  let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
393
393
  default: obj
@@ -460,8 +460,8 @@ __webpack_require__.add({
460
460
  });
461
461
  };
462
462
  },
463
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/options.js" (module, __unused_rspack_exports, __webpack_require__) {
464
- let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/req.js");
463
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/options.js" (module, __unused_rspack_exports, __webpack_require__) {
464
+ let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/req.js");
465
465
  module.exports = async function options(config, file) {
466
466
  if (config.parser && 'string' == typeof config.parser) try {
467
467
  config.parser = await req(config.parser, file);
@@ -481,8 +481,8 @@ __webpack_require__.add({
481
481
  return config;
482
482
  };
483
483
  },
484
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/plugins.js" (module, __unused_rspack_exports, __webpack_require__) {
485
- let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/req.js");
484
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/plugins.js" (module, __unused_rspack_exports, __webpack_require__) {
485
+ let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/req.js");
486
486
  async function load(plugin, options, file) {
487
487
  try {
488
488
  if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
@@ -498,7 +498,7 @@ __webpack_require__.add({
498
498
  }), list;
499
499
  };
500
500
  },
501
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/req.js" (module, __unused_rspack_exports, __webpack_require__) {
501
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/req.js" (module, __unused_rspack_exports, __webpack_require__) {
502
502
  let tsx, jiti, { createRequire } = __webpack_require__("node:module?1bcb"), { pathToFileURL } = __webpack_require__("node:url?b4ec"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
503
503
  module.exports = async function req(name, rootFile = __rspack_import_meta_filename__) {
504
504
  let url = createRequire(rootFile).resolve(name);
@@ -650,24 +650,31 @@ let createStyler = (style)=>(text)=>node_util.styleText(style, String(text)), co
650
650
  level: 'info'
651
651
  },
652
652
  debug: createLogType('debug', 'verbose', color.magenta)
653
- }, errorStackRegExp = /at [^\r\n]{0,200}(?::\d+:\d+[\s)]*|\(<anonymous>\)|\(index\s\d+\))$/, normalizeErrorMessage = (err)=>{
653
+ }, ANSI_REGEXP = RegExp("\x1b\\[[0-9;]*m", 'g'), errorStackRegExp = /at [^\r\n]{0,200}(?::\d+:\d+[\s)]*|\(<anonymous>\)|\(index\s\d+\))$/, isErrorStackMessage = (message)=>{
654
+ let stripped = message.replace(ANSI_REGEXP, '');
655
+ return errorStackRegExp.test(stripped);
656
+ }, normalizeErrorMessage = (err)=>{
654
657
  if (err.stack) {
655
658
  let [rawName, ...rest] = err.stack.split('\n'), name = rawName.startsWith('Error: ') ? rawName.slice(7) : rawName;
656
659
  return `${name}\n${color.gray(rest.join('\n'))}`;
657
660
  }
658
661
  return err.message;
659
662
  }, createLogger = (options = {})=>{
660
- let { level = 'info', prefix, console: console1 = globalThis.console } = options, maxLevel = level, log = (type, message, ...args)=>{
663
+ let { level = 'info', prefix, console: console1 = globalThis.console, alignMultiline } = options, maxLevel = level, log = (type, message, ...args)=>{
661
664
  let logType = LOG_TYPES[type], { level } = logType;
662
665
  if (LOG_LEVEL[level] > LOG_LEVEL[maxLevel]) return;
663
666
  if (null == message) return console1.log();
664
- let label = 'label' in logType ? logType.label : '', text = '';
665
- if (message instanceof Error) {
667
+ let label = 'label' in logType ? logType.label : '', header = label ? prefix ? `${label} ${prefix}` : label : prefix, text = '', isErrorObject = message instanceof Error;
668
+ if (isErrorObject) {
666
669
  text += normalizeErrorMessage(message);
667
670
  let { cause } = message;
668
671
  cause && (text += color.yellow('\n [cause]: '), text += cause instanceof Error ? normalizeErrorMessage(cause) : String(cause));
669
- } else text = 'error' === level && 'string' == typeof message ? message.split('\n').map((line)=>errorStackRegExp.test(line) ? color.gray(line) : line).join('\n') : `${message}`;
670
- prefix && (text = `${prefix} ${text}`), console1['error' === level || 'warn' === level ? level : 'log'](label ? `${label} ${text}` : text, ...args);
672
+ } else text = 'error' === level && 'string' == typeof message ? message.split('\n').map((line)=>isErrorStackMessage(line) ? color.gray(line) : line).join('\n') : `${message}`;
673
+ if (alignMultiline && header && !isErrorObject && text.includes('\n')) {
674
+ let indent = ' '.repeat(header.replace(ANSI_REGEXP, '').length + 1), skipStack = 'error' === level;
675
+ text = text.split('\n').map((line, i)=>0 === i || '' === line || skipStack && isErrorStackMessage(line) ? line : indent + line).join('\n');
676
+ }
677
+ console1['error' === level || 'warn' === level ? level : 'log'](header ? `${header} ${text}` : text, ...args);
671
678
  }, logger = {
672
679
  greet: (message)=>log('log', supportsTrueColor ? `\x1b[1;38;2;132;225;199m${message}\x1b[39;22m` : color.bold(color.cyan(message)))
673
680
  };
@@ -2501,6 +2508,7 @@ function createAsyncHook() {
2501
2508
  function initHooks() {
2502
2509
  return {
2503
2510
  onExit: createAsyncHook(),
2511
+ onRestart: createAsyncHook(),
2504
2512
  onCloseBuild: createAsyncHook(),
2505
2513
  onAfterBuild: createAsyncHook(),
2506
2514
  onBeforeBuild: createAsyncHook(),
@@ -3269,6 +3277,7 @@ function initPluginAPI({ context, pluginManager }) {
3269
3277
  getNormalizedConfig,
3270
3278
  isPluginExists: pluginManager.isPluginExists,
3271
3279
  onExit,
3280
+ onRestart: hooks.onRestart.tap,
3272
3281
  onAfterBuild: hooks.onAfterBuild.tap,
3273
3282
  onCloseBuild: hooks.onCloseBuild.tap,
3274
3283
  onBeforeBuild: hooks.onBeforeBuild.tap,
@@ -3383,6 +3392,8 @@ function createPublicContext(context) {
3383
3392
  'action',
3384
3393
  'version',
3385
3394
  'rootPath',
3395
+ 'configFile',
3396
+ 'configFileDependencies',
3386
3397
  'distPath',
3387
3398
  'devServer',
3388
3399
  'cachePath',
@@ -3396,11 +3407,13 @@ function createPublicContext(context) {
3396
3407
  set: (target, prop)=>(target.logger.error(`Context is readonly, you can not assign to the "context.${prop}" prop.`), !0)
3397
3408
  });
3398
3409
  }
3399
- async function createContext(options, userConfig, logger) {
3400
- 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;
3410
+ async function createContext(options, userConfig, logger, loadConfigResult) {
3411
+ 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();
3401
3412
  return {
3402
- version: "2.1.6",
3413
+ version: "2.1.7",
3403
3414
  rootPath,
3415
+ configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3416
+ configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
3404
3417
  distPath: '',
3405
3418
  cachePath,
3406
3419
  logger,
@@ -3409,7 +3422,38 @@ async function createContext(options, userConfig, logger) {
3409
3422
  environments: {},
3410
3423
  environmentList: [],
3411
3424
  publicPathnames: [],
3412
- hooks: initHooks(),
3425
+ hooks,
3426
+ restartManager: (({ onRestart, restart })=>{
3427
+ let cleanups = new Set();
3428
+ return {
3429
+ canRestart: !!restart,
3430
+ registerCleanup: (cleanup)=>(cleanups.add(cleanup), ()=>{
3431
+ cleanups.delete(cleanup);
3432
+ }),
3433
+ async requestRestart (context) {
3434
+ let firstError;
3435
+ if (!restart) return await onRestart(context), !1;
3436
+ let currentCleanups = cleanups;
3437
+ cleanups = new Set();
3438
+ let hasError = !1;
3439
+ try {
3440
+ await onRestart(context);
3441
+ } catch (error) {
3442
+ hasError = !0, firstError = error;
3443
+ }
3444
+ for (let cleanup of currentCleanups)try {
3445
+ await cleanup();
3446
+ } catch (error) {
3447
+ hasError || (hasError = !0, firstError = error);
3448
+ }
3449
+ if (hasError) throw firstError;
3450
+ return restart(context);
3451
+ }
3452
+ };
3453
+ })({
3454
+ onRestart: hooks.onRestart.callBatch,
3455
+ restart: options.restart
3456
+ }),
3413
3457
  config: {
3414
3458
  ...rsbuildConfig
3415
3459
  },
@@ -3926,7 +3970,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
3926
3970
  }
3927
3971
  return tsconfigPaths.size && 'prefer-tsconfig' === normalizedBaseConfig.resolve.aliasStrategy && normalizedBaseConfig.dev.watchFiles.push({
3928
3972
  paths: Array.from(tsconfigPaths),
3929
- type: 'reload-server'
3973
+ type: 'restart'
3930
3974
  }), context.normalizedConfig = {
3931
3975
  ...normalizedBaseConfig,
3932
3976
  environments
@@ -4143,8 +4187,132 @@ async function createCompiler_createCompiler(options) {
4143
4187
  rspackConfigs
4144
4188
  };
4145
4189
  }
4190
+ async function setupWatchFiles(options) {
4191
+ let { config, root, buildManager } = options, { hmr, liveReload } = config.dev;
4192
+ if (!hmr && !liveReload || !buildManager) return;
4193
+ let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root), serverFilesWatcher = await watchServerFiles(config.server, buildManager, root);
4194
+ return {
4195
+ async close () {
4196
+ await Promise.all([
4197
+ closeDevFilesWatcher?.(),
4198
+ serverFilesWatcher?.close()
4199
+ ]);
4200
+ }
4201
+ };
4202
+ }
4203
+ async function watchDevFiles(devConfig, buildManager, root) {
4204
+ let { watchFiles } = devConfig;
4205
+ if (!watchFiles) return;
4206
+ let watchers = [];
4207
+ for (let { paths, options, type } of helpers_castArray(watchFiles)){
4208
+ let watchOptions = prepareWatchOptions(paths, options, type), watcher = await startWatchFiles(watchOptions, buildManager, root);
4209
+ watcher && watchers.push(watcher);
4210
+ }
4211
+ return async ()=>{
4212
+ for (let watcher of watchers)await watcher.close();
4213
+ };
4214
+ }
4215
+ function watchServerFiles({ publicDir }, buildManager, root) {
4216
+ if (!publicDir.length) return;
4217
+ let watchPaths = publicDir.filter((item)=>item.watch).map((item)=>item.name);
4218
+ if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), buildManager, root);
4219
+ }
4220
+ function prepareWatchOptions(paths, options = {}, type) {
4221
+ return {
4222
+ paths: 'string' == typeof paths ? [
4223
+ paths
4224
+ ] : paths,
4225
+ options,
4226
+ type
4227
+ };
4228
+ }
4229
+ let GLOB_REGEX = /[*?{}[\]()!+|]/;
4230
+ async function createChokidar(pathOrGlobs, root, options) {
4231
+ let { default: chokidar } = await import("./chokidar.js"), watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
4232
+ if (globPatterns.length) {
4233
+ let { glob } = await import("./tinyglobby.js");
4234
+ for (let file of (await glob(globPatterns, {
4235
+ cwd: root,
4236
+ absolute: !0
4237
+ })))watchFiles.add(file);
4238
+ }
4239
+ return chokidar.watch(Array.from(watchFiles), options);
4240
+ }
4241
+ async function startWatchFiles({ paths, options, type = 'reload-page' }, buildManager, root) {
4242
+ if ('reload-page' !== type) return;
4243
+ let watcher = await createChokidar(paths, root, options);
4244
+ return watcher.on('change', ()=>{
4245
+ buildManager.socketServer.sendMessage({
4246
+ type: 'full-reload'
4247
+ });
4248
+ }), watcher;
4249
+ }
4250
+ let requestRestart = ({ filePath, clear = !0, action, logger, restartManager })=>{
4251
+ if (restartManager.canRestart) {
4252
+ clear && isTTY() && !process.env.DEBUG && process.stdout.write('\x1B[H\x1B[2J');
4253
+ let id = 'dev' === action ? 'server' : 'build';
4254
+ if (filePath) {
4255
+ let filename = node_path.basename(filePath);
4256
+ logger.info(`restarting ${id} as ${color.yellow(filename)} changed\n`);
4257
+ } else logger.info(`restarting ${id}...\n`);
4258
+ }
4259
+ return restartManager.requestRestart({
4260
+ action,
4261
+ filePath
4262
+ });
4263
+ };
4264
+ function watchFilesForRestart({ watchFiles, context, action }) {
4265
+ let closePromise, defaultFiles = context.configFile ? [
4266
+ context.configFile,
4267
+ ...context.configFileDependencies
4268
+ ] : [];
4269
+ if (!watchFiles.length && !defaultFiles.length) return;
4270
+ let watchGroups = [];
4271
+ for (let { paths, options, type } of watchFiles){
4272
+ if ('restart' !== type && 'reload-server' !== type) continue;
4273
+ let files = helpers_castArray(paths);
4274
+ files.length && (options ? watchGroups.push({
4275
+ files,
4276
+ options
4277
+ }) : defaultFiles.push(...files));
4278
+ }
4279
+ if (defaultFiles.length && watchGroups.push({
4280
+ files: defaultFiles
4281
+ }), !watchGroups.length) return;
4282
+ let { logger, restartManager, rootPath: root } = context, restarting = !1, onChange = async (filePath, cwd)=>{
4283
+ if (restarting || closePromise) return;
4284
+ restarting = !0;
4285
+ let absoluteFilePath = node_path.resolve(cwd, filePath);
4286
+ try {
4287
+ await requestRestart({
4288
+ action,
4289
+ filePath: absoluteFilePath,
4290
+ logger,
4291
+ restartManager
4292
+ }) ? await close() : restartManager.canRestart && logger.error('build' === action ? 'Restart build failed.' : 'Restart server failed.');
4293
+ } catch (error) {
4294
+ logger.error(error);
4295
+ } finally{
4296
+ restarting = !1;
4297
+ }
4298
+ }, watchersPromise = Promise.all(watchGroups.map(async ({ files, options })=>{
4299
+ try {
4300
+ let watcher = await createChokidar(files, root, {
4301
+ ignoreInitial: !0,
4302
+ ignorePermissionErrors: !0,
4303
+ ...options
4304
+ }), cwd = options?.cwd || root, handleChange = (filePath)=>void onChange(filePath, cwd);
4305
+ return watcher.on('add', handleChange), watcher.on('change', handleChange), watcher.on('unlink', handleChange), watcher;
4306
+ } catch (error) {
4307
+ logger.error(error);
4308
+ }
4309
+ })), close = ()=>(closePromise || (closePromise = watchersPromise.then((watchers)=>Promise.all(watchers.map((watcher)=>watcher?.close()))).then(()=>{})), closePromise);
4310
+ return {
4311
+ close
4312
+ };
4313
+ }
4146
4314
  let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOptions, { watch } = {})=>{
4147
- let { context } = initOptions, { logger } = context, { compiler, rspackConfigs } = await createCompiler_createCompiler(initOptions);
4315
+ let stats, closeCompiler, closingPromise, unregisterRestart, restartWatcher, { context } = initOptions, { logger } = context, { compiler, rspackConfigs } = await createCompiler_createCompiler(initOptions);
4148
4316
  if ((({ context, isWatch, compiler, rspackConfigs, MultiStatsCtor })=>{
4149
4317
  let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
4150
4318
  let promise = context.hooks.onAfterBuild.callBatch({
@@ -4206,28 +4374,32 @@ let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOption
4206
4374
  MultiStatsCtor: core_rspack.MultiStats
4207
4375
  }), watch) {
4208
4376
  let watchOptions = rspackConfigs.map((options)=>options.watchOptions || {});
4209
- return compiler.watch(watchOptions.length > 1 ? watchOptions : watchOptions[0] || {}, (err)=>{
4377
+ compiler.watch(watchOptions.length > 1 ? watchOptions : watchOptions[0] || {}, (err)=>{
4210
4378
  err && logger.error(err);
4211
- }), {
4212
- close: ()=>new Promise((resolve)=>{
4213
- compiler.close(()=>{
4214
- resolve();
4215
- });
4216
- })
4217
- };
4218
- }
4219
- let { stats } = await new Promise((resolve, reject)=>{
4379
+ }), closeCompiler = ()=>new Promise((resolve)=>{
4380
+ compiler.close(()=>{
4381
+ resolve();
4382
+ });
4383
+ });
4384
+ } else stats = await new Promise((resolve, reject)=>{
4220
4385
  compiler.run((err, stats)=>{
4221
4386
  compiler.close((closeErr)=>{
4222
- closeErr && logger.error('Failed to close compiler: ', closeErr), err ? reject(err) : context.buildState.hasErrors ? reject(Error(RSPACK_BUILD_ERROR)) : resolve({
4223
- stats
4224
- });
4387
+ closeErr && logger.error('Failed to close compiler: ', closeErr), err ? reject(err) : context.buildState.hasErrors ? reject(Error(RSPACK_BUILD_ERROR)) : resolve(stats);
4225
4388
  });
4226
4389
  });
4227
4390
  });
4228
- return {
4391
+ let closeBuild = ()=>closingPromise ||= (async ()=>{
4392
+ unregisterRestart?.(), unregisterRestart = void 0, await context.hooks.onCloseBuild.callBatch(), await closeCompiler?.();
4393
+ })();
4394
+ return watch && (unregisterRestart = context.restartManager.registerCleanup(closeBuild), restartWatcher = watchFilesForRestart({
4395
+ watchFiles: context.normalizedConfig.dev.watchFiles,
4396
+ context,
4397
+ action: 'build'
4398
+ })), {
4229
4399
  stats,
4230
- close: async ()=>{}
4400
+ close: async ()=>{
4401
+ await restartWatcher?.close(), await closeBuild();
4402
+ }
4231
4403
  };
4232
4404
  }, main = __webpack_require__("../../node_modules/.pnpm/dotenv-expand@13.0.0_patch_hash=5ff37847fa487be2db4e4f14c2b21937f4e51cc7a43deea4506d4aaf3fa6149c/node_modules/dotenv-expand/lib/main.js"), DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
4233
4405
  function loadEnv_parse(src) {
@@ -4746,7 +4918,7 @@ function getRegExpForExts(exts) {
4746
4918
  function getCacheDirectory({ cacheDirectory }, context) {
4747
4919
  return cacheDirectory ? external_node_path_isAbsolute(cacheDirectory) ? cacheDirectory : join(context.rootPath, cacheDirectory) : join(context.cachePath, 'rspack');
4748
4920
  }
4749
- async function getBuildDependencies(context, config, environmentContext, additionalDependencies) {
4921
+ async function getBuildDependencies(context, environmentContext, additionalDependencies) {
4750
4922
  let rootPackageJson = join(context.rootPath, 'package.json'), browserslistConfig = join(context.rootPath, '.browserslistrc'), buildDependencies = {};
4751
4923
  await isFileExists(rootPackageJson) && (buildDependencies.packageJson = [
4752
4924
  rootPackageJson
@@ -4754,8 +4926,9 @@ async function getBuildDependencies(context, config, environmentContext, additio
4754
4926
  let { tsconfigPath } = environmentContext;
4755
4927
  tsconfigPath && (buildDependencies.tsconfig = [
4756
4928
  tsconfigPath
4757
- ]), config._privateMeta?.configFilePath && (buildDependencies.rsbuildConfig = [
4758
- config._privateMeta.configFilePath
4929
+ ]), context.configFile && (buildDependencies.rsbuildConfig = [
4930
+ context.configFile,
4931
+ ...context.configFileDependencies
4759
4932
  ]), await isFileExists(browserslistConfig) && (buildDependencies.browserslistrc = [
4760
4933
  browserslistConfig
4761
4934
  ]);
@@ -4843,7 +5016,7 @@ function parseMinifyOptions(config) {
4843
5016
  cssOptions: minify.cssOptions
4844
5017
  };
4845
5018
  }
4846
- let postcss_load_config_src = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/index.js");
5019
+ let postcss_load_config_src = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/index.js");
4847
5020
  var postcss_load_config_src_default = __webpack_require__.n(postcss_load_config_src);
4848
5021
  async function getLightningCSSLoaderOptions(config, targets, minify) {
4849
5022
  let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
@@ -5095,7 +5268,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5095
5268
  if (!showTotal && !showDetail) return {
5096
5269
  logs
5097
5270
  };
5098
- let relativeDistPath = node_path.relative(rootPath, distPath), snapshot = saveSnapshot ? {
5271
+ let relativeDistPath = node_path.relative(rootPath, distPath), rootFolderLabel = `${relativeDistPath || '.'}${node_path.sep}`, snapshot = saveSnapshot ? {
5099
5272
  files: {},
5100
5273
  totalSize: 0,
5101
5274
  totalGzipSize: 0
@@ -5117,7 +5290,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5117
5290
  isSignificantDiff(gzipDiff) && (gzipSizeLabel += ` ${formatDiff(gzipDiff).label}`);
5118
5291
  }
5119
5292
  }
5120
- let separatorIndex = filePath.lastIndexOf('/'), folderLabel = (-1 === separatorIndex ? node_path.join(relativeDistPath, '.') : node_path.join(relativeDistPath, filePath.slice(0, separatorIndex))) + node_path.sep, filename = -1 === separatorIndex ? filePath : filePath.slice(separatorIndex + 1);
5293
+ let separatorIndex = filePath.lastIndexOf('/'), folderLabel = -1 === separatorIndex ? rootFolderLabel : `${node_path.join(relativeDistPath, filePath.slice(0, separatorIndex))}${node_path.sep}`, filename = -1 === separatorIndex ? filePath : filePath.slice(separatorIndex + 1);
5121
5294
  return {
5122
5295
  filePath,
5123
5296
  filenameLabel: color.dim(folderLabel) + (JS_REGEX.test(filename) ? color.cyan(filename) : filename.endsWith('.css') ? color.yellow(filename) : filename.endsWith('.html') ? color.green(filename) : color.magenta(filename)),
@@ -5806,6 +5979,8 @@ async function open_open({ port, routes, config, protocol, clearCache, logger })
5806
5979
  for (let url of (targets.length ? urls.push(...targets.map((target)=>resolveUrl(replacePortPlaceholder(target, port), baseUrl))) : routes.length ? urls.push(`${baseUrl}${routes[0].pathname}`) : urls.push(baseUrl), before && await before(), urls))openedURLs.includes(url) || (openBrowser(url, logger), openedURLs.push(url));
5807
5980
  }
5808
5981
  let getServerUrlFromClientConfig = async (config, context)=>{
5982
+ let { assetPrefix } = config.dev;
5983
+ if (!(!0 === assetPrefix || 'string' == typeof assetPrefix && isURL(assetPrefix))) return;
5809
5984
  let { devServer } = context;
5810
5985
  if (!devServer) return;
5811
5986
  let { client } = config.dev, hasClientHost = !!client.host, hasClientPort = void 0 !== client.port && '' !== client.port;
@@ -7953,69 +8128,9 @@ async function applyServerSetup(setup, context) {
7953
8128
  }
7954
8129
  return postCallbacks;
7955
8130
  }
7956
- async function setupWatchFiles(options) {
7957
- let { config, root, buildManager } = options, { hmr, liveReload } = config.dev;
7958
- if (!hmr && !liveReload || !buildManager) return;
7959
- let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root), serverFilesWatcher = await watchServerFiles(config.server, buildManager, root);
7960
- return {
7961
- async close () {
7962
- await Promise.all([
7963
- closeDevFilesWatcher?.(),
7964
- serverFilesWatcher?.close()
7965
- ]);
7966
- }
7967
- };
7968
- }
7969
- async function watchDevFiles(devConfig, buildManager, root) {
7970
- let { watchFiles } = devConfig;
7971
- if (!watchFiles) return;
7972
- let watchers = [];
7973
- for (let { paths, options, type } of helpers_castArray(watchFiles)){
7974
- let watchOptions = prepareWatchOptions(paths, options, type), watcher = await startWatchFiles(watchOptions, buildManager, root);
7975
- watcher && watchers.push(watcher);
7976
- }
7977
- return async ()=>{
7978
- for (let watcher of watchers)await watcher.close();
7979
- };
7980
- }
7981
- function watchServerFiles({ publicDir }, buildManager, root) {
7982
- if (!publicDir.length) return;
7983
- let watchPaths = publicDir.filter((item)=>item.watch).map((item)=>item.name);
7984
- if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), buildManager, root);
7985
- }
7986
- function prepareWatchOptions(paths, options = {}, type) {
7987
- return {
7988
- paths: 'string' == typeof paths ? [
7989
- paths
7990
- ] : paths,
7991
- options,
7992
- type
7993
- };
7994
- }
7995
- let GLOB_REGEX = /[*?{}[\]()!+|]/;
7996
- async function createChokidar(pathOrGlobs, root, options) {
7997
- let { default: chokidar } = await import("./chokidar.js"), watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
7998
- if (globPatterns.length) {
7999
- let { glob } = await import("./tinyglobby.js");
8000
- for (let file of (await glob(globPatterns, {
8001
- cwd: root,
8002
- absolute: !0
8003
- })))watchFiles.add(file);
8004
- }
8005
- return chokidar.watch(Array.from(watchFiles), options);
8006
- }
8007
- async function startWatchFiles({ paths, options, type = 'reload-page' }, buildManager, root) {
8008
- if ('reload-page' !== type) return;
8009
- let watcher = await createChokidar(paths, root, options);
8010
- return watcher.on('change', ()=>{
8011
- buildManager.socketServer.sendMessage({
8012
- type: 'full-reload'
8013
- });
8014
- }), watcher;
8015
- }
8016
8131
  async function devServer_createDevServer(options, createCompiler, config, { getPortSilently, runCompile = !0 } = {}) {
8017
8132
  var environmentCount;
8018
- let stats, waiters, { context } = options, { logger } = context;
8133
+ let closingPromise, unregisterRestart, stats, waiters, { context } = options, { logger } = context;
8019
8134
  logger.debug('create dev server');
8020
8135
  let { port, portTip } = await resolvePort(config), { middlewareMode, host } = config.server, isHttps = !!config.server.https, routes = getRoutes(context), fallbackPathname = 0 === routes.length && context.environmentList.some((item)=>'web' === item.config.output.target) ? config.server.base : void 0;
8021
8136
  context.devServer = {
@@ -8086,12 +8201,22 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
8086
8201
  protocol,
8087
8202
  clearCache: !0,
8088
8203
  logger
8089
- }), state = {}, cleanupGracefulShutdown = middlewareMode ? null : setupGracefulShutdown(), closingPromise = null, closeServer = async ()=>(closingPromise || (closingPromise = (async ()=>{
8204
+ }), state = {}, cleanupGracefulShutdown = middlewareMode ? null : setupGracefulShutdown(), closeServerResources = ()=>(closingPromise || (unregisterRestart?.(), unregisterRestart = void 0, closingPromise = (async ()=>{
8090
8205
  removeCleanup(closeServer), cleanupGracefulShutdown?.(), await context.hooks.onCloseDevServer.callBatch(), await Promise.all([
8091
8206
  state.devMiddlewares?.close(),
8092
8207
  state.fileWatcher?.close()
8093
8208
  ]);
8094
- })()), closingPromise);
8209
+ })()), closingPromise), closeServer = async ()=>{
8210
+ await state.restartWatcher?.close(), await closeServerResources();
8211
+ }, restartServer = async ()=>{
8212
+ let restarted = await requestRestart({
8213
+ action: 'dev',
8214
+ clear: !1,
8215
+ logger,
8216
+ restartManager: context.restartManager
8217
+ });
8218
+ return restarted && await state.restartWatcher?.close(), restarted;
8219
+ };
8095
8220
  middlewareMode || registerCleanup(closeServer);
8096
8221
  let beforeCreateCompiler = async ()=>{
8097
8222
  if (printUrls(), cliShortcutsEnabled) {
@@ -8099,10 +8224,7 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
8099
8224
  openPage,
8100
8225
  closeServer,
8101
8226
  printUrls,
8102
- restartServer: ()=>restartDevServer({
8103
- clear: !1,
8104
- logger
8105
- }),
8227
+ restartServer: context.restartManager.canRestart ? restartServer : void 0,
8106
8228
  help: shortcutsOptions.help,
8107
8229
  customShortcuts: shortcutsOptions.custom,
8108
8230
  logger
@@ -8163,7 +8285,7 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
8163
8285
  port
8164
8286
  }, async (err)=>{
8165
8287
  if (err) throw err;
8166
- middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), state.devMiddlewares && httpServer.on('upgrade', state.devMiddlewares.onUpgrade), logger.debug('listen dev server done'), await devServer.afterListen(), onBeforeRestartServer(devServer.close), resolve({
8288
+ middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), state.devMiddlewares && httpServer.on('upgrade', state.devMiddlewares.onUpgrade), logger.debug('listen dev server done'), await devServer.afterListen(), resolve({
8167
8289
  port,
8168
8290
  urls: urls.map((item)=>item.url),
8169
8291
  server: devServer
@@ -8205,7 +8327,11 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
8205
8327
  devServer,
8206
8328
  context,
8207
8329
  postCallbacks
8208
- }), state.buildManager?.watch(), logger.debug('create dev server done'), devServer;
8330
+ }), state.buildManager?.watch(), unregisterRestart = context.restartManager.registerCleanup(closeServerResources), state.restartWatcher = watchFilesForRestart({
8331
+ watchFiles: config.dev.watchFiles,
8332
+ context,
8333
+ action: 'dev'
8334
+ }), logger.debug('create dev server done'), devServer;
8209
8335
  }
8210
8336
  async function startPreviewServer(context, config, { getPortSilently } = {}) {
8211
8337
  let environmentList, { logger } = context, { connect } = await import("./connect-next.js"), middlewares = connect(), { port, portTip } = await resolvePort(config), serverConfig = config.server, { host, headers, proxy, historyApiFallback, compress, base, cors } = serverConfig, assetPrefixes = context.environmentList.map((environment)=>environment.config.output.assetPrefix);
@@ -8437,7 +8563,7 @@ function applyDefaultPlugins(pluginManager, context) {
8437
8563
  let { config } = environment, { buildCache = !1 } = config.performance;
8438
8564
  if (!1 === buildCache) return;
8439
8565
  cacheEnabled = !0;
8440
- let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = getCacheDirectory(cacheConfig, context), buildDependencies = await getBuildDependencies(context, config, environment, cacheConfig.buildDependencies), cacheVersion = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length ? `${environment.name}-${env}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : `${environment.name}-${env}`;
8566
+ let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = getCacheDirectory(cacheConfig, context), buildDependencies = await getBuildDependencies(context, environment, cacheConfig.buildDependencies), cacheVersion = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length ? `${environment.name}-${env}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : `${environment.name}-${env}`;
8441
8567
  chain.cache({
8442
8568
  type: 'persistent',
8443
8569
  version: cacheVersion,
@@ -8562,7 +8688,7 @@ function applyDefaultPlugins(pluginManager, context) {
8562
8688
  let showDiff = environments.some((environment)=>{
8563
8689
  let { printFileSize } = environment.config.performance;
8564
8690
  return 'object' == typeof printFileSize && !!printFileSize.diff;
8565
- }), { configFilePath } = api.getNormalizedConfig()._privateMeta || {}, snapshotHash = showDiff && configFilePath ? await helpers_hash(configFilePath) : '', snapshotPath = showDiff ? getSnapshotPath(api.context.cachePath, snapshotHash) : '', prevSnapshots = showDiff ? await loadPrevSnapshots(snapshotPath) : null, nextSnapshots = {}, logs = await Promise.all(environments.map(async ({ name, index, config, distPath })=>{
8691
+ }), { configFile } = api.context, snapshotHash = showDiff && configFile ? await helpers_hash(configFile) : '', snapshotPath = showDiff ? getSnapshotPath(api.context.cachePath, snapshotHash) : '', prevSnapshots = showDiff ? await loadPrevSnapshots(snapshotPath) : null, nextSnapshots = {}, logs = await Promise.all(environments.map(async ({ name, index, config, distPath })=>{
8566
8692
  let statsItem = 'stats' in stats ? stats.stats[index] : stats, { logs: sizeLogs, snapshot } = await printFileSizes(((config)=>{
8567
8693
  let { printFileSize } = config.performance, defaultConfig = {
8568
8694
  total: !0,
@@ -9054,9 +9180,16 @@ try {
9054
9180
  setup (api) {
9055
9181
  api.modifyBundlerChain(async (chain, { environment, CHAIN_ID, rspack })=>{
9056
9182
  let { config } = environment, { minifyJs, minifyCss, jsOptions, cssOptions } = parseMinifyOptions(config);
9057
- if (chain.optimization.minimize(minifyJs || minifyCss), minifyJs && chain.optimization.minimizer(CHAIN_ID.MINIMIZER.JS).use(rspack.SwcJsMinimizerRspackPlugin, [
9058
- getSwcMinimizerOptions(config, jsOptions)
9059
- ]).end(), minifyCss) {
9183
+ if (chain.optimization.minimize(minifyJs || minifyCss), minifyJs) {
9184
+ let registerJsMinimizer = (jsOptionsItem, index = 0)=>{
9185
+ let minimizerId = 0 === index ? CHAIN_ID.MINIMIZER.JS : `${CHAIN_ID.MINIMIZER.JS}-${index}`;
9186
+ chain.optimization.minimizer(minimizerId).use(rspack.SwcJsMinimizerRspackPlugin, [
9187
+ getSwcMinimizerOptions(config, jsOptionsItem)
9188
+ ]).end();
9189
+ }, jsOptionsList = helpers_castArray(jsOptions);
9190
+ jsOptionsList.length > 0 ? jsOptionsList.forEach(registerJsMinimizer) : registerJsMinimizer();
9191
+ }
9192
+ if (minifyCss) {
9060
9193
  let loaderOptions = await getLightningCSSLoaderOptions(config, environment.browserslist, !0), defaultOptions = {
9061
9194
  minimizerOptions: {
9062
9195
  targets: isPlainObject(loaderOptions.targets) ? environment.browserslist : loaderOptions.targets,
@@ -9418,7 +9551,7 @@ try {
9418
9551
  api.modifyBundlerChain(async (chain, { CHAIN_ID, environment, isDev })=>{
9419
9552
  let { output: { manifest }, dev: { writeToDisk } } = environment.config;
9420
9553
  if (!1 === manifest) return;
9421
- let manifestOptions = normalizeManifestObjectConfig(manifest), { RspackManifestPlugin } = await import("./manifest-plugin.js").then(__webpack_require__.bind(__webpack_require__, "../../node_modules/.pnpm/rspack-manifest-plugin@5.2.2_@rspack+core@2.1.4/node_modules/rspack-manifest-plugin/dist/index.js")), { htmlPaths } = environment, filter = manifestOptions.filter ?? ((file)=>!file.name.endsWith('.LICENSE.txt'));
9554
+ let manifestOptions = normalizeManifestObjectConfig(manifest), { RspackManifestPlugin } = await import("./manifest-plugin.js").then(__webpack_require__.bind(__webpack_require__, "../../node_modules/.pnpm/rspack-manifest-plugin@5.2.2_@rspack+core@2.1.5/node_modules/rspack-manifest-plugin/dist/index.js")), { htmlPaths } = environment, filter = manifestOptions.filter ?? ((file)=>!file.name.endsWith('.LICENSE.txt'));
9422
9555
  manifestFilenames.set(environment.name, manifestOptions.filename);
9423
9556
  let pluginOptions = {
9424
9557
  fileName: manifestOptions.filename,
@@ -9605,7 +9738,7 @@ function applyEnvsToConfig(config, envs) {
9605
9738
  ...config.dev.watchFiles ? helpers_castArray(config.dev.watchFiles) : [],
9606
9739
  {
9607
9740
  paths: envs.filePaths,
9608
- type: 'reload-server'
9741
+ type: 'restart'
9609
9742
  }
9610
9743
  ], config.performance?.buildCache))) {
9611
9744
  let { buildCache } = config.performance;
@@ -9614,11 +9747,16 @@ function applyEnvsToConfig(config, envs) {
9614
9747
  } : (buildCache.buildDependencies ||= [], buildCache.buildDependencies.push(...envs.filePaths));
9615
9748
  }
9616
9749
  }
9750
+ function isLoadConfigResult(result) {
9751
+ return 'object' == typeof result && null !== result && 'content' in result && 'filePath' in result && 'dependencies' in result;
9752
+ }
9617
9753
  async function createRsbuild(options = {}) {
9618
- let envs = options.loadEnv ? loadEnv({
9754
+ let loadConfigResult, envs = options.loadEnv ? loadEnv({
9619
9755
  cwd: options.cwd,
9620
9756
  ...'boolean' == typeof options.loadEnv ? {} : options.loadEnv
9621
- }) : null, configOrFactory = options.config ?? options.rsbuildConfig, config = isFunction(configOrFactory) ? await configOrFactory() : configOrFactory || {}, logger = config.customLogger ?? logger_createLogger({
9757
+ }) : null, configOrFactory = options.config ?? options.rsbuildConfig, config = isFunction(configOrFactory) ? await configOrFactory() : configOrFactory;
9758
+ isLoadConfigResult(config) && (loadConfigResult = config, config = config.content);
9759
+ let logger = (config ||= {}).customLogger ?? logger_createLogger({
9622
9760
  ...src_logger.options,
9623
9761
  level: src_logger.level
9624
9762
  });
@@ -9628,7 +9766,7 @@ async function createRsbuild(options = {}) {
9628
9766
  callerName: 'rsbuild',
9629
9767
  ...options,
9630
9768
  rsbuildConfig: config
9631
- }, pluginManager = createPluginManager(logger), context = await createContext(resolvedOptions, config, logger), getPluginAPI = initPluginAPI({
9769
+ }, pluginManager = createPluginManager(logger), context = await createContext(resolvedOptions, config, logger, loadConfigResult), getPluginAPI = initPluginAPI({
9632
9770
  context,
9633
9771
  pluginManager
9634
9772
  });
@@ -9650,20 +9788,11 @@ async function createRsbuild(options = {}) {
9650
9788
  if (isEmptyDir(distPath)) throw Error(`${color.dim('[rsbuild:preview]')} The output directory ${color.yellow(distPath)} is empty, please build the project before previewing.`);
9651
9789
  }
9652
9790
  return startPreviewServer(context, config, options);
9653
- }, build = async (options)=>{
9654
- context.action = 'build', process.env.NODE_ENV || setNodeEnv('production');
9655
- let buildInstance = await build_build({
9791
+ }, build = async (options)=>(context.action = 'build', process.env.NODE_ENV || setNodeEnv('production'), build_build({
9656
9792
  context,
9657
9793
  pluginManager,
9658
9794
  rsbuildOptions: resolvedOptions
9659
- }, options);
9660
- return {
9661
- ...buildInstance,
9662
- close: async ()=>{
9663
- await context.hooks.onCloseBuild.callBatch(), await buildInstance.close();
9664
- }
9665
- };
9666
- }, startDevServer = async (options)=>{
9795
+ }, options)), startDevServer = async (options)=>{
9667
9796
  context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development');
9668
9797
  let config = await initRsbuildConfig({
9669
9798
  context,
@@ -9750,7 +9879,8 @@ async function createRsbuild(options = {}) {
9750
9879
  'onCloseBuild',
9751
9880
  'onCloseDevServer',
9752
9881
  'onDevCompileDone',
9753
- 'onExit'
9882
+ 'onExit',
9883
+ 'onRestart'
9754
9884
  ])
9755
9885
  };
9756
9886
  envs && (rsbuild.onCloseBuild(envs.cleanup), rsbuild.onCloseDevServer(envs.cleanup));
@@ -9897,7 +10027,8 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, configFileName
9897
10027
  if (!result.filePath) return src_logger.debug('no config file found.'), result;
9898
10028
  if (!isObject(result.content)) throw Error(`The config must be an object or a function that returns an object, get ${color.yellow(String(result.content))}`);
9899
10029
  return result.content._privateMeta = {
9900
- configFilePath: result.filePath
10030
+ configFilePath: result.filePath,
10031
+ configFileDependencies: result.dependencies
9901
10032
  }, src_logger.debug('configuration loaded from:', result.filePath), result;
9902
10033
  }
9903
10034
  let cliState = {
@@ -9905,13 +10036,13 @@ let cliState = {
9905
10036
  }, initCliAction = (command, options)=>{
9906
10037
  process.env.NODE_ENV || (process.env.NODE_ENV = 'build' === command || 'preview' === command ? 'production' : 'development'), options.environment?.some((env)=>env.includes(',')) && (options.environment = options.environment.flatMap((env)=>env.split(','))), cliState.command = command, cliState.options = options;
9907
10038
  }, init_loadConfig = async (root)=>{
9908
- let { options, command } = cliState, { content: config, filePath, dependencies } = await loadConfig_loadConfig({
10039
+ let { options, command } = cliState, result = await loadConfig_loadConfig({
9909
10040
  cwd: root,
9910
10041
  path: options.config,
9911
10042
  envMode: options.envMode,
9912
10043
  loader: options.configLoader,
9913
10044
  command
9914
- });
10045
+ }), { content: config } = result;
9915
10046
  if (config.dev ||= {}, config.source ||= {}, config.server ||= {}, options.base && (config.server.base = options.base), options.root && (config.root = root), options.mode && (config.mode = options.mode), options.logLevel && (config.logLevel = options.logLevel), options.open && !config.server?.open && (config.server.open = options.open), void 0 !== options.host && (config.server.host = options.host), options.port && (config.server.port = options.port), void 0 !== options.strictPort && (config.server.strictPort = options.strictPort), void 0 !== options.distPath) {
9916
10047
  config.output ||= {};
9917
10048
  let { distPath } = config.output;
@@ -9927,18 +10058,16 @@ let cliState = {
9927
10058
  if ('boolean' != typeof sourceMap) throw Error('The "--source-map" option only accepts a boolean value.');
9928
10059
  config.output ||= {}, config.output.sourceMap = sourceMap;
9929
10060
  }
9930
- return void 0 === config.dev.cliShortcuts && (config.dev.cliShortcuts = !0), filePath && (config.dev.watchFiles = [
9931
- ...config.dev.watchFiles ? helpers_castArray(config.dev.watchFiles) : [],
9932
- {
9933
- paths: [
9934
- filePath,
9935
- ...dependencies
9936
- ],
9937
- type: 'reload-server'
9938
- }
9939
- ]), config;
10061
+ return void 0 === config.dev.cliShortcuts && (config.dev.cliShortcuts = !0), result;
10062
+ }, init_restart = async ({ action })=>{
10063
+ let rsbuild = await init_init({
10064
+ isRestart: !0
10065
+ });
10066
+ return !!rsbuild && ('build' === action ? await rsbuild.build({
10067
+ watch: !0
10068
+ }) : await rsbuild.startDevServer(), !0);
9940
10069
  };
9941
- async function init_init({ isRestart, isBuildWatch = !1 } = {}) {
10070
+ async function init_init({ isRestart } = {}) {
9942
10071
  let logger = src_logger, { options } = cliState;
9943
10072
  try {
9944
10073
  var envDir;
@@ -9949,90 +10078,21 @@ async function init_init({ isRestart, isBuildWatch = !1 } = {}) {
9949
10078
  loadEnv: !1 !== options.env && {
9950
10079
  cwd: (envDir = options.envDir) ? node_path.isAbsolute(envDir) ? envDir : node_path.join(root, envDir) : root,
9951
10080
  mode: options.envMode
9952
- }
10081
+ },
10082
+ restart: init_restart
9953
10083
  });
9954
- return logger = rsbuild.logger, rsbuild.onBeforeCreateCompiler(()=>{
9955
- if ('dev' !== rsbuild.context.action && !isBuildWatch) return;
9956
- let files = [], config = rsbuild.getNormalizedConfig();
9957
- if (config.dev.watchFiles) for (let watchConfig of config.dev.watchFiles){
9958
- if ('reload-server' !== watchConfig.type) continue;
9959
- let paths = helpers_castArray(watchConfig.paths);
9960
- watchConfig.options ? watchFilesForRestart({
9961
- files: paths,
9962
- rsbuild,
9963
- isBuildWatch,
9964
- watchOptions: watchConfig.options
9965
- }) : files.push(...paths);
9966
- }
9967
- watchFilesForRestart({
9968
- files,
9969
- rsbuild,
9970
- isBuildWatch
9971
- });
9972
- }), rsbuild;
10084
+ return logger = rsbuild.logger, rsbuild;
9973
10085
  } catch (err) {
9974
10086
  if (isRestart) logger.error(err);
9975
10087
  else throw err;
9976
10088
  }
9977
10089
  }
9978
- let cleaners = [], onBeforeRestartServer = (cleaner)=>{
9979
- cleaners.push(cleaner);
9980
- }, beforeRestart = async ({ filePath, clear = !0, id, logger })=>{
9981
- if (clear && isTTY() && !process.env.DEBUG && process.stdout.write('\x1B[H\x1B[2J'), filePath) {
9982
- let filename = node_path.basename(filePath);
9983
- logger.info(`restarting ${id} as ${color.yellow(filename)} changed\n`);
9984
- } else logger.info(`restarting ${id}...\n`);
9985
- for (let cleaner of cleaners)await cleaner();
9986
- cleaners = [];
9987
- }, restartDevServer = async ({ filePath, clear = !0, logger })=>{
9988
- await beforeRestart({
9989
- filePath,
9990
- clear,
9991
- id: 'server',
9992
- logger
9993
- });
9994
- let rsbuild = await init_init({
9995
- isRestart: !0
9996
- });
9997
- return !!rsbuild && (await rsbuild.startDevServer(), !0);
9998
- }, restartBuild = async ({ filePath, clear = !0, logger })=>{
9999
- await beforeRestart({
10000
- filePath,
10001
- clear,
10002
- id: 'build',
10003
- logger
10004
- });
10005
- let rsbuild = await init_init({
10006
- isRestart: !0,
10007
- isBuildWatch: !0
10008
- });
10009
- return !!rsbuild && (onBeforeRestartServer((await rsbuild.build({
10010
- watch: !0
10011
- })).close), !0);
10012
- };
10013
- async function watchFilesForRestart({ files, rsbuild, isBuildWatch, watchOptions }) {
10014
- if (!files.length) return;
10015
- let root = rsbuild.context.rootPath, watcher = await createChokidar(files, root, {
10016
- ignoreInitial: !0,
10017
- ignorePermissionErrors: !0,
10018
- ...watchOptions
10019
- }), restarting = !1, onChange = async (filePath)=>{
10020
- restarting || (restarting = !0, (isBuildWatch ? await restartBuild({
10021
- filePath,
10022
- logger: rsbuild.logger
10023
- }) : await restartDevServer({
10024
- filePath,
10025
- logger: rsbuild.logger
10026
- })) ? await watcher.close() : rsbuild.logger.error(isBuildWatch ? 'Restart build failed.' : 'Restart server failed.'), restarting = !1);
10027
- };
10028
- watcher.on('add', onChange), watcher.on('change', onChange), watcher.on('unlink', onChange);
10029
- }
10030
10090
  let applyServerOptions = (command)=>{
10031
10091
  command.option('-o, --open [url]', 'Open the page in browser on startup').option('--port <port>', 'Set the port number for the server').option('--strict-port', 'Exit if the specified port is already in use').option('--host [host]', 'Set the host that the server listens to');
10032
10092
  };
10033
10093
  function setupCommands(argv) {
10034
10094
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10035
- cli.version("2.1.6"), 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)', {
10095
+ cli.version("2.1.7"), 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)', {
10036
10096
  default: 'auto'
10037
10097
  }).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', {
10038
10098
  type: [
@@ -10056,15 +10116,13 @@ function setupCommands(argv) {
10056
10116
  initCliAction('build', options);
10057
10117
  try {
10058
10118
  options.watch || (process.env.RSPACK_UNSAFE_FAST_DROP = 'true');
10059
- let rsbuild = await init_init({
10060
- isBuildWatch: options.watch
10061
- });
10119
+ let rsbuild = await init_init();
10062
10120
  if (!rsbuild) return;
10063
10121
  logger = rsbuild.logger;
10064
10122
  let buildResult = await rsbuild.build({
10065
10123
  watch: options.watch
10066
10124
  });
10067
- buildResult && (options.watch ? onBeforeRestartServer(buildResult.close) : await buildResult.close());
10125
+ options.watch || await buildResult.close();
10068
10126
  } catch (err) {
10069
10127
  err instanceof Error && err.message === RSPACK_BUILD_ERROR || logger.error('Failed to build.'), logger.error(err), process.exit(1);
10070
10128
  }
@@ -10091,12 +10149,15 @@ function setupCommands(argv) {
10091
10149
  logger.error('Failed to inspect config.'), logger.error(err), process.exit(1);
10092
10150
  }
10093
10151
  }), cli.help((sections)=>{
10094
- for (let section of (sections.shift(), sections))'Usage' === section.title && (section.body = section.body.replace('$ rsbuild', color.yellow("$ rsbuild [command] [options]"))), 'Commands' === section.title && (section.body = section.body.replace(` ${devDescription}`, `dev ${devDescription}`)), section.title?.startsWith('For more info') ? (section.title = color.dim(' For details on a sub-command, run'), section.body = color.dim(' $ rsbuild <command> -h')) : section.title && (section.title = color.cyan(section.title));
10152
+ sections.shift();
10153
+ let commandName = cli.matchedCommandName;
10154
+ for (let section of sections = sections.filter(({ title })=>!commandName || 'Commands' !== title && !title?.startsWith('For more info')))'Usage' === section.title && (section.body = ` ${color.yellow(`$ rsbuild ${commandName || '[command]'} [options]`)}`), 'Commands' === section.title && (section.body = section.body.replace(` ${devDescription}`, `dev ${devDescription}`)), section.title?.startsWith('For more info') ? (section.title = color.dim(' For details on a sub-command, run'), section.body = color.dim(' $ rsbuild <command> -h')) : section.title && (section.title = color.cyan(section.title));
10155
+ return sections;
10095
10156
  }), cli.parse(argv);
10096
10157
  }
10097
10158
  function showGreeting() {
10098
10159
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10099
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.1.6\n`);
10160
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.1.7\n`);
10100
10161
  }
10101
10162
  function setupLogLevel(argv) {
10102
10163
  if (argv.length <= 3) return;
@@ -10118,5 +10179,5 @@ function runCLI({ argv = process.argv } = {}) {
10118
10179
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10119
10180
  }
10120
10181
  }
10121
- let src_version = "2.1.6";
10182
+ let src_version = "2.1.7";
10122
10183
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, 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 };