@rsbuild/core 2.0.0 → 2.0.2

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/753.js CHANGED
@@ -384,8 +384,8 @@ __webpack_require__.add({
384
384
  return (asyncHooks.AsyncResource && (res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn')), res && res.runInAsyncScope) ? res.runInAsyncScope.bind(res, fn, null) : fn;
385
385
  }
386
386
  },
387
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.10_yaml@2.8.2/node_modules/postcss-load-config/src/index.js" (module, __unused_rspack_exports, __webpack_require__) {
388
- let yaml, { resolve } = __webpack_require__("node:path?435f"), config = __webpack_require__("../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js"), loadOptions = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.10_yaml@2.8.2/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.10_yaml@2.8.2/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.10_yaml@2.8.2/node_modules/postcss-load-config/src/req.js");
387
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.12_yaml@2.8.2/node_modules/postcss-load-config/src/index.js" (module, __unused_rspack_exports, __webpack_require__) {
388
+ let yaml, { resolve } = __webpack_require__("node:path?435f"), config = __webpack_require__("../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js"), loadOptions = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.12_yaml@2.8.2/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.12_yaml@2.8.2/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.12_yaml@2.8.2/node_modules/postcss-load-config/src/req.js");
389
389
  async function processResult(ctx, result) {
390
390
  let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
391
391
  default: obj
@@ -458,8 +458,8 @@ __webpack_require__.add({
458
458
  });
459
459
  };
460
460
  },
461
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.10_yaml@2.8.2/node_modules/postcss-load-config/src/options.js" (module, __unused_rspack_exports, __webpack_require__) {
462
- let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.10_yaml@2.8.2/node_modules/postcss-load-config/src/req.js");
461
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.12_yaml@2.8.2/node_modules/postcss-load-config/src/options.js" (module, __unused_rspack_exports, __webpack_require__) {
462
+ let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.12_yaml@2.8.2/node_modules/postcss-load-config/src/req.js");
463
463
  module.exports = async function options(config, file) {
464
464
  if (config.parser && 'string' == typeof config.parser) try {
465
465
  config.parser = await req(config.parser, file);
@@ -479,8 +479,8 @@ __webpack_require__.add({
479
479
  return config;
480
480
  };
481
481
  },
482
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.10_yaml@2.8.2/node_modules/postcss-load-config/src/plugins.js" (module, __unused_rspack_exports, __webpack_require__) {
483
- let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.10_yaml@2.8.2/node_modules/postcss-load-config/src/req.js");
482
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.12_yaml@2.8.2/node_modules/postcss-load-config/src/plugins.js" (module, __unused_rspack_exports, __webpack_require__) {
483
+ let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.12_yaml@2.8.2/node_modules/postcss-load-config/src/req.js");
484
484
  async function load(plugin, options, file) {
485
485
  try {
486
486
  if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
@@ -496,7 +496,7 @@ __webpack_require__.add({
496
496
  }), list;
497
497
  };
498
498
  },
499
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.10_yaml@2.8.2/node_modules/postcss-load-config/src/req.js" (module, __unused_rspack_exports, __webpack_require__) {
499
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.12_yaml@2.8.2/node_modules/postcss-load-config/src/req.js" (module, __unused_rspack_exports, __webpack_require__) {
500
500
  let tsx, jiti;
501
501
  var __filename = __rspack_fileURLToPath(import.meta.url);
502
502
  let { createRequire } = __webpack_require__("node:module?1bcb"), { pathToFileURL } = __webpack_require__("node:url?b4ec"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
@@ -3467,7 +3467,7 @@ function createPublicContext(context) {
3467
3467
  async function createContext(options, userConfig, logger) {
3468
3468
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0;
3469
3469
  return {
3470
- version: "2.0.0",
3470
+ version: "2.0.2",
3471
3471
  rootPath,
3472
3472
  distPath: '',
3473
3473
  cachePath,
@@ -3660,6 +3660,7 @@ let configChain_CHAIN_ID = {
3660
3660
  JS_RAW: 'js-raw',
3661
3661
  CSS_MAIN: 'css',
3662
3662
  CSS_RAW: 'css-raw',
3663
+ CSS_URL: 'css-url',
3663
3664
  CSS_INLINE: 'css-inline',
3664
3665
  SVG: 'svg',
3665
3666
  SVG_RAW: 'svg-asset-raw',
@@ -3671,6 +3672,7 @@ let configChain_CHAIN_ID = {
3671
3672
  USE: {
3672
3673
  TS: 'ts',
3673
3674
  CSS: 'css',
3675
+ CSS_URL: 'css-url',
3674
3676
  SASS: 'sass',
3675
3677
  LESS: 'less',
3676
3678
  STYLUS: 'stylus',
@@ -4316,21 +4318,39 @@ let addTrailingSep = (dir)=>dir.endsWith(sep) ? dir : dir + sep, isStrictSubdir
4316
4318
  ...defaultOptions,
4317
4319
  ...userOptions
4318
4320
  };
4319
- };
4321
+ }, getConsolePureFuncs = (methods)=>methods.map((method)=>`console.${method}`), ALL_CONSOLE_PURE_FUNCS = getConsolePureFuncs([
4322
+ 'assert',
4323
+ 'clear',
4324
+ 'count',
4325
+ 'countReset',
4326
+ 'debug',
4327
+ 'dir',
4328
+ 'dirxml',
4329
+ 'error',
4330
+ 'group',
4331
+ 'groupCollapsed',
4332
+ 'groupEnd',
4333
+ 'info',
4334
+ 'log',
4335
+ 'profile',
4336
+ 'profileEnd',
4337
+ 'table',
4338
+ 'time',
4339
+ 'timeEnd',
4340
+ 'timeLog',
4341
+ 'timeStamp',
4342
+ 'trace',
4343
+ 'warn'
4344
+ ]);
4320
4345
  function getSwcMinimizerOptions(config, jsOptions) {
4321
4346
  let options = {};
4322
4347
  options.minimizerOptions ||= {}, options.minimizerOptions.format ||= {};
4323
4348
  let { removeConsole } = config.performance;
4324
- if (!0 === removeConsole) options.minimizerOptions.compress = {
4325
- drop_console: !0
4326
- };
4327
- else if (Array.isArray(removeConsole)) {
4328
- let pureFuncs = removeConsole.map((method)=>`console.${method}`);
4329
- options.minimizerOptions.compress = {
4330
- pure_funcs: pureFuncs
4331
- };
4332
- }
4333
- if (config.output.legalComments) switch(config.output.legalComments){
4349
+ if (!0 === removeConsole ? options.minimizerOptions.compress = {
4350
+ pure_funcs: ALL_CONSOLE_PURE_FUNCS
4351
+ } : Array.isArray(removeConsole) && (options.minimizerOptions.compress = {
4352
+ pure_funcs: getConsolePureFuncs(removeConsole)
4353
+ }), config.output.legalComments) switch(config.output.legalComments){
4334
4354
  case 'inline':
4335
4355
  options.minimizerOptions.format.comments = 'some', options.extractComments = !1;
4336
4356
  break;
@@ -4358,7 +4378,7 @@ function parseMinifyOptions(config) {
4358
4378
  cssOptions: minify.cssOptions
4359
4379
  };
4360
4380
  }
4361
- let postcss_load_config_src = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.10_yaml@2.8.2/node_modules/postcss-load-config/src/index.js");
4381
+ let postcss_load_config_src = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.12_yaml@2.8.2/node_modules/postcss-load-config/src/index.js");
4362
4382
  var postcss_load_config_src_default = __webpack_require__.n(postcss_load_config_src);
4363
4383
  function getLightningCSSLoaderOptions(config, targets, minify) {
4364
4384
  let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
@@ -4956,7 +4976,12 @@ function getInlineTests(config) {
4956
4976
  styleTests
4957
4977
  };
4958
4978
  }
4959
- let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), joinUrlSegments = (s1, s2)=>s1 && s2 ? addTrailingSlash(s1) + s2.replace(/^\/+/, '') : s1 || s2 || '', stripBase = (path, base)=>{
4979
+ let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), formatPrefix = (input)=>{
4980
+ let prefix = input;
4981
+ if (prefix?.startsWith('./') && (prefix = prefix.replace('./', '')), !prefix) return '/';
4982
+ let hasLeadingSlash = prefix.startsWith('/'), hasTailSlash = prefix.endsWith('/');
4983
+ return `${hasLeadingSlash ? '' : '/'}${prefix}${hasTailSlash ? '' : '/'}`;
4984
+ }, joinUrlSegments = (s1, s2)=>s1 && s2 ? addTrailingSlash(s1) + s2.replace(/^\/+/, '') : s1 || s2 || '', stripBase = (path, base)=>{
4960
4985
  if (path === base) return '/';
4961
4986
  let trailingSlashBase = addTrailingSlash(base);
4962
4987
  return path.startsWith(trailingSlashBase) ? path.slice(trailingSlashBase.length - 1) : path;
@@ -4969,12 +4994,7 @@ let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), joinUrlSegments = (
4969
4994
  return prev.concat(...routes);
4970
4995
  }, []);
4971
4996
  }, formatRoutes = (entry, base, distPathPrefix, outputStructure)=>{
4972
- let prefix = joinUrlSegments(base, ((input)=>{
4973
- let prefix = input;
4974
- if (prefix?.startsWith('./') && (prefix = prefix.replace('./', '')), !prefix) return '/';
4975
- let hasLeadingSlash = prefix.startsWith('/'), hasTailSlash = prefix.endsWith('/');
4976
- return `${hasLeadingSlash ? '' : '/'}${prefix}${hasTailSlash ? '' : '/'}`;
4977
- })(distPathPrefix));
4997
+ let prefix = joinUrlSegments(base, formatPrefix(distPathPrefix));
4978
4998
  return Object.keys(entry).map((entryName)=>({
4979
4999
  entryName,
4980
5000
  pathname: prefix + ('index' === entryName && 'nested' !== outputStructure ? '' : entryName)
@@ -4993,7 +5013,7 @@ function getURLMessages(urls, routes) {
4993
5013
  for (let { entryName, pathname } of (prevLabel !== label && (index > 0 && (message += '\n'), message += ` ➜ ${label}\n`, prevLabel = label), routes))message += ` ${color.dim('-')} ${color.dim(entryName.padEnd(maxNameLength + 4))}${color.cyan(normalizeUrl(`${url}${pathname}`))}\n`;
4994
5014
  }), message;
4995
5015
  }
4996
- function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, trailingLineBreak = !0, originalConfig, logger }) {
5016
+ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, fallbackPathname, trailingLineBreak = !0, originalConfig, logger }) {
4997
5017
  if (!1 === printUrls) return null;
4998
5018
  let urls = originalUrls, useCustomUrl = isFunction(printUrls);
4999
5019
  if (useCustomUrl) {
@@ -5015,8 +5035,15 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
5015
5035
  };
5016
5036
  });
5017
5037
  }
5018
- if (0 === urls.length || 0 === routes.length && !useCustomUrl) return null;
5019
- let message = getURLMessages(urls, routes);
5038
+ if (0 === urls.length) return null;
5039
+ let printableRoutes = 0 !== routes.length || useCustomUrl || void 0 === fallbackPathname ? routes : [
5040
+ {
5041
+ entryName: 'index',
5042
+ pathname: formatPrefix(fallbackPathname)
5043
+ }
5044
+ ];
5045
+ if (0 === printableRoutes.length && !useCustomUrl) return null;
5046
+ let message = getURLMessages(urls, printableRoutes);
5020
5047
  return originalConfig && originalConfig.server?.host === void 0 && (message += ` ➜ ${color.dim('Network:')} ${color.dim('use')} ${color.bold('--host')} ${color.dim('to expose')}\n`), !trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
5021
5048
  }
5022
5049
  let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
@@ -6637,7 +6664,7 @@ function gzipMiddleware_gzipMiddleware({ filter, level = node_zlib.constants.Z_B
6637
6664
  write(chunk) || gzip.pause();
6638
6665
  }), on('drain', ()=>gzip.resume()), gzip.on('end', ()=>{
6639
6666
  end();
6640
- }), listeners))gzip.on.apply(gzip, listener);
6667
+ }), listeners))gzip.on(...listener);
6641
6668
  else for (let listener of listeners)on.apply(res, listener);
