@rsbuild/core 1.4.7 → 1.4.9

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.
@@ -1,19 +1,19 @@
1
1
  (() => {
2
2
  var __webpack_modules__ = {
3
- 6079: (module, __unused_webpack_exports, __nccwpck_require__) => {
3
+ 717: (module, __unused_webpack_exports, __nccwpck_require__) => {
4
4
  "use strict";
5
- const loader = __nccwpck_require__(6161);
5
+ const loader = __nccwpck_require__(8263);
6
6
  module.exports = loader.default;
7
7
  module.exports.defaultGetLocalIdent =
8
- __nccwpck_require__(3212).defaultGetLocalIdent;
8
+ __nccwpck_require__(8674).defaultGetLocalIdent;
9
9
  },
10
- 6161: (__unused_webpack_module, exports, __nccwpck_require__) => {
10
+ 8263: (__unused_webpack_module, exports, __nccwpck_require__) => {
11
11
  "use strict";
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports["default"] = loader;
14
14
  var _postcss = _interopRequireDefault(__nccwpck_require__(9409));
15
- var _plugins = __nccwpck_require__(4222);
16
- var _utils = __nccwpck_require__(3212);
15
+ var _plugins = __nccwpck_require__(4092);
16
+ var _utils = __nccwpck_require__(8674);
17
17
  function _interopRequireDefault(obj) {
18
18
  return obj && obj.__esModule ? obj : { default: obj };
19
19
  }
@@ -236,7 +236,7 @@
236
236
  callback(null, `${importCode}${moduleCode}${exportCode}`);
237
237
  }
238
238
  },
239
- 4222: (__unused_webpack_module, exports, __nccwpck_require__) => {
239
+ 4092: (__unused_webpack_module, exports, __nccwpck_require__) => {
240
240
  "use strict";
241
241
  Object.defineProperty(exports, "__esModule", { value: true });
242
242
  Object.defineProperty(exports, "icssParser", {
@@ -258,22 +258,22 @@
258
258
  },
259
259
  });
260
260
  var _postcssImportParser = _interopRequireDefault(
261
- __nccwpck_require__(7173),
261
+ __nccwpck_require__(5943),
262
262
  );
263
263
  var _postcssIcssParser = _interopRequireDefault(
264
- __nccwpck_require__(2420),
264
+ __nccwpck_require__(8058),
265
265
  );
266
- var _postcssUrlParser = _interopRequireDefault(__nccwpck_require__(835));
266
+ var _postcssUrlParser = _interopRequireDefault(__nccwpck_require__(9661));
267
267
  function _interopRequireDefault(obj) {
268
268
  return obj && obj.__esModule ? obj : { default: obj };
269
269
  }
270
270
  },
271
- 2420: (__unused_webpack_module, exports, __nccwpck_require__) => {
271
+ 8058: (__unused_webpack_module, exports, __nccwpck_require__) => {
272
272
  "use strict";
273
273
  Object.defineProperty(exports, "__esModule", { value: true });
274
274
  exports["default"] = void 0;
275
275
  var _icssUtils = __nccwpck_require__(9028);
276
- var _utils = __nccwpck_require__(3212);
276
+ var _utils = __nccwpck_require__(8674);
277
277
  const plugin = (options = {}) => ({
278
278
  postcssPlugin: "postcss-icss-parser",
279
279
  async OnceExit(root) {
@@ -372,14 +372,14 @@
372
372
  plugin.postcss = true;
373
373
  var _default = (exports["default"] = plugin);
374
374
  },
375
- 7173: (__unused_webpack_module, exports, __nccwpck_require__) => {
375
+ 5943: (__unused_webpack_module, exports, __nccwpck_require__) => {
376
376
  "use strict";
377
377
  Object.defineProperty(exports, "__esModule", { value: true });
378
378
  exports["default"] = void 0;
379
379
  var _postcssValueParser = _interopRequireDefault(
380
380
  __nccwpck_require__(2948),
381
381
  );
382
- var _utils = __nccwpck_require__(3212);
382
+ var _utils = __nccwpck_require__(8674);
383
383
  function _interopRequireDefault(obj) {
384
384
  return obj && obj.__esModule ? obj : { default: obj };
385
385
  }
@@ -684,14 +684,14 @@
684
684
  plugin.postcss = true;
685
685
  var _default = (exports["default"] = plugin);
686
686
  },
687
- 835: (__unused_webpack_module, exports, __nccwpck_require__) => {
687
+ 9661: (__unused_webpack_module, exports, __nccwpck_require__) => {
688
688
  "use strict";
689
689
  Object.defineProperty(exports, "__esModule", { value: true });
690
690
  exports["default"] = void 0;
691
691
  var _postcssValueParser = _interopRequireDefault(
692
692
  __nccwpck_require__(2948),
693
693
  );
694
- var _utils = __nccwpck_require__(3212);
694
+ var _utils = __nccwpck_require__(8674);
695
695
  function _interopRequireDefault(obj) {
696
696
  return obj && obj.__esModule ? obj : { default: obj };
697
697
  }
@@ -1034,7 +1034,7 @@
1034
1034
  plugin.postcss = true;
1035
1035
  var _default = (exports["default"] = plugin);
1036
1036
  },
1037
- 3212: (__unused_webpack_module, exports, __nccwpck_require__) => {
1037
+ 8674: (__unused_webpack_module, exports, __nccwpck_require__) => {
1038
1038
  "use strict";
1039
1039
  Object.defineProperty(exports, "__esModule", { value: true });
1040
1040
  exports.WEBPACK_IGNORE_COMMENT_REGEXP = void 0;
@@ -8098,6 +8098,6 @@
8098
8098
  }
8099
8099
  if (typeof __nccwpck_require__ !== "undefined")
8100
8100
  __nccwpck_require__.ab = __dirname + "/";
8101
- var __webpack_exports__ = __nccwpck_require__(6079);
8101
+ var __webpack_exports__ = __nccwpck_require__(717);
8102
8102
  module.exports = __webpack_exports__;
8103
8103
  })();
@@ -1,8 +1,8 @@
1
1
  (() => {
2
2
  var __webpack_modules__ = {
3
- 776: (module, __unused_webpack_exports, __nccwpck_require__) => {
3
+ 53: (module, __unused_webpack_exports, __nccwpck_require__) => {
4
4
  "use strict";
5
- const { HtmlWebpackChildCompiler } = __nccwpck_require__(397);
5
+ const { HtmlWebpackChildCompiler } = __nccwpck_require__(902);
6
6
  const compilerMap = new WeakMap();
7
7
  class CachedChildCompilation {
8
8
  constructor(compiler) {
@@ -311,7 +311,7 @@
311
311
  }
312
312
  module.exports = { CachedChildCompilation };
313
313
  },
314
- 397: (module) => {
314
+ 902: (module) => {
315
315
  "use strict";
316
316
  class HtmlWebpackChildCompiler {
317
317
  constructor(templates) {
@@ -480,7 +480,7 @@
480
480
  }
481
481
  module.exports = { HtmlWebpackChildCompiler };
482
482
  },
483
- 875: (module) => {
483
+ 270: (module) => {
484
484
  "use strict";
485
485
  module.exports = {};
486
486
  module.exports.none = (chunks) => chunks;
@@ -499,7 +499,7 @@
499
499
  };
500
500
  module.exports.auto = module.exports.none;
501
501
  },
502
- 926: (module) => {
502
+ 201: (module) => {
503
503
  "use strict";
504
504
  module.exports = function (err) {
505
505
  return {
@@ -520,7 +520,7 @@
520
520
  };
521
521
  };
522
522
  },
523
- 829: (module, __unused_webpack_exports, __nccwpck_require__) => {
523
+ 96: (module, __unused_webpack_exports, __nccwpck_require__) => {
524
524
  "use strict";
525
525
  const { AsyncSeriesWaterfallHook } = __nccwpck_require__(408);
526
526
  const htmlWebpackPluginHooksMap = new WeakMap();
@@ -546,7 +546,7 @@
546
546
  }
547
547
  module.exports = { getHtmlRspackPluginHooks };
548
548
  },
549
- 236: (module) => {
549
+ 869: (module) => {
550
550
  const voidTags = [
551
551
  "area",
552
552
  "base",
@@ -614,19 +614,19 @@
614
614
  htmlTagObjectToString,
615
615
  };
616
616
  },
617
- 297: (module, __unused_webpack_exports, __nccwpck_require__) => {
617
+ 32: (module, __unused_webpack_exports, __nccwpck_require__) => {
618
618
  "use strict";
619
619
  const promisify = __nccwpck_require__(23).promisify;
620
620
  const vm = __nccwpck_require__(154);
621
621
  const fs = __nccwpck_require__(896);
622
622
  const path = __nccwpck_require__(928);
623
- const { CachedChildCompilation } = __nccwpck_require__(776);
623
+ const { CachedChildCompilation } = __nccwpck_require__(53);
624
624
  const { createHtmlTagObject, htmlTagObjectToString, HtmlTagArray } =
625
- __nccwpck_require__(236);
626
- const prettyError = __nccwpck_require__(926);
627
- const chunkSorter = __nccwpck_require__(875);
625
+ __nccwpck_require__(869);
626
+ const prettyError = __nccwpck_require__(201);
627
+ const chunkSorter = __nccwpck_require__(270);
628
628
  const getHtmlRspackPluginHooks =
629
- __nccwpck_require__(829).getHtmlRspackPluginHooks;
629
+ __nccwpck_require__(96).getHtmlRspackPluginHooks;
630
630
  const WITH_PLACEHOLDER = "function __with_placeholder__";
631
631
  class HtmlRspackPlugin {
632
632
  constructor(userOptions = {}) {
@@ -1597,6 +1597,6 @@
1597
1597
  }
1598
1598
  if (typeof __nccwpck_require__ !== "undefined")
1599
1599
  __nccwpck_require__.ab = __dirname + "/";
1600
- var __webpack_exports__ = __nccwpck_require__(297);
1600
+ var __webpack_exports__ = __nccwpck_require__(32);
1601
1601
  module.exports = __webpack_exports__;
1602
1602
  })();
@@ -1,15 +1,15 @@
1
1
  (() => {
2
2
  "use strict";
3
3
  var __webpack_modules__ = {
4
- 124: (module, __unused_webpack_exports, __nccwpck_require__) => {
5
- module.exports = __nccwpck_require__(642)["default"];
4
+ 357: (module, __unused_webpack_exports, __nccwpck_require__) => {
5
+ module.exports = __nccwpck_require__(583)["default"];
6
6
  },
7
- 642: (__unused_webpack_module, exports, __nccwpck_require__) => {
7
+ 583: (__unused_webpack_module, exports, __nccwpck_require__) => {
8
8
  var __webpack_unused_export__;
9
9
  __webpack_unused_export__ = { value: true };
10
10
  exports["default"] = loader;
11
11
  var _path = _interopRequireDefault(__nccwpck_require__(928));
12
- var _utils = __nccwpck_require__(307);
12
+ var _utils = __nccwpck_require__(370);
13
13
  function _interopRequireDefault(obj) {
14
14
  return obj && obj.__esModule ? obj : { default: obj };
15
15
  }
@@ -179,7 +179,7 @@
179
179
  callback(null, result.css, map, { ast });
180
180
  }
181
181
  },
182
- 307: (module, exports, __nccwpck_require__) => {
182
+ 370: (module, exports, __nccwpck_require__) => {
183
183
  module = __nccwpck_require__.nmd(module);
184
184
  Object.defineProperty(exports, "__esModule", { value: true });
185
185
  exports.exec = exec;
@@ -716,6 +716,6 @@
716
716
  })();
717
717
  if (typeof __nccwpck_require__ !== "undefined")
718
718
  __nccwpck_require__.ab = __dirname + "/";
719
- var __webpack_exports__ = __nccwpck_require__(124);
719
+ var __webpack_exports__ = __nccwpck_require__(357);
720
720
  module.exports = __webpack_exports__;
721
721
  })();
@@ -1,7 +1,7 @@
1
1
  (() => {
2
2
  "use strict";
3
3
  var __webpack_modules__ = {
4
- 664: (__unused_webpack_module, exports, __nccwpck_require__) => {
4
+ 759: (__unused_webpack_module, exports, __nccwpck_require__) => {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.transformFiles =
7
7
  exports.reduceChunk =
@@ -120,7 +120,7 @@
120
120
  .map(standardizeFilePaths);
121
121
  exports.transformFiles = transformFiles;
122
122
  },
123
- 161: (__unused_webpack_module, exports, __nccwpck_require__) => {
123
+ 330: (__unused_webpack_module, exports, __nccwpck_require__) => {
124
124
  Object.defineProperty(exports, "__esModule", { value: true });
125
125
  exports.normalModuleLoaderHook =
126
126
  exports.getCompilerHooks =
@@ -130,7 +130,7 @@
130
130
  const fs_1 = __nccwpck_require__(896);
131
131
  const path_1 = __nccwpck_require__(928);
132
132
  const lite_tapable_1 = __nccwpck_require__(408);
133
- const helpers_1 = __nccwpck_require__(664);
133
+ const helpers_1 = __nccwpck_require__(759);
134
134
  const compilerHookMap = new WeakMap();
135
135
  const getCompilerHooks = (compiler) => {
136
136
  let hooks = compilerHookMap.get(compiler);
@@ -312,7 +312,7 @@
312
312
  exports.getCompilerHooks =
313
313
  void 0;
314
314
  const path_1 = __nccwpck_require__(928);
315
- const hooks_1 = __nccwpck_require__(161);
315
+ const hooks_1 = __nccwpck_require__(330);
316
316
  Object.defineProperty(exports, "getCompilerHooks", {
317
317
  enumerable: true,
318
318
  get: function () {
package/dist/index.cjs CHANGED
@@ -1607,47 +1607,6 @@ ${section.body}` : section.body).join("\n\n"));
1607
1607
  }), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
1608
1608
  }
1609
1609
  }
1610
- let RSBUILD_ALL_ENVIRONMENT_SYMBOL = 'RSBUILD_ALL_ENVIRONMENT_SYMBOL', isPluginMatchEnvironment = (pluginEnvironment, currentEnvironment)=>pluginEnvironment === currentEnvironment || pluginEnvironment === RSBUILD_ALL_ENVIRONMENT_SYMBOL;
1611
- async function initPlugins({ getPluginAPI, pluginManager }) {
1612
- index_js_namespaceObject.logger.debug('init plugins');
1613
- let plugins = ((plugins)=>{
1614
- let allLines = [];
1615
- function getPlugin(name) {
1616
- let targets = plugins.filter((item)=>item.instance.name === name);
1617
- if (!targets.length) throw Error(`${picocolors_index_js_default().dim('[rsbuild:plugin]')} Plugin "${picocolors_index_js_default().yellow(name)}" not existed`);
1618
- return targets;
1619
- }
1620
- for (let plugin of plugins){
1621
- if (plugin.instance.pre) for (let pre of plugin.instance.pre)pre && plugins.some((item)=>item.instance.name === pre) && allLines.push([
1622
- pre,
1623
- plugin.instance.name
1624
- ]);
1625
- if (plugin.instance.post) for (let post of plugin.instance.post)post && plugins.some((item)=>item.instance.name === post) && allLines.push([
1626
- plugin.instance.name,
1627
- post
1628
- ]);
1629
- }
1630
- let zeroEndPoints = plugins.filter((item)=>!allLines.find((l)=>l[1] === item.instance.name)), sortedPoint = [];
1631
- for(; zeroEndPoints.length;){
1632
- let zep = zeroEndPoints.shift();
1633
- sortedPoint.push(...getPlugin(zep.instance.name)), allLines = allLines.filter((l)=>l[0] !== getPlugin(zep.instance.name)[0].instance.name), zeroEndPoints = plugins.filter((item)=>!sortedPoint.find((sp)=>sp.instance.name === item.instance.name)).filter((item)=>!allLines.find((l)=>l[1] === item.instance.name));
1634
- }
1635
- if (allLines.length) {
1636
- let restInRingPoints = {};
1637
- for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
1638
- throw Error(`${picocolors_index_js_default().dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${picocolors_index_js_default().yellow(Object.keys(restInRingPoints).join(','))}`);
1639
- }
1640
- return sortedPoint;
1641
- })(pluginManager.getAllPluginsWithMeta()), removedPlugins = plugins.reduce((ret, plugin)=>(plugin.instance.remove && (ret[plugin.environment] ??= [], ret[plugin.environment].push(...plugin.instance.remove)), ret), {});
1642
- for (let plugin of plugins){
1643
- var _removedPlugins_plugin_environment, _removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL;
1644
- let isGlobalPlugin = 'RSBUILD_ALL_ENVIRONMENT_SYMBOL' === plugin.environment;
1645
- if ((null == (_removedPlugins_plugin_environment = removedPlugins[plugin.environment]) ? void 0 : _removedPlugins_plugin_environment.includes(plugin.instance.name)) || !isGlobalPlugin && (null == (_removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL = removedPlugins[RSBUILD_ALL_ENVIRONMENT_SYMBOL]) ? void 0 : _removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL.includes(plugin.instance.name))) continue;
1646
- let { instance, environment } = plugin;
1647
- await instance.setup(getPluginAPI(environment));
1648
- }
1649
- index_js_namespaceObject.logger.debug('init plugins done');
1650
- }
1651
1610
  function createEnvironmentAsyncHook() {
1652
1611
  let preGroup = [], postGroup = [], defaultGroup = [], tapEnvironment = ({ environment, handler: cb })=>{
1653
1612
  isFunction(cb) ? defaultGroup.push({
@@ -1675,7 +1634,7 @@ ${section.body}` : section.body).join("\n\n"));
1675
1634
  ...defaultGroup,
1676
1635
  ...postGroup
1677
1636
  ]){
1678
- if (callback.environment && environment && !isPluginMatchEnvironment(callback.environment, environment)) continue;
1637
+ if (environment && callback.environment && callback.environment !== environment) continue;
1679
1638
  let result = await callback.handler(...params);
1680
1639
  void 0 !== result && (params[0] = result);
1681
1640
  }
@@ -1688,7 +1647,7 @@ ${section.body}` : section.body).join("\n\n"));
1688
1647
  ...defaultGroup,
1689
1648
  ...postGroup
1690
1649
  ]){
1691
- if (callback.environment && environment && !isPluginMatchEnvironment(callback.environment, environment)) continue;
1650
+ if (environment && callback.environment && callback.environment !== environment) continue;
1692
1651
  let result = await callback.handler(...params);
1693
1652
  results.push(result);
1694
1653
  }
@@ -2131,6 +2090,70 @@ ${section.body}` : section.body).join("\n\n"));
2131
2090
  }
2132
2091
  }
2133
2092
  }
2093
+ let isEnvironmentMatch = (pluginEnvironment, specifiedEnvironment)=>pluginEnvironment === specifiedEnvironment || void 0 === pluginEnvironment;
2094
+ async function initPlugins({ context, pluginManager }) {
2095
+ index_js_namespaceObject.logger.debug('init plugins');
2096
+ let plugins = pluginManager.getAllPluginsWithMeta();
2097
+ plugins = ((plugins)=>{
2098
+ let allLines = [];
2099
+ function getPlugin(name) {
2100
+ let targets = plugins.filter((item)=>item.instance.name === name);
2101
+ if (!targets.length) throw Error(`${picocolors_index_js_default().dim('[rsbuild:plugin]')} Plugin "${picocolors_index_js_default().yellow(name)}" not existed`);
2102
+ return targets;
2103
+ }
2104
+ for (let plugin of plugins){
2105
+ if (plugin.instance.pre) for (let pre of plugin.instance.pre)pre && plugins.some((item)=>item.instance.name === pre) && allLines.push([
2106
+ pre,
2107
+ plugin.instance.name
2108
+ ]);
2109
+ if (plugin.instance.post) for (let post of plugin.instance.post)post && plugins.some((item)=>item.instance.name === post) && allLines.push([
2110
+ plugin.instance.name,
2111
+ post
2112
+ ]);
2113
+ }
2114
+ let zeroEndPoints = plugins.filter((item)=>!allLines.find((l)=>l[1] === item.instance.name)), sortedPoint = [];
2115
+ for(; zeroEndPoints.length;){
2116
+ let zep = zeroEndPoints.shift();
2117
+ sortedPoint.push(...getPlugin(zep.instance.name)), allLines = allLines.filter((l)=>l[0] !== getPlugin(zep.instance.name)[0].instance.name), zeroEndPoints = plugins.filter((item)=>!sortedPoint.find((sp)=>sp.instance.name === item.instance.name)).filter((item)=>!allLines.find((l)=>l[1] === item.instance.name));
2118
+ }
2119
+ if (allLines.length) {
2120
+ let restInRingPoints = {};
2121
+ for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
2122
+ throw Error(`${picocolors_index_js_default().dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${picocolors_index_js_default().yellow(Object.keys(restInRingPoints).join(','))}`);
2123
+ }
2124
+ return sortedPoint;
2125
+ })(plugins = ((plugins)=>{
2126
+ let prePlugins = [], normalPlugins = [], postPlugins = [];
2127
+ for (let plugin of plugins){
2128
+ let { enforce } = plugin.instance;
2129
+ 'pre' === enforce ? prePlugins.push(plugin) : 'post' === enforce ? postPlugins.push(plugin) : normalPlugins.push(plugin);
2130
+ }
2131
+ return [
2132
+ ...prePlugins,
2133
+ ...normalPlugins,
2134
+ ...postPlugins
2135
+ ];
2136
+ })(plugins));
2137
+ let removedPlugins = new Set(), removedEnvPlugins = {};
2138
+ for (let { environment, instance } of plugins)if (instance.remove) if (environment) for (let item of (removedEnvPlugins[environment] ??= new Set(), instance.remove))removedEnvPlugins[environment].add(item);
2139
+ else for (let item of instance.remove)removedPlugins.add(item);
2140
+ for (let { instance, environment } of plugins){
2141
+ var _removedEnvPlugins_environment;
2142
+ let { name, setup } = instance;
2143
+ if (!(removedPlugins.has(name) || environment && (null == (_removedEnvPlugins_environment = removedEnvPlugins[environment]) ? void 0 : _removedEnvPlugins_environment.has(name)))) {
2144
+ if (instance.apply && context.action) {
2145
+ let expected = {
2146
+ build: 'build',
2147
+ dev: 'serve',
2148
+ preview: 'serve'
2149
+ }[context.action];
2150
+ if (expected && instance.apply !== expected) continue;
2151
+ }
2152
+ await setup(context.getPluginAPI(environment));
2153
+ }
2154
+ }
2155
+ index_js_namespaceObject.logger.debug('init plugins done');
2156
+ }
2134
2157
  let mapProcessAssetsStage = (compiler, stage)=>{
2135
2158
  let { Compilation } = compiler.webpack;
2136
2159
  switch(stage){
@@ -2250,7 +2273,7 @@ ${section.body}` : section.body).join("\n\n"));
2250
2273
  async function createContext(options, userConfig) {
2251
2274
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = (0, external_node_path_namespaceObject.join)(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
2252
2275
  return {
2253
- version: "1.4.7",
2276
+ version: "1.4.9",
2254
2277
  rootPath,
2255
2278
  distPath: '',
2256
2279
  cachePath,
@@ -2640,7 +2663,7 @@ ${section.body}` : section.body).join("\n\n"));
2640
2663
  async function initRsbuildConfig({ context, pluginManager }) {
2641
2664
  if (context.normalizedConfig) return context.normalizedConfig;
2642
2665
  await initPlugins({
2643
- getPluginAPI: context.getPluginAPI,
2666
+ context,
2644
2667
  pluginManager
2645
2668
  }), await modifyRsbuildConfig(context);
2646
2669
  let normalizedBaseConfig = ((config)=>{
@@ -3809,13 +3832,13 @@ ${section.body}` : section.body).join("\n\n"));
3809
3832
  if (routes.length <= 1) {
3810
3833
  let pathname = routes.length ? routes[0].pathname : '';
3811
3834
  return urls.map(({ label, url })=>{
3812
- let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `\u{279C} ${picocolors_index_js_default().dim(label.padEnd(10))}`;
3835
+ let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `\u{279C} ${picocolors_index_js_default().dim(label.padEnd(10))}`;
3813
3836
  return ` ${prefix}${picocolors_index_js_default().cyan(normalizedPathname)}\n`;
3814
3837
  }).join('');
3815
3838
  }
3816
3839
  let message = '', maxNameLength = Math.max(...routes.map((r)=>r.entryName.length));
3817
3840
  return urls.forEach(({ label, url }, index)=>{
3818
- for (let r of (index > 0 && (message += '\n'), message += ` ${`\u{279C} ${label}`}\n`, routes))message += ` ${picocolors_index_js_default().dim('-')} ${picocolors_index_js_default().dim(r.entryName.padEnd(maxNameLength + 4))}${picocolors_index_js_default().cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
3841
+ for (let r of (index > 0 && (message += '\n'), message += ` ${`\u{279C} ${label}`}\n`, routes))message += ` ${picocolors_index_js_default().dim('-')} ${picocolors_index_js_default().dim(r.entryName.padEnd(maxNameLength + 4))}${picocolors_index_js_default().cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
3819
3842
  }), message;
3820
3843
  }(urls, routes);
3821
3844
  return !1 === trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), index_js_namespaceObject.logger.log(message), message;
@@ -4213,7 +4236,7 @@ ${section.body}` : section.body).join("\n\n"));
4213
4236
  return {
4214
4237
  ...defaultConfig,
4215
4238
  minSize: 0,
4216
- maxInitialRequests: Number.POSITIVE_INFINITY,
4239
+ maxInitialRequests: 1 / 0,
4217
4240
  ...override,
4218
4241
  cacheGroups: {
4219
4242
  ...defaultConfig.cacheGroups,
@@ -4241,7 +4264,7 @@ ${section.body}` : section.body).join("\n\n"));
4241
4264
  return {
4242
4265
  ...defaultConfig,
4243
4266
  minSize: userConfig.minSize ?? 0,
4244
- maxSize: userConfig.maxSize ?? Number.POSITIVE_INFINITY,
4267
+ maxSize: userConfig.maxSize ?? 1 / 0,
4245
4268
  ...override,
4246
4269
  cacheGroups: {
4247
4270
  ...defaultConfig.cacheGroups,
@@ -4334,7 +4357,7 @@ ${section.body}` : section.body).join("\n\n"));
4334
4357
  }
4335
4358
  ].filter(Boolean);
4336
4359
  if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${picocolors_index_js_default().dim('[rsbuild:config]')} ${picocolors_index_js_default().yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
4337
- help && index_js_namespaceObject.logger.log(!0 === help ? ` \u{279C} ${picocolors_index_js_default().dim('press')} ${picocolors_index_js_default().bold('h + enter')} ${picocolors_index_js_default().dim('to show shortcuts')}\n` : ` \u{279C} ${help}\n`);
4360
+ help && index_js_namespaceObject.logger.log(!0 === help ? ` \u{279C} ${picocolors_index_js_default().dim('press')} ${picocolors_index_js_default().bold('h + enter')} ${picocolors_index_js_default().dim('to show shortcuts')}\n` : ` \u{279C} ${help}\n`);
4338
4361
  let { createInterface } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "node:readline")), rl = createInterface({
4339
4362
  input: process.stdin
4340
4363
  });
@@ -5492,15 +5515,22 @@ ${section.body}` : section.body).join("\n\n"));
5492
5515
  port: port1,
5493
5516
  https
5494
5517
  };
5495
- let waitFirstCompileDone = runCompile ? new Promise((resolve)=>{
5496
- context.hooks.onDevCompileDone.tap(({ stats, isFirstCompile })=>{
5497
- lastStats = 'stats' in stats ? stats.stats : [
5498
- stats
5499
- ], isFirstCompile && resolve();
5500
- });
5501
- }) : Promise.resolve(), startCompile = async ()=>{
5518
+ let waitLastCompileDoneResolve = null, waitLastCompileDone = new Promise((resolve)=>{
5519
+ waitLastCompileDoneResolve = resolve;
5520
+ });
5521
+ context.hooks.onDevCompileDone.tap(({ stats })=>{
5522
+ lastStats = 'stats' in stats ? stats.stats : [
5523
+ stats
5524
+ ], waitLastCompileDoneResolve && (waitLastCompileDoneResolve(), waitLastCompileDoneResolve = null);
5525
+ });
5526
+ let startCompile = async ()=>{
5502
5527
  let compiler = customCompiler || await createCompiler();
5503
5528
  if (!compiler) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Failed to get compiler instance.`);
5529
+ null == compiler || compiler.hooks.watchRun.tap('rsbuild:watchRun', ()=>{
5530
+ lastStats && (waitLastCompileDoneResolve && (waitLastCompileDoneResolve(), waitLastCompileDoneResolve = null), waitLastCompileDone = new Promise((resolve)=>{
5531
+ waitLastCompileDoneResolve = resolve;
5532
+ }));
5533
+ });
5504
5534
  let publicPaths = helpers_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
5505
5535
  getPublicPathFromCompiler(compiler)
5506
5536
  ], compilationManager = new CompilationManager({
@@ -5558,19 +5588,19 @@ ${section.body}` : section.body).join("\n\n"));
5558
5588
  {
5559
5589
  getStats: async ()=>{
5560
5590
  if (!compilationManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('getStats')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
5561
- return await waitFirstCompileDone, lastStats[environment.index];
5591
+ return await waitLastCompileDone, lastStats[environment.index];
5562
5592
  },
5563
5593
  context: environment,
5564
5594
  loadBundle: async (entryName)=>{
5565
5595
  if (!compilationManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('loadBundle')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
5566
- return await waitFirstCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
5596
+ return await waitLastCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
5567
5597
  readFileSync: compilationManager.readFileSync,
5568
5598
  environment
5569
5599
  });
5570
5600
  },
5571
5601
  getTransformedHtml: async (entryName)=>{
5572
5602
  if (!compilationManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('getTransformedHtml')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
5573
- return await waitFirstCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
5603
+ return await waitLastCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
5574
5604
  readFileSync: compilationManager.readFileSync,
5575
5605
  environment
5576
5606
  });
@@ -7239,10 +7269,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7239
7269
  },
7240
7270
  {
7241
7271
  name: 'rsbuild:lazy-compilation',
7272
+ apply: 'serve',
7242
7273
  setup (api) {
7243
- api.modifyBundlerChain((chain, { environment, isProd, target })=>{
7274
+ api.modifyBundlerChain((chain, { environment, target })=>{
7244
7275
  var _config_dev;
7245
- if (isProd || 'web' !== target) return;
7276
+ if ('web' !== target) return;
7246
7277
  let { config } = environment, options = null == (_config_dev = config.dev) ? void 0 : _config_dev.lazyCompilation;
7247
7278
  if (options) {
7248
7279
  if (!0 === options && Object.keys(chain.entryPoints.entries() || {}).length <= 1) return void chain.experiments({
@@ -7359,12 +7390,10 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7359
7390
  ...options,
7360
7391
  rsbuildConfig: config
7361
7392
  }, pluginManager = (plugins = [], {
7362
- getPlugins: (options = {
7363
- environment: RSBUILD_ALL_ENVIRONMENT_SYMBOL
7364
- })=>plugins.filter((p)=>isPluginMatchEnvironment(p.environment, options.environment)).map((p)=>p.instance),
7393
+ getPlugins: (options = {})=>plugins.filter((plugin)=>isEnvironmentMatch(plugin.environment, options.environment)).map(({ instance })=>instance),
7365
7394
  getAllPluginsWithMeta: ()=>plugins,
7366
7395
  addPlugins: (newPlugins, options)=>{
7367
- let { before, environment = RSBUILD_ALL_ENVIRONMENT_SYMBOL } = options || {};
7396
+ let { before, environment } = options || {};
7368
7397
  for (let newPlugin of newPlugins)if (newPlugin) {
7369
7398
  var plugin = newPlugin;
7370
7399
  let type = typeof plugin;
@@ -7406,9 +7435,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7406
7435
  removePlugins: (pluginNames, options = {})=>{
7407
7436
  plugins = plugins.filter((plugin)=>!(pluginNames.includes(plugin.instance.name) && (!options.environment || plugin.environment === options.environment)));
7408
7437
  },
7409
- isPluginExists: (pluginName, options = {
7410
- environment: RSBUILD_ALL_ENVIRONMENT_SYMBOL
7411
- })=>!!plugins.find((plugin)=>plugin.instance.name === pluginName && isPluginMatchEnvironment(plugin.environment, options.environment))
7438
+ isPluginExists: (pluginName, options = {})=>plugins.some((plugin)=>plugin.instance.name === pluginName && isEnvironmentMatch(plugin.environment, options.environment))
7412
7439
  }), context = await createContext(resolvedOptions, config), getPluginAPI = function({ context, pluginManager }) {
7413
7440
  let { hooks } = context, publicContext = function(context) {
7414
7441
  let exposedKeys = [
@@ -7462,7 +7489,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7462
7489
  let pluginName = 'RsbuildCorePlugin';
7463
7490
  chain.plugin(pluginName).use(class {
7464
7491
  apply(compiler) {
7465
- for (let { handler, environment: pluginEnvironment } of (compiler.__rsbuildTransformer = transformer, resolveFns))(!pluginEnvironment || isPluginMatchEnvironment(pluginEnvironment, environment.name)) && compiler.hooks.compilation.tap(pluginName, (compilation, { normalModuleFactory })=>{
7492
+ for (let { handler, environment: pluginEnvironment } of (compiler.__rsbuildTransformer = transformer, resolveFns))(!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compiler.hooks.compilation.tap(pluginName, (compilation, { normalModuleFactory })=>{
7466
7493
  normalModuleFactory.hooks.resolve.tapPromise(pluginName, async (resolveData)=>handler({
7467
7494
  compiler,
7468
7495
  compilation,
@@ -7475,7 +7502,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7475
7502
  childCompiler.__rsbuildTransformer = transformer;
7476
7503
  });
7477
7504
  let { sources } = compiler.webpack;
7478
- for (let { descriptor, handler, environment: pluginEnvironment } of processAssetsFns)(!descriptor.targets || descriptor.targets.includes(target)) && (!descriptor.environments || descriptor.environments.includes(environment.name)) && (!pluginEnvironment || isPluginMatchEnvironment(pluginEnvironment, environment.name)) && compilation.hooks.processAssets.tapPromise({
7505
+ for (let { descriptor, handler, environment: pluginEnvironment } of processAssetsFns)(!descriptor.targets || descriptor.targets.includes(target)) && (!descriptor.environments || descriptor.environments.includes(environment.name)) && (!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compilation.hooks.processAssets.tapPromise({
7479
7506
  name: pluginName,
7480
7507
  stage: mapProcessAssetsStage(compiler, descriptor.stage)
7481
7508
  }, async (assets)=>handler({
@@ -7528,7 +7555,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7528
7555
  handler: (chain, { target, environment })=>{
7529
7556
  if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environment.name)) return;
7530
7557
  let rule = chain.module.rule(id);
7531
- 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.enforce && rule.enforce(descriptor.enforce);
7558
+ 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);
7532
7559
  let loaderName = descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs', loaderPath = (0, external_node_path_namespaceObject.join)(LOADER_PATH, loaderName);
7533
7560
  rule.use(id).loader(loaderPath).options({
7534
7561
  id,
@@ -7677,7 +7704,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7677
7704
  envs && (rsbuild.onCloseBuild(envs.cleanup), rsbuild.onCloseDevServer(envs.cleanup));
7678
7705
  let getFlattenedPlugins = async (pluginOptions)=>{
7679
7706
  let plugins = pluginOptions;
7680
- do plugins = (await Promise.all(plugins)).flat(Number.POSITIVE_INFINITY);
7707
+ do plugins = (await Promise.all(plugins)).flat(1 / 0);
7681
7708
  while (plugins.some((v)=>(0, types_namespaceObject.isPromise)(v)));
7682
7709
  return plugins;
7683
7710
  };
@@ -7889,11 +7916,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7889
7916
  ].includes(level) && (index_js_namespaceObject.logger.level = level);
7890
7917
  }
7891
7918
  let { npm_execpath } = process.env;
7892
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && index_js_namespaceObject.logger.log(), index_js_namespaceObject.logger.greet(` Rsbuild v1.4.7\n`);
7919
+ (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && index_js_namespaceObject.logger.log(), index_js_namespaceObject.logger.greet(` Rsbuild v1.4.9\n`);
7893
7920
  try {
7894
7921
  !function() {
7895
7922
  let cli = ((name = "")=>new CAC(name))('rsbuild');
7896
- cli.help(), cli.version("1.4.7"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7923
+ cli.help(), cli.version("1.4.9"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7897
7924
  default: 'jiti'
7898
7925
  }).option('-r, --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('-m, --mode <mode>', 'specify the build mode, can be `development`, `production` or `none`').option('--log-level <level>', 'specify the log level, can be `info`, `warn`, `error` or `silent`').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file').option('--environment <name>', 'specify the name of environment to build', {
7899
7926
  type: [
@@ -7951,7 +7978,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7951
7978
  index_js_namespaceObject.logger.error('Failed to start Rsbuild CLI.'), index_js_namespaceObject.logger.error(err);
7952
7979
  }
7953
7980
  }
7954
- let src_version = "1.4.7";
7981
+ let src_version = "1.4.9";
7955
7982
  })(), exports.PLUGIN_CSS_NAME = __webpack_exports__.PLUGIN_CSS_NAME, exports.PLUGIN_SWC_NAME = __webpack_exports__.PLUGIN_SWC_NAME, exports.createRsbuild = __webpack_exports__.createRsbuild, exports.defaultAllowedOrigins = __webpack_exports__.defaultAllowedOrigins, exports.defineConfig = __webpack_exports__.defineConfig, exports.ensureAssetPrefix = __webpack_exports__.ensureAssetPrefix, exports.loadConfig = __webpack_exports__.loadConfig, exports.loadEnv = __webpack_exports__.loadEnv, exports.logger = __webpack_exports__.logger, exports.mergeRsbuildConfig = __webpack_exports__.mergeRsbuildConfig, exports.rspack = __webpack_exports__.rspack, exports.runCLI = __webpack_exports__.runCLI, exports.version = __webpack_exports__.version, __webpack_exports__)-1 === [
7956
7983
  "PLUGIN_CSS_NAME",
7957
7984
  "PLUGIN_SWC_NAME",
package/dist/index.js CHANGED
@@ -1428,47 +1428,6 @@ class CAC extends EventEmitter {
1428
1428
  }), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
1429
1429
  }
1430
1430
  }
1431
- let RSBUILD_ALL_ENVIRONMENT_SYMBOL = 'RSBUILD_ALL_ENVIRONMENT_SYMBOL', isPluginMatchEnvironment = (pluginEnvironment, currentEnvironment)=>pluginEnvironment === currentEnvironment || pluginEnvironment === RSBUILD_ALL_ENVIRONMENT_SYMBOL;
1432
- async function initPlugins({ getPluginAPI, pluginManager }) {
1433
- logger.debug('init plugins');
1434
- let plugins = ((plugins)=>{
1435
- let allLines = [];
1436
- function getPlugin(name) {
1437
- let targets = plugins.filter((item)=>item.instance.name === name);
1438
- if (!targets.length) throw Error(`${picocolors.dim('[rsbuild:plugin]')} Plugin "${picocolors.yellow(name)}" not existed`);
1439
- return targets;
1440
- }
1441
- for (let plugin of plugins){
1442
- if (plugin.instance.pre) for (let pre of plugin.instance.pre)pre && plugins.some((item)=>item.instance.name === pre) && allLines.push([
1443
- pre,
1444
- plugin.instance.name
1445
- ]);
1446
- if (plugin.instance.post) for (let post of plugin.instance.post)post && plugins.some((item)=>item.instance.name === post) && allLines.push([
1447
- plugin.instance.name,
1448
- post
1449
- ]);
1450
- }
1451
- let zeroEndPoints = plugins.filter((item)=>!allLines.find((l)=>l[1] === item.instance.name)), sortedPoint = [];
1452
- for(; zeroEndPoints.length;){
1453
- let zep = zeroEndPoints.shift();
1454
- sortedPoint.push(...getPlugin(zep.instance.name)), allLines = allLines.filter((l)=>l[0] !== getPlugin(zep.instance.name)[0].instance.name), zeroEndPoints = plugins.filter((item)=>!sortedPoint.find((sp)=>sp.instance.name === item.instance.name)).filter((item)=>!allLines.find((l)=>l[1] === item.instance.name));
1455
- }
1456
- if (allLines.length) {
1457
- let restInRingPoints = {};
1458
- for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
1459
- throw Error(`${picocolors.dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${picocolors.yellow(Object.keys(restInRingPoints).join(','))}`);
1460
- }
1461
- return sortedPoint;
1462
- })(pluginManager.getAllPluginsWithMeta()), removedPlugins = plugins.reduce((ret, plugin)=>(plugin.instance.remove && (ret[plugin.environment] ??= [], ret[plugin.environment].push(...plugin.instance.remove)), ret), {});
1463
- for (let plugin of plugins){
1464
- var _removedPlugins_plugin_environment, _removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL;
1465
- let isGlobalPlugin = 'RSBUILD_ALL_ENVIRONMENT_SYMBOL' === plugin.environment;
1466
- if ((null == (_removedPlugins_plugin_environment = removedPlugins[plugin.environment]) ? void 0 : _removedPlugins_plugin_environment.includes(plugin.instance.name)) || !isGlobalPlugin && (null == (_removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL = removedPlugins[RSBUILD_ALL_ENVIRONMENT_SYMBOL]) ? void 0 : _removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL.includes(plugin.instance.name))) continue;
1467
- let { instance, environment } = plugin;
1468
- await instance.setup(getPluginAPI(environment));
1469
- }
1470
- logger.debug('init plugins done');
1471
- }
1472
1431
  function createEnvironmentAsyncHook() {
1473
1432
  let preGroup = [], postGroup = [], defaultGroup = [], tapEnvironment = ({ environment, handler: cb })=>{
1474
1433
  isFunction(cb) ? defaultGroup.push({
@@ -1496,7 +1455,7 @@ function createEnvironmentAsyncHook() {
1496
1455
  ...defaultGroup,
1497
1456
  ...postGroup
1498
1457
  ]){
1499
- if (callback.environment && environment && !isPluginMatchEnvironment(callback.environment, environment)) continue;
1458
+ if (environment && callback.environment && callback.environment !== environment) continue;
1500
1459
  let result = await callback.handler(...params);
1501
1460
  void 0 !== result && (params[0] = result);
1502
1461
  }
@@ -1509,7 +1468,7 @@ function createEnvironmentAsyncHook() {
1509
1468
  ...defaultGroup,
1510
1469
  ...postGroup
1511
1470
  ]){
1512
- if (callback.environment && environment && !isPluginMatchEnvironment(callback.environment, environment)) continue;
1471
+ if (environment && callback.environment && callback.environment !== environment) continue;
1513
1472
  let result = await callback.handler(...params);
1514
1473
  results.push(result);
1515
1474
  }
@@ -1946,6 +1905,70 @@ function exit(exitCode, type) {
1946
1905
  }
1947
1906
  }
1948
1907
  }
1908
+ let isEnvironmentMatch = (pluginEnvironment, specifiedEnvironment)=>pluginEnvironment === specifiedEnvironment || void 0 === pluginEnvironment;
1909
+ async function initPlugins({ context, pluginManager }) {
1910
+ logger.debug('init plugins');
1911
+ let plugins = pluginManager.getAllPluginsWithMeta();
1912
+ plugins = ((plugins)=>{
1913
+ let allLines = [];
1914
+ function getPlugin(name) {
1915
+ let targets = plugins.filter((item)=>item.instance.name === name);
1916
+ if (!targets.length) throw Error(`${picocolors.dim('[rsbuild:plugin]')} Plugin "${picocolors.yellow(name)}" not existed`);
1917
+ return targets;
1918
+ }
1919
+ for (let plugin of plugins){
1920
+ if (plugin.instance.pre) for (let pre of plugin.instance.pre)pre && plugins.some((item)=>item.instance.name === pre) && allLines.push([
1921
+ pre,
1922
+ plugin.instance.name
1923
+ ]);
1924
+ if (plugin.instance.post) for (let post of plugin.instance.post)post && plugins.some((item)=>item.instance.name === post) && allLines.push([
1925
+ plugin.instance.name,
1926
+ post
1927
+ ]);
1928
+ }
1929
+ let zeroEndPoints = plugins.filter((item)=>!allLines.find((l)=>l[1] === item.instance.name)), sortedPoint = [];
1930
+ for(; zeroEndPoints.length;){
1931
+ let zep = zeroEndPoints.shift();
1932
+ sortedPoint.push(...getPlugin(zep.instance.name)), allLines = allLines.filter((l)=>l[0] !== getPlugin(zep.instance.name)[0].instance.name), zeroEndPoints = plugins.filter((item)=>!sortedPoint.find((sp)=>sp.instance.name === item.instance.name)).filter((item)=>!allLines.find((l)=>l[1] === item.instance.name));
1933
+ }
1934
+ if (allLines.length) {
1935
+ let restInRingPoints = {};
1936
+ for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
1937
+ throw Error(`${picocolors.dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${picocolors.yellow(Object.keys(restInRingPoints).join(','))}`);
1938
+ }
1939
+ return sortedPoint;
1940
+ })(plugins = ((plugins)=>{
1941
+ let prePlugins = [], normalPlugins = [], postPlugins = [];
1942
+ for (let plugin of plugins){
1943
+ let { enforce } = plugin.instance;
1944
+ 'pre' === enforce ? prePlugins.push(plugin) : 'post' === enforce ? postPlugins.push(plugin) : normalPlugins.push(plugin);
1945
+ }
1946
+ return [
1947
+ ...prePlugins,
1948
+ ...normalPlugins,
1949
+ ...postPlugins
1950
+ ];
1951
+ })(plugins));
1952
+ let removedPlugins = new Set(), removedEnvPlugins = {};
1953
+ for (let { environment, instance } of plugins)if (instance.remove) if (environment) for (let item of (removedEnvPlugins[environment] ??= new Set(), instance.remove))removedEnvPlugins[environment].add(item);
1954
+ else for (let item of instance.remove)removedPlugins.add(item);
1955
+ for (let { instance, environment } of plugins){
1956
+ var _removedEnvPlugins_environment;
1957
+ let { name, setup } = instance;
1958
+ if (!(removedPlugins.has(name) || environment && (null == (_removedEnvPlugins_environment = removedEnvPlugins[environment]) ? void 0 : _removedEnvPlugins_environment.has(name)))) {
1959
+ if (instance.apply && context.action) {
1960
+ let expected = {
1961
+ build: 'build',
1962
+ dev: 'serve',
1963
+ preview: 'serve'
1964
+ }[context.action];
1965
+ if (expected && instance.apply !== expected) continue;
1966
+ }
1967
+ await setup(context.getPluginAPI(environment));
1968
+ }
1969
+ }
1970
+ logger.debug('init plugins done');
1971
+ }
1949
1972
  let mapProcessAssetsStage = (compiler, stage)=>{
1950
1973
  let { Compilation } = compiler.webpack;
1951
1974
  switch(stage){
@@ -2065,7 +2088,7 @@ async function updateEnvironmentContext(context, configs) {
2065
2088
  async function createContext(options, userConfig) {
2066
2089
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
2067
2090
  return {
2068
- version: "1.4.7",
2091
+ version: "1.4.9",
2069
2092
  rootPath,
2070
2093
  distPath: '',
2071
2094
  cachePath,
@@ -2448,7 +2471,7 @@ async function modifyEnvironmentConfig(context, config, name) {
2448
2471
  async function initRsbuildConfig({ context, pluginManager }) {
2449
2472
  if (context.normalizedConfig) return context.normalizedConfig;
2450
2473
  await initPlugins({
2451
- getPluginAPI: context.getPluginAPI,
2474
+ context,
2452
2475
  pluginManager
2453
2476
  }), await modifyRsbuildConfig(context);
2454
2477
  let normalizedBaseConfig = ((config)=>{
@@ -3614,13 +3637,13 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
3614
3637
  if (routes.length <= 1) {
3615
3638
  let pathname = routes.length ? routes[0].pathname : '';
3616
3639
  return urls.map(({ label, url })=>{
3617
- let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `\u{279C} ${picocolors.dim(label.padEnd(10))}`;
3640
+ let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `\u{279C} ${picocolors.dim(label.padEnd(10))}`;
3618
3641
  return ` ${prefix}${picocolors.cyan(normalizedPathname)}\n`;
3619
3642
  }).join('');
3620
3643
  }
3621
3644
  let message = '', maxNameLength = Math.max(...routes.map((r)=>r.entryName.length));
3622
3645
  return urls.forEach(({ label, url }, index)=>{
3623
- for (let r of (index > 0 && (message += '\n'), message += ` ${`\u{279C} ${label}`}\n`, routes))message += ` ${picocolors.dim('-')} ${picocolors.dim(r.entryName.padEnd(maxNameLength + 4))}${picocolors.cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
3646
+ for (let r of (index > 0 && (message += '\n'), message += ` ${`\u{279C} ${label}`}\n`, routes))message += ` ${picocolors.dim('-')} ${picocolors.dim(r.entryName.padEnd(maxNameLength + 4))}${picocolors.cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
3624
3647
  }), message;
3625
3648
  }(urls, routes);
3626
3649
  return !1 === trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
@@ -4014,7 +4037,7 @@ let MODULE_PATH_REGEX = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\
4014
4037
  return {
4015
4038
  ...defaultConfig,
4016
4039
  minSize: 0,
4017
- maxInitialRequests: Number.POSITIVE_INFINITY,
4040
+ maxInitialRequests: 1 / 0,
4018
4041
  ...override,
4019
4042
  cacheGroups: {
4020
4043
  ...defaultConfig.cacheGroups,
@@ -4042,7 +4065,7 @@ let MODULE_PATH_REGEX = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\
4042
4065
  return {
4043
4066
  ...defaultConfig,
4044
4067
  minSize: userConfig.minSize ?? 0,
4045
- maxSize: userConfig.maxSize ?? Number.POSITIVE_INFINITY,
4068
+ maxSize: userConfig.maxSize ?? 1 / 0,
4046
4069
  ...override,
4047
4070
  cacheGroups: {
4048
4071
  ...defaultConfig.cacheGroups,
@@ -4135,7 +4158,7 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
4135
4158
  }
4136
4159
  ].filter(Boolean);
4137
4160
  if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${picocolors.dim('[rsbuild:config]')} ${picocolors.yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
4138
- help && logger.log(!0 === help ? ` \u{279C} ${picocolors.dim('press')} ${picocolors.bold('h + enter')} ${picocolors.dim('to show shortcuts')}\n` : ` \u{279C} ${help}\n`);
4161
+ help && logger.log(!0 === help ? ` \u{279C} ${picocolors.dim('press')} ${picocolors.bold('h + enter')} ${picocolors.dim('to show shortcuts')}\n` : ` \u{279C} ${help}\n`);
4139
4162
  let { createInterface } = await import("node:readline"), rl = createInterface({
4140
4163
  input: process.stdin
4141
4164
  });
@@ -5282,15 +5305,22 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
5282
5305
  port,
5283
5306
  https
5284
5307
  };
5285
- let waitFirstCompileDone = runCompile ? new Promise((resolve)=>{
5286
- context.hooks.onDevCompileDone.tap(({ stats, isFirstCompile })=>{
5287
- lastStats = 'stats' in stats ? stats.stats : [
5288
- stats
5289
- ], isFirstCompile && resolve();
5290
- });
5291
- }) : Promise.resolve(), startCompile = async ()=>{
5308
+ let waitLastCompileDoneResolve = null, waitLastCompileDone = new Promise((resolve)=>{
5309
+ waitLastCompileDoneResolve = resolve;
5310
+ });
5311
+ context.hooks.onDevCompileDone.tap(({ stats })=>{
5312
+ lastStats = 'stats' in stats ? stats.stats : [
5313
+ stats
5314
+ ], waitLastCompileDoneResolve && (waitLastCompileDoneResolve(), waitLastCompileDoneResolve = null);
5315
+ });
5316
+ let startCompile = async ()=>{
5292
5317
  let compiler = customCompiler || await createCompiler();
5293
5318
  if (!compiler) throw Error(`${picocolors.dim('[rsbuild:server]')} Failed to get compiler instance.`);
5319
+ null == compiler || compiler.hooks.watchRun.tap('rsbuild:watchRun', ()=>{
5320
+ lastStats && (waitLastCompileDoneResolve && (waitLastCompileDoneResolve(), waitLastCompileDoneResolve = null), waitLastCompileDone = new Promise((resolve)=>{
5321
+ waitLastCompileDoneResolve = resolve;
5322
+ }));
5323
+ });
5294
5324
  let publicPaths = helpers_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
5295
5325
  getPublicPathFromCompiler(compiler)
5296
5326
  ], compilationManager = new CompilationManager({
@@ -5348,19 +5378,19 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
5348
5378
  {
5349
5379
  getStats: async ()=>{
5350
5380
  if (!compilationManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('getStats')} when ${picocolors.yellow('runCompile')} is false`);
5351
- return await waitFirstCompileDone, lastStats[environment.index];
5381
+ return await waitLastCompileDone, lastStats[environment.index];
5352
5382
  },
5353
5383
  context: environment,
5354
5384
  loadBundle: async (entryName)=>{
5355
5385
  if (!compilationManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('loadBundle')} when ${picocolors.yellow('runCompile')} is false`);
5356
- return await waitFirstCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
5386
+ return await waitLastCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
5357
5387
  readFileSync: compilationManager.readFileSync,
5358
5388
  environment
5359
5389
  });
5360
5390
  },
5361
5391
  getTransformedHtml: async (entryName)=>{
5362
5392
  if (!compilationManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('getTransformedHtml')} when ${picocolors.yellow('runCompile')} is false`);
5363
- return await waitFirstCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
5393
+ return await waitLastCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
5364
5394
  readFileSync: compilationManager.readFileSync,
5365
5395
  environment
5366
5396
  });
@@ -7026,10 +7056,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7026
7056
  },
7027
7057
  {
7028
7058
  name: 'rsbuild:lazy-compilation',
7059
+ apply: 'serve',
7029
7060
  setup (api) {
7030
- api.modifyBundlerChain((chain, { environment, isProd, target })=>{
7061
+ api.modifyBundlerChain((chain, { environment, target })=>{
7031
7062
  var _config_dev;
7032
- if (isProd || 'web' !== target) return;
7063
+ if ('web' !== target) return;
7033
7064
  let { config } = environment, options = null == (_config_dev = config.dev) ? void 0 : _config_dev.lazyCompilation;
7034
7065
  if (options) {
7035
7066
  if (!0 === options && Object.keys(chain.entryPoints.entries() || {}).length <= 1) return void chain.experiments({
@@ -7146,12 +7177,10 @@ async function createRsbuild(options = {}) {
7146
7177
  ...options,
7147
7178
  rsbuildConfig: config
7148
7179
  }, pluginManager = (plugins = [], {
7149
- getPlugins: (options = {
7150
- environment: RSBUILD_ALL_ENVIRONMENT_SYMBOL
7151
- })=>plugins.filter((p)=>isPluginMatchEnvironment(p.environment, options.environment)).map((p)=>p.instance),
7180
+ getPlugins: (options = {})=>plugins.filter((plugin)=>isEnvironmentMatch(plugin.environment, options.environment)).map(({ instance })=>instance),
7152
7181
  getAllPluginsWithMeta: ()=>plugins,
7153
7182
  addPlugins: (newPlugins, options)=>{
7154
- let { before, environment = RSBUILD_ALL_ENVIRONMENT_SYMBOL } = options || {};
7183
+ let { before, environment } = options || {};
7155
7184
  for (let newPlugin of newPlugins)if (newPlugin) {
7156
7185
  let type = typeof newPlugin;
7157
7186
  if ('object' !== type || null === newPlugin) throw Error(`${picocolors.dim('[rsbuild:plugin]')} Expect Rsbuild plugin instance to be an object, but got ${picocolors.yellow(type)}.`);
@@ -7192,9 +7221,7 @@ async function createRsbuild(options = {}) {
7192
7221
  removePlugins: (pluginNames, options = {})=>{
7193
7222
  plugins = plugins.filter((plugin)=>!(pluginNames.includes(plugin.instance.name) && (!options.environment || plugin.environment === options.environment)));
7194
7223
  },
7195
- isPluginExists: (pluginName, options = {
7196
- environment: RSBUILD_ALL_ENVIRONMENT_SYMBOL
7197
- })=>!!plugins.find((plugin)=>plugin.instance.name === pluginName && isPluginMatchEnvironment(plugin.environment, options.environment))
7224
+ isPluginExists: (pluginName, options = {})=>plugins.some((plugin)=>plugin.instance.name === pluginName && isEnvironmentMatch(plugin.environment, options.environment))
7198
7225
  }), context = await createContext(resolvedOptions, config), getPluginAPI = function({ context, pluginManager }) {
7199
7226
  let { hooks } = context, publicContext = function(context) {
7200
7227
  let exposedKeys = [
@@ -7248,7 +7275,7 @@ async function createRsbuild(options = {}) {
7248
7275
  let pluginName = 'RsbuildCorePlugin';
7249
7276
  chain.plugin(pluginName).use(class {
7250
7277
  apply(compiler) {
7251
- for (let { handler, environment: pluginEnvironment } of (compiler.__rsbuildTransformer = transformer, resolveFns))(!pluginEnvironment || isPluginMatchEnvironment(pluginEnvironment, environment.name)) && compiler.hooks.compilation.tap(pluginName, (compilation, { normalModuleFactory })=>{
7278
+ for (let { handler, environment: pluginEnvironment } of (compiler.__rsbuildTransformer = transformer, resolveFns))(!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compiler.hooks.compilation.tap(pluginName, (compilation, { normalModuleFactory })=>{
7252
7279
  normalModuleFactory.hooks.resolve.tapPromise(pluginName, async (resolveData)=>handler({
7253
7280
  compiler,
7254
7281
  compilation,
@@ -7261,7 +7288,7 @@ async function createRsbuild(options = {}) {
7261
7288
  childCompiler.__rsbuildTransformer = transformer;
7262
7289
  });
7263
7290
  let { sources } = compiler.webpack;
7264
- for (let { descriptor, handler, environment: pluginEnvironment } of processAssetsFns)(!descriptor.targets || descriptor.targets.includes(target)) && (!descriptor.environments || descriptor.environments.includes(environment.name)) && (!pluginEnvironment || isPluginMatchEnvironment(pluginEnvironment, environment.name)) && compilation.hooks.processAssets.tapPromise({
7291
+ for (let { descriptor, handler, environment: pluginEnvironment } of processAssetsFns)(!descriptor.targets || descriptor.targets.includes(target)) && (!descriptor.environments || descriptor.environments.includes(environment.name)) && (!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compilation.hooks.processAssets.tapPromise({
7265
7292
  name: pluginName,
7266
7293
  stage: mapProcessAssetsStage(compiler, descriptor.stage)
7267
7294
  }, async (assets)=>handler({
@@ -7312,7 +7339,7 @@ async function createRsbuild(options = {}) {
7312
7339
  handler: (chain, { target, environment })=>{
7313
7340
  if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environment.name)) return;
7314
7341
  let rule = chain.module.rule(id);
7315
- 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.enforce && rule.enforce(descriptor.enforce);
7342
+ 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);
7316
7343
  let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs');
7317
7344
  rule.use(id).loader(loaderPath).options({
7318
7345
  id,
@@ -7460,7 +7487,7 @@ async function createRsbuild(options = {}) {
7460
7487
  envs && (rsbuild.onCloseBuild(envs.cleanup), rsbuild.onCloseDevServer(envs.cleanup));
7461
7488
  let getFlattenedPlugins = async (pluginOptions)=>{
7462
7489
  let plugins = pluginOptions;
7463
- do plugins = (await Promise.all(plugins)).flat(Number.POSITIVE_INFINITY);
7490
+ do plugins = (await Promise.all(plugins)).flat(1 / 0);
7464
7491
  while (plugins.some((v)=>isPromise(v)));
7465
7492
  return plugins;
7466
7493
  };
@@ -7672,11 +7699,11 @@ async function runCLI() {
7672
7699
  ].includes(level) && (logger.level = level);
7673
7700
  }
7674
7701
  let { npm_execpath } = process.env;
7675
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.7\n`);
7702
+ (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.9\n`);
7676
7703
  try {
7677
7704
  !function() {
7678
7705
  let cli = ((name = "")=>new CAC(name))('rsbuild');
7679
- cli.help(), cli.version("1.4.7"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7706
+ cli.help(), cli.version("1.4.9"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7680
7707
  default: 'jiti'
7681
7708
  }).option('-r, --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('-m, --mode <mode>', 'specify the build mode, can be `development`, `production` or `none`').option('--log-level <level>', 'specify the log level, can be `info`, `warn`, `error` or `silent`').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file').option('--environment <name>', 'specify the name of environment to build', {
7682
7709
  type: [
@@ -7734,5 +7761,5 @@ async function runCLI() {
7734
7761
  logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
7735
7762
  }
7736
7763
  }
7737
- let src_version = "1.4.7";
7764
+ let src_version = "1.4.9";
7738
7765
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger, mergeRsbuildConfig, rspack, runCLI, src_version as version };
@@ -23,7 +23,7 @@ export type LoadEnvOptions = {
23
23
  };
24
24
  export type LoadEnvResult = {
25
25
  /**
26
- * All env variables in the .env file
26
+ * All environment variables in the .env file
27
27
  */
28
28
  parsed: Record<string, string>;
29
29
  /**
@@ -31,7 +31,7 @@ export type LoadEnvResult = {
31
31
  */
32
32
  filePaths: string[];
33
33
  /**
34
- * Env variables that start with prefixes.
34
+ * Environment variables that start with prefixes.
35
35
  *
36
36
  * @example
37
37
  * ```ts
@@ -42,7 +42,7 @@ export type LoadEnvResult = {
42
42
  **/
43
43
  rawPublicVars: Record<string, string | undefined>;
44
44
  /**
45
- * Formatted env variables that start with prefixes.
45
+ * Formatted environment variables that start with prefixes.
46
46
  * The keys contain the prefixes `process.env.*` and `import.meta.env.*`.
47
47
  * The values are processed by `JSON.stringify`.
48
48
  *
@@ -56,7 +56,7 @@ export type LoadEnvResult = {
56
56
  **/
57
57
  publicVars: Record<string, string>;
58
58
  /**
59
- * Clear the env variables mounted on `process.env`
59
+ * Clear the environment variables mounted on `process.env`
60
60
  */
61
61
  cleanup: () => void;
62
62
  };
@@ -1,9 +1,21 @@
1
- import type { PluginManager, PluginMeta, RsbuildPluginAPI } from './types';
2
- export declare const RSBUILD_ALL_ENVIRONMENT_SYMBOL = "RSBUILD_ALL_ENVIRONMENT_SYMBOL";
3
- export declare const isPluginMatchEnvironment: (pluginEnvironment: string, currentEnvironment: string) => boolean;
1
+ import type { InternalContext, PluginManager, PluginMeta } from './types';
2
+ /**
3
+ * Determines whether the plugin is registered in the specified environment.
4
+ * If the pluginEnvironment is undefined, it means it can match any environment.
5
+ */
6
+ export declare const isEnvironmentMatch: (pluginEnvironment?: string, specifiedEnvironment?: string) => boolean;
4
7
  export declare function createPluginManager(): PluginManager;
5
- export declare const pluginDagSort: (plugins: PluginMeta[]) => PluginMeta[];
6
- export declare function initPlugins({ getPluginAPI, pluginManager, }: {
7
- getPluginAPI: (environment?: string) => RsbuildPluginAPI;
8
+ /**
9
+ * Sorts plugins by their `enforce` property.
10
+ */
11
+ export declare const sortPluginsByEnforce: (plugins: PluginMeta[]) => PluginMeta[];
12
+ /**
13
+ * Performs topological sorting on plugins based on their dependencies.
14
+ * Uses the `pre` and `post` properties of plugins to determine the correct
15
+ * execution order.
16
+ */
17
+ export declare const sortPluginsByDependencies: (plugins: PluginMeta[]) => PluginMeta[];
18
+ export declare function initPlugins({ context, pluginManager, }: {
19
+ context: InternalContext;
8
20
  pluginManager: PluginManager;
9
21
  }): Promise<void>;
@@ -6,7 +6,7 @@ import type { Logger } from '../logger';
6
6
  import type { ModifyRspackConfigUtils, NarrowedRspackConfig, NormalizedConfig, NormalizedEnvironmentConfig, RsbuildConfig, RspackMerge } from './config';
7
7
  import type { RsbuildContext } from './context';
8
8
  import type { EnvironmentContext, ModifyBundlerChainFn, ModifyChainUtils, ModifyEnvironmentConfigFn, ModifyHTMLFn, ModifyHTMLTagsFn, ModifyRsbuildConfigFn, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterEnvironmentCompileFn, OnAfterStartDevServerFn, OnAfterStartProdServerFn, OnBeforeBuildFn, OnBeforeCreateCompilerFn, OnBeforeEnvironmentCompileFn, OnBeforeStartDevServerFn, OnBeforeStartProdServerFn, OnCloseBuildFn, OnCloseDevServerFn, OnDevCompileDoneFn, OnExitFn } from './hooks';
9
- import type { RsbuildInstance, RsbuildTarget } from './rsbuild';
9
+ import type { AddPluginsOptions, RsbuildInstance, RsbuildTarget } from './rsbuild';
10
10
  import type { Rspack } from './rspack';
11
11
  import type { HtmlRspackPlugin } from './thirdParty';
12
12
  import type { Falsy, MaybePromise } from './utils';
@@ -117,13 +117,14 @@ export type ModifyWebpackConfigUtils = ModifyWebpackChainUtils & {
117
117
  export type ModifyWebpackChainFn = (chain: RspackChain, utils: ModifyWebpackChainUtils) => Promise<void> | void;
118
118
  export type ModifyWebpackConfigFn = (config: WebpackConfig, utils: ModifyWebpackConfigUtils) => Promise<WebpackConfig | void> | WebpackConfig | void;
119
119
  export type PluginMeta = {
120
- environment: string;
120
+ environment?: AddPluginsOptions['environment'];
121
121
  instance: RsbuildPlugin;
122
122
  };
123
123
  export type PluginManager = Pick<RsbuildInstance, 'getPlugins' | 'addPlugins' | 'isPluginExists' | 'removePlugins'> & {
124
124
  /** Get all plugins with environment info */
125
125
  getAllPluginsWithMeta: () => PluginMeta[];
126
126
  };
127
+ export type RsbuildPluginApply = 'serve' | 'build';
127
128
  /**
128
129
  * The type of the Rsbuild plugin object.
129
130
  */
@@ -132,18 +133,37 @@ export type RsbuildPlugin = {
132
133
  * The name of the plugin, a unique identifier.
133
134
  */
134
135
  name: string;
136
+ /**
137
+ * Conditional apply the plugin during serve or build.
138
+ * - `'serve'`: Apply the plugin when starting the dev server or preview server.
139
+ * - `'build'`: Apply the plugin during build.
140
+ * - If not specified, the plugin will be applied during both serve and build.
141
+ */
142
+ apply?: RsbuildPluginApply;
135
143
  /**
136
144
  * The setup function of the plugin, which can be an async function.
137
145
  * This function is called once when the plugin is initialized.
138
146
  * @param api provides the context info, utility functions and lifecycle hooks.
139
147
  */
140
148
  setup: (api: RsbuildPluginAPI) => MaybePromise<void>;
149
+ /**
150
+ * Specifies the execution order of the plugin.
151
+ * - `'pre'`: Execute the plugin before other plugins.
152
+ * - `'post'`: Execute the plugin after other plugins.
153
+ * - If not specified, the plugin will execute in the order they were registered.
154
+ *
155
+ * This affects the order in which hooks are registered, but if a hook specifies
156
+ * an `order` property, the `order` takes higher precedence.
157
+ */
158
+ enforce?: 'pre' | 'post';
141
159
  /**
142
160
  * Declare the names of pre-plugins, which will be executed before the current plugin.
161
+ * This has higher precedence than the `enforce` property.
143
162
  */
144
163
  pre?: string[];
145
164
  /**
146
165
  * Declare the names of post-plugins, which will be executed after the current plugin.
166
+ * This has higher precedence than the `enforce` property.
147
167
  */
148
168
  post?: string[];
149
169
  /**
@@ -290,6 +310,11 @@ export type TransformDescriptor = {
290
310
  * @see https://rspack.rs/config/module#rulemimetype
291
311
  */
292
312
  mimetype?: Rspack.RuleSetCondition;
313
+ /**
314
+ * The original property for specifying execution order, now deprecated in favor of `order`.
315
+ * @deprecated Use `order` instead.
316
+ */
317
+ enforce?: 'pre' | 'post';
293
318
  /**
294
319
  * Specifies the execution order of the transform function.
295
320
  * - When specified as 'pre', the transform function will execute before other
@@ -298,7 +323,7 @@ export type TransformDescriptor = {
298
323
  * transform functions (or Rspack loaders).
299
324
  * @see https://rspack.rs/config/module#ruleenforce
300
325
  */
301
- enforce?: 'pre' | 'post';
326
+ order?: HookOrder;
302
327
  };
303
328
  export type TransformHook = (descriptor: TransformDescriptor, handler: TransformHandler) => void;
304
329
  export type ProcessAssetsStage = 'additional' | 'pre-process' | 'derived' | 'additions' | 'none' | 'optimize' | 'optimize-count' | 'optimize-compatibility' | 'optimize-size' | 'dev-tooling' | 'optimize-inline' | 'summarize' | 'optimize-hash' | 'optimize-transfer' | 'analyse' | 'report';
@@ -135,7 +135,7 @@ export type CreateRsbuildOptions = {
135
135
  */
136
136
  rsbuildConfig?: RsbuildConfig | (() => Promise<RsbuildConfig>);
137
137
  /**
138
- * Whether to call `loadEnv` to load env variables and define them
138
+ * Whether to call `loadEnv` to load environment variables and define them
139
139
  * as global variables via `source.define`.
140
140
  * @default false
141
141
  */
@@ -158,23 +158,26 @@ export type RsbuildProvider<B extends 'rspack' | 'webpack' = 'rspack'> = (option
158
158
  rsbuildOptions: ResolvedCreateRsbuildOptions;
159
159
  helpers: RsbuildProviderHelpers;
160
160
  }) => Promise<ProviderInstance<B>>;
161
+ export type AddPluginsOptions = {
162
+ /**
163
+ * Insert before the specified plugin.
164
+ */
165
+ before?: string;
166
+ /**
167
+ * Specify the environment that the plugin will be applied to.
168
+ * If not specified, the plugin will be be registered as a global plugin and
169
+ * applied to all environments.
170
+ */
171
+ environment?: string;
172
+ };
173
+ export type AddPlugins = (plugins: Array<RsbuildPlugin | Falsy>, options?: AddPluginsOptions) => void;
161
174
  export type RsbuildInstance = {
162
175
  /**
163
176
  * Register one or more Rsbuild plugins, which can be called multiple times.
164
177
  * This method needs to be called before compiling. If it is called after
165
178
  * compiling, it will not affect the compilation result.
166
179
  */
167
- addPlugins: (plugins: Array<RsbuildPlugin | Falsy>, options?: {
168
- /**
169
- * Insert before the specified plugin.
170
- */
171
- before?: string;
172
- /**
173
- * Add a plugin for the specified environment.
174
- * If environment is not specified, it will be registered as a global plugin (effective in all environments)
175
- */
176
- environment?: string;
177
- }) => void;
180
+ addPlugins: AddPlugins;
178
181
  /**
179
182
  * Get all the Rsbuild plugins registered in the current Rsbuild instance.
180
183
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "1.4.7",
3
+ "version": "1.4.9",
4
4
  "description": "The Rspack-based build tool.",
5
5
  "homepage": "https://rsbuild.rs",
6
6
  "bugs": {
@@ -46,17 +46,17 @@
46
46
  "types.d.ts"
47
47
  ],
48
48
  "dependencies": {
49
- "@rspack/core": "1.4.8",
49
+ "@rspack/core": "1.4.9",
50
50
  "@rspack/lite-tapable": "~1.0.1",
51
51
  "@swc/helpers": "^0.5.17",
52
52
  "core-js": "~3.44.0",
53
53
  "jiti": "^2.4.2"
54
54
  },
55
55
  "devDependencies": {
56
- "@rslib/core": "0.10.5",
56
+ "@rslib/core": "0.10.6",
57
57
  "@types/connect": "3.4.38",
58
58
  "@types/cors": "^2.8.19",
59
- "@types/node": "^22.16.4",
59
+ "@types/node": "^22.16.5",
60
60
  "@types/on-finished": "2.3.5",
61
61
  "@types/webpack-bundle-analyzer": "4.7.0",
62
62
  "@types/ws": "^8.18.1",
package/types.d.ts CHANGED
@@ -1,10 +1,27 @@
1
1
  /// <reference types="@rspack/core/module" />
2
2
 
3
+ /**
4
+ * This is a placeholder for extending the type options.
5
+ * You can augment this interface to enable stricter type checking.
6
+ * @example
7
+ * ```ts
8
+ * interface RsbuildTypeOptions {
9
+ * // This will enable strict type checking for `import.meta.env`.
10
+ * strictImportMetaEnv: true;
11
+ * }
12
+ * ```
13
+ */
14
+ // biome-ignore lint/suspicious/noEmptyInterface: placeholder
15
+ interface RsbuildTypeOptions {}
16
+
3
17
  /**
4
18
  * import.meta
5
19
  */
20
+ type ImportMetaEnvFallbackKey =
21
+ 'strictImportMetaEnv' extends keyof RsbuildTypeOptions ? never : string;
22
+
6
23
  interface ImportMetaEnv {
7
- [key: string]: any;
24
+ [key: ImportMetaEnvFallbackKey]: any;
8
25
  /**
9
26
  * The value of the `mode` configuration.
10
27
  * @example