@rsbuild/core 1.5.13 → 1.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -10,10 +10,8 @@ import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
10
10
  import * as __WEBPACK_EXTERNAL_MODULE_os__ from "os";
11
11
  import * as __WEBPACK_EXTERNAL_MODULE_path__ from "path";
12
12
  import * as __WEBPACK_EXTERNAL_MODULE_url__ from "url";
13
- import { logger } from "../compiled/rslog/index.js";
14
- import picocolors from "../compiled/picocolors/index.js";
15
- import node_fs, { existsSync } from "node:fs";
16
13
  import { EventEmitter } from "events";
14
+ import node_fs, { existsSync } from "node:fs";
17
15
  import node_os, { constants as external_node_os_constants } from "node:os";
18
16
  import node_process from "node:process";
19
17
  import { isPromise, isRegExp } from "node:util/types";
@@ -881,8 +879,8 @@ var superClass, superClass1, __webpack_modules__ = {
881
879
  return 'boolean' == typeof msg.finished ? !!(msg.finished || socket && !socket.writable) : 'boolean' == typeof msg.complete ? !!(msg.upgrade || !socket || !socket.readable || msg.complete && !msg.readable) : void 0;
882
880
  }
883
881
  },
884
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.0_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
885
- let yaml, { resolve } = __webpack_require__("node:path"), 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.6.0_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/options.js"), loadPlugins = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.0_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/plugins.js"), req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.0_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/req.js");
882
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
883
+ let yaml, { resolve } = __webpack_require__("node:path"), 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.6.1_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/options.js"), loadPlugins = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/plugins.js"), req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/req.js");
886
884
  async function processResult(ctx, result) {
887
885
  let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
888
886
  default: obj
@@ -953,8 +951,8 @@ var superClass, superClass1, __webpack_modules__ = {
953
951
  });
954
952
  };
955
953
  },
956
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.0_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/options.js": function(module, __unused_webpack_exports, __webpack_require__) {
957
- let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.0_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/req.js");
954
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/options.js": function(module, __unused_webpack_exports, __webpack_require__) {
955
+ let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/req.js");
958
956
  module.exports = async function(config, file) {
959
957
  if (config.parser && 'string' == typeof config.parser) try {
960
958
  config.parser = await req(config.parser, file);
@@ -974,8 +972,8 @@ var superClass, superClass1, __webpack_modules__ = {
974
972
  return config;
975
973
  };
976
974
  },
977
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.0_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/plugins.js": function(module, __unused_webpack_exports, __webpack_require__) {
978
- let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.0_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/req.js");
975
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/plugins.js": function(module, __unused_webpack_exports, __webpack_require__) {
976
+ let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/req.js");
979
977
  async function load(plugin, options, file) {
980
978
  try {
981
979
  if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
@@ -991,7 +989,7 @@ var superClass, superClass1, __webpack_modules__ = {
991
989
  }), list;
992
990
  };
993
991
  },
994
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.0_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/req.js": function(module, __unused_webpack_exports, __webpack_require__) {
992
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/req.js": function(module, __unused_webpack_exports, __webpack_require__) {
995
993
  let tsx, jiti;
996
994
  var __filename = __webpack_fileURLToPath__(import.meta.url);