6642
6669
  let statusCode = writeHeadStatus ?? res.statusCode;
6643
6670
  void 0 !== writeHeadMessage ? writeHead(statusCode, writeHeadMessage) : writeHead(statusCode);
@@ -7307,7 +7334,7 @@ async function startWatchFiles({ paths, options, type = 'reload-page' }, buildMa
7307
7334
  async function devServer_createDevServer(options, createCompiler, config, { getPortSilently, runCompile = !0 } = {}) {
7308
7335
  let lastStats, { context } = options, { logger } = context;
7309
7336
  logger.debug('create dev server');
7310
- let { port, portTip } = await resolvePort(config), { middlewareMode, host } = config.server, isHttps = !!config.server.https, routes = getRoutes(context);
7337
+ let { port, portTip } = await resolvePort(config), { middlewareMode, host } = config.server, isHttps = !!config.server.https, routes = getRoutes(context), fallbackPathname = 0 === routes.length && context.environmentList.some((item)=>'web' === item.config.output.target) ? config.server.base : void 0;
7311
7338
  context.devServer = {
7312
7339
  hostname: host,
7313
7340
  port,
@@ -7349,6 +7376,7 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
7349
7376
  routes,
7350
7377
  protocol,
7351
7378
  printUrls: config.server.printUrls,
7379
+ fallbackPathname,
7352
7380
  trailingLineBreak: !cliShortcutsEnabled,
7353
7381
  originalConfig: context.originalConfig,
7354
7382
  logger
@@ -8197,6 +8225,8 @@ try {
8197
8225
  cssRule.test(CSS_REGEX).dependency({
8198
8226
  not: 'url'
8199
8227
  });
8228
+ let urlRule = cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_URL).resourceQuery(/^\?url$/);
8229
+ urlRule.use(CHAIN_ID.USE.CSS_URL).loader(node_path.join(dirname, 'cssUrlLoader.mjs'));
8200
8230
  let inlineRule = cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_INLINE).resourceQuery(INLINE_QUERY_REGEX);
8201
8231
  cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_RAW).type('asset/source').resourceQuery(RAW_QUERY_REGEX);
8202
8232
  let mainRule = cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_MAIN), emitCss = config.output.emitCss ?? 'web' === target;
