@rsbuild/core 2.2.9 → 2.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  (() => {
2
2
  var __webpack_modules__ = {
3
- 535: (module, __unused_webpack_exports, __nccwpck_require__) => {
3
+ 793: (module, __unused_webpack_exports, __nccwpck_require__) => {
4
4
  "use strict";
5
- const { HtmlWebpackChildCompiler } = __nccwpck_require__(284);
5
+ const { HtmlWebpackChildCompiler } = __nccwpck_require__(82);
6
6
  const compilerMap = new WeakMap();
7
7
  class CachedChildCompilation {
8
8
  constructor(compiler) {
@@ -307,7 +307,7 @@
307
307
  }
308
308
  module.exports = { CachedChildCompilation };
309
309
  },
310
- 284: (module) => {
310
+ 82: (module) => {
311
311
  "use strict";
312
312
  class HtmlWebpackChildCompiler {
313
313
  compilationPromise;
@@ -476,7 +476,7 @@
476
476
  }
477
477
  module.exports = { HtmlWebpackChildCompiler };
478
478
  },
479
- 876: (module) => {
479
+ 474: (module) => {
480
480
  "use strict";
481
481
  function none(chunks) {
482
482
  return chunks;
@@ -492,7 +492,7 @@
492
492
  }
493
493
  module.exports = { auto: none, manual, none };
494
494
  },
495
- 123: (module) => {
495
+ 621: (module) => {
496
496
  "use strict";
497
497
  module.exports = function (err) {
498
498
  return {
@@ -516,7 +516,7 @@
516
516
  };
517
517
  };
518
518
  },
519
- 90: (module, __unused_webpack_exports, __nccwpck_require__) => {
519
+ 116: (module, __unused_webpack_exports, __nccwpck_require__) => {
520
520
  "use strict";
521
521
  const { AsyncSeriesWaterfallHook } = __nccwpck_require__(176);
522
522
  const htmlWebpackPluginHooksMap = new WeakMap();
@@ -542,7 +542,7 @@
542
542
  }
543
543
  module.exports = { getHtmlRspackPluginHooks };
544
544
  },
545
- 527: (module) => {
545
+ 265: (module) => {
546
546
  const voidTags = [
547
547
  "area",
548
548
  "base",
@@ -610,19 +610,19 @@
610
610
  htmlTagObjectToString,
611
611
  };
612
612
  },
613
- 718: (module, __unused_webpack_exports, __nccwpck_require__) => {
613
+ 52: (module, __unused_webpack_exports, __nccwpck_require__) => {
614
614
  "use strict";
615
615
  const promisify = __nccwpck_require__(23).promisify;
616
616
  const vm = __nccwpck_require__(154);
617
617
  const fs = __nccwpck_require__(896);
618
618
  const path = __nccwpck_require__(928);
619
- const { CachedChildCompilation } = __nccwpck_require__(535);
619
+ const { CachedChildCompilation } = __nccwpck_require__(793);
620
620
  const { createHtmlTagObject, htmlTagObjectToString, HtmlTagArray } =
621
- __nccwpck_require__(527);
622
- const prettyError = __nccwpck_require__(123);
623
- const chunkSorter = __nccwpck_require__(876);
621
+ __nccwpck_require__(265);
622
+ const prettyError = __nccwpck_require__(621);
623
+ const chunkSorter = __nccwpck_require__(474);
624
624
  const getHtmlRspackPluginHooks =
625
- __nccwpck_require__(90).getHtmlRspackPluginHooks;
625
+ __nccwpck_require__(116).getHtmlRspackPluginHooks;
626
626
  const WITH_PLACEHOLDER = "function __with_placeholder__";
627
627
  class HtmlRspackPlugin {
628
628
  constructor(userOptions = {}) {
@@ -2395,6 +2395,6 @@
2395
2395
  }
2396
2396
  if (typeof __nccwpck_require__ !== "undefined")
2397
2397
  __nccwpck_require__.ab = __dirname + "/";
2398
- var __webpack_exports__ = __nccwpck_require__(718);
2398
+ var __webpack_exports__ = __nccwpck_require__(52);
2399
2399
  module.exports = __webpack_exports__;
2400
2400
  })();
@@ -1,15 +1,15 @@
1
1
  (() => {
2
2
  "use strict";
3
3
  var __webpack_modules__ = {
4
- 841: (module, __unused_webpack_exports, __nccwpck_require__) => {
5
- module.exports = __nccwpck_require__(147)["default"];
4
+ 951: (module, __unused_webpack_exports, __nccwpck_require__) => {
5
+ module.exports = __nccwpck_require__(265)["default"];
6
6
  },
7
- 147: (__unused_webpack_module, exports, __nccwpck_require__) => {
7
+ 265: (__unused_webpack_module, exports, __nccwpck_require__) => {
8
8
  var __webpack_unused_export__;
9
9
  __webpack_unused_export__ = { value: true };
10
10
  exports["default"] = loader;
11
11
  var _nodePath = _interopRequireDefault(__nccwpck_require__(760));
12
- var _utils = __nccwpck_require__(870);
12
+ var _utils = __nccwpck_require__(284);
13
13
  function _interopRequireDefault(e) {
14
14
  return e && e.__esModule ? e : { default: e };
15
15
  }
@@ -179,7 +179,7 @@
179
179
  callback(null, result.css, map, { ast });
180
180
  }
181
181
  },
182
- 870: (module, exports, __nccwpck_require__) => {
182
+ 284: (module, exports, __nccwpck_require__) => {
183
183
  module = __nccwpck_require__.nmd(module);
184
184
  Object.defineProperty(exports, "__esModule", { value: true });
185
185
  exports.exec = exec;
@@ -716,6 +716,6 @@
716
716
  })();
717
717
  if (typeof __nccwpck_require__ !== "undefined")
718
718
  __nccwpck_require__.ab = __dirname + "/";
719
- var __webpack_exports__ = __nccwpck_require__(841);
719
+ var __webpack_exports__ = __nccwpck_require__(951);
720
720
  module.exports = __webpack_exports__;
721
721
  })();
package/dist/1.js ADDED
@@ -0,0 +1,84 @@
1
+ import { isAbsolute, join, relative, sep, win32 } from "node:path";
2
+ let isDeno = "u" > typeof Deno, isWindows = 'win32' === process.platform, JS_DIST_DIR = 'static/js', CSS_DIST_DIR = 'static/css', SVG_DIST_DIR = 'static/svg', FONT_DIST_DIR = 'static/font', WASM_DIST_DIR = 'static/wasm', IMAGE_DIST_DIR = 'static/image', MEDIA_DIST_DIR = 'static/media', ASSETS_DIST_DIR = 'static/assets', dirname = import.meta.dirname, LOADER_PATH = dirname, STATIC_PATH = join(dirname, '../static'), CLIENT_PATH = join(dirname, 'client'), COMPILED_PATH = join(dirname, '../compiled'), TS_CONFIG_FILE = 'tsconfig.json', HMR_SOCKET_PATH = '/rsbuild-hmr', RSBUILD_OUTPUTS_PATH = '.rsbuild', LOCALHOST = 'localhost', ALL_INTERFACES_IPV4 = '0.0.0.0', DEFAULT_STACK_TRACE = 'summary', DEFAULT_WEB_BROWSERSLIST = [
3
+ 'chrome >= 107',
4
+ 'edge >= 107',
5
+ 'firefox >= 104',
6
+ 'safari >= 16'
7
+ ], DEFAULT_BROWSERSLIST = {
8
+ web: DEFAULT_WEB_BROWSERSLIST,
9
+ 'web-worker': DEFAULT_WEB_BROWSERSLIST,
10
+ node: [
11
+ 'node >= 20'
12
+ ]
13
+ }, 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(?:&|=|$)/, URL_QUERY_REGEX = /[?&]url(?:&|=|$)/, WORKER_QUERY_REGEX = /[?&]worker(?:&|=|$)/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
14
+ 'woff',
15
+ 'woff2',
16
+ 'eot',
17
+ 'ttf',
18
+ 'otf',
19
+ 'ttc'
20
+ ], ASSET_EXTENSIONS = [
21
+ 'webmanifest',
22
+ 'pdf',
23
+ 'txt'
24
+ ], IMAGE_EXTENSIONS = [
25
+ 'png',
26
+ 'jpg',
27
+ 'jpeg',
28
+ 'pjpeg',
29
+ 'pjp',
30
+ 'gif',
31
+ 'bmp',
32
+ 'webp',
33
+ 'ico',
34
+ 'apng',
35
+ 'avif',
36
+ 'tif',
37
+ 'tiff',
38
+ 'jfif',
39
+ 'cur',
40
+ 'jxl'
41
+ ], VIDEO_EXTENSIONS = [
42
+ 'mp4',
43
+ 'webm',
44
+ 'ogg',
45
+ 'mov'
46
+ ], AUDIO_EXTENSIONS = [
47
+ 'mp3',
48
+ 'wav',
49
+ 'flac',
50
+ 'aac',
51
+ 'm4a',
52
+ 'opus'
53
+ ], TRACK_EXTENSIONS = [
54
+ 'vtt'
55
+ ], LAZY_COMPILATION_IDENTIFIER = 'lazy-compilation-proxy', BROWSER_LOG_PREFIX = '[browser]';
56
+ function toRelativePath(base, filepath) {
57
+ let relativePath = relative(base, filepath);
58
+ return '' === relativePath ? `.${sep}` : relativePath.startsWith('.') ? relativePath : `.${sep}${relativePath}`;
59
+ }
60
+ function relativeWithin(parent, target) {
61
+ let relativePath = relative(parent, target);
62
+ if (!('..' === relativePath || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath))) return relativePath;
63
+ }
64
+ function getCommonParentPath(paths) {
65
+ let uniquePaths = [
66
+ ...new Set(paths)
67
+ ];
68
+ if (1 === uniquePaths.length) return uniquePaths[0];
69
+ let [first, ...rest] = uniquePaths.map((p)=>p.split(sep)), common = [];
70
+ for(let i = 0; i < first.length; i++){
71
+ let segment = first[i];
72
+ if (rest.every((p)=>p[i] === segment)) common.push(segment);
73
+ else break;
74
+ }
75
+ return common.join(sep);
76
+ }
77
+ let getCompiledPath = (packageName)=>join(COMPILED_PATH, packageName, 'index.js'), ensureAbsolutePath = (base, filePath)=>isAbsolute(filePath) ? filePath : join(base, filePath), getPathnameFromUrl = (url)=>{
78
+ try {
79
+ return url ? new URL(url, 'http://localhost').pathname : url;
80
+ } catch {
81
+ return url;
82
+ }
83
+ }, dedupeNestedPaths = (paths)=>paths.sort((p1, p2)=>p2.length > p1.length ? -1 : 1).reduce((prev, curr)=>prev.some((p)=>void 0 !== relativeWithin(p, curr)) ? prev : prev.concat(curr), []), toPosixPath = (filepath)=>'/' === sep ? filepath : filepath.replace(/\\/g, '/'), normalizeRuleConditionPath = (filepath)=>isWindows && 'string' == typeof filepath && filepath.includes('/') && win32.isAbsolute(filepath) ? filepath.replace(/\//g, '\\') : filepath;
84
+ export { ALL_INTERFACES_IPV4, ASSETS_DIST_DIR, ASSET_EXTENSIONS, AUDIO_EXTENSIONS, BROWSER_LOG_PREFIX, CLIENT_PATH, COMPILED_PATH, CSS_DIST_DIR, CSS_REGEX, DEFAULT_BROWSERSLIST, DEFAULT_STACK_TRACE, DEFAULT_WEB_BROWSERSLIST, FONT_DIST_DIR, FONT_EXTENSIONS, HMR_SOCKET_PATH, IMAGE_DIST_DIR, IMAGE_EXTENSIONS, INLINE_QUERY_REGEX, JS_DIST_DIR, JS_REGEX, LAZY_COMPILATION_IDENTIFIER, LOADER_PATH, LOCALHOST, MEDIA_DIST_DIR, NODE_MODULES_REGEX, PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, RAW_QUERY_REGEX, RSBUILD_OUTPUTS_PATH, SCRIPT_REGEX, STATIC_PATH, SVG_DIST_DIR, TRACK_EXTENSIONS, TS_CONFIG_FILE, URL_QUERY_REGEX, VIDEO_EXTENSIONS, WASM_DIST_DIR, WORKER_QUERY_REGEX, dedupeNestedPaths, ensureAbsolutePath, getCommonParentPath, getCompiledPath, getPathnameFromUrl, isDeno, isWindows, normalizeRuleConditionPath, relativeWithin, toPosixPath, toRelativePath };
@@ -94,7 +94,9 @@ function hmr_init(token, config, serverHost, serverPort, serverBase, liveReload,
94
94
  }
95
95
  function handleResolvedClientError({ id, message }) {
96
96
  if (!createOverlay || hasBuildErrors) return;
97
- for (const item of clientErrors)if (item.id === id) item.message = message;
97
+ const clientError = clientErrors.find((item)=>item.id === id);
98
+ if (!clientError) return;
99
+ clientError.message = message;
98
100
  createOverlay('Runtime errors', clientErrors.map((item)=>item.message).filter(Boolean).join('\n\n'));
99
101
  }
100
102
  const shouldUpdate = ()=>lastHash !== import.meta.rspackHash;
@@ -145,7 +147,10 @@ function hmr_init(token, config, serverHost, serverPort, serverBase, liveReload,
145
147
  switch(message.type){
146
148
  case 'hash':
147
149
  lastHash = message.data;
148
- if (clearOverlay && shouldUpdate()) clearOverlay();
150
+ if (shouldUpdate()) {
151
+ clientErrors.length = 0;
152
+ null == clearOverlay || clearOverlay();
153
+ }
149
154
  break;
150
155
  case 'ok':
151
156
  handleSuccess();
@@ -13,6 +13,12 @@ function _define_property(obj, key, value) {
13
13
  const { HTMLElement: HTMLElement = class {
14
14
  }, customElements: customElements } = "u" > typeof window ? window : globalThis;
15
15
  class ErrorOverlay extends HTMLElement {
16
+ connectedCallback() {
17
+ document.addEventListener('keydown', this.onEscKeydown);
18
+ }
19
+ disconnectedCallback() {
20
+ document.removeEventListener('keydown', this.onEscKeydown);
21
+ }
16
22
  init(html) {
17
23
  var _root_querySelector, _root_querySelector1;
18
24
  const root = this.attachShadow({
@@ -28,14 +34,11 @@ class ErrorOverlay extends HTMLElement {
28
34
  }
29
35
  e.stopPropagation();
30
36
  });
31
- const onEscKeydown = (e)=>{
32
- if ('Escape' === e.key || 'Escape' === e.code) this.close();
33
- document.removeEventListener('keydown', onEscKeydown);
34
- };
35
- document.addEventListener('keydown', onEscKeydown);
36
37
  }
37
38
  constructor(...args){
38
- super(...args), _define_property(this, "close", (immediate = false)=>{
39
+ super(...args), _define_property(this, "onEscKeydown", (e)=>{
40
+ if ('Escape' === e.key || 'Escape' === e.code) this.close();
41
+ }), _define_property(this, "close", (immediate = false)=>{
39
42
  const remove = ()=>{
40
43
  var _this_parentNode;
41
44
  return null == (_this_parentNode = this.parentNode) ? void 0 : _this_parentNode.removeChild(this);
@@ -1,8 +1,9 @@
1
1
  import node_path from "node:path";
2
+ import { relativeWithin } from "./1.js";
2
3
  import { isCSSModules } from "./c.js";
3
4
  let HASH_PLACEHOLDER_REGEX = /\[(?:[^:\]]+:)?(?:chunkhash|contenthash|hash|fullhash)(?::[^\]]+)?]/i, getRelativePath = (root, resourcePath)=>{
4
- let relativePath = node_path.relative(root, resourcePath);
5
- if (relativePath && !('..' === relativePath || relativePath.startsWith(`..${node_path.sep}`)) && !node_path.isAbsolute(relativePath)) return relativePath.replace(/\\/g, '/');
5
+ let relativePath = relativeWithin(root, resourcePath);
6
+ if (relativePath) return relativePath.replace(/\\/g, '/');
6
7
  }, pitch = async function(remainingRequest) {
7
8
  let root, resourcePath, nameSource, hash, options = this.getOptions();
8
9
  if (isCSSModules(options.modules, this)) throw Error('[rsbuild:css] CSS Modules do not support the ?url query. Use ?inline to import the compiled CSS content as a string.');
@@ -5,6 +5,7 @@ export { require } from './vendors.js';
5
5
  export { color, RspackChain };
6
6
  export declare const getNodeEnv: () => string;
7
7
  export declare const setNodeEnv: (env: string) => void;
8
+ export declare const isCI: () => boolean;
8
9
  export declare const isFunction: (func: unknown) => func is (...args: any[]) => any;
9
10
  export declare const isObject: (obj: unknown) => obj is Record<string, any>;
10
11
  export declare const isPlainObject: (obj: unknown) => obj is Record<string, any>;
@@ -1,5 +1,14 @@
1
1
  import type { Rspack } from '../types/index.js';
2
2
  export declare function toRelativePath(base: string, filepath: string): string;
3
+ /**
4
+ * Returns `target` relative to `parent`, or `undefined` if it is outside `parent`.
5
+ * Returns `''` for the same directory.
6
+ *
7
+ * @example
8
+ * relativeWithin('/project', '/project/src'); // 'src'
9
+ * relativeWithin('/project', '/project'); // ''
10
+ * relativeWithin('/project', '/project-legacy'); // undefined
11
+ */ export declare function relativeWithin(parent: string, target: string): string | undefined;
3
12
  export declare function getCommonParentPath(paths: string[]): string;
4
13
  export declare const getCompiledPath: (packageName: string) => string;
5
14
  /**
@@ -11,4 +11,4 @@ import{rspackRequire as e,moduleFactories as t}from"./rslib-runtime.js";import r
11
11
  For more details, see: https://github.com/chimurai/http-proxy-middleware/issues/40
12
12
  `,H=(e,t)=>{e.on("error",(e,t,r,o)=>{$(`httpxy error event:
13
13
  %O`,e),"ECONNRESET"===e.code&&t&&"POST"===t.method&&"body"in t&&t.body&&console.error(i("red",O))}),e.on("proxyReq",(e,t,r)=>{r.on("error",e=>{$("Socket error in proxyReq event: \n%O",e)})}),e.on("proxyRes",(e,t,r)=>{r.on("close",()=>{r.writableEnded||($("Destroying proxyRes in proxyRes close event"),e.destroy())})}),e.on("proxyReqWs",(e,t,r)=>{r.on("error",e=>{$("Socket error in proxyReqWs event: \n%O",e)})}),e.on("open",e=>{e.on("error",e=>{$("Socket error in open event: \n%O",e)})}),e.on("close",(e,t,r)=>{t.on("error",e=>{$("Socket error in close event: \n%O",e)})}),e.on("econnreset",(e,t,r,o)=>{$(`httpxy econnreset event:
14
- %O`,e)})};function T(e){return e?.replace(/[<>]/g,e=>encodeURIComponent(e))??""}let L=(e,t)=>{e.on("error",(e,t,r,o)=>{if(!t||!r)throw e;if(r&&"function"==typeof r.writeHead){if(!r.headersSent){let t=function(e){let t;if(/HPE_INVALID/.test(e))return 502;if(/HPM_ERR_INVALID_MULTIPART_/.test(e))return 400;switch(e){case"ECONNRESET":case"ENOTFOUND":case"ECONNREFUSED":case"ETIMEDOUT":t=504;break;default:t=500}return t}(e.code);r.writeHead(t)}let o=t.headers&&t.headers.host;r.end(`Error occurred while trying to proxy: ${T(o)}${T(t.url)}`)}else!r||"function"!=typeof r.write||"writeHead"in r||r.destroy()})},I={info:()=>{},warn:()=>{},error:()=>{}},F=(e,t)=>{let r=t.logger||I;e.on("error",(e,t,o,n)=>{let s=t?.headers?.host,i=`${s}${t?.url}`,a=`${n?.href}`;r.error("[HPM] Error occurred while proxying request %s to %s [%s] (%s)",i,a,e.code||e,"https://nodejs.org/api/errors.html#errors_common_system_errors")}),e.on("proxyRes",(e,o,n)=>{let s,i=o.originalUrl??`${o.baseUrl||""}${o.url}`;try{var c;let t=(c=e.req?.agent?.sockets,Object.keys(c||{})?.[0]?.split(":")[1]),{protocol:r,host:o,path:n}=e.req;s=function({protocol:e,host:t,port:r,path:o}){let n=t?.includes(":")?`[${t}]`:t,s=new u(`${e||"undefined:"}//${n||"[::]"}`);return r&&(s.port=r),o&&(s.pathname=o),s}({protocol:r,host:o,port:t,path:n})}catch(r){console.error("[HPM] Unexpected error while creating target URL",r),(s=new a(t.target)).pathname=e.req.path}let l=s.toString(),p=`[HPM] ${o.method} ${i} -> ${l} [${e.statusCode}]`;r.info(p)}),e.on("open",e=>{r.info("[HPM] Client connected: %o",e.address())}),e.on("close",(e,t,o)=>{r.info("[HPM] Client disconnected: %o",t.address())})};function P(e){return e.name||"[anonymous Function]"}let j=S.extend("proxy-events-plugin"),N=(e,t)=>{let r;if(t.on){for(r in t.on)if(Object.prototype.hasOwnProperty.call(t.on,r)){let o=t.on[r];if(!o)continue;j(`register event handler: "${r}" -> "${P(o)}"`),e.on(r,o)}}},M=e("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/is-glob/4.0.3/5f6010d19ebbd407d4ddad3f32ad93b07ae9baaa0b44d778899bd947e1a7324b/node_modules/is-glob/index.js"),U=e("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromatch/4.0.8/e3e5f26f16f8b95548bbbd14ad679e23348853c21837502922840101deaebdcd/node_modules/micromatch/index.js");function B(e,t){let r=G(t);return r?.indexOf(e)===0}function D(e,t){let r=U([G(t)],e);return r&&r.length>0}function G(e){return e&&new URL(e,"http://0.0.0.0").pathname}function q(e){return"string"==typeof e&&!M(e)}function K(e){return M(e)}function W(e){if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}let Z=S.extend("path-rewriter"),z=S.extend("router");async function Q(e,t,r){let o,n=r.router;return W(n)?o=function(e,t){let r,o=e.headers.host??"",n=e.url??"";for(let[e,i]of Object.entries(t))if(V(e)){var s;if(V(s=e)&&!s.startsWith("/")){let[t,s]=function(e){let t=e.indexOf("/");return[e.slice(0,t),e.slice(t)]}(e);if(o===t&&n.startsWith(s)){z('match: "%s" -> "%s"',e,r=i);break}}else if(n.startsWith(e)){z('match: "%s" -> "%s"',e,r=i);break}}else if(e===o){z('match: "%s" -> "%s"',o,r=i);break}return r}(e,n):"function"==typeof n&&(o=await n(e,t,r)),o}function V(e){return e.indexOf("/")>-1}let X=S.extend("ipv6");function Y(e,t){var r,o,n;let s="string"==typeof(r=e)?new URL(r):r instanceof URL?r:void 0;if(s&&(o=s.hostname).startsWith("[")&&o.endsWith("]")){let r="::"===(n=s.hostname.replace(/^\[|\]$/g,""))?(X("normalizing hostname unspecified IPv6 address (::) to loopback (::1)"),"::1"):n;return X('normalized IPv6 "%s" %s',t,e),{hostname:r,auth:s.username||s.password?`${s.username}:${s.password}`:void 0,pathname:s.pathname,port:s.port,protocol:s.protocol,search:s.search}}return e}class J{wsInternalSubscribedServers=new WeakSet;activeServers=new Set;proxyOptions;proxy;pathRewriter;logger;constructor(e){if(!e.target&&!e.router)throw new k('[HPM] Missing "target" option. Example: {target: "http://www.example.org"}',"ERR_CONFIG_FACTORY_TARGET_MISSING");this.proxyOptions=e,this.logger=e.logger||I,S("create proxy server"),this.proxy=function(e={}){return new w(e)}({}),this.registerPlugins(this.proxy,this.proxyOptions),this.pathRewriter=function(e){let t;if(function(e){if("function"==typeof e)return!0;if(W(e))return 0!==Object.keys(e).length;if(null==e)return!1;throw new k("[HPM] Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function","HPM_INVALID_PATH_REWRITER_CONFIG")}(e))if("function"==typeof e)return e;else return t=function(e){let t=[];if(W(e))for(let[r,o]of Object.entries(e))t.push({regex:new RegExp(r),value:o}),Z('rewrite rule created: "%s" ~> "%s"',r,o);return t}(e),function(e){let r=e;for(let o of t)if(o.regex.test(e)){Z('rewriting path from "%s" to "%s"',e,r=r.replace(o.regex,o.value));break}return r}}(this.proxyOptions.pathRewrite),this.middleware.upgrade=(e,t,r)=>{let o=this.#e(e);o&&!this.wsInternalSubscribedServers.has(o)&&this.handleUpgrade(e,t,r)}}#e(e){return e.socket?.server}middleware=async(e,t,r)=>{if(this.shouldProxy(this.proxyOptions.pathFilter,e)){let o;try{if(!(o=await this.prepareProxyRequest(e,t)).target&&!o.forward)throw Error("Must provide a proper URL as target")}catch(e){r?.(e);return}try{S("proxy request to target: %O",o.target),await this.proxy.web(e,t,o)}catch(n){this.proxy.emit("error",n,e,t,o.target),r?.(n)}}else r?.();let o=this.#e(e);o&&!this.activeServers.has(o)&&(S("registering server close listener"),this.activeServers.add(o),o.on("close",()=>{(S("server close signal received."),this.activeServers.delete(o),this.activeServers.size>0)?S(`proxy server not closed: ${this.activeServers.size} server(s) still active`):(S("closing proxy server"),this.proxy.close(()=>S("proxy server closed")))})),!0===this.proxyOptions.ws&&o&&this.catchUpgradeRequest(o)};registerPlugins(e,t){let r;(r=t.on?.error?[]:[L],[...t.ejectPlugins?[]:[H,N,F,...r],...t.plugins??[]]).forEach(r=>{S(`register plugin: "${P(r)}"`),r(e,t)})}catchUpgradeRequest=e=>{this.wsInternalSubscribedServers.has(e)||(S("subscribing to server upgrade event"),e.on("upgrade",this.handleUpgrade),this.wsInternalSubscribedServers.add(e))};handleUpgrade=async(e,t,r)=>{try{if(this.shouldProxy(this.proxyOptions.pathFilter,e)){let o=await this.prepareProxyRequest(e,void 0);await this.proxy.ws(e,t,o,r),S("server upgrade event received. Proxying WebSocket")}}catch(r){this.proxy.emit("error",r,e,t)}};shouldProxy=(e,t)=>{try{return function(e="/",t,r){if(q(e))return B(e,t);if(K(e))return D(e,t);if(Array.isArray(e)){if(e.every(q)){var o=e,n=t;let r=!1;for(let e of o)if(B(e,n)){r=!0;break}return r}if(e.every(K))return D(e,t);throw new k('[HPM] Invalid pathFilter. Plain paths (e.g. "/api") can not be mixed with globs (e.g. "/api/**"). Expecting something like: ["/api", "/ajax"] or ["/api/**", "!**.html"].',"HPM_INVALID_PATH_FILTER_ARRAY_CONFIG")}if("function"==typeof e)return!!e(G(t),r);throw new k('[HPM] Invalid pathFilter. Expecting something like: "/api" or ["/api", "/ajax"]',"HPM_INVALID_PATH_FILTER_CONFIG")}(e,t.url,t)}catch(e){return S("Error: matchPathFilter() called with request url: ",`"${t.url}"`),this.logger.error(e),!1}};prepareProxyRequest=async(e,t)=>{let r=Object.assign({},this.proxyOptions);return await this.applyRouter(e,t,r),r.target=Y(r.target,"target"),r.forward=Y(r.forward,"forward"),await this.applyPathRewrite(e,t,this.pathRewriter,r),r};applyRouter=async(e,t,r)=>{let o;r.router&&(o=await Q(e,t,r))&&(S('router new target: "%s"',o),r.target=o)};applyPathRewrite=async(e,t,r,o)=>{if(e.url&&r){let n=await r(e.url,e,t,o);"string"==typeof n?(S("pathRewrite new path: %s",n),e.url=n):S("pathRewrite: no rewritten path found: %s",e.url)}}}function ee(e){let{middleware:t}=new J(e);return t}S.extend("response-interceptor");export{ee as createProxyMiddleware};
14
+ %O`,e)})};function T(e){return e?.replace(/[<>]/g,e=>encodeURIComponent(e))??""}let L=(e,t)=>{e.on("error",(e,t,r,o)=>{if(!t||!r)throw e;if(r&&"function"==typeof r.writeHead){if(!r.headersSent){let t=function(e){let t;if(/HPE_INVALID/.test(e))return 502;if(/HPM_ERR_INVALID_MULTIPART_/.test(e))return 400;switch(e){case"ECONNRESET":case"ENOTFOUND":case"ECONNREFUSED":case"ETIMEDOUT":t=504;break;default:t=500}return t}(e.code);r.writeHead(t)}let o=t.headers&&t.headers.host;r.end(`Error occurred while trying to proxy: ${T(o)}${T(t.url)}`)}else!r||"function"!=typeof r.write||"writeHead"in r||r.destroy()})},I={info:()=>{},warn:()=>{},error:()=>{}},F=(e,t)=>{let r=t.logger||I;e.on("error",(e,t,o,n)=>{let s=t?.headers?.host,i=`${s}${t?.url}`,a=`${n?.href}`;r.error("[HPM] Error occurred while proxying request %s to %s [%s] (%s)",i,a,e.code||e,"https://nodejs.org/api/errors.html#errors_common_system_errors")}),e.on("proxyRes",(e,o,n)=>{let s,i=o.originalUrl??`${o.baseUrl||""}${o.url}`;try{var c;let t=(c=e.req?.agent?.sockets,Object.keys(c||{})?.[0]?.split(":")[1]),{protocol:r,host:o,path:n}=e.req;s=function({protocol:e,host:t,port:r,path:o}){let n=t?.includes(":")?`[${t}]`:t,s=new u(`${e||"undefined:"}//${n||"[::]"}`);return r&&(s.port=r),o&&(s.pathname=o),s}({protocol:r,host:o,port:t,path:n})}catch(r){console.error("[HPM] Unexpected error while creating target URL",r),(s=new a(t.target)).pathname=e.req.path}let l=s.toString(),p=`[HPM] ${o.method} ${i} -> ${l} [${e.statusCode}]`;r.info(p)}),e.on("open",e=>{r.info("[HPM] Client connected: %o",e.address())}),e.on("close",(e,t,o)=>{r.info("[HPM] Client disconnected: %o",t.address())})};function P(e){return e.name||"[anonymous Function]"}let j=S.extend("proxy-events-plugin"),N=(e,t)=>{let r;if(t.on){for(r in t.on)if(Object.prototype.hasOwnProperty.call(t.on,r)){let o=t.on[r];if(!o)continue;j(`register event handler: "${r}" -> "${P(o)}"`),e.on(r,o)}}},M=e("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/is-glob/4.0.3/5f6010d19ebbd407d4ddad3f32ad93b07ae9baaa0b44d778899bd947e1a7324b/node_modules/is-glob/index.js"),U=e("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/micromatch/4.0.8/e3e5f26f16f8b95548bbbd14ad679e23348853c21837502922840101deaebdcd/node_modules/micromatch/index.js");function B(e,t){let r=G(t);return r?.indexOf(e)===0}function D(e,t){let r=U([G(t)],e);return r&&r.length>0}function G(e){return e&&new URL(e,"http://0.0.0.0").pathname}function q(e){return"string"==typeof e&&!M(e)}function K(e){return M(e)}function W(e){if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}let Z=S.extend("path-rewriter"),z=S.extend("router");async function Q(e,t,r){let o,n=r.router;return W(n)?o=function(e,t){let r,o=e.headers.host??"",n=e.url??"";for(let[e,i]of Object.entries(t))if(V(e)){var s;if(V(s=e)&&!s.startsWith("/")){let[t,s]=function(e){let t=e.indexOf("/");return[e.slice(0,t),e.slice(t)]}(e);if(o===t&&n.startsWith(s)){z('match: "%s" -> "%s"',e,r=i);break}}else if(n.startsWith(e)){z('match: "%s" -> "%s"',e,r=i);break}}else if(e===o){z('match: "%s" -> "%s"',o,r=i);break}return r}(e,n):"function"==typeof n&&(o=await n(e,t,r)),o}function V(e){return e.indexOf("/")>-1}let X=S.extend("ipv6");function Y(e,t){var r,o,n;let s="string"==typeof(r=e)?new URL(r):r instanceof URL?r:void 0;if(s&&(o=s.hostname).startsWith("[")&&o.endsWith("]")){let r="::"===(n=s.hostname.replace(/^\[|\]$/g,""))?(X("normalizing hostname unspecified IPv6 address (::) to loopback (::1)"),"::1"):n;return X('normalized IPv6 "%s" %s',t,e),{hostname:r,auth:s.username||s.password?`${s.username}:${s.password}`:void 0,pathname:s.pathname,port:s.port,protocol:s.protocol,search:s.search}}return e}class J{wsInternalSubscribedServers=new WeakSet;activeServers=new Set;proxyOptions;proxy;pathRewriter;logger;constructor(e){if(!e.target&&!e.router)throw new k('[HPM] Missing "target" option. Example: {target: "http://www.example.org"}',"ERR_CONFIG_FACTORY_TARGET_MISSING");this.proxyOptions=e,this.logger=e.logger||I,S("create proxy server"),this.proxy=function(e={}){return new w(e)}({}),this.registerPlugins(this.proxy,this.proxyOptions),this.pathRewriter=function(e){let t;if(function(e){if("function"==typeof e)return!0;if(W(e))return 0!==Object.keys(e).length;if(null==e)return!1;throw new k("[HPM] Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function","HPM_INVALID_PATH_REWRITER_CONFIG")}(e))if("function"==typeof e)return e;else return t=function(e){let t=[];if(W(e))for(let[r,o]of Object.entries(e))t.push({regex:new RegExp(r),value:o}),Z('rewrite rule created: "%s" ~> "%s"',r,o);return t}(e),function(e){let r=e;for(let o of t)if(o.regex.test(e)){Z('rewriting path from "%s" to "%s"',e,r=r.replace(o.regex,o.value));break}return r}}(this.proxyOptions.pathRewrite),this.middleware.upgrade=(e,t,r)=>{let o=this.#e(e);o&&!this.wsInternalSubscribedServers.has(o)&&this.handleUpgrade(e,t,r)}}#e(e){return e.socket?.server}middleware=async(e,t,r)=>{if(this.shouldProxy(this.proxyOptions.pathFilter,e)){let o;try{if(!(o=await this.prepareProxyRequest(e,t)).target&&!o.forward)throw Error("Must provide a proper URL as target")}catch(e){r?.(e);return}try{S("proxy request to target: %O",o.target),await this.proxy.web(e,t,o)}catch(n){this.proxy.emit("error",n,e,t,o.target),r?.(n)}}else r?.();let o=this.#e(e);o&&!this.activeServers.has(o)&&(S("registering server close listener"),this.activeServers.add(o),o.on("close",()=>{(S("server close signal received."),this.activeServers.delete(o),this.activeServers.size>0)?S(`proxy server not closed: ${this.activeServers.size} server(s) still active`):(S("closing proxy server"),this.proxy.close(()=>S("proxy server closed")))})),!0===this.proxyOptions.ws&&o&&this.catchUpgradeRequest(o)};registerPlugins(e,t){let r,o,n;(r=t.on?.error?[]:[L],o=t.ejectPlugins?[]:[H,N,F,...r],n=t.plugins??[],[...o,...n]).forEach(r=>{S(`register plugin: "${P(r)}"`),r(e,t)})}catchUpgradeRequest=e=>{this.wsInternalSubscribedServers.has(e)||(S("subscribing to server upgrade event"),e.on("upgrade",this.handleUpgrade),this.wsInternalSubscribedServers.add(e))};handleUpgrade=async(e,t,r)=>{try{if(this.shouldProxy(this.proxyOptions.pathFilter,e)){let o=await this.prepareProxyRequest(e,void 0);await this.proxy.ws(e,t,o,r),S("server upgrade event received. Proxying WebSocket")}}catch(r){this.proxy.emit("error",r,e,t)}};shouldProxy=(e,t)=>{try{return function(e="/",t,r){if(q(e))return B(e,t);if(K(e))return D(e,t);if(Array.isArray(e)){if(e.every(q)){var o,n,s=e,i=t;let r=!1;for(let e of s)if(B(e,i)){r=!0;break}return r}if(e.every(K)){return o=e,n=t,D(o,n)}throw new k('[HPM] Invalid pathFilter. Plain paths (e.g. "/api") can not be mixed with globs (e.g. "/api/**"). Expecting something like: ["/api", "/ajax"] or ["/api/**", "!**.html"].',"HPM_INVALID_PATH_FILTER_ARRAY_CONFIG")}if("function"==typeof e)return!!e(G(t),r);throw new k('[HPM] Invalid pathFilter. Expecting something like: "/api" or ["/api", "/ajax"]',"HPM_INVALID_PATH_FILTER_CONFIG")}(e,t.url,t)}catch(e){return S("Error: matchPathFilter() called with request url: ",`"${t.url}"`),this.logger.error(e),!1}};prepareProxyRequest=async(e,t)=>{let r=Object.assign({},this.proxyOptions);return await this.applyRouter(e,t,r),r.target=Y(r.target,"target"),r.forward=Y(r.forward,"forward"),await this.applyPathRewrite(e,t,this.pathRewriter,r),r};applyRouter=async(e,t,r)=>{let o;r.router&&(o=await Q(e,t,r))&&(S('router new target: "%s"',o),r.target=o)};applyPathRewrite=async(e,t,r,o)=>{if(e.url&&r){let n=await r(e.url,e,t,o);"string"==typeof n?(S("pathRewrite new path: %s",n),e.url=n):S("pathRewrite: no rewritten path found: %s",e.url)}}}function ee(e){let{middleware:t}=new J(e);return t}S.extend("response-interceptor");export{ee as createProxyMiddleware};
package/dist/index.d.ts CHANGED
@@ -25,4 +25,4 @@ export type { HotClient, HotOnConnect, RsbuildDevServer } from './server/devServ
25
25
  export type { RsbuildServerBase, ServerStartResult, StartDevServerResult, StartPreviewServerResult } from './server/helper.js';
26
26
  export type { RsbuildPreviewServer } from './server/previewServer.js';
27
27
  // Types
28
- export type { AliasStrategy, AppIcon, AppIconItem, AutoExternal, AutoExternalExclude, Build, BuildOptions, BuildResult, Charset, CleanDistPath, CleanDistPathObject, ClientConfig, CliShortcut, CompressOptions, ConfigChain, ConfigChainWithContext, Connect, ConsoleType, CreateCompiler, CreateRsbuildOptions, CrossOrigin, CSSLoaderOptions, CSSModules, CSSModulesLocalsConvention, DataUriLimit, Decorators, DevConfig, DistPathConfig, EnvironmentConfig, EnvironmentContext, FilenameConfig, FilenameHash, HistoryApiFallbackContext, HistoryApiFallbackOptions, HtmlBasicTag, HtmlConfig, HtmlFallback, HtmlRspackPlugin, HtmlTag, HtmlTagContext, HtmlTagDescriptor, HtmlTagHandler, InitConfigsOptions, InlineChunkConfig, InlineChunkTest, InlineChunkTestFunction, InspectConfigOptions, InspectConfigResult, InternalContext, LegalComments, LogLevel, ManifestConfig, ManifestData, ManifestObjectConfig, MergedEnvironmentConfig, MetaAttrs, MetaOptions, Minify, ModifyBundlerChainFn, ModifyBundlerChainUtils, ModifyChainUtils, ModifyEnvironmentConfigFn, ModifyEnvironmentConfigUtils, ModifyHTMLContext, ModifyHTMLFn, ModifyHTMLTagsContext, ModifyHTMLTagsFn, ModifyRsbuildConfigFn, ModifyRsbuildConfigUtils, ModifyRspackConfigFn, ModifyRspackConfigUtils, ModuleFederationConfig, NormalizedConfig, NormalizedDevConfig, NormalizedEnvironmentConfig, NormalizedHtmlConfig, NormalizedModuleFederationConfig, NormalizedOutputConfig, NormalizedPerformanceConfig, NormalizedResolveConfig, NormalizedSecurityConfig, NormalizedServerConfig, NormalizedSourceConfig, NormalizedSplitChunksConfig, NormalizedToolsConfig, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterDevCompileFn, OnAfterEnvironmentCompileFn, OnAfterStartDevServerFn, OnAfterStartPreviewServerFn, OnBeforeBuildFn, OnBeforeCreateCompilerFn, OnBeforeDevCompileFn, OnBeforeEnvironmentCompileFn, OnBeforeStartDevServerFn, OnBeforeStartPreviewServerFn, OnCloseBuildFn, OnCloseDevServerFn, OnDevCompileDoneFn, OnExitFn, OnRestartFn, OutputConfig, OverlayOptions, OutputStructure, PerformanceConfig, PluginManager, Polyfill, PostCSSLoaderOptions, PostCSSOptions, PostCSSPlugin, PreconnectOption, PreviewOptions, PrintUrls, ProcessAssetsDescriptor, ProcessAssetsHandler, ProcessAssetsHook, ProgressBarConfig, ProxyBypass, ProxyConfig, ProxyFilter, ProxyOptions, PublicDir, PublicDirOptions, ReadonlyRoutes, RequestHandler, ResolveConfig, ResolvedCreateRsbuildOptions, ResolveHandler, ResolveHook, ResourceHintsIncludeType, RestartContext, RestartFn, RsbuildConfig, RsbuildContext, RsbuildEntry, RsbuildEntryDescription, RsbuildInstance, RsbuildMode, RsbuildPlugin, RsbuildPluginAPI, RsbuildPlugins, RsbuildTarget, RspackChain, RspackRule, ScriptInject, ScriptLoading, SecurityConfig, ServerConfig, SetupMiddlewaresContext, SetupMiddlewaresFn, SourceConfig, SourceMap, SourceMapExtract, SourceMapExtractOptions, SourceMapExtractTarget, SplitChunks, SplitChunksConfig, SplitChunksPreset, SriAlgorithm, SriOptions, StartDevServerOptions, StyleLoaderOptions, ToolsConfig, TransformContext, TransformDescriptor, TransformHandler, TransformHook, TransformImport, WatchFileEvent, WatchFiles, WebSocketUrlResolver } from './types/index.js';
28
+ export type { AliasStrategy, AppIcon, AppIconItem, AutoExternal, AutoExternalExclude, Build, BuildOptions, BuildResult, Charset, CleanDistPath, CleanDistPathObject, ClientConfig, CliShortcut, CompressOptions, ConfigChain, ConfigChainWithContext, Connect, ConsoleType, CreateCompiler, CreateRsbuildOptions, CrossOrigin, CSSLoaderOptions, CSSModules, CSSModulesLocalsConvention, DataUriLimit, Decorators, DevConfig, DistPathConfig, EnvironmentConfig, EnvironmentContext, FilenameConfig, FilenameHash, HistoryApiFallbackContext, HistoryApiFallbackOptions, HtmlBasicTag, HtmlConfig, HtmlFallback, HtmlRspackPlugin, HtmlTag, HtmlTagContext, HtmlTagDescriptor, HtmlTagHandler, InitConfigsOptions, InlineChunkConfig, InlineChunkTest, InlineChunkTestFunction, InspectConfigOptions, InspectConfigResult, InternalContext, LegalComments, LogLevel, ManifestConfig, ManifestData, ManifestObjectConfig, MergedEnvironmentConfig, MetaAttrs, MetaOptions, Minify, ModifyBundlerChainFn, ModifyBundlerChainUtils, ModifyChainUtils, ModifyEnvironmentConfigFn, ModifyEnvironmentConfigUtils, ModifyHTMLContext, ModifyHTMLFn, ModifyHTMLTagsContext, ModifyHTMLTagsFn, ModifyRsbuildConfigFn, ModifyRsbuildConfigUtils, ModifyRspackConfigFn, ModifyRspackConfigUtils, ModuleFederationConfig, NormalizedConfig, NormalizedDevConfig, NormalizedEnvironmentConfig, NormalizedHtmlConfig, NormalizedModuleFederationConfig, NormalizedOutputConfig, NormalizedPerformanceConfig, NormalizedResolveConfig, NormalizedSecurityConfig, NormalizedServerConfig, NormalizedSourceConfig, NormalizedSplitChunksConfig, NormalizedToolsConfig, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterDevCompileFn, OnAfterEnvironmentCompileFn, OnAfterStartDevServerFn, OnAfterStartPreviewServerFn, OnBeforeBuildFn, OnBeforeCreateCompilerFn, OnBeforeDevCompileFn, OnBeforeEnvironmentCompileFn, OnBeforeStartDevServerFn, OnBeforeStartPreviewServerFn, OnCloseBuildFn, OnCloseDevServerFn, OnDevCompileDoneFn, OnExitFn, OnRestartFn, OutputConfig, OverlayOptions, OutputStructure, PerformanceConfig, PluginManager, Polyfill, PostCSSLoaderOptions, PostCSSOptions, PostCSSPlugin, PreconnectOption, PreviewOptions, PrintUrls, ProcessAssetsDescriptor, ProcessAssetsHandler, ProcessAssetsHook, ProgressBarConfig, ProxyBypass, ProxyConfig, ProxyFilter, ProxyOptions, PublicDir, PublicDirOptions, ReadonlyRoutes, RequestHandler, ResolveConfig, ResolvedCreateRsbuildOptions, ResolveHandler, ResolveHook, ResourceHintsIncludeType, RestartContext, RestartFn, RsbuildConfig, RsbuildContext, RsbuildEntry, RsbuildEntryDescription, RsbuildInstance, RsbuildMiddlewares, RsbuildMode, RsbuildPlugin, RsbuildPluginAPI, RsbuildPlugins, RsbuildServerResponse, RsbuildTarget, RspackChain, RspackRule, ScriptInject, ScriptLoading, SecurityConfig, ServerConfig, SetupMiddlewaresContext, SetupMiddlewaresFn, SourceConfig, SourceMap, SourceMapExtract, SourceMapExtractOptions, SourceMapExtractTarget, SplitChunks, SplitChunksConfig, SplitChunksPreset, SriAlgorithm, SriOptions, StartDevServerOptions, StyleLoaderOptions, ToolsConfig, TransformContext, TransformDescriptor, TransformHandler, TransformHook, TransformImport, WatchFileEvent, WatchFiles, WebSocketUrlResolver } from './types/index.js';
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
- export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createLogger, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig, loadEnv, logger, mergeRsbuildConfig, rspack, runCLI, version } from "./m.js";
1
+ export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME } from "./1.js";
2
+ export { createLogger, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig, loadEnv, logger, mergeRsbuildConfig, rspack, runCLI, version } from "./m.js";