997
995
  let { createRequire } = __webpack_require__("node:module"), { pathToFileURL } = __webpack_require__("node:url"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
@@ -1591,7 +1589,7 @@ __webpack_require__.r(provider_helpers_namespaceObject), __webpack_require__.d(p
1591
1589
  getChainUtils: ()=>getChainUtils,
1592
1590
  getConfigUtils: ()=>getConfigUtils,
1593
1591
  getHTMLPlugin: ()=>getHTMLPlugin,
1594
- getStatsOptions: ()=>getStatsOptions,
1592
+ getRsbuildStats: ()=>getRsbuildStats,
1595
1593
  initRsbuildConfig: ()=>initRsbuildConfig,
1596
1594
  inspectConfig: ()=>inspectConfig_inspectConfig,
1597
1595
  modifyBundlerChain: ()=>modifyBundlerChain,
@@ -1603,1414 +1601,1172 @@ __webpack_require__.r(provider_helpers_namespaceObject), __webpack_require__.d(p
1603
1601
  });
1604
1602
  var external_node_module_ = __webpack_require__("node:module");
1605
1603
  let rspack_rspack = (0, external_node_module_.createRequire)(import.meta.url)('@rspack/core');
1606
- var external_node_path_ = __webpack_require__("node:path"), external_node_url_ = __webpack_require__("node:url"), cjs = __webpack_require__("../../node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js"), cjs_default = __webpack_require__.n(cjs), dist = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/index.js");
1607
- function createMap(superClass) {
1608
- return class extends superClass {
1609
- extend(methods) {
1610
- return this.shorthands = methods, methods.forEach((method)=>{
1611
- this[method] = (value)=>this.set(method, value);
1612
- }), this;
1613
- }
1614
- clear() {
1615
- return this.store.clear(), this;
1616
- }
1617
- delete(key) {
1618
- return this.store.delete(key), this;
1619
- }
1620
- order() {
1621
- let entries = [
1622
- ...this.store
1623
- ].reduce((acc, [key, value])=>(acc[key] = value, acc), {}), names = Object.keys(entries), order = [
1624
- ...names
1625
- ];
1626
- return names.forEach((name)=>{
1627
- if (!entries[name]) return;
1628
- let { __before, __after } = entries[name];
1629
- __before && order.includes(__before) ? (order.splice(order.indexOf(name), 1), order.splice(order.indexOf(__before), 0, name)) : __after && order.includes(__after) && (order.splice(order.indexOf(name), 1), order.splice(order.indexOf(__after) + 1, 0, name));
1630
- }), {
1631
- entries,
1632
- order
1633
- };
1634
- }
1635
- entries() {
1636
- let { entries, order } = this.order();
1637
- if (order.length) return entries;
1638
- }
1639
- values() {
1640
- let { entries, order } = this.order();
1641
- return order.map((name)=>entries[name]);
1642
- }
1643
- get(key) {
1644
- return this.store.get(key);
1645
- }
1646
- getOrCompute(key, fn) {
1647
- return this.has(key) || this.set(key, fn()), this.get(key);
1648
- }
1649
- has(key) {
1650
- return this.store.has(key);
1651
- }
1652
- set(key, value) {
1653
- return this.store.set(key, value), this;
1654
- }
1655
- merge(obj, omit = []) {
1656
- return Object.keys(obj).forEach((key)=>{
1657
- if (omit.includes(key)) return;
1658
- let value = obj[key];
1659
- (Array.isArray(value) || 'object' == typeof value) && null !== value && this.has(key) ? this.set(key, cjs(this.get(key), value)) : this.set(key, value);
1660
- }), this;
1661
- }
1662
- clean(obj) {
1663
- return Object.keys(obj).reduce((acc, key)=>{
1664
- let value = obj[key];
1665
- return void 0 === value || Array.isArray(value) && !value.length || '[object Object]' === Object.prototype.toString.call(value) && !Object.keys(value).length || (acc[key] = value), acc;
1666
- }, {});
1667
- }
1668
- when(condition, whenTruthy = Function.prototype, whenFalsy = Function.prototype) {
1669
- return condition ? whenTruthy(this) : whenFalsy(this), this;
1670
- }
1671
- constructor(...args){
1672
- super(...args), this.store = new Map();
1673
- }
1674
- };
1675
- }
1676
- function createChainable(superClass) {
1677
- return class extends superClass {
1678
- batch(handler) {
1679
- return handler(this), this;
1680
- }
1681
- end() {
1682
- return this.parent;
1683
- }
1684
- constructor(parent){
1685
- super(), this.parent = parent;
1686
- }
1687
- };
1604
+ var external_node_path_ = __webpack_require__("node:path"), external_node_url_ = __webpack_require__("node:url");
1605
+ let constants_filename = (0, external_node_url_.fileURLToPath)(import.meta.url), constants_dirname = (0, external_node_path_.dirname)(constants_filename), isDeno = 'undefined' != typeof Deno, ROOT_DIST_DIR = 'dist', LOADER_PATH = (0, external_node_path_.join)(constants_dirname), STATIC_PATH = (0, external_node_path_.join)(constants_dirname, '../static'), COMPILED_PATH = (0, external_node_path_.join)(constants_dirname, '../compiled'), RSBUILD_OUTPUTS_PATH = '.rsbuild', DEFAULT_DEV_HOST = '0.0.0.0', DEFAULT_ASSET_PREFIX = '/', DEFAULT_WEB_BROWSERSLIST = [
1606
+ 'chrome >= 87',
1607
+ 'edge >= 88',
1608
+ 'firefox >= 78',
1609
+ 'safari >= 14'
1610
+ ], DEFAULT_BROWSERSLIST = {
1611
+ web: DEFAULT_WEB_BROWSERSLIST,
1612
+ 'web-worker': DEFAULT_WEB_BROWSERSLIST,
1613
+ node: [
1614
+ 'node >= 16'
1615
+ ]
1616
+ }, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, RAW_QUERY_REGEX = /[?&]raw(?:&|=|$)/, INLINE_QUERY_REGEX = /[?&]inline(?:&|=|$)/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
1617
+ 'woff',
1618
+ 'woff2',
1619
+ 'eot',
1620
+ 'ttf',
1621
+ 'otf',
1622
+ 'ttc'
1623
+ ], IMAGE_EXTENSIONS = [
1624
+ 'png',
1625
+ 'jpg',
1626
+ 'jpeg',
1627
+ 'pjpeg',
1628
+ 'pjp',
1629
+ 'gif',
1630
+ 'bmp',
1631
+ 'webp',
1632
+ 'ico',
1633
+ 'apng',
1634
+ 'avif',
1635
+ 'tif',
1636
+ 'tiff',
1637
+ 'jfif',
1638
+ 'cur'
1639
+ ], VIDEO_EXTENSIONS = [
1640
+ 'mp4',
1641
+ 'webm',
1642
+ 'ogg',
1643
+ 'mov'
1644
+ ], AUDIO_EXTENSIONS = [
1645
+ 'mp3',
1646
+ 'wav',
1647
+ 'flac',
1648
+ 'aac',
1649
+ 'm4a',
1650
+ 'opus'
1651
+ ], vendors_require = (0, external_node_module_.createRequire)(import.meta.url), requireCompiledPackage = (name)=>vendors_require(`${COMPILED_PATH}/${name}/index.js`), color = requireCompiledPackage('picocolors'), logger = requireCompiledPackage('rslog').logger, isDebug = ()=>{
1652
+ if (!process.env.DEBUG) return !1;
1653
+ let values = process.env.DEBUG.toLocaleLowerCase().split(',');
1654
+ return [
1655
+ 'rsbuild',
1656
+ 'builder',
1657
+ '*'
1658
+ ].some((key)=>values.includes(key));
1659
+ };
1660
+ function toArr(any) {
1661
+ return null == any ? [] : Array.isArray(any) ? any : [
1662
+ any
1663
+ ];
1688
1664
  }
1689
- let ChainedMap = createMap(createChainable(Object)), ChainedValueMap = (superClass = createMap(createChainable(class extends Function {
1690
- classCall() {
1691
- throw Error('not implemented');
1665
+ isDebug() && (logger.level = 'verbose'), logger.override({
1666
+ debug: (message, ...args)=>{
1667
+ let now, hours, minutes, seconds;
1668
+ if ('verbose' !== logger.level) return;
1669
+ let time = color.gray((hours = String((now = new Date()).getHours()).padStart(2, '0'), minutes = String(now.getMinutes()).padStart(2, '0'), seconds = String(now.getSeconds()).padStart(2, '0'), `${hours}:${minutes}:${seconds}`));
1670
+ console.log(` ${color.magenta('rsbuild')} ${time} ${message}`, ...args);
1692
1671
  }
1693
- constructor(){
1694
- return super(), new Proxy(this, {
1695
- apply: (target, thisArg, args)=>target.classCall(...args)
1696
- });
1672
+ });
1673
+ let removeBrackets = (v)=>v.replace(/[<[].+/, "").trim(), findLongest = (arr)=>arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0], padRight = (str, length)=>str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`, setDotProp = (obj, keys, val)=>{
1674
+ let x, i = 0, length = keys.length, t = obj;
1675
+ for(; i < length; ++i)x = t[keys[i]], t = t[keys[i]] = i === length - 1 ? val : null != x ? x : ~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
1676
+ }, setByType = (obj, transforms)=>{
1677
+ for (let key of Object.keys(transforms)){
1678
+ let transform = transforms[key];
1679
+ transform.shouldTransform && (obj[key] = Array.prototype.concat.call([], obj[key]), "function" == typeof transform.transformFunction && (obj[key] = obj[key].map(transform.transformFunction)));
1697
1680
  }
1698
- })), class extends superClass {
1699
- set(...args) {
1700
- return this.useMap = !0, this.value = void 0, super.set(...args);
1681
+ }, camelcaseOptionName = (name)=>name.split(".").map((v, i)=>0 === i ? v.replace(/([a-z])-([a-z])/g, (_, p1, p2)=>p1 + p2.toUpperCase()) : v).join(".");
1682
+ class CACError extends Error {
1683
+ constructor(message){
1684
+ super(message), this.name = this.constructor.name, "function" == typeof Error.captureStackTrace ? Error.captureStackTrace(this, this.constructor) : this.stack = Error(message).stack;
1701
1685
  }
1702
- clear() {
1703
- return this.value = void 0, super.clear();
1686
+ }
1687
+ class Option {
1688
+ constructor(rawName, description, config){
1689
+ this.rawName = rawName, this.description = description, this.config = Object.assign({}, config), rawName = rawName.replace(/\.\*/g, ""), this.negated = !1, this.names = removeBrackets(rawName).split(",").map((v)=>{
1690
+ let name = v.trim().replace(/^-{1,2}/, "");
1691
+ return name.startsWith("no-") && (this.negated = !0, name = name.replace(/^no-/, "")), camelcaseOptionName(name);
1692
+ }).sort((a, b)=>a.length > b.length ? 1 : -1), this.name = this.names[this.names.length - 1], this.negated && null == this.config.default && (this.config.default = !0), rawName.includes("<") ? this.required = !0 : rawName.includes("[") ? this.required = !1 : this.isBoolean = !0;
1704
1693
  }
1705
- classCall(value) {
1706
- return this.clear(), this.useMap = !1, this.value = value, this.parent;
1694
+ }
1695
+ let processArgs = process.argv, platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
1696
+ class Command {
1697
+ constructor(rawName, description, config = {}, cli){
1698
+ this.rawName = rawName, this.description = description, this.config = config, this.cli = cli, this.options = [], this.aliasNames = [], this.name = removeBrackets(rawName), this.args = ((v)=>{
1699
+ let angledMatch, squareMatch, ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g, SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g, res = [], parse = (match)=>{
1700
+ let variadic = !1, value = match[1];
1701
+ return value.startsWith("...") && (value = value.slice(3), variadic = !0), {
1702
+ required: match[0].startsWith("<"),
1703
+ value,
1704
+ variadic
1705
+ };
1706
+ };
1707
+ for(; angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v);)res.push(parse(angledMatch));
1708
+ for(; squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v);)res.push(parse(squareMatch));
1709
+ return res;
1710
+ })(rawName), this.examples = [];
1707
1711
  }
1708
- entries() {
1709
- return this.useMap ? super.entries() : this.value;
1712
+ usage(text) {
1713
+ return this.usageText = text, this;
1710
1714
  }
1711
- values() {
1712
- return this.useMap ? super.values() : this.value;
1715
+ allowUnknownOptions() {
1716
+ return this.config.allowUnknownOptions = !0, this;
1713
1717
  }
1714
- constructor(...args){
1715
- super(...args), this.value = void 0, this.useMap = !0;
1718
+ ignoreOptionDefaultValue() {
1719
+ return this.config.ignoreOptionDefaultValue = !0, this;
1716
1720
  }
1717
- }), ChainedSet = (superClass1 = createChainable(Object), class extends superClass1 {
1718
- add(value) {
1719
- return this.store.add(value), this;
1721
+ version(version, customFlags = "-v, --version") {
1722
+ return this.versionNumber = version, this.option(customFlags, "Display version number"), this;
1720
1723
  }
1721
- prepend(value) {
1722
- return this.store = new Set([
1723
- value,
1724
- ...this.store
1725
- ]), this;
1724
+ example(example) {
1725
+ return this.examples.push(example), this;
1726
1726
  }
1727
- clear() {
1728
- return this.store.clear(), this;
1727
+ option(rawName, description, config) {
1728
+ let option = new Option(rawName, description, config);
1729
+ return this.options.push(option), this;
1729
1730
  }
1730
- delete(value) {
1731
- return this.store.delete(value), this;
1731
+ alias(name) {
1732
+ return this.aliasNames.push(name), this;
1732
1733
  }
1733
- values() {
1734
- return [
1735
- ...this.store
1736
- ];
1734
+ action(callback) {
1735
+ return this.commandAction = callback, this;
1737
1736
  }
1738
- has(value) {
1739
- return this.store.has(value);
1737
+ isMatched(name) {
1738
+ return this.name === name || this.aliasNames.includes(name);
1740
1739
  }
1741
- merge(arr) {
1742
- return void 0 !== arr && (this.store = new Set([
1743
- ...this.store,
1744
- ...arr
1745
- ])), this;
1740
+ get isDefaultCommand() {
1741
+ return "" === this.name || this.aliasNames.includes("!");
1746
1742
  }
1747
- when(condition, whenTruthy = Function.prototype, whenFalsy = Function.prototype) {
1748
- return condition ? whenTruthy(this) : whenFalsy(this), this;
1743
+ get isGlobalCommand() {
1744
+ return this instanceof GlobalCommand;
1749
1745
  }
1750
- constructor(...args){
1751
- super(...args), this.store = new Set();
1746
+ hasOption(name) {
1747
+ return name = name.split(".")[0], this.options.find((option)=>option.names.includes(name));
1752
1748
  }
1753
- }), Orderable = (Class)=>class extends Class {
1754
- before(name) {
1755
- if (this.__after) throw Error(`Unable to set .before(${JSON.stringify(name)}) with existing value for .after()`);
1756
- return this.__before = name, this;
1757
- }
1758
- after(name) {
1759
- if (this.__before) throw Error(`Unable to set .after(${JSON.stringify(name)}) with existing value for .before()`);
1760
- return this.__after = name, this;
1749
+ outputHelp() {
1750
+ let { name, commands } = this.cli, { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand, sections = [
1751
+ {
1752
+ body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
1753
+ }
1754
+ ];
1755
+ if (sections.push({
1756
+ title: "Usage",
1757
+ body: ` $ ${name} ${this.usageText || this.rawName}`
1758
+ }), (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
1759
+ let longestCommandName = findLongest(commands.map((command)=>command.rawName));
1760
+ sections.push({
1761
+ title: "Commands",
1762
+ body: commands.map((command)=>` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`).join("\n")
1763
+ }), sections.push({
1764
+ title: "For more info, run any command with the `--help` flag",
1765
+ body: commands.map((command)=>` $ ${name}${"" === command.name ? "" : ` ${command.name}`} --help`).join("\n")
1766
+ });
1761
1767
  }
1762
- merge(obj, omit = []) {
1763
- return obj.before && this.before(obj.before), obj.after && this.after(obj.after), super.merge(obj, [
1764
- ...omit,
1765
- 'before',
1766
- 'after'
1767
- ]);
1768
+ let options = this.isGlobalCommand ? globalOptions : [
1769
+ ...this.options,
1770
+ ...globalOptions || []
1771
+ ];
1772
+ if (this.isGlobalCommand || this.isDefaultCommand || (options = options.filter((option)=>"version" !== option.name)), options.length > 0) {
1773
+ let longestOptionName = findLongest(options.map((option)=>option.rawName));
1774
+ sections.push({
1775
+ title: "Options",
1776
+ body: options.map((option)=>` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${void 0 === option.config.default ? "" : `(default: ${option.config.default})`}`).join("\n")
1777
+ });
1768
1778
  }
1769
- }, src_Plugin = Orderable(class extends ChainedMap {
1770
- use(plugin, args = []) {
1771
- return this.set('plugin', plugin).set('args', args);
1779
+ this.examples.length > 0 && sections.push({
1780
+ title: "Examples",
1781
+ body: this.examples.map((example)=>"function" == typeof example ? example(name) : example).join("\n")
1782
+ }), helpCallback && (sections = helpCallback(sections) || sections), console.log(sections.map((section)=>section.title ? `${section.title}:
1783
+ ${section.body}` : section.body).join("\n\n"));
1772
1784
  }
1773
- tap(f) {
1774
- if (!this.has('plugin')) throw Error(`Cannot call .tap() on a plugin that has not yet been defined. Call ${this.type}('${this.name}').use(<Plugin>) first.`);
1775
- return this.set('args', f(this.get('args') || [])), this;
1785
+ outputVersion() {
1786
+ let { name } = this.cli, { versionNumber } = this.cli.globalCommand;
1787
+ versionNumber && console.log(`${name}/${versionNumber} ${platformInfo}`);
1776
1788
  }
1777
- set(key, value) {
1778
- if ('args' === key && !Array.isArray(value)) throw Error('args must be an array of arguments');
1779
- return super.set(key, value);
1789
+ checkRequiredArgs() {
1790
+ let minimalArgsCount = this.args.filter((arg)=>arg.required).length;
1791
+ if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
1780
1792
  }
1781
- merge(obj, omit = []) {
1782
- return 'plugin' in obj && this.set('plugin', obj.plugin), 'args' in obj && this.set('args', obj.args), super.merge(obj, [
1783
- ...omit,
1784
- 'args',
1785
- 'plugin'
1786
- ]);
1793
+ checkUnknownOptions() {
1794
+ let { options, globalCommand } = this.cli;
1795
+ if (!this.config.allowUnknownOptions) {
1796
+ for (let name of Object.keys(options))if ("--" !== name && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
1797
+ }
1787
1798
  }
1788
- toConfig() {
1789
- let init = this.get('init'), plugin = this.get('plugin'), args = this.get('args'), pluginPath = null;
1790
- if (void 0 === plugin) throw Error(`Invalid ${this.type} configuration: ${this.type}('${this.name}').use(<Plugin>) was not called to specify the plugin`);
1791
- 'string' == typeof plugin && (plugin = require(pluginPath = plugin));
1792
- let constructorName = plugin.__expression ? `(${plugin.__expression})` : plugin.name, config = init(plugin, args);
1793
- return Object.defineProperties(config, {
1794
- __pluginName: {
1795
- value: this.name
1796
- },
1797
- __pluginType: {
1798
- value: this.type
1799
- },
1800
- __pluginArgs: {
1801
- value: args
1802
- },
1803
- __pluginConstructorName: {
1804
- value: constructorName
1805
- },
1806
- __pluginPath: {
1807
- value: pluginPath
1799
+ checkOptionValue() {
1800
+ let { options: parsedOptions, globalCommand } = this.cli, options = [
1801
+ ...globalCommand.options,
1802
+ ...this.options
1803
+ ];
1804
+ for (let option of options){
1805
+ let value = parsedOptions[option.name.split(".")[0]];
1806
+ if (option.required) {
1807
+ let hasNegated = options.some((o)=>o.negated && o.names.includes(option.name));
1808
+ if (!0 === value || !1 === value && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
1808
1809
  }
1809
- }), config;
1810
+ }
1810
1811
  }
1811
- constructor(parent, name, type = 'plugin'){
1812
- super(parent), this.name = name, this.type = type, this.extend([
1813
- 'init'
1814
- ]), this.init((Plugin, args = [])=>'function' == typeof Plugin ? new Plugin(...args) : Plugin);
1812
+ }
1813
+ class GlobalCommand extends Command {
1814
+ constructor(cli){
1815
+ super("@@global@@", "", {}, cli);
1815
1816
  }
1816
- }), childMaps = [
1817
- 'alias',
1818
- 'fallback',
1819
- 'byDependency',
1820
- 'extensionAlias'
1821
- ], childSets = [
1822
- 'aliasFields',
1823
- 'conditionNames',
1824
- "descriptionFiles",
1825
- 'extensions',
1826
- 'mainFields',
1827
- 'mainFiles',
1828
- 'exportsFields',
1829
- 'importsFields',
1830
- 'restrictions',
1831
- 'roots',
1832
- 'modules'
1833
- ];
1834
- class Resolve_class extends ChainedMap {
1835
- plugin(name) {
1836
- return this.plugins.getOrCompute(name, ()=>new src_Plugin(this, name, 'resolve.plugin'));
1817
+ }
1818
+ var __assign = Object.assign;
1819
+ class CAC extends EventEmitter {
1820
+ constructor(name = ""){
1821
+ super(), this.name = name, this.commands = [], this.rawArgs = [], this.args = [], this.options = {}, this.globalCommand = new GlobalCommand(this), this.globalCommand.usage("<command> [options]");
1837
1822
  }
1838
- get(key) {
1839
- return childMaps.includes(key) ? this[key].entries() : childSets.includes(key) ? this[key].values() : super.get(key);
1823
+ usage(text) {
1824
+ return this.globalCommand.usage(text), this;
1840
1825
  }
1841
- toConfig() {
1842
- let config = Object.assign(this.entries() || {}, {
1843
- plugins: this.plugins.values().map((plugin)=>plugin.toConfig())
1844
- });
1845
- return childMaps.forEach((key)=>{
1846
- config[key] = this[key].entries();
1847
- }), childSets.forEach((key)=>{
1848
- config[key] = this[key].values();
1849
- }), this.clean(config);
1826
+ command(rawName, description, config) {
1827
+ let command = new Command(rawName, description || "", config, this);
1828
+ return command.globalCommand = this.globalCommand, this.commands.push(command), command;
1850
1829
  }
1851
- merge(obj, omit = []) {
1852
- !omit.includes('plugin') && 'plugin' in obj && Object.keys(obj.plugin).forEach((name)=>this.plugin(name).merge(obj.plugin[name]));
1853
- let omissions = [
1854
- ...childMaps,
1855
- ...childSets
1856
- ];
1857
- return omissions.forEach((key)=>{
1858
- !omit.includes(key) && key in obj && this[key].merge(obj[key]);
1859
- }), super.merge(obj, [
1860
- ...omit,
1861
- ...omissions,
1862
- 'plugin'
1863
- ]);
1830
+ option(rawName, description, config) {
1831
+ return this.globalCommand.option(rawName, description, config), this;
1864
1832
  }
1865
- constructor(parent){
1866
- super(parent), childMaps.forEach((key)=>{
1867
- this[key] = new ChainedMap(this);
1868
- }), childSets.forEach((key)=>{
1869
- this[key] = new ChainedSet(this);
1870
- }), this.plugins = new ChainedMap(this), this.extend([
1871
- 'cachePredicate',
1872
- 'cacheWithContext',
1873
- 'enforceExtension',
1874
- 'symlinks',
1875
- 'unsafeCache',
1876
- 'preferRelative',
1877
- 'preferAbsolute',
1878
- 'tsConfig'
1879
- ]);
1833
+ help(callback) {
1834
+ return this.globalCommand.option("-h, --help", "Display this message"), this.globalCommand.helpCallback = callback, this.showHelpOnExit = !0, this;
1880
1835
  }
1881
- }
1882
- class ResolveLoader_class extends Resolve_class {
1883
- toConfig() {
1884
- return this.clean({
1885
- modules: this.modules.values(),
1886
- moduleExtensions: this.moduleExtensions.values(),
1887
- packageMains: this.packageMains.values(),
1888
- ...super.toConfig()
1889
- });
1836
+ version(version, customFlags = "-v, --version") {
1837
+ return this.globalCommand.version(version, customFlags), this.showVersionOnExit = !0, this;
1890
1838
  }
1891
- merge(obj, omit = []) {
1892
- let omissions = [
1893
- 'modules',
1894
- 'moduleExtensions',
1895
- 'packageMains'
1896
- ];
1897
- return omissions.forEach((key)=>{
1898
- !omit.includes(key) && key in obj && this[key].merge(obj[key]);
1899
- }), super.merge(obj, [
1900
- ...omit,
1901
- ...omissions
1902
- ]);
1839
+ example(example) {
1840
+ return this.globalCommand.example(example), this;
1903
1841
  }
1904
- constructor(parent){
1905
- super(parent), this.modules = new ChainedSet(this), this.moduleExtensions = new ChainedSet(this), this.packageMains = new ChainedSet(this);
1842
+ outputHelp() {
1843
+ this.matchedCommand ? this.matchedCommand.outputHelp() : this.globalCommand.outputHelp();
1906
1844
  }
1907
- }
1908
- class Output_class extends ChainedMap {
1909
- constructor(parent){
1910
- super(parent), this.extend([
1911
- 'auxiliaryComment',
1912
- 'charset',
1913
- 'chunkFilename',
1914
- 'chunkLoadTimeout',
1915
- 'chunkLoadingGlobal',
1916
- 'chunkLoading',
1917
- 'chunkFormat',
1918
- 'enabledChunkLoadingTypes',
1919
- 'crossOriginLoading',
1920
- 'devtoolFallbackModuleFilenameTemplate',
1921
- 'devtoolModuleFilenameTemplate',
1922
- 'devtoolNamespace',
1923
- 'filename',
1924
- 'assetModuleFilename',
1925
- 'globalObject',
1926
- 'uniqueName',
1927
- 'hashDigest',
1928
- 'hashDigestLength',
1929
- 'hashFunction',
1930
- 'hashSalt',
1931
- 'hotUpdateChunkFilename',
1932
- 'hotUpdateGlobal',
1933
- 'hotUpdateMainFilename',
1934
- 'library',
1935
- 'libraryExport',
1936
- 'libraryTarget',
1937
- 'importFunctionName',
1938
- 'path',
1939
- 'pathinfo',
1940
- 'publicPath',
1941
- "scriptType",
1942
- 'sourceMapFilename',
1943
- 'sourcePrefix',
1944
- 'strictModuleErrorHandling',
1945
- 'strictModuleExceptionHandling',
1946
- 'umdNamedDefine',
1947
- 'workerChunkLoading',
1948
- 'enabledLibraryTypes',
1949
- 'environment',
1950
- 'compareBeforeEmit',
1951
- 'wasmLoading',
1952
- 'webassemblyModuleFilename',
1953
- 'enabledWasmLoadingTypes',
1954
- 'iife',
1955
- 'module',
1956
- 'clean'
1957
- ]);
1958
- }
1959
- }
1960
- class DevServer_class extends ChainedMap {
1961
- toConfig() {
1962
- return this.clean({
1963
- allowedHosts: this.allowedHosts.values(),
1964
- ...this.entries() || {}
1965
- });
1966
- }
1967
- merge(obj, omit = []) {
1968
- return !omit.includes('allowedHosts') && 'allowedHosts' in obj && this.allowedHosts.merge(obj.allowedHosts), super.merge(obj, [
1969
- 'allowedHosts'
1970
- ]);
1971
- }
1972
- constructor(parent){
1973
- super(parent), this.allowedHosts = new ChainedSet(this), this.extend([
1974
- 'after',
1975
- 'before',
1976
- 'bonjour',
1977
- 'clientLogLevel',
1978
- 'compress',
1979
- 'contentBase',
1980
- 'contentBasePublicPath',
1981
- 'disableHostCheck',
1982
- 'filename',
1983
- 'headers',
1984
- 'historyApiFallback',
1985
- 'host',
1986
- 'hot',
1987
- 'hotOnly',
1988
- 'http2',
1989
- 'https',
1990
- 'index',
1991
- 'injectClient',
1992
- 'injectHot',
1993
- 'inline',
1994
- 'lazy',
1995
- 'liveReload',
1996
- 'mimeTypes',
1997
- 'noInfo',
1998
- 'onListening',
1999
- 'open',
2000
- 'openPage',
2001
- 'overlay',
2002
- 'pfx',
2003
- 'pfxPassphrase',
2004
- 'port',
2005
- 'proxy',
2006
- 'progress',
2007
- 'public',
2008
- 'publicPath',
2009
- 'quiet',
2010
- 'serveIndex',
2011
- 'setup',
2012
- 'socket',
2013
- 'sockHost',
2014
- 'sockPath',
2015
- 'sockPort',
2016
- 'staticOptions',
2017
- 'stats',
2018
- 'stdin',
2019
- 'transportMode',
2020
- 'useLocalIp',
2021
- 'watchContentBase',
2022
- 'watchOptions',
2023
- 'writeToDisk'
2024
- ]);
1845
+ outputVersion() {
1846
+ this.globalCommand.outputVersion();
2025
1847
  }
2026
- }
2027
- let Use = Orderable(class extends ChainedMap {
2028
- tap(f) {
2029
- return this.options(f(this.get('options'))), this;
1848
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
1849
+ return this.args = args, this.options = options, matchedCommand && (this.matchedCommand = matchedCommand), matchedCommandName && (this.matchedCommandName = matchedCommandName), this;
2030
1850
  }
2031
- merge(obj, omit = []) {
2032
- return !omit.includes('loader') && 'loader' in obj && this.loader(obj.loader), !omit.includes('options') && 'options' in obj && this.options(cjs(this.store.get('options') || {}, obj.options)), super.merge(obj, [
2033
- ...omit,
2034
- 'loader',
2035
- 'options'
2036
- ]);
1851
+ unsetMatchedCommand() {
1852
+ this.matchedCommand = void 0, this.matchedCommandName = void 0;
2037
1853
  }
2038
- toConfig() {
2039
- let config = this.clean(this.entries() || {});
2040
- return Object.defineProperties(config, {
2041
- __useName: {
2042
- value: this.name
2043
- },
2044
- __ruleNames: {
2045
- value: this.parent && this.parent.names
2046
- },
2047
- __ruleTypes: {
2048
- value: this.parent && this.parent.ruleTypes
1854
+ parse(argv = processArgs, { run = !0 } = {}) {
1855
+ var input;
1856
+ let m;
1857
+ this.rawArgs = argv, this.name || (this.name = argv[1] ? (input = argv[1], (m = /([^\\\/]+)$/.exec(input)) ? m[1] : "") : "cli");
1858
+ let shouldParse = !0;
1859
+ for (let command of this.commands){
1860
+ let parsed = this.mri(argv.slice(2), command), commandName = parsed.args[0];
1861
+ if (command.isMatched(commandName)) {
1862
+ shouldParse = !1;
1863
+ let parsedInfo = __assign(__assign({}, parsed), {
1864
+ args: parsed.args.slice(1)
1865
+ });
1866
+ this.setParsedInfo(parsedInfo, command, commandName), this.emit(`command:${commandName}`, command);
2049
1867
  }
2050
- }), config;
2051
- }
2052
- constructor(parent, name){
2053
- super(parent), this.name = name, this.extend([
2054
- 'loader',
2055
- 'options',
2056
- 'parallel'
2057
- ]);
2058
- }
2059
- });
2060
- function toArray(arr) {
2061
- return Array.isArray(arr) ? arr : [
2062
- arr
2063
- ];
2064
- }
2065
- let Rule_Rule = Orderable(class extends ChainedMap {
2066
- use(name) {
2067
- return this.uses.getOrCompute(name, ()=>new Use(this, name));
2068
- }
2069
- rule(name) {
2070
- return this.rules.getOrCompute(name, ()=>new Rule_Rule(this, name, 'rule'));
2071
- }
2072
- oneOf(name) {
2073
- return this.oneOfs.getOrCompute(name, ()=>new Rule_Rule(this, name, 'oneOf'));
2074
- }
2075
- pre() {
2076
- return this.enforce('pre');
2077
- }
2078
- post() {
2079
- return this.enforce('post');
2080
- }
2081
- toConfig() {
2082
- let config = this.clean(Object.assign(this.entries() || {}, {
2083
- include: this.include.values(),
2084
- exclude: this.exclude.values(),
2085
- rules: this.rules.values().map((rule)=>rule.toConfig()),
2086
- oneOf: this.oneOfs.values().map((oneOf)=>oneOf.toConfig()),
2087
- use: this.uses.values().map((use)=>use.toConfig()),
2088
- resolve: this.resolve.toConfig()
2089
- }));
2090
- return Object.defineProperties(config, {
2091
- __ruleNames: {
2092
- value: this.names
2093
- },
2094
- __ruleTypes: {
2095
- value: this.ruleTypes
1868
+ }
1869
+ if (shouldParse) {
1870
+ for (let command of this.commands)if ("" === command.name) {
1871
+ shouldParse = !1;
1872
+ let parsed = this.mri(argv.slice(2), command);
1873
+ this.setParsedInfo(parsed, command), this.emit("command:!", command);
2096
1874
  }
2097
- }), config;
2098
- }
2099
- merge(obj, omit = []) {
2100
- return !omit.includes('include') && 'include' in obj && this.include.merge(toArray(obj.include)), !omit.includes('exclude') && 'exclude' in obj && this.exclude.merge(toArray(obj.exclude)), !omit.includes('use') && 'use' in obj && Object.keys(obj.use).forEach((name)=>this.use(name).merge(obj.use[name])), !omit.includes('rules') && 'rules' in obj && Object.keys(obj.rules).forEach((name)=>this.rule(name).merge(obj.rules[name])), !omit.includes('oneOf') && 'oneOf' in obj && Object.keys(obj.oneOf).forEach((name)=>this.oneOf(name).merge(obj.oneOf[name])), !omit.includes('resolve') && 'resolve' in obj && this.resolve.merge(obj.resolve), !omit.includes('test') && 'test' in obj && this.test(obj.test instanceof RegExp || 'function' == typeof obj.test ? obj.test : new RegExp(obj.test)), super.merge(obj, [
2101
- ...omit,
2102
- 'include',
2103
- 'exclude',
2104
- 'use',
2105
- 'rules',
2106
- 'oneOf',
2107
- 'resolve',
2108
- 'test'
2109
- ]);
2110
- }
2111
- constructor(parent, name, ruleType = 'rule'){
2112
- super(parent), this.ruleName = name, this.names = [], this.ruleType = ruleType, this.ruleTypes = [];
2113
- let rule = this;
2114
- for(; rule instanceof Rule_Rule;)this.names.unshift(rule.ruleName), this.ruleTypes.unshift(rule.ruleType), rule = rule.parent;
2115
- this.uses = new ChainedMap(this), this.include = new ChainedSet(this), this.exclude = new ChainedSet(this), this.rules = new ChainedMap(this), this.oneOfs = new ChainedMap(this), this.resolve = new Resolve_class(this), this.resolve.extend([
2116
- 'fullySpecified'
2117
- ]), this.extend([
2118
- 'dependency',
2119
- 'enforce',
2120
- 'issuer',
2121
- 'issuerLayer',
2122
- 'layer',
2123
- 'mimetype',
2124
- 'parser',
2125
- 'generator',
2126
- 'resource',
2127
- 'resourceFragment',
2128
- 'resourceQuery',
2129
- 'sideEffects',
2130
- 'with',
2131
- 'test',
2132
- 'type'
2133
- ]);
2134
- }
2135
- });
2136
- class Module_class extends ChainedMap {
2137
- defaultRule(name) {
2138
- return this.defaultRules.getOrCompute(name, ()=>new Rule_Rule(this, name, 'defaultRule'));
2139
- }
2140
- rule(name) {
2141
- return this.rules.getOrCompute(name, ()=>new Rule_Rule(this, name, 'rule'));
2142
- }
2143
- toConfig() {
2144
- return this.clean(Object.assign(this.entries() || {}, {
2145
- defaultRules: this.defaultRules.values().map((r)=>r.toConfig()),
2146
- generator: this.generator.entries(),
2147
- parser: this.parser.entries(),
2148
- rules: this.rules.values().map((r)=>r.toConfig())
2149
- }));
1875
+ }
1876
+ if (shouldParse) {
1877
+ let parsed = this.mri(argv.slice(2));
1878
+ this.setParsedInfo(parsed);
1879
+ }
1880
+ this.options.help && this.showHelpOnExit && (this.outputHelp(), run = !1, this.unsetMatchedCommand()), this.options.version && this.showVersionOnExit && null == this.matchedCommandName && (this.outputVersion(), run = !1, this.unsetMatchedCommand());
1881
+ let parsedArgv = {
1882
+ args: this.args,
1883
+ options: this.options
1884
+ };
1885
+ return run && this.runMatchedCommand(), !this.matchedCommand && this.args[0] && this.emit("command:*"), parsedArgv;
2150
1886
  }
2151
- merge(obj, omit = []) {
2152
- return !omit.includes('rule') && 'rule' in obj && Object.keys(obj.rule).forEach((name)=>this.rule(name).merge(obj.rule[name])), !omit.includes('defaultRule') && 'defaultRule' in obj && Object.keys(obj.defaultRule).forEach((name)=>this.defaultRule(name).merge(obj.defaultRule[name])), super.merge(obj, [
2153
- 'rule',
2154
- 'defaultRule'
2155
- ]);
1887
+ mri(argv, command) {
1888
+ let cliOptions = [
1889
+ ...this.globalCommand.options,
1890
+ ...command ? command.options : []
1891
+ ], mriOptions = ((options)=>{
1892
+ let result = {
1893
+ alias: {},
1894
+ boolean: []
1895
+ };
1896
+ for (let [index, option] of options.entries())option.names.length > 1 && (result.alias[option.names[0]] = option.names.slice(1)), option.isBoolean && (option.negated && options.some((o, i)=>i !== index && o.names.some((name)=>option.names.includes(name)) && "boolean" == typeof o.required) || result.boolean.push(option.names[0]));
1897
+ return result;
1898
+ })(cliOptions), argsAfterDoubleDashes = [], doubleDashesIndex = argv.indexOf("--");
1899
+ doubleDashesIndex > -1 && (argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1), argv = argv.slice(0, doubleDashesIndex));
1900
+ let parsed = function(args, opts) {
1901
+ opts = opts || {};
1902
+ var k, arr, arg, name, val, out = {
1903
+ _: []
1904
+ }, i = 0, j = 0, idx = 0, len = (args = args || []).length;
1905
+ let alibi = void 0 !== opts.alias, strict = void 0 !== opts.unknown, defaults = void 0 !== opts.default;
1906
+ if (opts.alias = opts.alias || {}, opts.string = toArr(opts.string), opts.boolean = toArr(opts.boolean), alibi) for(k in opts.alias)for(i = 0, arr = opts.alias[k] = toArr(opts.alias[k]); i < arr.length; i++)(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
1907
+ for(i = opts.boolean.length; i-- > 0;)for(j = (arr = opts.alias[opts.boolean[i]] || []).length; j-- > 0;)opts.boolean.push(arr[j]);
1908
+ for(i = opts.string.length; i-- > 0;)for(j = (arr = opts.alias[opts.string[i]] || []).length; j-- > 0;)opts.string.push(arr[j]);
1909
+ if (defaults) {
1910
+ for(k in opts.default)if (name = typeof opts.default[k], arr = opts.alias[k] = opts.alias[k] || [], void 0 !== opts[name]) for(opts[name].push(k), i = 0; i < arr.length; i++)opts[name].push(arr[i]);
1911
+ }
1912
+ let keys = strict ? Object.keys(opts.alias) : [];
1913
+ for(i = 0; i < len; i++){
1914
+ if ('--' === (arg = args[i])) {
1915
+ out._ = out._.concat(args.slice(++i));
1916
+ break;
1917
+ }
1918
+ for(j = 0; j < arg.length && 45 === arg.charCodeAt(j); j++);
1919
+ if (0 === j) out._.push(arg);
1920
+ else if ('no-' === arg.substring(j, j + 3)) {
1921
+ if (name = arg.substring(j + 3), strict && !~keys.indexOf(name)) return opts.unknown(arg);
1922
+ out[name] = !1;
1923
+ } else {
1924
+ for(idx = j + 1; idx < arg.length && 61 !== arg.charCodeAt(idx); idx++);
1925
+ for(name = arg.substring(j, idx), val = arg.substring(++idx) || i + 1 === len || 45 === ('' + args[i + 1]).charCodeAt(0) || args[++i], arr = 2 === j ? [
1926
+ name
1927
+ ] : name, idx = 0; idx < arr.length; idx++){
1928
+ if (name = arr[idx], strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
1929
+ !function(out, key, val, opts) {
1930
+ var x, old = out[key], nxt = ~opts.string.indexOf(key) ? null == val || !0 === val ? '' : String(val) : 'boolean' == typeof val ? val : ~opts.boolean.indexOf(key) ? 'false' !== val && ('true' === val || (out._.push(0 * (x = +val) == 0 ? x : val), !!val)) : 0 * (x = +val) == 0 ? x : val;
1931
+ out[key] = null == old ? nxt : Array.isArray(old) ? old.concat(nxt) : [
1932
+ old,
1933
+ nxt
1934
+ ];
1935
+ }(out, name, idx + 1 < arr.length || val, opts);
1936
+ }
1937
+ }
1938
+ }
1939
+ if (defaults) for(k in opts.default)void 0 === out[k] && (out[k] = opts.default[k]);
1940
+ if (alibi) for(k in out)for(arr = opts.alias[k] || []; arr.length > 0;)out[arr.shift()] = out[k];
1941
+ return out;
1942
+ }(argv, mriOptions), args = (parsed = Object.keys(parsed).reduce((res, name)=>__assign(__assign({}, res), {
1943
+ [camelcaseOptionName(name)]: parsed[name]
1944
+ }), {
1945
+ _: []
1946
+ }))._, options = {
1947
+ "--": argsAfterDoubleDashes
1948
+ }, ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue, transforms = Object.create(null);
1949
+ for (let cliOption of cliOptions){
1950
+ if (!ignoreDefault && void 0 !== cliOption.config.default) for (let name of cliOption.names)options[name] = cliOption.config.default;
1951
+ Array.isArray(cliOption.config.type) && void 0 === transforms[cliOption.name] && (transforms[cliOption.name] = Object.create(null), transforms[cliOption.name].shouldTransform = !0, transforms[cliOption.name].transformFunction = cliOption.config.type[0]);
1952
+ }
1953
+ for (let key of Object.keys(parsed))"_" !== key && (setDotProp(options, key.split("."), parsed[key]), setByType(options, transforms));
1954
+ return {
1955
+ args,
1956
+ options
1957
+ };
2156
1958
  }
2157
- constructor(parent){
2158
- super(parent), this.rules = new ChainedMap(this), this.defaultRules = new ChainedMap(this), this.generator = new ChainedMap(this), this.parser = new ChainedMap(this), this.extend([
2159
- 'noParse',
2160
- 'unsafeCache',
2161
- 'wrappedContextCritical',
2162
- 'exprContextRegExp',
2163
- 'wrappedContextRecursive',
2164
- 'strictExportPresence',
2165
- 'wrappedContextRegExp'
2166
- ]);
1959
+ runMatchedCommand() {
1960
+ let { args, options, matchedCommand: command } = this;
1961
+ if (!command || !command.commandAction) return;
1962
+ command.checkUnknownOptions(), command.checkOptionValue(), command.checkRequiredArgs();
1963
+ let actionArgs = [];
1964
+ return command.args.forEach((arg, index)=>{
1965
+ arg.variadic ? actionArgs.push(args.slice(index)) : actionArgs.push(args[index]);
1966
+ }), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
2167
1967
  }
2168
1968
  }
2169
- class Optimization_class extends ChainedMap {
2170
- minimizer(name) {
2171
- if (Array.isArray(name)) throw Error("optimization.minimizer() no longer supports being passed an array. Either switch to the new syntax (https://github.com/neutrinojs/webpack-chain#config-optimization-minimizers-adding) or downgrade to webpack-chain 4. If using Vue this likely means a Vue plugin has not yet been updated to support Vue CLI 4+.");
2172
- return this.minimizers.getOrCompute(name, ()=>new src_Plugin(this, name, 'optimization.minimizer'));
2173
- }
2174
- toConfig() {
2175
- return this.clean(Object.assign(this.entries() || {}, {
2176
- splitChunks: this.splitChunks.entries(),
2177
- minimizer: this.minimizers.values().map((plugin)=>plugin.toConfig())
2178
- }));
1969
+ var cjs = __webpack_require__("../../node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js"), cjs_default = __webpack_require__.n(cjs), javascript_stringify_dist = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/index.js");
1970
+ function createMap(superClass) {
1971
+ return class extends superClass {
1972
+ extend(methods) {
1973
+ return this.shorthands = methods, methods.forEach((method)=>{
1974
+ this[method] = (value)=>this.set(method, value);
1975
+ }), this;
1976
+ }
1977
+ clear() {
1978
+ return this.store.clear(), this;
1979
+ }
1980
+ delete(key) {
1981
+ return this.store.delete(key), this;
1982
+ }
1983
+ order() {
1984
+ let entries = [
1985
+ ...this.store
1986
+ ].reduce((acc, [key, value])=>(acc[key] = value, acc), {}), names = Object.keys(entries), order = [
1987
+ ...names
1988
+ ];
1989
+ return names.forEach((name)=>{
1990
+ if (!entries[name]) return;
1991
+ let { __before, __after } = entries[name];
1992
+ __before && order.includes(__before) ? (order.splice(order.indexOf(name), 1), order.splice(order.indexOf(__before), 0, name)) : __after && order.includes(__after) && (order.splice(order.indexOf(name), 1), order.splice(order.indexOf(__after) + 1, 0, name));
1993
+ }), {
1994
+ entries,
1995
+ order
1996
+ };
1997
+ }
1998
+ entries() {
1999
+ let { entries, order } = this.order();
2000
+ if (order.length) return entries;
2001
+ }
2002
+ values() {
2003
+ let { entries, order } = this.order();
2004
+ return order.map((name)=>entries[name]);
2005
+ }
2006
+ get(key) {
2007
+ return this.store.get(key);
2008
+ }
2009
+ getOrCompute(key, fn) {
2010
+ return this.has(key) || this.set(key, fn()), this.get(key);
2011
+ }
2012
+ has(key) {
2013
+ return this.store.has(key);
2014
+ }
2015
+ set(key, value) {
2016
+ return this.store.set(key, value), this;
2017
+ }
2018
+ merge(obj, omit = []) {
2019
+ return Object.keys(obj).forEach((key)=>{
2020
+ if (omit.includes(key)) return;
2021
+ let value = obj[key];
2022
+ (Array.isArray(value) || 'object' == typeof value) && null !== value && this.has(key) ? this.set(key, cjs(this.get(key), value)) : this.set(key, value);
2023
+ }), this;
2024
+ }
2025
+ clean(obj) {
2026
+ return Object.keys(obj).reduce((acc, key)=>{
2027
+ let value = obj[key];
2028
+ return void 0 === value || Array.isArray(value) && !value.length || '[object Object]' === Object.prototype.toString.call(value) && !Object.keys(value).length || (acc[key] = value), acc;
2029
+ }, {});
2030
+ }
2031
+ when(condition, whenTruthy = Function.prototype, whenFalsy = Function.prototype) {
2032
+ return condition ? whenTruthy(this) : whenFalsy(this), this;
2033
+ }
2034
+ constructor(...args){
2035
+ super(...args), this.store = new Map();
2036
+ }
2037
+ };
2038
+ }
2039
+ function createChainable(superClass) {
2040
+ return class extends superClass {
2041
+ batch(handler) {
2042
+ return handler(this), this;
2043
+ }
2044
+ end() {
2045
+ return this.parent;
2046
+ }
2047
+ constructor(parent){
2048
+ super(), this.parent = parent;
2049
+ }
2050
+ };
2051
+ }
2052
+ let ChainedMap = createMap(createChainable(Object)), ChainedValueMap = (superClass = createMap(createChainable(class extends Function {
2053
+ classCall() {
2054
+ throw Error('not implemented');
2179
2055
  }
2180
- merge(obj, omit = []) {
2181
- return !omit.includes('minimizer') && 'minimizer' in obj && Object.keys(obj.minimizer).forEach((name)=>this.minimizer(name).merge(obj.minimizer[name])), super.merge(obj, [
2182
- ...omit,
2183
- 'minimizer'
2184
- ]);
2056
+ constructor(){
2057
+ return super(), new Proxy(this, {
2058
+ apply: (target, thisArg, args)=>target.classCall(...args)
2059
+ });
2185
2060
  }
2186
- constructor(parent){
2187
- super(parent), this.minimizers = new ChainedMap(this), this.splitChunks = new ChainedValueMap(this), this.extend([
2188
- 'minimize',
2189
- 'runtimeChunk',
2190
- 'emitOnErrors',
2191
- 'moduleIds',
2192
- 'chunkIds',
2193
- 'nodeEnv',
2194
- 'mangleWasmImports',
2195
- 'removeAvailableModules',
2196
- 'removeEmptyChunks',
2197
- 'mergeDuplicateChunks',
2198
- 'flagIncludedChunks',
2199
- 'providedExports',
2200
- 'usedExports',
2201
- 'concatenateModules',
2202
- 'sideEffects',
2203
- 'portableRecords',
2204
- 'mangleExports',
2205
- 'innerGraph',
2206
- 'realContentHash',
2207
- 'avoidEntryIife'
2208
- ]);
2061
+ })), class extends superClass {
2062
+ set(...args) {
2063
+ return this.useMap = !0, this.value = void 0, super.set(...args);
2209
2064
  }
2210
- }
2211
- class Performance_class extends ChainedValueMap {
2212
- constructor(parent){
2213
- super(parent), this.extend([
2214
- 'assetFilter',
2215
- 'hints',
2216
- 'maxAssetSize',
2217
- 'maxEntrypointSize'
2218
- ]);
2065
+ clear() {
2066
+ return this.value = void 0, super.clear();
2219
2067
  }
2220
- }
2221
- let castArray = (value)=>Array.isArray(value) ? value : [
2222
- value
2223
- ];
2224
- class src_class extends ChainedMap {
2225
- static toString(config, { verbose = !1, configPrefix = 'config' } = {}) {
2226
- return (0, dist.stringify)(config, (value, indent, stringify)=>{
2227
- if (value && value.__pluginName) {
2228
- let prefix = `/* ${configPrefix}.${value.__pluginType}('${value.__pluginName}') */\n`, constructorExpression = value.__pluginPath ? `(require(${stringify(value.__pluginPath)}))` : value.__pluginConstructorName;
2229
- if (constructorExpression) {
2230
- let args = stringify(value.__pluginArgs).slice(1, -1);
2231
- return `${prefix}new ${constructorExpression}(${args})`;
2232
- }
2233
- return prefix + stringify(value.__pluginArgs && value.__pluginArgs.length ? {
2234
- args: value.__pluginArgs
2235
- } : {});
2236
- }
2237
- if (value && value.__ruleNames) {
2238
- let ruleTypes = value.__ruleTypes;
2239
- return `/* ${configPrefix}.module${value.__ruleNames.map((r, index)=>`.${ruleTypes ? ruleTypes[index] : 'rule'}('${r}')`).join('')}${value.__useName ? `.use('${value.__useName}')` : ""} */\n` + stringify(value);
2240
- }
2241
- return value && value.__expression ? value.__expression : 'function' == typeof value && !verbose && value.toString().length > 100 ? "function () { /* omitted long function */ }" : stringify(value);
2242
- }, 2);
2068
+ classCall(value) {
2069
+ return this.clear(), this.useMap = !1, this.value = value, this.parent;
2243
2070
  }
2244
- entry(name) {
2245
- return this.entryPoints.getOrCompute(name, ()=>new ChainedSet(this));
2071
+ entries() {
2072
+ return this.useMap ? super.entries() : this.value;
2246
2073
  }
2247
- plugin(name) {
2248
- return this.plugins.getOrCompute(name, ()=>new src_Plugin(this, name));
2074
+ values() {
2075
+ return this.useMap ? super.values() : this.value;
2249
2076
  }
2250
- toConfig() {
2251
- let entryPoints = this.entryPoints.entries() || {}, baseConfig = this.entries() || {};
2252
- return this.clean(Object.assign(baseConfig, {
2253
- node: this.node.entries(),
2254
- output: this.output.entries(),
2255
- resolve: this.resolve.toConfig(),
2256
- resolveLoader: this.resolveLoader.toConfig(),
2257
- devServer: this.devServer.toConfig(),
2258
- module: this.module.toConfig(),
2259
- optimization: this.optimization.toConfig(),
2260
- plugins: this.plugins.values().map((plugin)=>plugin.toConfig()),
2261
- performance: this.performance.entries(),
2262
- entry: ((entryPoints)=>{
2263
- let entry = Object.keys(entryPoints).reduce((acc, key)=>Object.assign(acc, {
2264
- [key]: entryPoints[key].values()
2265
- }), {}), formattedEntry = {};
2266
- for (let [entryName, entryValue] of Object.entries(entry)){
2267
- let entryImport = [], entryDescription = null;
2268
- for (let item of castArray(entryValue)){
2269
- if ('string' == typeof item) {
2270
- entryImport.push(item);
2271
- continue;
2272
- }
2273
- item.import && entryImport.push(...castArray(item.import)), entryDescription ? Object.assign(entryDescription, item) : entryDescription = item;
2274
- }
2275
- formattedEntry[entryName] = entryDescription ? {
2276
- ...entryDescription,
2277
- import: entryImport
2278
- } : entryImport;
2279
- }
2280
- return formattedEntry;
2281
- })(entryPoints)
2282
- }));
2077
+ constructor(...args){
2078
+ super(...args), this.value = void 0, this.useMap = !0;
2283
2079
  }
2284
- toString(options) {
2285
- return this.constructor.toString(this.toConfig(), options);
2080
+ }), ChainedSet = (superClass1 = createChainable(Object), class extends superClass1 {
2081
+ add(value) {
2082
+ return this.store.add(value), this;
2286
2083
  }
2287
- merge(obj = {}, omit = []) {
2288
- let omissions = [
2289
- 'node',
2290
- 'output',
2291
- 'resolve',
2292
- 'resolveLoader',
2293
- 'devServer',
2294
- 'optimization',
2295
- 'performance',
2296
- 'module'
2084
+ prepend(value) {
2085
+ return this.store = new Set([
2086
+ value,
2087
+ ...this.store
2088
+ ]), this;
2089
+ }
2090
+ clear() {
2091
+ return this.store.clear(), this;
2092
+ }
2093
+ delete(value) {
2094
+ return this.store.delete(value), this;
2095
+ }
2096
+ values() {
2097
+ return [
2098
+ ...this.store
2297
2099
  ];
2298
- return !omit.includes('entry') && 'entry' in obj && Object.keys(obj.entry).forEach((name)=>this.entry(name).merge([].concat(obj.entry[name]))), !omit.includes('plugin') && 'plugin' in obj && Object.keys(obj.plugin).forEach((name)=>this.plugin(name).merge(obj.plugin[name])), omissions.forEach((key)=>{
2299
- !omit.includes(key) && key in obj && this[key].merge(obj[key]);
2300
- }), super.merge(obj, [
2301
- ...omit,
2302
- ...omissions,
2303
- 'entry',
2304
- 'plugin'
2305
- ]);
2306
2100
  }
2307
- constructor(){
2308
- super(), this.entryPoints = new ChainedMap(this), this.output = new Output_class(this), this.module = new Module_class(this), this.resolve = new Resolve_class(this), this.resolveLoader = new ResolveLoader_class(this), this.optimization = new Optimization_class(this), this.plugins = new ChainedMap(this), this.devServer = new DevServer_class(this), this.performance = new Performance_class(this), this.node = new ChainedValueMap(this), this.extend([
2309
- 'context',
2310
- 'mode',
2311
- 'devtool',
2312
- 'target',
2313
- 'watch',
2314
- 'watchOptions',
2315
- 'externals',
2316
- 'externalsType',
2317
- 'externalsPresets',
2318
- 'stats',
2319
- 'experiments',
2320
- 'amd',
2321
- 'bail',
2322
- 'cache',
2323
- 'dependencies',
2324
- 'ignoreWarnings',
2325
- 'loader',
2326
- 'parallelism',
2327
- 'profile',
2328
- 'recordsPath',
2329
- 'recordsInputPath',
2330
- 'recordsOutputPath',
2331
- 'name',
2332
- 'infrastructureLogging',
2333
- 'snapshot',
2334
- 'lazyCompilation'
2335
- ]);
2101
+ has(value) {
2102
+ return this.store.has(value);
2336
2103
  }
2337
- }
2338
- let constants_filename = (0, external_node_url_.fileURLToPath)(import.meta.url), constants_dirname = (0, external_node_path_.dirname)(constants_filename), isDeno = 'undefined' != typeof Deno, ROOT_DIST_DIR = 'dist', LOADER_PATH = (0, external_node_path_.join)(constants_dirname), STATIC_PATH = (0, external_node_path_.join)(constants_dirname, '../static'), COMPILED_PATH = (0, external_node_path_.join)(constants_dirname, '../compiled'), RSBUILD_OUTPUTS_PATH = '.rsbuild', DEFAULT_DEV_HOST = '0.0.0.0', DEFAULT_ASSET_PREFIX = '/', DEFAULT_WEB_BROWSERSLIST = [
2339
- 'chrome >= 87',
2340
- 'edge >= 88',
2341
- 'firefox >= 78',
2342
- 'safari >= 14'
2343
- ], DEFAULT_BROWSERSLIST = {
2344
- web: DEFAULT_WEB_BROWSERSLIST,
2345
- 'web-worker': DEFAULT_WEB_BROWSERSLIST,
2346
- node: [
2347
- 'node >= 16'
2348
- ]
2349
- }, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, RAW_QUERY_REGEX = /[?&]raw(?:&|=|$)/, INLINE_QUERY_REGEX = /[?&]inline(?:&|=|$)/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
2350
- 'woff',
2351
- 'woff2',
2352
- 'eot',
2353
- 'ttf',
2354
- 'otf',
2355
- 'ttc'
2356
- ], IMAGE_EXTENSIONS = [
2357
- 'png',
2358
- 'jpg',
2359
- 'jpeg',
2360
- 'pjpeg',
2361
- 'pjp',
2362
- 'gif',
2363
- 'bmp',
2364
- 'webp',
2365
- 'ico',
2366
- 'apng',
2367
- 'avif',
2368
- 'tif',
2369
- 'tiff',
2370
- 'jfif',
2371
- 'cur'
2372
- ], VIDEO_EXTENSIONS = [
2373
- 'mp4',
2374
- 'webm',
2375
- 'ogg',
2376
- 'mov'
2377
- ], AUDIO_EXTENSIONS = [
2378
- 'mp3',
2379
- 'wav',
2380
- 'flac',
2381
- 'aac',
2382
- 'm4a',
2383
- 'opus'
2384
- ];
2385
- function getCommonParentPath(paths) {
2386
- let uniquePaths = [
2387
- ...new Set(paths)
2388
- ];
2389
- if (1 === uniquePaths.length) return uniquePaths[0];
2390
- let [first, ...rest] = uniquePaths.map((p)=>p.split(external_node_path_.sep)), common = [];
2391
- for(let i = 0; i < first.length; i++){
2392
- let segment = first[i];
2393
- if (rest.every((p)=>p[i] === segment)) common.push(segment);
2394
- else break;
2104
+ merge(arr) {
2105
+ return void 0 !== arr && (this.store = new Set([
2106
+ ...this.store,
2107
+ ...arr
2108
+ ])), this;
2395
2109
  }
2396
- return common.join(external_node_path_.sep);
2397
- }
2398
- let getCompiledPath = (packageName)=>(0, external_node_path_.join)(COMPILED_PATH, packageName, 'index.js'), ensureAbsolutePath = (base, filePath)=>(0, external_node_path_.isAbsolute)(filePath) ? filePath : (0, external_node_path_.join)(base, filePath), getPathnameFromUrl = (publicPath)=>{
2399
- try {
2400
- return publicPath ? new URL(publicPath).pathname : publicPath;
2401
- } catch {
2402
- return publicPath;
2110
+ when(condition, whenTruthy = Function.prototype, whenFalsy = Function.prototype) {
2111
+ return condition ? whenTruthy(this) : whenFalsy(this), this;
2403
2112
  }
2404
- }, dedupeNestedPaths = (paths)=>paths.sort((p1, p2)=>p2.length > p1.length ? -1 : 1).reduce((prev, curr)=>prev.find((p)=>curr.startsWith(p) || curr === p) ? prev : prev.concat(curr), []), toPosixPath = (filepath)=>'/' === external_node_path_.sep ? filepath : filepath.replace(/\\/g, '/'), isFileSync = (filePath)=>{
2405
- try {
2406
- return node_fs.statSync(filePath, {
2407
- throwIfNoEntry: !1
2408
- })?.isFile();
2409
- } catch (_) {
2410
- return !1;
2113
+ constructor(...args){
2114
+ super(...args), this.store = new Set();
2115
+ }
2116
+ }), Orderable = (Class)=>class extends Class {
2117
+ before(name) {
2118
+ if (this.__after) throw Error(`Unable to set .before(${JSON.stringify(name)}) with existing value for .after()`);
2119
+ return this.__before = name, this;
2120
+ }
2121
+ after(name) {
2122
+ if (this.__before) throw Error(`Unable to set .after(${JSON.stringify(name)}) with existing value for .before()`);
2123
+ return this.__after = name, this;
2124
+ }
2125
+ merge(obj, omit = []) {
2126
+ return obj.before && this.before(obj.before), obj.after && this.after(obj.after), super.merge(obj, [
2127
+ ...omit,
2128
+ 'before',
2129
+ 'after'
2130
+ ]);
2131
+ }
2132
+ }, src_Plugin = Orderable(class extends ChainedMap {
2133
+ use(plugin, args = []) {
2134
+ return this.set('plugin', plugin).set('args', args);
2135
+ }
2136
+ tap(f) {
2137
+ if (!this.has('plugin')) throw Error(`Cannot call .tap() on a plugin that has not yet been defined. Call ${this.type}('${this.name}').use(<Plugin>) first.`);
2138
+ return this.set('args', f(this.get('args') || [])), this;
2139
+ }
2140
+ set(key, value) {
2141
+ if ('args' === key && !Array.isArray(value)) throw Error('args must be an array of arguments');
2142
+ return super.set(key, value);
2411
2143
  }
2412
- }, findExists = (files)=>{
2413
- for (let file of files)if (isFileSync(file)) return file;
2414
- return !1;
2415
- };
2416
- async function pathExists(path) {
2417
- return node_fs.promises.access(path).then(()=>!0).catch(()=>!1);
2418
- }
2419
- async function isFileExists(file) {
2420
- return node_fs.promises.access(file, node_fs.constants.F_OK).then(()=>!0).catch(()=>!1);
2421
- }
2422
- async function fileExistsByCompilation({ inputFileSystem }, filePath) {
2423
- return new Promise((resolve)=>{
2424
- inputFileSystem ? inputFileSystem.stat(filePath, (err, stats)=>{
2425
- err ? resolve(!1) : resolve(!!stats?.isFile());
2426
- }) : resolve(!1);
2427
- });
2428
- }
2429
- async function emptyDir(dir, keep = [], checkExists = !0) {
2430
- if (!checkExists || await pathExists(dir)) try {
2431
- let entries = await node_fs.promises.readdir(dir, {
2432
- withFileTypes: !0
2433
- });
2434
- await Promise.all(entries.map(async (entry)=>{
2435
- let fullPath = external_node_path_.default.join(dir, entry.name);
2436
- !keep.some((reg)=>reg.test(toPosixPath(fullPath))) && (entry.isDirectory() ? (await emptyDir(fullPath, keep, !1), keep.length || await node_fs.promises.rmdir(fullPath)) : await node_fs.promises.unlink(fullPath));
2437
- }));
2438
- } catch (err) {
2439
- logger.debug(`failed to empty dir: ${dir}`), logger.debug(err);
2144
+ merge(obj, omit = []) {
2145
+ return 'plugin' in obj && this.set('plugin', obj.plugin), 'args' in obj && this.set('args', obj.args), super.merge(obj, [
2146
+ ...omit,
2147
+ 'args',
2148
+ 'plugin'
2149
+ ]);
2440
2150
  }
2441
- }
2442
- let formatFileName = (fileName)=>/:\d+:\d+/.test(fileName) ? `File: ${picocolors.cyan(fileName)}\n` : `File: ${picocolors.cyan(`${fileName}:1:1`)}\n`;
2443
- function formatMessage(stats, verbose) {
2444
- let message;
2445
- if ('object' == typeof stats) {
2446
- let fileName = function(stats) {
2447
- let file = stats.file || stats.moduleName;
2448
- if (file) return formatFileName(file);
2449
- if (stats.moduleIdentifier) {
2450
- let matched = stats.moduleIdentifier.match(/(?:!|^)([^!]+)$/);
2451
- if (matched) {
2452
- let fileName = matched.pop();
2453
- if (fileName) return formatFileName(fileName);
2454
- }
2455
- }
2456
- return '';
2457
- }(stats), mainMessage = stats.message, details = verbose && stats.details ? `\nDetails: ${stats.details}\n` : '', stack = verbose && stats.stack ? `\n${stats.stack}` : '', moduleTrace = function(stats) {
2458
- let traceStr = '';
2459
- if (stats.moduleTrace) for (let trace of stats.moduleTrace)trace.originName && (traceStr += `\n @ ${trace.originName}`);
2460
- return traceStr;
2461
- }(stats);
2462
- message = `${fileName}${mainMessage}${details}${stack}${moduleTrace}`;
2463
- } else message = stats;
2464
- let innerError = '-- inner error --';
2465
- return !verbose && message.includes(innerError) && (message = message.split(innerError)[0]), (message = (message = ((message)=>{
2466
- let getTips = (moduleName)=>{
2467
- let tips = [
2468
- `Error: "${moduleName}" is a built-in Node.js module and cannot be imported in client-side code.\n`,
2469
- 'Solution: Check if you need to import Node.js module.',
2470
- ' - If not needed, remove the import.',
2471
- ` - If needed, use "${picocolors.yellow('@rsbuild/plugin-node-polyfill')}" to polyfill it. (See ${picocolors.yellow('https://npmjs.com/package/@rsbuild/plugin-node-polyfill')})`
2472
- ];
2473
- return `${message}\n\n${picocolors.red(tips.join('\n'))}`;
2474
- };
2475
- if (message.includes('need an additional plugin to handle "node:" URIs')) return getTips('node:*');
2476
- if (!message.includes("Can't resolve")) return message;
2477
- let matchArray = message.match(/Can't resolve '(\w+)'/);
2478
- if (!matchArray) return message;
2479
- let moduleName = matchArray[1];
2480
- return moduleName && [
2481
- 'assert',
2482
- 'buffer',
2483
- 'child_process',
2484
- 'cluster',
2485
- 'console',
2486
- 'constants',
2487
- 'crypto',
2488
- 'dgram',
2489
- 'dns',
2490
- 'domain',
2491
- 'events',
2492
- 'fs',
2493
- 'http',
2494
- 'https',
2495
- 'module',
2496
- 'net',
2497
- 'os',
2498
- 'path',
2499
- 'punycode',
2500
- 'process',
2501
- 'querystring',
2502
- 'readline',
2503
- 'repl',
2504
- 'stream',
2505
- '_stream_duplex',
2506
- '_stream_passthrough',
2507
- '_stream_readable',
2508
- '_stream_transform',
2509
- '_stream_writable',
2510
- 'string_decoder',
2511
- 'sys',
2512
- 'timers',
2513
- 'tls',
2514
- 'tty',
2515
- 'url',
2516
- 'util',
2517
- 'vm',
2518
- 'zlib'
2519
- ].includes(moduleName) ? getTips(moduleName) : message;
2520
- })(message = function(message) {
2521
- let hint = 'You may need an appropriate loader to handle this file type.';
2522
- if (-1 === message.indexOf(hint)) return message;
2523
- let createPluginHint = (packageName, keyword)=>`To enable support for ${keyword}, use "${picocolors.yellow(`@rsbuild/plugin-${packageName}`)}" ${picocolors.dim(`(https://npmjs.com/package/@rsbuild/plugin-${packageName})`)}.`;
2524
- for (let plugin of [
2525
- {
2526
- test: /File: .+\.s(c|a)ss/,
2527
- hint: createPluginHint('sass', 'Sass')
2528
- },
2529
- {
2530
- test: /File: .+\.less/,
2531
- hint: createPluginHint('less', 'Less')
2532
- },
2533
- {
2534
- test: /File: .+\.styl(us)?/,
2535
- hint: createPluginHint('stylus', 'Stylus')
2536
- },
2537
- {
2538
- test: /File: .+\.vue?/,
2539
- hint: createPluginHint('vue', 'Vue')
2151
+ toConfig() {
2152
+ let init = this.get('init'), plugin = this.get('plugin'), args = this.get('args'), pluginPath = null;
2153
+ if (void 0 === plugin) throw Error(`Invalid ${this.type} configuration: ${this.type}('${this.name}').use(<Plugin>) was not called to specify the plugin`);
2154
+ 'string' == typeof plugin && (plugin = require(pluginPath = plugin));
2155
+ let constructorName = plugin.__expression ? `(${plugin.__expression})` : plugin.name, config = init(plugin, args);
2156
+ return Object.defineProperties(config, {
2157
+ __pluginName: {
2158
+ value: this.name
2540
2159
  },
2541
- {
2542
- test: /File: .+\.svelte?/,
2543
- hint: createPluginHint('svelte', 'Svelte')
2160
+ __pluginType: {
2161
+ value: this.type
2544
2162
  },
2545
- {
2546
- test: /File: .+\.mdx/,
2547
- hint: createPluginHint('mdx', 'MDX')
2163
+ __pluginArgs: {
2164
+ value: args
2548
2165
  },
2549
- {
2550
- test: /File: .+\.toml/,
2551
- hint: createPluginHint('toml', 'TOML')
2166
+ __pluginConstructorName: {
2167
+ value: constructorName
2552
2168
  },
2553
- {
2554
- test: /File: .+\.yaml/,
2555
- hint: createPluginHint('yaml', 'YAML')
2169
+ __pluginPath: {
2170
+ value: pluginPath
2556
2171
  }
2557
- ])if (plugin.test.test(message)) return message.replace(hint, plugin.hint);
2558
- return message;
2559
- }(message))).split('\n').filter((line, index, arr)=>0 === index || '' !== line.trim() || line.trim() !== arr[index - 1].trim()).join('\n')).trim();
2560
- }
2561
- function formatStatsMessages(stats, verbose) {
2562
- return {
2563
- errors: stats.errors?.map((error)=>formatMessage(error, verbose)) || [],
2564
- warnings: stats.warnings?.map((warning)=>formatMessage(warning, verbose)) || []
2565
- };
2566
- }
2567
- let getAllStatsErrors = (statsData)=>statsData.errorsCount && statsData.errors?.length === 0 ? statsData.children?.reduce((errors, curr)=>errors.concat(curr.errors || []), []) : statsData.errors, getAssetsFromStats = (stats)=>stats.toJson({
2568
- all: !1,
2569
- assets: !0,
2570
- cachedAssets: !0,
2571
- groupAssetsByInfo: !1,
2572
- groupAssetsByPath: !1,
2573
- groupAssetsByChunk: !1,
2574
- groupAssetsByExtension: !1,
2575
- groupAssetsByEmitStatus: !1
2576
- }).assets || [], getAllStatsWarnings = (statsData)=>statsData.warningsCount && statsData.warnings?.length === 0 ? statsData.children?.reduce((warnings, curr)=>warnings.concat(curr.warnings || []), []) : statsData.warnings;
2577
- function getStatsOptions(compiler) {
2578
- if (helpers_isMultiCompiler(compiler)) return {
2579
- children: compiler.compilers.map((compiler)=>compiler.options ? compiler.options.stats : void 0)
2580
- };
2581
- let { stats } = compiler.options;
2582
- return 'string' == typeof stats ? {
2583
- preset: stats
2584
- } : 'object' == typeof stats ? stats : {};
2585
- }
2586
- function formatStats(statsData, hasErrors) {
2587
- let verbose = 'verbose' === logger.level;
2588
- if (hasErrors) {
2589
- let { errors } = formatStatsMessages({
2590
- errors: getAllStatsErrors(statsData),
2591
- warnings: []
2592
- }, verbose);
2593
- return {
2594
- message: function(errors) {
2595
- let title = picocolors.bold(picocolors.red(errors.length > 1 ? 'Build errors: ' : 'Build error: '));
2596
- if (!errors.length) return `${title}\n${picocolors.yellow("For more details, please set 'stats.errors: true' ")}`;
2597
- let text = `${errors.join('\n\n')}\n`;
2598
- return `${title}\n${text}`;
2599
- }(errors),
2600
- level: 'error'
2601
- };
2172
+ }), config;
2602
2173
  }
2603
- let { warnings } = formatStatsMessages({
2604
- errors: [],
2605
- warnings: getAllStatsWarnings(statsData)
2606
- }, verbose);
2607
- if (warnings.length) {
2608
- let title = picocolors.bold(picocolors.yellow(warnings.length > 1 ? 'Build warnings: \n' : 'Build warning: \n'));
2609
- return {
2610
- message: `${title}${warnings.join('\n\n')}\n`,
2611
- level: 'warning'
2612
- };
2174
+ constructor(parent, name, type = 'plugin'){
2175
+ super(parent), this.name = name, this.type = type, this.extend([
2176
+ 'init'
2177
+ ]), this.init((Plugin, args = [])=>'function' == typeof Plugin ? new Plugin(...args) : Plugin);
2613
2178
  }
2614
- return {};
2615
- }
2616
- let rspackMinVersion = '1.5.0', setNodeEnv = (env)=>{
2617
- process.env.NODE_ENV = env;
2618
- }, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), objectPrototype = Object.prototype, isPlainObject = (obj)=>null !== obj && 'object' == typeof obj && Object.getPrototypeOf(obj) === objectPrototype, helpers_castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
2619
- arr
2620
- ], cloneDeep = (value)=>null == value ? value : cjs_default()({}, value, {
2621
- isMergeableObject: isPlainObject
2622
- }), addTrailingSlash = (s)=>s.endsWith('/') ? s : `${s}/`, formatPublicPath = (publicPath, withSlash = !0)=>'auto' === publicPath ? publicPath : withSlash ? addTrailingSlash(publicPath) : publicPath.replace(/\/+$/, ''), getPublicPathFromChain = (chain, withSlash = !0)=>{
2623
- let publicPath = chain.output.get('publicPath');
2624
- return 'string' == typeof publicPath ? formatPublicPath(publicPath, withSlash) : formatPublicPath(DEFAULT_ASSET_PREFIX, withSlash);
2625
- }, getPublicPathFromCompiler = (compiler)=>{
2626
- let { publicPath } = compiler.options.output;
2627
- return 'string' == typeof publicPath ? 'auto' === publicPath ? '' : publicPath.endsWith('/') ? publicPath : `${publicPath}/` : DEFAULT_ASSET_PREFIX;
2628
- }, urlJoin = (base, path)=>{
2629
- let [urlProtocol, baseUrl] = base.split('://');
2630
- return `${urlProtocol}://${external_node_path_.posix.join(baseUrl, path)}`;
2631
- }, canParse = (url)=>{
2632
- try {
2633
- return new external_node_url_.URL(url), !0;
2634
- } catch {
2635
- return !1;
2179
+ }), childMaps = [
2180
+ 'alias',
2181
+ 'fallback',
2182
+ 'byDependency',
2183
+ 'extensionAlias'
2184
+ ], childSets = [
2185
+ 'aliasFields',
2186
+ 'conditionNames',
2187
+ "descriptionFiles",
2188
+ 'extensions',
2189
+ 'mainFields',
2190
+ 'mainFiles',
2191
+ 'exportsFields',
2192
+ 'importsFields',
2193
+ 'restrictions',
2194
+ 'roots',
2195
+ 'modules'
2196
+ ];
2197
+ class Resolve_class extends ChainedMap {
2198
+ plugin(name) {
2199
+ return this.plugins.getOrCompute(name, ()=>new src_Plugin(this, name, 'resolve.plugin'));
2636
2200
  }
2637
- }, ensureAssetPrefix = (url, assetPrefix = DEFAULT_ASSET_PREFIX)=>url.startsWith('//') || canParse(url) || 'auto' === assetPrefix || 'function' == typeof assetPrefix ? url : assetPrefix.startsWith('http') ? urlJoin(assetPrefix, url) : assetPrefix.startsWith('//') ? urlJoin(`https:${assetPrefix}`, url).replace('https:', '') : external_node_path_.posix.join(assetPrefix, url);
2638
- function getFilename(config, type, isProd, isServer) {
2639
- let { filename, filenameHash } = config.output, defaultHash = '[contenthash:8]', getHash = ()=>'string' == typeof filenameHash ? filenameHash ? `.[${filenameHash}]` : '' : filenameHash ? `.${defaultHash}` : '';
2640
- switch(type){
2641
- case 'js':
2642
- return filename.js ?? `[name]${isProd && !isServer ? getHash() : ''}.js`;
2643
- case 'css':
2644
- return filename.css ?? `[name]${isProd ? getHash() : ''}.css`;
2645
- case 'svg':
2646
- return filename.svg ?? `[name]${getHash()}.svg`;
2647
- case 'font':
2648
- return filename.font ?? `[name]${getHash()}[ext]`;
2649
- case 'image':
2650
- return filename.image ?? `[name]${getHash()}[ext]`;
2651
- case 'media':
2652
- return filename.media ?? `[name]${getHash()}[ext]`;
2653
- case 'assets':
2654
- return filename.assets ?? `[name]${getHash()}[ext]`;
2655
- case 'wasm':
2656
- {
2657
- let hash = 'string' == typeof filenameHash ? `[${filenameHash}]` : defaultHash;
2658
- return filename.wasm ?? `${hash}.module.wasm`;
2659
- }
2660
- case 'html':
2661
- if (filename.html) return filename.html;
2662
- return 'flat' === config.html.outputStructure ? '[name].html' : '[name]/index.html';
2663
- default:
2664
- throw Error(`${picocolors.dim('[rsbuild:config]')} unknown key ${picocolors.yellow(type)} in ${picocolors.yellow('output.filename')}`);
2201
+ get(key) {
2202
+ return childMaps.includes(key) ? this[key].entries() : childSets.includes(key) ? this[key].values() : super.get(key);
2665
2203
  }
2666
- }
2667
- let applyToCompiler = (compiler, apply)=>{
2668
- helpers_isMultiCompiler(compiler) ? compiler.compilers.forEach(apply) : apply(compiler, 0);
2669
- }, upperFirst = (str)=>str ? str.charAt(0).toUpperCase() + str.slice(1) : '', isURL = (str)=>str.startsWith('http') || str.startsWith('//:'), createVirtualModule = (content)=>`data:text/javascript,${content}`, helpers_isMultiCompiler = (compiler)=>'compilers' in compiler && Array.isArray(compiler.compilers);
2670
- function pick(obj, keys) {
2671
- let result = {};
2672
- for (let key of keys)void 0 !== obj[key] && (result[key] = obj[key]);
2673
- return result;
2674
- }
2675
- let prettyTime = (seconds)=>{
2676
- let time, time1;
2677
- if (seconds < 10) {
2678
- let time, digits = seconds >= 0.01 ? 2 : 3;
2679
- return `${time = seconds.toFixed(digits), picocolors.bold(time)} s`;
2204
+ toConfig() {
2205
+ let config = Object.assign(this.entries() || {}, {
2206
+ plugins: this.plugins.values().map((plugin)=>plugin.toConfig())
2207
+ });
2208
+ return childMaps.forEach((key)=>{
2209
+ config[key] = this[key].entries();
2210
+ }), childSets.forEach((key)=>{
2211
+ config[key] = this[key].values();
2212
+ }), this.clean(config);
2213
+ }
2214
+ merge(obj, omit = []) {
2215
+ !omit.includes('plugin') && 'plugin' in obj && Object.keys(obj.plugin).forEach((name)=>this.plugin(name).merge(obj.plugin[name]));
2216
+ let omissions = [
2217
+ ...childMaps,
2218
+ ...childSets
2219
+ ];
2220
+ return omissions.forEach((key)=>{
2221
+ !omit.includes(key) && key in obj && this[key].merge(obj[key]);
2222
+ }), super.merge(obj, [
2223
+ ...omit,
2224
+ ...omissions,
2225
+ 'plugin'
2226
+ ]);
2680
2227
  }
2681
- if (seconds < 60) {
2682
- let time;
2683
- return `${time = seconds.toFixed(1), picocolors.bold(time)} s`;
2228
+ constructor(parent){
2229
+ super(parent), childMaps.forEach((key)=>{
2230
+ this[key] = new ChainedMap(this);
2231
+ }), childSets.forEach((key)=>{
2232
+ this[key] = new ChainedSet(this);
2233
+ }), this.plugins = new ChainedMap(this), this.extend([
2234
+ 'cachePredicate',
2235
+ 'cacheWithContext',
2236
+ 'enforceExtension',
2237
+ 'symlinks',
2238
+ 'unsafeCache',
2239
+ 'preferRelative',
2240
+ 'preferAbsolute',
2241
+ 'tsConfig'
2242
+ ]);
2684
2243
  }
2685
- let minutes = Math.floor(seconds / 60), minutesLabel = `${(time = minutes.toFixed(0), picocolors.bold(time))} m`, remainingSeconds = seconds % 60;
2686
- if (0 === remainingSeconds) return minutesLabel;
2687
- let secondsLabel = `${(time1 = remainingSeconds.toFixed(+(remainingSeconds % 1 != 0)), picocolors.bold(time1))} s`;
2688
- return `${minutesLabel} ${secondsLabel}`;
2689
- }, isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !process.env.CI, addCompilationError = (compilation, message)=>{
2690
- compilation.errors.push(new compilation.compiler.webpack.WebpackError(message));
2691
- };
2692
- async function helpers_hash(data) {
2693
- let crypto = await import("node:crypto");
2694
- return crypto.hash ? crypto.hash('sha256', data, 'hex').slice(0, 16) : crypto.createHash('sha256').update(data).digest('hex').slice(0, 16);
2695
- }
2696
- let isDebug = ()=>{
2697
- if (!process.env.DEBUG) return !1;
2698
- let values = process.env.DEBUG.toLocaleLowerCase().split(',');
2699
- return [
2700
- 'rsbuild',
2701
- 'builder',
2702
- '*'
2703
- ].some((key)=>values.includes(key));
2704
- };
2705
- function toArr(any) {
2706
- return null == any ? [] : Array.isArray(any) ? any : [
2707
- any
2708
- ];
2709
2244
  }
2710
- isDebug() && (logger.level = 'verbose'), logger.override({
2711
- debug: (message, ...args)=>{
2712
- let now, hours, minutes, seconds;
2713
- if ('verbose' !== logger.level) return;
2714
- let time = picocolors.gray((hours = String((now = new Date()).getHours()).padStart(2, '0'), minutes = String(now.getMinutes()).padStart(2, '0'), seconds = String(now.getSeconds()).padStart(2, '0'), `${hours}:${minutes}:${seconds}`));
2715
- console.log(` ${picocolors.magenta('rsbuild')} ${time} ${message}`, ...args);
2245
+ class ResolveLoader_class extends Resolve_class {
2246
+ toConfig() {
2247
+ return this.clean({
2248
+ modules: this.modules.values(),
2249
+ moduleExtensions: this.moduleExtensions.values(),
2250
+ packageMains: this.packageMains.values(),
2251
+ ...super.toConfig()
2252
+ });
2716
2253
  }
2717
- });
2718
- let removeBrackets = (v)=>v.replace(/[<[].+/, "").trim(), findLongest = (arr)=>arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0], padRight = (str, length)=>str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`, setDotProp = (obj, keys, val)=>{
2719
- let x, i = 0, length = keys.length, t = obj;
2720
- for(; i < length; ++i)x = t[keys[i]], t = t[keys[i]] = i === length - 1 ? val : null != x ? x : ~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
2721
- }, setByType = (obj, transforms)=>{
2722
- for (let key of Object.keys(transforms)){
2723
- let transform = transforms[key];
2724
- transform.shouldTransform && (obj[key] = Array.prototype.concat.call([], obj[key]), "function" == typeof transform.transformFunction && (obj[key] = obj[key].map(transform.transformFunction)));
2254
+ merge(obj, omit = []) {
2255
+ let omissions = [
2256
+ 'modules',
2257
+ 'moduleExtensions',
2258
+ 'packageMains'
2259
+ ];
2260
+ return omissions.forEach((key)=>{
2261
+ !omit.includes(key) && key in obj && this[key].merge(obj[key]);
2262
+ }), super.merge(obj, [
2263
+ ...omit,
2264
+ ...omissions
2265
+ ]);
2725
2266
  }
2726
- }, camelcaseOptionName = (name)=>name.split(".").map((v, i)=>0 === i ? v.replace(/([a-z])-([a-z])/g, (_, p1, p2)=>p1 + p2.toUpperCase()) : v).join(".");
2727
- class CACError extends Error {
2728
- constructor(message){
2729
- super(message), this.name = this.constructor.name, "function" == typeof Error.captureStackTrace ? Error.captureStackTrace(this, this.constructor) : this.stack = Error(message).stack;
2267
+ constructor(parent){
2268
+ super(parent), this.modules = new ChainedSet(this), this.moduleExtensions = new ChainedSet(this), this.packageMains = new ChainedSet(this);
2730
2269
  }
2731
2270
  }
2732
- class Option {
2733
- constructor(rawName, description, config){
2734
- this.rawName = rawName, this.description = description, this.config = Object.assign({}, config), rawName = rawName.replace(/\.\*/g, ""), this.negated = !1, this.names = removeBrackets(rawName).split(",").map((v)=>{
2735
- let name = v.trim().replace(/^-{1,2}/, "");
2736
- return name.startsWith("no-") && (this.negated = !0, name = name.replace(/^no-/, "")), camelcaseOptionName(name);
2737
- }).sort((a, b)=>a.length > b.length ? 1 : -1), this.name = this.names[this.names.length - 1], this.negated && null == this.config.default && (this.config.default = !0), rawName.includes("<") ? this.required = !0 : rawName.includes("[") ? this.required = !1 : this.isBoolean = !0;
2271
+ class Output_class extends ChainedMap {
2272
+ constructor(parent){
2273
+ super(parent), this.extend([
2274
+ 'auxiliaryComment',
2275
+ 'charset',
2276
+ 'chunkFilename',
2277
+ 'chunkLoadTimeout',
2278
+ 'chunkLoadingGlobal',
2279
+ 'chunkLoading',
2280
+ 'chunkFormat',
2281
+ 'enabledChunkLoadingTypes',
2282
+ 'crossOriginLoading',
2283
+ 'devtoolFallbackModuleFilenameTemplate',
2284
+ 'devtoolModuleFilenameTemplate',
2285
+ 'devtoolNamespace',
2286
+ 'filename',
2287
+ 'assetModuleFilename',
2288
+ 'globalObject',
2289
+ 'uniqueName',
2290
+ 'hashDigest',
2291
+ 'hashDigestLength',
2292
+ 'hashFunction',
2293
+ 'hashSalt',
2294
+ 'hotUpdateChunkFilename',
2295
+ 'hotUpdateGlobal',
2296
+ 'hotUpdateMainFilename',
2297
+ 'library',
2298
+ 'libraryExport',
2299
+ 'libraryTarget',
2300
+ 'importFunctionName',
2301
+ 'path',
2302
+ 'pathinfo',
2303
+ 'publicPath',
2304
+ "scriptType",
2305
+ 'sourceMapFilename',
2306
+ 'sourcePrefix',
2307
+ 'strictModuleErrorHandling',
2308
+ 'strictModuleExceptionHandling',
2309
+ 'umdNamedDefine',
2310
+ 'workerChunkLoading',
2311
+ 'enabledLibraryTypes',
2312
+ 'environment',
2313
+ 'compareBeforeEmit',
2314
+ 'wasmLoading',
2315
+ 'webassemblyModuleFilename',
2316
+ 'enabledWasmLoadingTypes',
2317
+ 'iife',
2318
+ 'module',
2319
+ 'clean'
2320
+ ]);
2738
2321
  }
2739
2322
  }
2740
- let processArgs = process.argv, platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
2741
- class Command {
2742
- constructor(rawName, description, config = {}, cli){
2743
- this.rawName = rawName, this.description = description, this.config = config, this.cli = cli, this.options = [], this.aliasNames = [], this.name = removeBrackets(rawName), this.args = ((v)=>{
2744
- let angledMatch, squareMatch, ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g, SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g, res = [], parse = (match)=>{
2745
- let variadic = !1, value = match[1];
2746
- return value.startsWith("...") && (value = value.slice(3), variadic = !0), {
2747
- required: match[0].startsWith("<"),
2748
- value,
2749
- variadic
2750
- };
2751
- };
2752
- for(; angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v);)res.push(parse(angledMatch));
2753
- for(; squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v);)res.push(parse(squareMatch));
2754
- return res;
2755
- })(rawName), this.examples = [];
2323
+ class DevServer_class extends ChainedMap {
2324
+ toConfig() {
2325
+ return this.clean({
2326
+ allowedHosts: this.allowedHosts.values(),
2327
+ ...this.entries() || {}
2328
+ });
2756
2329
  }
2757
- usage(text) {
2758
- return this.usageText = text, this;
2330
+ merge(obj, omit = []) {
2331
+ return !omit.includes('allowedHosts') && 'allowedHosts' in obj && this.allowedHosts.merge(obj.allowedHosts), super.merge(obj, [
2332
+ 'allowedHosts'
2333
+ ]);
2759
2334
  }
2760
- allowUnknownOptions() {
2761
- return this.config.allowUnknownOptions = !0, this;
2335
+ constructor(parent){
2336
+ super(parent), this.allowedHosts = new ChainedSet(this), this.extend([
2337
+ 'after',
2338
+ 'before',
2339
+ 'bonjour',
2340
+ 'clientLogLevel',
2341
+ 'compress',
2342
+ 'contentBase',
2343
+ 'contentBasePublicPath',
2344
+ 'disableHostCheck',
2345
+ 'filename',
2346
+ 'headers',
2347
+ 'historyApiFallback',
2348
+ 'host',
2349
+ 'hot',
2350
+ 'hotOnly',
2351
+ 'http2',
2352
+ 'https',
2353
+ 'index',
2354
+ 'injectClient',
2355
+ 'injectHot',
2356
+ 'inline',
2357
+ 'lazy',
2358
+ 'liveReload',
2359
+ 'mimeTypes',
2360
+ 'noInfo',
2361
+ 'onListening',
2362
+ 'open',
2363
+ 'openPage',
2364
+ 'overlay',
2365
+ 'pfx',
2366
+ 'pfxPassphrase',
2367
+ 'port',
2368
+ 'proxy',
2369
+ 'progress',
2370
+ 'public',
2371
+ 'publicPath',
2372
+ 'quiet',
2373
+ 'serveIndex',
2374
+ 'setup',
2375
+ 'socket',
2376
+ 'sockHost',
2377
+ 'sockPath',
2378
+ 'sockPort',
2379
+ 'staticOptions',
2380
+ 'stats',
2381
+ 'stdin',
2382
+ 'transportMode',
2383
+ 'useLocalIp',
2384
+ 'watchContentBase',
2385
+ 'watchOptions',
2386
+ 'writeToDisk'
2387
+ ]);
2762
2388
  }
2763
- ignoreOptionDefaultValue() {
2764
- return this.config.ignoreOptionDefaultValue = !0, this;
2389
+ }
2390
+ let Use = Orderable(class extends ChainedMap {
2391
+ tap(f) {
2392
+ return this.options(f(this.get('options'))), this;
2765
2393
  }
2766
- version(version, customFlags = "-v, --version") {
2767
- return this.versionNumber = version, this.option(customFlags, "Display version number"), this;
2394
+ merge(obj, omit = []) {
2395
+ return !omit.includes('loader') && 'loader' in obj && this.loader(obj.loader), !omit.includes('options') && 'options' in obj && this.options(cjs(this.store.get('options') || {}, obj.options)), super.merge(obj, [
2396
+ ...omit,
2397
+ 'loader',
2398
+ 'options'
2399
+ ]);
2400
+ }
2401
+ toConfig() {
2402
+ let config = this.clean(this.entries() || {});
2403
+ return Object.defineProperties(config, {
2404
+ __useName: {
2405
+ value: this.name
2406
+ },
2407
+ __ruleNames: {
2408
+ value: this.parent && this.parent.names
2409
+ },
2410
+ __ruleTypes: {
2411
+ value: this.parent && this.parent.ruleTypes
2412
+ }
2413
+ }), config;
2414
+ }
2415
+ constructor(parent, name){
2416
+ super(parent), this.name = name, this.extend([
2417
+ 'loader',
2418
+ 'options',
2419
+ 'parallel'
2420
+ ]);
2768
2421
  }
2769
- example(example) {
2770
- return this.examples.push(example), this;
2422
+ });
2423
+ function toArray(arr) {
2424
+ return Array.isArray(arr) ? arr : [
2425
+ arr
2426
+ ];
2427
+ }
2428
+ let Rule_Rule = Orderable(class extends ChainedMap {
2429
+ use(name) {
2430
+ return this.uses.getOrCompute(name, ()=>new Use(this, name));
2771
2431
  }
2772
- option(rawName, description, config) {
2773
- let option = new Option(rawName, description, config);
2774
- return this.options.push(option), this;
2432
+ rule(name) {
2433
+ return this.rules.getOrCompute(name, ()=>new Rule_Rule(this, name, 'rule'));
2775
2434
  }
2776
- alias(name) {
2777
- return this.aliasNames.push(name), this;
2435
+ oneOf(name) {
2436
+ return this.oneOfs.getOrCompute(name, ()=>new Rule_Rule(this, name, 'oneOf'));
2778
2437
  }
2779
- action(callback) {
2780
- return this.commandAction = callback, this;
2438
+ pre() {
2439
+ return this.enforce('pre');
2781
2440
  }
2782
- isMatched(name) {
2783
- return this.name === name || this.aliasNames.includes(name);
2441
+ post() {
2442
+ return this.enforce('post');
2784
2443
  }
2785
- get isDefaultCommand() {
2786
- return "" === this.name || this.aliasNames.includes("!");
2444
+ toConfig() {
2445
+ let config = this.clean(Object.assign(this.entries() || {}, {
2446
+ include: this.include.values(),
2447
+ exclude: this.exclude.values(),
2448
+ rules: this.rules.values().map((rule)=>rule.toConfig()),
2449
+ oneOf: this.oneOfs.values().map((oneOf)=>oneOf.toConfig()),
2450
+ use: this.uses.values().map((use)=>use.toConfig()),
2451
+ resolve: this.resolve.toConfig()
2452
+ }));
2453
+ return Object.defineProperties(config, {
2454
+ __ruleNames: {
2455
+ value: this.names
2456
+ },
2457
+ __ruleTypes: {
2458
+ value: this.ruleTypes
2459
+ }
2460
+ }), config;
2787
2461
  }
2788
- get isGlobalCommand() {
2789
- return this instanceof GlobalCommand;
2462
+ merge(obj, omit = []) {
2463
+ return !omit.includes('include') && 'include' in obj && this.include.merge(toArray(obj.include)), !omit.includes('exclude') && 'exclude' in obj && this.exclude.merge(toArray(obj.exclude)), !omit.includes('use') && 'use' in obj && Object.keys(obj.use).forEach((name)=>this.use(name).merge(obj.use[name])), !omit.includes('rules') && 'rules' in obj && Object.keys(obj.rules).forEach((name)=>this.rule(name).merge(obj.rules[name])), !omit.includes('oneOf') && 'oneOf' in obj && Object.keys(obj.oneOf).forEach((name)=>this.oneOf(name).merge(obj.oneOf[name])), !omit.includes('resolve') && 'resolve' in obj && this.resolve.merge(obj.resolve), !omit.includes('test') && 'test' in obj && this.test(obj.test instanceof RegExp || 'function' == typeof obj.test ? obj.test : new RegExp(obj.test)), super.merge(obj, [
2464
+ ...omit,
2465
+ 'include',
2466
+ 'exclude',
2467
+ 'use',
2468
+ 'rules',
2469
+ 'oneOf',
2470
+ 'resolve',
2471
+ 'test'
2472
+ ]);
2790
2473
  }
2791
- hasOption(name) {
2792
- return name = name.split(".")[0], this.options.find((option)=>option.names.includes(name));
2474
+ constructor(parent, name, ruleType = 'rule'){
2475
+ super(parent), this.ruleName = name, this.names = [], this.ruleType = ruleType, this.ruleTypes = [];
2476
+ let rule = this;
2477
+ for(; rule instanceof Rule_Rule;)this.names.unshift(rule.ruleName), this.ruleTypes.unshift(rule.ruleType), rule = rule.parent;
2478
+ this.uses = new ChainedMap(this), this.include = new ChainedSet(this), this.exclude = new ChainedSet(this), this.rules = new ChainedMap(this), this.oneOfs = new ChainedMap(this), this.resolve = new Resolve_class(this), this.resolve.extend([
2479
+ 'fullySpecified'
2480
+ ]), this.extend([
2481
+ 'dependency',
2482
+ 'enforce',
2483
+ 'issuer',
2484
+ 'issuerLayer',
2485
+ 'layer',
2486
+ 'mimetype',
2487
+ 'parser',
2488
+ 'generator',
2489
+ 'resource',
2490
+ 'resourceFragment',
2491
+ 'resourceQuery',
2492
+ 'sideEffects',
2493
+ 'with',
2494
+ 'test',
2495
+ 'type'
2496
+ ]);
2793
2497
  }
2794
- outputHelp() {
2795
- let { name, commands } = this.cli, { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand, sections = [
2796
- {
2797
- body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
2798
- }
2799
- ];
2800
- if (sections.push({
2801
- title: "Usage",
2802
- body: ` $ ${name} ${this.usageText || this.rawName}`
2803
- }), (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
2804
- let longestCommandName = findLongest(commands.map((command)=>command.rawName));
2805
- sections.push({
2806
- title: "Commands",
2807
- body: commands.map((command)=>` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`).join("\n")
2808
- }), sections.push({
2809
- title: "For more info, run any command with the `--help` flag",
2810
- body: commands.map((command)=>` $ ${name}${"" === command.name ? "" : ` ${command.name}`} --help`).join("\n")
2811
- });
2812
- }
2813
- let options = this.isGlobalCommand ? globalOptions : [
2814
- ...this.options,
2815
- ...globalOptions || []
2816
- ];
2817
- if (this.isGlobalCommand || this.isDefaultCommand || (options = options.filter((option)=>"version" !== option.name)), options.length > 0) {
2818
- let longestOptionName = findLongest(options.map((option)=>option.rawName));
2819
- sections.push({
2820
- title: "Options",
2821
- body: options.map((option)=>` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${void 0 === option.config.default ? "" : `(default: ${option.config.default})`}`).join("\n")
2822
- });
2823
- }
2824
- this.examples.length > 0 && sections.push({
2825
- title: "Examples",
2826
- body: this.examples.map((example)=>"function" == typeof example ? example(name) : example).join("\n")
2827
- }), helpCallback && (sections = helpCallback(sections) || sections), console.log(sections.map((section)=>section.title ? `${section.title}:
2828
- ${section.body}` : section.body).join("\n\n"));
2498
+ });
2499
+ class Module_class extends ChainedMap {
2500
+ defaultRule(name) {
2501
+ return this.defaultRules.getOrCompute(name, ()=>new Rule_Rule(this, name, 'defaultRule'));
2829
2502
  }
2830
- outputVersion() {
2831
- let { name } = this.cli, { versionNumber } = this.cli.globalCommand;
2832
- versionNumber && console.log(`${name}/${versionNumber} ${platformInfo}`);
2503
+ rule(name) {
2504
+ return this.rules.getOrCompute(name, ()=>new Rule_Rule(this, name, 'rule'));
2833
2505
  }
2834
- checkRequiredArgs() {
2835
- let minimalArgsCount = this.args.filter((arg)=>arg.required).length;
2836
- if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
2506
+ toConfig() {
2507
+ return this.clean(Object.assign(this.entries() || {}, {
2508
+ defaultRules: this.defaultRules.values().map((r)=>r.toConfig()),
2509
+ generator: this.generator.entries(),
2510
+ parser: this.parser.entries(),
2511
+ rules: this.rules.values().map((r)=>r.toConfig())
2512
+ }));
2837
2513
  }
2838
- checkUnknownOptions() {
2839
- let { options, globalCommand } = this.cli;
2840
- if (!this.config.allowUnknownOptions) {
2841
- for (let name of Object.keys(options))if ("--" !== name && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
2842
- }
2514
+ merge(obj, omit = []) {
2515
+ return !omit.includes('rule') && 'rule' in obj && Object.keys(obj.rule).forEach((name)=>this.rule(name).merge(obj.rule[name])), !omit.includes('defaultRule') && 'defaultRule' in obj && Object.keys(obj.defaultRule).forEach((name)=>this.defaultRule(name).merge(obj.defaultRule[name])), super.merge(obj, [
2516
+ 'rule',
2517
+ 'defaultRule'
2518
+ ]);
2843
2519
  }
2844
- checkOptionValue() {
2845
- let { options: parsedOptions, globalCommand } = this.cli, options = [
2846
- ...globalCommand.options,
2847
- ...this.options
2848
- ];
2849
- for (let option of options){
2850
- let value = parsedOptions[option.name.split(".")[0]];
2851
- if (option.required) {
2852
- let hasNegated = options.some((o)=>o.negated && o.names.includes(option.name));
2853
- if (!0 === value || !1 === value && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
2854
- }
2855
- }
2520
+ constructor(parent){
2521
+ super(parent), this.rules = new ChainedMap(this), this.defaultRules = new ChainedMap(this), this.generator = new ChainedMap(this), this.parser = new ChainedMap(this), this.extend([
2522
+ 'noParse',
2523
+ 'unsafeCache',
2524
+ 'wrappedContextCritical',
2525
+ 'exprContextRegExp',
2526
+ 'wrappedContextRecursive',
2527
+ 'strictExportPresence',
2528
+ 'wrappedContextRegExp'
2529
+ ]);
2856
2530
  }
2857
2531
  }
2858
- class GlobalCommand extends Command {
2859
- constructor(cli){
2860
- super("@@global@@", "", {}, cli);
2532
+ class Optimization_class extends ChainedMap {
2533
+ minimizer(name) {
2534
+ if (Array.isArray(name)) throw Error("optimization.minimizer() no longer supports being passed an array. Either switch to the new syntax (https://github.com/neutrinojs/webpack-chain#config-optimization-minimizers-adding) or downgrade to webpack-chain 4. If using Vue this likely means a Vue plugin has not yet been updated to support Vue CLI 4+.");
2535
+ return this.minimizers.getOrCompute(name, ()=>new src_Plugin(this, name, 'optimization.minimizer'));
2861
2536
  }
2862
- }
2863
- var __assign = Object.assign;
2864
- class CAC extends EventEmitter {
2865
- constructor(name = ""){
2866
- super(), this.name = name, this.commands = [], this.rawArgs = [], this.args = [], this.options = {}, this.globalCommand = new GlobalCommand(this), this.globalCommand.usage("<command> [options]");
2537
+ toConfig() {
2538
+ return this.clean(Object.assign(this.entries() || {}, {
2539
+ splitChunks: this.splitChunks.entries(),
2540
+ minimizer: this.minimizers.values().map((plugin)=>plugin.toConfig())
2541
+ }));
2867
2542
  }
2868
- usage(text) {
2869
- return this.globalCommand.usage(text), this;
2543
+ merge(obj, omit = []) {
2544
+ return !omit.includes('minimizer') && 'minimizer' in obj && Object.keys(obj.minimizer).forEach((name)=>this.minimizer(name).merge(obj.minimizer[name])), super.merge(obj, [
2545
+ ...omit,
2546
+ 'minimizer'
2547
+ ]);
2870
2548
  }
2871
- command(rawName, description, config) {
2872
- let command = new Command(rawName, description || "", config, this);
2873
- return command.globalCommand = this.globalCommand, this.commands.push(command), command;
2549
+ constructor(parent){
2550
+ super(parent), this.minimizers = new ChainedMap(this), this.splitChunks = new ChainedValueMap(this), this.extend([
2551
+ 'minimize',
2552
+ 'runtimeChunk',
2553
+ 'emitOnErrors',
2554
+ 'moduleIds',
2555
+ 'chunkIds',
2556
+ 'nodeEnv',
2557
+ 'mangleWasmImports',
2558
+ 'removeAvailableModules',
2559
+ 'removeEmptyChunks',
2560
+ 'mergeDuplicateChunks',
2561
+ 'flagIncludedChunks',
2562
+ 'providedExports',
2563
+ 'usedExports',
2564
+ 'concatenateModules',
2565
+ 'sideEffects',
2566
+ 'portableRecords',
2567
+ 'mangleExports',
2568
+ 'innerGraph',
2569
+ 'realContentHash',
2570
+ 'avoidEntryIife'
2571
+ ]);
2874
2572
  }
2875
- option(rawName, description, config) {
2876
- return this.globalCommand.option(rawName, description, config), this;
2573
+ }
2574
+ class Performance_class extends ChainedValueMap {
2575
+ constructor(parent){
2576
+ super(parent), this.extend([
2577
+ 'assetFilter',
2578
+ 'hints',
2579
+ 'maxAssetSize',
2580
+ 'maxEntrypointSize'
2581
+ ]);
2877
2582
  }
2878
- help(callback) {
2879
- return this.globalCommand.option("-h, --help", "Display this message"), this.globalCommand.helpCallback = callback, this.showHelpOnExit = !0, this;
2583
+ }
2584
+ let castArray = (value)=>Array.isArray(value) ? value : [
2585
+ value
2586
+ ];
2587
+ class src_class extends ChainedMap {
2588
+ static toString(config, { verbose = !1, configPrefix = 'config' } = {}) {
2589
+ return (0, javascript_stringify_dist.stringify)(config, (value, indent, stringify)=>{
2590
+ if (value && value.__pluginName) {
2591
+ let prefix = `/* ${configPrefix}.${value.__pluginType}('${value.__pluginName}') */\n`, constructorExpression = value.__pluginPath ? `(require(${stringify(value.__pluginPath)}))` : value.__pluginConstructorName;
2592
+ if (constructorExpression) {
2593
+ let args = stringify(value.__pluginArgs).slice(1, -1);
2594
+ return `${prefix}new ${constructorExpression}(${args})`;
2595
+ }
2596
+ return prefix + stringify(value.__pluginArgs && value.__pluginArgs.length ? {
2597
+ args: value.__pluginArgs
2598
+ } : {});
2599
+ }
2600
+ if (value && value.__ruleNames) {
2601
+ let ruleTypes = value.__ruleTypes;
2602
+ return `/* ${configPrefix}.module${value.__ruleNames.map((r, index)=>`.${ruleTypes ? ruleTypes[index] : 'rule'}('${r}')`).join('')}${value.__useName ? `.use('${value.__useName}')` : ""} */\n` + stringify(value);
2603
+ }
2604
+ return value && value.__expression ? value.__expression : 'function' == typeof value && !verbose && value.toString().length > 100 ? "function () { /* omitted long function */ }" : stringify(value);
2605
+ }, 2);
2880
2606
  }
2881
- version(version, customFlags = "-v, --version") {
2882
- return this.globalCommand.version(version, customFlags), this.showVersionOnExit = !0, this;
2607
+ entry(name) {
2608
+ return this.entryPoints.getOrCompute(name, ()=>new ChainedSet(this));
2883
2609
  }
2884
- example(example) {
2885
- return this.globalCommand.example(example), this;
2610
+ plugin(name) {
2611
+ return this.plugins.getOrCompute(name, ()=>new src_Plugin(this, name));
2886
2612
  }
2887
- outputHelp() {
2888
- this.matchedCommand ? this.matchedCommand.outputHelp() : this.globalCommand.outputHelp();
2613
+ toConfig() {
2614
+ let entryPoints = this.entryPoints.entries() || {}, baseConfig = this.entries() || {};
2615
+ return this.clean(Object.assign(baseConfig, {
2616
+ node: this.node.entries(),
2617
+ output: this.output.entries(),
2618
+ resolve: this.resolve.toConfig(),
2619
+ resolveLoader: this.resolveLoader.toConfig(),
2620
+ devServer: this.devServer.toConfig(),
2621
+ module: this.module.toConfig(),
2622
+ optimization: this.optimization.toConfig(),
2623
+ plugins: this.plugins.values().map((plugin)=>plugin.toConfig()),
2624
+ performance: this.performance.entries(),
2625
+ entry: ((entryPoints)=>{
2626
+ let entry = Object.keys(entryPoints).reduce((acc, key)=>Object.assign(acc, {
2627
+ [key]: entryPoints[key].values()
2628
+ }), {}), formattedEntry = {};
2629
+ for (let [entryName, entryValue] of Object.entries(entry)){
2630
+ let entryImport = [], entryDescription = null;
2631
+ for (let item of castArray(entryValue)){
2632
+ if ('string' == typeof item) {
2633
+ entryImport.push(item);
2634
+ continue;
2635
+ }
2636
+ item.import && entryImport.push(...castArray(item.import)), entryDescription ? Object.assign(entryDescription, item) : entryDescription = item;
2637
+ }
2638
+ formattedEntry[entryName] = entryDescription ? {
2639
+ ...entryDescription,
2640
+ import: entryImport
2641
+ } : entryImport;
2642
+ }
2643
+ return formattedEntry;
2644
+ })(entryPoints)
2645
+ }));
2889
2646
  }
2890
- outputVersion() {
2891
- this.globalCommand.outputVersion();
2647
+ toString(options) {
2648
+ return this.constructor.toString(this.toConfig(), options);
2892
2649
  }
2893
- setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
2894
- return this.args = args, this.options = options, matchedCommand && (this.matchedCommand = matchedCommand), matchedCommandName && (this.matchedCommandName = matchedCommandName), this;
2650
+ merge(obj = {}, omit = []) {
2651
+ let omissions = [
2652
+ 'node',
2653
+ 'output',
2654
+ 'resolve',
2655
+ 'resolveLoader',
2656
+ 'devServer',
2657
+ 'optimization',
2658
+ 'performance',
2659
+ 'module'
2660
+ ];
2661
+ return !omit.includes('entry') && 'entry' in obj && Object.keys(obj.entry).forEach((name)=>this.entry(name).merge([].concat(obj.entry[name]))), !omit.includes('plugin') && 'plugin' in obj && Object.keys(obj.plugin).forEach((name)=>this.plugin(name).merge(obj.plugin[name])), omissions.forEach((key)=>{
2662
+ !omit.includes(key) && key in obj && this[key].merge(obj[key]);
2663
+ }), super.merge(obj, [
2664
+ ...omit,
2665
+ ...omissions,
2666
+ 'entry',
2667
+ 'plugin'
2668
+ ]);
2895
2669
  }
2896
- unsetMatchedCommand() {
2897
- this.matchedCommand = void 0, this.matchedCommandName = void 0;
2670
+ constructor(){
2671
+ super(), this.entryPoints = new ChainedMap(this), this.output = new Output_class(this), this.module = new Module_class(this), this.resolve = new Resolve_class(this), this.resolveLoader = new ResolveLoader_class(this), this.optimization = new Optimization_class(this), this.plugins = new ChainedMap(this), this.devServer = new DevServer_class(this), this.performance = new Performance_class(this), this.node = new ChainedValueMap(this), this.extend([
2672
+ 'context',
2673
+ 'mode',
2674
+ 'devtool',
2675
+ 'target',
2676
+ 'watch',
2677
+ 'watchOptions',
2678
+ 'externals',
2679
+ 'externalsType',
2680
+ 'externalsPresets',
2681
+ 'stats',
2682
+ 'experiments',
2683
+ 'amd',
2684
+ 'bail',
2685
+ 'cache',
2686
+ 'dependencies',
2687
+ 'ignoreWarnings',
2688
+ 'loader',
2689
+ 'parallelism',
2690
+ 'profile',
2691
+ 'recordsPath',
2692
+ 'recordsInputPath',
2693
+ 'recordsOutputPath',
2694
+ 'name',
2695
+ 'infrastructureLogging',
2696
+ 'snapshot',
2697
+ 'lazyCompilation'
2698
+ ]);
2898
2699
  }
2899
- parse(argv = processArgs, { run = !0 } = {}) {
2900
- var input;
2901
- let m;
2902
- this.rawArgs = argv, this.name || (this.name = argv[1] ? (input = argv[1], (m = /([^\\\/]+)$/.exec(input)) ? m[1] : "") : "cli");
2903
- let shouldParse = !0;
2904
- for (let command of this.commands){
2905
- let parsed = this.mri(argv.slice(2), command), commandName = parsed.args[0];
2906
- if (command.isMatched(commandName)) {
2907
- shouldParse = !1;
2908
- let parsedInfo = __assign(__assign({}, parsed), {
2909
- args: parsed.args.slice(1)
2910
- });
2911
- this.setParsedInfo(parsedInfo, command, commandName), this.emit(`command:${commandName}`, command);
2912
- }
2913
- }
2914
- if (shouldParse) {
2915
- for (let command of this.commands)if ("" === command.name) {
2916
- shouldParse = !1;
2917
- let parsed = this.mri(argv.slice(2), command);
2918
- this.setParsedInfo(parsed, command), this.emit("command:!", command);
2700
+ }
2701
+ let setNodeEnv = (env)=>{
2702
+ process.env.NODE_ENV = env;
2703
+ }, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), objectPrototype = Object.prototype, isPlainObject = (obj)=>null !== obj && 'object' == typeof obj && Object.getPrototypeOf(obj) === objectPrototype, helpers_castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
2704
+ arr
2705
+ ], cloneDeep = (value)=>null == value ? value : cjs_default()({}, value, {
2706
+ isMergeableObject: isPlainObject
2707
+ });
2708
+ function getFilename(config, type, isProd, isServer) {
2709
+ let { filename, filenameHash } = config.output, defaultHash = '[contenthash:8]', getHash = ()=>'string' == typeof filenameHash ? filenameHash ? `.[${filenameHash}]` : '' : filenameHash ? `.${defaultHash}` : '';
2710
+ switch(type){
2711
+ case 'js':
2712
+ return filename.js ?? `[name]${isProd && !isServer ? getHash() : ''}.js`;
2713
+ case 'css':
2714
+ return filename.css ?? `[name]${isProd ? getHash() : ''}.css`;
2715
+ case 'svg':
2716
+ return filename.svg ?? `[name]${getHash()}.svg`;
2717
+ case 'font':
2718
+ return filename.font ?? `[name]${getHash()}[ext]`;
2719
+ case 'image':
2720
+ return filename.image ?? `[name]${getHash()}[ext]`;
2721
+ case 'media':
2722
+ return filename.media ?? `[name]${getHash()}[ext]`;
2723
+ case 'assets':
2724
+ return filename.assets ?? `[name]${getHash()}[ext]`;
2725
+ case 'wasm':
2726
+ {
2727
+ let hash = 'string' == typeof filenameHash ? `[${filenameHash}]` : defaultHash;
2728
+ return filename.wasm ?? `${hash}.module.wasm`;
2919
2729
  }
2920
- }
2921
- if (shouldParse) {
2922
- let parsed = this.mri(argv.slice(2));
2923
- this.setParsedInfo(parsed);
2924
- }
2925
- this.options.help && this.showHelpOnExit && (this.outputHelp(), run = !1, this.unsetMatchedCommand()), this.options.version && this.showVersionOnExit && null == this.matchedCommandName && (this.outputVersion(), run = !1, this.unsetMatchedCommand());
2926
- let parsedArgv = {
2927
- args: this.args,
2928
- options: this.options
2929
- };
2930
- return run && this.runMatchedCommand(), !this.matchedCommand && this.args[0] && this.emit("command:*"), parsedArgv;
2730
+ case 'html':
2731
+ if (filename.html) return filename.html;
2732
+ return 'flat' === config.html.outputStructure ? '[name].html' : '[name]/index.html';
2733
+ default:
2734
+ throw Error(`${color.dim('[rsbuild:config]')} unknown key ${color.yellow(type)} in ${color.yellow('output.filename')}`);
2931
2735
  }
2932
- mri(argv, command) {
2933
- let cliOptions = [
2934
- ...this.globalCommand.options,
2935
- ...command ? command.options : []
2936
- ], mriOptions = ((options)=>{
2937
- let result = {
2938
- alias: {},
2939
- boolean: []
2940
- };
2941
- for (let [index, option] of options.entries())option.names.length > 1 && (result.alias[option.names[0]] = option.names.slice(1)), option.isBoolean && (option.negated && options.some((o, i)=>i !== index && o.names.some((name)=>option.names.includes(name)) && "boolean" == typeof o.required) || result.boolean.push(option.names[0]));
2942
- return result;
2943
- })(cliOptions), argsAfterDoubleDashes = [], doubleDashesIndex = argv.indexOf("--");
2944
- doubleDashesIndex > -1 && (argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1), argv = argv.slice(0, doubleDashesIndex));
2945
- let parsed = function(args, opts) {
2946
- opts = opts || {};
2947
- var k, arr, arg, name, val, out = {
2948
- _: []
2949
- }, i = 0, j = 0, idx = 0, len = (args = args || []).length;
2950
- let alibi = void 0 !== opts.alias, strict = void 0 !== opts.unknown, defaults = void 0 !== opts.default;
2951
- if (opts.alias = opts.alias || {}, opts.string = toArr(opts.string), opts.boolean = toArr(opts.boolean), alibi) for(k in opts.alias)for(i = 0, arr = opts.alias[k] = toArr(opts.alias[k]); i < arr.length; i++)(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
2952
- for(i = opts.boolean.length; i-- > 0;)for(j = (arr = opts.alias[opts.boolean[i]] || []).length; j-- > 0;)opts.boolean.push(arr[j]);
2953
- for(i = opts.string.length; i-- > 0;)for(j = (arr = opts.alias[opts.string[i]] || []).length; j-- > 0;)opts.string.push(arr[j]);
2954
- if (defaults) {
2955
- for(k in opts.default)if (name = typeof opts.default[k], arr = opts.alias[k] = opts.alias[k] || [], void 0 !== opts[name]) for(opts[name].push(k), i = 0; i < arr.length; i++)opts[name].push(arr[i]);
2956
- }
2957
- let keys = strict ? Object.keys(opts.alias) : [];
2958
- for(i = 0; i < len; i++){
2959
- if ('--' === (arg = args[i])) {
2960
- out._ = out._.concat(args.slice(++i));
2961
- break;
2962
- }
2963
- for(j = 0; j < arg.length && 45 === arg.charCodeAt(j); j++);
2964
- if (0 === j) out._.push(arg);
2965
- else if ('no-' === arg.substring(j, j + 3)) {
2966
- if (name = arg.substring(j + 3), strict && !~keys.indexOf(name)) return opts.unknown(arg);
2967
- out[name] = !1;
2968
- } else {
2969
- for(idx = j + 1; idx < arg.length && 61 !== arg.charCodeAt(idx); idx++);
2970
- for(name = arg.substring(j, idx), val = arg.substring(++idx) || i + 1 === len || 45 === ('' + args[i + 1]).charCodeAt(0) || args[++i], arr = 2 === j ? [
2971
- name
2972
- ] : name, idx = 0; idx < arr.length; idx++){
2973
- if (name = arr[idx], strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
2974
- !function(out, key, val, opts) {
2975
- var x, old = out[key], nxt = ~opts.string.indexOf(key) ? null == val || !0 === val ? '' : String(val) : 'boolean' == typeof val ? val : ~opts.boolean.indexOf(key) ? 'false' !== val && ('true' === val || (out._.push(0 * (x = +val) == 0 ? x : val), !!val)) : 0 * (x = +val) == 0 ? x : val;
2976
- out[key] = null == old ? nxt : Array.isArray(old) ? old.concat(nxt) : [
2977
- old,
2978
- nxt
2979
- ];
2980
- }(out, name, idx + 1 < arr.length || val, opts);
2981
- }
2982
- }
2983
- }
2984
- if (defaults) for(k in opts.default)void 0 === out[k] && (out[k] = opts.default[k]);
2985
- if (alibi) for(k in out)for(arr = opts.alias[k] || []; arr.length > 0;)out[arr.shift()] = out[k];
2986
- return out;
2987
- }(argv, mriOptions), args = (parsed = Object.keys(parsed).reduce((res, name)=>__assign(__assign({}, res), {
2988
- [camelcaseOptionName(name)]: parsed[name]
2989
- }), {
2990
- _: []
2991
- }))._, options = {
2992
- "--": argsAfterDoubleDashes
2993
- }, ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue, transforms = Object.create(null);
2994
- for (let cliOption of cliOptions){
2995
- if (!ignoreDefault && void 0 !== cliOption.config.default) for (let name of cliOption.names)options[name] = cliOption.config.default;
2996
- Array.isArray(cliOption.config.type) && void 0 === transforms[cliOption.name] && (transforms[cliOption.name] = Object.create(null), transforms[cliOption.name].shouldTransform = !0, transforms[cliOption.name].transformFunction = cliOption.config.type[0]);
2997
- }
2998
- for (let key of Object.keys(parsed))"_" !== key && (setDotProp(options, key.split("."), parsed[key]), setByType(options, transforms));
2999
- return {
3000
- args,
3001
- options
3002
- };
2736
+ }
2737
+ let upperFirst = (str)=>str ? str.charAt(0).toUpperCase() + str.slice(1) : '', createVirtualModule = (content)=>`data:text/javascript,${content}`;
2738
+ function pick(obj, keys) {
2739
+ let result = {};
2740
+ for (let key of keys)void 0 !== obj[key] && (result[key] = obj[key]);
2741
+ return result;
2742
+ }
2743
+ let prettyTime = (seconds)=>{
2744
+ let time, time1;
2745
+ if (seconds < 10) {
2746
+ let time, digits = seconds >= 0.01 ? 2 : 3;
2747
+ return `${time = seconds.toFixed(digits), color.bold(time)} s`;
3003
2748
  }
3004
- runMatchedCommand() {
3005
- let { args, options, matchedCommand: command } = this;
3006
- if (!command || !command.commandAction) return;
3007
- command.checkUnknownOptions(), command.checkOptionValue(), command.checkRequiredArgs();
3008
- let actionArgs = [];
3009
- return command.args.forEach((arg, index)=>{
3010
- arg.variadic ? actionArgs.push(args.slice(index)) : actionArgs.push(args[index]);
3011
- }), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
2749
+ if (seconds < 60) {
2750
+ let time;
2751
+ return `${time = seconds.toFixed(1), color.bold(time)} s`;
3012
2752
  }
2753
+ let minutes = Math.floor(seconds / 60), minutesLabel = `${(time = minutes.toFixed(0), color.bold(time))} m`, remainingSeconds = seconds % 60;
2754
+ if (0 === remainingSeconds) return minutesLabel;
2755
+ let secondsLabel = `${(time1 = remainingSeconds.toFixed(+(remainingSeconds % 1 != 0)), color.bold(time1))} s`;
2756
+ return `${minutesLabel} ${secondsLabel}`;
2757
+ }, isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !process.env.CI;
2758
+ async function helpers_hash(data) {
2759
+ let crypto = await import("node:crypto");
2760
+ return crypto.hash ? crypto.hash('sha256', data, 'hex').slice(0, 16) : crypto.createHash('sha256').update(data).digest('hex').slice(0, 16);
3013
2761
  }
2762
+ let compiler_isMultiCompiler = (compiler)=>'compilers' in compiler && Array.isArray(compiler.compilers), getPublicPathFromCompiler = (compiler)=>{
2763
+ let { publicPath } = compiler.options.output;
2764
+ return 'string' == typeof publicPath ? 'auto' === publicPath ? '' : publicPath.endsWith('/') ? publicPath : `${publicPath}/` : DEFAULT_ASSET_PREFIX;
2765
+ }, applyToCompiler = (compiler, apply)=>{
2766
+ compiler_isMultiCompiler(compiler) ? compiler.compilers.forEach(apply) : apply(compiler, 0);
2767
+ }, addCompilationError = (compilation, message)=>{
2768
+ compilation.errors.push(new compilation.compiler.webpack.WebpackError(message));
2769
+ };
3014
2770
  function createEnvironmentAsyncHook() {
3015
2771
  let preGroup = [], postGroup = [], defaultGroup = [], tapEnvironment = ({ environment, handler: cb })=>{
3016
2772
  isFunction(cb) ? defaultGroup.push({
@@ -3094,7 +2850,7 @@ function createAsyncHook() {
3094
2850
  }
3095
2851
  let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompiler, isWatch })=>{
3096
2852
  let name = 'rsbuild:beforeCompile';
3097
- if (helpers_isMultiCompiler(compiler)) {
2853
+ if (compiler_isMultiCompiler(compiler)) {
3098
2854
  let waitBeforeCompileDone, { compilers } = compiler;
3099
2855
  compiler.hooks.invalid.tap(name, ()=>{
3100
2856
  waitBeforeCompileDone = void 0;
@@ -3109,7 +2865,7 @@ let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompiler, isW
3109
2865
  await beforeCompile?.(), await beforeEnvironmentCompiler(0);
3110
2866
  });
3111
2867
  }, onCompileDone = ({ compiler, onDone, onEnvironmentDone, MultiStatsCtor })=>{
3112
- if (helpers_isMultiCompiler(compiler)) {
2868
+ if (compiler_isMultiCompiler(compiler)) {
3113
2869
  let { compilers } = compiler, compilerStats = [], doneCompilers = 0;
3114
2870
  for(let index = 0; index < compilers.length; index++){
3115
2871
  let compiler = compilers[index], compilerIndex = index, compilerDone = !1;
@@ -3220,6 +2976,179 @@ let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompiler, isW
3220
2976
  MultiStatsCtor
3221
2977
  });
3222
2978
  };
2979
+ function formatStatsError(stats, verbose) {
2980
+ let message, fileName = function(stats) {
2981
+ let file = stats.file || stats.moduleName;
2982
+ if (file) return file;
2983
+ if (stats.moduleIdentifier) {
2984
+ let matched = stats.moduleIdentifier.match(/(?:!|^)([^!]+)$/);
2985
+ if (matched) {
2986
+ let fileName = matched.pop();
2987
+ if (fileName) return fileName;
2988
+ }
2989
+ }
2990
+ return '';
2991
+ }(stats), mainMessage = stats.message, details = verbose && stats.details ? `\nDetails: ${stats.details}\n` : '', stack = verbose && stats.stack ? `\n${stats.stack}` : '', moduleTrace = function(stats, errorFile) {
2992
+ if (!stats.moduleTrace) return;
2993
+ let moduleNames = stats.moduleTrace.map((trace)=>trace.originName).filter(Boolean);
2994
+ if (!moduleNames.length) return;
2995
+ errorFile && moduleNames.unshift(`${errorFile} ${color.bold(color.red('×'))}`);
2996
+ let rawTrace = moduleNames.reverse().map((item)=>`\n ${item}`).join('');
2997
+ return color.dim(`Import traces (entry → error):${rawTrace}`);
2998
+ }(stats, fileName) ?? '';
2999
+ message = `${/:\d+:\d+/.test(fileName) ? `File: ${color.cyan(fileName)}\n` : `File: ${color.cyan(`${fileName}:1:1`)}\n`}${mainMessage}${details}${stack}${moduleTrace}`;
3000
+ let innerError = '-- inner error --';
3001
+ return !verbose && message.includes(innerError) && (message = message.split(innerError)[0]), (message = (message = ((message)=>{
3002
+ let getTips = (moduleName)=>{
3003
+ let tips = [
3004
+ `Error: "${moduleName}" is a built-in Node.js module and cannot be imported in client-side code.\n`,
3005
+ 'Solution: Check if you need to import Node.js module.',
3006
+ ' - If not needed, remove the import.',
3007
+ ` - If needed, use "${color.yellow('@rsbuild/plugin-node-polyfill')}" to polyfill it. (See ${color.yellow('https://npmjs.com/package/@rsbuild/plugin-node-polyfill')})`
3008
+ ];
3009
+ return `${message}\n\n${color.red(tips.join('\n'))}`;
3010
+ };
3011
+ if (message.includes('need an additional plugin to handle "node:" URIs')) return getTips('node:*');
3012
+ if (!message.includes("Can't resolve")) return message;
3013
+ let matchArray = message.match(/Can't resolve '(\w+)'/);
3014
+ if (!matchArray) return message;
3015
+ let moduleName = matchArray[1];
3016
+ return moduleName && [
3017
+ 'assert',
3018
+ 'buffer',
3019
+ 'child_process',
3020
+ 'cluster',
3021
+ 'console',
3022
+ 'constants',
3023
+ 'crypto',
3024
+ 'dgram',
3025
+ 'dns',
3026
+ 'domain',
3027
+ 'events',
3028
+ 'fs',
3029
+ 'http',
3030
+ 'https',
3031
+ 'module',
3032
+ 'net',
3033
+ 'os',
3034
+ 'path',
3035
+ 'punycode',
3036
+ 'process',
3037
+ 'querystring',
3038
+ 'readline',
3039
+ 'repl',
3040
+ 'stream',
3041
+ '_stream_duplex',
3042
+ '_stream_passthrough',
3043
+ '_stream_readable',
3044
+ '_stream_transform',
3045
+ '_stream_writable',
3046
+ 'string_decoder',
3047
+ 'sys',
3048
+ 'timers',
3049
+ 'tls',
3050
+ 'tty',
3051
+ 'url',
3052
+ 'util',
3053
+ 'vm',
3054
+ 'zlib'
3055
+ ].includes(moduleName) ? getTips(moduleName) : message;
3056
+ })(message = function(message) {
3057
+ let hint = 'You may need an appropriate loader to handle this file type.';
3058
+ if (-1 === message.indexOf(hint)) return message;
3059
+ let createPluginHint = (packageName, keyword)=>`To enable support for ${keyword}, use "${color.yellow(`@rsbuild/plugin-${packageName}`)}" ${color.dim(`(https://npmjs.com/package/@rsbuild/plugin-${packageName})`)}.`;
3060
+ for (let plugin of [
3061
+ {
3062
+ test: /File: .+\.s(c|a)ss/,
3063
+ hint: createPluginHint('sass', 'Sass')
3064
+ },
3065
+ {
3066
+ test: /File: .+\.less/,
3067
+ hint: createPluginHint('less', 'Less')
3068
+ },
3069
+ {
3070
+ test: /File: .+\.styl(us)?/,
3071
+ hint: createPluginHint('stylus', 'Stylus')
3072
+ },
3073
+ {
3074
+ test: /File: .+\.vue?/,
3075
+ hint: createPluginHint('vue', 'Vue')
3076
+ },
3077
+ {
3078
+ test: /File: .+\.svelte?/,
3079
+ hint: createPluginHint('svelte', 'Svelte')
3080
+ },
3081
+ {
3082
+ test: /File: .+\.mdx/,
3083
+ hint: createPluginHint('mdx', 'MDX')
3084
+ },
3085
+ {
3086
+ test: /File: .+\.toml/,
3087
+ hint: createPluginHint('toml', 'TOML')
3088
+ },
3089
+ {
3090
+ test: /File: .+\.yaml/,
3091
+ hint: createPluginHint('yaml', 'YAML')
3092
+ }
3093
+ ])if (plugin.test.test(message)) return message.replace(hint, plugin.hint);
3094
+ return message;
3095
+ }(message))).split('\n').filter((line, index, arr)=>0 === index || '' !== line.trim() || line.trim() !== arr[index - 1].trim()).join('\n')).trim();
3096
+ }
3097
+ let getStatsErrors = ({ errors, children })=>void 0 !== errors && errors.length > 0 ? errors : children ? children.reduce((errors, ret)=>ret.errors ? errors.concat(ret.errors) : errors, []) : [], getStatsWarnings = ({ warnings, children })=>void 0 !== warnings && warnings.length > 0 ? warnings : children ? children.reduce((warnings, ret)=>ret.warnings ? warnings.concat(ret.warnings) : warnings, []) : [], getAssetsFromStats = (stats)=>stats.toJson({
3098
+ all: !1,
3099
+ assets: !0,
3100
+ cachedAssets: !0,
3101
+ groupAssetsByInfo: !1,
3102
+ groupAssetsByPath: !1,
3103
+ groupAssetsByChunk: !1,
3104
+ groupAssetsByExtension: !1,
3105
+ groupAssetsByEmitStatus: !1
3106
+ }).assets || [];
3107
+ function getRsbuildStats(statsInstance, compiler, action) {
3108
+ let statsOptions = function(compiler, action) {
3109
+ let defaultOptions = {
3110
+ all: !1,
3111
+ timings: !0,
3112
+ errors: !0,
3113
+ warnings: !0,
3114
+ moduleTrace: !0
3115
+ };
3116
+ if ('dev' === action && (defaultOptions.hash = !0, defaultOptions.entrypoints = !0), compiler_isMultiCompiler(compiler)) return {
3117
+ ...defaultOptions,
3118
+ children: compiler.compilers.map((compiler)=>compiler.options ? compiler.options.stats : void 0)
3119
+ };
3120
+ let { stats } = compiler.options;
3121
+ return 'string' == typeof stats ? {
3122
+ ...defaultOptions,
3123
+ preset: stats
3124
+ } : 'object' == typeof stats ? {
3125
+ ...defaultOptions,
3126
+ ...stats
3127
+ } : defaultOptions;
3128
+ }(compiler, action);
3129
+ return statsInstance.toJson(statsOptions);
3130
+ }
3131
+ function formatStats(stats, hasErrors) {
3132
+ let verbose = 'verbose' === logger.level;
3133
+ if (hasErrors) return {
3134
+ message: function(errors) {
3135
+ if (!errors.length) return 'Build failed. No errors reported since Rspack\'s "stats.errors" is disabled.';
3136
+ let title = color.bold(color.red(errors.length > 1 ? 'Build errors: ' : 'Build error: ')), text = `${errors.join('\n\n')}\n`;
3137
+ return `${title}\n${text}`;
3138
+ }(getStatsErrors(stats).map((item)=>formatStatsError(item, verbose))),
3139
+ level: 'error'
3140
+ };
3141
+ let warningMessages = getStatsWarnings(stats).map((item)=>formatStatsError(item, verbose));
3142
+ if (warningMessages.length) {
3143
+ let title = color.bold(color.yellow(warningMessages.length > 1 ? 'Build warnings: \n' : 'Build warning: \n'));
3144
+ return {
3145
+ message: `${title}${warningMessages.join('\n\n')}\n`,
3146
+ level: 'warning'
3147
+ };
3148
+ }
3149
+ return {};
3150
+ }
3151
+ let rspackMinVersion = '1.5.0';
3223
3152
  class BrowserslistError extends Error {
3224
3153
  constructor(message){
3225
3154
  var key, value;
@@ -3283,7 +3212,65 @@ function eachParent(file, callback) {
3283
3212
  if (void 0 !== result) return result;
3284
3213
  }while (loc !== (loc = external_node_path_.default.dirname(loc)));
3285
3214
  }
3286
- let configCache = {}, OVERRIDE_PATHS = [
3215
+ let configCache = {};
3216
+ function getCommonParentPath(paths) {
3217
+ let uniquePaths = [
3218
+ ...new Set(paths)
3219
+ ];
3220
+ if (1 === uniquePaths.length) return uniquePaths[0];
3221
+ let [first, ...rest] = uniquePaths.map((p)=>p.split(external_node_path_.sep)), common = [];
3222
+ for(let i = 0; i < first.length; i++){
3223
+ let segment = first[i];
3224
+ if (rest.every((p)=>p[i] === segment)) common.push(segment);
3225
+ else break;
3226
+ }
3227
+ return common.join(external_node_path_.sep);
3228
+ }
3229
+ let getCompiledPath = (packageName)=>(0, external_node_path_.join)(COMPILED_PATH, packageName, 'index.js'), ensureAbsolutePath = (base, filePath)=>(0, external_node_path_.isAbsolute)(filePath) ? filePath : (0, external_node_path_.join)(base, filePath), getPathnameFromUrl = (publicPath)=>{
3230
+ try {
3231
+ return publicPath ? new URL(publicPath).pathname : publicPath;
3232
+ } catch {
3233
+ return publicPath;
3234
+ }
3235
+ }, dedupeNestedPaths = (paths)=>paths.sort((p1, p2)=>p2.length > p1.length ? -1 : 1).reduce((prev, curr)=>prev.find((p)=>curr.startsWith(p) || curr === p) ? prev : prev.concat(curr), []), toPosixPath = (filepath)=>'/' === external_node_path_.sep ? filepath : filepath.replace(/\\/g, '/'), isFileSync = (filePath)=>{
3236
+ try {
3237
+ return node_fs.statSync(filePath, {
3238
+ throwIfNoEntry: !1
3239
+ })?.isFile();
3240
+ } catch (_) {
3241
+ return !1;
3242
+ }
3243
+ }, findExists = (files)=>{
3244
+ for (let file of files)if (isFileSync(file)) return file;
3245
+ return !1;
3246
+ };
3247
+ async function pathExists(path) {
3248
+ return node_fs.promises.access(path).then(()=>!0).catch(()=>!1);
3249
+ }
3250
+ async function isFileExists(file) {
3251
+ return node_fs.promises.access(file, node_fs.constants.F_OK).then(()=>!0).catch(()=>!1);
3252
+ }
3253
+ async function fileExistsByCompilation({ inputFileSystem }, filePath) {
3254
+ return new Promise((resolve)=>{
3255
+ inputFileSystem ? inputFileSystem.stat(filePath, (err, stats)=>{
3256
+ err ? resolve(!1) : resolve(!!stats?.isFile());
3257
+ }) : resolve(!1);
3258
+ });
3259
+ }
3260
+ async function emptyDir(dir, keep = [], checkExists = !0) {
3261
+ if (!checkExists || await pathExists(dir)) try {
3262
+ let entries = await node_fs.promises.readdir(dir, {
3263
+ withFileTypes: !0
3264
+ });
3265
+ await Promise.all(entries.map(async (entry)=>{
3266
+ let fullPath = external_node_path_.default.join(dir, entry.name);
3267
+ !keep.some((reg)=>reg.test(toPosixPath(fullPath))) && (entry.isDirectory() ? (await emptyDir(fullPath, keep, !1), keep.length || await node_fs.promises.rmdir(fullPath)) : await node_fs.promises.unlink(fullPath));
3268
+ }));
3269
+ } catch (err) {
3270
+ logger.debug(`failed to empty dir: ${dir}`), logger.debug(err);
3271
+ }
3272
+ }
3273
+ let OVERRIDE_PATHS = [
3287
3274
  'performance.removeConsole',
3288
3275
  'output.inlineScripts',
3289
3276
  'output.inlineStyles',
@@ -3503,7 +3490,19 @@ function exit(exitCode, type) {
3503
3490
  }
3504
3491
  }
3505
3492
  }
3506
- let isEnvironmentMatch = (pluginEnvironment, specifiedEnvironment)=>pluginEnvironment === specifiedEnvironment || void 0 === pluginEnvironment;
3493
+ let addTrailingSlash = (s)=>s.endsWith('/') ? s : `${s}/`, isURL = (str)=>str.startsWith('http') || str.startsWith('//:'), urlJoin = (base, path)=>{
3494
+ let [urlProtocol, baseUrl] = base.split('://');
3495
+ return `${urlProtocol}://${external_node_path_.posix.join(baseUrl, path)}`;
3496
+ }, canParse = (url)=>{
3497
+ try {
3498
+ return new external_node_url_.URL(url), !0;
3499
+ } catch {
3500
+ return !1;
3501
+ }
3502
+ }, ensureAssetPrefix = (url, assetPrefix = DEFAULT_ASSET_PREFIX)=>url.startsWith('//') || canParse(url) || 'auto' === assetPrefix || 'function' == typeof assetPrefix ? url : assetPrefix.startsWith('http') ? urlJoin(assetPrefix, url) : assetPrefix.startsWith('//') ? urlJoin(`https:${assetPrefix}`, url).replace('https:', '') : external_node_path_.posix.join(assetPrefix, url), formatPublicPath = (publicPath, withSlash = !0)=>'auto' === publicPath ? publicPath : withSlash ? addTrailingSlash(publicPath) : publicPath.replace(/\/+$/, ''), getPublicPathFromChain = (chain, withSlash = !0)=>{
3503
+ let publicPath = chain.output.get('publicPath');
3504
+ return 'string' == typeof publicPath ? formatPublicPath(publicPath, withSlash) : formatPublicPath(DEFAULT_ASSET_PREFIX, withSlash);
3505
+ }, isEnvironmentMatch = (pluginEnvironment, specifiedEnvironment)=>pluginEnvironment === specifiedEnvironment || void 0 === pluginEnvironment;
3507
3506
  async function initPlugins({ context, pluginManager }) {
3508
3507
  logger.debug('initializing plugins');
3509
3508
  let plugins = pluginManager.getAllPluginsWithMeta();
@@ -3523,7 +3522,7 @@ async function initPlugins({ context, pluginManager }) {
3523
3522
  for(; zeroEndPoints.length;){
3524
3523
  let pluginInstances = function(name) {
3525
3524
  let targets = plugins.filter((item)=>item.instance.name === name);
3526
- if (!targets.length) throw Error(`${picocolors.dim('[rsbuild:plugin]')} Plugin "${picocolors.yellow(name)}" not existed`);
3525
+ if (!targets.length) throw Error(`${color.dim('[rsbuild:plugin]')} Plugin "${color.yellow(name)}" not existed`);
3527
3526
  return targets;
3528
3527
  }(zeroEndPoints.shift().instance.name);
3529
3528
  sortedPoint.push(...pluginInstances), allLines = allLines.filter((l)=>l[0] !== pluginInstances[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));
@@ -3531,7 +3530,7 @@ async function initPlugins({ context, pluginManager }) {
3531
3530
  if (allLines.length) {
3532
3531
  let restInRingPoints = {};
3533
3532
  for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
3534
- throw Error(`${picocolors.dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${picocolors.yellow(Object.keys(restInRingPoints).join(','))}`);
3533
+ throw Error(`${color.dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${color.yellow(Object.keys(restInRingPoints).join(','))}`);
3535
3534
  }
3536
3535
  return sortedPoint;
3537
3536
  })(plugins = ((plugins)=>{
@@ -3605,12 +3604,12 @@ let mapProcessAssetsStage = (compiler, stage)=>{
3605
3604
  case 'report':
3606
3605
  return Compilation.PROCESS_ASSETS_STAGE_REPORT;
3607
3606
  default:
3608
- throw Error(`${picocolors.dim('[rsbuild]')} Invalid process assets stage: ${stage}`);
3607
+ throw Error(`${color.dim('[rsbuild]')} Invalid process assets stage: ${stage}`);
3609
3608
  }
3610
3609
  }, browsersListCache = new Map(), getEnvironmentHTMLPaths = (entry, config)=>'web' !== config.output.target || !1 === config.tools.htmlPlugin ? {} : Object.keys(entry).reduce((prev, key)=>{
3611
3610
  var entryName, config1;
3612
3611
  let filename, prefix, entryValue = entry[key];
3613
- return ('string' == typeof entryValue || Array.isArray(entryValue) || !1 !== entryValue.html) && (prev[key] = (entryName = key, filename = getFilename(config1 = config, 'html').replace('[name]', entryName), (prefix = config1.output.distPath.html).startsWith('/') && logger.warn(`${picocolors.dim('[rsbuild:config]')} Absolute path is not recommended at ${picocolors.yellow(`output.distPath.html: "${prefix}"`)}, use relative path instead.`), external_node_path_.posix.join(prefix, filename).replace(/^\/+/, ''))), prev;
3612
+ return ('string' == typeof entryValue || Array.isArray(entryValue) || !1 !== entryValue.html) && (prev[key] = (entryName = key, filename = getFilename(config1 = config, 'html').replace('[name]', entryName), (prefix = config1.output.distPath.html).startsWith('/') && logger.warn(`${color.dim('[rsbuild:config]')} Absolute path is not recommended at ${color.yellow(`output.distPath.html: "${prefix}"`)}, use relative path instead.`), external_node_path_.posix.join(prefix, filename).replace(/^\/+/, ''))), prev;
3614
3613
  }, {});
3615
3614
  async function updateEnvironmentContext(context, configs) {
3616
3615
  for (let [index, [name, config]] of (context.environments ||= {}, Object.entries(configs).entries())){
@@ -3679,7 +3678,7 @@ async function updateEnvironmentContext(context, configs) {
3679
3678
  async function createContext(options, userConfig) {
3680
3679
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = (0, external_node_path_.join)(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
3681
3680
  return {
3682
- version: "1.5.13",
3681
+ version: "1.5.15",
3683
3682
  rootPath,
3684
3683
  distPath: '',
3685
3684
  cachePath,
@@ -3717,6 +3716,7 @@ async function createContext(options, userConfig) {
3717
3716
  originalConfig: userConfig,
3718
3717
  specifiedEnvironments,
3719
3718
  buildState: {
3719
+ stats: null,
3720
3720
  status: 'idle',
3721
3721
  hasErrors: !1
3722
3722
  }
@@ -3761,7 +3761,7 @@ async function outputInspectConfigFiles({ rawBundlerConfigs, rawEnvironmentConfi
3761
3761
  await node_fs.promises.mkdir(outputPath, {
3762
3762
  recursive: !0
3763
3763
  }), await Promise.all(files.map(async (item)=>node_fs.promises.writeFile(item.path, `export default ${item.content}`)));
3764
- let fileInfos = files.map((item)=>` - ${picocolors.bold(picocolors.yellow(item.label))}: ${picocolors.underline(item.path)}`).join('\n');
3764
+ let fileInfos = files.map((item)=>` - ${color.bold(color.yellow(item.label))}: ${color.underline(item.path)}`).join('\n');
3765
3765
  logger.success(`config inspection completed, generated files: \n\n${fileInfos}\n`);
3766
3766
  }
3767
3767
  function stringifyConfig(config, verbose) {
@@ -3954,9 +3954,9 @@ let configChain_CHAIN_ID = {
3954
3954
  RESOLVE_PLUGIN: {
3955
3955
  TS_CONFIG_PATHS: 'ts-config-paths'
3956
3956
  }
3957
- }, pluginHelper_require = (0, external_node_module_.createRequire)(import.meta.url), setHTMLPlugin = (plugin)=>{
3957
+ }, setHTMLPlugin = (plugin)=>{
3958
3958
  plugin && (pluginHelper_htmlPlugin = plugin);
3959
- }, getHTMLPlugin = ()=>(pluginHelper_htmlPlugin || (pluginHelper_htmlPlugin = pluginHelper_require('../compiled/html-rspack-plugin/index.js')), pluginHelper_htmlPlugin), setCssExtractPlugin = (plugin)=>{
3959
+ }, getHTMLPlugin = ()=>(pluginHelper_htmlPlugin || (pluginHelper_htmlPlugin = requireCompiledPackage('html-rspack-plugin')), pluginHelper_htmlPlugin), setCssExtractPlugin = (plugin)=>{
3960
3960
  cssExtractPlugin = plugin;
3961
3961
  };
3962
3962
  async function modifyRspackConfig(context, rspackConfig, chainUtils) {
@@ -4037,11 +4037,11 @@ async function generateRspackConfig({ target, context, environment }) {
4037
4037
  var config = rspackConfig = await modifyRspackConfig(context, rspackConfig, chainUtils);
4038
4038
  if (config.plugins) {
4039
4039
  for (let plugin of config.plugins)if (plugin && void 0 === plugin.apply && 'name' in plugin && 'setup' in plugin) {
4040
- let name = picocolors.bold(picocolors.yellow(plugin.name));
4041
- throw Error(`${picocolors.dim('[rsbuild:plugin]')} "${picocolors.yellow(name)}" appears to be an Rsbuild plugin. It cannot be used as an Rspack plugin.`);
4040
+ let name = color.bold(color.yellow(plugin.name));
4041
+ throw Error(`${color.dim('[rsbuild:plugin]')} "${color.yellow(name)}" appears to be an Rsbuild plugin. It cannot be used as an Rspack plugin.`);
4042
4042
  }
4043
4043
  }
4044
- return config.devServer && logger.warn(`${picocolors.dim('[rsbuild:config]')} Find invalid Rspack config: "${picocolors.yellow('devServer')}". Note that Rspack's "devServer" config is not supported by Rsbuild. You can use Rsbuild's "dev" config to configure the Rsbuild dev server.`), rspackConfig;
4044
+ return config.devServer && logger.warn(`${color.dim('[rsbuild:config]')} Find invalid Rspack config: "${color.yellow('devServer')}". Note that Rspack's "devServer" config is not supported by Rsbuild. You can use Rsbuild's "dev" config to configure the Rsbuild dev server.`), rspackConfig;
4045
4045
  }
4046
4046
  let allowedEnvironmentDevKeys = [
4047
4047
  'hmr',
@@ -4058,7 +4058,7 @@ async function modifyRsbuildConfig(context) {
4058
4058
  let pluginsCount = context.config.plugins?.length ?? 0, [modified] = await context.hooks.modifyRsbuildConfig.callChain(context.config, {
4059
4059
  mergeRsbuildConfig: mergeRsbuildConfig
4060
4060
  });
4061
- context.config = modified, (modified.plugins?.length ?? 0) !== pluginsCount && logger.warn(`${picocolors.dim('[rsbuild]')} Cannot change plugins via ${picocolors.yellow('modifyRsbuildConfig')} as plugins are already initialized when it executes.`), logger.debug('applied modifyRsbuildConfig hook');
4061
+ context.config = modified, (modified.plugins?.length ?? 0) !== pluginsCount && logger.warn(`${color.dim('[rsbuild]')} Cannot change plugins via ${color.yellow('modifyRsbuildConfig')} as plugins are already initialized when it executes.`), logger.debug('applied modifyRsbuildConfig hook');
4062
4062
  }
4063
4063
  async function modifyEnvironmentConfig(context, config, name) {
4064
4064
  logger.debug(`applying modifyEnvironmentConfig hook (${name})`);
@@ -4075,8 +4075,8 @@ async function modifyEnvironmentConfig(context, config, name) {
4075
4075
  return logger.debug(`applied modifyEnvironmentConfig hook (${name})`), modified;
4076
4076
  }
4077
4077
  let createEnvironmentNotFoundError = (environments = [])=>{
4078
- let envList = picocolors.yellow(environments.join(','));
4079
- return Error(`${picocolors.dim('[rsbuild:config]')} The current build is specified to run only in the ${envList} environment, but the configuration of the specified environment was not found.`);
4078
+ let envList = color.yellow(environments.join(','));
4079
+ return Error(`${color.dim('[rsbuild:config]')} The current build is specified to run only in the ${envList} environment, but the configuration of the specified environment was not found.`);
4080
4080
  };
4081
4081
  async function initRsbuildConfig({ context, pluginManager }) {
4082
4082
  let distPaths;
@@ -4159,7 +4159,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
4159
4159
  ...normalizedBaseConfig,
4160
4160
  environments
4161
4161
  }, await updateEnvironmentContext(context, environments), distPaths = Object.values(context.environments).map((item)=>item.distPath), context.distPath = getCommonParentPath(distPaths), ((config)=>{
4162
- if (config.server.base && !config.server.base.startsWith('/')) throw Error(`${picocolors.dim('[rsbuild:config]')} The ${picocolors.yellow('"server.base"')} option should start with a slash, for example: "/base"`);
4162
+ if (config.server.base && !config.server.base.startsWith('/')) throw Error(`${color.dim('[rsbuild:config]')} The ${color.yellow('"server.base"')} option should start with a slash, for example: "/base"`);
4163
4163
  if (!config.environments) return;
4164
4164
  let environmentNames = Object.keys(config.environments), environmentNameRegexp = /^[\w$-]+$/, validTargets = [
4165
4165
  'web',
@@ -4167,9 +4167,9 @@ async function initRsbuildConfig({ context, pluginManager }) {
4167
4167
  'web-worker'
4168
4168
  ];
4169
4169
  for (let name of environmentNames){
4170
- environmentNameRegexp.test(name) || logger.warn(`${picocolors.dim('[rsbuild:config]')} Environment name "${picocolors.yellow(name)}" contains invalid characters. Only letters, numbers, "-", "_", and "$" are allowed.`);
4170
+ environmentNameRegexp.test(name) || logger.warn(`${color.dim('[rsbuild:config]')} Environment name "${color.yellow(name)}" contains invalid characters. Only letters, numbers, "-", "_", and "$" are allowed.`);
4171
4171
  let outputConfig = config.environments[name].output;
4172
- if (outputConfig.target && !validTargets.includes(outputConfig.target)) throw Error(`${picocolors.dim('[rsbuild:config]')} Invalid value of ${picocolors.yellow('output.target')}: ${picocolors.yellow(`"${outputConfig.target}"`)}, valid values are: ${picocolors.yellow(validTargets.join(', '))}`);
4172
+ if (outputConfig.target && !validTargets.includes(outputConfig.target)) throw Error(`${color.dim('[rsbuild:config]')} Invalid value of ${color.yellow('output.target')}: ${color.yellow(`"${outputConfig.target}"`)}, valid values are: ${color.yellow(validTargets.join(', '))}`);
4173
4173
  }
4174
4174
  })(context.normalizedConfig), context.normalizedConfig;
4175
4175
  }
@@ -4232,7 +4232,7 @@ async function createCompiler_createCompiler(options) {
4232
4232
  if (item1 < item2) return -1;
4233
4233
  }
4234
4234
  return 0;
4235
- })(version, rspackMinVersion) >= 0)) throw Error(`${picocolors.dim('[rsbuild]')} The current Rspack version does not meet the requirements, the minimum supported version of Rspack is ${picocolors.green(rspackMinVersion)}`);
4235
+ })(version, rspackMinVersion) >= 0)) throw Error(`${color.dim('[rsbuild]')} The current Rspack version does not meet the requirements, the minimum supported version of Rspack is ${color.green(rspackMinVersion)}`);
4236
4236
  let isMultiCompiler = rspackConfigs.length > 1, compiler = isMultiCompiler ? rspack_rspack(rspackConfigs) : rspack_rspack(rspackConfigs[0]), isVersionLogged = !1, isCompiling = !1, logRspackVersion = ()=>{
4237
4237
  isVersionLogged || (logger.debug(`using Rspack v${rspack_rspack.rspackVersion}`), isVersionLogged = !0);
4238
4238
  }, lazyModules = new Set();
@@ -4254,40 +4254,34 @@ async function createCompiler_createCompiler(options) {
4254
4254
  let { modifiedFiles } = compiler, changedFiles = modifiedFiles?.size ? Array.from(modifiedFiles) : lazyModules.size ? Array.from(lazyModules) : null;
4255
4255
  if (changedFiles?.length) {
4256
4256
  let fileInfo = formatFileList(changedFiles, context.rootPath);
4257
- logger.start(`building ${picocolors.dim(fileInfo)}`);
4257
+ logger.start(`building ${color.dim(fileInfo)}`);
4258
4258
  return;
4259
4259
  }
4260
4260
  let removedFiles = compiler.removedFiles ? Array.from(compiler.removedFiles) : null;
4261
4261
  if (removedFiles?.length) {
4262
4262
  let fileInfo = formatFileList(removedFiles, context.rootPath);
4263
- logger.start(`building ${picocolors.dim(`removed ${fileInfo}`)}`);
4263
+ logger.start(`building ${color.dim(`removed ${fileInfo}`)}`);
4264
4264
  return;
4265
4265
  }
4266
4266
  logger.start('build started...');
4267
4267
  }(compiler, context, lazyModules), lazyModules.size && lazyModules.clear(), isCompiling = !0;
4268
4268
  }), compiler.hooks.invalid.tap(HOOK_NAME, ()=>{
4269
- context.buildState.status = 'idle', context.buildState.hasErrors = !1;
4269
+ context.buildState.stats = null, context.buildState.status = 'idle', context.buildState.hasErrors = !1;
4270
4270
  }), 'build' === context.action && (isMultiCompiler ? compiler.compilers[0] : compiler).hooks.run.tap(HOOK_NAME, ()=>{
4271
4271
  logger.info('build started...'), logRspackVersion();
4272
- }), compiler.hooks.done.tap(HOOK_NAME, (stats)=>{
4273
- let hasErrors = stats.hasErrors();
4274
- context.buildState.hasErrors = hasErrors, context.buildState.status = 'done';
4275
- let statsOptions = getStatsOptions(compiler), statsJson = stats.toJson({
4276
- children: !0,
4277
- moduleTrace: !0,
4278
- timings: !0,
4279
- preset: 'errors-warnings',
4280
- ...statsOptions
4281
- }), printTime = (c, index)=>{
4282
- if (c.time) {
4283
- let time = prettyTime(c.time / 1000), { name } = rspackConfigs[index], suffix = name && isMultiCompiler ? picocolors.dim(` (${name})`) : '';
4272
+ }), compiler.hooks.done.tap(HOOK_NAME, (statsInstance)=>{
4273
+ let stats = getRsbuildStats(statsInstance, compiler, context.action), hasErrors = statsInstance.hasErrors();
4274
+ context.buildState.stats = stats, context.buildState.status = 'done', context.buildState.hasErrors = hasErrors;
4275
+ let printTime = (statsItem, index)=>{
4276
+ if (statsItem.time) {
4277
+ let time = prettyTime(statsItem.time / 1000), { name } = rspackConfigs[index], suffix = name && isMultiCompiler ? color.dim(` (${name})`) : '';
4284
4278
  logger.ready(`built in ${time}${suffix}`);
4285
4279
  }
4286
4280
  };
4287
- hasErrors || (isMultiCompiler && statsJson.children?.length ? statsJson.children.forEach((c, index)=>{
4281
+ hasErrors || (isMultiCompiler && stats.children?.length ? stats.children.forEach((c, index)=>{
4288
4282
  printTime(c, index);
4289
- }) : printTime(statsJson, 0));
4290
- let { message, level } = formatStats(statsJson, hasErrors);
4283
+ }) : printTime(stats, 0));
4284
+ let { message, level } = formatStats(stats, hasErrors);
4291
4285
  'error' === level && logger.error(message), 'warning' === level && logger.warn(message), isCompiling = !1;
4292
4286
  }), 'dev' === context.action && registerDevHook({
4293
4287
  context,
@@ -4330,7 +4324,7 @@ let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOption
4330
4324
  let { stats } = await new Promise((resolve, reject)=>{
4331
4325
  compiler.run((err, stats)=>{
4332
4326
  compiler.close((closeErr)=>{
4333
- closeErr && logger.error('Failed to close compiler: ', closeErr), err ? reject(err) : stats?.hasErrors() ? reject(Error(RSPACK_BUILD_ERROR)) : resolve({
4327
+ closeErr && logger.error('Failed to close compiler: ', closeErr), err ? reject(err) : context.buildState.hasErrors ? reject(Error(RSPACK_BUILD_ERROR)) : resolve({
4334
4328
  stats
4335
4329
  });
4336
4330
  });
@@ -4346,7 +4340,7 @@ let DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\
4346
4340
  function loadEnv({ cwd = process.cwd(), mode = process.env.NODE_ENV || '', prefixes = [
4347
4341
  'PUBLIC_'
4348
4342
  ], processEnv = process.env } = {}) {
4349
- if ('local' === mode) throw Error(`${picocolors.dim('[rsbuild:loadEnv]')} ${picocolors.yellow('local')} cannot be used as a value for env mode, because ${picocolors.yellow('.env.local')} represents a temporary local file. Please use another value.`);
4343
+ if ('local' === mode) throw Error(`${color.dim('[rsbuild:loadEnv]')} ${color.yellow('local')} cannot be used as a value for env mode, because ${color.yellow('.env.local')} represents a temporary local file. Please use another value.`);
4350
4344
  let filePaths = [
4351
4345
  '.env',
4352
4346
  '.env.local',
@@ -4458,7 +4452,7 @@ let addTrailingSep = (dir)=>dir.endsWith(external_node_path_.sep) ? dir : dir +
4458
4452
  ...userOptions
4459
4453
  };
4460
4454
  };
4461
- var postcss_load_config_src = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.0_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/index.js"), src_default = __webpack_require__.n(postcss_load_config_src);
4455
+ var postcss_load_config_src = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.0/node_modules/postcss-load-config/src/index.js"), src_default = __webpack_require__.n(postcss_load_config_src);
4462
4456
  let parseMinifyOptions = (config)=>{
4463
4457
  let isProd = 'production' === config.mode, { minify } = config.output;
4464
4458
  if ('boolean' == typeof minify) {
@@ -4522,7 +4516,7 @@ let getPostcssLoaderOptions = async ({ config, root, postcssrcCache })=>{
4522
4516
  if ('function' == typeof postcssOptions) {
4523
4517
  let postcssOptionsWrapper = (loaderContext)=>{
4524
4518
  let options = postcssOptions(loaderContext);
4525
- if ('object' != typeof options || null === options) throw Error(`${picocolors.dim('[rsbuild:css]')} \`postcssOptions\` function must return a PostCSSOptions object, got ${picocolors.yellow(typeof options)}.`);
4519
+ if ('object' != typeof options || null === options) throw Error(`${color.dim('[rsbuild:css]')} \`postcssOptions\` function must return a PostCSSOptions object, got ${color.yellow(typeof options)}.`);
4526
4520
  return updatePostcssOptions({
4527
4521
  ...userOptions,
4528
4522
  ...options,
@@ -4543,10 +4537,10 @@ async function gzipSize(input) {
4543
4537
  let data = await fileSize_gzip(input);
4544
4538
  return Buffer.byteLength(data);
4545
4539
  }
4546
- let EXCLUDE_ASSET_REGEX = /\.(?:map|LICENSE\.txt|d\.ts)$/, excludeAsset = (asset)=>EXCLUDE_ASSET_REGEX.test(asset.name), getAssetColor = (size)=>size > 300000 ? picocolors.red : size > 100000 ? picocolors.yellow : picocolors.green, calcFileSize = (len)=>{
4540
+ let EXCLUDE_ASSET_REGEX = /\.(?:map|LICENSE\.txt|d\.ts)$/, excludeAsset = (asset)=>EXCLUDE_ASSET_REGEX.test(asset.name), getAssetColor = (size)=>size > 300000 ? color.red : size > 100000 ? color.yellow : color.green, calcFileSize = (len)=>{
4547
4541
  let val = len / 1000;
4548
4542
  return `${val.toFixed(val < 1 ? 2 : 1)} kB`;
4549
- }, coloringAssetName = (assetName)=>JS_REGEX.test(assetName) ? picocolors.cyan(assetName) : assetName.endsWith('.css') ? picocolors.yellow(assetName) : assetName.endsWith('.html') ? picocolors.green(assetName) : picocolors.magenta(assetName), COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i;
4543
+ }, coloringAssetName = (assetName)=>JS_REGEX.test(assetName) ? color.cyan(assetName) : assetName.endsWith('.css') ? color.yellow(assetName) : assetName.endsWith('.html') ? color.green(assetName) : color.magenta(assetName), COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i;
4550
4544
  async function printFileSizes(options, stats, rootPath, distPath, environmentName) {
4551
4545
  let logs = [], showDetail = !1 !== options.detail, showTotal = !1 !== options.total;
4552
4546
  if (!showTotal && !showDetail) return logs;
@@ -4589,10 +4583,10 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
4589
4583
  ], showGzipHeader && rowTypes.push('Gzip'), headerRow = rowTypes.reduce((prev, cur, index)=>{
4590
4584
  let length = lengths[index], curLabel = cur;
4591
4585
  return length && (curLabel = cur.length < length ? cur + ' '.repeat(length - cur.length) : cur), `${prev + curLabel} `;
4592
- }, ''), picocolors.blue(headerRow))), assets)){
4586
+ }, ''), color.blue(headerRow))), assets)){
4593
4587
  let { sizeLabel } = asset, { name, folder, gzipSizeLabel } = asset, fileNameLength = (folder + external_node_path_.default.sep + name).length, sizeLength = sizeLabel.length;
4594
4588
  sizeLength < maxSizeLength && (sizeLabel += ' '.repeat(maxSizeLength - sizeLength));
4595
- let fileNameLabel = picocolors.dim(asset.folder + external_node_path_.default.sep) + coloringAssetName(asset.name);
4589
+ let fileNameLabel = color.dim(asset.folder + external_node_path_.default.sep) + coloringAssetName(asset.name);
4596
4590
  fileNameLength < maxFileLength && (fileNameLabel += ' '.repeat(maxFileLength - fileNameLength));
4597
4591
  let log = `${fileNameLabel} ${sizeLabel}`;
4598
4592
  gzipSizeLabel && (log += ` ${gzipSizeLabel}`), logs.push(log);
@@ -4603,7 +4597,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
4603
4597
  if (customTotal) logs.push(customTotal);
4604
4598
  else {
4605
4599
  let log = '';
4606
- if (log += ' '.repeat(maxFileLength - totalSizeLabel.length), log += picocolors.magenta(totalSizeLabel), log += ` ${totalSizeStr}`, options.compressed) {
4600
+ if (log += ' '.repeat(maxFileLength - totalSizeLabel.length), log += color.magenta(totalSizeLabel), log += ` ${totalSizeStr}`, options.compressed) {
4607
4601
  let colorFn = getAssetColor(totalGzipSize / assets.length);
4608
4602
  log += ' '.repeat(maxSizeLength - totalSizeStr.length), log += ` ${colorFn(calcFileSize(totalGzipSize))}`;
4609
4603
  }
@@ -4614,8 +4608,8 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
4614
4608
  let customTotal = getCustomTotal();
4615
4609
  if (customTotal) logs.push(customTotal);
4616
4610
  else {
4617
- let log = `${picocolors.magenta(totalSizeLabel)} ${totalSizeStr}`;
4618
- options.compressed && (log += picocolors.green(` (${calcFileSize(totalGzipSize)} gzipped)`)), logs.push(log);
4611
+ let log = `${color.magenta(totalSizeLabel)} ${totalSizeStr}`;
4612
+ options.compressed && (log += color.green(` (${calcFileSize(totalGzipSize)} gzipped)`)), logs.push(log);
4619
4613
  }
4620
4614
  }
4621
4615
  return logs.push(''), logs;
@@ -4677,12 +4671,12 @@ class RsbuildHtmlPlugin {
4677
4671
  let emitFavicon = async ({ compilation, favicon, faviconDistPath })=>{
4678
4672
  let buffer, name = external_node_path_.default.basename(favicon);
4679
4673
  if (compilation.assets[name]) return name;
4680
- if (!compilation.inputFileSystem) return addCompilationError(compilation, `${picocolors.dim('[rsbuild:html]')} Failed to read the favicon file as ${picocolors.yellow('compilation.inputFileSystem')} is not available.`), null;
4674
+ if (!compilation.inputFileSystem) return addCompilationError(compilation, `${color.dim('[rsbuild:html]')} Failed to read the favicon file as ${color.yellow('compilation.inputFileSystem')} is not available.`), null;
4681
4675
  let inputFilename = external_node_path_.default.isAbsolute(favicon) ? favicon : external_node_path_.default.join(compilation.compiler.context, favicon);
4682
4676
  try {
4683
4677
  if (!(buffer = await external_node_util_promisify(compilation.inputFileSystem.readFile)(inputFilename))) throw Error('Buffer is undefined');
4684
4678
  } catch (error) {
4685
- return logger.debug(`read favicon error: ${error}`), addCompilationError(compilation, `${picocolors.dim('[rsbuild:html]')} Failed to read the favicon file at ${picocolors.yellow(inputFilename)}.`), null;
4679
+ return logger.debug(`read favicon error: ${error}`), addCompilationError(compilation, `${color.dim('[rsbuild:html]')} Failed to read the favicon file at ${color.yellow(inputFilename)}.`), null;
4686
4680
  }
4687
4681
  let source = new compiler.webpack.sources.RawSource(buffer, !1), outputFilename = external_node_path_.default.posix.join(faviconDistPath, name);
4688
4682
  return compilation.emitAsset(outputFilename, source), outputFilename;
@@ -4834,7 +4828,7 @@ async function getTemplate(entryName, config, rootPath) {
4834
4828
  }
4835
4829
  let absolutePath = (0, external_node_path_.isAbsolute)(templatePath) ? templatePath : external_node_path_.default.join(rootPath, templatePath);
4836
4830
  if (!existTemplatePath.has(absolutePath)) {
4837
- if (!await isFileExists(absolutePath)) throw Error(`${picocolors.dim('[rsbuild:html]')} Failed to resolve HTML template, check if the file exists: ${picocolors.yellow(absolutePath)}`);
4831
+ if (!await isFileExists(absolutePath)) throw Error(`${color.dim('[rsbuild:html]')} Failed to resolve HTML template, check if the file exists: ${color.yellow(absolutePath)}`);
4838
4832
  existTemplatePath.add(absolutePath);
4839
4833
  }
4840
4834
  let templateContent = await node_fs.promises.readFile(absolutePath, 'utf-8');
@@ -5227,7 +5221,7 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
5227
5221
  protocol
5228
5222
  });
5229
5223
  if (!newUrls) return null;
5230
- if (!Array.isArray(newUrls)) throw Error(`${picocolors.dim('[rsbuild:config]')} "server.printUrls" must return an array, but got ${typeof newUrls}.`);
5224
+ if (!Array.isArray(newUrls)) throw Error(`${color.dim('[rsbuild:config]')} "server.printUrls" must return an array, but got ${typeof newUrls}.`);
5231
5225
  urls = newUrls.map((url)=>({
5232
5226
  url,
5233
5227
  label: getUrlLabel(url)
@@ -5238,13 +5232,13 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
5238
5232
  if (routes.length <= 1) {
5239
5233
  let pathname = routes.length ? routes[0].pathname : '';
5240
5234
  return urls.map(({ label, url })=>{
5241
- let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `➜ ${picocolors.dim(label.padEnd(10))}`;
5242
- return ` ${prefix}${picocolors.cyan(normalizedPathname)}\n`;
5235
+ let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `➜ ${color.dim(label.padEnd(10))}`;
5236
+ return ` ${prefix}${color.cyan(normalizedPathname)}\n`;
5243
5237
  }).join('');
5244
5238
  }
5245
5239
  let message = '', maxNameLength = Math.max(...routes.map((r)=>r.entryName.length));
5246
5240
  return urls.forEach(({ label, url }, index)=>{
5247
- for (let r of (index > 0 && (message += '\n'), message += ` ➜ ${label}\n`, routes))message += ` ${picocolors.dim('-')} ${picocolors.dim(r.entryName.padEnd(maxNameLength + 4))}${picocolors.cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
5241
+ for (let r of (index > 0 && (message += '\n'), message += ` ➜ ${label}\n`, routes))message += ` ${color.dim('-')} ${color.dim(r.entryName.padEnd(maxNameLength + 4))}${color.cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
5248
5242
  }), message;
5249
5243
  }(urls, routes);
5250
5244
  return !trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
@@ -5266,14 +5260,14 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
5266
5260
  if ('EADDRINUSE' !== e.code) throw e;
5267
5261
  port++, attempts++;
5268
5262
  }
5269
- if (port !== original && strictPort) throw Error(`${picocolors.dim('[rsbuild:server]')} Port ${picocolors.yellow(original)} is occupied, please choose another one.`);
5263
+ if (port !== original && strictPort) throw Error(`${color.dim('[rsbuild:server]')} Port ${color.yellow(original)} is occupied, please choose another one.`);
5270
5264
  return port;
5271
5265
  }, getServerConfig = async ({ config })=>{
5272
5266
  let { host, port: originalPort, strictPort } = config.server, port = await getPort({
5273
5267
  host,
5274
5268
  port: originalPort,
5275
5269
  strictPort
5276
- }), https = !!config.server.https, portTip = port !== originalPort ? `port ${originalPort} is in use, ${picocolors.yellow(`using port ${port}.`)}` : void 0;
5270
+ }), https = !!config.server.https, portTip = port !== originalPort ? `port ${originalPort} is in use, ${color.yellow(`using port ${port}.`)}` : void 0;
5277
5271
  return {
5278
5272
  port,
5279
5273
  host,
@@ -5425,7 +5419,7 @@ async function server_open_open({ https, port, routes, config, clearCache }) {
5425
5419
  try {
5426
5420
  return new URL(str, base).href;
5427
5421
  } catch {
5428
- throw Error(`${picocolors.dim('[rsbuild:open]')} Invalid input: ${picocolors.yellow(str)} is not a valid URL or pathname`);
5422
+ throw Error(`${color.dim('[rsbuild:open]')} Invalid input: ${color.yellow(str)} is not a valid URL or pathname`);
5429
5423
  }
5430
5424
  })(replacePortPlaceholder(target, port), baseUrl))) : routes.length && urls.push(`${baseUrl}${routes[0].pathname}`), before && await before(), urls))openedURLs.includes(url) || (openBrowser(url), openedURLs.push(url));
5431
5425
  }
@@ -5723,7 +5717,7 @@ async function resolveHostname(host = 'localhost') {
5723
5717
  }
5724
5718
  var on_finished = __webpack_require__("../../node_modules/.pnpm/on-finished@2.4.1/node_modules/on-finished/index.js"), on_finished_default = __webpack_require__.n(on_finished), range_parser = __webpack_require__("../../node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js"), range_parser_default = __webpack_require__.n(range_parser);
5725
5719
  let matchHtmlRegExp = /["'&<>]/, UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
5726
- function getFileFromUrl(url, outputFileSystem, environments) {
5720
+ async function getFileFromUrl(url, outputFileSystem, environments) {
5727
5721
  let pathname;
5728
5722
  try {
5729
5723
  let urlObject = new URL(url, 'http://localhost');
@@ -5731,38 +5725,42 @@ function getFileFromUrl(url, outputFileSystem, environments) {
5731
5725
  } catch {
5732
5726
  return;
5733
5727
  }
5734
- if (pathname) {
5735
- if (pathname.includes('\0')) return {
5736
- errorCode: 400
5737
- };
5738
- if (UP_PATH_REGEXP.test(external_node_path_.default.normalize(`./${pathname}`))) return {
5739
- errorCode: 403
5740
- };
5741
- for (let distPath of new Set(Object.values(environments).map((env)=>env.distPath))){
5742
- let fsStats, filename = external_node_path_.default.join(distPath, pathname);
5743
- try {
5744
- fsStats = outputFileSystem.statSync?.(filename);
5745
- } catch {
5746
- continue;
5747
- }
5748
- if (fsStats) {
5728
+ if (!pathname) return;
5729
+ if (pathname.includes('\0')) return {
5730
+ errorCode: 400
5731
+ };
5732
+ if (UP_PATH_REGEXP.test(external_node_path_.default.normalize(`./${pathname}`))) return {
5733
+ errorCode: 403
5734
+ };
5735
+ let distPaths = new Set(Object.values(environments).map((env)=>env.distPath)), stat = async (filename)=>new Promise((resolve, reject)=>{
5736
+ outputFileSystem.stat(filename, (err, stats)=>{
5737
+ err ? reject(err) : resolve(stats);
5738
+ });
5739
+ });
5740
+ for (let distPath of distPaths){
5741
+ let fsStats, filename = external_node_path_.default.join(distPath, pathname);
5742
+ try {
5743
+ fsStats = await stat(filename);
5744
+ } catch {
5745
+ continue;
5746
+ }
5747
+ if (fsStats) {
5748
+ if (fsStats.isFile()) return {
5749
+ filename,
5750
+ fsStats
5751
+ };
5752
+ if (fsStats.isDirectory()) {
5753
+ filename = external_node_path_.default.join(filename, 'index.html');
5754
+ try {
5755
+ fsStats = await stat(filename);
5756
+ } catch {
5757
+ continue;
5758
+ }
5759
+ if (!fsStats) continue;
5749
5760
  if (fsStats.isFile()) return {
5750
5761
  filename,
5751
5762
  fsStats
5752
5763
  };
5753
- if (fsStats.isDirectory()) {
5754
- filename = external_node_path_.default.join(filename, 'index.html');
5755
- try {
5756
- fsStats = outputFileSystem.statSync?.(filename);
5757
- } catch {
5758
- continue;
5759
- }
5760
- if (!fsStats) continue;
5761
- if (fsStats.isFile()) return {
5762
- filename,
5763
- fsStats
5764
- };
5765
- }
5766
5764
  }
5767
5765
  }
5768
5766
  }
@@ -5781,10 +5779,6 @@ function parseTokenList(str) {
5781
5779
  }
5782
5780
  return start !== end && list.push(str.substring(start, end)), list;
5783
5781
  }
5784
- async function getContentType(str) {
5785
- let { lookup } = await import("../compiled/mrmime/index.js"), mime = lookup(str);
5786
- return !!mime && ((mime.startsWith('text/') || 'application/json' === mime || 'application/manifest+json' === mime) && (mime += '; charset=utf-8'), mime);
5787
- }
5788
5782
  let BYTES_RANGE_REGEXP = /^ *bytes/i;
5789
5783
  function getValueContentRangeHeader(type, size, range) {
5790
5784
  return `${type} ${range ? `${range.start}-${range.end}` : '*'}:${size}`.replace(':', '/');
@@ -5816,15 +5810,7 @@ let CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/, statuses =
5816
5810
  }), acceptedMethods = [
5817
5811
  'GET',
5818
5812
  'HEAD'
5819
- ];
5820
- async function setupOutputFileSystem(writeToDisk, compilers) {
5821
- if (!0 !== writeToDisk) {
5822
- let { createFsFromVolume, Volume } = await import("../compiled/memfs/index.js"), outputFileSystem = createFsFromVolume(new Volume());
5823
- for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
5824
- }
5825
- return compilers[0].outputFileSystem;
5826
- }
5827
- let noop = ()=>{}, assets_middleware_require = (0, external_node_module_.createRequire)(import.meta.url), assetsMiddleware = async ({ config, compiler, context, socketServer, resolvedPort })=>{
5813
+ ], noop = ()=>{}, assets_middleware_require = (0, external_node_module_.createRequire)(import.meta.url), isTsError = (error)=>'message' in error && error.stack?.includes('ts-checker-rspack-plugin'), assetsMiddleware = async ({ config, compiler, context, socketServer, resolvedPort })=>{
5828
5814
  var config1, ready;
5829
5815
  let watching, writeToDiskValues, resolvedHost = await resolveHostname(config.server.host), { environments } = context;
5830
5816
  applyToCompiler(compiler, (compiler, index)=>{
@@ -5859,24 +5845,43 @@ let noop = ()=>{}, assets_middleware_require = (0, external_node_module_.createR
5859
5845
  compiler,
5860
5846
  resolvedHost,
5861
5847
  resolvedPort
5862
- }), (({ compiler, token, socketServer })=>{
5863
- ((compiler)=>{
5848
+ }), (({ context, compiler, token, socketServer })=>{
5849
+ if (((compiler)=>{
5864
5850
  let { target } = compiler.options;
5865
5851
  return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
5866
- })(compiler) || (compiler.hooks.invalid.tap('rsbuild-dev-server', (fileName)=>{
5867
- if ('string' == typeof fileName && fileName.endsWith('.html')) return void socketServer.sockWrite({
5852
+ })(compiler)) return;
5853
+ let errorsCount = null;
5854
+ compiler.hooks.invalid.tap('rsbuild-dev-server', (fileName)=>{
5855
+ errorsCount = null, 'string' == typeof fileName && fileName.endsWith('.html') && socketServer.sockWrite({
5868
5856
  type: 'static-changed'
5869
5857
  }, token);
5870
5858
  }), compiler.hooks.done.tap('rsbuild-dev-server', (stats)=>{
5871
- socketServer.onBuildDone(stats, token);
5872
- }));
5859
+ let { errors } = stats.compilation;
5860
+ if (errors.length === errorsCount) return;
5861
+ let isRecalled = null !== errorsCount;
5862
+ if (errorsCount = errors.length, isRecalled) {
5863
+ let tsErrors = errors.filter(isTsError);
5864
+ if (!tsErrors.length) return;
5865
+ let { stats: statsJson } = context.buildState, statsErrors = tsErrors.map((item)=>pick(item, [
5866
+ 'message',
5867
+ 'file'
5868
+ ]));
5869
+ statsJson && (statsJson.errors = statsJson.errors ? [
5870
+ ...statsJson.errors,
5871
+ ...statsErrors
5872
+ ] : statsErrors), socketServer.sendError(statsErrors, token);
5873
+ return;
5874
+ }
5875
+ socketServer.onBuildDone(token);
5876
+ });
5873
5877
  })({
5878
+ context,
5874
5879
  compiler,
5875
5880
  socketServer,
5876
5881
  token
5877
5882
  }));
5878
5883
  });
5879
- let compilers = helpers_isMultiCompiler(compiler) ? compiler.compilers : [
5884
+ let compilers = compiler_isMultiCompiler(compiler) ? compiler.compilers : [
5880
5885
  compiler
5881
5886
  ], callbacks = [];
5882
5887
  compiler.hooks.done.tap('rsbuild-dev-middleware', ()=>{
@@ -5914,7 +5919,13 @@ let noop = ()=>{}, assets_middleware_require = (0, external_node_module_.createR
5914
5919
  }), compiler.__hasRsbuildAssetEmittedCallback = !0);
5915
5920
  });
5916
5921
  }(compilers, writeToDisk);
5917
- let outputFileSystem = await setupOutputFileSystem(writeToDisk, compilers), instance = (ready = (callback)=>{
5922
+ let outputFileSystem = function(writeToDisk, compilers) {
5923
+ if (!0 !== writeToDisk) {
5924
+ let { createFsFromVolume, Volume } = requireCompiledPackage('memfs'), outputFileSystem = createFsFromVolume(new Volume());
5925
+ for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
5926
+ }
5927
+ return compilers[0].outputFileSystem;
5928
+ }(writeToDisk, compilers), instance = (ready = (callback)=>{
5918
5929
  'done' === context.buildState.status ? callback() : callbacks.push(callback);
5919
5930
  }, async function(req, res, next) {
5920
5931
  let { environments } = context;
@@ -5971,7 +5982,7 @@ let noop = ()=>{}, assets_middleware_require = (0, external_node_module_.createR
5971
5982
  var range, offset;
5972
5983
  let bufferOrStream, byteLength, end;
5973
5984
  if (!req.url) return void await goNext();
5974
- let resolved = getFileFromUrl(req.url, outputFileSystem, environments);
5985
+ let resolved = await getFileFromUrl(req.url, outputFileSystem, environments);
5975
5986
  if (!resolved) return void await goNext();
5976
5987
  if ('errorCode' in resolved) {
5977
5988
  403 === resolved.errorCode && logger.error(`[rsbuild:middleware] Malicious path "${req.url}".`), sendError(resolved.errorCode);
@@ -5979,7 +5990,10 @@ let noop = ()=>{}, assets_middleware_require = (0, external_node_module_.createR
5979
5990
  }
5980
5991
  let { fsStats, filename } = resolved, { size } = fsStats, len = size, offset1 = 0;
5981
5992
  if (!res.getHeader('Content-Type')) {
5982
- let contentType = await getContentType(filename);
5993
+ let contentType = function(str) {
5994
+ let { lookup } = requireCompiledPackage('mrmime'), mime = lookup(str);
5995
+ return !!mime && ((mime.startsWith('text/') || 'application/json' === mime || 'application/manifest+json' === mime) && (mime += '; charset=utf-8'), mime);
5996
+ }(filename);
5983
5997
  contentType && res.setHeader('Content-Type', contentType);
5984
5998
  }
5985
5999
  res.getHeader('Accept-Ranges') || res.setHeader('Accept-Ranges', 'bytes');
@@ -6116,13 +6130,6 @@ let noop = ()=>{}, assets_middleware_require = (0, external_node_module_.createR
6116
6130
  }, instance;
6117
6131
  };
6118
6132
  var UNKNOWN_FUNCTION = '<unknown>', chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i, chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/, winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i, geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i, geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i, javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i, nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
6119
- async function mapSourceMapPosition(rawSourceMap, line, column) {
6120
- let { default: { TraceMap, originalPositionFor } } = await import("../compiled/@jridgewell/trace-mapping/index.js");
6121
- return originalPositionFor(new TraceMap(rawSourceMap), {
6122
- line,
6123
- column
6124
- });
6125
- }
6126
6133
  let resolveSourceLocation = async (stack, fs, environments)=>{
6127
6134
  let parsed = stack.split('\n').reduce(function(stack, line) {
6128
6135
  var line1, parts, line2, parts1, line3, parts2, parseResult = function(line) {
@@ -6173,12 +6180,18 @@ let resolveSourceLocation = async (stack, fs, environments)=>{
6173
6180
  if (!parsed.length) return;
6174
6181
  let frame = parsed.find((frame)=>null !== frame.file && null !== frame.column && null !== frame.lineNumber && SCRIPT_REGEX.test(frame.file));
6175
6182
  if (!frame) return;
6176
- let { file, column, lineNumber } = frame, sourceMapInfo = getFileFromUrl(`${file}.map`, fs, environments);
6183
+ let { file, column, lineNumber } = frame, sourceMapInfo = await getFileFromUrl(`${file}.map`, fs, environments);
6177
6184
  if (!sourceMapInfo || 'errorCode' in sourceMapInfo) return;
6178
6185
  let readFile = external_node_util_promisify(fs.readFile);
6179
6186
  try {
6180
6187
  let sourceMap = await readFile(sourceMapInfo.filename);
6181
- if (sourceMap) return await mapSourceMapPosition(sourceMap.toString(), lineNumber, column);
6188
+ if (sourceMap) return function(rawSourceMap, line, column) {
6189
+ let { TraceMap, originalPositionFor } = requireCompiledPackage('@jridgewell/trace-mapping');
6190
+ return originalPositionFor(new TraceMap(rawSourceMap), {
6191
+ line,
6192
+ column
6193
+ });
6194
+ }(sourceMap.toString(), lineNumber, column);
6182
6195
  } catch (error) {
6183
6196
  error instanceof Error && logger.debug(`failed to map source map position: ${error.message}`);
6184
6197
  }
@@ -6190,10 +6203,10 @@ let resolveSourceLocation = async (stack, fs, environments)=>{
6190
6203
  let rawLocation = external_node_path_.default.relative(context.rootPath, source);
6191
6204
  return null !== line && (rawLocation += null === column ? `:${line}` : `:${line}:${column}`), rawLocation;
6192
6205
  }, formatBrowserErrorLog = async (message, context, fs)=>{
6193
- let log = `${picocolors.cyan('[browser]')} ${picocolors.red(message.message)}`;
6206
+ let log = `${color.cyan('[browser]')} ${color.red(message.message)}`;
6194
6207
  if (message.stack) {
6195
6208
  let rawLocation = await formatErrorLocation(message.stack, context, fs);
6196
- rawLocation && (log += picocolors.dim(` (${rawLocation})`));
6209
+ rawLocation && (log += color.dim(` (${rawLocation})`));
6197
6210
  }
6198
6211
  return log;
6199
6212
  }, styles = {
@@ -6234,13 +6247,13 @@ class SocketServer {
6234
6247
  socketsMap = new Map();
6235
6248
  options;
6236
6249
  context;
6237
- stats;
6238
- initialChunks;
6250
+ initialChunksMap = new Map();
6239
6251
  heartbeatTimer = null;
6240
6252
  getOutputFileSystem;
6241
6253
  reportedBrowserLogs = new Set();
6254
+ currentHash = new Map();
6242
6255
  constructor(context, options, getOutputFileSystem){
6243
- this.options = options, this.stats = {}, this.initialChunks = {}, this.context = context, this.getOutputFileSystem = getOutputFileSystem;
6256
+ this.context = context, this.options = options, this.getOutputFileSystem = getOutputFileSystem;
6244
6257
  }
6245
6258
  upgrade = (req, socket, head)=>{
6246
6259
  if (!this.wsServer.shouldHandle(req)) return;
@@ -6251,136 +6264,51 @@ class SocketServer {
6251
6264
  };
6252
6265
  checkSockets = ()=>{
6253
6266
  for (let socket of this.wsServer.clients)socket.isAlive ? (socket.isAlive = !1, socket.ping(()=>{})) : socket.terminate();
6254
- null !== this.heartbeatTimer && (this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref());
6255
- };
6256
- clearHeartbeatTimer() {
6257
- this.heartbeatTimer && (clearTimeout(this.heartbeatTimer), this.heartbeatTimer = null);
6258
- }
6259
- async prepare() {
6260
- this.clearHeartbeatTimer();
6261
- let { default: ws } = await import("../compiled/ws/index.js");
6262
- this.wsServer = new ws.Server({
6263
- noServer: !0,
6264
- path: this.options.client?.path
6265
- }), this.wsServer.on('error', (err)=>{
6266
- logger.error(err);
6267
- }), this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref(), this.wsServer.on('connection', (socket, req)=>{
6268
- let query = parseQueryString(req);
6269
- this.onConnect(socket, query.token);
6270
- });
6271
- }
6272
- onBuildDone(stats, token) {
6273
- this.stats[token] = stats, this.reportedBrowserLogs.clear(), this.socketsMap.size && this.sendStats({
6274
- token
6275
- });
6276
- }
6277
- sockWrite(message, token) {
6278
- let messageStr = JSON.stringify(message), sendToSockets = (sockets)=>{
6279
- for (let socket of sockets)this.send(socket, messageStr);
6280
- };
6281
- if (token) {
6282
- let sockets = this.socketsMap.get(token);
6283
- sockets && sendToSockets(sockets);
6284
- } else for (let sockets of this.socketsMap.values())sendToSockets(sockets);
6267
+ null !== this.heartbeatTimer && (this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref());
6268
+ };
6269
+ clearHeartbeatTimer() {
6270
+ this.heartbeatTimer && (clearTimeout(this.heartbeatTimer), this.heartbeatTimer = null);
6285
6271
  }
6286
- async close() {
6287
- for (let socket of (this.clearHeartbeatTimer(), this.wsServer.removeAllListeners(), this.wsServer.clients))socket.terminate();
6288
- for (let sockets of this.socketsMap.values())sockets.forEach((socket)=>{
6289
- socket.close();
6290
- });
6291
- return this.stats = {}, this.initialChunks = {}, this.socketsMap.clear(), this.reportedBrowserLogs.clear(), new Promise((resolve, reject)=>{
6292
- this.wsServer.close((err)=>{
6293
- err ? reject(err) : resolve();
6294
- });
6272
+ prepare() {
6273
+ this.clearHeartbeatTimer();
6274
+ let ws = requireCompiledPackage('ws');
6275
+ this.wsServer = new ws.Server({
6276
+ noServer: !0,
6277
+ path: this.options.client?.path
6278
+ }), this.wsServer.on('error', (err)=>{
6279
+ logger.error(err);
6280
+ }), this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref(), this.wsServer.on('connection', (socket, req)=>{
6281
+ let query = parseQueryString(req);
6282
+ this.onConnect(socket, query.token);
6295
6283
  });
6296
6284
  }
6297
- onConnect(socket, token) {
6298
- socket.isAlive = !0, socket.on('pong', ()=>{
6299
- socket.isAlive = !0;
6300
- }), socket.on('message', async (data)=>{
6301
- try {
6302
- let message = JSON.parse('string' == typeof data ? data : data.toString());
6303
- if ('client-error' === message.type && 'rspack' === this.context.bundlerType && !this.context.buildState.hasErrors) {
6304
- let log = await formatBrowserErrorLog(message, this.context, this.getOutputFileSystem());
6305
- this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), logger.error(log));
6306
- }
6307
- } catch {}
6308
- });
6309
- let sockets = this.socketsMap.get(token);
6310
- sockets || (sockets = new Set(), this.socketsMap.set(token, sockets)), sockets.add(socket), socket.on('close', ()=>{
6311
- let sockets = this.socketsMap.get(token);
6312
- sockets && (sockets.delete(socket), 0 === sockets.size && this.socketsMap.delete(token));
6313
- }), this.stats && this.sendStats({
6314
- force: !0,
6285
+ onBuildDone(token) {
6286
+ this.reportedBrowserLogs.clear(), this.socketsMap.size && this.sendStats({
6315
6287
  token
6316
6288
  });
6317
6289
  }
6318
- getStats(name) {
6319
- let curStats = this.stats[name];
6320
- if (!curStats) return null;
6321
- let statsOptions = getStatsOptions(curStats.compilation.compiler), statsJson = curStats.toJson({
6322
- all: !1,
6323
- hash: !0,
6324
- assets: !0,
6325
- warnings: !0,
6326
- warningsCount: !0,
6327
- errors: !0,
6328
- errorsCount: !0,
6329
- errorDetails: !1,
6330
- entrypoints: !0,
6331
- children: !0,
6332
- moduleTrace: !0,
6333
- ...statsOptions
6334
- });
6335
- return statsJson ? {
6336
- statsJson,
6337
- root: curStats.compilation.compiler.options.context
6338
- } : null;
6339
- }
6340
- sendStats({ force = !1, token }) {
6341
- let result = this.getStats(token);
6342
- if (!result) return null;
6343
- let { statsJson, root } = result, newInitialChunks = new Set();
6344
- if (statsJson.entrypoints) for (let entrypoint of Object.values(statsJson.entrypoints)){
6345
- let chunks = entrypoint.chunks;
6346
- if (Array.isArray(chunks)) for (let chunkName of chunks)chunkName && newInitialChunks.add(String(chunkName));
6347
- }
6348
- let initialChunks = this.initialChunks[token], shouldReload = !!statsJson.entrypoints && !!initialChunks && !(initialChunks.size === newInitialChunks.size && [
6349
- ...initialChunks
6350
- ].every((value)=>newInitialChunks.has(value)));
6351
- if (this.initialChunks[token] = newInitialChunks, shouldReload) return void this.sockWrite({
6352
- type: 'static-changed'
6353
- }, token);
6354
- if (!force && statsJson && !statsJson.errorsCount && statsJson.assets && statsJson.assets.every((asset)=>!asset.emitted)) return void this.sockWrite({
6355
- type: 'ok'
6356
- }, token);
6357
- if (statsJson.hash && this.sockWrite({
6358
- type: 'hash',
6359
- data: statsJson.hash
6360
- }, token), statsJson.errorsCount) {
6361
- let htmlItems, { errors: formattedErrors } = formatStatsMessages({
6362
- errors: getAllStatsErrors(statsJson),
6363
- warnings: []
6364
- });
6365
- this.sockWrite({
6366
- type: 'errors',
6367
- data: {
6368
- text: formattedErrors,
6369
- html: (htmlItems = formattedErrors.map((item)=>{
6370
- var text;
6371
- let ansiCodes, ret, pathRegex, urlRegex;
6372
- return text = item ? item.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;') : '', ansiCodes = [], ret = text.replace(/\x1B\[([0-9;]+)m/g, (_match, sequences)=>{
6373
- let style = '';
6374
- for (let seq of sequences.split(';'))styles[seq] && (style += `${styles[seq]};`);
6375
- return style ? (ansiCodes.push(sequences), `<span style="${style}">`) : closeCode.includes(Number(sequences)) && ansiCodes.length > 0 ? (ansiCodes.pop(), '</span>') : '';
6376
- }), ansiCodes.length > 0 && (ret += Array(ansiCodes.length + 1).join('</span>')), pathRegex = /(?:\.\.?[/\\]|[a-zA-Z]:\\|\/)[^:]*:\d+:\d+/g, urlRegex = /(https?:\/\/(?:[\w-]+\.)+[a-z0-9](?:[\w-.~:/?#[\]@!$&'*+,;=])*)/gi, ret.split('\n').map((line)=>{
6377
- let replacedLine = line.replace(pathRegex, (file)=>{
6378
- let relativePath, hasClosingSpan = file.includes('</span>') && !file.includes('<span'), filePath = hasClosingSpan ? file.replace('</span>', '') : file, isAbsolute = external_node_path_.default.isAbsolute(filePath), absolutePath = root && !isAbsolute ? external_node_path_.default.join(root, filePath) : filePath, relativePath1 = root && isAbsolute ? '' === (relativePath = (0, external_node_path_.relative)(root, filePath)) ? `.${external_node_path_.sep}` : relativePath.startsWith('.') ? relativePath : `.${external_node_path_.sep}${relativePath}` : filePath;
6379
- return `<a class="file-link" data-file="${absolutePath}">${relativePath1}</a>${hasClosingSpan ? '</span>' : ''}`;
6380
- });
6381
- return replacedLine.replace(urlRegex, (url)=>`<a class="url-link" href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>`);
6382
- }).join('\n');
6383
- }), `
6290
+ sendError(errors, token) {
6291
+ var root;
6292
+ let htmlItems, formattedErrors = errors.map((item)=>formatStatsError(item));
6293
+ this.sockWrite({
6294
+ type: 'errors',
6295
+ data: {
6296
+ text: formattedErrors,
6297
+ html: (root = this.context.rootPath, htmlItems = formattedErrors.map((item)=>{
6298
+ var text;
6299
+ let ansiCodes, ret, pathRegex, urlRegex;
6300
+ return text = item ? item.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;') : '', ansiCodes = [], ret = text.replace(/\x1B\[([0-9;]+)m/g, (_match, sequences)=>{
6301
+ let style = '';
6302
+ for (let seq of sequences.split(';'))styles[seq] && (style += `${styles[seq]};`);
6303
+ return style ? (ansiCodes.push(sequences), `<span style="${style}">`) : closeCode.includes(Number(sequences)) && ansiCodes.length > 0 ? (ansiCodes.pop(), '</span>') : '';
6304
+ }), ansiCodes.length > 0 && (ret += Array(ansiCodes.length + 1).join('</span>')), pathRegex = /(?:\.\.?[/\\]|[a-zA-Z]:\\|\/)[^:]*:\d+:\d+/g, urlRegex = /(https?:\/\/(?:[\w-]+\.)+[a-z0-9](?:[\w-.~:/?#[\]@!$&'*+,;=])*)/gi, ret.split('\n').map((line)=>{
6305
+ let replacedLine = line.replace(pathRegex, (file)=>{
6306
+ let relativePath, hasClosingSpan = file.includes('</span>') && !file.includes('<span'), filePath = hasClosingSpan ? file.replace('</span>', '') : file, isAbsolute = external_node_path_.default.isAbsolute(filePath), absolutePath = root && !isAbsolute ? external_node_path_.default.join(root, filePath) : filePath, relativePath1 = root && isAbsolute ? '' === (relativePath = (0, external_node_path_.relative)(root, filePath)) ? `.${external_node_path_.sep}` : relativePath.startsWith('.') ? relativePath : `.${external_node_path_.sep}${relativePath}` : filePath;
6307
+ return `<a class="file-link" data-file="${absolutePath}">${relativePath1}</a>${hasClosingSpan ? '</span>' : ''}`;
6308
+ });
6309
+ return replacedLine.replace(urlRegex, (url)=>`<a class="url-link" href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>`);
6310
+ }).join('\n');
6311
+ }), `
6384
6312
  <style>
6385
6313
  .root {
6386
6314
  position: fixed;
@@ -6511,19 +6439,95 @@ class SocketServer {
6511
6439
  </div>
6512
6440
  </div>
6513
6441
  `)
6442
+ }
6443
+ }, token);
6444
+ }
6445
+ sockWrite(message, token) {
6446
+ let messageStr = JSON.stringify(message), sendToSockets = (sockets)=>{
6447
+ for (let socket of sockets)this.send(socket, messageStr);
6448
+ };
6449
+ if (token) {
6450
+ let sockets = this.socketsMap.get(token);
6451
+ sockets && sendToSockets(sockets);
6452
+ } else for (let sockets of this.socketsMap.values())sendToSockets(sockets);
6453
+ }
6454
+ async close() {
6455
+ for (let socket of (this.clearHeartbeatTimer(), this.wsServer.removeAllListeners(), this.wsServer.clients))socket.terminate();
6456
+ for (let sockets of this.socketsMap.values())sockets.forEach((socket)=>{
6457
+ socket.close();
6458
+ });
6459
+ return this.socketsMap.clear(), this.initialChunksMap.clear(), this.reportedBrowserLogs.clear(), new Promise((resolve, reject)=>{
6460
+ this.wsServer.close((err)=>{
6461
+ err ? reject(err) : resolve();
6462
+ });
6463
+ });
6464
+ }
6465
+ onConnect(socket, token) {
6466
+ socket.isAlive = !0, socket.on('pong', ()=>{
6467
+ socket.isAlive = !0;
6468
+ }), socket.on('message', async (data)=>{
6469
+ try {
6470
+ let message = JSON.parse('string' == typeof data ? data : data.toString());
6471
+ if ('client-error' === message.type && 'rspack' === this.context.bundlerType && !this.context.buildState.hasErrors) {
6472
+ let log = await formatBrowserErrorLog(message, this.context, this.getOutputFileSystem());
6473
+ this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), logger.error(log));
6514
6474
  }
6475
+ } catch {}
6476
+ });
6477
+ let sockets = this.socketsMap.get(token);
6478
+ sockets || (sockets = new Set(), this.socketsMap.set(token, sockets)), sockets.add(socket), socket.on('close', ()=>{
6479
+ let sockets = this.socketsMap.get(token);
6480
+ sockets && (sockets.delete(socket), 0 === sockets.size && this.socketsMap.delete(token));
6481
+ }), this.sendStats({
6482
+ force: !0,
6483
+ token
6484
+ });
6485
+ }
6486
+ getStats(token) {
6487
+ let { stats } = this.context.buildState, environment = Object.values(this.context.environments).find(({ webSocketToken })=>webSocketToken === token);
6488
+ if (!stats || !environment) return;
6489
+ let currentStats = stats;
6490
+ if (stats.children) {
6491
+ let childStats = stats.children[environment.index];
6492
+ childStats && (currentStats = childStats);
6493
+ }
6494
+ return {
6495
+ stats: currentStats,
6496
+ errors: getStatsErrors(stats),
6497
+ warnings: getStatsWarnings(stats)
6498
+ };
6499
+ }
6500
+ sendStats({ force = !1, token }) {
6501
+ let result = this.getStats(token);
6502
+ if (!result) return null;
6503
+ let { stats, errors, warnings } = result, newInitialChunks = new Set();
6504
+ if (stats.entrypoints) for (let entrypoint of Object.values(stats.entrypoints)){
6505
+ let { chunks } = entrypoint;
6506
+ if (Array.isArray(chunks)) for (let chunkName of chunks)chunkName && newInitialChunks.add(String(chunkName));
6507
+ }
6508
+ let initialChunks = this.initialChunksMap.get(token), shouldReload = stats.entrypoints && initialChunks && !(initialChunks.size === newInitialChunks.size && [
6509
+ ...initialChunks
6510
+ ].every((value)=>newInitialChunks.has(value)));
6511
+ if (this.initialChunksMap.set(token, newInitialChunks), shouldReload) return void this.sockWrite({
6512
+ type: 'static-changed'
6513
+ }, token);
6514
+ if (stats.hash) {
6515
+ let prevHash = this.currentHash.get(token);
6516
+ if (this.currentHash.set(token, stats.hash), !force && 0 === errors.length && 0 === warnings.length && prevHash === stats.hash) return void this.sockWrite({
6517
+ type: 'ok'
6518
+ }, token);
6519
+ this.sockWrite({
6520
+ type: 'hash',
6521
+ data: stats.hash
6515
6522
  }, token);
6516
- return;
6517
6523
  }
6518
- if (statsJson.warningsCount) {
6519
- let { warnings: formattedWarnings } = formatStatsMessages({
6520
- warnings: getAllStatsWarnings(statsJson),
6521
- errors: []
6522
- });
6524
+ if (errors.length > 0) return void this.sendError(errors, token);
6525
+ if (warnings.length > 0) {
6526
+ let warningMessages = warnings.map((item)=>formatStatsError(item));
6523
6527
  this.sockWrite({
6524
6528
  type: 'warnings',
6525
6529
  data: {
6526
- text: formattedWarnings
6530
+ text: warningMessages
6527
6531
  }
6528
6532
  }, token);
6529
6533
  return;
@@ -6549,9 +6553,9 @@ class BuildManager {
6549
6553
  this.config = config, this.context = context, this.compiler = compiler, this.publicPaths = publicPaths, this.resolvedPort = resolvedPort, this.outputFileSystem = node_fs, this.socketServer = new SocketServer(context, config.dev, ()=>this.outputFileSystem);
6550
6554
  }
6551
6555
  async init() {
6552
- await this.setupCompilationMiddleware(), await this.socketServer.prepare();
6556
+ await this.setupCompilationMiddleware(), this.socketServer.prepare();
6553
6557
  let { compiler } = this;
6554
- this.outputFileSystem = (helpers_isMultiCompiler(compiler) ? compiler.compilers[0].outputFileSystem : compiler.outputFileSystem) || node_fs;
6558
+ this.outputFileSystem = (compiler_isMultiCompiler(compiler) ? compiler.compilers[0].outputFileSystem : compiler.outputFileSystem) || node_fs;
6555
6559
  }
6556
6560
  watch() {
6557
6561
  this.middleware.watch();
@@ -6589,19 +6593,19 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
6589
6593
  let shortcuts = [
6590
6594
  {
6591
6595
  key: 'c',
6592
- description: `${picocolors.bold('c + enter')} ${picocolors.dim('clear console')}`,
6596
+ description: `${color.bold('c + enter')} ${color.dim('clear console')}`,
6593
6597
  action: ()=>{
6594
6598
  console.clear();
6595
6599
  }
6596
6600
  },
6597
6601
  {
6598
6602
  key: 'o',
6599
- description: `${picocolors.bold('o + enter')} ${picocolors.dim('open in browser')}`,
6603
+ description: `${color.bold('o + enter')} ${color.dim('open in browser')}`,
6600
6604
  action: openPage
6601
6605
  },
6602
6606
  {
6603
6607
  key: 'q',
6604
- description: `${picocolors.bold('q + enter')} ${picocolors.dim('quit process')}`,
6608
+ description: `${color.bold('q + enter')} ${color.dim('quit process')}`,
6605
6609
  action: async ()=>{
6606
6610
  try {
6607
6611
  await closeServer();
@@ -6612,23 +6616,23 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
6612
6616
  },
6613
6617
  restartServer ? {
6614
6618
  key: 'r',
6615
- description: `${picocolors.bold('r + enter')} ${picocolors.dim('restart server')}`,
6619
+ description: `${color.bold('r + enter')} ${color.dim('restart server')}`,
6616
6620
  action: restartServer
6617
6621
  } : null,
6618
6622
  {
6619
6623
  key: 'u',
6620
- description: `${picocolors.bold('u + enter')} ${picocolors.dim('show urls')}`,
6624
+ description: `${color.bold('u + enter')} ${color.dim('show urls')}`,
6621
6625
  action: printUrls
6622
6626
  }
6623
6627
  ].filter(Boolean);
6624
- if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${picocolors.dim('[rsbuild:config]')} ${picocolors.yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
6625
- help && logger.log(!0 === help ? ` ➜ ${picocolors.dim('press')} ${picocolors.bold('h + enter')} ${picocolors.dim('to show shortcuts')}\n` : ` ➜ ${help}\n`);
6628
+ if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${color.dim('[rsbuild:config]')} ${color.yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
6629
+ help && logger.log(!0 === help ? ` ➜ ${color.dim('press')} ${color.bold('h + enter')} ${color.dim('to show shortcuts')}\n` : ` ➜ ${help}\n`);
6626
6630
  let { createInterface } = await import("node:readline"), rl = createInterface({
6627
6631
  input: process.stdin
6628
6632
  });
6629
6633
  return rl.on('line', (input)=>{
6630
6634
  if ('h' === input) {
6631
- let message = `\n ${picocolors.bold(picocolors.blue('Shortcuts:'))}\n`;
6635
+ let message = `\n ${color.bold(color.blue('Shortcuts:'))}\n`;
6632
6636
  for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
6633
6637
  logger.log(message);
6634
6638
  }
@@ -6727,8 +6731,8 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6727
6731
  }, getRequestLoggerMiddleware = ()=>(req, res, next)=>{
6728
6732
  let _startAt = process.hrtime();
6729
6733
  on_finished_default()(res, ()=>{
6730
- let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = status >= 500 ? picocolors.red : status >= 400 ? picocolors.yellow : status >= 300 ? picocolors.cyan : status >= 200 ? picocolors.green : (res)=>res, endAt = process.hrtime(), totalTime = (endAt[0] - _startAt[0]) * 1e3 + (endAt[1] - _startAt[1]) * 1e-6;
6731
- logger.debug(`${statusColor(status)} ${method} ${url} ${picocolors.dim(`${totalTime.toFixed(3)} ms`)}`);
6734
+ let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = status >= 500 ? color.red : status >= 400 ? color.yellow : status >= 300 ? color.cyan : status >= 200 ? color.green : (res)=>res, endAt = process.hrtime(), totalTime = (endAt[0] - _startAt[0]) * 1e3 + (endAt[1] - _startAt[1]) * 1e-6;
6735
+ logger.debug(`${statusColor(status)} ${method} ${url} ${color.dim(`${totalTime.toFixed(3)} ms`)}`);
6732
6736
  }), next();
6733
6737
  }, notFoundMiddleware = (_req, res, _next)=>{
6734
6738
  res.statusCode = 404, res.end();
@@ -6768,7 +6772,7 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6768
6772
  res.writeHead(404, {
6769
6773
  'Content-Type': 'text/plain'
6770
6774
  }), res.end(`The server is configured with a base URL of ${base} - did you mean to visit ${redirectPath} instead?`);
6771
- }, createProxyMiddleware = async (proxyOptions)=>{
6775
+ }, createProxyMiddleware = (proxyOptions)=>{
6772
6776
  let formattedOptions = function(proxyOptions) {
6773
6777
  let ret = [];
6774
6778
  if (Array.isArray(proxyOptions)) ret.push(...proxyOptions);
@@ -6783,7 +6787,7 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6783
6787
  'string' == typeof options ? opts.target = options : Object.assign(opts, options), ret.push(opts);
6784
6788
  }
6785
6789
  return ret;
6786
- }(proxyOptions), proxyMiddlewares = [], middlewares = [], { createProxyMiddleware: baseMiddleware } = await import("../compiled/http-proxy-middleware/index.js");
6790
+ }(proxyOptions), proxyMiddlewares = [], middlewares = [], { createProxyMiddleware: baseMiddleware } = requireCompiledPackage('http-proxy-middleware');
6787
6791
  for (let opts of formattedOptions){
6788
6792
  let { onProxyRes } = opts;
6789
6793
  opts.onProxyRes = (proxyRes, _req, res)=>{
@@ -6803,169 +6807,6 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6803
6807
  for (let middleware of proxyMiddlewares)'function' == typeof middleware.upgrade && middleware.upgrade(req, socket, head);
6804
6808
  }
6805
6809
  };
6806
- }, applyDefaultMiddlewares = async ({ config, buildManager, context, devServerAPI, middlewares, pwd, postCallbacks })=>{
6807
- let upgradeEvents = [], { server } = config;
6808
- if (server.cors) {
6809
- let { default: corsMiddleware } = await import("../compiled/cors/index.js");
6810
- middlewares.push(corsMiddleware('boolean' == typeof server.cors ? {} : server.cors));
6811
- }
6812
- let { headers } = server;
6813
- if (headers && middlewares.push((_req, res, next)=>{
6814
- for (let [key, value] of Object.entries(headers))res.setHeader(key, value);
6815
- next();
6816
- }), server.proxy) {
6817
- let { middlewares: proxyMiddlewares, upgrade } = await createProxyMiddleware(server.proxy);
6818
- for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.push(middleware);
6819
- }
6820
- let { compress } = server;
6821
- if (compress && middlewares.push(gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && 'rspack' === context.bundlerType && buildManager) {
6822
- let { compiler } = buildManager;
6823
- (helpers_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.experiments?.lazyCompilation || childCompiler.options.lazyCompilation) : compiler.options.experiments?.lazyCompilation || compiler.options.lazyCompilation) && middlewares.push(rspack_rspack.experiments.lazyCompilationMiddleware(compiler));
6824
- }
6825
- server.base && '/' !== server.base && middlewares.push(getBaseMiddleware({
6826
- base: server.base
6827
- }));
6828
- let { default: launchEditorMiddleware } = await import("../compiled/launch-editor-middleware/index.js");
6829
- for (let publicDir of (middlewares.push([
6830
- '/__open-in-editor',
6831
- launchEditorMiddleware()
6832
- ]), middlewares.push((({ environments })=>async (req, res, next)=>{
6833
- if ('/rsbuild-dev-server' !== req.url.replace(postfixRE, '')) return void next();
6834
- res.writeHead(200, {
6835
- 'Content-Type': 'text/html; charset=utf-8'
6836
- }), res.write(`<!DOCTYPE html>
6837
- <html>
6838
- <head>
6839
- <meta charset="utf-8"/>
6840
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6841
- <style>
6842
- body {
6843
- margin: 0;
6844
- color: #f6f7f9;
6845
- padding: 32px 40px;
6846
- line-height: 1.8;
6847
- min-height: 100vh;
6848
- background-image: linear-gradient(#020917, #101725);
6849
- font-family: ui-sans-serif,system-ui,sans-serif;
6850
- }
6851
- h1, h2 {
6852
- font-weight: 500;
6853
- }
6854
- h1 {
6855
- margin: 0;
6856
- font-size: 36px;
6857
- }
6858
- h2 {
6859
- font-size: 20px;
6860
- margin: 24px 0 16px;
6861
- }
6862
- ul {
6863
- margin: 0;
6864
- padding-left: 16px;
6865
- }
6866
- a {
6867
- color: #58c4dc;
6868
- text-decoration: none;
6869
- }
6870
- a:hover {
6871
- text-decoration: underline;
6872
- }
6873
- </style>
6874
- </head>
6875
- <body>
6876
- <h1>Assets Report</h1>
6877
- </body>
6878
- </html>`);
6879
- try {
6880
- for(let key in environments){
6881
- res.write(`<h2>Environment: ${key}</h2>`);
6882
- let list = [], environment = environments[key], stats = await environment.getStats(), assets = getAssetsFromStats(stats);
6883
- for (let asset of (res.write('<ul>'), assets))list.push(`<li><a target="_blank" href="${asset?.name}">${asset?.name}</a></li>`);
6884
- res.write(list?.join('')), res.write('</ul>');
6885
- }
6886
- res.end('</body></html>');
6887
- } catch (err) {
6888
- logger.error(err), res.writeHead(500), res.end('Failed to list the files');
6889
- }
6890
- })({
6891
- environments: devServerAPI.environments
6892
- })), buildManager && (middlewares.push(buildManager.middleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.push((req, res, next)=>{
6893
- req.url?.endsWith('.hot-update.json') && 'OPTIONS' !== req.method ? (res.statusCode = 404, res.end()) : next();
6894
- })), buildManager && middlewares.push((({ distPath, buildManager })=>async (req, res, next)=>{
6895
- if (!maybeHTMLRequest(req)) return void next();
6896
- let pathname = req.url.replace(postfixRE, ''), rewrite = (newUrl)=>{
6897
- req.url = newUrl, buildManager.middleware(req, res, (...args)=>{
6898
- next(...args);
6899
- });
6900
- };
6901
- if (pathname.endsWith('/')) {
6902
- let newUrl = `${pathname}index.html`, filePath = external_node_path_.default.join(distPath, newUrl);
6903
- if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
6904
- } else if (!external_node_path_.default.extname(pathname)) {
6905
- let newUrl = `${pathname}.html`, filePath = external_node_path_.default.join(distPath, newUrl);
6906
- if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
6907
- }
6908
- next();
6909
- })({
6910
- buildManager,
6911
- distPath: context.distPath
6912
- })), normalizePublicDirs(server?.publicDir))){
6913
- let { default: sirv } = await import("../compiled/sirv/index.js"), { name } = publicDir, assetMiddleware = sirv((0, external_node_path_.isAbsolute)(name) ? name : (0, external_node_path_.join)(pwd, name), {
6914
- etag: !0,
6915
- dev: !0
6916
- });
6917
- middlewares.push(assetMiddleware);
6918
- }
6919
- for (let callback of postCallbacks)callback();
6920
- return buildManager && middlewares.push((({ htmlFallback, distPath, buildManager })=>async (req, res, next)=>{
6921
- if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url || 'index' !== htmlFallback) return void next();
6922
- let filePath = external_node_path_.default.join(distPath, 'index.html');
6923
- if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) {
6924
- let newUrl = '/index.html';
6925
- 'verbose' === logger.level && logger.debug(` ${req.method} ${req.url} ${picocolors.yellow('fallback to')} ${newUrl}`), req.url = newUrl, buildManager.middleware(req, res, (...args)=>{
6926
- next(...args);
6927
- });
6928
- return;
6929
- }
6930
- next();
6931
- })({
6932
- buildManager,
6933
- distPath: context.distPath,
6934
- htmlFallback: server.htmlFallback
6935
- })), server.historyApiFallback && (middlewares.push(historyApiFallbackMiddleware(!0 === server.historyApiFallback ? {} : server.historyApiFallback)), buildManager?.middleware && middlewares.push(buildManager.middleware)), middlewares.push(faviconFallbackMiddleware), {
6936
- onUpgrade: (...args)=>{
6937
- for (let cb of upgradeEvents)cb(...args);
6938
- }
6939
- };
6940
- }, getDevMiddlewares = async (options)=>{
6941
- let middlewares = [], { buildManager } = options;
6942
- 'verbose' === logger.level && middlewares.push(getRequestLoggerMiddleware());
6943
- let { before, after } = ((config, devServerAPI)=>{
6944
- let setupMiddlewares = config.dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
6945
- 'sockWrite',
6946
- 'environments'
6947
- ]), before = [], after = [];
6948
- for (let handler of helpers_castArray(setupMiddlewares))handler({
6949
- unshift: (...handlers)=>before.unshift(...handlers),
6950
- push: (...handlers)=>after.push(...handlers)
6951
- }, serverOptions);
6952
- return {
6953
- before,
6954
- after
6955
- };
6956
- })(options.config, options.devServerAPI);
6957
- middlewares.push(...before);
6958
- let { onUpgrade } = await applyDefaultMiddlewares({
6959
- ...options,
6960
- middlewares
6961
- });
6962
- return middlewares.push(...after), {
6963
- close: async ()=>{
6964
- await buildManager?.close();
6965
- },
6966
- onUpgrade,
6967
- middlewares
6968
- };
6969
6810
  }, asModule = async (something, context, unlinked)=>{
6970
6811
  let { Module, SyntheticModule } = await import("node:vm");
6971
6812
  if (something instanceof Module) return something;
@@ -7025,7 +6866,7 @@ class BasicRunner {
7025
6866
  postExecute(_m, _file) {}
7026
6867
  createRunner() {
7027
6868
  this.requirers.set('entry', (_currentDirectory, _modulePath, _context = {})=>{
7028
- throw Error(`${picocolors.dim('[rsbuild:runner]')} Not implemented`);
6869
+ throw Error(`${color.dim('[rsbuild:runner]')} Not implemented`);
7029
6870
  });
7030
6871
  }
7031
6872
  }
@@ -7120,7 +6961,7 @@ class EsmRunner extends CommonJsRunner {
7120
6961
  createEsmRequirer() {
7121
6962
  let esmCache = new Map(), esmIdentifier = this._options.name, vm = esm_require('node:vm');
7122
6963
  return (currentDirectory, modulePath, context = {})=>{
7123
- if (!vm.SourceTextModule) throw Error(`${picocolors.dim('[rsbuild:runner]')} Running ESM bundle needs add Node.js option ${picocolors.yellow('--experimental-vm-modules')}.`);
6964
+ if (!vm.SourceTextModule) throw Error(`${color.dim('[rsbuild:runner]')} Running ESM bundle needs add Node.js option ${color.yellow('--experimental-vm-modules')}.`);
7124
6965
  let _require = this.getRequire(), file = context.file || this.getFile(modulePath, currentDirectory);
7125
6966
  if (!file) return this.requirers.get('miss')(currentDirectory, modulePath);
7126
6967
  let esm = esmCache.get(file.path);
@@ -7156,7 +6997,7 @@ class BasicRunnerFactory {
7156
6997
  name: this.name,
7157
6998
  ...options
7158
6999
  }, { compilerOptions } = options;
7159
- if ('web' === compilerOptions.target || 'webworker' === compilerOptions.target) throw Error(`${picocolors.dim('[rsbuild:runner]')} Not support run ${picocolors.yellow(compilerOptions.target)} resource in Rsbuild server`);
7000
+ if ('web' === compilerOptions.target || 'webworker' === compilerOptions.target) throw Error(`${color.dim('[rsbuild:runner]')} Not support run ${color.yellow(compilerOptions.target)} resource in Rsbuild server`);
7160
7001
  return new EsmRunner(runnerOptions);
7161
7002
  }
7162
7003
  }
@@ -7170,13 +7011,13 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
7170
7011
  entrypoints: !0,
7171
7012
  outputPath: !0
7172
7013
  });
7173
- if (!entrypoints?.[entryName]) throw Error(`${picocolors.dim('[rsbuild:loadBundle]')} Can't find entry: ${picocolors.yellow(entryName)}`);
7014
+ if (!entrypoints?.[entryName]) throw Error(`${color.dim('[rsbuild:loadBundle]')} Can't find entry: ${color.yellow(entryName)}`);
7174
7015
  let { chunks: entryChunks = [] } = entrypoints[entryName], files = entryChunks.reduce((prev, entryChunkName)=>{
7175
7016
  let chunk = chunks?.find((chunk)=>chunk.entry && chunk.names?.includes(String(entryChunkName)));
7176
7017
  return chunk?.files ? prev.concat(chunk.files.filter((file)=>!file.endsWith('.css'))) : prev;
7177
7018
  }, []);
7178
- if (0 === files.length) throw Error(`${picocolors.dim('[rsbuild:loadBundle]')} Failed to get bundle by entryName: ${picocolors.yellow(entryName)}`);
7179
- if (files.length > 1) throw Error(`${picocolors.dim('[rsbuild:loadBundle]')} Only support load single entry chunk, but got ${picocolors.yellow(files.length)}: ${files.join(',')}`);
7019
+ if (0 === files.length) throw Error(`${color.dim('[rsbuild:loadBundle]')} Failed to get bundle by entryName: ${color.yellow(entryName)}`);
7020
+ if (files.length > 1) throw Error(`${color.dim('[rsbuild:loadBundle]')} Only support load single entry chunk, but got ${color.yellow(files.length)}: ${files.join(',')}`);
7180
7021
  let allChunkFiles = chunks?.flatMap((c)=>c.files).map((file)=>(0, external_node_path_.join)(outputPath, file)) || [];
7181
7022
  return await runner_run({
7182
7023
  bundlePath: files[0],
@@ -7277,9 +7118,9 @@ function prepareWatchOptions(paths, options = {}, type) {
7277
7118
  }
7278
7119
  let GLOB_REGEX = /[*?{}[\]()!@+|]/;
7279
7120
  async function createChokidar(pathOrGlobs, root, options) {
7280
- let chokidar = await import("../compiled/chokidar/index.js"), watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
7121
+ let chokidar = requireCompiledPackage('chokidar'), watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
7281
7122
  if (globPatterns.length) {
7282
- let tinyglobby = await import("../compiled/tinyglobby/index.js"), { glob } = tinyglobby.default || tinyglobby;
7123
+ let { glob } = requireCompiledPackage('tinyglobby');
7283
7124
  for (let file of (await glob(globPatterns, {
7284
7125
  cwd: root,
7285
7126
  absolute: !0
@@ -7317,13 +7158,13 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7317
7158
  });
7318
7159
  let startCompile = async ()=>{
7319
7160
  let compiler = customCompiler || await createCompiler();
7320
- if (!compiler) throw Error(`${picocolors.dim('[rsbuild:server]')} Failed to get compiler instance.`);
7161
+ if (!compiler) throw Error(`${color.dim('[rsbuild:server]')} Failed to get compiler instance.`);
7321
7162
  compiler?.hooks.watchRun.tap('rsbuild:watchRun', ()=>{
7322
7163
  lastStats && (waitLastCompileDoneResolve && (waitLastCompileDoneResolve(), waitLastCompileDoneResolve = null), waitLastCompileDone = new Promise((resolve)=>{
7323
7164
  waitLastCompileDoneResolve = resolve;
7324
7165
  }));
7325
7166
  });
7326
- let publicPaths = helpers_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
7167
+ let publicPaths = compiler_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
7327
7168
  getPublicPathFromCompiler(compiler)
7328
7169
  ], buildManager = new BuildManager({
7329
7170
  context,
@@ -7374,33 +7215,33 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7374
7215
  !getPortSilently && portTip && logger.info(portTip);
7375
7216
  }, cacheableLoadBundle = createCacheableFunction(loadBundle), cacheableTransformedHtml = createCacheableFunction((_stats, entryName, utils)=>((entryName, utils)=>{
7376
7217
  let { htmlPaths, distPath } = utils.environment, htmlPath = htmlPaths[entryName];
7377
- if (!htmlPath) throw Error(`${picocolors.dim('[rsbuild:getTransformedHtml]')} Failed to get HTML file by entryName: ${picocolors.yellow(entryName)}`);
7218
+ if (!htmlPath) throw Error(`${color.dim('[rsbuild:getTransformedHtml]')} Failed to get HTML file by entryName: ${color.yellow(entryName)}`);
7378
7219
  let fileName = (0, external_node_path_.join)(distPath, htmlPath);
7379
7220
  return utils.readFileSync(fileName);
7380
7221
  })(entryName, utils)), environmentAPI = Object.fromEntries(Object.entries(context.environments).map(([name, environment])=>[
7381
7222
  name,
7382
7223
  {
7383
7224
  getStats: async ()=>{
7384
- if (!buildManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('getStats')} when ${picocolors.yellow('runCompile')} is false`);
7225
+ if (!buildManager) throw Error(`${color.dim('[rsbuild:server]')} Can not call ${color.yellow('getStats')} when ${color.yellow('runCompile')} is false`);
7385
7226
  return await waitLastCompileDone, lastStats[environment.index];
7386
7227
  },
7387
7228
  context: environment,
7388
7229
  loadBundle: async (entryName)=>{
7389
- if (!buildManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('loadBundle')} when ${picocolors.yellow('runCompile')} is false`);
7230
+ if (!buildManager) throw Error(`${color.dim('[rsbuild:server]')} Can not call ${color.yellow('loadBundle')} when ${color.yellow('runCompile')} is false`);
7390
7231
  return await waitLastCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
7391
7232
  readFileSync: buildManager.readFileSync,
7392
7233
  environment
7393
7234
  });
7394
7235
  },
7395
7236
  getTransformedHtml: async (entryName)=>{
7396
- if (!buildManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('getTransformedHtml')} when ${picocolors.yellow('runCompile')} is false`);
7237
+ if (!buildManager) throw Error(`${color.dim('[rsbuild:server]')} Can not call ${color.yellow('getTransformedHtml')} when ${color.yellow('runCompile')} is false`);
7397
7238
  return await waitLastCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
7398
7239
  readFileSync: buildManager.readFileSync,
7399
7240
  environment
7400
7241
  });
7401
7242
  }
7402
7243
  }
7403
- ])), { default: connect } = await import("../compiled/connect/index.js"), middlewares = connect(), httpServer = middlewareMode ? null : await createHttpServer({
7244
+ ])), middlewares = requireCompiledPackage('connect')(), httpServer = middlewareMode ? null : await createHttpServer({
7404
7245
  serverConfig: config.server,
7405
7246
  middlewares
7406
7247
  }), devServerAPI = {
@@ -7413,7 +7254,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7413
7254
  data
7414
7255
  }),
7415
7256
  listen: async ()=>{
7416
- if (!httpServer) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not listen dev server as ${picocolors.yellow('server.middlewareMode')} is enabled.`);
7257
+ if (!httpServer) throw Error(`${color.dim('[rsbuild:server]')} Can not listen dev server as ${color.yellow('server.middlewareMode')} is enabled.`);
7417
7258
  let serverTerminator = getServerTerminator(httpServer);
7418
7259
  return logger.debug('listen dev server'), context.hooks.onCloseDevServer.tap(serverTerminator), new Promise((resolve)=>{
7419
7260
  httpServer.listen({
@@ -7454,7 +7295,170 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7454
7295
  config,
7455
7296
  buildManager,
7456
7297
  root
7457
- }), (devMiddlewares = await getDevMiddlewares({
7298
+ }), (devMiddlewares = ((options)=>{
7299
+ let middlewares = [], { buildManager } = options;
7300
+ 'verbose' === logger.level && middlewares.push(getRequestLoggerMiddleware());
7301
+ let { before, after } = ((config, devServerAPI)=>{
7302
+ let setupMiddlewares = config.dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
7303
+ 'sockWrite',
7304
+ 'environments'
7305
+ ]), before = [], after = [];
7306
+ for (let handler of helpers_castArray(setupMiddlewares))handler({
7307
+ unshift: (...handlers)=>before.unshift(...handlers),
7308
+ push: (...handlers)=>after.push(...handlers)
7309
+ }, serverOptions);
7310
+ return {
7311
+ before,
7312
+ after
7313
+ };
7314
+ })(options.config, options.devServerAPI);
7315
+ middlewares.push(...before);
7316
+ let { onUpgrade } = (({ config, buildManager, context, devServerAPI, middlewares, pwd, postCallbacks })=>{
7317
+ let upgradeEvents = [], { server } = config;
7318
+ if (server.cors) {
7319
+ let corsMiddleware = requireCompiledPackage('cors');
7320
+ middlewares.push(corsMiddleware('boolean' == typeof server.cors ? {} : server.cors));
7321
+ }
7322
+ let { headers } = server;
7323
+ if (headers && middlewares.push((_req, res, next)=>{
7324
+ for (let [key, value] of Object.entries(headers))res.setHeader(key, value);
7325
+ next();
7326
+ }), server.proxy) {
7327
+ let { middlewares: proxyMiddlewares, upgrade } = createProxyMiddleware(server.proxy);
7328
+ for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.push(middleware);
7329
+ }
7330
+ let { compress } = server;
7331
+ if (compress && middlewares.push(gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && 'rspack' === context.bundlerType && buildManager) {
7332
+ let { compiler } = buildManager;
7333
+ (compiler_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.experiments?.lazyCompilation || childCompiler.options.lazyCompilation) : compiler.options.experiments?.lazyCompilation || compiler.options.lazyCompilation) && middlewares.push(rspack_rspack.experiments.lazyCompilationMiddleware(compiler));
7334
+ }
7335
+ server.base && '/' !== server.base && middlewares.push(getBaseMiddleware({
7336
+ base: server.base
7337
+ }));
7338
+ let launchEditorMiddleware = requireCompiledPackage('launch-editor-middleware');
7339
+ for (let publicDir of (middlewares.push([
7340
+ '/__open-in-editor',
7341
+ launchEditorMiddleware()
7342
+ ]), middlewares.push((({ environments })=>async (req, res, next)=>{
7343
+ if ('/rsbuild-dev-server' !== req.url.replace(postfixRE, '')) return void next();
7344
+ res.writeHead(200, {
7345
+ 'Content-Type': 'text/html; charset=utf-8'
7346
+ }), res.write(`<!DOCTYPE html>
7347
+ <html>
7348
+ <head>
7349
+ <meta charset="utf-8"/>
7350
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
7351
+ <style>
7352
+ body {
7353
+ margin: 0;
7354
+ color: #f6f7f9;
7355
+ padding: 32px 40px;
7356
+ line-height: 1.8;
7357
+ min-height: 100vh;
7358
+ background-image: linear-gradient(#020917, #101725);
7359
+ font-family: ui-sans-serif,system-ui,sans-serif;
7360
+ }
7361
+ h1, h2 {
7362
+ font-weight: 500;
7363
+ }
7364
+ h1 {
7365
+ margin: 0;
7366
+ font-size: 36px;
7367
+ }
7368
+ h2 {
7369
+ font-size: 20px;
7370
+ margin: 24px 0 16px;
7371
+ }
7372
+ ul {
7373
+ margin: 0;
7374
+ padding-left: 16px;
7375
+ }
7376
+ a {
7377
+ color: #58c4dc;
7378
+ text-decoration: none;
7379
+ }
7380
+ a:hover {
7381
+ text-decoration: underline;
7382
+ }
7383
+ </style>
7384
+ </head>
7385
+ <body>
7386
+ <h1>Assets Report</h1>
7387
+ </body>
7388
+ </html>`);
7389
+ try {
7390
+ for(let key in environments){
7391
+ res.write(`<h2>Environment: ${key}</h2>`);
7392
+ let list = [], environment = environments[key], stats = await environment.getStats(), assets = getAssetsFromStats(stats);
7393
+ for (let asset of (res.write('<ul>'), assets))list.push(`<li><a target="_blank" href="${asset?.name}">${asset?.name}</a></li>`);
7394
+ res.write(list?.join('')), res.write('</ul>');
7395
+ }
7396
+ res.end('</body></html>');
7397
+ } catch (err) {
7398
+ logger.error(err), res.writeHead(500), res.end('Failed to list the files');
7399
+ }
7400
+ })({
7401
+ environments: devServerAPI.environments
7402
+ })), buildManager && (middlewares.push(buildManager.middleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.push((req, res, next)=>{
7403
+ req.url?.endsWith('.hot-update.json') && 'OPTIONS' !== req.method ? (res.statusCode = 404, res.end()) : next();
7404
+ })), buildManager && middlewares.push((({ distPath, buildManager })=>async (req, res, next)=>{
7405
+ if (!maybeHTMLRequest(req)) return void next();
7406
+ let pathname = req.url.replace(postfixRE, ''), rewrite = (newUrl)=>{
7407
+ req.url = newUrl, buildManager.middleware(req, res, (...args)=>{
7408
+ next(...args);
7409
+ });
7410
+ };
7411
+ if (pathname.endsWith('/')) {
7412
+ let newUrl = `${pathname}index.html`, filePath = external_node_path_.default.join(distPath, newUrl);
7413
+ if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
7414
+ } else if (!external_node_path_.default.extname(pathname)) {
7415
+ let newUrl = `${pathname}.html`, filePath = external_node_path_.default.join(distPath, newUrl);
7416
+ if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
7417
+ }
7418
+ next();
7419
+ })({
7420
+ buildManager,
7421
+ distPath: context.distPath
7422
+ })), normalizePublicDirs(server?.publicDir))){
7423
+ let sirv = requireCompiledPackage('sirv'), { name } = publicDir, assetMiddleware = sirv((0, external_node_path_.isAbsolute)(name) ? name : (0, external_node_path_.join)(pwd, name), {
7424
+ etag: !0,
7425
+ dev: !0
7426
+ });
7427
+ middlewares.push(assetMiddleware);
7428
+ }
7429
+ for (let callback of postCallbacks)callback();
7430
+ return buildManager && middlewares.push((({ htmlFallback, distPath, buildManager })=>async (req, res, next)=>{
7431
+ if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url || 'index' !== htmlFallback) return void next();
7432
+ let filePath = external_node_path_.default.join(distPath, 'index.html');
7433
+ if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) {
7434
+ let newUrl = '/index.html';
7435
+ 'verbose' === logger.level && logger.debug(` ${req.method} ${req.url} ${color.yellow('fallback to')} ${newUrl}`), req.url = newUrl, buildManager.middleware(req, res, (...args)=>{
7436
+ next(...args);
7437
+ });
7438
+ return;
7439
+ }
7440
+ next();
7441
+ })({
7442
+ buildManager,
7443
+ distPath: context.distPath,
7444
+ htmlFallback: server.htmlFallback
7445
+ })), server.historyApiFallback && (middlewares.push(historyApiFallbackMiddleware(!0 === server.historyApiFallback ? {} : server.historyApiFallback)), buildManager?.middleware && middlewares.push(buildManager.middleware)), middlewares.push(faviconFallbackMiddleware), {
7446
+ onUpgrade: (...args)=>{
7447
+ for (let cb of upgradeEvents)cb(...args);
7448
+ }
7449
+ };
7450
+ })({
7451
+ ...options,
7452
+ middlewares
7453
+ });
7454
+ return middlewares.push(...after), {
7455
+ close: async ()=>{
7456
+ await buildManager?.close();
7457
+ },
7458
+ onUpgrade,
7459
+ middlewares
7460
+ };
7461
+ })({
7458
7462
  pwd: root,
7459
7463
  buildManager,
7460
7464
  config,
@@ -7542,14 +7546,14 @@ class RsbuildProdServer {
7542
7546
  async applyDefaultMiddlewares() {
7543
7547
  let { headers, proxy, historyApiFallback, compress, base, cors } = this.options.serverConfig;
7544
7548
  if ('verbose' === logger.level && this.middlewares.use(getRequestLoggerMiddleware()), cors) {
7545
- let { default: corsMiddleware } = await import("../compiled/cors/index.js");
7549
+ let corsMiddleware = requireCompiledPackage('cors');
7546
7550
  this.middlewares.use(corsMiddleware('boolean' == typeof cors ? {} : cors));
7547
7551
  }
7548
7552
  if (headers && this.middlewares.use((_req, res, next)=>{
7549
7553
  for (let [key, value] of Object.entries(headers))res.setHeader(key, value);
7550
7554
  next();
7551
7555
  }), proxy) {
7552
- let { middlewares, upgrade } = await createProxyMiddleware(proxy);
7556
+ let { middlewares, upgrade } = createProxyMiddleware(proxy);
7553
7557
  for (let middleware of middlewares)this.middlewares.use(middleware);
7554
7558
  this.app.on('upgrade', upgrade);
7555
7559
  }
@@ -7562,10 +7566,10 @@ class RsbuildProdServer {
7562
7566
  }
7563
7567
  base && '/' !== base && this.middlewares.use(getBaseMiddleware({
7564
7568
  base
7565
- })), await this.applyStaticAssetMiddleware(), historyApiFallback && (this.middlewares.use(historyApiFallbackMiddleware(!0 === historyApiFallback ? {} : historyApiFallback)), await this.applyStaticAssetMiddleware()), this.middlewares.use(faviconFallbackMiddleware), this.middlewares.use(optionsFallbackMiddleware), this.middlewares.use(notFoundMiddleware);
7569
+ })), this.applyStaticAssetMiddleware(), historyApiFallback && (this.middlewares.use(historyApiFallbackMiddleware(!0 === historyApiFallback ? {} : historyApiFallback)), this.applyStaticAssetMiddleware()), this.middlewares.use(faviconFallbackMiddleware), this.middlewares.use(optionsFallbackMiddleware), this.middlewares.use(notFoundMiddleware);
7566
7570
  }
7567
- async applyStaticAssetMiddleware() {
7568
- let { output: { path, assetPrefixes }, serverConfig: { htmlFallback } } = this.options, { default: sirv } = await import("../compiled/sirv/index.js"), assetMiddleware = sirv(path, {
7571
+ applyStaticAssetMiddleware() {
7572
+ let { output: { path, assetPrefixes }, serverConfig: { htmlFallback } } = this.options, assetMiddleware = requireCompiledPackage('sirv')(path, {
7569
7573
  etag: !0,
7570
7574
  dev: !0,
7571
7575
  ignores: [
@@ -7585,7 +7589,7 @@ class RsbuildProdServer {
7585
7589
  async function startProdServer(context, config, { getPortSilently } = {}) {
7586
7590
  let { port, host, https, portTip } = await getServerConfig({
7587
7591
  config
7588
- }), { default: connect } = await import("../compiled/connect/index.js"), middlewares = connect(), serverConfig = config.server, server = new RsbuildProdServer({
7592
+ }), middlewares = requireCompiledPackage('connect')(), serverConfig = config.server, server = new RsbuildProdServer({
7589
7593
  pwd: context.rootPath,
7590
7594
  output: {
7591
7595
  path: context.distPath,
@@ -7688,13 +7692,13 @@ async function createRsbuild(options = {}) {
7688
7692
  let { before, environment } = options || {};
7689
7693
  for (let newPlugin of newPlugins)if (newPlugin) if (!function(plugin) {
7690
7694
  let type = typeof plugin;
7691
- if ('object' !== type || null === plugin) throw Error(`${picocolors.dim('[rsbuild:plugin]')} Expect Rsbuild plugin instance to be an object, but got ${picocolors.yellow(type)}.`);
7695
+ if ('object' !== type || null === plugin) throw Error(`${color.dim('[rsbuild:plugin]')} Expect Rsbuild plugin instance to be an object, but got ${color.yellow(type)}.`);
7692
7696
  if (!isFunction(plugin.setup)) {
7693
7697
  if (isFunction(plugin.apply)) {
7694
7698
  let { name = 'SomeWebpackPlugin' } = plugin.constructor || {};
7695
7699
  throw Error([
7696
- `${picocolors.yellow(name)} looks like a webpack or Rspack plugin, please use ${picocolors.yellow('`tools.rspack`')} to register it:`,
7697
- picocolors.green(`
7700
+ `${color.yellow(name)} looks like a webpack or Rspack plugin, please use ${color.yellow('`tools.rspack`')} to register it:`,
7701
+ color.green(`
7698
7702
  // rsbuild.config.ts
7699
7703
  export default {
7700
7704
  tools: {
@@ -7706,7 +7710,7 @@ async function createRsbuild(options = {}) {
7706
7710
  `)
7707
7711
  ].join('\n'));
7708
7712
  }
7709
- throw Error(`${picocolors.dim('[rsbuild:plugin]')} Expect the setup function of Rsbuild plugin to be a function, but got ${picocolors.yellow(type)}.`);
7713
+ throw Error(`${color.dim('[rsbuild:plugin]')} Expect the setup function of Rsbuild plugin to be a function, but got ${color.yellow(type)}.`);
7710
7714
  }
7711
7715
  }(newPlugin), before) {
7712
7716
  let index = plugins.findIndex((item)=>item.instance.name === before);
@@ -7746,12 +7750,12 @@ async function createRsbuild(options = {}) {
7746
7750
  if (context.normalizedConfig) {
7747
7751
  if (options?.environment) {
7748
7752
  let config = context.normalizedConfig.environments[options.environment];
7749
- if (!config) throw Error(`${picocolors.dim('[rsbuild]')} Cannot find normalized config by environment: ${options.environment}.`);
7753
+ if (!config) throw Error(`${color.dim('[rsbuild]')} Cannot find normalized config by environment: ${options.environment}.`);
7750
7754
  return config;
7751
7755
  }
7752
7756
  return context.normalizedConfig;
7753
7757
  }
7754
- throw Error(`${picocolors.dim('[rsbuild]')} Cannot access normalized config until ${picocolors.yellow('modifyRsbuildConfig')} is called.`);
7758
+ throw Error(`${color.dim('[rsbuild]')} Cannot access normalized config until ${color.yellow('modifyRsbuildConfig')} is called.`);
7755
7759
  }
7756
7760
  let getRsbuildConfig = (type = 'current')=>{
7757
7761
  switch(type){
@@ -7762,7 +7766,7 @@ async function createRsbuild(options = {}) {
7762
7766
  case 'normalized':
7763
7767
  return getNormalizedConfig();
7764
7768
  }
7765
- throw Error(`${picocolors.dim('[rsbuild]')} ${picocolors.yellow('getRsbuildConfig')} get an invalid type param.`);
7769
+ throw Error(`${color.dim('[rsbuild]')} ${color.yellow('getRsbuildConfig')} get an invalid type param.`);
7766
7770
  }, exposed = [], expose = (id, api)=>{
7767
7771
  exposed.push({
7768
7772
  id,
@@ -7958,22 +7962,25 @@ async function createRsbuild(options = {}) {
7958
7962
  aggregateTimeout: 0
7959
7963
  }), chain.performance.hints(!1), chain.module.parser.merge({
7960
7964
  javascript: {
7961
- inlineConst: !1,
7962
- exportsPresence: 'error',
7965
+ exportsPresence: 'error'
7966
+ }
7967
+ }), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(bundler.HotModuleReplacementPlugin), isDev && chain.output.devtoolModuleFilenameTemplate((info)=>toPosixPath(info.absoluteResourcePath)), 'rspack' === api.context.bundlerType && (chain.module.parser.merge({
7968
+ javascript: {
7969
+ inlineConst: isProd,
7963
7970
  typeReexportsPresence: 'tolerant'
7964
7971
  }
7965
- }), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(bundler.HotModuleReplacementPlugin), isDev && chain.output.devtoolModuleFilenameTemplate((info)=>toPosixPath(info.absoluteResourcePath)), 'rspack' === api.context.bundlerType && chain.experiments({
7972
+ }), chain.experiments({
7966
7973
  ...chain.get('experiments'),
7967
7974
  lazyBarrel: !0,
7968
7975
  inlineEnum: isProd,
7969
- inlineConst: !1,
7976
+ inlineConst: isProd,
7970
7977
  typeReexportsPresence: !0,
7971
7978
  rspackFuture: {
7972
7979
  bundlerInfo: {
7973
7980
  force: !1
7974
7981
  }
7975
7982
  }
7976
- }), process.env.RSPACK_CONFIG_VALIDATE ||= 'loose-silent';
7983
+ })), process.env.RSPACK_CONFIG_VALIDATE ||= 'loose-silent';
7977
7984
  });
7978
7985
  }
7979
7986
  },
@@ -7992,7 +7999,7 @@ async function createRsbuild(options = {}) {
7992
7999
  preEntry.forEach(addEntry), injectCoreJsEntry && addEntry(createVirtualModule('import "core-js";')), helpers_castArray(entry[entryName]).forEach(addEntry);
7993
8000
  }
7994
8001
  }), api.onBeforeCreateCompiler(({ bundlerConfigs })=>{
7995
- if (bundlerConfigs.every((config)=>!config.entry)) throw Error(`${picocolors.dim('[rsbuild:config]')} Could not find any entry module, please make sure that ${picocolors.yellow('src/index.(ts|js|tsx|jsx|mts|cts|mjs|cjs)')} exists, or customize entry through the ${picocolors.yellow('source.entry')} configuration.`);
8002
+ if (bundlerConfigs.every((config)=>!config.entry)) throw Error(`${color.dim('[rsbuild:config]')} Could not find any entry module, please make sure that ${color.yellow('src/index.(ts|js|tsx|jsx|mts|cts|mjs|cjs)')} exists, or customize entry through the ${color.yellow('source.entry')} configuration.`);
7996
8003
  });
7997
8004
  }
7998
8005
  },
@@ -8123,13 +8130,13 @@ async function createRsbuild(options = {}) {
8123
8130
  initial: {},
8124
8131
  config: config.resolve.alias
8125
8132
  });
8126
- if (config.source.alias && (logger.warn(`${picocolors.dim('[rsbuild:config]')} The ${picocolors.yellow('"source.alias"')} config is deprecated, use ${picocolors.yellow('"resolve.alias"')} instead.`), mergedAlias = reduceConfigs({
8133
+ if (config.source.alias && (logger.warn(`${color.dim('[rsbuild:config]')} The ${color.yellow('"source.alias"')} config is deprecated, use ${color.yellow('"resolve.alias"')} instead.`), mergedAlias = reduceConfigs({
8127
8134
  initial: mergedAlias,
8128
8135
  config: config.source.alias
8129
8136
  })), config.resolve.dedupe) for (let pkgName of config.resolve.dedupe){
8130
8137
  let pkgPath;
8131
8138
  if (mergedAlias[pkgName]) {
8132
- logger.debug(`${picocolors.dim('[rsbuild:resolve]')} The package ${picocolors.yellow(pkgName)} is already in the alias config, dedupe option for ${picocolors.yellow(pkgName)} will be ignored.`);
8139
+ logger.debug(`${color.dim('[rsbuild:resolve]')} The package ${color.yellow(pkgName)} is already in the alias config, dedupe option for ${color.yellow(pkgName)} will be ignored.`);
8133
8140
  continue;
8134
8141
  }
8135
8142
  try {
@@ -8151,7 +8158,7 @@ async function createRsbuild(options = {}) {
8151
8158
  ].join(external_node_path_.sep);
8152
8159
  for(; !pkgPath.endsWith(trailing) && pkgPath.includes('node_modules');)pkgPath = (0, external_node_path_.dirname)(pkgPath);
8153
8160
  } catch {
8154
- logger.debug(`${picocolors.dim('[rsbuild:resolve]')} The package ${picocolors.yellow(pkgName)} is not resolved in the project, dedupe option for ${picocolors.yellow(pkgName)} will be ignored.`);
8161
+ logger.debug(`${color.dim('[rsbuild:resolve]')} The package ${color.yellow(pkgName)} is not resolved in the project, dedupe option for ${color.yellow(pkgName)} will be ignored.`);
8155
8162
  continue;
8156
8163
  }
8157
8164
  mergedAlias[pkgName] = pkgPath;
@@ -8164,7 +8171,7 @@ async function createRsbuild(options = {}) {
8164
8171
  chain,
8165
8172
  config,
8166
8173
  rootPath: api.context.rootPath
8167
- }), chain.module.rule(CHAIN_ID.RULE.MJS).test(/\.m?js/).resolve.set('fullySpecified', !1), config.source.aliasStrategy && logger.warn(`${picocolors.dim('[rsbuild:config]')} The ${picocolors.yellow('"source.aliasStrategy"')} config is deprecated, use ${picocolors.yellow('"resolve.aliasStrategy"')} instead.`);
8174
+ }), chain.module.rule(CHAIN_ID.RULE.MJS).test(/\.m?js/).resolve.set('fullySpecified', !1), config.source.aliasStrategy && logger.warn(`${color.dim('[rsbuild:config]')} The ${color.yellow('"source.aliasStrategy"')} config is deprecated, use ${color.yellow('"resolve.aliasStrategy"')} instead.`);
8168
8175
  let aliasStrategy = config.source.aliasStrategy ?? config.resolve.aliasStrategy;
8169
8176
  tsconfigPath && 'rspack' === api.context.bundlerType && 'prefer-tsconfig' === aliasStrategy && chain.resolve.tsConfig({
8170
8177
  configFile: tsconfigPath,
@@ -8178,7 +8185,7 @@ async function createRsbuild(options = {}) {
8178
8185
  name: 'rsbuild:file-size',
8179
8186
  setup (api) {
8180
8187
  api.onAfterBuild(async ({ stats, environments, isFirstCompile })=>{
8181
- if (!stats || stats.hasErrors() || !isFirstCompile) return;
8188
+ if (!stats || context.buildState.hasErrors || !isFirstCompile) return;
8182
8189
  let logs = [];
8183
8190
  await Promise.all(Object.values(environments).map(async (environment, index)=>{
8184
8191
  let { printFileSize } = environment.config.performance;
@@ -8210,7 +8217,7 @@ async function createRsbuild(options = {}) {
8210
8217
  return 'auto' === enable ? isDev && !config.dev.writeToDisk ? void 0 : isStrictSubdir(rootPath, distPath) ? {
8211
8218
  path: distPath,
8212
8219
  keep
8213
- } : (logger.warn('The dist path is not a subdir of root path, Rsbuild will not empty it.'), logger.warn(`Please set ${picocolors.yellow('`output.cleanDistPath`')} config manually.`), logger.warn(`Current root path: ${picocolors.dim(rootPath)}`), void logger.warn(`Current dist path: ${picocolors.dim(distPath)}`)) : !0 === enable ? {
8220
+ } : (logger.warn('The dist path is not a subdir of root path, Rsbuild will not empty it.'), logger.warn(`Please set ${color.yellow('`output.cleanDistPath`')} config manually.`), logger.warn(`Current root path: ${color.dim(rootPath)}`), void logger.warn(`Current dist path: ${color.dim(distPath)}`)) : !0 === enable ? {
8214
8221
  path: distPath,
8215
8222
  keep
8216
8223
  } : void 0;
@@ -8424,7 +8431,7 @@ async function createRsbuild(options = {}) {
8424
8431
  }, async ({ compilation, environment, sources })=>{
8425
8432
  let { config } = environment, { appIcon } = config.html;
8426
8433
  if (!appIcon) return;
8427
- let { lookup } = await import("../compiled/mrmime/index.js"), distDir = config.output.distPath.image, manifestFile = appIcon.filename ?? 'manifest.webmanifest', publicPath = getPublicPathFromCompiler(compilation), icons = appIcon.icons.map((icon)=>((icon, distDir, publicPath, lookup)=>{
8434
+ let { lookup } = requireCompiledPackage('mrmime'), distDir = config.output.distPath.image, manifestFile = appIcon.filename ?? 'manifest.webmanifest', publicPath = getPublicPathFromCompiler(compilation), icons = appIcon.icons.map((icon)=>((icon, distDir, publicPath, lookup)=>{
8428
8435
  let { src, size } = icon, cached = iconFormatMap.get(src);
8429
8436
  if (cached) return cached;
8430
8437
  let sizes = `${size}x${size}`;
@@ -8451,21 +8458,21 @@ async function createRsbuild(options = {}) {
8451
8458
  })(icon, distDir, publicPath, lookup)), tags = [];
8452
8459
  for (let icon of icons){
8453
8460
  if ('web-app-manifest' === icon.target && !appIcon.name) {
8454
- addCompilationError(compilation, `${picocolors.dim('[rsbuild:app-icon]')} ${picocolors.yellow('"appIcon.name"')} is required when ${picocolors.yellow('"target"')} is ${picocolors.yellow('"web-app-manifest"')}.`);
8461
+ addCompilationError(compilation, `${color.dim('[rsbuild:app-icon]')} ${color.yellow('"appIcon.name"')} is required when ${color.yellow('"target"')} is ${color.yellow('"web-app-manifest"')}.`);
8455
8462
  continue;
8456
8463
  }
8457
8464
  if (!icon.isURL) {
8458
8465
  if (!compilation.inputFileSystem) {
8459
- addCompilationError(compilation, `${picocolors.dim('[rsbuild:app-icon]')} Failed to read the icon file as ${picocolors.yellow('"compilation.inputFileSystem"')} is not available.`);
8466
+ addCompilationError(compilation, `${color.dim('[rsbuild:app-icon]')} Failed to read the icon file as ${color.yellow('"compilation.inputFileSystem"')} is not available.`);
8460
8467
  continue;
8461
8468
  }
8462
8469
  if (!await fileExistsByCompilation(compilation, icon.absolutePath)) {
8463
- addCompilationError(compilation, `${picocolors.dim('[rsbuild:app-icon]')} Failed to find the icon file at ${picocolors.yellow(icon.absolutePath)}.`);
8470
+ addCompilationError(compilation, `${color.dim('[rsbuild:app-icon]')} Failed to find the icon file at ${color.yellow(icon.absolutePath)}.`);
8464
8471
  continue;
8465
8472
  }
8466
8473
  let source = await external_node_util_promisify(compilation.inputFileSystem.readFile)(icon.absolutePath);
8467
8474
  if (!source) {
8468
- addCompilationError(compilation, `${picocolors.dim('[rsbuild:app-icon]')} Failed to read the icon file at ${picocolors.yellow(icon.absolutePath)}.`);
8475
+ addCompilationError(compilation, `${color.dim('[rsbuild:app-icon]')} Failed to read the icon file at ${color.yellow(icon.absolutePath)}.`);
8469
8476
  continue;
8470
8477
  }
8471
8478
  compilation.emitAsset(icon.relativePath, new sources.RawSource(source));
@@ -8562,7 +8569,7 @@ async function createRsbuild(options = {}) {
8562
8569
  }
8563
8570
  return basename ? `${basename}.node` : null;
8564
8571
  })(resourcePath);
8565
- if (null === name) throw Error(`${picocolors.dim('[rsbuild:node-addons]')} Failed to load Node.js addon: ${picocolors.yellow(resourcePath)}`);
8572
+ if (null === name) throw Error(`${color.dim('[rsbuild:node-addons]')} Failed to load Node.js addon: ${color.yellow(resourcePath)}`);
8566
8573
  return emitFile(name, code), `
8567
8574
  try {
8568
8575
  const path = require("path");
@@ -8597,7 +8604,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8597
8604
  if (!value) return;
8598
8605
  let check = (value)=>{
8599
8606
  let pathKey = Object.keys(value).find((key)=>'path' === key.toLowerCase() && value[key] === process.env[key]);
8600
- pathKey && logger.warn(`${picocolors.dim('[rsbuild:config]')} The ${picocolors.yellow('"source.define"')} option includes an object with the key ${picocolors.yellow(JSON.stringify(pathKey))} under ${picocolors.yellow('"process.env"')}, indicating potential exposure of all environment variables. This can lead to security risks and should be avoided.`);
8607
+ pathKey && logger.warn(`${color.dim('[rsbuild:config]')} The ${color.yellow('"source.define"')} option includes an object with the key ${color.yellow(JSON.stringify(pathKey))} under ${color.yellow('"process.env"')}, indicating potential exposure of all environment variables. This can lead to security risks and should be avoided.`);
8601
8608
  };
8602
8609
  if ('object' == typeof value) return check(value);
8603
8610
  if ('string' == typeof value) try {
@@ -8875,7 +8882,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8875
8882
  swcConfig.jsc.transform.legacyDecorator = !1, swcConfig.jsc.transform.decoratorVersion = '2022-03';
8876
8883
  break;
8877
8884
  default:
8878
- throw Error(`${picocolors.dim('[rsbuild:swc]')} Unknown decorators version: ${picocolors.yellow(version)}`);
8885
+ throw Error(`${color.dim('[rsbuild:swc]')} Unknown decorators version: ${color.yellow(version)}`);
8879
8886
  }
8880
8887
  }(swcConfig, config), (targets = helpers_castArray(target)).includes('web') || targets.includes('web-worker')) {
8881
8888
  let polyfillMode = config.output.polyfill;
@@ -9064,19 +9071,19 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9064
9071
  ]
9065
9072
  });
9066
9073
  } catch {
9067
- logger.warn(`\`process.env.RSDOCTOR\` enabled, please install ${picocolors.bold(picocolors.yellow(packageName))} package.`);
9074
+ logger.warn(`\`process.env.RSDOCTOR\` enabled, please install ${color.bold(color.yellow(packageName))} package.`);
9068
9075
  return;
9069
9076
  }
9070
9077
  try {
9071
9078
  let moduleURL = 'win32' === process.platform ? (0, external_node_url_.pathToFileURL)(packagePath).href : packagePath;
9072
9079
  module = await import(moduleURL);
9073
9080
  } catch {
9074
- logger.error(`\`process.env.RSDOCTOR\` enabled, but failed to load ${picocolors.bold(picocolors.yellow(packageName))} module.`);
9081
+ logger.error(`\`process.env.RSDOCTOR\` enabled, but failed to load ${color.bold(color.yellow(packageName))} module.`);
9075
9082
  return;
9076
9083
  }
9077
9084
  if (module && module[pluginName]) {
9078
9085
  for (let config of bundlerConfigs)config.plugins ||= [], config.plugins.push(new module[pluginName]());
9079
- logger.info(`${picocolors.bold(picocolors.yellow(packageName))} enabled.`);
9086
+ logger.info(`${color.bold(color.yellow(packageName))} enabled.`);
9080
9087
  }
9081
9088
  });
9082
9089
  }
@@ -9169,10 +9176,10 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9169
9176
  handler: (config)=>{
9170
9177
  if (isUseAnalyzer(config) || Object.values(config.environments || []).some((config)=>isUseAnalyzer(config))) return config.dev ||= {}, config.dev.writeToDisk = !0, config;
9171
9178
  }
9172
- }), api.modifyBundlerChain(async (chain, { CHAIN_ID, environment })=>{
9179
+ }), api.modifyBundlerChain((chain, { CHAIN_ID, environment })=>{
9173
9180
  let { config } = environment;
9174
9181
  if (!isUseAnalyzer(config)) return;
9175
- let { default: BundleAnalyzer } = await import("../compiled/webpack-bundle-analyzer/index.js");
9182
+ let BundleAnalyzer = requireCompiledPackage('webpack-bundle-analyzer');
9176
9183
  chain.plugin(CHAIN_ID.PLUGIN.BUNDLE_ANALYZER).use(BundleAnalyzer.BundleAnalyzerPlugin, [
9177
9184
  {
9178
9185
  analyzerMode: 'static',
@@ -9212,7 +9219,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9212
9219
  dereference: !0
9213
9220
  }))));
9214
9221
  } catch (err) {
9215
- throw err instanceof Error && (err.message = `Failed to copy public directory '${picocolors.yellow(normalizedPath)}' to output directory. To disable public directory copying, set \`${picocolors.cyan('server.publicDir: false')}\` in your config.\n${err.message}`), err;
9222
+ throw err instanceof Error && (err.message = `Failed to copy public directory '${color.yellow(normalizedPath)}' to output directory. To disable public directory copying, set \`${color.cyan('server.publicDir: false')}\` in your config.\n${err.message}`), err;
9216
9223
  }
9217
9224
  }
9218
9225
  });
@@ -9222,7 +9229,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9222
9229
  name: 'rsbuild:manifest',
9223
9230
  setup (api) {
9224
9231
  let manifestFilenames = new Map();
9225
- api.modifyBundlerChain(async (chain, { CHAIN_ID, environment, isDev })=>{
9232
+ api.modifyBundlerChain((chain, { CHAIN_ID, environment, isDev })=>{
9226
9233
  let { output: { manifest }, dev: { writeToDisk } } = environment.config;
9227
9234
  if (!1 === manifest) return;
9228
9235
  let manifestOptions = function(manifest) {
@@ -9236,7 +9243,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9236
9243
  ...defaultOptions,
9237
9244
  ...manifest
9238
9245
  };
9239
- }(manifest), { RspackManifestPlugin } = await import("../compiled/rspack-manifest-plugin/index.js"), { htmlPaths } = environment, filter = manifestOptions.filter ?? ((file)=>!file.name.endsWith('.LICENSE.txt'));
9246
+ }(manifest), { RspackManifestPlugin } = requireCompiledPackage('rspack-manifest-plugin'), { htmlPaths } = environment, filter = manifestOptions.filter ?? ((file)=>!file.name.endsWith('.LICENSE.txt'));
9240
9247
  manifestFilenames.set(environment.name, manifestOptions.filename), chain.plugin(CHAIN_ID.PLUGIN.MANIFEST).use(RspackManifestPlugin, [
9241
9248
  {
9242
9249
  fileName: manifestOptions.filename,
@@ -9292,7 +9299,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9292
9299
  manifestData
9293
9300
  });
9294
9301
  if (isObject(generatedManifest)) return environment.manifest = generatedManifest, generatedManifest;
9295
- throw Error(`${picocolors.dim('[rsbuild:manifest]')} \`manifest.generate\` function must return a valid manifest object.`);
9302
+ throw Error(`${color.dim('[rsbuild:manifest]')} \`manifest.generate\` function must return a valid manifest object.`);
9296
9303
  }
9297
9304
  return environment.manifest = manifestData, manifestData;
9298
9305
  }
@@ -9301,7 +9308,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9301
9308
  }), api.onAfterCreateCompiler(()=>{
9302
9309
  if (manifestFilenames.size <= 1) return void manifestFilenames.clear();
9303
9310
  let environmentNames = Array.from(manifestFilenames.keys()), filenames = Array.from(manifestFilenames.values());
9304
- new Set(filenames).size !== filenames.length && logger.warn(`${picocolors.dim('[rsbuild:manifest]')} The ${picocolors.yellow('"manifest.filename"')} option must be unique when there are multiple environments (${environmentNames.join(', ')}), otherwise the manifest file will be overwritten.`), manifestFilenames.clear();
9311
+ new Set(filenames).size !== filenames.length && logger.warn(`${color.dim('[rsbuild:manifest]')} The ${color.yellow('"manifest.filename"')} option must be unique when there are multiple environments (${environmentNames.join(', ')}), otherwise the manifest file will be overwritten.`), manifestFilenames.clear();
9305
9312
  });
9306
9313
  }
9307
9314
  },
@@ -9347,7 +9354,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9347
9354
  api.onBeforeBuild(async ({ isFirstCompile })=>{
9348
9355
  isFirstCompile && await onStart();
9349
9356
  }), api.onBeforeStartDevServer(onStart), api.onExit(()=>{
9350
- traceOutput && (rspack_rspack.experiments.globalTrace.cleanup(), logger.info(`profile file saved to ${picocolors.cyan(traceOutput)}`));
9357
+ traceOutput && (rspack_rspack.experiments.globalTrace.cleanup(), logger.info(`profile file saved to ${color.cyan(traceOutput)}`));
9351
9358
  });
9352
9359
  }
9353
9360
  },
@@ -9455,8 +9462,8 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9455
9462
  }), { distPath } = context, { checkDistDir = !0 } = options;
9456
9463
  if (checkDistDir) {
9457
9464
  let files;
9458
- if (!existsSync(distPath)) throw Error(`${picocolors.dim('[rsbuild:preview]')} The output directory ${picocolors.yellow(distPath)} does not exist, please build the project before previewing.`);
9459
- if (0 === (files = node_fs.readdirSync(distPath)).length || 1 === files.length && '.git' === files[0]) throw Error(`${picocolors.dim('[rsbuild:preview]')} The output directory ${picocolors.yellow(distPath)} is empty, please build the project before previewing.`);
9465
+ if (!existsSync(distPath)) throw Error(`${color.dim('[rsbuild:preview]')} The output directory ${color.yellow(distPath)} does not exist, please build the project before previewing.`);
9466
+ if (0 === (files = node_fs.readdirSync(distPath)).length || 1 === files.length && '.git' === files[0]) throw Error(`${color.dim('[rsbuild:preview]')} The output directory ${color.yellow(distPath)} is empty, please build the project before previewing.`);
9460
9467
  }
9461
9468
  return startProdServer(context, config, options);
9462
9469
  },
@@ -9525,7 +9532,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
9525
9532
  if (customConfig) {
9526
9533
  let customConfigPath = (0, external_node_path_.isAbsolute)(customConfig) ? customConfig : (0, external_node_path_.join)(root, customConfig);
9527
9534
  if (node_fs.existsSync(customConfigPath)) return customConfigPath;
9528
- logger.warn(`Cannot find config file: ${picocolors.dim(customConfigPath)}\n`);
9535
+ logger.warn(`Cannot find config file: ${color.dim(customConfigPath)}\n`);
9529
9536
  }
9530
9537
  for (let file of [
9531
9538
  'rsbuild.config.mjs',
@@ -9551,7 +9558,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
9551
9558
  let configFileURL = (0, external_node_url_.pathToFileURL)(configFilePath).href, exportModule = await import(`${configFileURL}?t=${Date.now()}`);
9552
9559
  configExport = exportModule.default ? exportModule.default : exportModule;
9553
9560
  } catch (err) {
9554
- let errorMessage = `Failed to load file with native loader: ${picocolors.dim(configFilePath)}`;
9561
+ let errorMessage = `Failed to load file with native loader: ${color.dim(configFilePath)}`;
9555
9562
  if ('native' === loader) throw logger.error(errorMessage), err;
9556
9563
  logger.debug(`${errorMessage}, fallback to jiti.`), logger.debug(err);
9557
9564
  }
@@ -9570,7 +9577,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
9570
9577
  });
9571
9578
  }
9572
9579
  } catch (err) {
9573
- throw logger.error(`Failed to load file with jiti: ${picocolors.dim(configFilePath)}`), err;
9580
+ throw logger.error(`Failed to load file with jiti: ${color.dim(configFilePath)}`), err;
9574
9581
  }
9575
9582
  if ('function' == typeof configExport) {
9576
9583
  let command = process.argv[2], nodeEnv = process.env.NODE_ENV || '', result = await configExport({
@@ -9579,13 +9586,13 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
9579
9586
  envMode: envMode || nodeEnv,
9580
9587
  meta
9581
9588
  });
9582
- if (void 0 === result) throw Error(`${picocolors.dim('[rsbuild:loadConfig]')} The config function must return a config object.`);
9589
+ if (void 0 === result) throw Error(`${color.dim('[rsbuild:loadConfig]')} The config function must return a config object.`);
9583
9590
  return {
9584
9591
  content: applyMetaInfo(result),
9585
9592
  filePath: configFilePath
9586
9593
  };
9587
9594
  }
9588
- if (!isObject(configExport)) throw Error(`${picocolors.dim('[rsbuild:loadConfig]')} The config must be an object or a function that returns an object, get ${picocolors.yellow(configExport)}`);
9595
+ if (!isObject(configExport)) throw Error(`${color.dim('[rsbuild:loadConfig]')} The config must be an object or a function that returns an object, get ${color.yellow(configExport)}`);
9589
9596
  return logger.debug('configuration loaded from:', configFilePath), {
9590
9597
  content: applyMetaInfo(configExport),
9591
9598
  filePath: configFilePath
@@ -9648,7 +9655,7 @@ let cleaners = [], onBeforeRestartServer = (cleaner)=>{
9648
9655
  }, beforeRestart = async ({ filePath, clear = !0, id })=>{
9649
9656
  if (clear && isTTY() && !process.env.DEBUG && process.stdout.write('\x1B[H\x1B[2J'), filePath) {
9650
9657
  let filename = external_node_path_.default.basename(filePath);
9651
- logger.info(`restarting ${id} as ${picocolors.yellow(filename)} changed\n`);
9658
+ logger.info(`restarting ${id} as ${color.yellow(filename)} changed\n`);
9652
9659
  } else logger.info(`restarting ${id}...\n`);
9653
9660
  for (let cleaner of cleaners)await cleaner();
9654
9661
  cleaners = [];
@@ -9713,18 +9720,18 @@ function runCLI() {
9713
9720
  }
9714
9721
  !function() {
9715
9722
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
9716
- logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.5.13\n`);
9723
+ logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.5.15\n`);
9717
9724
  }();
9718
9725
  try {
9719
9726
  let cli, devDescription, devCommand, buildCommand, previewCommand, inspectCommand;
9720
- (cli = ((name = "")=>new CAC(name))('rsbuild')).version("1.5.13"), 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)', {
9727
+ (cli = ((name = "")=>new CAC(name))('rsbuild')).version("1.5.15"), 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)', {
9721
9728
  default: 'jiti'
9722
9729
  }).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', {
9723
9730
  type: [
9724
9731
  String
9725
9732
  ],
9726
9733
  default: []
9727
- }).option('--log-level <level>', 'Set the log level (info | warn | error | silent)').option('-m, --mode <mode>', 'Set the build mode (development | production | none)').option('-r, --root <root>', 'Set the project root directory (absolute path or relative to cwd)').option('--no-env', 'Disable loading of `.env` files'), devDescription = `Start the dev server ${picocolors.dim('(default if no command is given)')}`, devCommand = cli.command('', devDescription).alias('dev'), buildCommand = cli.command('build', 'Build the app for production'), previewCommand = cli.command('preview', 'Preview the production build locally'), inspectCommand = cli.command('inspect', 'Inspect the Rspack and Rsbuild configs'), applyServerOptions(devCommand), applyServerOptions(previewCommand), devCommand.action(async (options)=>{
9734
+ }).option('--log-level <level>', 'Set the log level (info | warn | error | silent)').option('-m, --mode <mode>', 'Set the build mode (development | production | none)').option('-r, --root <root>', 'Set the project root directory (absolute path or relative to cwd)').option('--no-env', 'Disable loading of `.env` files'), devDescription = `Start the dev server ${color.dim('(default if no command is given)')}`, devCommand = cli.command('', devDescription).alias('dev'), buildCommand = cli.command('build', 'Build the app for production'), previewCommand = cli.command('preview', 'Preview the production build locally'), inspectCommand = cli.command('inspect', 'Inspect the Rspack and Rsbuild configs'), applyServerOptions(devCommand), applyServerOptions(previewCommand), devCommand.action(async (options)=>{
9728
9735
  try {
9729
9736
  let rsbuild = await init_init({
9730
9737
  cliOptions: options
@@ -9768,11 +9775,11 @@ function runCLI() {
9768
9775
  logger.error('Failed to inspect config.'), logger.error(err), process.exit(1);
9769
9776
  }
9770
9777
  }), cli.help((sections)=>{
9771
- for (let section of (sections.shift(), sections))'Commands' === section.title && (section.body = section.body.replace(` ${devDescription}`, `dev ${devDescription}`)), section.title?.startsWith('For more info') ? (section.title = picocolors.dim(' For details on a sub-command, run'), section.body = picocolors.dim(' $ rsbuild <command> -h')) : section.title = picocolors.cyan(section.title);
9778
+ for (let section of (sections.shift(), sections))'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 = color.cyan(section.title);
9772
9779
  }), cli.parse();
9773
9780
  } catch (err) {
9774
9781
  logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
9775
9782
  }
9776
9783
  }
9777
- let src_version = "1.5.13";
9784
+ let src_version = "1.5.15";
9778
9785
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger, mergeRsbuildConfig, rspack_rspack as rspack, runCLI, src_version as version };