@@ -8212,7 +8242,7 @@ try {
8212
8242
  normal: 0,
8213
8243
  inline: 0
8214
8244
  }, updateRules = (callback, options = {})=>{
8215
- options.skipMain || callback(mainRule, 'main'), callback(inlineRule, 'inline');
8245
+ options.skipMain || callback(mainRule, 'main'), callback(inlineRule, 'inline'), callback(urlRule, 'url');
8216
8246
  }, cssLoaderPath = join(COMPILED_PATH, 'css-loader', 'index.js');
8217
8247
  if (updateRules((rule)=>{
8218
8248
  rule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath);
@@ -8224,7 +8254,7 @@ try {
8224
8254
  webEnvironment && (browserslist = webEnvironment.browserslist, minifyCss = parseMinifyOptions(webEnvironment.config).minifyCss);
8225
8255
  }
8226
8256
  updateRules((rule, type)=>{
8227
- let minify = ('inline' === type || config.output.injectStyles) && minifyCss, lightningcssOptions = getLightningCSSLoaderOptions(config, browserslist, minify);
8257
+ let minify = ('inline' === type || 'url' === type || config.output.injectStyles) && minifyCss, lightningcssOptions = getLightningCSSLoaderOptions(config, browserslist, minify);
8228
8258
  rule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(lightningcssOptions);
8229
8259
  }, {
8230
8260
  skipMain: !emitCss
@@ -8281,7 +8311,7 @@ try {
8281
8311
  });
8282
8312
  updateRules((rule, type)=>{
8283
8313
  let finalOptions = cssLoaderOptions;
8284
- finalOptions = 'inline' === type ? {
8314
+ finalOptions = 'inline' === type || 'url' === type ? {
8285
8315
  ...cssLoaderOptions,
8286
8316
  exportType: 'string',
8287
8317
  modules: !1,
@@ -8289,7 +8319,12 @@ try {
8289
8319
  } : {
8290
8320
  ...cssLoaderOptions,
8291
8321
  importLoaders: importLoaders.normal
8292
- }, rule.use(CHAIN_ID.USE.CSS).options(finalOptions), rule.sideEffects(!0), rule.resolve.preferRelative(!0);
8322
+ }, rule.use(CHAIN_ID.USE.CSS).options(finalOptions), 'url' !== type && rule.sideEffects(!0), rule.resolve.preferRelative(!0);
8323
+ });
8324
+ let cssUrlFilename = getFilename(config, 'css', isProd), cssUrlPath = config.output.distPath.css;
8325
+ urlRule.use(CHAIN_ID.USE.CSS_URL).options({
8326
+ filename: 'function' == typeof cssUrlFilename ? (pathData, assetInfo)=>posix.join(cssUrlPath, cssUrlFilename(pathData, assetInfo)) : posix.join(cssUrlPath, cssUrlFilename),
8327
+ modules: cssLoaderOptions.modules
8293
8328
  });
8294
8329
  let isStringExport = 'string' === cssLoaderOptions.exportType;
8295
8330
  if (isStringExport && mainRule.uses.has(CHAIN_ID.USE.MINI_CSS_EXTRACT) && mainRule.uses.delete(CHAIN_ID.USE.MINI_CSS_EXTRACT), emitCss && !config.output.injectStyles && !isStringExport) {
@@ -9186,7 +9221,7 @@ let applyServerOptions = (command)=>{
9186
9221
  };
9187
9222
  function setupCommands() {
9188
9223
  let cli = ((name = "")=>new CAC(name))('rsbuild');
9189
- cli.version("2.0.0"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
9224
+ cli.version("2.0.2"), 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)', {
9190
9225
  default: 'auto'
9191
9226
  }).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', {
9192
9227
  type: [
@@ -9263,7 +9298,7 @@ function initNodeEnv() {
9263
9298
  }
9264
9299
  function showGreeting() {
9265
9300
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
9266
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.0.0\n`);
9301
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.0.2\n`);
9267
9302
  }
9268
9303
  function setupLogLevel() {
9269
9304
  let logLevelIndex = process.argv.findIndex((item)=>'--log-level' === item || '--logLevel' === item);
@@ -9284,5 +9319,5 @@ function runCLI() {
9284
9319
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
9285
9320
  }
9286
9321
  }
9287
- let src_version = "2.0.0";
9322
+ let src_version = "2.0.2";
9288
9323
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, core_rspack as rspack, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger_createLogger as createLogger, mergeRsbuildConfig, runCLI, src_logger as logger, src_version as version };
@@ -0,0 +1,38 @@
1
+ import node_path from "node:path";
2
+ let CSS_MODULE_REGEX = /\.module\.\w+$/i, HASH_PLACEHOLDER_REGEX = /\[(?:[^:\]]+:)?(?:chunkhash|contenthash|hash|fullhash)(?::[^\]]+)?]/i, getRelativePath = (root, resourcePath)=>{
3
+ let relativePath = node_path.relative(root, resourcePath);
4
+ if (relativePath && !('..' === relativePath || relativePath.startsWith(`..${node_path.sep}`)) && !node_path.isAbsolute(relativePath)) return relativePath.replace(/\\/g, '/');
5
+ }, pitch = async function(remainingRequest) {
6
+ let root, resourcePath, nameSource, hash, options = this.getOptions();
7
+ if (((modules, resourcePath, resourceQuery, resourceFragment)=>{
8
+ if (!modules) return !1;
9
+ if (!0 === modules || 'string' == typeof modules) return !0;
10
+ let { auto } = modules;
11
+ return !1 !== auto && (auto instanceof RegExp ? auto.test(resourcePath) : 'function' == typeof auto ? auto(resourcePath, resourceQuery, resourceFragment) : CSS_MODULE_REGEX.test(resourcePath));
12
+ })(options.modules, this.resourcePath, this.resourceQuery, this.resourceFragment)) throw Error('[rsbuild:css] CSS Modules do not support the ?url query. Use ?inline to import the compiled CSS content as a string.');
13
+ let content = ((moduleExports)=>{
14
+ let content = moduleExports && 'object' == typeof moduleExports && 'default' in moduleExports ? moduleExports.default : moduleExports;
15
+ if ('string' != typeof content) throw Error('[rsbuild:css] Expected CSS ?url imports to export a string.');
16
+ return content;
17
+ })(await this.importModule(`!!${remainingRequest}`)), ext = node_path.extname(this.resourcePath), sourceFilename = node_path.relative(this.rootContext, this.resourcePath).replace(/\\/g, '/'), name = (root = this.rootContext, resourcePath = this.resourcePath, nameSource = getRelativePath(node_path.join(root, 'src'), resourcePath) ?? getRelativePath(root, resourcePath) ?? node_path.basename(resourcePath), ext ? nameSource.slice(0, -ext.length) : nameSource), contentHash = ((hash = this.utils.createHash(this._compilation.outputOptions.hashFunction)).update(Buffer.from(content)), hash.digest(this._compilation.outputOptions.hashDigest || 'hex')), pathData = {
18
+ contentHash,
19
+ chunk: {
20
+ name,
21
+ hash: contentHash,
22
+ contentHash: {
23
+ css: contentHash
24
+ }
25
+ }
26
+ }, assetInfo = {
27
+ sourceFilename
28
+ }, filenameTemplate = 'function' == typeof options.filename ? options.filename(pathData, assetInfo) : options.filename, { path: filename, info } = this._compilation.getAssetPathWithInfo(filenameTemplate, pathData);
29
+ return this.emitFile(filename, content, void 0, {
30
+ ...info,
31
+ ...assetInfo,
32
+ immutable: info.immutable || HASH_PLACEHOLDER_REGEX.test(filenameTemplate)
33
+ }), `export default __webpack_public_path__ + ${JSON.stringify(filename)};`;
34
+ };
35
+ export default function(source) {
36
+ return source;
37
+ };
38
+ export { pitch };
@@ -6,6 +6,7 @@ import { EventEmitter } from "node:events";
6
6
  import "node:net";
7
7
  import "node:stream";
8
8
  import { URL as external_node_url_URL } from "node:url";
9
+ import { URL as external_url_URL } from "url";
9
10
  import "node:zlib";
10
11
  import "node:querystring";
11
12
  import { __webpack_require__ } from "./1~rslib-runtime.js";
@@ -2226,7 +2227,7 @@ function setupOutgoing(outgoing, options, req, forward) {
2226
2227
  }, req.headers?.[":authority"] && (outgoing.headers.host = req.headers[":authority"]), options.headers) for (let key of Object.keys(options.headers))outgoing.headers[key] = options.headers[key];
