@rsbuild/core 1.4.0-beta.2 → 1.4.0-beta.4
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/compiled/css-loader/index.js +41 -41
- package/compiled/html-rspack-plugin/index.js +14 -14
- package/compiled/launch-editor-middleware/index.js +8 -8
- package/compiled/postcss/index.js +110 -110
- package/compiled/postcss/package.json +1 -1
- package/compiled/postcss-load-config/index.js +10 -10
- package/compiled/postcss-loader/index.js +6 -6
- package/compiled/rslog/index.d.ts +1 -1
- package/compiled/rslog/index.js +260 -309
- package/compiled/rslog/package.json +1 -1
- package/compiled/rspack-manifest-plugin/index.js +4 -4
- package/compiled/tinyglobby/index.js +88 -80
- package/compiled/webpack-bundle-analyzer/index.js +148 -25
- package/dist/client/overlay.js +2 -2
- package/dist/index.cjs +70 -210
- package/dist/index.js +401 -551
- package/dist-types/helpers/index.d.ts +1 -1
- package/dist-types/plugins/lazyCompilation.d.ts +2 -0
- package/dist-types/types/config.d.ts +9 -0
- package/package.json +9 -10
- package/types.d.ts +25 -0
package/dist/index.js
CHANGED
|
@@ -1,25 +1,20 @@
|
|
|
1
1
|
/*! For license information please see index.js.LICENSE.txt */
|
|
2
2
|
let swcHelpersPath, pluginHelper_htmlPlugin, cssExtractPlugin;
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import
|
|
10
|
-
import
|
|
11
|
-
import
|
|
12
|
-
import
|
|
13
|
-
import
|
|
14
|
-
import
|
|
15
|
-
import
|
|
16
|
-
import
|
|
17
|
-
import
|
|
18
|
-
import * as __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__ from "node:util";
|
|
19
|
-
import * as __WEBPACK_EXTERNAL_MODULE__compiled_mrmime_index_js_86f064ca__ from "../compiled/mrmime/index.js";
|
|
20
|
-
import * as __WEBPACK_EXTERNAL_MODULE__compiled_rspack_chain_index_js_b67fefbd__ from "../compiled/rspack-chain/index.js";
|
|
21
|
-
import * as __WEBPACK_EXTERNAL_MODULE_node_zlib_a5bb16fc__ from "node:zlib";
|
|
22
|
-
import * as __WEBPACK_EXTERNAL_MODULE_events__ from "events";
|
|
3
|
+
import { rspack } from "@rspack/core";
|
|
4
|
+
import external_node_fs_default, { existsSync } from "node:fs";
|
|
5
|
+
import external_node_path_default, { dirname, isAbsolute as external_node_path_isAbsolute, join, posix, relative, sep } from "node:path";
|
|
6
|
+
import { URL as external_node_url_URL, fileURLToPath, pathToFileURL } from "node:url";
|
|
7
|
+
import index_js_default from "../compiled/picocolors/index.js";
|
|
8
|
+
import { logger } from "../compiled/rslog/index.js";
|
|
9
|
+
import { isPromise, isRegExp } from "node:util/types";
|
|
10
|
+
import { createRequire } from "node:module";
|
|
11
|
+
import external_node_os_default, { constants } from "node:os";
|
|
12
|
+
import external_node_process_default from "node:process";
|
|
13
|
+
import { promisify as external_node_util_promisify } from "node:util";
|
|
14
|
+
import { lookup } from "../compiled/mrmime/index.js";
|
|
15
|
+
import rspack_chain_index_js_default from "../compiled/rspack-chain/index.js";
|
|
16
|
+
import external_node_zlib_default from "node:zlib";
|
|
17
|
+
import { EventEmitter } from "events";
|
|
23
18
|
var EsmMode, __webpack_modules__ = {
|
|
24
19
|
"../../node_modules/.pnpm/clone-deep@4.0.1/node_modules/clone-deep/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
|
|
25
20
|
let clone = __webpack_require__("../../node_modules/.pnpm/shallow-clone@3.0.1/node_modules/shallow-clone/index.js"), typeOf = __webpack_require__("../../node_modules/.pnpm/kind-of@6.0.3/node_modules/kind-of/index.js"), isPlainObject = __webpack_require__("../../node_modules/.pnpm/is-plain-object@2.0.4/node_modules/is-plain-object/index.js");
|
|
@@ -119,154 +114,6 @@ var EsmMode, __webpack_modules__ = {
|
|
|
119
114
|
return options;
|
|
120
115
|
};
|
|
121
116
|
},
|
|
122
|
-
"../../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/main.js": function(module, __unused_webpack_exports, __webpack_require__) {
|
|
123
|
-
let fs = __webpack_require__("fs"), path = __webpack_require__("path"), os = __webpack_require__("os"), crypto = __webpack_require__("crypto"), version = __webpack_require__("../../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/package.json").version, LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
|
|
124
|
-
function _debug(message) {
|
|
125
|
-
console.log(`[dotenv@${version}][DEBUG] ${message}`);
|
|
126
|
-
}
|
|
127
|
-
function _dotenvKey(options) {
|
|
128
|
-
return options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0 ? options.DOTENV_KEY : process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0 ? process.env.DOTENV_KEY : '';
|
|
129
|
-
}
|
|
130
|
-
function _vaultPath(options) {
|
|
131
|
-
let possibleVaultPath = null;
|
|
132
|
-
if (options && options.path && options.path.length > 0) if (Array.isArray(options.path)) for (let filepath of options.path)fs.existsSync(filepath) && (possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`);
|
|
133
|
-
else possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`;
|
|
134
|
-
else possibleVaultPath = path.resolve(process.cwd(), '.env.vault');
|
|
135
|
-
return fs.existsSync(possibleVaultPath) ? possibleVaultPath : null;
|
|
136
|
-
}
|
|
137
|
-
function _resolveHome(envPath) {
|
|
138
|
-
return '~' === envPath[0] ? path.join(os.homedir(), envPath.slice(1)) : envPath;
|
|
139
|
-
}
|
|
140
|
-
let DotenvModule = {
|
|
141
|
-
configDotenv: function(options) {
|
|
142
|
-
let lastError, dotenvPath = path.resolve(process.cwd(), '.env'), encoding = 'utf8', debug = !!(options && options.debug);
|
|
143
|
-
options && options.encoding ? encoding = options.encoding : debug && _debug('No encoding is specified. UTF-8 is used by default');
|
|
144
|
-
let optionPaths = [
|
|
145
|
-
dotenvPath
|
|
146
|
-
];
|
|
147
|
-
if (options && options.path) if (Array.isArray(options.path)) for (let filepath of (optionPaths = [], options.path))optionPaths.push(_resolveHome(filepath));
|
|
148
|
-
else optionPaths = [
|
|
149
|
-
_resolveHome(options.path)
|
|
150
|
-
];
|
|
151
|
-
let parsedAll = {};
|
|
152
|
-
for (let path of optionPaths)try {
|
|
153
|
-
let parsed = DotenvModule.parse(fs.readFileSync(path, {
|
|
154
|
-
encoding
|
|
155
|
-
}));
|
|
156
|
-
DotenvModule.populate(parsedAll, parsed, options);
|
|
157
|
-
} catch (e) {
|
|
158
|
-
debug && _debug(`Failed to load ${path} ${e.message}`), lastError = e;
|
|
159
|
-
}
|
|
160
|
-
let processEnv = process.env;
|
|
161
|
-
return (options && null != options.processEnv && (processEnv = options.processEnv), DotenvModule.populate(processEnv, parsedAll, options), lastError) ? {
|
|
162
|
-
parsed: parsedAll,
|
|
163
|
-
error: lastError
|
|
164
|
-
} : {
|
|
165
|
-
parsed: parsedAll
|
|
166
|
-
};
|
|
167
|
-
},
|
|
168
|
-
_configVault: function(options) {
|
|
169
|
-
options && options.debug && _debug('Loading env from encrypted .env.vault');
|
|
170
|
-
let parsed = DotenvModule._parseVault(options), processEnv = process.env;
|
|
171
|
-
return options && null != options.processEnv && (processEnv = options.processEnv), DotenvModule.populate(processEnv, parsed, options), {
|
|
172
|
-
parsed
|
|
173
|
-
};
|
|
174
|
-
},
|
|
175
|
-
_parseVault: function(options) {
|
|
176
|
-
let decrypted, vaultPath = _vaultPath(options), result = DotenvModule.configDotenv({
|
|
177
|
-
path: vaultPath
|
|
178
|
-
});
|
|
179
|
-
if (!result.parsed) {
|
|
180
|
-
let err = Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
|
|
181
|
-
throw err.code = 'MISSING_DATA', err;
|
|
182
|
-
}
|
|
183
|
-
let keys = _dotenvKey(options).split(','), length = keys.length;
|
|
184
|
-
for(let i = 0; i < length; i++)try {
|
|
185
|
-
let key = keys[i].trim(), attrs = function(result, dotenvKey) {
|
|
186
|
-
let uri;
|
|
187
|
-
try {
|
|
188
|
-
uri = new URL(dotenvKey);
|
|
189
|
-
} catch (error) {
|
|
190
|
-
if ('ERR_INVALID_URL' === error.code) {
|
|
191
|
-
let err = Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development');
|
|
192
|
-
throw err.code = 'INVALID_DOTENV_KEY', err;
|
|
193
|
-
}
|
|
194
|
-
throw error;
|
|
195
|
-
}
|
|
196
|
-
let key = uri.password;
|
|
197
|
-
if (!key) {
|
|
198
|
-
let err = Error('INVALID_DOTENV_KEY: Missing key part');
|
|
199
|
-
throw err.code = 'INVALID_DOTENV_KEY', err;
|
|
200
|
-
}
|
|
201
|
-
let environment = uri.searchParams.get('environment');
|
|
202
|
-
if (!environment) {
|
|
203
|
-
let err = Error('INVALID_DOTENV_KEY: Missing environment part');
|
|
204
|
-
throw err.code = 'INVALID_DOTENV_KEY', err;
|
|
205
|
-
}
|
|
206
|
-
let environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`, ciphertext = result.parsed[environmentKey];
|
|
207
|
-
if (!ciphertext) {
|
|
208
|
-
let err = Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
|
|
209
|
-
throw err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT', err;
|
|
210
|
-
}
|
|
211
|
-
return {
|
|
212
|
-
ciphertext,
|
|
213
|
-
key
|
|
214
|
-
};
|
|
215
|
-
}(result, key);
|
|
216
|
-
decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
|
|
217
|
-
break;
|
|
218
|
-
} catch (error) {
|
|
219
|
-
if (i + 1 >= length) throw error;
|
|
220
|
-
}
|
|
221
|
-
return DotenvModule.parse(decrypted);
|
|
222
|
-
},
|
|
223
|
-
config: function(options) {
|
|
224
|
-
if (0 === _dotenvKey(options).length) return DotenvModule.configDotenv(options);
|
|
225
|
-
let vaultPath = _vaultPath(options);
|
|
226
|
-
if (!vaultPath) {
|
|
227
|
-
var message;
|
|
228
|
-
return message = `You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`, console.log(`[dotenv@${version}][WARN] ${message}`), DotenvModule.configDotenv(options);
|
|
229
|
-
}
|
|
230
|
-
return DotenvModule._configVault(options);
|
|
231
|
-
},
|
|
232
|
-
decrypt: function(encrypted, keyStr) {
|
|
233
|
-
let key = Buffer.from(keyStr.slice(-64), 'hex'), ciphertext = Buffer.from(encrypted, 'base64'), nonce = ciphertext.subarray(0, 12), authTag = ciphertext.subarray(-16);
|
|
234
|
-
ciphertext = ciphertext.subarray(12, -16);
|
|
235
|
-
try {
|
|
236
|
-
let aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce);
|
|
237
|
-
return aesgcm.setAuthTag(authTag), `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
|
|
238
|
-
} catch (error) {
|
|
239
|
-
let isRange = error instanceof RangeError, invalidKeyLength = 'Invalid key length' === error.message, decryptionFailed = 'Unsupported state or unable to authenticate data' === error.message;
|
|
240
|
-
if (isRange || invalidKeyLength) {
|
|
241
|
-
let err = Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)');
|
|
242
|
-
throw err.code = 'INVALID_DOTENV_KEY', err;
|
|
243
|
-
}
|
|
244
|
-
if (decryptionFailed) {
|
|
245
|
-
let err = Error('DECRYPTION_FAILED: Please check your DOTENV_KEY');
|
|
246
|
-
throw err.code = 'DECRYPTION_FAILED', err;
|
|
247
|
-
}
|
|
248
|
-
throw error;
|
|
249
|
-
}
|
|
250
|
-
},
|
|
251
|
-
parse: function(src) {
|
|
252
|
-
let match, obj = {}, lines = src.toString();
|
|
253
|
-
for(lines = lines.replace(/\r\n?/mg, '\n'); null != (match = LINE.exec(lines));){
|
|
254
|
-
let key = match[1], value = match[2] || '', maybeQuote = (value = value.trim())[0];
|
|
255
|
-
value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2'), '"' === maybeQuote && (value = (value = value.replace(/\\n/g, '\n')).replace(/\\r/g, '\r')), obj[key] = value;
|
|
256
|
-
}
|
|
257
|
-
return obj;
|
|
258
|
-
},
|
|
259
|
-
populate: function(processEnv, parsed, options = {}) {
|
|
260
|
-
let debug = !!(options && options.debug), override = !!(options && options.override);
|
|
261
|
-
if ('object' != typeof parsed) {
|
|
262
|
-
let err = Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate');
|
|
263
|
-
throw err.code = 'OBJECT_REQUIRED', err;
|
|
264
|
-
}
|
|
265
|
-
for (let key of Object.keys(parsed))Object.prototype.hasOwnProperty.call(processEnv, key) ? (!0 === override && (processEnv[key] = parsed[key]), debug && (!0 === override ? _debug(`"${key}" is already defined and WAS overwritten`) : _debug(`"${key}" is already defined and was NOT overwritten`))) : processEnv[key] = parsed[key];
|
|
266
|
-
}
|
|
267
|
-
};
|
|
268
|
-
module.exports.configDotenv = DotenvModule.configDotenv, module.exports._configVault = DotenvModule._configVault, module.exports._parseVault = DotenvModule._parseVault, module.exports.config = DotenvModule.config, module.exports.decrypt = DotenvModule.decrypt, module.exports.parse = DotenvModule.parse, module.exports.populate = DotenvModule.populate, module.exports = DotenvModule;
|
|
269
|
-
},
|
|
270
117
|
"../../node_modules/.pnpm/flat@5.0.2/node_modules/flat/index.js": function(module) {
|
|
271
118
|
function isBuffer(obj) {
|
|
272
119
|
return obj && obj.constructor && 'function' == typeof obj.constructor.isBuffer && obj.constructor.isBuffer(obj);
|
|
@@ -873,21 +720,6 @@ var EsmMode, __webpack_modules__ = {
|
|
|
873
720
|
var matcher = new WildcardMatcher(text, separator || /[\/\.]/);
|
|
874
721
|
return void 0 !== test ? matcher.match(test) : matcher;
|
|
875
722
|
};
|
|
876
|
-
},
|
|
877
|
-
crypto: function(module) {
|
|
878
|
-
module.exports = __WEBPACK_EXTERNAL_MODULE_crypto__;
|
|
879
|
-
},
|
|
880
|
-
fs: function(module) {
|
|
881
|
-
module.exports = __WEBPACK_EXTERNAL_MODULE_fs__;
|
|
882
|
-
},
|
|
883
|
-
os: function(module) {
|
|
884
|
-
module.exports = __WEBPACK_EXTERNAL_MODULE_os__;
|
|
885
|
-
},
|
|
886
|
-
path: function(module) {
|
|
887
|
-
module.exports = __WEBPACK_EXTERNAL_MODULE_path__;
|
|
888
|
-
},
|
|
889
|
-
"../../node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/package.json": function(module) {
|
|
890
|
-
module.exports = JSON.parse('{"name":"dotenv","version":"16.5.0","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}');
|
|
891
723
|
}
|
|
892
724
|
}, __webpack_module_cache__ = {};
|
|
893
725
|
function __webpack_require__(moduleId) {
|
|
@@ -932,8 +764,8 @@ __webpack_require__.r(provider_helpers_namespaceObject), __webpack_require__.d(p
|
|
|
932
764
|
setCssExtractPlugin: ()=>setCssExtractPlugin,
|
|
933
765
|
setHTMLPlugin: ()=>setHTMLPlugin
|
|
934
766
|
});
|
|
935
|
-
var main = __webpack_require__("../../node_modules/.pnpm/dotenv
|
|
936
|
-
let constants_filename =
|
|
767
|
+
var main = __webpack_require__("../../node_modules/.pnpm/dotenv-expand@12.0.2/node_modules/dotenv-expand/lib/main.js"), cjs = __webpack_require__("../../node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js"), cjs_default = __webpack_require__.n(cjs);
|
|
768
|
+
let constants_filename = fileURLToPath(import.meta.url), constants_dirname = dirname(constants_filename), ROOT_DIST_DIR = 'dist', LOADER_PATH = join(constants_dirname), STATIC_PATH = join(constants_dirname, '../static'), COMPILED_PATH = join(constants_dirname, '../compiled'), RSBUILD_OUTPUTS_PATH = '.rsbuild', DEFAULT_DEV_HOST = '0.0.0.0', DEFAULT_ASSET_PREFIX = '/', DEFAULT_WEB_BROWSERSLIST = [
|
|
937
769
|
'chrome >= 87',
|
|
938
770
|
'edge >= 88',
|
|
939
771
|
'firefox >= 78',
|
|
@@ -988,26 +820,26 @@ let constants_filename = (0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileU
|
|
|
988
820
|
'*'
|
|
989
821
|
].some((key)=>values.includes(key));
|
|
990
822
|
};
|
|
991
|
-
isDebug() && (
|
|
823
|
+
isDebug() && (logger.level = 'verbose'), logger.override({
|
|
992
824
|
debug: (message, ...args)=>{
|
|
993
|
-
if ('verbose' !==
|
|
994
|
-
let time =
|
|
825
|
+
if ('verbose' !== logger.level) return;
|
|
826
|
+
let time = index_js_default.gray(`${function() {
|
|
995
827
|
let now = new Date(), hours = String(now.getHours()).padStart(2, '0'), minutes = String(now.getMinutes()).padStart(2, '0'), seconds = String(now.getSeconds()).padStart(2, '0');
|
|
996
828
|
return `${hours}:${minutes}:${seconds}`;
|
|
997
829
|
}()}`);
|
|
998
|
-
console.log(` ${
|
|
830
|
+
console.log(` ${index_js_default.magenta('rsbuild')} ${time} ${message}`, ...args);
|
|
999
831
|
}
|
|
1000
832
|
});
|
|
1001
|
-
let getCompiledPath = (packageName)=>
|
|
833
|
+
let getCompiledPath = (packageName)=>join(COMPILED_PATH, packageName, 'index.js'), ensureAbsolutePath = (base, filePath)=>external_node_path_isAbsolute(filePath) ? filePath : join(base, filePath), getPathnameFromUrl = (publicPath)=>{
|
|
1002
834
|
try {
|
|
1003
835
|
return publicPath ? new URL(publicPath).pathname : publicPath;
|
|
1004
836
|
} catch (err) {
|
|
1005
837
|
return publicPath;
|
|
1006
838
|
}
|
|
1007
|
-
}, 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)=>'/' ===
|
|
839
|
+
}, 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)=>'/' === sep ? filepath : filepath.replace(/\\/g, '/'), isFileSync = (filePath)=>{
|
|
1008
840
|
try {
|
|
1009
841
|
var _fs_statSync;
|
|
1010
|
-
return null == (_fs_statSync =
|
|
842
|
+
return null == (_fs_statSync = external_node_fs_default.statSync(filePath, {
|
|
1011
843
|
throwIfNoEntry: !1
|
|
1012
844
|
})) ? void 0 : _fs_statSync.isFile();
|
|
1013
845
|
} catch (_) {
|
|
@@ -1018,10 +850,10 @@ let getCompiledPath = (packageName)=>(0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b
|
|
|
1018
850
|
return !1;
|
|
1019
851
|
};
|
|
1020
852
|
async function pathExists(path) {
|
|
1021
|
-
return
|
|
853
|
+
return external_node_fs_default.promises.access(path).then(()=>!0).catch(()=>!1);
|
|
1022
854
|
}
|
|
1023
855
|
async function isFileExists(file) {
|
|
1024
|
-
return
|
|
856
|
+
return external_node_fs_default.promises.access(file, external_node_fs_default.constants.F_OK).then(()=>!0).catch(()=>!1);
|
|
1025
857
|
}
|
|
1026
858
|
async function fileExistsByCompilation({ inputFileSystem }, filePath) {
|
|
1027
859
|
return new Promise((resolve)=>{
|
|
@@ -1033,26 +865,26 @@ async function fileExistsByCompilation({ inputFileSystem }, filePath) {
|
|
|
1033
865
|
}
|
|
1034
866
|
async function emptyDir(dir, keep = [], checkExists = !0) {
|
|
1035
867
|
if (!checkExists || await pathExists(dir)) try {
|
|
1036
|
-
let entries = await
|
|
868
|
+
let entries = await external_node_fs_default.promises.readdir(dir, {
|
|
1037
869
|
withFileTypes: !0
|
|
1038
870
|
});
|
|
1039
871
|
await Promise.all(entries.map(async (entry)=>{
|
|
1040
|
-
let fullPath =
|
|
1041
|
-
!keep.some((reg)=>reg.test(toPosixPath(fullPath))) && (entry.isDirectory() ? (await emptyDir(fullPath, keep, !1), keep.length || await
|
|
872
|
+
let fullPath = external_node_path_default.join(dir, entry.name);
|
|
873
|
+
!keep.some((reg)=>reg.test(toPosixPath(fullPath))) && (entry.isDirectory() ? (await emptyDir(fullPath, keep, !1), keep.length || await external_node_fs_default.promises.rmdir(fullPath)) : await external_node_fs_default.promises.unlink(fullPath));
|
|
1042
874
|
}));
|
|
1043
875
|
} catch (err) {
|
|
1044
|
-
|
|
876
|
+
logger.debug(`failed to empty dir: ${dir}`), logger.debug(err);
|
|
1045
877
|
}
|
|
1046
878
|
}
|
|
1047
|
-
let formatFileName = (fileName)=>/:\d+:\d+/.test(fileName) ? `File: ${
|
|
879
|
+
let formatFileName = (fileName)=>/:\d+:\d+/.test(fileName) ? `File: ${index_js_default.cyan(fileName)}\n` : `File: ${index_js_default.cyan(`${fileName}:1:1`)}\n`, hintNodePolyfill = (message)=>{
|
|
1048
880
|
let getTips = (moduleName)=>{
|
|
1049
881
|
let tips = [
|
|
1050
882
|
`Error: "${moduleName}" is a built-in Node.js module and cannot be imported in client-side code.\n`,
|
|
1051
883
|
'Solution: Check if you need to import Node.js module.',
|
|
1052
884
|
' - If not needed, remove the import.',
|
|
1053
|
-
` - If needed, use "${
|
|
885
|
+
` - If needed, use "${index_js_default.yellow('@rsbuild/plugin-node-polyfill')}" to polyfill it. (See ${index_js_default.yellow('https://npmjs.com/package/@rsbuild/plugin-node-polyfill')})`
|
|
1054
886
|
];
|
|
1055
|
-
return `${message}\n\n${
|
|
887
|
+
return `${message}\n\n${index_js_default.red(tips.join('\n'))}`;
|
|
1056
888
|
};
|
|
1057
889
|
if (message.includes('need an additional plugin to handle "node:" URIs')) return getTips('node:*');
|
|
1058
890
|
if (!message.includes("Can't resolve")) return message;
|
|
@@ -1124,7 +956,7 @@ function formatMessage(stats, verbose) {
|
|
|
1124
956
|
return !verbose && message.includes(innerError) && (message = message.split(innerError)[0]), (message = (message = hintNodePolyfill(message = function(message) {
|
|
1125
957
|
let hint = 'You may need an appropriate loader to handle this file type.';
|
|
1126
958
|
if (-1 === message.indexOf(hint)) return message;
|
|
1127
|
-
let createPluginHint = (packageName, keyword)=>`To enable support for ${keyword}, use "${
|
|
959
|
+
let createPluginHint = (packageName, keyword)=>`To enable support for ${keyword}, use "${index_js_default.yellow(`@rsbuild/plugin-${packageName}`)}" ${index_js_default.dim(`(https://npmjs.com/package/@rsbuild/plugin-${packageName})`)}.`;
|
|
1128
960
|
for (let plugin of [
|
|
1129
961
|
{
|
|
1130
962
|
test: /File: .+\.s(c|a)ss/,
|
|
@@ -1186,7 +1018,7 @@ function getStatsOptions(compiler) {
|
|
|
1186
1018
|
} : 'object' == typeof stats ? stats : {};
|
|
1187
1019
|
}
|
|
1188
1020
|
function formatStats(statsData, hasErrors) {
|
|
1189
|
-
let verbose = 'verbose' ===
|
|
1021
|
+
let verbose = 'verbose' === logger.level;
|
|
1190
1022
|
if (hasErrors) {
|
|
1191
1023
|
let { errors } = formatStatsMessages({
|
|
1192
1024
|
errors: getAllStatsErrors(statsData),
|
|
@@ -1194,8 +1026,8 @@ function formatStats(statsData, hasErrors) {
|
|
|
1194
1026
|
}, verbose);
|
|
1195
1027
|
return {
|
|
1196
1028
|
message: function(errors) {
|
|
1197
|
-
let title =
|
|
1198
|
-
if (!errors.length) return `${title}\n${
|
|
1029
|
+
let title = index_js_default.bold(index_js_default.red(errors.length > 1 ? 'Build errors: ' : 'Build error: '));
|
|
1030
|
+
if (!errors.length) return `${title}\n${index_js_default.yellow("For more details, please setting 'stats.errors: true' ")}`;
|
|
1199
1031
|
let text = `${errors.join('\n\n')}\n`;
|
|
1200
1032
|
return `${title}\n${text}`;
|
|
1201
1033
|
}(errors),
|
|
@@ -1207,7 +1039,7 @@ function formatStats(statsData, hasErrors) {
|
|
|
1207
1039
|
warnings: getAllStatsWarnings(statsData)
|
|
1208
1040
|
}, verbose);
|
|
1209
1041
|
if (warnings.length) {
|
|
1210
|
-
let title =
|
|
1042
|
+
let title = index_js_default.bold(index_js_default.yellow(warnings.length > 1 ? 'Build warnings: \n' : 'Build warning: \n'));
|
|
1211
1043
|
return {
|
|
1212
1044
|
message: `${title}${warnings.join('\n\n')}\n`,
|
|
1213
1045
|
level: 'warning'
|
|
@@ -1240,14 +1072,14 @@ let rspackMinVersion = '1.2.4', getNodeEnv = ()=>process.env.NODE_ENV, setNodeEn
|
|
|
1240
1072
|
return 'string' == typeof publicPath ? 'auto' === publicPath ? '' : publicPath.endsWith('/') ? publicPath : `${publicPath}/` : DEFAULT_ASSET_PREFIX;
|
|
1241
1073
|
}, urlJoin = (base, path)=>{
|
|
1242
1074
|
let [urlProtocol, baseUrl] = base.split('://');
|
|
1243
|
-
return `${urlProtocol}://${
|
|
1075
|
+
return `${urlProtocol}://${posix.join(baseUrl, path)}`;
|
|
1244
1076
|
}, canParse = (url)=>{
|
|
1245
1077
|
try {
|
|
1246
|
-
return new
|
|
1078
|
+
return new external_node_url_URL(url), !0;
|
|
1247
1079
|
} catch {
|
|
1248
1080
|
return !1;
|
|
1249
1081
|
}
|
|
1250
|
-
}, 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:', '') :
|
|
1082
|
+
}, 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:', '') : posix.join(assetPrefix, url);
|
|
1251
1083
|
function getFilename(config, type, isProd, isServer) {
|
|
1252
1084
|
let { filename, filenameHash } = config.output, hash = 'string' == typeof filenameHash ? filenameHash ? `.[${filenameHash}]` : '' : filenameHash ? '.[contenthash:8]' : '';
|
|
1253
1085
|
switch(type){
|
|
@@ -1266,7 +1098,7 @@ function getFilename(config, type, isProd, isServer) {
|
|
|
1266
1098
|
case 'assets':
|
|
1267
1099
|
return filename.assets ?? `[name]${hash}[ext]`;
|
|
1268
1100
|
default:
|
|
1269
|
-
throw Error(`${
|
|
1101
|
+
throw Error(`${index_js_default.dim('[rsbuild:config]')} unknown key ${index_js_default.yellow(type)} in ${index_js_default.yellow('output.filename')}`);
|
|
1270
1102
|
}
|
|
1271
1103
|
}
|
|
1272
1104
|
let applyToCompiler = (compiler, apply)=>{
|
|
@@ -1276,7 +1108,7 @@ function pick(obj, keys) {
|
|
|
1276
1108
|
return keys.reduce((ret, key)=>(void 0 !== obj[key] && (ret[key] = obj[key]), ret), {});
|
|
1277
1109
|
}
|
|
1278
1110
|
let camelCase = (input)=>input.replace(/[-_](\w)/g, (_, c)=>c.toUpperCase()), prettyTime = (seconds)=>{
|
|
1279
|
-
let format = (time)=>
|
|
1111
|
+
let format = (time)=>index_js_default.bold(time);
|
|
1280
1112
|
if (seconds < 10) {
|
|
1281
1113
|
let digits = seconds >= 0.01 ? 2 : 3;
|
|
1282
1114
|
return `${format(seconds.toFixed(digits))} s`;
|
|
@@ -1287,18 +1119,30 @@ let camelCase = (input)=>input.replace(/[-_](\w)/g, (_, c)=>c.toUpperCase()), pr
|
|
|
1287
1119
|
}, isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !process.env.CI, addCompilationError = (compilation, message)=>{
|
|
1288
1120
|
compilation.errors.push(new compilation.compiler.webpack.WebpackError(message));
|
|
1289
1121
|
};
|
|
1122
|
+
async function helpers_hash(data) {
|
|
1123
|
+
let crypto = await import("node:crypto");
|
|
1124
|
+
return crypto.hash ? crypto.hash('sha256', data, 'hex').slice(0, 16) : crypto.createHash('sha256').update(data).digest('hex').slice(0, 16);
|
|
1125
|
+
}
|
|
1126
|
+
let DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
|
|
1290
1127
|
function loadEnv({ cwd = process.cwd(), mode = getNodeEnv(), prefixes = [
|
|
1291
1128
|
'PUBLIC_'
|
|
1292
1129
|
], processEnv = process.env } = {}) {
|
|
1293
|
-
if ('local' === mode) throw Error(`${
|
|
1130
|
+
if ('local' === mode) throw Error(`${index_js_default.dim('[rsbuild:loadEnv]')} ${index_js_default.yellow('local')} cannot be used as a value for env mode, because ${index_js_default.yellow('.env.local')} represents a temporary local file. Please use another value.`);
|
|
1294
1131
|
let filePaths = [
|
|
1295
1132
|
'.env',
|
|
1296
1133
|
'.env.local',
|
|
1297
1134
|
`.env.${mode}`,
|
|
1298
1135
|
`.env.${mode}.local`
|
|
1299
|
-
].map((filename)=>
|
|
1300
|
-
for (let envPath of filePaths)Object.assign(parsed, (
|
|
1301
|
-
|
|
1136
|
+
].map((filename)=>join(cwd, filename)).filter(isFileSync), parsed = {};
|
|
1137
|
+
for (let envPath of filePaths)Object.assign(parsed, function(src) {
|
|
1138
|
+
let match, obj = {}, lines = src.toString();
|
|
1139
|
+
for(lines = lines.replace(/\r\n?/gm, '\n'); null != (match = DOTENV_LINE.exec(lines));){
|
|
1140
|
+
let key = match[1], value = match[2] || '', maybeQuote = (value = value.trim())[0];
|
|
1141
|
+
value = value.replace(/^(['"`])([\s\S]*)\1$/gm, '$2'), '"' === maybeQuote && (value = (value = value.replace(/\\n/g, '\n')).replace(/\\r/g, '\r')), obj[key] = value;
|
|
1142
|
+
}
|
|
1143
|
+
return obj;
|
|
1144
|
+
}(external_node_fs_default.readFileSync(envPath))), logger.debug('loaded env file:', envPath);
|
|
1145
|
+
parsed.NODE_ENV && (processEnv.NODE_ENV = parsed.NODE_ENV), (0, main.expand)({
|
|
1302
1146
|
parsed,
|
|
1303
1147
|
processEnv
|
|
1304
1148
|
});
|
|
@@ -1335,11 +1179,11 @@ class BrowserslistError extends Error {
|
|
|
1335
1179
|
let isFileCache = {};
|
|
1336
1180
|
function isFile(file) {
|
|
1337
1181
|
if (file in isFileCache) return isFileCache[file];
|
|
1338
|
-
let result =
|
|
1182
|
+
let result = external_node_fs_default.existsSync(file) && external_node_fs_default.statSync(file).isFile();
|
|
1339
1183
|
return isFileCache[file] = result, result;
|
|
1340
1184
|
}
|
|
1341
1185
|
function parsePackage(file) {
|
|
1342
|
-
let config = JSON.parse(
|
|
1186
|
+
let config = JSON.parse(external_node_fs_default.readFileSync(file).toString().replace(/^\uFEFF/m, ''));
|
|
1343
1187
|
if (config.browserlist && !config.browserslist) throw new BrowserslistError(`\`browserlist\` key instead of \`browserslist\` in ${file}`);
|
|
1344
1188
|
let list = config.browserslist;
|
|
1345
1189
|
for(let i in Array.isArray(list) && (list = {
|
|
@@ -1371,20 +1215,20 @@ function parseConfig(string) {
|
|
|
1371
1215
|
}), result;
|
|
1372
1216
|
}
|
|
1373
1217
|
function parsePackageOrReadConfig(file) {
|
|
1374
|
-
if ('package.json' ===
|
|
1218
|
+
if ('package.json' === external_node_path_default.basename(file)) return parsePackage(file);
|
|
1375
1219
|
if (!isFile(file)) throw new BrowserslistError(`Can't read ${file} config`);
|
|
1376
|
-
return parseConfig(
|
|
1220
|
+
return parseConfig(external_node_fs_default.readFileSync(file, 'utf-8'));
|
|
1377
1221
|
}
|
|
1378
1222
|
function pickEnv(config, opts) {
|
|
1379
1223
|
let name;
|
|
1380
1224
|
return 'object' != typeof config ? config : config['string' == typeof opts.env ? opts.env : process.env.BROWSERSLIST_ENV ? process.env.BROWSERSLIST_ENV : process.env.NODE_ENV ? process.env.NODE_ENV : 'production'] || config.defaults;
|
|
1381
1225
|
}
|
|
1382
1226
|
function eachParent(file, callback) {
|
|
1383
|
-
let dir = isFile(file) ?
|
|
1227
|
+
let dir = isFile(file) ? external_node_path_default.dirname(file) : file, loc = external_node_path_default.resolve(dir);
|
|
1384
1228
|
do {
|
|
1385
1229
|
let result = callback(loc);
|
|
1386
1230
|
if (void 0 !== result) return result;
|
|
1387
|
-
}while (loc !== (loc =
|
|
1231
|
+
}while (loc !== (loc = external_node_path_default.dirname(loc)));
|
|
1388
1232
|
}
|
|
1389
1233
|
let configCache = {}, OVERRIDE_PATHS = [
|
|
1390
1234
|
'performance.removeConsole',
|
|
@@ -1430,7 +1274,7 @@ let configCache = {}, OVERRIDE_PATHS = [
|
|
|
1430
1274
|
merged[key] = merge(x[key], y[key], childPath);
|
|
1431
1275
|
}
|
|
1432
1276
|
return merged;
|
|
1433
|
-
}, mergeRsbuildConfig = (...configs)=>2 === configs.length ? merge(configs[0], configs[1]) : configs.length < 2 ? configs[0] : configs.reduce((result, config)=>merge(result, config), {}), defaultConfig_require =
|
|
1277
|
+
}, mergeRsbuildConfig = (...configs)=>2 === configs.length ? merge(configs[0], configs[1]) : configs.length < 2 ? configs[0] : configs.reduce((result, config)=>merge(result, config), {}), defaultConfig_require = createRequire(import.meta.url), getDefaultDevConfig = ()=>({
|
|
1434
1278
|
hmr: !0,
|
|
1435
1279
|
liveReload: !0,
|
|
1436
1280
|
watchFiles: [],
|
|
@@ -1539,7 +1383,7 @@ let configCache = {}, OVERRIDE_PATHS = [
|
|
|
1539
1383
|
exportLocalsConvention: 'camelCase'
|
|
1540
1384
|
},
|
|
1541
1385
|
emitAssets: !0
|
|
1542
|
-
}), getDefaultResolveConfig = ()=>(swcHelpersPath || (swcHelpersPath =
|
|
1386
|
+
}), getDefaultResolveConfig = ()=>(swcHelpersPath || (swcHelpersPath = dirname(defaultConfig_require.resolve('@swc/helpers/package.json'))), {
|
|
1543
1387
|
alias: {
|
|
1544
1388
|
'@swc/helpers': swcHelpersPath
|
|
1545
1389
|
},
|
|
@@ -1567,7 +1411,7 @@ let configCache = {}, OVERRIDE_PATHS = [
|
|
|
1567
1411
|
var _merged_server, _config_dev, _config_output;
|
|
1568
1412
|
let merged = mergeRsbuildConfig(createDefaultConfig(), config);
|
|
1569
1413
|
if (merged.root ||= rootPath, merged.source ||= {}, (null == (_merged_server = merged.server) ? void 0 : _merged_server.base) && ((null == (_config_dev = config.dev) ? void 0 : _config_dev.assetPrefix) === void 0 && (merged.dev ||= {}, merged.dev.assetPrefix = merged.server.base), (null == (_config_output = config.output) ? void 0 : _config_output.assetPrefix) === void 0 && (merged.output ||= {}, merged.output.assetPrefix = merged.server.base)), !merged.source.tsconfigPath) {
|
|
1570
|
-
let tsconfigPath =
|
|
1414
|
+
let tsconfigPath = join(rootPath, 'tsconfig.json');
|
|
1571
1415
|
await isFileExists(tsconfigPath) && (merged.source.tsconfigPath = tsconfigPath);
|
|
1572
1416
|
}
|
|
1573
1417
|
return merged;
|
|
@@ -1605,7 +1449,7 @@ let configCache = {}, OVERRIDE_PATHS = [
|
|
|
1605
1449
|
let allLines = [];
|
|
1606
1450
|
function getPlugin(name) {
|
|
1607
1451
|
let targets = plugins.filter((item)=>item.instance.name === name);
|
|
1608
|
-
if (!targets.length) throw Error(`${
|
|
1452
|
+
if (!targets.length) throw Error(`${index_js_default.dim('[rsbuild:plugin]')} Plugin "${index_js_default.yellow(name)}" not existed`);
|
|
1609
1453
|
return targets;
|
|
1610
1454
|
}
|
|
1611
1455
|
for (let plugin of plugins){
|
|
@@ -1626,12 +1470,12 @@ let configCache = {}, OVERRIDE_PATHS = [
|
|
|
1626
1470
|
if (allLines.length) {
|
|
1627
1471
|
let restInRingPoints = {};
|
|
1628
1472
|
for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
|
|
1629
|
-
throw Error(`${
|
|
1473
|
+
throw Error(`${index_js_default.dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${index_js_default.yellow(Object.keys(restInRingPoints).join(','))}`);
|
|
1630
1474
|
}
|
|
1631
1475
|
return sortedPoint;
|
|
1632
1476
|
};
|
|
1633
1477
|
async function initPlugins({ getPluginAPI, pluginManager }) {
|
|
1634
|
-
|
|
1478
|
+
logger.debug('init plugins');
|
|
1635
1479
|
let plugins = pluginDagSort(pluginManager.getAllPluginsWithMeta()), removedPlugins = plugins.reduce((ret, plugin)=>(plugin.instance.remove && (ret[plugin.environment] ??= [], ret[plugin.environment].push(...plugin.instance.remove)), ret), {});
|
|
1636
1480
|
for (let plugin of plugins){
|
|
1637
1481
|
var _removedPlugins_plugin_environment, _removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL;
|
|
@@ -1640,7 +1484,7 @@ async function initPlugins({ getPluginAPI, pluginManager }) {
|
|
|
1640
1484
|
let { instance, environment } = plugin;
|
|
1641
1485
|
await instance.setup(getPluginAPI(environment));
|
|
1642
1486
|
}
|
|
1643
|
-
|
|
1487
|
+
logger.debug('init plugins done');
|
|
1644
1488
|
}
|
|
1645
1489
|
function createEnvironmentAsyncHook() {
|
|
1646
1490
|
let preGroup = [], postGroup = [], defaultGroup = [], tapEnvironment = ({ environment, handler: cb })=>{
|
|
@@ -1846,8 +1690,8 @@ function exit(exitCode, type) {
|
|
|
1846
1690
|
if (!isCalled) {
|
|
1847
1691
|
for (let callback of (isCalled = !0, exitHook_callbacks))callback(exitCode);
|
|
1848
1692
|
if ('SIGINT' === type) {
|
|
1849
|
-
let listeners =
|
|
1850
|
-
Array.isArray(listeners) && listeners.length <= 1 &&
|
|
1693
|
+
let listeners = external_node_process_default.listeners('SIGINT');
|
|
1694
|
+
Array.isArray(listeners) && listeners.length <= 1 && external_node_process_default.exit(exitCode);
|
|
1851
1695
|
}
|
|
1852
1696
|
}
|
|
1853
1697
|
}
|
|
@@ -1887,7 +1731,7 @@ let mapProcessAssetsStage = (compiler, stage)=>{
|
|
|
1887
1731
|
case 'report':
|
|
1888
1732
|
return Compilation.PROCESS_ASSETS_STAGE_REPORT;
|
|
1889
1733
|
default:
|
|
1890
|
-
throw Error(`${
|
|
1734
|
+
throw Error(`${index_js_default.dim('[rsbuild]')} Invalid process assets stage: ${stage}`);
|
|
1891
1735
|
}
|
|
1892
1736
|
}, browsersListCache = new Map();
|
|
1893
1737
|
async function getBrowserslist(path) {
|
|
@@ -1897,10 +1741,10 @@ async function getBrowserslist(path) {
|
|
|
1897
1741
|
if (opts.config) return pickEnv(parsePackageOrReadConfig(opts.config), opts);
|
|
1898
1742
|
if (opts.path) {
|
|
1899
1743
|
let config = function(from) {
|
|
1900
|
-
let resolved, fromDir = isFile(from =
|
|
1744
|
+
let resolved, fromDir = isFile(from = external_node_path_default.resolve(from)) ? external_node_path_default.dirname(from) : from;
|
|
1901
1745
|
if (fromDir in configCache) return configCache[fromDir];
|
|
1902
1746
|
let configFile = eachParent(from, (dir)=>{
|
|
1903
|
-
let pkgBrowserslist, config =
|
|
1747
|
+
let pkgBrowserslist, config = external_node_path_default.join(dir, 'browserslist'), pkg = external_node_path_default.join(dir, 'package.json'), rc = external_node_path_default.join(dir, '.browserslistrc');
|
|
1904
1748
|
if (isFile(pkg)) try {
|
|
1905
1749
|
pkgBrowserslist = parsePackage(pkg);
|
|
1906
1750
|
} catch (e) {
|
|
@@ -1913,7 +1757,7 @@ async function getBrowserslist(path) {
|
|
|
1913
1757
|
return isFile(config) ? config : isFile(rc) ? rc : pkgBrowserslist ? pkg : void 0;
|
|
1914
1758
|
});
|
|
1915
1759
|
configFile && (resolved = parsePackageOrReadConfig(configFile));
|
|
1916
|
-
let configDir = configFile &&
|
|
1760
|
+
let configDir = configFile && external_node_path_default.dirname(configFile);
|
|
1917
1761
|
return eachParent(from, (dir)=>{
|
|
1918
1762
|
if (resolved && (configCache[dir] = resolved), dir === configDir) return null;
|
|
1919
1763
|
}), resolved;
|
|
@@ -1942,7 +1786,7 @@ let getEnvironmentHTMLPaths = (entry, config)=>'web' !== config.output.target ||
|
|
|
1942
1786
|
let filename;
|
|
1943
1787
|
filename = config.output.filename.html ? config.output.filename.html.replace('[name]', entryName) : 'flat' === config.html.outputStructure ? `${entryName}.html` : `${entryName}/index.html`;
|
|
1944
1788
|
let prefix = config.output.distPath.html;
|
|
1945
|
-
return prefix.startsWith('/') &&
|
|
1789
|
+
return prefix.startsWith('/') && logger.warn(`${index_js_default.dim('[rsbuild:config]')} Absolute path is not recommended at ${index_js_default.yellow(`output.distPath.html: "${prefix}"`)}, use relative path instead.`), removeLeadingSlash(posix.join(prefix, filename));
|
|
1946
1790
|
}(key, config)), prev;
|
|
1947
1791
|
}, {});
|
|
1948
1792
|
async function updateEnvironmentContext(context, configs) {
|
|
@@ -1962,14 +1806,14 @@ async function updateEnvironmentContext(context, configs) {
|
|
|
1962
1806
|
};
|
|
1963
1807
|
context.environments[name] = new Proxy(environmentContext, {
|
|
1964
1808
|
get: (target, prop)=>target[prop],
|
|
1965
|
-
set: (target, prop, newValue)=>('manifest' === prop ? target[prop] = newValue :
|
|
1809
|
+
set: (target, prop, newValue)=>('manifest' === prop ? target[prop] = newValue : logger.error(`EnvironmentContext is readonly, you can not assign to the "environment.${prop}" prop.`), !0)
|
|
1966
1810
|
});
|
|
1967
1811
|
}
|
|
1968
1812
|
}
|
|
1969
1813
|
async function createContext(options, userConfig) {
|
|
1970
|
-
let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath =
|
|
1814
|
+
let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
|
|
1971
1815
|
return {
|
|
1972
|
-
version: "1.4.0-beta.
|
|
1816
|
+
version: "1.4.0-beta.4",
|
|
1973
1817
|
rootPath,
|
|
1974
1818
|
distPath: '',
|
|
1975
1819
|
cachePath,
|
|
@@ -2020,18 +1864,18 @@ let pluginAppIcon = ()=>({
|
|
|
2020
1864
|
src,
|
|
2021
1865
|
sizes,
|
|
2022
1866
|
isURL: !0,
|
|
2023
|
-
mimeType:
|
|
1867
|
+
mimeType: lookup(src)
|
|
2024
1868
|
};
|
|
2025
1869
|
return iconFormatMap.set(src, formatted), formatted;
|
|
2026
1870
|
}
|
|
2027
|
-
let absolutePath =
|
|
1871
|
+
let absolutePath = external_node_path_default.isAbsolute(src) ? src : external_node_path_default.join(api.context.rootPath, src), relativePath = external_node_path_default.posix.join(distDir, external_node_path_default.basename(absolutePath)), formatted = {
|
|
2028
1872
|
...icon,
|
|
2029
1873
|
sizes,
|
|
2030
1874
|
src: ensureAssetPrefix(relativePath, publicPath),
|
|
2031
1875
|
isURL: !1,
|
|
2032
1876
|
absolutePath,
|
|
2033
1877
|
relativePath,
|
|
2034
|
-
mimeType:
|
|
1878
|
+
mimeType: lookup(absolutePath)
|
|
2035
1879
|
};
|
|
2036
1880
|
return iconFormatMap.set(src, formatted), formatted;
|
|
2037
1881
|
};
|
|
@@ -2043,21 +1887,21 @@ let pluginAppIcon = ()=>({
|
|
|
2043
1887
|
let distDir = config.output.distPath.image, manifestFile = appIcon.filename ?? 'manifest.webmanifest', publicPath = getPublicPathFromCompiler(compilation), icons = appIcon.icons.map((icon)=>formatIcon(icon, distDir, publicPath)), tags = [];
|
|
2044
1888
|
for (let icon of icons){
|
|
2045
1889
|
if ('web-app-manifest' === icon.target && !appIcon.name) {
|
|
2046
|
-
addCompilationError(compilation, `${
|
|
1890
|
+
addCompilationError(compilation, `${index_js_default.dim('[rsbuild:app-icon]')} ${index_js_default.yellow('"appIcon.name"')} is required when ${index_js_default.yellow('"target"')} is ${index_js_default.yellow('"web-app-manifest"')}.`);
|
|
2047
1891
|
continue;
|
|
2048
1892
|
}
|
|
2049
1893
|
if (!icon.isURL) {
|
|
2050
1894
|
if (!compilation.inputFileSystem) {
|
|
2051
|
-
addCompilationError(compilation, `${
|
|
1895
|
+
addCompilationError(compilation, `${index_js_default.dim('[rsbuild:app-icon]')} Failed to read the icon file as ${index_js_default.yellow('"compilation.inputFileSystem"')} is not available.`);
|
|
2052
1896
|
continue;
|
|
2053
1897
|
}
|
|
2054
1898
|
if (!await fileExistsByCompilation(compilation, icon.absolutePath)) {
|
|
2055
|
-
addCompilationError(compilation, `${
|
|
1899
|
+
addCompilationError(compilation, `${index_js_default.dim('[rsbuild:app-icon]')} Failed to find the icon file at ${index_js_default.yellow(icon.absolutePath)}.`);
|
|
2056
1900
|
continue;
|
|
2057
1901
|
}
|
|
2058
|
-
let source = await (
|
|
1902
|
+
let source = await external_node_util_promisify(compilation.inputFileSystem.readFile)(icon.absolutePath);
|
|
2059
1903
|
if (!source) {
|
|
2060
|
-
addCompilationError(compilation, `${
|
|
1904
|
+
addCompilationError(compilation, `${index_js_default.dim('[rsbuild:app-icon]')} Failed to read the icon file at ${index_js_default.yellow(icon.absolutePath)}.`);
|
|
2061
1905
|
continue;
|
|
2062
1906
|
}
|
|
2063
1907
|
compilation.emitAsset(icon.relativePath, new sources.RawSource(source));
|
|
@@ -2109,8 +1953,8 @@ let pluginAppIcon = ()=>({
|
|
|
2109
1953
|
});
|
|
2110
1954
|
async function modifyBundlerChain(context, utils) {
|
|
2111
1955
|
var _utils_environment_config_tools;
|
|
2112
|
-
|
|
2113
|
-
let bundlerChain = new
|
|
1956
|
+
logger.debug('modify bundler chain');
|
|
1957
|
+
let bundlerChain = new rspack_chain_index_js_default(), [modifiedBundlerChain] = await context.hooks.modifyBundlerChain.callChain({
|
|
2114
1958
|
environment: utils.environment.name,
|
|
2115
1959
|
args: [
|
|
2116
1960
|
bundlerChain,
|
|
@@ -2118,7 +1962,7 @@ async function modifyBundlerChain(context, utils) {
|
|
|
2118
1962
|
]
|
|
2119
1963
|
});
|
|
2120
1964
|
if (null == (_utils_environment_config_tools = utils.environment.config.tools) ? void 0 : _utils_environment_config_tools.bundlerChain) for (let item of castArray(utils.environment.config.tools.bundlerChain))await item(modifiedBundlerChain, utils);
|
|
2121
|
-
return
|
|
1965
|
+
return logger.debug('modify bundler chain done'), modifiedBundlerChain;
|
|
2122
1966
|
}
|
|
2123
1967
|
let configChain_CHAIN_ID = {
|
|
2124
1968
|
RULE: {
|
|
@@ -2219,8 +2063,8 @@ let configChain_CHAIN_ID = {
|
|
|
2219
2063
|
let distDir = config.output.distPath[assetType], filename = getFilename(config, assetType, isProd);
|
|
2220
2064
|
return 'function' == typeof filename ? (...args)=>{
|
|
2221
2065
|
let name = filename(...args);
|
|
2222
|
-
return
|
|
2223
|
-
} :
|
|
2066
|
+
return external_node_path_default.posix.join(distDir, name);
|
|
2067
|
+
} : external_node_path_default.posix.join(distDir, filename);
|
|
2224
2068
|
}, createAssetRule = (assetType, exts, emit)=>{
|
|
2225
2069
|
let regExp = function(exts) {
|
|
2226
2070
|
let matcher = exts.map((ext)=>ext.trim()).map((ext)=>ext.startsWith('.') ? ext.slice(1) : ext).join('|');
|
|
@@ -2284,10 +2128,7 @@ let configChain_CHAIN_ID = {
|
|
|
2284
2128
|
javascript: {
|
|
2285
2129
|
exportsPresence: 'error'
|
|
2286
2130
|
}
|
|
2287
|
-
}), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(bundler.HotModuleReplacementPlugin), 'development' === env && chain.output.devtoolModuleFilenameTemplate((info)=>toPosixPath(info.absoluteResourcePath)), process.env.RSPACK_CONFIG_VALIDATE ||= 'loose-unrecognized-keys'
|
|
2288
|
-
...chain.get('experiments'),
|
|
2289
|
-
incremental: !0
|
|
2290
|
-
});
|
|
2131
|
+
}), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(bundler.HotModuleReplacementPlugin), 'development' === env && chain.output.devtoolModuleFilenameTemplate((info)=>toPosixPath(info.absoluteResourcePath)), process.env.RSPACK_CONFIG_VALIDATE ||= 'loose-unrecognized-keys';
|
|
2291
2132
|
});
|
|
2292
2133
|
}
|
|
2293
2134
|
}), isUseAnalyzer = (config)=>{
|
|
@@ -2295,27 +2136,27 @@ let configChain_CHAIN_ID = {
|
|
|
2295
2136
|
return process.env.BUNDLE_ANALYZE || (null == (_config_performance = config.performance) ? void 0 : _config_performance.bundleAnalyze);
|
|
2296
2137
|
};
|
|
2297
2138
|
async function validateWebpackCache(cacheDirectory, buildDependencies) {
|
|
2298
|
-
let configFile =
|
|
2139
|
+
let configFile = join(cacheDirectory, 'buildDependencies.json');
|
|
2299
2140
|
if (await isFileExists(configFile)) {
|
|
2300
|
-
let rawConfigFile = await
|
|
2141
|
+
let rawConfigFile = await external_node_fs_default.promises.readFile(configFile, 'utf-8'), prevBuildDependencies = null;
|
|
2301
2142
|
try {
|
|
2302
2143
|
prevBuildDependencies = JSON.parse(rawConfigFile);
|
|
2303
2144
|
} catch (e) {
|
|
2304
|
-
|
|
2145
|
+
logger.debug('failed to parse the previous buildDependencies.json', e);
|
|
2305
2146
|
}
|
|
2306
2147
|
if (JSON.stringify(prevBuildDependencies) === JSON.stringify(buildDependencies)) return;
|
|
2307
|
-
await
|
|
2148
|
+
await external_node_fs_default.promises.rm(cacheDirectory, {
|
|
2308
2149
|
force: !0,
|
|
2309
2150
|
recursive: !0
|
|
2310
2151
|
});
|
|
2311
2152
|
}
|
|
2312
|
-
await
|
|
2153
|
+
await external_node_fs_default.promises.mkdir(cacheDirectory, {
|
|
2313
2154
|
recursive: !0
|
|
2314
|
-
}), await
|
|
2155
|
+
}), await external_node_fs_default.promises.writeFile(configFile, JSON.stringify(buildDependencies));
|
|
2315
2156
|
}
|
|
2316
2157
|
async function getBuildDependencies(context, config, environmentContext, userBuildDependencies) {
|
|
2317
2158
|
var _config__privateMeta;
|
|
2318
|
-
let rootPackageJson =
|
|
2159
|
+
let rootPackageJson = join(context.rootPath, 'package.json'), browserslistConfig = join(context.rootPath, '.browserslistrc'), buildDependencies = {};
|
|
2319
2160
|
await isFileExists(rootPackageJson) && (buildDependencies.packageJson = [
|
|
2320
2161
|
rootPackageJson
|
|
2321
2162
|
]);
|
|
@@ -2332,7 +2173,7 @@ async function getBuildDependencies(context, config, environmentContext, userBui
|
|
|
2332
2173
|
'js',
|
|
2333
2174
|
'cjs',
|
|
2334
2175
|
'mjs'
|
|
2335
|
-
].map((ext)=>
|
|
2176
|
+
].map((ext)=>join(context.rootPath, `tailwind.config.${ext}`)));
|
|
2336
2177
|
return tailwindConfig && (buildDependencies.tailwindcss = [
|
|
2337
2178
|
tailwindConfig
|
|
2338
2179
|
]), {
|
|
@@ -2345,17 +2186,16 @@ let pluginCache = ()=>({
|
|
|
2345
2186
|
setup (api) {
|
|
2346
2187
|
let cacheEnabled = !1;
|
|
2347
2188
|
api.modifyBundlerChain(async (chain, { environment, env })=>{
|
|
2348
|
-
var data;
|
|
2349
2189
|
let { config } = environment, { bundlerType } = api.context, buildCache = config.performance.buildCache ?? 'webpack' === bundlerType;
|
|
2350
2190
|
if (!1 === buildCache) return;
|
|
2351
2191
|
cacheEnabled = !0;
|
|
2352
2192
|
let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = function({ cacheDirectory }, context) {
|
|
2353
|
-
return cacheDirectory ? (
|
|
2193
|
+
return cacheDirectory ? external_node_path_isAbsolute(cacheDirectory) ? cacheDirectory : join(context.rootPath, cacheDirectory) : join(context.cachePath, context.bundlerType);
|
|
2354
2194
|
}(cacheConfig, context), buildDependencies = await getBuildDependencies(context, config, environment, cacheConfig.buildDependencies ? {
|
|
2355
2195
|
userBuildDependencies: cacheConfig.buildDependencies
|
|
2356
2196
|
} : {});
|
|
2357
2197
|
'webpack' === bundlerType && await validateWebpackCache(cacheDirectory, buildDependencies);
|
|
2358
|
-
let cacheVersion = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length ? `${environment.name}-${env}-${
|
|
2198
|
+
let cacheVersion = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length ? `${environment.name}-${env}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : `${environment.name}-${env}`;
|
|
2359
2199
|
'rspack' === bundlerType ? (chain.cache(!0), chain.experiments({
|
|
2360
2200
|
...chain.get('experiments'),
|
|
2361
2201
|
cache: {
|
|
@@ -2374,10 +2214,10 @@ let pluginCache = ()=>({
|
|
|
2374
2214
|
buildDependencies
|
|
2375
2215
|
});
|
|
2376
2216
|
}), api.onAfterCreateCompiler(()=>{
|
|
2377
|
-
cacheEnabled && 'rspack' === api.context.bundlerType &&
|
|
2217
|
+
cacheEnabled && 'rspack' === api.context.bundlerType && logger.info(`Rspack persistent cache enabled ${index_js_default.dim('(experimental)')}`);
|
|
2378
2218
|
});
|
|
2379
2219
|
}
|
|
2380
|
-
}), addTrailingSep = (dir)=>dir.endsWith(
|
|
2220
|
+
}), addTrailingSep = (dir)=>dir.endsWith(sep) ? dir : dir + sep, isStrictSubdir = (parent, child)=>{
|
|
2381
2221
|
let parentDir = addTrailingSep(parent), childDir = addTrailingSep(child);
|
|
2382
2222
|
return parentDir !== childDir && childDir.startsWith(parentDir);
|
|
2383
2223
|
}, normalizeCleanDistPath = (userOptions)=>{
|
|
@@ -2395,7 +2235,7 @@ let pluginCache = ()=>({
|
|
|
2395
2235
|
name: 'rsbuild:clean-output',
|
|
2396
2236
|
setup (api) {
|
|
2397
2237
|
let getRsbuildOutputPath = ()=>{
|
|
2398
|
-
let { rootPath, distPath } = api.context, config = api.getNormalizedConfig(), targetPath =
|
|
2238
|
+
let { rootPath, distPath } = api.context, config = api.getNormalizedConfig(), targetPath = join(distPath, RSBUILD_OUTPUTS_PATH), { enable } = normalizeCleanDistPath(config.output.cleanDistPath);
|
|
2399
2239
|
if (!0 === enable || 'auto' === enable && isStrictSubdir(rootPath, targetPath)) return {
|
|
2400
2240
|
path: targetPath
|
|
2401
2241
|
};
|
|
@@ -2404,7 +2244,7 @@ let pluginCache = ()=>({
|
|
|
2404
2244
|
return 'auto' === enable ? isDev && !config.dev.writeToDisk ? void 0 : isStrictSubdir(rootPath, distPath) ? {
|
|
2405
2245
|
path: distPath,
|
|
2406
2246
|
keep
|
|
2407
|
-
} : (
|
|
2247
|
+
} : (logger.warn('The dist path is not a subdir of root path, Rsbuild will not empty it.'), logger.warn(`Please set ${index_js_default.yellow('`output.cleanDistPath`')} config manually.`), logger.warn(`Current root path: ${index_js_default.dim(rootPath)}`), void logger.warn(`Current dist path: ${index_js_default.dim(distPath)}`)) : !0 === enable ? {
|
|
2408
2248
|
path: distPath,
|
|
2409
2249
|
keep
|
|
2410
2250
|
} : void 0;
|
|
@@ -2460,11 +2300,11 @@ function reduceConfigsMergeContext({ initial, config, ctx, mergeFn = Object.assi
|
|
|
2460
2300
|
mergeFn
|
|
2461
2301
|
}), initial) : config ?? initial;
|
|
2462
2302
|
}
|
|
2463
|
-
let pluginHelper_require =
|
|
2303
|
+
let pluginHelper_require = createRequire(import.meta.url), setHTMLPlugin = (plugin)=>{
|
|
2464
2304
|
plugin && (pluginHelper_htmlPlugin = plugin);
|
|
2465
2305
|
}, getHTMLPlugin = ()=>(pluginHelper_htmlPlugin || (pluginHelper_htmlPlugin = pluginHelper_require('../compiled/html-rspack-plugin/index.js')), pluginHelper_htmlPlugin), setCssExtractPlugin = (plugin)=>{
|
|
2466
2306
|
cssExtractPlugin = plugin;
|
|
2467
|
-
}, getCssExtractPlugin = ()=>cssExtractPlugin ||
|
|
2307
|
+
}, getCssExtractPlugin = ()=>cssExtractPlugin || rspack.CssExtractRspackPlugin, getSwcMinimizerOptions = (config, jsOptions)=>{
|
|
2468
2308
|
let options = {};
|
|
2469
2309
|
options.minimizerOptions ||= {}, options.minimizerOptions.format ||= {};
|
|
2470
2310
|
let { removeConsole } = config.performance;
|
|
@@ -2509,7 +2349,7 @@ let pluginHelper_require = (0, __WEBPACK_EXTERNAL_MODULE_node_module_ab9f2194__.
|
|
|
2509
2349
|
let isRspack = 'rspack' === api.context.bundlerType;
|
|
2510
2350
|
api.modifyBundlerChain(async (chain, { environment, CHAIN_ID })=>{
|
|
2511
2351
|
let { config } = environment, { minifyJs, minifyCss, jsOptions, cssOptions } = parseMinifyOptions(config);
|
|
2512
|
-
if (chain.optimization.minimize(minifyJs || minifyCss), minifyJs && isRspack && chain.optimization.minimizer(CHAIN_ID.MINIMIZER.JS).use(
|
|
2352
|
+
if (chain.optimization.minimize(minifyJs || minifyCss), minifyJs && isRspack && chain.optimization.minimizer(CHAIN_ID.MINIMIZER.JS).use(rspack.SwcJsMinimizerRspackPlugin, [
|
|
2513
2353
|
getSwcMinimizerOptions(config, jsOptions)
|
|
2514
2354
|
]).end(), minifyCss && isRspack) {
|
|
2515
2355
|
let loaderOptions = getLightningCSSLoaderOptions(config, environment.browserslist, !0), defaultOptions = {
|
|
@@ -2526,7 +2366,7 @@ let pluginHelper_require = (0, __WEBPACK_EXTERNAL_MODULE_node_module_ab9f2194__.
|
|
|
2526
2366
|
])
|
|
2527
2367
|
}
|
|
2528
2368
|
}, mergedOptions = cssOptions ? cjs_default()(defaultOptions, cssOptions) : defaultOptions;
|
|
2529
|
-
chain.optimization.minimizer(CHAIN_ID.MINIMIZER.CSS).use(
|
|
2369
|
+
chain.optimization.minimizer(CHAIN_ID.MINIMIZER.CSS).use(rspack.LightningCssMinimizerRspackPlugin, [
|
|
2530
2370
|
mergedOptions
|
|
2531
2371
|
]).end();
|
|
2532
2372
|
}
|
|
@@ -2598,7 +2438,7 @@ let isPostcssPluginCreator = (plugin)=>'function' == typeof plugin && !0 === plu
|
|
|
2598
2438
|
if ('function' == typeof postcssOptions) {
|
|
2599
2439
|
let postcssOptionsWrapper = (loaderContext)=>{
|
|
2600
2440
|
let options = postcssOptions(loaderContext);
|
|
2601
|
-
if ('object' != typeof options || null === options) throw Error(`${
|
|
2441
|
+
if ('object' != typeof options || null === options) throw Error(`${index_js_default.dim('[rsbuild:css]')} \`postcssOptions\` function must return a PostCSSOptions object, got ${index_js_default.yellow(typeof options)}.`);
|
|
2602
2442
|
return updatePostcssOptions({
|
|
2603
2443
|
...userOptions,
|
|
2604
2444
|
...options,
|
|
@@ -2649,7 +2489,7 @@ let isPostcssPluginCreator = (plugin)=>'function' == typeof plugin && !0 === plu
|
|
|
2649
2489
|
});
|
|
2650
2490
|
rule.use(CHAIN_ID.USE.STYLE).loader(getCompiledPath('style-loader')).options(styleLoaderOptions);
|
|
2651
2491
|
} else rule.use(CHAIN_ID.USE.MINI_CSS_EXTRACT).loader(getCssExtractPlugin().loader).options(config.tools.cssExtract.loaderOptions);
|
|
2652
|
-
else rule.use(CHAIN_ID.USE.IGNORE_CSS).loader(
|
|
2492
|
+
else rule.use(CHAIN_ID.USE.IGNORE_CSS).loader(external_node_path_default.join(LOADER_PATH, 'ignoreCssLoader.mjs'));
|
|
2653
2493
|
let importLoaders = 0, updateRules = (callback)=>{
|
|
2654
2494
|
callback(rule, 'normal'), callback(inlineRule, 'inline');
|
|
2655
2495
|
}, cssLoaderPath = getCompiledPath('css-loader');
|
|
@@ -2698,12 +2538,12 @@ let isPostcssPluginCreator = (plugin)=>'function' == typeof plugin && !0 === plu
|
|
|
2698
2538
|
{
|
|
2699
2539
|
filename: isCssFilenameFn ? (...args)=>{
|
|
2700
2540
|
let name = cssFilename(...args);
|
|
2701
|
-
return
|
|
2702
|
-
} :
|
|
2541
|
+
return posix.join(cssPath, name);
|
|
2542
|
+
} : posix.join(cssPath, cssFilename),
|
|
2703
2543
|
chunkFilename: isCssFilenameFn ? (...args)=>{
|
|
2704
2544
|
let name = cssFilename(...args);
|
|
2705
|
-
return
|
|
2706
|
-
} :
|
|
2545
|
+
return posix.join(cssAsyncPath, name);
|
|
2546
|
+
} : posix.join(cssAsyncPath, cssFilename),
|
|
2707
2547
|
...extractPluginOptions
|
|
2708
2548
|
}
|
|
2709
2549
|
]);
|
|
@@ -2732,7 +2572,7 @@ let isPostcssPluginCreator = (plugin)=>'function' == typeof plugin && !0 === plu
|
|
|
2732
2572
|
if (!value) return;
|
|
2733
2573
|
let check = (value)=>{
|
|
2734
2574
|
let pathKey = Object.keys(value).find((key)=>'path' === key.toLowerCase() && value[key] === process.env[key]);
|
|
2735
|
-
pathKey &&
|
|
2575
|
+
pathKey && logger.warn(`${index_js_default.dim('[rsbuild:config]')} The ${index_js_default.yellow('"source.define"')} option includes an object with the key ${index_js_default.yellow(JSON.stringify(pathKey))} under ${index_js_default.yellow('"process.env"')}, indicating potential exposure of all environment variables. This can lead to security risks and should be avoided.`);
|
|
2736
2576
|
};
|
|
2737
2577
|
if ('object' == typeof value) return check(value);
|
|
2738
2578
|
if ('string' == typeof value) try {
|
|
@@ -2758,27 +2598,27 @@ let isPostcssPluginCreator = (plugin)=>'function' == typeof plugin && !0 === plu
|
|
|
2758
2598
|
preEntry.forEach(addEntry), injectCoreJsEntry && addEntry(createVirtualModule('import "core-js";')), castArray(entry[entryName]).forEach(addEntry);
|
|
2759
2599
|
}
|
|
2760
2600
|
}), api.onBeforeCreateCompiler(({ bundlerConfigs })=>{
|
|
2761
|
-
if (bundlerConfigs.every((config)=>!config.entry)) throw Error(`${
|
|
2601
|
+
if (bundlerConfigs.every((config)=>!config.entry)) throw Error(`${index_js_default.dim('[rsbuild:config]')} Could not find any entry module, please make sure that ${index_js_default.yellow('src/index.(ts|js|tsx|jsx|mts|cts|mjs|cjs)')} exists, or customize entry through the ${index_js_default.yellow('source.entry')} configuration.`);
|
|
2762
2602
|
});
|
|
2763
2603
|
}
|
|
2764
|
-
}), fileSize_gzip = (
|
|
2604
|
+
}), fileSize_gzip = external_node_util_promisify(external_node_zlib_default.gzip);
|
|
2765
2605
|
async function gzipSize(input) {
|
|
2766
2606
|
let data = await fileSize_gzip(input);
|
|
2767
2607
|
return Buffer.byteLength(data);
|
|
2768
2608
|
}
|
|
2769
|
-
let EXCLUDE_ASSET_REGEX = /\.(?:map|LICENSE\.txt|d\.ts)$/, excludeAsset = (asset)=>EXCLUDE_ASSET_REGEX.test(asset.name), getAssetColor = (size)=>size > 300000 ?
|
|
2609
|
+
let EXCLUDE_ASSET_REGEX = /\.(?:map|LICENSE\.txt|d\.ts)$/, excludeAsset = (asset)=>EXCLUDE_ASSET_REGEX.test(asset.name), getAssetColor = (size)=>size > 300000 ? index_js_default.red : size > 100000 ? index_js_default.yellow : index_js_default.green, calcFileSize = (len)=>{
|
|
2770
2610
|
let val = len / 1000;
|
|
2771
2611
|
return `${val.toFixed(val < 1 ? 2 : 1)} kB`;
|
|
2772
|
-
}, coloringAssetName = (assetName)=>JS_REGEX.test(assetName) ?
|
|
2612
|
+
}, coloringAssetName = (assetName)=>JS_REGEX.test(assetName) ? index_js_default.cyan(assetName) : CSS_REGEX.test(assetName) ? index_js_default.yellow(assetName) : HTML_REGEX.test(assetName) ? index_js_default.green(assetName) : index_js_default.magenta(assetName), COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i, isCompressible = (assetName)=>COMPRESSIBLE_REGEX.test(assetName);
|
|
2773
2613
|
async function printFileSizes(options, stats, rootPath, environmentName) {
|
|
2774
2614
|
let logs = [], showTotal = !1 !== options.total, showDetail = !1 !== options.detail, exclude = options.exclude ?? excludeAsset;
|
|
2775
2615
|
if (!showTotal && !showDetail) return logs;
|
|
2776
2616
|
let formatAsset = async (asset, distPath, distFolder)=>{
|
|
2777
|
-
let fileName = asset.name.split('?')[0], contents = await
|
|
2617
|
+
let fileName = asset.name.split('?')[0], contents = await external_node_fs_default.promises.readFile(external_node_path_default.join(distPath, fileName)), size = Buffer.byteLength(contents), gzippedSize = options.compressed && isCompressible(fileName) ? await gzipSize(contents) : null, gzipSizeLabel = gzippedSize ? getAssetColor(gzippedSize)(calcFileSize(gzippedSize)) : null;
|
|
2778
2618
|
return {
|
|
2779
2619
|
size,
|
|
2780
|
-
folder:
|
|
2781
|
-
name:
|
|
2620
|
+
folder: external_node_path_default.join(distFolder, external_node_path_default.dirname(fileName)),
|
|
2621
|
+
name: external_node_path_default.basename(fileName),
|
|
2782
2622
|
gzippedSize,
|
|
2783
2623
|
sizeLabel: calcFileSize(size),
|
|
2784
2624
|
gzipSizeLabel
|
|
@@ -2801,7 +2641,7 @@ async function printFileSizes(options, stats, rootPath, environmentName) {
|
|
|
2801
2641
|
size: asset.size
|
|
2802
2642
|
};
|
|
2803
2643
|
return !exclude(assetInfo) && (!options.include || options.include(assetInfo));
|
|
2804
|
-
}), distFolder =
|
|
2644
|
+
}), distFolder = external_node_path_default.relative(rootPath, distPath);
|
|
2805
2645
|
return Promise.all(filteredAssets.map((asset)=>formatAsset(asset, distPath, distFolder)));
|
|
2806
2646
|
}, assets = await getAssets();
|
|
2807
2647
|
if (0 === assets.length) return logs;
|
|
@@ -2810,7 +2650,7 @@ async function printFileSizes(options, stats, rootPath, environmentName) {
|
|
|
2810
2650
|
for (let asset of (showTotal = showTotal && !(showDetail && 1 === assets.length), assets))totalSize += asset.size, options.compressed && (totalGzipSize += asset.gzippedSize ?? asset.size);
|
|
2811
2651
|
let fileHeader = showDetail ? `File (${environmentName})` : '', totalSizeLabel = showTotal ? showDetail ? 'Total:' : `Total size (${environmentName}):` : '', totalSizeStr = showTotal ? calcFileSize(totalSize) : '';
|
|
2812
2652
|
if (showDetail) {
|
|
2813
|
-
let maxFileLength = Math.max(...assets.map((a)=>(a.folder +
|
|
2653
|
+
let maxFileLength = Math.max(...assets.map((a)=>(a.folder + external_node_path_default.sep + a.name).length), showTotal ? totalSizeLabel.length : 0, fileHeader.length), maxSizeLength = Math.max(...assets.map((a)=>a.sizeLabel.length), totalSizeStr.length), showGzipHeader = !!(options.compressed && assets.some((item)=>null !== item.gzippedSize));
|
|
2814
2654
|
for (let asset of (logs.push(function(maxFileLength, maxSizeLength, fileHeader, showGzipHeader) {
|
|
2815
2655
|
let lengths = [
|
|
2816
2656
|
maxFileLength,
|
|
@@ -2824,11 +2664,11 @@ async function printFileSizes(options, stats, rootPath, environmentName) {
|
|
|
2824
2664
|
let length = lengths[index], curLabel = cur;
|
|
2825
2665
|
return length && (curLabel = cur.length < length ? cur + ' '.repeat(length - cur.length) : cur), `${prev + curLabel} `;
|
|
2826
2666
|
}, '');
|
|
2827
|
-
return
|
|
2667
|
+
return index_js_default.blue(headerRow);
|
|
2828
2668
|
}(maxFileLength, maxSizeLength, fileHeader, showGzipHeader)), assets)){
|
|
2829
|
-
let { sizeLabel } = asset, { name, folder, gzipSizeLabel } = asset, fileNameLength = (folder +
|
|
2669
|
+
let { sizeLabel } = asset, { name, folder, gzipSizeLabel } = asset, fileNameLength = (folder + external_node_path_default.sep + name).length, sizeLength = sizeLabel.length;
|
|
2830
2670
|
sizeLength < maxSizeLength && (sizeLabel += ' '.repeat(maxSizeLength - sizeLength));
|
|
2831
|
-
let fileNameLabel =
|
|
2671
|
+
let fileNameLabel = index_js_default.dim(asset.folder + external_node_path_default.sep) + coloringAssetName(asset.name);
|
|
2832
2672
|
fileNameLength < maxFileLength && (fileNameLabel += ' '.repeat(maxFileLength - fileNameLength));
|
|
2833
2673
|
let log = `${fileNameLabel} ${sizeLabel}`;
|
|
2834
2674
|
gzipSizeLabel && (log += ` ${gzipSizeLabel}`), logs.push(log);
|
|
@@ -2836,15 +2676,15 @@ async function printFileSizes(options, stats, rootPath, environmentName) {
|
|
|
2836
2676
|
if (showTotal) {
|
|
2837
2677
|
logs.push('');
|
|
2838
2678
|
let log = '';
|
|
2839
|
-
if (log += ' '.repeat(maxFileLength - totalSizeLabel.length), log +=
|
|
2679
|
+
if (log += ' '.repeat(maxFileLength - totalSizeLabel.length), log += index_js_default.magenta(totalSizeLabel), log += ` ${totalSizeStr}`, options.compressed) {
|
|
2840
2680
|
let colorFn = getAssetColor(totalGzipSize / assets.length);
|
|
2841
2681
|
log += ' '.repeat(maxSizeLength - totalSizeStr.length), log += ` ${colorFn(calcFileSize(totalGzipSize))}`;
|
|
2842
2682
|
}
|
|
2843
2683
|
logs.push(log);
|
|
2844
2684
|
}
|
|
2845
2685
|
} else if (showTotal) {
|
|
2846
|
-
let log = `${
|
|
2847
|
-
options.compressed && (log +=
|
|
2686
|
+
let log = `${index_js_default.magenta(totalSizeLabel)} ${totalSizeStr}`;
|
|
2687
|
+
options.compressed && (log += index_js_default.green(` (${calcFileSize(totalGzipSize)} gzipped)`)), logs.push(log);
|
|
2848
2688
|
}
|
|
2849
2689
|
return logs.push(''), logs;
|
|
2850
2690
|
}
|
|
@@ -2869,8 +2709,8 @@ let pluginFileSize = ()=>({
|
|
|
2869
2709
|
}, statsLogs = await printFileSizes(mergedConfig, multiStats[index], api.context.rootPath, environment.name);
|
|
2870
2710
|
logs.push(...statsLogs);
|
|
2871
2711
|
})).catch((err)=>{
|
|
2872
|
-
|
|
2873
|
-
}),
|
|
2712
|
+
logger.warn('Failed to print file size.'), logger.warn(err);
|
|
2713
|
+
}), logger.log(logs.join('\n'));
|
|
2874
2714
|
});
|
|
2875
2715
|
}
|
|
2876
2716
|
});
|
|
@@ -2980,14 +2820,14 @@ let entryNameSymbol = Symbol('entryName'), VOID_TAGS = [
|
|
|
2980
2820
|
class RsbuildHtmlPlugin {
|
|
2981
2821
|
apply(compiler) {
|
|
2982
2822
|
let emitFavicon = async (compilation, favicon)=>{
|
|
2983
|
-
let buffer, name =
|
|
2823
|
+
let buffer, name = external_node_path_default.basename(favicon);
|
|
2984
2824
|
if (compilation.assets[name]) return name;
|
|
2985
|
-
if (!compilation.inputFileSystem) return addCompilationError(compilation, `${
|
|
2986
|
-
let filename =
|
|
2825
|
+
if (!compilation.inputFileSystem) return addCompilationError(compilation, `${index_js_default.dim('[rsbuild:html]')} Failed to read the favicon file as ${index_js_default.yellow('compilation.inputFileSystem')} is not available.`), null;
|
|
2826
|
+
let filename = external_node_path_default.isAbsolute(favicon) ? favicon : external_node_path_default.join(compilation.compiler.context, favicon);
|
|
2987
2827
|
try {
|
|
2988
|
-
if (!(buffer = await (
|
|
2828
|
+
if (!(buffer = await external_node_util_promisify(compilation.inputFileSystem.readFile)(filename))) throw Error('Buffer is undefined');
|
|
2989
2829
|
} catch (error) {
|
|
2990
|
-
return
|
|
2830
|
+
return logger.debug(`read favicon error: ${error}`), addCompilationError(compilation, `${index_js_default.dim('[rsbuild:html]')} Failed to read the favicon file at ${index_js_default.yellow(filename)}.`), null;
|
|
2991
2831
|
}
|
|
2992
2832
|
let source = new compiler.webpack.sources.RawSource(buffer, !1);
|
|
2993
2833
|
return compilation.emitAsset(name, source), name;
|
|
@@ -3083,12 +2923,12 @@ async function getTemplate(entryName, config, rootPath) {
|
|
|
3083
2923
|
templatePath: void 0,
|
|
3084
2924
|
templateContent: getDefaultTemplateContent(config.html.mountId)
|
|
3085
2925
|
};
|
|
3086
|
-
let absolutePath = (
|
|
2926
|
+
let absolutePath = external_node_path_isAbsolute(templatePath) ? templatePath : external_node_path_default.join(rootPath, templatePath);
|
|
3087
2927
|
if (!existTemplatePath.has(absolutePath)) {
|
|
3088
|
-
if (!await isFileExists(absolutePath)) throw Error(`${
|
|
2928
|
+
if (!await isFileExists(absolutePath)) throw Error(`${index_js_default.dim('[rsbuild:html]')} Failed to resolve HTML template, check if the file exists: ${index_js_default.yellow(absolutePath)}`);
|
|
3089
2929
|
existTemplatePath.add(absolutePath);
|
|
3090
2930
|
}
|
|
3091
|
-
let templateContent = await
|
|
2931
|
+
let templateContent = await external_node_fs_default.promises.readFile(absolutePath, 'utf-8');
|
|
3092
2932
|
return {
|
|
3093
2933
|
templatePath: absolutePath,
|
|
3094
2934
|
templateContent
|
|
@@ -3236,7 +3076,7 @@ let getTagConfig = (config)=>{
|
|
|
3236
3076
|
function updateSourceMappingURL({ source, compilation, publicPath, type, config }) {
|
|
3237
3077
|
let { devtool } = compilation.options;
|
|
3238
3078
|
if (devtool && !devtool.includes('inline') && source.includes('# sourceMappingURL')) {
|
|
3239
|
-
let prefix = addTrailingSlash(
|
|
3079
|
+
let prefix = addTrailingSlash(external_node_path_default.join(publicPath, config.output.distPath[type] || ''));
|
|
3240
3080
|
return source.replace(/# sourceMappingURL=/, `# sourceMappingURL=${prefix}`);
|
|
3241
3081
|
}
|
|
3242
3082
|
return source;
|
|
@@ -3249,7 +3089,7 @@ function matchTests(name, asset, tests) {
|
|
|
3249
3089
|
}
|
|
3250
3090
|
let getInlineTests = (config)=>{
|
|
3251
3091
|
let isProd = 'production' === config.mode, { inlineStyles, inlineScripts } = config.output, scriptTests = [], styleTests = [];
|
|
3252
|
-
return inlineScripts && (!0 === inlineScripts ? isProd && scriptTests.push(JS_REGEX) :
|
|
3092
|
+
return inlineScripts && (!0 === inlineScripts ? isProd && scriptTests.push(JS_REGEX) : isRegExp(inlineScripts) || isFunction(inlineScripts) ? isProd && scriptTests.push(inlineScripts) : ('auto' === inlineScripts.enable ? isProd : inlineScripts.enable) && scriptTests.push(inlineScripts.test)), inlineStyles && (!0 === inlineStyles ? isProd && styleTests.push(CSS_REGEX) : isRegExp(inlineStyles) || isFunction(inlineStyles) ? isProd && styleTests.push(inlineStyles) : ('auto' === inlineStyles.enable ? isProd : inlineStyles.enable) && styleTests.push(inlineStyles.test)), {
|
|
3253
3093
|
scriptTests,
|
|
3254
3094
|
styleTests
|
|
3255
3095
|
};
|
|
@@ -3319,6 +3159,19 @@ let getInlineTests = (config)=>{
|
|
|
3319
3159
|
};
|
|
3320
3160
|
});
|
|
3321
3161
|
}
|
|
3162
|
+
}), pluginLazyCompilation = ()=>({
|
|
3163
|
+
name: 'rsbuild:lazy-compilation',
|
|
3164
|
+
setup (api) {
|
|
3165
|
+
api.modifyBundlerChain((chain, { environment, isProd, target })=>{
|
|
3166
|
+
var _config_dev;
|
|
3167
|
+
if (isProd || 'web' !== target) return;
|
|
3168
|
+
let { config } = environment, options = null == (_config_dev = config.dev) ? void 0 : _config_dev.lazyCompilation;
|
|
3169
|
+
options && chain.experiments({
|
|
3170
|
+
...chain.get('experiments'),
|
|
3171
|
+
lazyCompilation: options
|
|
3172
|
+
});
|
|
3173
|
+
});
|
|
3174
|
+
}
|
|
3322
3175
|
});
|
|
3323
3176
|
function recursiveChunkEntryNames(chunk) {
|
|
3324
3177
|
let [...chunkGroups] = chunk.groupsIterable;
|
|
@@ -3380,7 +3233,7 @@ let generateManifest = (htmlPaths, manifestOptions, environment)=>(_seed, files)
|
|
|
3380
3233
|
manifestData
|
|
3381
3234
|
});
|
|
3382
3235
|
if (isObject(generatedManifest)) return environment.manifest = generatedManifest, generatedManifest;
|
|
3383
|
-
throw Error(`${
|
|
3236
|
+
throw Error(`${index_js_default.dim('[rsbuild:manifest]')} \`manifest.generate\` function must return a valid manifest object.`);
|
|
3384
3237
|
}
|
|
3385
3238
|
return environment.manifest = manifestData, manifestData;
|
|
3386
3239
|
}, pluginManifest = ()=>({
|
|
@@ -3413,7 +3266,7 @@ let generateManifest = (htmlPaths, manifestOptions, environment)=>(_seed, files)
|
|
|
3413
3266
|
}), api.onAfterCreateCompiler(()=>{
|
|
3414
3267
|
if (manifestFilenames.size <= 1) return void manifestFilenames.clear();
|
|
3415
3268
|
let environmentNames = Array.from(manifestFilenames.keys()), filenames = Array.from(manifestFilenames.values());
|
|
3416
|
-
new Set(filenames).size !== filenames.length &&
|
|
3269
|
+
new Set(filenames).size !== filenames.length && logger.warn(`${index_js_default.dim('[rsbuild:manifest]')} The ${index_js_default.yellow('"manifest.filename"')} option must be unique when there are multiple environments (${environmentNames.join(', ')}), otherwise the manifest file will be overwritten.`), manifestFilenames.clear();
|
|
3417
3270
|
});
|
|
3418
3271
|
}
|
|
3419
3272
|
});
|
|
@@ -3422,7 +3275,7 @@ class PatchSplitChunksPlugin {
|
|
|
3422
3275
|
let { splitChunks } = compiler.options.optimization;
|
|
3423
3276
|
if (!splitChunks) return;
|
|
3424
3277
|
let applyPatch = (config)=>{
|
|
3425
|
-
if ('object' != typeof config ||
|
|
3278
|
+
if ('object' != typeof config || isRegExp(config)) return;
|
|
3426
3279
|
let { chunks } = config;
|
|
3427
3280
|
if (chunks && 'async' !== chunks) {
|
|
3428
3281
|
if ('function' == typeof chunks) {
|
|
@@ -3469,7 +3322,7 @@ let pluginMoment = ()=>({
|
|
|
3469
3322
|
}), nodeAddons_getFilename = (resourcePath)=>{
|
|
3470
3323
|
let basename = '';
|
|
3471
3324
|
if (resourcePath) {
|
|
3472
|
-
let parsed =
|
|
3325
|
+
let parsed = external_node_path_default.parse(resourcePath);
|
|
3473
3326
|
parsed.dir && (basename = parsed.name);
|
|
3474
3327
|
}
|
|
3475
3328
|
return basename ? `${basename}.node` : null;
|
|
@@ -3484,7 +3337,7 @@ let pluginMoment = ()=>({
|
|
|
3484
3337
|
raw: !0
|
|
3485
3338
|
}, ({ code, emitFile, resourcePath })=>{
|
|
3486
3339
|
let name = nodeAddons_getFilename(resourcePath);
|
|
3487
|
-
if (null === name) throw Error(`${
|
|
3340
|
+
if (null === name) throw Error(`${index_js_default.dim('[rsbuild:node-addons]')} Failed to load Node.js addon: ${index_js_default.yellow(resourcePath)}`);
|
|
3488
3341
|
return emitFile(name, code), `
|
|
3489
3342
|
try {
|
|
3490
3343
|
const path = require("path");
|
|
@@ -3541,7 +3394,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
|
|
|
3541
3394
|
let trailingSlashBase = addTrailingSlash(base);
|
|
3542
3395
|
return path.startsWith(trailingSlashBase) ? path.slice(trailingSlashBase.length - 1) : path;
|
|
3543
3396
|
}, getRoutes = (context)=>Object.values(context.environments).reduce((prev, environmentContext)=>{
|
|
3544
|
-
let { distPath, config } = environmentContext, distPrefix =
|
|
3397
|
+
let { distPath, config } = environmentContext, distPrefix = relative(context.distPath, distPath).split(sep).join('/'), routes = formatRoutes(environmentContext.htmlPaths, context.normalizedConfig.server.base, posix.join(distPrefix, config.output.distPath.html), config.html.outputStructure);
|
|
3545
3398
|
return prev.concat(...routes);
|
|
3546
3399
|
}, []), formatRoutes = (entry, base, distPathPrefix, outputStructure)=>{
|
|
3547
3400
|
let prefix = joinUrlSegments(base, formatPrefix(distPathPrefix));
|
|
@@ -3561,7 +3414,7 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
|
|
|
3561
3414
|
protocol
|
|
3562
3415
|
});
|
|
3563
3416
|
if (!newUrls) return null;
|
|
3564
|
-
if (!Array.isArray(newUrls)) throw Error(`${
|
|
3417
|
+
if (!Array.isArray(newUrls)) throw Error(`${index_js_default.dim('[rsbuild:config]')} "server.printUrls" must return an array, but got ${typeof newUrls}.`);
|
|
3565
3418
|
urls = newUrls.map((url)=>({
|
|
3566
3419
|
url,
|
|
3567
3420
|
label: getUrlLabel(url)
|
|
@@ -3572,16 +3425,16 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
|
|
|
3572
3425
|
if (routes.length <= 1) {
|
|
3573
3426
|
let pathname = routes.length ? routes[0].pathname : '';
|
|
3574
3427
|
return urls.map(({ label, url })=>{
|
|
3575
|
-
let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `\u{279C} ${
|
|
3576
|
-
return ` ${prefix}${
|
|
3428
|
+
let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `\u{279C} ${index_js_default.dim(label.padEnd(10))}`;
|
|
3429
|
+
return ` ${prefix}${index_js_default.cyan(normalizedPathname)}\n`;
|
|
3577
3430
|
}).join('');
|
|
3578
3431
|
}
|
|
3579
3432
|
let message = '', maxNameLength = Math.max(...routes.map((r)=>r.entryName.length));
|
|
3580
3433
|
return urls.forEach(({ label, url }, index)=>{
|
|
3581
|
-
for (let r of (index > 0 && (message += '\n'), message += ` ${`\u{279C} ${label}`}\n`, routes))message += ` ${
|
|
3434
|
+
for (let r of (index > 0 && (message += '\n'), message += ` ${`\u{279C} ${label}`}\n`, routes))message += ` ${index_js_default.dim('-')} ${index_js_default.dim(r.entryName.padEnd(maxNameLength + 4))}${index_js_default.cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
|
|
3582
3435
|
}), message;
|
|
3583
3436
|
}(urls, routes);
|
|
3584
|
-
return !1 === trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)),
|
|
3437
|
+
return !1 === trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
|
|
3585
3438
|
}
|
|
3586
3439
|
let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
3587
3440
|
'string' == typeof port && (port = Number.parseInt(port, 10)), strictPort && (tryLimits = 1);
|
|
@@ -3600,14 +3453,14 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
|
3600
3453
|
if ('EADDRINUSE' !== e.code) throw e;
|
|
3601
3454
|
port++, attempts++;
|
|
3602
3455
|
}
|
|
3603
|
-
if (port !== original && strictPort) throw Error(`${
|
|
3456
|
+
if (port !== original && strictPort) throw Error(`${index_js_default.dim('[rsbuild:server]')} Port ${index_js_default.yellow(original)} is occupied, please choose another one.`);
|
|
3604
3457
|
return port;
|
|
3605
3458
|
}, getServerConfig = async ({ config })=>{
|
|
3606
3459
|
let { host, port: originalPort, strictPort } = config.server, port = await getPort({
|
|
3607
3460
|
host,
|
|
3608
3461
|
port: originalPort,
|
|
3609
3462
|
strictPort
|
|
3610
|
-
}), https = !!config.server.https, portTip = port !== originalPort ? `port ${originalPort} is in use, ${
|
|
3463
|
+
}), https = !!config.server.https, portTip = port !== originalPort ? `port ${originalPort} is in use, ${index_js_default.yellow(`using port ${port}.`)}` : void 0;
|
|
3611
3464
|
return {
|
|
3612
3465
|
port,
|
|
3613
3466
|
host,
|
|
@@ -3615,7 +3468,7 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
|
3615
3468
|
portTip
|
|
3616
3469
|
};
|
|
3617
3470
|
}, getIpv4Interfaces = ()=>{
|
|
3618
|
-
let interfaces =
|
|
3471
|
+
let interfaces = external_node_os_default.networkInterfaces(), ipv4Interfaces = new Map();
|
|
3619
3472
|
for (let key of Object.keys(interfaces))for (let detail of interfaces[key]){
|
|
3620
3473
|
let familyV4Value = 'string' == typeof detail.family ? 'IPv4' : 4;
|
|
3621
3474
|
detail.family !== familyV4Value || ipv4Interfaces.has(detail.address) || ipv4Interfaces.set(detail.address, detail);
|
|
@@ -3714,9 +3567,9 @@ async function openBrowser(url) {
|
|
|
3714
3567
|
if (chromiumBrowser) return await execAsync(`osascript openChrome.applescript "${encodeURI(url)}" "${chromiumBrowser}"`, {
|
|
3715
3568
|
cwd: STATIC_PATH
|
|
3716
3569
|
}), !0;
|
|
3717
|
-
|
|
3570
|
+
logger.debug('failed to find the target browser.');
|
|
3718
3571
|
} catch (err) {
|
|
3719
|
-
|
|
3572
|
+
logger.debug("failed to open start URL with apple script."), logger.debug(err);
|
|
3720
3573
|
}
|
|
3721
3574
|
}
|
|
3722
3575
|
try {
|
|
@@ -3728,7 +3581,7 @@ async function openBrowser(url) {
|
|
|
3728
3581
|
} : {};
|
|
3729
3582
|
return await open(url, options), !0;
|
|
3730
3583
|
} catch (err) {
|
|
3731
|
-
return
|
|
3584
|
+
return logger.error('Failed to open start URL.'), logger.error(err), !1;
|
|
3732
3585
|
}
|
|
3733
3586
|
}
|
|
3734
3587
|
let openedURLs = [], clearOpenedURLs = ()=>{
|
|
@@ -3758,7 +3611,7 @@ async function open_open({ https, port, routes, config, clearCache }) {
|
|
|
3758
3611
|
try {
|
|
3759
3612
|
return new URL(str, base).href;
|
|
3760
3613
|
} catch (e) {
|
|
3761
|
-
throw Error(`${
|
|
3614
|
+
throw Error(`${index_js_default.dim('[rsbuild:open]')} Invalid input: ${index_js_default.yellow(str)} is not a valid URL or pathname`);
|
|
3762
3615
|
}
|
|
3763
3616
|
})(replacePortPlaceholder(target, port), baseUrl))) : routes.length && urls.push(`${baseUrl}${routes[0].pathname}`), before && await before(), urls))openedURLs.includes(url) || (openBrowser(url), openedURLs.push(url));
|
|
3764
3617
|
}
|
|
@@ -3785,18 +3638,18 @@ let getJsAsyncPath = (jsPath, isServer, jsAsync)=>void 0 !== jsAsync ? jsAsync :
|
|
|
3785
3638
|
}), jsPath = config.output.distPath.js, jsAsyncPath = getJsAsyncPath(jsPath, isServer, config.output.distPath.jsAsync), jsFilename = getFilename(config, 'js', isProd, isServer), isJsFilenameFn = 'function' == typeof jsFilename;
|
|
3786
3639
|
if (chain.output.path(distPath).filename(isJsFilenameFn ? (...args)=>{
|
|
3787
3640
|
let name = jsFilename(...args);
|
|
3788
|
-
return
|
|
3789
|
-
} :
|
|
3641
|
+
return posix.join(jsPath, name);
|
|
3642
|
+
} : posix.join(jsPath, jsFilename)).chunkFilename(isJsFilenameFn ? (...args)=>{
|
|
3790
3643
|
let name = jsFilename(...args);
|
|
3791
|
-
return
|
|
3792
|
-
} :
|
|
3644
|
+
return posix.join(jsAsyncPath, name);
|
|
3645
|
+
} : posix.join(jsAsyncPath, jsFilename)).publicPath(publicPath).pathinfo(!1).hashFunction('xxhash64'), isServer && chain.output.library({
|
|
3793
3646
|
type: 'commonjs2',
|
|
3794
3647
|
...chain.output.get('library') || {}
|
|
3795
3648
|
}), config.output.copy && 'rspack' === api.context.bundlerType) {
|
|
3796
3649
|
let { copy } = config.output, options = Array.isArray(copy) ? {
|
|
3797
3650
|
patterns: copy
|
|
3798
3651
|
} : copy;
|
|
3799
|
-
chain.plugin(CHAIN_ID.PLUGIN.COPY).use(
|
|
3652
|
+
chain.plugin(CHAIN_ID.PLUGIN.COPY).use(rspack.CopyRspackPlugin, [
|
|
3800
3653
|
options
|
|
3801
3654
|
]);
|
|
3802
3655
|
}
|
|
@@ -3834,7 +3687,7 @@ let getJsAsyncPath = (jsPath, isServer, jsAsync)=>void 0 !== jsAsync ? jsAsync :
|
|
|
3834
3687
|
let { config } = environment, options = config.dev.progressBar;
|
|
3835
3688
|
if (!options) return;
|
|
3836
3689
|
let prefix = !0 !== options && void 0 !== options.id ? options.id : environment.name;
|
|
3837
|
-
chain.plugin(CHAIN_ID.PLUGIN.PROGRESS).use(
|
|
3690
|
+
chain.plugin(CHAIN_ID.PLUGIN.PROGRESS).use(rspack.ProgressPlugin, [
|
|
3838
3691
|
{
|
|
3839
3692
|
prefix,
|
|
3840
3693
|
...!0 === options ? {} : options
|
|
@@ -3842,7 +3695,7 @@ let getJsAsyncPath = (jsPath, isServer, jsAsync)=>void 0 !== jsAsync ? jsAsync :
|
|
|
3842
3695
|
]);
|
|
3843
3696
|
});
|
|
3844
3697
|
}
|
|
3845
|
-
}), resolve_require =
|
|
3698
|
+
}), resolve_require = createRequire(import.meta.url), pluginResolve = ()=>({
|
|
3846
3699
|
name: 'rsbuild:resolve',
|
|
3847
3700
|
setup (api) {
|
|
3848
3701
|
api.modifyBundlerChain({
|
|
@@ -3863,17 +3716,17 @@ let getJsAsyncPath = (jsPath, isServer, jsAsync)=>void 0 !== jsAsync ? jsAsync :
|
|
|
3863
3716
|
initial: {},
|
|
3864
3717
|
config: config.resolve.alias
|
|
3865
3718
|
});
|
|
3866
|
-
if (config.source.alias && (
|
|
3719
|
+
if (config.source.alias && (logger.warn(`${index_js_default.dim('[rsbuild:config]')} The ${index_js_default.yellow('"source.alias"')} config is deprecated, use ${index_js_default.yellow('"resolve.alias"')} instead.`), mergedAlias = reduceConfigs({
|
|
3867
3720
|
initial: mergedAlias,
|
|
3868
3721
|
config: config.source.alias
|
|
3869
3722
|
})), config.resolve.dedupe) for (let pkgName of config.resolve.dedupe){
|
|
3870
3723
|
let pkgPath;
|
|
3871
3724
|
if (mergedAlias[pkgName]) {
|
|
3872
|
-
|
|
3725
|
+
logger.debug(`${index_js_default.dim('[rsbuild:resolve]')} The package ${index_js_default.yellow(pkgName)} is already in the alias config, dedupe option for ${index_js_default.yellow(pkgName)} will be ignored.`);
|
|
3873
3726
|
continue;
|
|
3874
3727
|
}
|
|
3875
3728
|
try {
|
|
3876
|
-
pkgPath =
|
|
3729
|
+
pkgPath = dirname(resolve_require.resolve(`${pkgName}/package.json`, {
|
|
3877
3730
|
paths: [
|
|
3878
3731
|
rootPath
|
|
3879
3732
|
]
|
|
@@ -3888,10 +3741,10 @@ let getJsAsyncPath = (jsPath, isServer, jsAsync)=>void 0 !== jsAsync ? jsAsync :
|
|
|
3888
3741
|
let trailing = [
|
|
3889
3742
|
'node_modules',
|
|
3890
3743
|
...pkgName.split('/')
|
|
3891
|
-
].join(
|
|
3892
|
-
for(; !pkgPath.endsWith(trailing) && pkgPath.includes('node_modules');)pkgPath =
|
|
3744
|
+
].join(sep);
|
|
3745
|
+
for(; !pkgPath.endsWith(trailing) && pkgPath.includes('node_modules');)pkgPath = dirname(pkgPath);
|
|
3893
3746
|
} catch (e) {
|
|
3894
|
-
|
|
3747
|
+
logger.debug(`${index_js_default.dim('[rsbuild:resolve]')} The package ${index_js_default.yellow(pkgName)} is not resolved in the project, dedupe option for ${index_js_default.yellow(pkgName)} will be ignored.`);
|
|
3895
3748
|
continue;
|
|
3896
3749
|
}
|
|
3897
3750
|
mergedAlias[pkgName] = pkgPath;
|
|
@@ -3904,7 +3757,7 @@ let getJsAsyncPath = (jsPath, isServer, jsAsync)=>void 0 !== jsAsync ? jsAsync :
|
|
|
3904
3757
|
chain,
|
|
3905
3758
|
config,
|
|
3906
3759
|
rootPath: api.context.rootPath
|
|
3907
|
-
}), chain.module.rule(CHAIN_ID.RULE.MJS).test(/\.m?js/).resolve.set('fullySpecified', !1), config.source.aliasStrategy &&
|
|
3760
|
+
}), chain.module.rule(CHAIN_ID.RULE.MJS).test(/\.m?js/).resolve.set('fullySpecified', !1), config.source.aliasStrategy && logger.warn(`${index_js_default.dim('[rsbuild:config]')} The ${index_js_default.yellow('"source.aliasStrategy"')} config is deprecated, use ${index_js_default.yellow('"resolve.aliasStrategy"')} instead.`);
|
|
3908
3761
|
let aliasStrategy = config.source.aliasStrategy ?? config.resolve.aliasStrategy;
|
|
3909
3762
|
tsconfigPath && 'rspack' === api.context.bundlerType && 'prefer-tsconfig' === aliasStrategy && chain.resolve.tsConfig({
|
|
3910
3763
|
configFile: tsconfigPath,
|
|
@@ -3992,7 +3845,7 @@ class HtmlResourceHintsPlugin {
|
|
|
3992
3845
|
rel: type
|
|
3993
3846
|
};
|
|
3994
3847
|
'preload' === type && (attributes.as = function({ href, file }) {
|
|
3995
|
-
let url = new
|
|
3848
|
+
let url = new external_node_url_URL(file || href, 'https://example.com'), extension = external_node_path_default.extname(url.pathname).slice(1);
|
|
3996
3849
|
return [
|
|
3997
3850
|
'css'
|
|
3998
3851
|
].includes(extension) ? 'style' : IMAGE_EXTENSIONS.includes(extension) ? 'image' : VIDEO_EXTENSIONS.includes(extension) ? 'video' : AUDIO_EXTENSIONS.includes(extension) ? 'audio' : FONT_EXTENSIONS.includes(extension) ? 'font' : [
|
|
@@ -4036,7 +3889,7 @@ let resourceHints_generateLinks = (options, rel)=>options.map((option)=>({
|
|
|
4036
3889
|
return [
|
|
4037
3890
|
...scriptTests,
|
|
4038
3891
|
...styleTests
|
|
4039
|
-
].filter((item)=>
|
|
3892
|
+
].filter((item)=>isRegExp(item));
|
|
4040
3893
|
}, pluginResourceHints = ()=>({
|
|
4041
3894
|
name: 'rsbuild:resource-hints',
|
|
4042
3895
|
setup (api) {
|
|
@@ -4086,7 +3939,7 @@ let resourceHints_generateLinks = (options, rel)=>options.map((option)=>({
|
|
|
4086
3939
|
}
|
|
4087
3940
|
});
|
|
4088
3941
|
}
|
|
4089
|
-
}), rsdoctor_require =
|
|
3942
|
+
}), rsdoctor_require = createRequire(import.meta.url), pluginRsdoctor = ()=>({
|
|
4090
3943
|
name: 'rsbuild:rsdoctor',
|
|
4091
3944
|
setup (api) {
|
|
4092
3945
|
api.onBeforeCreateCompiler(async ({ bundlerConfigs })=>{
|
|
@@ -4108,36 +3961,36 @@ let resourceHints_generateLinks = (options, rel)=>options.map((option)=>({
|
|
|
4108
3961
|
]
|
|
4109
3962
|
});
|
|
4110
3963
|
} catch (err) {
|
|
4111
|
-
|
|
3964
|
+
logger.warn(`\`process.env.RSDOCTOR\` enabled, please install ${index_js_default.bold(index_js_default.yellow(packageName))} package.`);
|
|
4112
3965
|
return;
|
|
4113
3966
|
}
|
|
4114
3967
|
try {
|
|
4115
|
-
let moduleURL = 'win32' === process.platform ?
|
|
3968
|
+
let moduleURL = 'win32' === process.platform ? pathToFileURL(packagePath).href : packagePath;
|
|
4116
3969
|
module = await import(moduleURL);
|
|
4117
3970
|
} catch (err) {
|
|
4118
|
-
|
|
3971
|
+
logger.error(`\`process.env.RSDOCTOR\` enabled, but failed to load ${index_js_default.bold(index_js_default.yellow(packageName))} module.`);
|
|
4119
3972
|
return;
|
|
4120
3973
|
}
|
|
4121
3974
|
if (module && module[pluginName]) {
|
|
4122
3975
|
for (let config of bundlerConfigs)config.plugins ||= [], config.plugins.push(new module[pluginName]());
|
|
4123
|
-
|
|
3976
|
+
logger.info(`${index_js_default.bold(index_js_default.yellow(packageName))} enabled.`);
|
|
4124
3977
|
}
|
|
4125
3978
|
});
|
|
4126
3979
|
}
|
|
4127
3980
|
});
|
|
4128
3981
|
async function ensureFileDir(outputFilePath) {
|
|
4129
|
-
let dir =
|
|
4130
|
-
await
|
|
3982
|
+
let dir = external_node_path_default.dirname(outputFilePath);
|
|
3983
|
+
await external_node_fs_default.promises.mkdir(dir, {
|
|
4131
3984
|
recursive: !0
|
|
4132
3985
|
});
|
|
4133
3986
|
}
|
|
4134
|
-
async function applyProfile(root, filterValue, traceLayer = '
|
|
4135
|
-
if ('
|
|
3987
|
+
async function applyProfile(root, filterValue, traceLayer = 'perfetto', traceOutput) {
|
|
3988
|
+
if ('perfetto' !== traceLayer && 'logger' !== traceLayer) throw Error(`unsupported trace layer: ${traceLayer}`);
|
|
4136
3989
|
if (!traceOutput) {
|
|
4137
|
-
let timestamp = Date.now(), defaultOutputDir =
|
|
4138
|
-
traceOutput = '
|
|
3990
|
+
let timestamp = Date.now(), defaultOutputDir = external_node_path_default.join(root, `.rspack-profile-${timestamp}-${process.pid}`), defaultRustTracePerfettoOutput = external_node_path_default.join(defaultOutputDir, 'rspack.pftrace');
|
|
3991
|
+
traceOutput = 'perfetto' === traceLayer ? defaultRustTracePerfettoOutput : 'stdout';
|
|
4139
3992
|
}
|
|
4140
|
-
return await ensureFileDir(traceOutput), await
|
|
3993
|
+
return await ensureFileDir(traceOutput), await rspack.experiments.globalTrace.register("OVERVIEW" === filterValue ? 'info' : "ALL" === filterValue ? 'trace' : filterValue, traceLayer, traceOutput), traceOutput;
|
|
4141
3994
|
}
|
|
4142
3995
|
let pluginRspackProfile = ()=>({
|
|
4143
3996
|
name: 'rsbuild:rspack-profile',
|
|
@@ -4152,7 +4005,7 @@ let pluginRspackProfile = ()=>({
|
|
|
4152
4005
|
api.onBeforeBuild(({ isFirstCompile })=>{
|
|
4153
4006
|
isFirstCompile && onStart();
|
|
4154
4007
|
}), api.onBeforeStartDevServer(onStart), api.onExit(()=>{
|
|
4155
|
-
traceOutput && (
|
|
4008
|
+
traceOutput && (rspack.experiments.globalTrace.cleanup(), logger.info(`profile file saved to ${index_js_default.cyan(traceOutput)}`));
|
|
4156
4009
|
});
|
|
4157
4010
|
}
|
|
4158
4011
|
}), pluginServer = ()=>({
|
|
@@ -4174,11 +4027,11 @@ let pluginRspackProfile = ()=>({
|
|
|
4174
4027
|
if (isFirstCompile) for (let publicDir of normalizePublicDirs(api.getNormalizedConfig().server.publicDir)){
|
|
4175
4028
|
let { name, copyOnBuild } = publicDir;
|
|
4176
4029
|
if (!1 === copyOnBuild || !name) continue;
|
|
4177
|
-
let normalizedPath = (
|
|
4178
|
-
if (!
|
|
4030
|
+
let normalizedPath = external_node_path_isAbsolute(name) ? name : join(api.context.rootPath, name);
|
|
4031
|
+
if (!external_node_fs_default.existsSync(normalizedPath)) continue;
|
|
4179
4032
|
let distPaths = dedupeNestedPaths(Object.values(environments).filter(({ config })=>!0 === copyOnBuild || 'auto' === copyOnBuild && 'node' !== config.output.target).map(({ distPath })=>distPath));
|
|
4180
4033
|
try {
|
|
4181
|
-
await Promise.all(distPaths.map((distPath)=>
|
|
4034
|
+
await Promise.all(distPaths.map((distPath)=>external_node_fs_default.promises.cp(normalizedPath, distPath, {
|
|
4182
4035
|
recursive: !0,
|
|
4183
4036
|
dereference: !0
|
|
4184
4037
|
})));
|
|
@@ -4344,24 +4197,24 @@ let pluginRspackProfile = ()=>({
|
|
|
4344
4197
|
let crossorigin = chain.output.get('crossOriginLoading');
|
|
4345
4198
|
(!1 === crossorigin || void 0 === crossorigin) && chain.output.crossOriginLoading('anonymous');
|
|
4346
4199
|
let { algorithm = 'sha384' } = sri;
|
|
4347
|
-
chain.plugin(CHAIN_ID.PLUGIN.SUBRESOURCE_INTEGRITY).use(
|
|
4200
|
+
chain.plugin(CHAIN_ID.PLUGIN.SUBRESOURCE_INTEGRITY).use(rspack.experiments.SubresourceIntegrityPlugin, [
|
|
4348
4201
|
{
|
|
4349
4202
|
enabled: !0,
|
|
4350
4203
|
hashFuncNames: [
|
|
4351
4204
|
algorithm
|
|
4352
4205
|
],
|
|
4353
|
-
htmlPlugin:
|
|
4206
|
+
htmlPlugin: external_node_path_default.join(COMPILED_PATH, 'html-rspack-plugin/index.js')
|
|
4354
4207
|
}
|
|
4355
4208
|
]);
|
|
4356
4209
|
});
|
|
4357
4210
|
}
|
|
4358
|
-
}), swc_require =
|
|
4211
|
+
}), swc_require = createRequire(import.meta.url), builtinSwcLoaderName = 'builtin:swc-loader', pluginSwc = ()=>({
|
|
4359
4212
|
name: PLUGIN_SWC_NAME,
|
|
4360
4213
|
setup (api) {
|
|
4361
4214
|
api.modifyBundlerChain({
|
|
4362
4215
|
order: 'pre',
|
|
4363
4216
|
handler: async (chain, { CHAIN_ID, isDev, target, environment })=>{
|
|
4364
|
-
let { config, browserslist } = environment, cacheRoot =
|
|
4217
|
+
let { config, browserslist } = environment, cacheRoot = external_node_path_default.join(api.context.cachePath, '.swc'), rule = chain.module.rule(CHAIN_ID.RULE.JS).test(SCRIPT_REGEX).type("javascript/auto").dependency({
|
|
4365
4218
|
not: 'url'
|
|
4366
4219
|
}).resourceQuery({
|
|
4367
4220
|
not: /raw|inline/
|
|
@@ -4416,7 +4269,7 @@ let pluginRspackProfile = ()=>({
|
|
|
4416
4269
|
swcConfig.jsc.transform.legacyDecorator = !1, swcConfig.jsc.transform.decoratorVersion = '2022-03';
|
|
4417
4270
|
break;
|
|
4418
4271
|
default:
|
|
4419
|
-
throw Error(`${
|
|
4272
|
+
throw Error(`${index_js_default.dim('[rsbuild:swc]')} Unknown decorators version: ${index_js_default.yellow(version)}`);
|
|
4420
4273
|
}
|
|
4421
4274
|
}(swcConfig, config), castArray(target).includes('web') || target.includes('web-worker')) {
|
|
4422
4275
|
let polyfillMode = config.output.polyfill;
|
|
@@ -4441,14 +4294,14 @@ let pluginRspackProfile = ()=>({
|
|
|
4441
4294
|
}
|
|
4442
4295
|
}), getCoreJsVersion = (corejsPkgPath)=>{
|
|
4443
4296
|
try {
|
|
4444
|
-
let rawJson =
|
|
4297
|
+
let rawJson = external_node_fs_default.readFileSync(corejsPkgPath, 'utf-8'), { version } = JSON.parse(rawJson), [major, minor] = version.split('.');
|
|
4445
4298
|
return `${major}.${minor}`;
|
|
4446
4299
|
} catch (err) {
|
|
4447
4300
|
return '3';
|
|
4448
4301
|
}
|
|
4449
4302
|
};
|
|
4450
4303
|
async function applyCoreJs(swcConfig, polyfillMode) {
|
|
4451
|
-
let coreJsPath = swc_require.resolve('core-js/package.json'), version = getCoreJsVersion(coreJsPath), coreJsDir =
|
|
4304
|
+
let coreJsPath = swc_require.resolve('core-js/package.json'), version = getCoreJsVersion(coreJsPath), coreJsDir = external_node_path_default.dirname(coreJsPath);
|
|
4452
4305
|
return swcConfig.env.coreJs = version, 'usage' === polyfillMode && (swcConfig.env.shippedProposals = !0), coreJsDir;
|
|
4453
4306
|
}
|
|
4454
4307
|
let reduceTransformImportConfig = (options)=>{
|
|
@@ -4488,7 +4341,7 @@ let reduceTransformImportConfig = (options)=>{
|
|
|
4488
4341
|
...chain.get('experiments'),
|
|
4489
4342
|
asyncWebAssembly: !0
|
|
4490
4343
|
});
|
|
4491
|
-
let wasmFilename =
|
|
4344
|
+
let wasmFilename = posix.join(distPath, '[hash].module.wasm');
|
|
4492
4345
|
chain.output.webassemblyModuleFilename(wasmFilename), chain.module.rule(CHAIN_ID.RULE.WASM).test(/\.wasm$/).dependency('url').type('asset/resource').set('generator', {
|
|
4493
4346
|
filename: wasmFilename
|
|
4494
4347
|
});
|
|
@@ -4526,40 +4379,36 @@ let reduceTransformImportConfig = (options)=>{
|
|
|
4526
4379
|
};
|
|
4527
4380
|
async function outputInspectConfigFiles({ rawBundlerConfigs, rawEnvironmentConfigs, inspectOptions, configType }) {
|
|
4528
4381
|
let { outputPath } = inspectOptions, files = [
|
|
4529
|
-
...rawEnvironmentConfigs.map(({ name, content })=>{
|
|
4530
|
-
|
|
4531
|
-
path: (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(outputPath, 'rsbuild.config.mjs'),
|
|
4382
|
+
...rawEnvironmentConfigs.map(({ name, content })=>1 === rawEnvironmentConfigs.length ? {
|
|
4383
|
+
path: join(outputPath, 'rsbuild.config.mjs'),
|
|
4532
4384
|
label: 'Rsbuild config',
|
|
4533
4385
|
content
|
|
4534
|
-
}
|
|
4535
|
-
|
|
4536
|
-
return {
|
|
4537
|
-
path: (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(outputPath, outputFile),
|
|
4386
|
+
} : {
|
|
4387
|
+
path: join(outputPath, `rsbuild.config.${name}.mjs`),
|
|
4538
4388
|
label: `Rsbuild config (${name})`,
|
|
4539
4389
|
content
|
|
4540
|
-
}
|
|
4541
|
-
}),
|
|
4390
|
+
}),
|
|
4542
4391
|
...rawBundlerConfigs.map(({ name, content })=>{
|
|
4543
|
-
let
|
|
4544
|
-
return
|
|
4392
|
+
let outputFilePath = join(outputPath, `${configType}.config.${name}.mjs`);
|
|
4393
|
+
return external_node_fs_default.existsSync(outputFilePath) && (outputFilePath = outputFilePath.replace(/\.mjs$/, `.${Date.now()}.mjs`)), {
|
|
4545
4394
|
path: outputFilePath,
|
|
4546
4395
|
label: `${upperFirst(configType)} Config (${name})`,
|
|
4547
4396
|
content
|
|
4548
4397
|
};
|
|
4549
4398
|
})
|
|
4550
4399
|
];
|
|
4551
|
-
await
|
|
4400
|
+
await external_node_fs_default.promises.mkdir(outputPath, {
|
|
4552
4401
|
recursive: !0
|
|
4553
|
-
}), await Promise.all(files.map(async (item)=>
|
|
4554
|
-
let fileInfos = files.map((item)=>` - ${
|
|
4555
|
-
|
|
4402
|
+
}), await Promise.all(files.map(async (item)=>external_node_fs_default.promises.writeFile(item.path, `export default ${item.content}`)));
|
|
4403
|
+
let fileInfos = files.map((item)=>` - ${index_js_default.bold(index_js_default.yellow(item.label))}: ${index_js_default.underline(item.path)}`).join('\n');
|
|
4404
|
+
logger.success(`config inspection completed, generated files: \n\n${fileInfos}\n`);
|
|
4556
4405
|
}
|
|
4557
4406
|
function stringifyConfig(config, verbose) {
|
|
4558
|
-
return (0,
|
|
4407
|
+
return (0, rspack_chain_index_js_default.toString)(config, {
|
|
4559
4408
|
verbose
|
|
4560
4409
|
});
|
|
4561
4410
|
}
|
|
4562
|
-
let getInspectOutputPath = (context, inspectOptions)=>inspectOptions.outputPath ? (
|
|
4411
|
+
let getInspectOutputPath = (context, inspectOptions)=>inspectOptions.outputPath ? external_node_path_isAbsolute(inspectOptions.outputPath) ? inspectOptions.outputPath : join(context.distPath, inspectOptions.outputPath) : join(context.distPath, RSBUILD_OUTPUTS_PATH);
|
|
4563
4412
|
async function inspectConfig({ context, pluginManager, bundlerConfigs, inspectOptions = {}, bundler = 'rspack' }) {
|
|
4564
4413
|
inspectOptions.mode ? setNodeEnv(inspectOptions.mode) : getNodeEnv() || setNodeEnv('development');
|
|
4565
4414
|
let rawBundlerConfigs = bundlerConfigs.map((config, index)=>({
|
|
@@ -4592,7 +4441,7 @@ async function inspectConfig({ context, pluginManager, bundlerConfigs, inspectOp
|
|
|
4592
4441
|
var dist = __webpack_require__("../../node_modules/.pnpm/webpack-merge@6.0.1/node_modules/webpack-merge/dist/index.js");
|
|
4593
4442
|
async function modifyRspackConfig(context, rspackConfig, chainUtils) {
|
|
4594
4443
|
var _utils_environment_config_tools;
|
|
4595
|
-
|
|
4444
|
+
logger.debug('modify Rspack config');
|
|
4596
4445
|
let currentConfig = rspackConfig, proxiedConfig = new Proxy({}, {
|
|
4597
4446
|
get: (_, prop)=>currentConfig[prop],
|
|
4598
4447
|
set: (_, prop, value)=>(currentConfig[prop] = value, !0)
|
|
@@ -4612,7 +4461,7 @@ async function modifyRspackConfig(context, rspackConfig, chainUtils) {
|
|
|
4612
4461
|
mergeFn: (...args)=>currentConfig = utils.mergeConfig.call(utils, args)
|
|
4613
4462
|
});
|
|
4614
4463
|
}
|
|
4615
|
-
return
|
|
4464
|
+
return logger.debug('modify Rspack config done'), currentConfig;
|
|
4616
4465
|
}
|
|
4617
4466
|
async function getConfigUtils(config, chainUtils) {
|
|
4618
4467
|
return {
|
|
@@ -4640,11 +4489,10 @@ async function getConfigUtils(config, chainUtils) {
|
|
|
4640
4489
|
};
|
|
4641
4490
|
}
|
|
4642
4491
|
function getChainUtils(target, environment) {
|
|
4643
|
-
let nodeEnv = getNodeEnv();
|
|
4644
4492
|
return {
|
|
4645
|
-
rspack:
|
|
4493
|
+
rspack: rspack,
|
|
4646
4494
|
environment,
|
|
4647
|
-
env:
|
|
4495
|
+
env: getNodeEnv(),
|
|
4648
4496
|
target,
|
|
4649
4497
|
isDev: 'development' === environment.config.mode,
|
|
4650
4498
|
isProd: 'production' === environment.config.mode,
|
|
@@ -4655,7 +4503,7 @@ function getChainUtils(target, environment) {
|
|
|
4655
4503
|
};
|
|
4656
4504
|
}
|
|
4657
4505
|
async function generateRspackConfig({ target, context, environment }) {
|
|
4658
|
-
let chainUtils = getChainUtils(target, context.environments[environment]), { BannerPlugin, DefinePlugin, IgnorePlugin, ProvidePlugin, SourceMapDevToolPlugin, HotModuleReplacementPlugin } =
|
|
4506
|
+
let chainUtils = getChainUtils(target, context.environments[environment]), { BannerPlugin, DefinePlugin, IgnorePlugin, ProvidePlugin, SourceMapDevToolPlugin, HotModuleReplacementPlugin } = rspack, rspackConfig = (await modifyBundlerChain(context, {
|
|
4659
4507
|
...chainUtils,
|
|
4660
4508
|
bundler: {
|
|
4661
4509
|
BannerPlugin,
|
|
@@ -4669,22 +4517,22 @@ async function generateRspackConfig({ target, context, environment }) {
|
|
|
4669
4517
|
var config = rspackConfig = await modifyRspackConfig(context, rspackConfig, chainUtils);
|
|
4670
4518
|
if (config.plugins) {
|
|
4671
4519
|
for (let plugin of config.plugins)if (plugin && void 0 === plugin.apply && 'name' in plugin && 'setup' in plugin) {
|
|
4672
|
-
let name =
|
|
4673
|
-
throw Error(`${
|
|
4520
|
+
let name = index_js_default.bold(index_js_default.yellow(plugin.name));
|
|
4521
|
+
throw Error(`${index_js_default.dim('[rsbuild:plugin]')} "${index_js_default.yellow(name)}" appears to be an Rsbuild plugin. It cannot be used as an Rspack plugin.`);
|
|
4674
4522
|
}
|
|
4675
4523
|
}
|
|
4676
|
-
return config.devServer &&
|
|
4524
|
+
return config.devServer && logger.warn(`${index_js_default.dim('[rsbuild:config]')} Find invalid Rspack config: "${index_js_default.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;
|
|
4677
4525
|
}
|
|
4678
4526
|
async function modifyRsbuildConfig(context) {
|
|
4679
4527
|
var _context_config_plugins, _modified_plugins;
|
|
4680
|
-
|
|
4528
|
+
logger.debug('modify Rsbuild config');
|
|
4681
4529
|
let pluginsCount = (null == (_context_config_plugins = context.config.plugins) ? void 0 : _context_config_plugins.length) ?? 0, [modified] = await context.hooks.modifyRsbuildConfig.callChain(context.config, {
|
|
4682
4530
|
mergeRsbuildConfig: mergeRsbuildConfig
|
|
4683
4531
|
});
|
|
4684
|
-
context.config = modified, ((null == (_modified_plugins = modified.plugins) ? void 0 : _modified_plugins.length) ?? 0) !== pluginsCount &&
|
|
4532
|
+
context.config = modified, ((null == (_modified_plugins = modified.plugins) ? void 0 : _modified_plugins.length) ?? 0) !== pluginsCount && logger.warn(`${index_js_default.dim('[rsbuild]')} Cannot change plugins via ${index_js_default.yellow('modifyRsbuildConfig')} as plugins are already initialized when it executes.`), logger.debug('modify Rsbuild config done');
|
|
4685
4533
|
}
|
|
4686
4534
|
async function modifyEnvironmentConfig(context, config, name) {
|
|
4687
|
-
|
|
4535
|
+
logger.debug(`modify Rsbuild environment(${name}) config`);
|
|
4688
4536
|
let [modified] = await context.hooks.modifyEnvironmentConfig.callChain({
|
|
4689
4537
|
environment: name,
|
|
4690
4538
|
args: [
|
|
@@ -4695,7 +4543,7 @@ async function modifyEnvironmentConfig(context, config, name) {
|
|
|
4695
4543
|
}
|
|
4696
4544
|
]
|
|
4697
4545
|
});
|
|
4698
|
-
return
|
|
4546
|
+
return logger.debug(`modify Rsbuild environment(${name}) config done`), modified;
|
|
4699
4547
|
}
|
|
4700
4548
|
let initEnvironmentConfigs = (normalizedConfig, rootPath, specifiedEnvironments)=>{
|
|
4701
4549
|
let defaultEntry, getDefaultEntryWithMemo = ()=>(defaultEntry || (defaultEntry = function(root) {
|
|
@@ -4708,7 +4556,7 @@ let initEnvironmentConfigs = (normalizedConfig, rootPath, specifiedEnvironments)
|
|
|
4708
4556
|
'cts',
|
|
4709
4557
|
'mjs',
|
|
4710
4558
|
'cjs'
|
|
4711
|
-
].map((ext)=>
|
|
4559
|
+
].map((ext)=>join(root, `src/index.${ext}`)));
|
|
4712
4560
|
return entryFile ? {
|
|
4713
4561
|
index: entryFile
|
|
4714
4562
|
} : {};
|
|
@@ -4733,11 +4581,11 @@ let initEnvironmentConfigs = (normalizedConfig, rootPath, specifiedEnvironments)
|
|
|
4733
4581
|
}, config)
|
|
4734
4582
|
})
|
|
4735
4583
|
]));
|
|
4736
|
-
if (!Object.keys(resolvedEnvironments).length) throw Error(`${
|
|
4584
|
+
if (!Object.keys(resolvedEnvironments).length) throw Error(`${index_js_default.dim('[rsbuild:config]')} The current build is specified to run only in the ${index_js_default.yellow(null == specifiedEnvironments ? void 0 : specifiedEnvironments.join(','))} environment, but the configuration of the specified environment was not found.`);
|
|
4737
4585
|
return resolvedEnvironments;
|
|
4738
4586
|
}
|
|
4739
4587
|
let defaultEnvironmentName = camelCase(rsbuildSharedConfig.output.target);
|
|
4740
|
-
if (!isEnvironmentEnabled(defaultEnvironmentName)) throw Error(`${
|
|
4588
|
+
if (!isEnvironmentEnabled(defaultEnvironmentName)) throw Error(`${index_js_default.dim('[rsbuild:config]')} The current build is specified to run only in the ${index_js_default.yellow(null == specifiedEnvironments ? void 0 : specifiedEnvironments.join(','))} environment, but the configuration of the specified environment was not found.`);
|
|
4741
4589
|
return {
|
|
4742
4590
|
[defaultEnvironmentName]: applyEnvironmentDefaultConfig({
|
|
4743
4591
|
...rsbuildSharedConfig,
|
|
@@ -4751,10 +4599,10 @@ let initEnvironmentConfigs = (normalizedConfig, rootPath, specifiedEnvironments)
|
|
|
4751
4599
|
})
|
|
4752
4600
|
};
|
|
4753
4601
|
}, validateRsbuildConfig = (config)=>{
|
|
4754
|
-
if (config.server.base && !config.server.base.startsWith('/')) throw Error(`${
|
|
4602
|
+
if (config.server.base && !config.server.base.startsWith('/')) throw Error(`${index_js_default.dim('[rsbuild:config]')} The ${index_js_default.yellow('"server.base"')} option should start with a slash, for example: "/base"`);
|
|
4755
4603
|
if (config.environments) {
|
|
4756
4604
|
let names = Object.keys(config.environments), regexp = /^[\w$-]+$/;
|
|
4757
|
-
for (let name of names)regexp.test(name) ||
|
|
4605
|
+
for (let name of names)regexp.test(name) || logger.warn(`${index_js_default.dim('[rsbuild:config]')} Environment name "${index_js_default.yellow(name)}" contains invalid characters. Only letters, numbers, "-", "_", and "$" are allowed.`);
|
|
4758
4606
|
}
|
|
4759
4607
|
};
|
|
4760
4608
|
async function initRsbuildConfig({ context, pluginManager }) {
|
|
@@ -4792,13 +4640,13 @@ async function initRsbuildConfig({ context, pluginManager }) {
|
|
|
4792
4640
|
...new Set(paths)
|
|
4793
4641
|
];
|
|
4794
4642
|
if (1 === uniquePaths.length) return uniquePaths[0];
|
|
4795
|
-
let [first, ...rest] = uniquePaths.map((p)=>p.split(
|
|
4643
|
+
let [first, ...rest] = uniquePaths.map((p)=>p.split(sep)), common = [];
|
|
4796
4644
|
for(let i = 0; i < first.length; i++){
|
|
4797
4645
|
let segment = first[i];
|
|
4798
4646
|
if (rest.every((p)=>p[i] === segment)) common.push(segment);
|
|
4799
4647
|
else break;
|
|
4800
4648
|
}
|
|
4801
|
-
return common.join(
|
|
4649
|
+
return common.join(sep);
|
|
4802
4650
|
}(distPaths), validateRsbuildConfig(context.normalizedConfig), context.normalizedConfig;
|
|
4803
4651
|
}
|
|
4804
4652
|
async function initConfigs({ context, pluginManager, rsbuildOptions }) {
|
|
@@ -4836,9 +4684,9 @@ function defineConfig(config) {
|
|
|
4836
4684
|
}
|
|
4837
4685
|
let resolveConfigPath = (root, customConfig)=>{
|
|
4838
4686
|
if (customConfig) {
|
|
4839
|
-
let customConfigPath = (
|
|
4840
|
-
if (
|
|
4841
|
-
|
|
4687
|
+
let customConfigPath = external_node_path_isAbsolute(customConfig) ? customConfig : join(root, customConfig);
|
|
4688
|
+
if (external_node_fs_default.existsSync(customConfigPath)) return customConfigPath;
|
|
4689
|
+
logger.warn(`Cannot find config file: ${index_js_default.dim(customConfigPath)}\n`);
|
|
4842
4690
|
}
|
|
4843
4691
|
for (let file of [
|
|
4844
4692
|
'rsbuild.config.mjs',
|
|
@@ -4848,14 +4696,14 @@ let resolveConfigPath = (root, customConfig)=>{
|
|
|
4848
4696
|
'rsbuild.config.mts',
|
|
4849
4697
|
'rsbuild.config.cts'
|
|
4850
4698
|
]){
|
|
4851
|
-
let configFile =
|
|
4852
|
-
if (
|
|
4699
|
+
let configFile = join(root, file);
|
|
4700
|
+
if (external_node_fs_default.existsSync(configFile)) return configFile;
|
|
4853
4701
|
}
|
|
4854
4702
|
return null;
|
|
4855
4703
|
};
|
|
4856
4704
|
async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta, loader = 'jiti' } = {}) {
|
|
4857
4705
|
let configExport, configFilePath = resolveConfigPath(cwd, path);
|
|
4858
|
-
if (!configFilePath) return
|
|
4706
|
+
if (!configFilePath) return logger.debug('no config file found.'), {
|
|
4859
4707
|
content: {},
|
|
4860
4708
|
filePath: configFilePath
|
|
4861
4709
|
};
|
|
@@ -4863,11 +4711,11 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
4863
4711
|
configFilePath
|
|
4864
4712
|
}, config);
|
|
4865
4713
|
if ('native' === loader || /\.(?:js|mjs|cjs)$/.test(configFilePath)) try {
|
|
4866
|
-
let configFileURL =
|
|
4714
|
+
let configFileURL = pathToFileURL(configFilePath).href, exportModule = await import(`${configFileURL}?t=${Date.now()}`);
|
|
4867
4715
|
configExport = exportModule.default ? exportModule.default : exportModule;
|
|
4868
4716
|
} catch (err) {
|
|
4869
|
-
if ('native' === loader) throw
|
|
4870
|
-
|
|
4717
|
+
if ('native' === loader) throw logger.error(`Failed to load file with native loader: ${index_js_default.dim(configFilePath)}`), err;
|
|
4718
|
+
logger.debug(`failed to load file with dynamic import: ${index_js_default.dim(configFilePath)}`);
|
|
4871
4719
|
}
|
|
4872
4720
|
try {
|
|
4873
4721
|
if (void 0 === configExport) {
|
|
@@ -4884,7 +4732,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
4884
4732
|
});
|
|
4885
4733
|
}
|
|
4886
4734
|
} catch (err) {
|
|
4887
|
-
throw
|
|
4735
|
+
throw logger.error(`Failed to load file with jiti: ${index_js_default.dim(configFilePath)}`), err;
|
|
4888
4736
|
}
|
|
4889
4737
|
if ('function' == typeof configExport) {
|
|
4890
4738
|
let command = process.argv[2], nodeEnv = getNodeEnv(), result = await configExport({
|
|
@@ -4893,19 +4741,19 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
4893
4741
|
envMode: envMode || nodeEnv,
|
|
4894
4742
|
meta
|
|
4895
4743
|
});
|
|
4896
|
-
if (void 0 === result) throw Error(`${
|
|
4744
|
+
if (void 0 === result) throw Error(`${index_js_default.dim('[rsbuild:loadConfig]')} The config function must return a config object.`);
|
|
4897
4745
|
return {
|
|
4898
4746
|
content: applyMetaInfo(result),
|
|
4899
4747
|
filePath: configFilePath
|
|
4900
4748
|
};
|
|
4901
4749
|
}
|
|
4902
|
-
if (!isObject(configExport)) throw Error(`${
|
|
4903
|
-
return
|
|
4750
|
+
if (!isObject(configExport)) throw Error(`${index_js_default.dim('[rsbuild:loadConfig]')} The config must be an object or a function that returns an object, get ${index_js_default.yellow(configExport)}`);
|
|
4751
|
+
return logger.debug('loaded config file:', configFilePath), {
|
|
4904
4752
|
content: applyMetaInfo(configExport),
|
|
4905
4753
|
filePath: configFilePath
|
|
4906
4754
|
};
|
|
4907
4755
|
}
|
|
4908
|
-
let commonOpts = {}, getEnvDir = (cwd, envDir)=>envDir ?
|
|
4756
|
+
let commonOpts = {}, getEnvDir = (cwd, envDir)=>envDir ? external_node_path_default.isAbsolute(envDir) ? envDir : external_node_path_default.join(cwd, envDir) : cwd, init_loadConfig = async (root)=>{
|
|
4909
4757
|
var _config_server;
|
|
4910
4758
|
let { content: config, filePath } = await loadConfig_loadConfig({
|
|
4911
4759
|
cwd: root,
|
|
@@ -4953,7 +4801,7 @@ async function init({ cliOptions, isRestart, isBuildWatch = !1 }) {
|
|
|
4953
4801
|
});
|
|
4954
4802
|
}), rsbuild;
|
|
4955
4803
|
} catch (err) {
|
|
4956
|
-
if (isRestart)
|
|
4804
|
+
if (isRestart) logger.error(err);
|
|
4957
4805
|
else throw err;
|
|
4958
4806
|
}
|
|
4959
4807
|
}
|
|
@@ -5023,9 +4871,9 @@ let cleaners = [], onBeforeRestartServer = (cleaner)=>{
|
|
|
5023
4871
|
isTTY() && !process.env.DEBUG && process.stdout.write('\x1B[H\x1B[2J');
|
|
5024
4872
|
}, beforeRestart = async ({ filePath, clear = !0, id })=>{
|
|
5025
4873
|
if (clear && clearConsole(), filePath) {
|
|
5026
|
-
let filename =
|
|
5027
|
-
|
|
5028
|
-
} else
|
|
4874
|
+
let filename = external_node_path_default.basename(filePath);
|
|
4875
|
+
logger.info(`restarting ${id} as ${index_js_default.yellow(filename)} changed\n`);
|
|
4876
|
+
} else logger.info(`restarting ${id}...\n`);
|
|
5029
4877
|
for (let cleaner of cleaners)await cleaner();
|
|
5030
4878
|
cleaners = [];
|
|
5031
4879
|
}, restartDevServer = async ({ filePath, clear = !0 } = {})=>{
|
|
@@ -5063,7 +4911,7 @@ async function watchFilesForRestart({ files, rsbuild, isBuildWatch, watchOptions
|
|
|
5063
4911
|
filePath
|
|
5064
4912
|
}) : await restartDevServer({
|
|
5065
4913
|
filePath
|
|
5066
|
-
})) ? await watcher.close() :
|
|
4914
|
+
})) ? await watcher.close() : logger.error(isBuildWatch ? 'Restart build failed.' : 'Restart server failed.'), restarting = !1);
|
|
5067
4915
|
};
|
|
5068
4916
|
watcher.on('add', onChange), watcher.on('change', onChange), watcher.on('unlink', onChange);
|
|
5069
4917
|
}
|
|
@@ -5072,19 +4920,19 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
|
|
|
5072
4920
|
let shortcuts = [
|
|
5073
4921
|
{
|
|
5074
4922
|
key: 'c',
|
|
5075
|
-
description: `${
|
|
4923
|
+
description: `${index_js_default.bold('c + enter')} ${index_js_default.dim('clear console')}`,
|
|
5076
4924
|
action: ()=>{
|
|
5077
4925
|
console.clear();
|
|
5078
4926
|
}
|
|
5079
4927
|
},
|
|
5080
4928
|
{
|
|
5081
4929
|
key: 'o',
|
|
5082
|
-
description: `${
|
|
4930
|
+
description: `${index_js_default.bold('o + enter')} ${index_js_default.dim('open in browser')}`,
|
|
5083
4931
|
action: openPage
|
|
5084
4932
|
},
|
|
5085
4933
|
{
|
|
5086
4934
|
key: 'q',
|
|
5087
|
-
description: `${
|
|
4935
|
+
description: `${index_js_default.bold('q + enter')} ${index_js_default.dim('quit process')}`,
|
|
5088
4936
|
action: async ()=>{
|
|
5089
4937
|
try {
|
|
5090
4938
|
await closeServer();
|
|
@@ -5095,25 +4943,25 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
|
|
|
5095
4943
|
},
|
|
5096
4944
|
restartServer ? {
|
|
5097
4945
|
key: 'r',
|
|
5098
|
-
description: `${
|
|
4946
|
+
description: `${index_js_default.bold('r + enter')} ${index_js_default.dim('restart server')}`,
|
|
5099
4947
|
action: restartServer
|
|
5100
4948
|
} : null,
|
|
5101
4949
|
{
|
|
5102
4950
|
key: 'u',
|
|
5103
|
-
description: `${
|
|
4951
|
+
description: `${index_js_default.bold('u + enter')} ${index_js_default.dim('show urls')}`,
|
|
5104
4952
|
action: printUrls
|
|
5105
4953
|
}
|
|
5106
4954
|
].filter(Boolean);
|
|
5107
|
-
if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${
|
|
5108
|
-
help &&
|
|
4955
|
+
if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${index_js_default.dim('[rsbuild:config]')} ${index_js_default.yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
|
|
4956
|
+
help && logger.log(!0 === help ? ` \u{279C} ${index_js_default.dim('press')} ${index_js_default.bold('h + enter')} ${index_js_default.dim('to show shortcuts')}\n` : ` \u{279C} ${help}\n`);
|
|
5109
4957
|
let { createInterface } = await import("node:readline"), rl = createInterface({
|
|
5110
4958
|
input: process.stdin
|
|
5111
4959
|
});
|
|
5112
4960
|
return rl.on('line', (input)=>{
|
|
5113
4961
|
if ('h' === input) {
|
|
5114
|
-
let message = `\n ${
|
|
4962
|
+
let message = `\n ${index_js_default.bold(index_js_default.blue('Shortcuts:'))}\n`;
|
|
5115
4963
|
for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
|
|
5116
|
-
|
|
4964
|
+
logger.log(message);
|
|
5117
4965
|
}
|
|
5118
4966
|
for (let shortcut of shortcuts)if (input === shortcut.key) return void shortcut.action();
|
|
5119
4967
|
}), ()=>{
|
|
@@ -5233,7 +5081,7 @@ class SocketServer {
|
|
|
5233
5081
|
noServer: !0,
|
|
5234
5082
|
path: null == (_this_options_client = this.options.client) ? void 0 : _this_options_client.path
|
|
5235
5083
|
}), this.wsServer.on('error', (err)=>{
|
|
5236
|
-
|
|
5084
|
+
logger.error(err);
|
|
5237
5085
|
}), this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref(), this.wsServer.on('connection', (socket, req)=>{
|
|
5238
5086
|
let queryStr = req.url ? req.url.split('?')[1] : '';
|
|
5239
5087
|
this.onConnect(socket, queryStr ? Object.fromEntries(new URLSearchParams(queryStr)) : {});
|
|
@@ -5350,9 +5198,9 @@ class SocketServer {
|
|
|
5350
5198
|
let pathRegex = /(?:\.\.?[\/\\]|[a-zA-Z]:\\|\/)[^:]*:\d+:\d+/g, urlRegex = /(https?:\/\/(?:[\w-]+\.)+[a-z0-9](?:[\w-.~:/?#[\]@!$&'*+,;=])*)/gi;
|
|
5351
5199
|
return text.split('\n').map((line)=>{
|
|
5352
5200
|
let replacedLine = line.replace(pathRegex, (file)=>{
|
|
5353
|
-
let hasClosingSpan = file.includes('</span>') && !file.includes('<span'), filePath = hasClosingSpan ? file.replace('</span>', '') : file, isAbsolute =
|
|
5354
|
-
let relativePath =
|
|
5355
|
-
return '' === relativePath ? `.${
|
|
5201
|
+
let hasClosingSpan = file.includes('</span>') && !file.includes('<span'), filePath = hasClosingSpan ? file.replace('</span>', '') : file, isAbsolute = external_node_path_default.isAbsolute(filePath), absolutePath = root1 && !isAbsolute ? external_node_path_default.join(root1, filePath) : filePath, relativePath = root1 && isAbsolute ? function(base, filepath) {
|
|
5202
|
+
let relativePath = relative(base, filepath);
|
|
5203
|
+
return '' === relativePath ? `.${sep}` : relativePath.startsWith('.') ? relativePath : `.${sep}${relativePath}`;
|
|
5356
5204
|
}(root1, filePath) : filePath;
|
|
5357
5205
|
return `<a class="file-link" data-file="${absolutePath}">${relativePath}</a>${hasClosingSpan ? '</span>' : ''}`;
|
|
5358
5206
|
});
|
|
@@ -5534,7 +5382,7 @@ function compilationManager_define_property(obj, key, value) {
|
|
|
5534
5382
|
writable: !0
|
|
5535
5383
|
}) : obj[key] = value, obj;
|
|
5536
5384
|
}
|
|
5537
|
-
let compilationManager_require =
|
|
5385
|
+
let compilationManager_require = createRequire(import.meta.url), formatDevConfig = (config, environments)=>{
|
|
5538
5386
|
let writeToDiskValues = Object.values(environments).map((env)=>env.config.dev.writeToDisk);
|
|
5539
5387
|
return 1 === new Set(writeToDiskValues).size ? {
|
|
5540
5388
|
...config,
|
|
@@ -5551,7 +5399,7 @@ class CompilationManager {
|
|
|
5551
5399
|
async init() {
|
|
5552
5400
|
await this.setupCompilationMiddleware(), await this.socketServer.prepare();
|
|
5553
5401
|
let { compiler } = this;
|
|
5554
|
-
this.outputFileSystem = (helpers_isMultiCompiler(compiler) ? compiler.compilers[0].outputFileSystem : compiler.outputFileSystem) ||
|
|
5402
|
+
this.outputFileSystem = (helpers_isMultiCompiler(compiler) ? compiler.compilers[0].outputFileSystem : compiler.outputFileSystem) || external_node_fs_default;
|
|
5555
5403
|
}
|
|
5556
5404
|
async close() {
|
|
5557
5405
|
await this.socketServer.close(), this.middleware && await new Promise((resolve)=>{
|
|
@@ -5597,7 +5445,7 @@ class CompilationManager {
|
|
|
5597
5445
|
wrapper.close = middleware.close, this.middleware = wrapper;
|
|
5598
5446
|
}
|
|
5599
5447
|
constructor({ dev, server, compiler, publicPaths, environments }){
|
|
5600
|
-
compilationManager_define_property(this, "middleware", void 0), compilationManager_define_property(this, "outputFileSystem", void 0), compilationManager_define_property(this, "devConfig", void 0), compilationManager_define_property(this, "serverConfig", void 0), compilationManager_define_property(this, "compiler", void 0), compilationManager_define_property(this, "publicPaths", void 0), compilationManager_define_property(this, "socketServer", void 0), compilationManager_define_property(this, "readFileSync", (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') :
|
|
5448
|
+
compilationManager_define_property(this, "middleware", void 0), compilationManager_define_property(this, "outputFileSystem", void 0), compilationManager_define_property(this, "devConfig", void 0), compilationManager_define_property(this, "serverConfig", void 0), compilationManager_define_property(this, "compiler", void 0), compilationManager_define_property(this, "publicPaths", void 0), compilationManager_define_property(this, "socketServer", void 0), compilationManager_define_property(this, "readFileSync", (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : external_node_fs_default.readFileSync(fileName, 'utf-8')), this.devConfig = formatDevConfig(dev, environments), this.serverConfig = server, this.compiler = compiler, this.publicPaths = publicPaths, this.outputFileSystem = external_node_fs_default, this.socketServer = new SocketServer(dev);
|
|
5601
5449
|
}
|
|
5602
5450
|
}
|
|
5603
5451
|
let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i, shouldCompress = (res)=>{
|
|
@@ -5606,12 +5454,12 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
|
|
|
5606
5454
|
if (contentType && !CONTENT_TYPE_REGEX.test(contentType)) return !1;
|
|
5607
5455
|
let size = res.getHeader('Content-Length');
|
|
5608
5456
|
return void 0 === size || Number(size) > 1024;
|
|
5609
|
-
}, gzipMiddleware = ({ level =
|
|
5457
|
+
}, gzipMiddleware = ({ level = external_node_zlib_default.constants.Z_BEST_SPEED } = {})=>(req, res, next)=>{
|
|
5610
5458
|
let gzip, writeHeadStatus, accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
|
|
5611
5459
|
if ('HEAD' === req.method || !encoding) return void next();
|
|
5612
5460
|
let started = !1, { end, write, on, writeHead } = res, listeners = [], start = ()=>{
|
|
5613
5461
|
if (!started) {
|
|
5614
|
-
if (started = !0, shouldCompress(res)) for (let listener of (res.setHeader('Content-Encoding', 'gzip'), res.removeHeader('Content-Length'), (gzip =
|
|
5462
|
+
if (started = !0, shouldCompress(res)) for (let listener of (res.setHeader('Content-Encoding', 'gzip'), res.removeHeader('Content-Length'), (gzip = external_node_zlib_default.createGzip({
|
|
5615
5463
|
level
|
|
5616
5464
|
})).on('data', (chunk)=>{
|
|
5617
5465
|
!1 === write.call(res, chunk) && gzip.pause();
|
|
@@ -5631,13 +5479,13 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
|
|
|
5631
5479
|
]), res), next();
|
|
5632
5480
|
}, faviconFallbackMiddleware = (req, res, next)=>{
|
|
5633
5481
|
'/favicon.ico' === req.url ? (res.statusCode = 204, res.end()) : next();
|
|
5634
|
-
}, getStatusCodeColor = (status)=>status >= 500 ?
|
|
5482
|
+
}, getStatusCodeColor = (status)=>status >= 500 ? index_js_default.red : status >= 400 ? index_js_default.yellow : status >= 300 ? index_js_default.cyan : status >= 200 ? index_js_default.green : (res)=>res, getRequestLoggerMiddleware = async ()=>{
|
|
5635
5483
|
let { default: onFinished } = await import("../compiled/on-finished/index.js");
|
|
5636
5484
|
return (req, res, next)=>{
|
|
5637
5485
|
let _startAt = process.hrtime();
|
|
5638
5486
|
onFinished(res, ()=>{
|
|
5639
5487
|
let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = getStatusCodeColor(status), endAt = process.hrtime(), totalTime = (endAt[0] - _startAt[0]) * 1e3 + (endAt[1] - _startAt[1]) * 1e-6;
|
|
5640
|
-
|
|
5488
|
+
logger.debug(`${statusColor(status)} ${method} ${index_js_default.gray(url)} ${index_js_default.gray(`${totalTime.toFixed(3)} ms`)}`);
|
|
5641
5489
|
}), next();
|
|
5642
5490
|
};
|
|
5643
5491
|
}, notFoundMiddleware = (_req, res, _next)=>{
|
|
@@ -5662,10 +5510,10 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
|
|
|
5662
5510
|
next(...args);
|
|
5663
5511
|
}));
|
|
5664
5512
|
if (pathname.endsWith('/')) {
|
|
5665
|
-
let newUrl = `${pathname}index.html`, filePath =
|
|
5513
|
+
let newUrl = `${pathname}index.html`, filePath = external_node_path_default.join(distPath, newUrl);
|
|
5666
5514
|
if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) return rewrite(newUrl);
|
|
5667
|
-
} else if (!
|
|
5668
|
-
let newUrl = `${pathname}.html`, filePath =
|
|
5515
|
+
} else if (!external_node_path_default.extname(pathname)) {
|
|
5516
|
+
let newUrl = `${pathname}.html`, filePath = external_node_path_default.join(distPath, newUrl);
|
|
5669
5517
|
if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) return rewrite(newUrl);
|
|
5670
5518
|
}
|
|
5671
5519
|
next();
|
|
@@ -5691,10 +5539,10 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
|
|
|
5691
5539
|
}), res.end(`The server is configured with a base URL of ${base} - did you mean to visit ${redirectPath} instead?`);
|
|
5692
5540
|
}, getHtmlFallbackMiddleware = ({ htmlFallback, distPath, compilationManager })=>async (req, res, next)=>{
|
|
5693
5541
|
if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url || 'index' !== htmlFallback) return next();
|
|
5694
|
-
let filePath =
|
|
5542
|
+
let filePath = external_node_path_default.join(distPath, 'index.html');
|
|
5695
5543
|
if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) {
|
|
5696
5544
|
let newUrl = '/index.html';
|
|
5697
|
-
return 'verbose' ===
|
|
5545
|
+
return 'verbose' === logger.level && logger.debug(`${req.method} ${index_js_default.gray(`${req.url} ${index_js_default.yellow('fallback')} to ${newUrl}`)}`), req.url = newUrl, compilationManager.middleware(req, res, (...args)=>next(...args));
|
|
5698
5546
|
}
|
|
5699
5547
|
next();
|
|
5700
5548
|
}, viewingServedFilesMiddleware = ({ environments })=>async (req, res, next)=>{
|
|
@@ -5754,7 +5602,7 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
|
|
|
5754
5602
|
}
|
|
5755
5603
|
res.end('</body></html>');
|
|
5756
5604
|
} catch (err) {
|
|
5757
|
-
|
|
5605
|
+
logger.error(err), res.writeHead(500), res.end('Failed to list the files');
|
|
5758
5606
|
}
|
|
5759
5607
|
} else next();
|
|
5760
5608
|
}, createProxyMiddleware = async (proxyOptions)=>{
|
|
@@ -5767,7 +5615,7 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
|
|
|
5767
5615
|
context,
|
|
5768
5616
|
changeOrigin: !0,
|
|
5769
5617
|
logLevel: 'warn',
|
|
5770
|
-
logProvider: ()=>
|
|
5618
|
+
logProvider: ()=>logger
|
|
5771
5619
|
};
|
|
5772
5620
|
'string' == typeof options ? opts.target = options : Object.assign(opts, options), ret.push(opts);
|
|
5773
5621
|
}
|
|
@@ -5821,7 +5669,7 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
|
|
|
5821
5669
|
}
|
|
5822
5670
|
if (server.compress && middlewares.push(gzipMiddleware()), 'dev' === context.action && 'rspack' === context.bundlerType && dev.lazyCompilation && compilationManager) {
|
|
5823
5671
|
let { compiler } = compilationManager;
|
|
5824
|
-
'object' == typeof dev.lazyCompilation && 'string' == typeof dev.lazyCompilation.serverUrl && context.devServer && (dev.lazyCompilation.serverUrl = replacePortPlaceholder(dev.lazyCompilation.serverUrl, context.devServer.port)), middlewares.push(
|
|
5672
|
+
'object' == typeof dev.lazyCompilation && 'string' == typeof dev.lazyCompilation.serverUrl && context.devServer && (dev.lazyCompilation.serverUrl = replacePortPlaceholder(dev.lazyCompilation.serverUrl, context.devServer.port)), middlewares.push(rspack.experiments.lazyCompilationMiddleware(helpers_isMultiCompiler(compiler) ? compiler.compilers[0] : compiler));
|
|
5825
5673
|
}
|
|
5826
5674
|
server.base && '/' !== server.base && middlewares.push(getBaseMiddleware({
|
|
5827
5675
|
base: server.base
|
|
@@ -5839,7 +5687,7 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
|
|
|
5839
5687
|
compilationManager,
|
|
5840
5688
|
distPath: context.distPath
|
|
5841
5689
|
})), normalizePublicDirs(null == server ? void 0 : server.publicDir))){
|
|
5842
|
-
let { default: sirv } = await import("../compiled/sirv/index.js"), { name } = publicDir, assetMiddleware = sirv((
|
|
5690
|
+
let { default: sirv } = await import("../compiled/sirv/index.js"), { name } = publicDir, assetMiddleware = sirv(external_node_path_isAbsolute(name) ? name : join(pwd, name), {
|
|
5843
5691
|
etag: !0,
|
|
5844
5692
|
dev: !0
|
|
5845
5693
|
});
|
|
@@ -5861,7 +5709,7 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
|
|
|
5861
5709
|
};
|
|
5862
5710
|
}, getDevMiddlewares = async (options)=>{
|
|
5863
5711
|
let middlewares = [], { compilationManager } = options;
|
|
5864
|
-
'verbose' ===
|
|
5712
|
+
'verbose' === logger.level && middlewares.push(await getRequestLoggerMiddleware());
|
|
5865
5713
|
let { before, after } = applySetupMiddlewares(options.dev, options.devServerAPI);
|
|
5866
5714
|
middlewares.push(...before);
|
|
5867
5715
|
let { onUpgrade } = await applyDefaultMiddlewares({
|
|
@@ -5921,11 +5769,11 @@ class BasicRunner {
|
|
|
5921
5769
|
}
|
|
5922
5770
|
getFile(modulePath, currentDirectory) {
|
|
5923
5771
|
if (Array.isArray(modulePath)) return {
|
|
5924
|
-
path:
|
|
5772
|
+
path: external_node_path_default.join(currentDirectory, '.array-require.js'),
|
|
5925
5773
|
content: `module.exports = (${modulePath.map((arg)=>`require(${JSON.stringify(`./${arg}`)})`).join(', ')});`,
|
|
5926
5774
|
subPath: ''
|
|
5927
5775
|
};
|
|
5928
|
-
let joinedPath = isRelativePath(modulePath) ?
|
|
5776
|
+
let joinedPath = isRelativePath(modulePath) ? external_node_path_default.join(currentDirectory, modulePath) : modulePath;
|
|
5929
5777
|
return this._options.isBundleOutput(joinedPath) ? {
|
|
5930
5778
|
path: joinedPath,
|
|
5931
5779
|
content: this._options.readFileSync(joinedPath),
|
|
@@ -5936,14 +5784,14 @@ class BasicRunner {
|
|
|
5936
5784
|
postExecute(_m, _file) {}
|
|
5937
5785
|
createRunner() {
|
|
5938
5786
|
this.requirers.set('entry', (_currentDirectory, _modulePath, _context = {})=>{
|
|
5939
|
-
throw Error(`${
|
|
5787
|
+
throw Error(`${index_js_default.dim('[rsbuild:runner]')} Not implemented`);
|
|
5940
5788
|
});
|
|
5941
5789
|
}
|
|
5942
5790
|
constructor(_options){
|
|
5943
5791
|
basic_define_property(this, "_options", void 0), basic_define_property(this, "globalContext", void 0), basic_define_property(this, "baseModuleScope", void 0), basic_define_property(this, "requirers", void 0), this._options = _options, this.globalContext = null, this.baseModuleScope = null, this.requirers = new Map();
|
|
5944
5792
|
}
|
|
5945
5793
|
}
|
|
5946
|
-
let cjs_require =
|
|
5794
|
+
let cjs_require = createRequire(import.meta.url), cjs_define = (...args)=>{
|
|
5947
5795
|
args.pop()();
|
|
5948
5796
|
};
|
|
5949
5797
|
class CommonJsRunner extends BasicRunner {
|
|
@@ -5972,10 +5820,10 @@ class CommonJsRunner extends BasicRunner {
|
|
|
5972
5820
|
createModuleScope(requireFn, m, file) {
|
|
5973
5821
|
return {
|
|
5974
5822
|
...this.baseModuleScope,
|
|
5975
|
-
require: requireFn.bind(null,
|
|
5823
|
+
require: requireFn.bind(null, external_node_path_default.dirname(file.path)),
|
|
5976
5824
|
module: m,
|
|
5977
5825
|
exports: m.exports,
|
|
5978
|
-
__dirname:
|
|
5826
|
+
__dirname: external_node_path_default.dirname(file.path),
|
|
5979
5827
|
__filename: file.path,
|
|
5980
5828
|
define: cjs_define
|
|
5981
5829
|
};
|
|
@@ -6016,7 +5864,7 @@ class CommonJsRunner extends BasicRunner {
|
|
|
6016
5864
|
}
|
|
6017
5865
|
}
|
|
6018
5866
|
var type_EsmMode = ((EsmMode = {})[EsmMode.Unknown = 0] = "Unknown", EsmMode[EsmMode.Evaluated = 1] = "Evaluated", EsmMode[EsmMode.Unlinked = 2] = "Unlinked", EsmMode);
|
|
6019
|
-
let esm_require =
|
|
5867
|
+
let esm_require = createRequire(import.meta.url);
|
|
6020
5868
|
class EsmRunner extends CommonJsRunner {
|
|
6021
5869
|
createRunner() {
|
|
6022
5870
|
var _this__options_compilerOptions_experiments;
|
|
@@ -6036,24 +5884,24 @@ class EsmRunner extends CommonJsRunner {
|
|
|
6036
5884
|
createEsmRequirer() {
|
|
6037
5885
|
let esmCache = new Map(), esmIdentifier = this._options.name, vm = esm_require('node:vm');
|
|
6038
5886
|
return (currentDirectory, modulePath, context = {})=>{
|
|
6039
|
-
if (!vm.SourceTextModule) throw Error(`${
|
|
5887
|
+
if (!vm.SourceTextModule) throw Error(`${index_js_default.dim('[rsbuild:runner]')} Running ESM bundle needs add Node.js option ${index_js_default.yellow('--experimental-vm-modules')}.`);
|
|
6040
5888
|
let _require = this.getRequire(), file = context.file || this.getFile(modulePath, currentDirectory);
|
|
6041
5889
|
if (!file) return this.requirers.get('miss')(currentDirectory, modulePath);
|
|
6042
5890
|
let esm = esmCache.get(file.path);
|
|
6043
5891
|
return (esm || (esm = new vm.SourceTextModule(file.content, {
|
|
6044
5892
|
identifier: `${esmIdentifier}-${file.path}`,
|
|
6045
|
-
url: `${
|
|
5893
|
+
url: `${pathToFileURL(file.path).href}?${esmIdentifier}`,
|
|
6046
5894
|
initializeImportMeta: (meta, _)=>{
|
|
6047
|
-
meta.url =
|
|
5895
|
+
meta.url = pathToFileURL(file.path).href;
|
|
6048
5896
|
},
|
|
6049
5897
|
importModuleDynamically: async (specifier, module)=>{
|
|
6050
|
-
let result = await _require(
|
|
5898
|
+
let result = await _require(external_node_path_default.dirname(file.path), specifier, {
|
|
6051
5899
|
esmMode: type_EsmMode.Evaluated
|
|
6052
5900
|
});
|
|
6053
5901
|
return await asModule(result, module.context);
|
|
6054
5902
|
}
|
|
6055
5903
|
}), esmCache.set(file.path, esm)), context.esmMode === type_EsmMode.Unlinked) ? esm : (async ()=>{
|
|
6056
|
-
if (await esm.link(async (specifier, referencingModule)=>await asModule(await _require(
|
|
5904
|
+
if (await esm.link(async (specifier, referencingModule)=>await asModule(await _require(external_node_path_default.dirname(referencingModule.identifier ? referencingModule.identifier.slice(esmIdentifier.length + 1) : fileURLToPath(referencingModule.url)), specifier, {
|
|
6057
5905
|
esmMode: type_EsmMode.Unlinked
|
|
6058
5906
|
}), referencingModule.context, !0)), esm.instantiate && esm.instantiate(), await esm.evaluate(), context.esmMode === type_EsmMode.Evaluated) return esm;
|
|
6059
5907
|
let ns = esm.namespace;
|
|
@@ -6071,7 +5919,7 @@ class BasicRunnerFactory {
|
|
|
6071
5919
|
name: this.name,
|
|
6072
5920
|
...options
|
|
6073
5921
|
}, { compilerOptions } = options;
|
|
6074
|
-
if ('web' === compilerOptions.target || 'webworker' === compilerOptions.target) throw Error(`${
|
|
5922
|
+
if ('web' === compilerOptions.target || 'webworker' === compilerOptions.target) throw Error(`${index_js_default.dim('[rsbuild:runner]')} Not support run ${index_js_default.yellow(compilerOptions.target)} resource in Rsbuild server`);
|
|
6075
5923
|
return new EsmRunner(runnerOptions);
|
|
6076
5924
|
}
|
|
6077
5925
|
constructor(name){
|
|
@@ -6091,7 +5939,7 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>new BasicRunne
|
|
|
6091
5939
|
entrypoints: !0,
|
|
6092
5940
|
outputPath: !0
|
|
6093
5941
|
});
|
|
6094
|
-
if (!(null == entrypoints ? void 0 : entrypoints[entryName])) throw Error(`${
|
|
5942
|
+
if (!(null == entrypoints ? void 0 : entrypoints[entryName])) throw Error(`${index_js_default.dim('[rsbuild:loadBundle]')} Can't find entry: ${index_js_default.yellow(entryName)}`);
|
|
6095
5943
|
let { chunks: entryChunks = [] } = entrypoints[entryName], files = entryChunks.reduce((prev, entryChunkName)=>{
|
|
6096
5944
|
let chunk = null == chunks ? void 0 : chunks.find((chunk)=>{
|
|
6097
5945
|
var _chunk_names;
|
|
@@ -6099,9 +5947,9 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>new BasicRunne
|
|
|
6099
5947
|
});
|
|
6100
5948
|
return (null == chunk ? void 0 : chunk.files) ? prev.concat(chunk.files.filter((file)=>!file.endsWith('.css'))) : prev;
|
|
6101
5949
|
}, []);
|
|
6102
|
-
if (0 === files.length) throw Error(`${
|
|
6103
|
-
if (files.length > 1) throw Error(`${
|
|
6104
|
-
let allChunkFiles = (null == chunks ? void 0 : chunks.flatMap((c)=>c.files).map((file)=>
|
|
5950
|
+
if (0 === files.length) throw Error(`${index_js_default.dim('[rsbuild:loadBundle]')} Failed to get bundle by entryName: ${index_js_default.yellow(entryName)}`);
|
|
5951
|
+
if (files.length > 1) throw Error(`${index_js_default.dim('[rsbuild:loadBundle]')} Only support load single entry chunk, but got ${index_js_default.yellow(files.length)}: ${files.join(',')}`);
|
|
5952
|
+
let allChunkFiles = (null == chunks ? void 0 : chunks.flatMap((c)=>c.files).map((file)=>join(outputPath, file))) || [];
|
|
6105
5953
|
return await runner_run({
|
|
6106
5954
|
bundlePath: files[0],
|
|
6107
5955
|
dist: outputPath,
|
|
@@ -6111,8 +5959,8 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>new BasicRunne
|
|
|
6111
5959
|
});
|
|
6112
5960
|
}, getTransformedHtml = async (entryName, utils)=>{
|
|
6113
5961
|
let { htmlPaths, distPath } = utils.environment, htmlPath = htmlPaths[entryName];
|
|
6114
|
-
if (!htmlPath) throw Error(`${
|
|
6115
|
-
let fileName =
|
|
5962
|
+
if (!htmlPath) throw Error(`${index_js_default.dim('[rsbuild:getTransformedHtml]')} Failed to get HTML file by entryName: ${index_js_default.yellow(entryName)}`);
|
|
5963
|
+
let fileName = join(distPath, htmlPath);
|
|
6116
5964
|
return utils.readFileSync(fileName);
|
|
6117
5965
|
}, createCacheableFunction = (getter)=>{
|
|
6118
5966
|
let cache = new WeakMap();
|
|
@@ -6140,7 +5988,7 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>new BasicRunne
|
|
|
6140
5988
|
}, shutdownRefCount = 0, setupGracefulShutdown = ()=>{
|
|
6141
5989
|
shutdownRefCount++;
|
|
6142
5990
|
let onSigterm = ()=>{
|
|
6143
|
-
handleTermination(
|
|
5991
|
+
handleTermination(constants.signals.SIGTERM + 128);
|
|
6144
5992
|
};
|
|
6145
5993
|
process.once('SIGTERM', onSigterm);
|
|
6146
5994
|
let isCI = 'true' === process.env.CI, onStdinEnd = ()=>{
|
|
@@ -6167,7 +6015,7 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>new BasicRunne
|
|
|
6167
6015
|
}, devServer_formatDevConfig = (config, port)=>('<port>' === config.client.port && (config.client.port = String(port)), config);
|
|
6168
6016
|
async function devServer_createDevServer(options, createCompiler, config, { compiler: customCompiler, getPortSilently, runCompile = !0 } = {}) {
|
|
6169
6017
|
let lastStats, fileWatcher, devMiddlewares;
|
|
6170
|
-
|
|
6018
|
+
logger.debug('create dev server');
|
|
6171
6019
|
let { port, host, https, portTip } = await getServerConfig({
|
|
6172
6020
|
config
|
|
6173
6021
|
}), { middlewareMode } = config.server, { context } = options, devConfig = devServer_formatDevConfig(config.dev, port), routes = getRoutes(context), root = context.rootPath;
|
|
@@ -6184,7 +6032,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
6184
6032
|
});
|
|
6185
6033
|
}) : Promise.resolve(), startCompile = async ()=>{
|
|
6186
6034
|
let compiler = customCompiler || await createCompiler();
|
|
6187
|
-
if (!compiler) throw Error(`${
|
|
6035
|
+
if (!compiler) throw Error(`${index_js_default.dim('[rsbuild:server]')} Failed to get compiler instance.`);
|
|
6188
6036
|
let publicPaths = helpers_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
|
|
6189
6037
|
getPublicPathFromCompiler(compiler)
|
|
6190
6038
|
], compilationManager = new CompilationManager({
|
|
@@ -6236,24 +6084,24 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
6236
6084
|
});
|
|
6237
6085
|
context.hooks.onCloseDevServer.tap(cleanup);
|
|
6238
6086
|
}
|
|
6239
|
-
!getPortSilently && portTip &&
|
|
6087
|
+
!getPortSilently && portTip && logger.info(portTip);
|
|
6240
6088
|
}, cacheableLoadBundle = createCacheableFunction(loadBundle), cacheableTransformedHtml = createCacheableFunction((_stats, entryName, utils)=>getTransformedHtml(entryName, utils)), environmentAPI = Object.fromEntries(Object.entries(context.environments).map(([name, environment])=>[
|
|
6241
6089
|
name,
|
|
6242
6090
|
{
|
|
6243
6091
|
getStats: async ()=>{
|
|
6244
|
-
if (!compilationManager) throw Error(`${
|
|
6092
|
+
if (!compilationManager) throw Error(`${index_js_default.dim('[rsbuild:server]')} Can not call ${index_js_default.yellow('getStats')} when ${index_js_default.yellow('runCompile')} is false`);
|
|
6245
6093
|
return await waitFirstCompileDone, lastStats[environment.index];
|
|
6246
6094
|
},
|
|
6247
6095
|
context: environment,
|
|
6248
6096
|
loadBundle: async (entryName)=>{
|
|
6249
|
-
if (!compilationManager) throw Error(`${
|
|
6097
|
+
if (!compilationManager) throw Error(`${index_js_default.dim('[rsbuild:server]')} Can not call ${index_js_default.yellow('loadBundle')} when ${index_js_default.yellow('runCompile')} is false`);
|
|
6250
6098
|
return await waitFirstCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
|
|
6251
6099
|
readFileSync: compilationManager.readFileSync,
|
|
6252
6100
|
environment
|
|
6253
6101
|
});
|
|
6254
6102
|
},
|
|
6255
6103
|
getTransformedHtml: async (entryName)=>{
|
|
6256
|
-
if (!compilationManager) throw Error(`${
|
|
6104
|
+
if (!compilationManager) throw Error(`${index_js_default.dim('[rsbuild:server]')} Can not call ${index_js_default.yellow('getTransformedHtml')} when ${index_js_default.yellow('runCompile')} is false`);
|
|
6257
6105
|
return await waitFirstCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
|
|
6258
6106
|
readFileSync: compilationManager.readFileSync,
|
|
6259
6107
|
environment
|
|
@@ -6273,15 +6121,15 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
6273
6121
|
data
|
|
6274
6122
|
}),
|
|
6275
6123
|
listen: async ()=>{
|
|
6276
|
-
if (!httpServer) throw Error(`${
|
|
6124
|
+
if (!httpServer) throw Error(`${index_js_default.dim('[rsbuild:server]')} Can not listen dev server as ${index_js_default.yellow('server.middlewareMode')} is enabled.`);
|
|
6277
6125
|
let serverTerminator = getServerTerminator(httpServer);
|
|
6278
|
-
return
|
|
6126
|
+
return logger.debug('listen dev server'), context.hooks.onCloseDevServer.tap(serverTerminator), new Promise((resolve)=>{
|
|
6279
6127
|
httpServer.listen({
|
|
6280
6128
|
host,
|
|
6281
6129
|
port
|
|
6282
6130
|
}, async (err)=>{
|
|
6283
6131
|
if (err) throw err;
|
|
6284
|
-
middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), devMiddlewares && httpServer.on('upgrade', devMiddlewares.onUpgrade),
|
|
6132
|
+
middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), devMiddlewares && httpServer.on('upgrade', devMiddlewares.onUpgrade), logger.debug('listen dev server done'), await devServerAPI.afterListen(), onBeforeRestartServer(devServerAPI.close), resolve({
|
|
6285
6133
|
port,
|
|
6286
6134
|
urls: urls.map((item)=>item.url),
|
|
6287
6135
|
server: {
|
|
@@ -6324,10 +6172,10 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
6324
6172
|
server: config.server,
|
|
6325
6173
|
postCallbacks
|
|
6326
6174
|
})).middlewares))Array.isArray(item) ? middlewares.use(...item) : middlewares.use(item);
|
|
6327
|
-
return
|
|
6175
|
+
return logger.debug('create dev server done'), devServerAPI;
|
|
6328
6176
|
}
|
|
6329
6177
|
function isLikelyFile(filePath) {
|
|
6330
|
-
return (filePath.split(
|
|
6178
|
+
return (filePath.split(sep).pop() || '').includes('.');
|
|
6331
6179
|
}
|
|
6332
6180
|
function formatFileList(paths, rootPath) {
|
|
6333
6181
|
let files = paths.filter(isLikelyFile);
|
|
@@ -6335,41 +6183,41 @@ function formatFileList(paths, rootPath) {
|
|
|
6335
6183
|
paths[0]
|
|
6336
6184
|
]);
|
|
6337
6185
|
let fileInfo = files.slice(0, 1).map((file)=>(function(originalFilePath, root) {
|
|
6338
|
-
let prefix = root.endsWith(
|
|
6186
|
+
let prefix = root.endsWith(sep) ? root : root + sep, filePath = originalFilePath;
|
|
6339
6187
|
filePath.startsWith(prefix) && (filePath = filePath.slice(prefix.length));
|
|
6340
|
-
let parts = filePath.split(
|
|
6341
|
-
return parts.length > 3 ? parts.slice(-3).join(
|
|
6188
|
+
let parts = filePath.split(sep).filter(Boolean);
|
|
6189
|
+
return parts.length > 3 ? parts.slice(-3).join(sep) : parts.join(sep);
|
|
6342
6190
|
})(file, rootPath)).join(', ');
|
|
6343
6191
|
return files.length > 1 ? `${fileInfo} and ${files.length - 1} more` : fileInfo;
|
|
6344
6192
|
}
|
|
6345
6193
|
async function createCompiler_createCompiler(options) {
|
|
6346
|
-
|
|
6194
|
+
logger.debug('create compiler');
|
|
6347
6195
|
let { context } = options, { rspackConfigs } = await initConfigs(options);
|
|
6348
6196
|
if (await context.hooks.onBeforeCreateCompiler.callBatch({
|
|
6349
6197
|
bundlerConfigs: rspackConfigs,
|
|
6350
6198
|
environments: context.environments
|
|
6351
|
-
}), !await isSatisfyRspackVersion(
|
|
6352
|
-
let isMultiCompiler = rspackConfigs.length > 1, compiler = isMultiCompiler ?
|
|
6353
|
-
isVersionLogged || (
|
|
6199
|
+
}), !await isSatisfyRspackVersion(rspack.rspackVersion)) throw Error(`${index_js_default.dim('[rsbuild]')} The current Rspack version does not meet the requirements, the minimum supported version of Rspack is ${index_js_default.green(rspackMinVersion)}`);
|
|
6200
|
+
let isMultiCompiler = rspackConfigs.length > 1, compiler = isMultiCompiler ? rspack(rspackConfigs) : rspack(rspackConfigs[0]), isVersionLogged = !1, isCompiling = !1, logRspackVersion = ()=>{
|
|
6201
|
+
isVersionLogged || (logger.debug(`use Rspack v${rspack.rspackVersion}`), isVersionLogged = !0);
|
|
6354
6202
|
};
|
|
6355
6203
|
compiler.hooks.watchRun.tap('rsbuild:compiling', (compiler)=>{
|
|
6356
6204
|
logRspackVersion(), isCompiling || function(compiler, context) {
|
|
6357
6205
|
let changedFiles = compiler.modifiedFiles ? Array.from(compiler.modifiedFiles) : null;
|
|
6358
6206
|
if (null == changedFiles ? void 0 : changedFiles.length) {
|
|
6359
6207
|
let fileInfo = formatFileList(changedFiles, context.rootPath);
|
|
6360
|
-
|
|
6208
|
+
logger.start(`building ${index_js_default.dim(fileInfo)}`);
|
|
6361
6209
|
return;
|
|
6362
6210
|
}
|
|
6363
6211
|
let removedFiles = compiler.removedFiles ? Array.from(compiler.removedFiles) : null;
|
|
6364
6212
|
if (null == removedFiles ? void 0 : removedFiles.length) {
|
|
6365
6213
|
let fileInfo = formatFileList(removedFiles, context.rootPath);
|
|
6366
|
-
|
|
6214
|
+
logger.start(`building ${index_js_default.dim(`removed ${fileInfo}`)}`);
|
|
6367
6215
|
return;
|
|
6368
6216
|
}
|
|
6369
|
-
|
|
6217
|
+
logger.start('build started...');
|
|
6370
6218
|
}(compiler, context), isCompiling = !0;
|
|
6371
6219
|
}), 'build' === context.action && compiler.hooks.run.tap('rsbuild:run', ()=>{
|
|
6372
|
-
|
|
6220
|
+
logger.info('build started...'), logRspackVersion();
|
|
6373
6221
|
});
|
|
6374
6222
|
let done = (stats)=>{
|
|
6375
6223
|
let statsOptions = getStatsOptions(compiler), statsJson = stats.toJson({
|
|
@@ -6380,8 +6228,8 @@ async function createCompiler_createCompiler(options) {
|
|
|
6380
6228
|
...statsOptions
|
|
6381
6229
|
}), printTime = (c, index)=>{
|
|
6382
6230
|
if (c.time) {
|
|
6383
|
-
let time = prettyTime(c.time / 1000), { name } = rspackConfigs[index], suffix = name && isMultiCompiler ?
|
|
6384
|
-
|
|
6231
|
+
let time = prettyTime(c.time / 1000), { name } = rspackConfigs[index], suffix = name && isMultiCompiler ? index_js_default.gray(` (${name})`) : '';
|
|
6232
|
+
logger.ready(`built in ${time}${suffix}`);
|
|
6385
6233
|
}
|
|
6386
6234
|
}, hasErrors = stats.hasErrors();
|
|
6387
6235
|
if (!hasErrors) {
|
|
@@ -6391,7 +6239,7 @@ async function createCompiler_createCompiler(options) {
|
|
|
6391
6239
|
}) : printTime(statsJson, 0);
|
|
6392
6240
|
}
|
|
6393
6241
|
let { message, level } = formatStats(statsJson, hasErrors);
|
|
6394
|
-
'error' === level &&
|
|
6242
|
+
'error' === level && logger.error(message), 'warning' === level && logger.warn(message), isCompiling = !1;
|
|
6395
6243
|
};
|
|
6396
6244
|
return compiler.hooks.done.tap('rsbuild:done', (stats)=>{
|
|
6397
6245
|
done(stats);
|
|
@@ -6399,11 +6247,11 @@ async function createCompiler_createCompiler(options) {
|
|
|
6399
6247
|
context,
|
|
6400
6248
|
compiler,
|
|
6401
6249
|
bundlerConfigs: rspackConfigs,
|
|
6402
|
-
MultiStatsCtor:
|
|
6250
|
+
MultiStatsCtor: rspack.MultiStats
|
|
6403
6251
|
}), await context.hooks.onAfterCreateCompiler.callBatch({
|
|
6404
6252
|
compiler,
|
|
6405
6253
|
environments: context.environments
|
|
6406
|
-
}),
|
|
6254
|
+
}), logger.debug('create compiler done'), {
|
|
6407
6255
|
compiler,
|
|
6408
6256
|
rspackConfigs
|
|
6409
6257
|
};
|
|
@@ -6420,9 +6268,9 @@ let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOption
|
|
|
6420
6268
|
bundlerConfigs,
|
|
6421
6269
|
compiler,
|
|
6422
6270
|
isWatch: !!watch,
|
|
6423
|
-
MultiStatsCtor:
|
|
6271
|
+
MultiStatsCtor: rspack.MultiStats
|
|
6424
6272
|
}), watch) return compiler.watch({}, (err)=>{
|
|
6425
|
-
err &&
|
|
6273
|
+
err && logger.error(err);
|
|
6426
6274
|
}), {
|
|
6427
6275
|
close: ()=>new Promise((resolve)=>{
|
|
6428
6276
|
compiler.close(()=>{
|
|
@@ -6433,7 +6281,7 @@ let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOption
|
|
|
6433
6281
|
let { stats } = await new Promise((resolve, reject)=>{
|
|
6434
6282
|
compiler.run((err, stats)=>{
|
|
6435
6283
|
compiler.close((closeErr)=>{
|
|
6436
|
-
closeErr &&
|
|
6284
|
+
closeErr && logger.error('Failed to close compiler: ', closeErr), err ? reject(err) : (null == stats ? void 0 : stats.hasErrors()) ? reject(Error(RSPACK_BUILD_ERROR)) : resolve({
|
|
6437
6285
|
stats
|
|
6438
6286
|
});
|
|
6439
6287
|
});
|
|
@@ -6517,7 +6365,7 @@ class RsbuildProdServer {
|
|
|
6517
6365
|
}
|
|
6518
6366
|
async applyDefaultMiddlewares() {
|
|
6519
6367
|
let { headers, proxy, historyApiFallback, compress, base, cors } = this.options.serverConfig;
|
|
6520
|
-
if ('verbose' ===
|
|
6368
|
+
if ('verbose' === logger.level && this.middlewares.use(await getRequestLoggerMiddleware()), cors) {
|
|
6521
6369
|
let { default: corsMiddleware } = await import("../compiled/cors/index.js");
|
|
6522
6370
|
this.middlewares.use(corsMiddleware('boolean' == typeof cors ? {} : cors));
|
|
6523
6371
|
}
|
|
@@ -6622,7 +6470,7 @@ async function startProdServer(context, config, { getPortSilently } = {}) {
|
|
|
6622
6470
|
customShortcuts: shortcutsOptions.custom
|
|
6623
6471
|
});
|
|
6624
6472
|
}
|
|
6625
|
-
!getPortSilently && portTip &&
|
|
6473
|
+
!getPortSilently && portTip && logger.info(portTip), resolve({
|
|
6626
6474
|
port,
|
|
6627
6475
|
urls: urls.map((item)=>item.url),
|
|
6628
6476
|
server: {
|
|
@@ -6718,7 +6566,7 @@ async function applyDefaultPlugins(pluginManager, context) {
|
|
|
6718
6566
|
let { config } = environment;
|
|
6719
6567
|
if (!(null == (_config_moduleFederation = config.moduleFederation) ? void 0 : _config_moduleFederation.options) || 'web' !== target) return;
|
|
6720
6568
|
let { options } = config.moduleFederation;
|
|
6721
|
-
chain.plugin(CHAIN_ID.PLUGIN.MODULE_FEDERATION).use(
|
|
6569
|
+
chain.plugin(CHAIN_ID.PLUGIN.MODULE_FEDERATION).use(rspack.container.ModuleFederationPlugin, [
|
|
6722
6570
|
options
|
|
6723
6571
|
]), options.name && (options.exposes && chain.plugin('mf-patch-split-chunks').use(PatchSplitChunksPlugin, [
|
|
6724
6572
|
options.name
|
|
@@ -6727,6 +6575,7 @@ async function applyDefaultPlugins(pluginManager, context) {
|
|
|
6727
6575
|
}
|
|
6728
6576
|
},
|
|
6729
6577
|
pluginRspackProfile(),
|
|
6578
|
+
pluginLazyCompilation(),
|
|
6730
6579
|
pluginSri(),
|
|
6731
6580
|
pluginNonce()
|
|
6732
6581
|
]);
|
|
@@ -6736,22 +6585,24 @@ async function createRsbuild(options = {}) {
|
|
|
6736
6585
|
cwd: options.cwd,
|
|
6737
6586
|
...'boolean' == typeof options.loadEnv ? {} : options.loadEnv
|
|
6738
6587
|
}) : null, config = isFunction(options.rsbuildConfig) ? await options.rsbuildConfig() : options.rsbuildConfig || {};
|
|
6739
|
-
|
|
6740
|
-
|
|
6741
|
-
|
|
6742
|
-
|
|
6743
|
-
|
|
6744
|
-
|
|
6745
|
-
|
|
6746
|
-
|
|
6747
|
-
|
|
6588
|
+
config.logLevel && (logger.level = config.logLevel), function(config, envs) {
|
|
6589
|
+
var _config_performance;
|
|
6590
|
+
if (null !== envs && (config.source ||= {}, config.source.define = {
|
|
6591
|
+
...envs.publicVars,
|
|
6592
|
+
...config.source.define
|
|
6593
|
+
}, 0 !== envs.filePaths.length && (config.dev ||= {}, config.dev.watchFiles = [
|
|
6594
|
+
...config.dev.watchFiles ? castArray(config.dev.watchFiles) : [],
|
|
6595
|
+
{
|
|
6596
|
+
paths: envs.filePaths,
|
|
6597
|
+
type: 'reload-server'
|
|
6598
|
+
}
|
|
6599
|
+
], null == (_config_performance = config.performance) ? void 0 : _config_performance.buildCache))) {
|
|
6600
|
+
let { buildCache } = config.performance;
|
|
6601
|
+
!0 === buildCache ? config.performance.buildCache = {
|
|
6602
|
+
buildDependencies: envs.filePaths
|
|
6603
|
+
} : (buildCache.buildDependencies ||= [], buildCache.buildDependencies.push(...envs.filePaths));
|
|
6748
6604
|
}
|
|
6749
|
-
|
|
6750
|
-
let { buildCache } = config1.performance;
|
|
6751
|
-
!0 === buildCache ? config1.performance.buildCache = {
|
|
6752
|
-
buildDependencies: envs1.filePaths
|
|
6753
|
-
} : (buildCache.buildDependencies ||= [], buildCache.buildDependencies.push(...envs1.filePaths));
|
|
6754
|
-
}
|
|
6605
|
+
}(config, envs);
|
|
6755
6606
|
let resolvedOptions = {
|
|
6756
6607
|
cwd: process.cwd(),
|
|
6757
6608
|
callerName: 'rsbuild',
|
|
@@ -6766,13 +6617,13 @@ async function createRsbuild(options = {}) {
|
|
|
6766
6617
|
let { before, environment = RSBUILD_ALL_ENVIRONMENT_SYMBOL } = options || {};
|
|
6767
6618
|
for (let newPlugin of newPlugins)if (newPlugin) {
|
|
6768
6619
|
let type = typeof newPlugin;
|
|
6769
|
-
if ('object' !== type || null === newPlugin) throw Error(`${
|
|
6620
|
+
if ('object' !== type || null === newPlugin) throw Error(`${index_js_default.dim('[rsbuild:plugin]')} Expect Rsbuild plugin instance to be an object, but got ${index_js_default.yellow(type)}.`);
|
|
6770
6621
|
if (!isFunction(newPlugin.setup)) {
|
|
6771
6622
|
if (isFunction(newPlugin.apply)) {
|
|
6772
6623
|
let { name = 'SomeWebpackPlugin' } = newPlugin.constructor || {};
|
|
6773
6624
|
throw Error([
|
|
6774
|
-
`${
|
|
6775
|
-
|
|
6625
|
+
`${index_js_default.yellow(name)} looks like a webpack or Rspack plugin, please use ${index_js_default.yellow('`tools.rspack`')} to register it:`,
|
|
6626
|
+
index_js_default.green(`
|
|
6776
6627
|
// rsbuild.config.ts
|
|
6777
6628
|
export default {
|
|
6778
6629
|
tools: {
|
|
@@ -6784,11 +6635,11 @@ async function createRsbuild(options = {}) {
|
|
|
6784
6635
|
`)
|
|
6785
6636
|
].join('\n'));
|
|
6786
6637
|
}
|
|
6787
|
-
throw Error(`${
|
|
6638
|
+
throw Error(`${index_js_default.dim('[rsbuild:plugin]')} Expect the setup function of Rsbuild plugin to be a function, but got ${index_js_default.yellow(type)}.`);
|
|
6788
6639
|
}
|
|
6789
6640
|
if (before) {
|
|
6790
6641
|
let index = plugins.findIndex((item)=>item.instance.name === before);
|
|
6791
|
-
-1 === index ? (
|
|
6642
|
+
-1 === index ? (logger.warn(`Plugin "${before}" does not exist.`), plugins.push({
|
|
6792
6643
|
environment,
|
|
6793
6644
|
instance: newPlugin
|
|
6794
6645
|
})) : plugins.splice(index, 0, {
|
|
@@ -6823,19 +6674,19 @@ async function createRsbuild(options = {}) {
|
|
|
6823
6674
|
get (target, prop) {
|
|
6824
6675
|
if (exposedKeys.includes(prop)) return target[prop];
|
|
6825
6676
|
},
|
|
6826
|
-
set: (_, prop)=>(
|
|
6677
|
+
set: (_, prop)=>(logger.error(`Context is readonly, you can not assign to the "context.${prop}" prop.`), !0)
|
|
6827
6678
|
});
|
|
6828
6679
|
}(context);
|
|
6829
6680
|
function getNormalizedConfig(options) {
|
|
6830
6681
|
if (context.normalizedConfig) {
|
|
6831
6682
|
if (null == options ? void 0 : options.environment) {
|
|
6832
6683
|
let config = context.normalizedConfig.environments[options.environment];
|
|
6833
|
-
if (!config) throw Error(`${
|
|
6684
|
+
if (!config) throw Error(`${index_js_default.dim('[rsbuild]')} Cannot find normalized config by environment: ${options.environment}.`);
|
|
6834
6685
|
return config;
|
|
6835
6686
|
}
|
|
6836
6687
|
return context.normalizedConfig;
|
|
6837
6688
|
}
|
|
6838
|
-
throw Error(`${
|
|
6689
|
+
throw Error(`${index_js_default.dim('[rsbuild]')} Cannot access normalized config until ${index_js_default.yellow('modifyRsbuildConfig')} is called.`);
|
|
6839
6690
|
}
|
|
6840
6691
|
let getRsbuildConfig = (type = 'current')=>{
|
|
6841
6692
|
switch(type){
|
|
@@ -6846,7 +6697,7 @@ async function createRsbuild(options = {}) {
|
|
|
6846
6697
|
case 'normalized':
|
|
6847
6698
|
return getNormalizedConfig();
|
|
6848
6699
|
}
|
|
6849
|
-
throw Error(`${
|
|
6700
|
+
throw Error(`${index_js_default.dim('[rsbuild]')} ${index_js_default.yellow('getRsbuildConfig')} get an invalid type param.`);
|
|
6850
6701
|
}, exposed = [], expose = (id, api)=>{
|
|
6851
6702
|
exposed.push({
|
|
6852
6703
|
id,
|
|
@@ -6904,7 +6755,7 @@ async function createRsbuild(options = {}) {
|
|
|
6904
6755
|
if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environment.name)) return;
|
|
6905
6756
|
let rule = chain.module.rule(id);
|
|
6906
6757
|
descriptor.test && rule.test(descriptor.test), descriptor.resourceQuery && rule.resourceQuery(descriptor.resourceQuery), descriptor.layer && rule.layer(descriptor.layer), descriptor.issuerLayer && rule.issuerLayer(descriptor.issuerLayer), descriptor.issuer && rule.issuer(descriptor.issuer), descriptor.with && rule.with(descriptor.with), descriptor.mimetype && rule.mimetype(descriptor.mimetype), descriptor.enforce && rule.enforce(descriptor.enforce);
|
|
6907
|
-
let
|
|
6758
|
+
let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs');
|
|
6908
6759
|
rule.use(id).loader(loaderPath).options({
|
|
6909
6760
|
id,
|
|
6910
6761
|
getEnvironment: ()=>environment
|
|
@@ -6929,11 +6780,11 @@ async function createRsbuild(options = {}) {
|
|
|
6929
6780
|
hooks.onExit.callBatch({
|
|
6930
6781
|
exitCode
|
|
6931
6782
|
});
|
|
6932
|
-
}, exitHook_callbacks.add(onExit), isRegistered || (isRegistered = !0,
|
|
6933
|
-
exit(
|
|
6934
|
-
}),
|
|
6935
|
-
exit(
|
|
6936
|
-
}),
|
|
6783
|
+
}, exitHook_callbacks.add(onExit), isRegistered || (isRegistered = !0, external_node_process_default.on('SIGINT', ()=>{
|
|
6784
|
+
exit(constants.signals.SIGINT + 128, 'SIGINT');
|
|
6785
|
+
}), external_node_process_default.once('SIGTERM', ()=>{
|
|
6786
|
+
exit(constants.signals.SIGTERM + 128, 'SIGTERM');
|
|
6787
|
+
}), external_node_process_default.once('exit', (exitCode)=>{
|
|
6937
6788
|
exit(exitCode, 'exit');
|
|
6938
6789
|
})), onExitListened = !0;
|
|
6939
6790
|
}
|
|
@@ -7005,7 +6856,7 @@ async function createRsbuild(options = {}) {
|
|
|
7005
6856
|
});
|
|
7006
6857
|
context.getPluginAPI = getPluginAPI;
|
|
7007
6858
|
let globalPluginAPI = getPluginAPI();
|
|
7008
|
-
|
|
6859
|
+
logger.debug('add default plugins'), await applyDefaultPlugins(pluginManager, context), logger.debug('add default plugins done');
|
|
7009
6860
|
let provider = config.provider || rspackProvider, providerInstance = await provider({
|
|
7010
6861
|
context,
|
|
7011
6862
|
pluginManager,
|
|
@@ -7029,11 +6880,11 @@ async function createRsbuild(options = {}) {
|
|
|
7029
6880
|
pluginManager
|
|
7030
6881
|
}), { distPath } = context, { checkDistDir = !0 } = options;
|
|
7031
6882
|
if (checkDistDir) {
|
|
7032
|
-
if (!
|
|
6883
|
+
if (!existsSync(distPath)) throw Error(`${index_js_default.dim('[rsbuild:preview]')} The output directory ${index_js_default.yellow(distPath)} does not exist, please build the project before previewing.`);
|
|
7033
6884
|
if (function(path) {
|
|
7034
|
-
let files =
|
|
6885
|
+
let files = external_node_fs_default.readdirSync(path);
|
|
7035
6886
|
return 0 === files.length || 1 === files.length && '.git' === files[0];
|
|
7036
|
-
}(distPath)) throw Error(`${
|
|
6887
|
+
}(distPath)) throw Error(`${index_js_default.dim('[rsbuild:preview]')} The output directory ${index_js_default.yellow(distPath)} is empty, please build the project before previewing.`);
|
|
7037
6888
|
}
|
|
7038
6889
|
return startProdServer(context, config, options);
|
|
7039
6890
|
},
|
|
@@ -7072,7 +6923,7 @@ async function createRsbuild(options = {}) {
|
|
|
7072
6923
|
let getFlattenedPlugins = async (pluginOptions)=>{
|
|
7073
6924
|
let plugins = pluginOptions;
|
|
7074
6925
|
do plugins = (await Promise.all(plugins)).flat(Number.POSITIVE_INFINITY);
|
|
7075
|
-
while (plugins.some((v)=>
|
|
6926
|
+
while (plugins.some((v)=>isPromise(v)));
|
|
7076
6927
|
return plugins;
|
|
7077
6928
|
};
|
|
7078
6929
|
if (config.plugins) {
|
|
@@ -7248,7 +7099,7 @@ class GlobalCommand extends Command {
|
|
|
7248
7099
|
}
|
|
7249
7100
|
}
|
|
7250
7101
|
var __assign = Object.assign;
|
|
7251
|
-
class CAC extends
|
|
7102
|
+
class CAC extends EventEmitter {
|
|
7252
7103
|
constructor(name = ""){
|
|
7253
7104
|
super(), this.name = name, this.commands = [], this.rawArgs = [], this.args = [], this.options = {}, this.globalCommand = new GlobalCommand(this), this.globalCommand.usage("<command> [options]");
|
|
7254
7105
|
}
|
|
@@ -7411,11 +7262,11 @@ async function runCLI() {
|
|
|
7411
7262
|
}
|
|
7412
7263
|
process.title = 'rsbuild-node';
|
|
7413
7264
|
let { npm_execpath } = process.env;
|
|
7414
|
-
(!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) &&
|
|
7265
|
+
(!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.0-beta.4\n`);
|
|
7415
7266
|
try {
|
|
7416
7267
|
!function() {
|
|
7417
7268
|
let cli = cac_dist('rsbuild');
|
|
7418
|
-
cli.help(), cli.version("1.4.0-beta.
|
|
7269
|
+
cli.help(), cli.version("1.4.0-beta.4"), applyCommonOptions(cli);
|
|
7419
7270
|
let devCommand = cli.command('', 'starting the dev server').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');
|
|
7420
7271
|
applyServerOptions(devCommand), applyServerOptions(previewCommand), devCommand.action(async (options)=>{
|
|
7421
7272
|
try {
|
|
@@ -7424,7 +7275,7 @@ async function runCLI() {
|
|
|
7424
7275
|
});
|
|
7425
7276
|
await (null == rsbuild ? void 0 : rsbuild.startDevServer());
|
|
7426
7277
|
} catch (err) {
|
|
7427
|
-
|
|
7278
|
+
logger.error('Failed to start dev server.'), logger.error(err), process.exit(1);
|
|
7428
7279
|
}
|
|
7429
7280
|
}), buildCommand.option('-w, --watch', 'turn on watch mode, watch for changes and rebuild').action(async (options)=>{
|
|
7430
7281
|
try {
|
|
@@ -7436,7 +7287,7 @@ async function runCLI() {
|
|
|
7436
7287
|
}));
|
|
7437
7288
|
buildInstance && (options.watch ? onBeforeRestartServer(buildInstance.close) : await buildInstance.close());
|
|
7438
7289
|
} catch (err) {
|
|
7439
|
-
err instanceof Error && err.message === RSPACK_BUILD_ERROR ||
|
|
7290
|
+
err instanceof Error && err.message === RSPACK_BUILD_ERROR || logger.error('Failed to build.'), logger.error(err), process.exit(1);
|
|
7440
7291
|
}
|
|
7441
7292
|
}), previewCommand.action(async (options)=>{
|
|
7442
7293
|
try {
|
|
@@ -7445,7 +7296,7 @@ async function runCLI() {
|
|
|
7445
7296
|
});
|
|
7446
7297
|
await (null == rsbuild ? void 0 : rsbuild.preview());
|
|
7447
7298
|
} catch (err) {
|
|
7448
|
-
|
|
7299
|
+
logger.error('Failed to start preview server.'), logger.error(err), process.exit(1);
|
|
7449
7300
|
}
|
|
7450
7301
|
}), inspectCommand.option('--output <output>', 'specify inspect content output path').option('--verbose', 'show full function definitions in output').action(async (options)=>{
|
|
7451
7302
|
try {
|
|
@@ -7458,14 +7309,13 @@ async function runCLI() {
|
|
|
7458
7309
|
writeToDisk: !0
|
|
7459
7310
|
}));
|
|
7460
7311
|
} catch (err) {
|
|
7461
|
-
|
|
7312
|
+
logger.error('Failed to inspect config.'), logger.error(err), process.exit(1);
|
|
7462
7313
|
}
|
|
7463
7314
|
}), cli.parse();
|
|
7464
7315
|
}();
|
|
7465
7316
|
} catch (err) {
|
|
7466
|
-
|
|
7317
|
+
logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
|
|
7467
7318
|
}
|
|
7468
7319
|
}
|
|
7469
|
-
let src_version = "1.4.0-beta.
|
|
7470
|
-
|
|
7471
|
-
export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, mergeRsbuildConfig, runCLI, src_version as version, __webpack_exports__logger as logger, __webpack_exports__rspack as rspack };
|
|
7320
|
+
let src_version = "1.4.0-beta.4";
|
|
7321
|
+
export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger, mergeRsbuildConfig, rspack, runCLI, src_version as version };
|