2227
2228
  if (req.httpVersionMajor > 1) for (let header of HTTP2_HEADER_BLACKLIST)delete outgoing.headers[header];
2228
2229
  if (options.auth && (outgoing.auth = options.auth), options.ca && (outgoing.ca = options.ca), isSSL.test(options[forward || "target"].protocol ?? "http") && (outgoing.rejectUnauthorized = void 0 === options.secure || options.secure), void 0 !== options.agent) outgoing.agent = options.agent || !1;
2229
- else if (req.httpVersionMajor > 1) outgoing.agent = !1;
2230
+ else if (req.httpVersionMajor > 1 || upgradeHeader.test(req.headers.connection || "")) outgoing.agent = !1;
2230
2231
  else {
2231
2232
  let targetProto = options[forward || "target"].protocol ?? "http";
2232
2233
  outgoing.agent = isSSL.test(targetProto) ? defaultAgents.https : defaultAgents.http;
@@ -2363,7 +2364,7 @@ let redirectStatuses = new Set([
2363
2364
  "proto"
2364
2365
  ]){
2365
2366
  let key = "x-forwarded-" + header;
2366
- req.headers[key] || (req.headers[key] = values[header]);
2367
+ req.headers[key] || void 0 === values[header] || (req.headers[key] = values[header]);
2367
2368
  }
2368
2369
  req.headers["x-forwarded-host"] = req.headers["x-forwarded-host"] || req.headers[":authority"] || req.headers.host || "";
2369
2370
  },
@@ -2463,7 +2464,7 @@ let redirectStatuses = new Set([
2463
2464
  "proto"
2464
2465
  ]){
2465
2466
  let key = "x-forwarded-" + header;
2466
- req.headers[key] || (req.headers[key] = values[header]);
2467
+ req.headers[key] || void 0 === values[header] || (req.headers[key] = values[header]);
2467
2468
  }
2468
2469
  },
2469
2470
  (req, socket, options, server, head, callback)=>{
@@ -2510,7 +2511,7 @@ var ERRORS, errors_ERRORS, ProxyServer = class extends EventEmitter {
2510
2511
  constructor(options = {}){
2511
2512
  super(), this.options = options || {}, this.options.prependPath = !1 !== options.prependPath, this.web = _createProxyFn("web", this), this.ws = _createProxyFn("ws", this);
2512
2513
  }
2513
- listen(port, hostname) {
2514
+ listen(port, hostname, listeningListener) {
2514
2515
  let closure = (req, res)=>this.web(req, res);
2515
2516
  if (this.options.http2) {
2516
2517
  if (!this.options.ssl) throw Error("HTTP/2 requires ssl option");
@@ -2521,7 +2522,7 @@ var ERRORS, errors_ERRORS, ProxyServer = class extends EventEmitter {
2521
2522
  } else this.options.ssl ? this._server = node_https.createServer(this.options.ssl, closure) : this._server = node_http.createServer(closure);
2522
2523
  return this.options.ws && this._server.on("upgrade", (req, socket, head)=>{
2523
2524
  this.ws(req, socket, this.options, head).catch(()=>{});
2524
- }), this._server.listen(port, hostname), this;
2525
+ }), this._server.listen(port, hostname, listeningListener), this;
2525
2526
  }
2526
2527
  close(callback) {
2527
2528
  this._server && this._server.close((...args)=>{
@@ -2657,6 +2658,10 @@ let errorResponsePlugin = (proxyServer, options)=>{
2657
2658
  warn: ()=>{},
2658
2659
  error: ()=>{}
2659
2660
  };
2661
+ function createUrl({ protocol, host, port, path }) {
2662
+ let ipv6Host = host?.includes(':') ? `[${host}]` : host, url = new external_url_URL(`${protocol || 'undefined:'}//${ipv6Host || '[::]'}`);
2663
+ return port && (url.port = port), path && (url.pathname = path), url;
2664
+ }
2660
2665
  function logger_plugin_getPort(sockets) {
2661
2666
  return Object.keys(sockets || {})?.[0]?.split(':')[1];
2662
2667
  }
@@ -2668,14 +2673,15 @@ let loggerPlugin = (proxyServer, options)=>{
2668
2673
  }), proxyServer.on('proxyRes', (proxyRes, req, res)=>{
2669
2674
  let target, originalUrl = req.originalUrl ?? `${req.baseUrl || ''}${req.url}`;
2670
2675
  try {
2671
- let port = logger_plugin_getPort(proxyRes.req?.agent?.sockets), obj = {
2672
- protocol: proxyRes.req.protocol,
2673
- host: proxyRes.req.host,
2674
- pathname: proxyRes.req.path
2675
- };
2676
- target = new external_node_url_URL(`${obj.protocol}//${obj.host}${obj.pathname}`), port && (target.port = port);
2676
+ let port = logger_plugin_getPort(proxyRes.req?.agent?.sockets), { protocol, host, path } = proxyRes.req;
2677
+ target = createUrl({
2678
+ protocol,
2679
+ host,
2680
+ port,
2681
+ path
2682
+ });
2677
2683
  } catch (err) {
2678
- (target = new external_node_url_URL(options.target)).pathname = proxyRes.req.path;
2684
+ console.error('[HPM] Unexpected error while creating target URL', err), (target = new external_node_url_URL(options.target)).pathname = proxyRes.req.path;
2679
2685
  }
2680
2686
  let targetUrl = target.toString(), exchange = `[HPM] ${req.method} ${originalUrl} -> ${targetUrl} [${proxyRes.statusCode}]`;
2681
2687
  logger.info(exchange);
@@ -2793,7 +2799,7 @@ async function getTarget(req, config) {
2793
2799
  return isPlainObject(router) ? newTarget = getTargetFromProxyTable(req, router) : 'function' == typeof router && (newTarget = await router(req)), newTarget;
2794
2800
  }
2795
2801
  function getTargetFromProxyTable(req, table) {
2796
- let result, host = req.headers.host, hostAndPath = host + req.url;
2802
+ let result, host = req.headers.host ?? '', hostAndPath = host + (req.url ?? '');
2797
2803
  for (let [key, value] of Object.entries(table))if (containsPath(key)) {
2798
2804
  if (hostAndPath.indexOf(key) > -1) {
2799
2805
  router_debug('match: "%s" -> "%s"', key, result = value);
@@ -2808,6 +2814,29 @@ function getTargetFromProxyTable(req, table) {
2808
2814
  function containsPath(v) {
2809
2815
  return v.indexOf('/') > -1;
2810
2816
  }
2817
+ let ipv6_debug = Debug.extend('ipv6');
2818
+ function normalizeIPv6LiteralTargets(options) {
2819
+ options.target = normalizeIPv6ProxyTarget(options.target, 'target'), options.forward = normalizeIPv6ProxyTarget(options.forward, 'forward');
2820
+ }
2821
+ function normalizeIPv6ProxyTarget(target, optionName) {
2822
+ let targetUrl = toTargetUrl(target);
2823
+ return targetUrl && isBracketedIPv6Hostname(targetUrl.hostname) ? (ipv6_debug('normalized IPv6 "%s" %s', optionName, target), {
2824
+ hostname: stripBrackets(targetUrl.hostname),
2825
+ pathname: targetUrl.pathname,
2826
+ port: targetUrl.port,
2827
+ protocol: targetUrl.protocol,
2828
+ search: targetUrl.search
2829
+ }) : target;
2830
+ }
2831
+ function toTargetUrl(target) {
2832
+ return 'string' == typeof target ? new URL(target) : target instanceof URL ? target : void 0;
2833
+ }
2834
+ function isBracketedIPv6Hostname(hostname) {
2835
+ return hostname.startsWith('[') && hostname.endsWith(']');
2836
+ }
2837
+ function stripBrackets(hostname) {
2838
+ return hostname.replace(/^\[|\]$/g, '');
2839
+ }
2811
2840
  class HttpProxyMiddleware {
2812
2841
  wsInternalSubscribed = !1;
2813
2842
  serverOnCloseSubscribed = !1;
@@ -2869,14 +2898,14 @@ class HttpProxyMiddleware {
2869
2898
  };
2870
2899
  prepareProxyRequest = async (req)=>{
2871
2900
  let newProxyOptions = Object.assign({}, this.proxyOptions);
2872
- return await this.applyRouter(req, newProxyOptions), await this.applyPathRewrite(req, this.pathRewriter), newProxyOptions;
2901
+ return await this.applyRouter(req, newProxyOptions), normalizeIPv6LiteralTargets(newProxyOptions), await this.applyPathRewrite(req, this.pathRewriter), newProxyOptions;
2873
2902
  };
2874
2903
  applyRouter = async (req, options)=>{
2875
2904
  let newTarget;
2876
2905
  options.router && (newTarget = await getTarget(req, options)) && (Debug('router new target: "%s"', newTarget), options.target = newTarget);
2877
2906
  };
2878
2907
  applyPathRewrite = async (req, pathRewriter)=>{
2879
- if (pathRewriter) {
2908
+ if (req.url && pathRewriter) {
2880
2909
  let path = await pathRewriter(req.url, req);
2881
2910
  'string' == typeof path ? (Debug('pathRewrite new path: %s', path), req.url = path) : Debug('pathRewrite: no rewritten path found: %s', req.url);
2882
2911
  }
@@ -1,6 +1,6 @@
1
1
  import type { RsbuildInstance } from '../types';
2
2
  import type { CommonOptions } from './commands';
3
- export declare function init({ cliOptions, isRestart, isBuildWatch, }: {
3
+ export declare function init({ cliOptions, isRestart, isBuildWatch }: {
4
4
  cliOptions?: CommonOptions;
5
5
  isRestart?: boolean;
6
6
  isBuildWatch?: boolean;