@unpackjs/core 3.7.8 → 3.8.1
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 +20 -20
- package/compiled/less-loader/index.js +8 -8
- package/compiled/postcss-loader/index.js +11 -11
- package/compiled/sass-loader/index.js +8 -8
- package/dist/index.js +870 -562
- package/dist/rslib-runtime.js +15 -0
- package/dist/transformLoader.js +11 -0
- package/dist/{typedCssModulesLoader.mjs → typedCssModulesLoader.js} +5 -13
- package/dist-types/bundler-config/cache.d.ts.map +1 -1
- package/dist-types/bundler-config/html.d.ts +6 -0
- package/dist-types/bundler-config/html.d.ts.map +1 -0
- package/dist-types/bundler-config/index.d.ts.map +1 -1
- package/dist-types/bundler-config/loaders/transformLoader.d.ts +5 -0
- package/dist-types/bundler-config/loaders/transformLoader.d.ts.map +1 -0
- package/dist-types/bundler-config/plugins/progress/helpers.d.ts.map +1 -1
- package/dist-types/bundler-config/plugins/progress/index.d.ts +2 -2
- package/dist-types/bundler-config/plugins/progress/index.d.ts.map +1 -1
- package/dist-types/bundler-config/plugins/registerHooks.d.ts +6 -0
- package/dist-types/bundler-config/plugins/registerHooks.d.ts.map +1 -0
- package/dist-types/constants.d.ts +3 -0
- package/dist-types/constants.d.ts.map +1 -1
- package/dist-types/createUnpack.d.ts +4 -1
- package/dist-types/createUnpack.d.ts.map +1 -1
- package/dist-types/global.d.ts +4 -2
- package/dist-types/global.d.ts.map +1 -1
- package/dist-types/index.d.ts +1 -0
- package/dist-types/index.d.ts.map +1 -1
- package/dist-types/plugin.d.ts +4 -1
- package/dist-types/plugin.d.ts.map +1 -1
- package/dist-types/plugins/browserLogs.d.ts +3 -0
- package/dist-types/plugins/browserLogs.d.ts.map +1 -0
- package/dist-types/plugins/fileSize.d.ts +3 -0
- package/dist-types/plugins/fileSize.d.ts.map +1 -0
- package/dist-types/plugins/prebundle.d.ts +3 -0
- package/dist-types/plugins/prebundle.d.ts.map +1 -0
- package/dist-types/run/dev.d.ts +4 -1
- package/dist-types/run/dev.d.ts.map +1 -1
- package/dist-types/types/config.d.ts +24 -26
- package/dist-types/types/config.d.ts.map +1 -1
- package/dist-types/types/plugin.d.ts +23 -2
- package/dist-types/types/plugin.d.ts.map +1 -1
- package/dist-types/utils.d.ts +13 -1
- package/dist-types/utils.d.ts.map +1 -1
- package/package.json +9 -7
- package/dist/transformDeepImportLoader.mjs +0 -82
- package/dist-types/bundler-config/loaders/transformDeepImportLoader.d.ts +0 -5
- package/dist-types/bundler-config/loaders/transformDeepImportLoader.d.ts.map +0 -1
- package/dist-types/prebundleDeps.d.ts +0 -5
- package/dist-types/prebundleDeps.d.ts.map +0 -1
- package/dist-types/reporter.d.ts +0 -8
- package/dist-types/reporter.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -5,37 +5,31 @@ import { fileURLToPath as __rspack_fileURLToPath, pathToFileURL } from "node:url
|
|
|
5
5
|
import node_path, { dirname as __rspack_dirname, join, sep } from "node:path";
|
|
6
6
|
import * as __rspack_external__compiled_launch_editor_index_js_29002383 from "../compiled/launch-editor/index.js";
|
|
7
7
|
import * as __rspack_external__compiled_webpack_merge_index_js_efd91626 from "../compiled/webpack-merge/index.js";
|
|
8
|
+
import { __webpack_require__ } from "./rslib-runtime.js";
|
|
8
9
|
import { rspack } from "@rspack/core";
|
|
9
10
|
import node_readline from "node:readline";
|
|
10
11
|
import node_fs from "node:fs";
|
|
11
12
|
import node_net from "node:net";
|
|
12
13
|
import node_os, { platform } from "node:os";
|
|
13
14
|
import portfinder from "portfinder";
|
|
15
|
+
import { format, promisify } from "node:util";
|
|
16
|
+
import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
|
|
17
|
+
import { parse } from "stacktrace-parser";
|
|
18
|
+
import node_zlib from "node:zlib";
|
|
19
|
+
import { glob, globSync } from "tinyglobby";
|
|
14
20
|
import { expand } from "dotenv-expand";
|
|
15
21
|
import node_assert from "node:assert";
|
|
16
|
-
import { glob, globSync } from "tinyglobby";
|
|
17
|
-
import { promisify } from "node:util";
|
|
18
|
-
import node_zlib from "node:zlib";
|
|
19
22
|
import { RspackDevServer } from "@rspack/dev-server";
|
|
20
23
|
import { exec, spawn } from "node:child_process";
|
|
21
|
-
import node_http from "node:http";
|
|
22
24
|
import chokidar from "chokidar";
|
|
23
|
-
|
|
25
|
+
__webpack_require__.add({
|
|
24
26
|
"compiled/launch-editor" (module) {
|
|
25
27
|
module.exports = __rspack_external__compiled_launch_editor_index_js_29002383;
|
|
26
28
|
},
|
|
27
29
|
"compiled/webpack-merge" (module) {
|
|
28
30
|
module.exports = __rspack_external__compiled_webpack_merge_index_js_efd91626;
|
|
29
31
|
}
|
|
30
|
-
}
|
|
31
|
-
function __webpack_require__(moduleId) {
|
|
32
|
-
var cachedModule = __webpack_module_cache__[moduleId];
|
|
33
|
-
if (void 0 !== cachedModule) return cachedModule.exports;
|
|
34
|
-
var module = __webpack_module_cache__[moduleId] = {
|
|
35
|
-
exports: {}
|
|
36
|
-
};
|
|
37
|
-
return __webpack_modules__[moduleId](module, module.exports, __webpack_require__), module.exports;
|
|
38
|
-
}
|
|
32
|
+
});
|
|
39
33
|
let isCI = !!process.env.CI, isTTY = !!process.stdout?.isTTY, noColor = !!process.env.NO_COLOR, forceColor = !!process.env.FORCE_COLOR, disableColor = !1;
|
|
40
34
|
disableColor = !!noColor || !forceColor && (isCI || !isTTY);
|
|
41
35
|
let ANSI_SGR_RE = /\x1b\[[0-9;]*m/g, ANSI_OPEN_RE = /\x1b\[([0-9;]+)m/g, COLOR_HEX = {
|
|
@@ -106,10 +100,12 @@ let restartCleaners = [], addRestartCleaner = (...cleaners)=>{
|
|
|
106
100
|
restartCleaners.push(...cleaners);
|
|
107
101
|
}, cleanUpBeforeRestart = async ()=>{
|
|
108
102
|
await Promise.all(restartCleaners.map((cleaner)=>cleaner())), restartCleaners.length = 0;
|
|
109
|
-
},
|
|
110
|
-
|
|
103
|
+
}, currentUnpackConfig = {}, getCurrentUnpackConfig = ()=>currentUnpackConfig, setCurrentUnpackConfig = (config)=>{
|
|
104
|
+
currentUnpackConfig = config;
|
|
105
|
+
}, unpackStartTime = 0, getUnpackStartTime = ()=>unpackStartTime, setUnpackStartTime = (time)=>{
|
|
106
|
+
unpackStartTime = time;
|
|
111
107
|
};
|
|
112
|
-
var logger_LogColor = ((LogColor = {}).error = "red", LogColor.warn = "yellow", LogColor.info = "cyan", LogColor.ready = "green", LogColor.event = "magenta", LogColor.wait = "blue", LogColor);
|
|
108
|
+
var LogColor, logger_LogColor = ((LogColor = {}).error = "red", LogColor.warn = "yellow", LogColor.info = "cyan", LogColor.ready = "green", LogColor.event = "magenta", LogColor.wait = "blue", LogColor);
|
|
113
109
|
let CSS_MODULES_LOCAL_IDENT_NAME = '[path][name]__[local]--[hash:5]', CSS_MODULES_REGEX = /\.module\.\w+$/i, DEV_DEFAULT_FILENAME = {
|
|
114
110
|
js: 'js/[name].js',
|
|
115
111
|
jsAsync: 'js/async/[name].js',
|
|
@@ -121,22 +117,17 @@ let CSS_MODULES_LOCAL_IDENT_NAME = '[path][name]__[local]--[hash:5]', CSS_MODULE
|
|
|
121
117
|
css: 'css/[name].[contenthash:8].css',
|
|
122
118
|
cssAsync: 'css/async/[name].[contenthash:8].css'
|
|
123
119
|
}, EXPORT_LOCALS_CONVENTION = 'camel-case-only', NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, DEFAULT_DEV_HOST = '0.0.0.0', TEMPLATE_CONTENT = ({ title = '', headTag = '', mountId = '' })=>`<!DOCTYPE html>
|
|
124
|
-
<html
|
|
125
|
-
|
|
126
|
-
<
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
</
|
|
134
|
-
|
|
135
|
-
<body>
|
|
136
|
-
<div id="${mountId}"></div>
|
|
137
|
-
</body>
|
|
138
|
-
|
|
139
|
-
</html>`;
|
|
120
|
+
<html>
|
|
121
|
+
<head>
|
|
122
|
+
<meta charset="UTF-8">
|
|
123
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
124
|
+
<title>${title}</title>
|
|
125
|
+
${headTag}
|
|
126
|
+
</head>
|
|
127
|
+
<body>
|
|
128
|
+
<div id="${mountId}"></div>
|
|
129
|
+
</body>
|
|
130
|
+
</html>`, JS_REGEX = /\.[jt]s$/, JSX_REGEX = /\.[jt]sx$/, SCRIPT_REGEX = /\.[jt]sx?$/;
|
|
140
131
|
var utils_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
141
132
|
let { merge: mergeConfig } = __webpack_require__("compiled/webpack-merge"), { default: launchEditor } = __webpack_require__("compiled/launch-editor"), getNodeEnv = ()=>process.env.NODE_ENV, setNodeEnv = (env)=>{
|
|
142
133
|
process.env.NODE_ENV = env;
|
|
@@ -169,7 +160,11 @@ let { merge: mergeConfig } = __webpack_require__("compiled/webpack-merge"), { de
|
|
|
169
160
|
}, (_, port)=>{
|
|
170
161
|
resolve(port);
|
|
171
162
|
});
|
|
172
|
-
}),
|
|
163
|
+
}), normalizePublicPath = (base)=>{
|
|
164
|
+
if (!base) return '/';
|
|
165
|
+
let normalized = base;
|
|
166
|
+
return normalized.startsWith('/') || (normalized = `/${normalized}`), normalized.endsWith('/') || (normalized = `${normalized}/`), normalized;
|
|
167
|
+
}, getCompiledPkgPath = (packageName)=>node_path.join(utils_dirname, '../compiled', packageName), getUserDepPath = (root, deps)=>{
|
|
173
168
|
for (let dep of Array.isArray(deps) ? deps : [
|
|
174
169
|
deps
|
|
175
170
|
]){
|
|
@@ -200,14 +195,15 @@ let debounce = (fn, delay)=>{
|
|
|
200
195
|
'127.0.0.1',
|
|
201
196
|
'::1',
|
|
202
197
|
'0000:0000:0000:0000:0000:0000:0000:0001'
|
|
203
|
-
].includes(host), concatUrl = ({ host, port, protocol })=>`${protocol}://${host}:${port}
|
|
198
|
+
].includes(host), concatUrl = ({ host, port, protocol, base })=>`${protocol}://${host}:${port}${normalizePublicPath(base)}`, LOCAL_LABEL = 'Local: ', NETWORK_LABEL = 'Network: ', getAddressUrls = ({ protocol = 'http', port, host, base })=>{
|
|
204
199
|
if (host && host !== DEFAULT_DEV_HOST) return [
|
|
205
200
|
{
|
|
206
201
|
label: isLoopbackHost(host) ? LOCAL_LABEL : NETWORK_LABEL,
|
|
207
202
|
url: concatUrl({
|
|
208
203
|
port,
|
|
209
204
|
host: node_net.isIPv6(host) ? '::' === host ? '[::1]' : `[${host}]` : host,
|
|
210
|
-
protocol
|
|
205
|
+
protocol,
|
|
206
|
+
base
|
|
211
207
|
})
|
|
212
208
|
}
|
|
213
209
|
];
|
|
@@ -219,7 +215,8 @@ let debounce = (fn, delay)=>{
|
|
|
219
215
|
url: concatUrl({
|
|
220
216
|
host: 'localhost',
|
|
221
217
|
port,
|
|
222
|
-
protocol
|
|
218
|
+
protocol,
|
|
219
|
+
base
|
|
223
220
|
})
|
|
224
221
|
}), hasLocalUrl = !0;
|
|
225
222
|
} else addressUrls.push({
|
|
@@ -227,7 +224,8 @@ let debounce = (fn, delay)=>{
|
|
|
227
224
|
url: concatUrl({
|
|
228
225
|
host: detail.address,
|
|
229
226
|
port,
|
|
230
|
-
protocol
|
|
227
|
+
protocol,
|
|
228
|
+
base
|
|
231
229
|
})
|
|
232
230
|
});
|
|
233
231
|
return addressUrls;
|
|
@@ -314,7 +312,33 @@ function pLimit(concurrency = Math.max(1, node_os.cpus().length - 1)) {
|
|
|
314
312
|
let pathToExportIdentifier = (path)=>{
|
|
315
313
|
let name = path.replace(/[^a-zA-Z0-9_$]+([a-zA-Z0-9_$])/g, (_, char)=>char.toUpperCase()).replace(/[^a-zA-Z0-9_$]/g, '');
|
|
316
314
|
return (!(name = name.charAt(0).toUpperCase() + name.slice(1)) || /^[^a-zA-Z_$]/.test(name)) && (name = `_${name}`), name;
|
|
317
|
-
}
|
|
315
|
+
};
|
|
316
|
+
function printServerUrls({ port, host, base }) {
|
|
317
|
+
let addressUrls = getAddressUrls({
|
|
318
|
+
port,
|
|
319
|
+
base
|
|
320
|
+
}), colorPrefix = colors.brand('➜');
|
|
321
|
+
addressUrls.forEach((addr, index)=>{
|
|
322
|
+
let url;
|
|
323
|
+
if (!host && 0 !== index) {
|
|
324
|
+
1 === index && console.log(` ${colors.dim(colorPrefix)} ${colors.bold(colors.dim('Network:'))} ${colors.dim('use')} ${colors.bold('--host')} ${colors.dim('to expose')}`);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
console.log(` ${colorPrefix} ${colors.bold(addr.label)}${(url = addr.url, colors.cyan(url.replace(/:(\d+)\//, (_, port)=>`:${colors.bold(port)}/`)))}`);
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
function getHtmlTemplateOrContent(rawTemplate, root) {
|
|
331
|
+
let template, templateContent;
|
|
332
|
+
if ('string' == typeof rawTemplate) {
|
|
333
|
+
let absPath = node_path.isAbsolute(rawTemplate) ? rawTemplate : node_path.resolve(root, rawTemplate);
|
|
334
|
+
node_fs.existsSync(absPath) ? template = rawTemplate : templateContent = rawTemplate;
|
|
335
|
+
} else templateContent = 'function' == typeof rawTemplate ? rawTemplate : TEMPLATE_CONTENT;
|
|
336
|
+
return {
|
|
337
|
+
template,
|
|
338
|
+
templateContent
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
let injectToHead = (html, script)=>html.replace(/<head(\s*[^>]*)>/i, (match)=>`${match}${script}`), logger_prefixes = {
|
|
318
342
|
wait: '○',
|
|
319
343
|
error: '⨯',
|
|
320
344
|
warn: '⚠',
|
|
@@ -507,13 +531,44 @@ let removeDir = (dir)=>{
|
|
|
507
531
|
recursive: !0,
|
|
508
532
|
force: !0
|
|
509
533
|
});
|
|
510
|
-
},
|
|
511
|
-
|
|
534
|
+
}, BROWSER_LOGS_ENDPOINT = '/__browser_logs__', browserLogs_SCRIPT_REGEX = /\.(js|jsx|mjs|cjs|ts|tsx|mts|cts|vue|svelte)$/, gzip = promisify(node_zlib.gzip), numberFormatter = new Intl.NumberFormat('en', {
|
|
535
|
+
maximumFractionDigits: 2,
|
|
536
|
+
minimumFractionDigits: 2
|
|
537
|
+
}), displaySize = (bytes)=>`${numberFormatter.format(bytes / 1000)} kB`;
|
|
538
|
+
async function getCompressedSize(content) {
|
|
539
|
+
return (await gzip(content)).length;
|
|
540
|
+
}
|
|
541
|
+
let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i, SPECIAL_NO_ENTRY_DEPS = [
|
|
542
|
+
'@iconify-icons/material-symbols'
|
|
543
|
+
], getExternalLibraryName = (pkgName)=>{
|
|
544
|
+
let externalAlias = {
|
|
545
|
+
react: 'React',
|
|
546
|
+
'react-dom': 'ReactDOM',
|
|
547
|
+
'react-router-dom': 'ReactRouterDOM'
|
|
548
|
+
};
|
|
549
|
+
return externalAlias[pkgName] ? externalAlias[pkgName] : pkgName.replace(/^@/, '').split(/[/\-.]/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase() + part.slice(1)).join('');
|
|
550
|
+
}, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`, DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
|
|
551
|
+
function getNormalizedPluginsByHook(hook) {
|
|
512
552
|
let pluginMap = new Map();
|
|
513
|
-
return plugins?.forEach((plugin)=>{
|
|
514
|
-
|
|
553
|
+
return getCurrentUnpackConfig().plugins?.forEach((plugin)=>{
|
|
554
|
+
((plugin, hook)=>{
|
|
555
|
+
if (!plugin[hook]) return !1;
|
|
556
|
+
let apply = plugin.apply;
|
|
557
|
+
if (!apply) return !0;
|
|
558
|
+
let env = {
|
|
559
|
+
mode: getNodeEnv(),
|
|
560
|
+
command: utils_isDevServer() ? 'dev' : 'build'
|
|
561
|
+
};
|
|
562
|
+
return 'string' == typeof apply ? apply === env.command : !!apply(getCurrentUnpackConfig(), env);
|
|
563
|
+
})(plugin, hook) && pluginMap.set(plugin.name, plugin);
|
|
515
564
|
}), Array.from(pluginMap.values());
|
|
516
565
|
}
|
|
566
|
+
async function applyPluginsByHook(hook, runner) {
|
|
567
|
+
for (let plugin of getNormalizedPluginsByHook(hook)){
|
|
568
|
+
let impl = plugin[hook];
|
|
569
|
+
await runner(impl);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
517
572
|
async function applyBuildAnalyzeConfig({ config }) {
|
|
518
573
|
let { RsdoctorRspackPlugin } = await import("@rsdoctor/rspack-plugin");
|
|
519
574
|
return config.plugins?.push(new RsdoctorRspackPlugin()), config;
|
|
@@ -542,7 +597,7 @@ async function getBuildDependencies(root) {
|
|
|
542
597
|
]), buildDependencies;
|
|
543
598
|
}
|
|
544
599
|
async function applyCacheConfig({ config, unpackConfig, envFilePaths }) {
|
|
545
|
-
let cacheConfig = isPlainObject(unpackConfig.
|
|
600
|
+
let cacheConfig = isPlainObject(unpackConfig.performance.cache) ? unpackConfig.performance.cache : {}, buildDependencies = await getBuildDependencies(unpackConfig.root);
|
|
546
601
|
buildDependencies.userBuildDependencies = cacheConfig.buildDependencies || [], buildDependencies.envFilePaths = envFilePaths;
|
|
547
602
|
let cacheDirectory = node_path.resolve(unpackConfig.root, cacheConfig.cacheDirectory || `${unpackConfig._context.cachePath}/cache`, utils_isDevServer() ? 'dev' : 'build');
|
|
548
603
|
return mergeConfig(config, {
|
|
@@ -656,20 +711,40 @@ let getOutputFilename = ({ type, hash, async })=>{
|
|
|
656
711
|
return async ? 'js' === type ? FILENAME.jsAsync : FILENAME.cssAsync : FILENAME[type];
|
|
657
712
|
};
|
|
658
713
|
var css_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
659
|
-
function
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
714
|
+
async function applyHtmlConfig({ config, unpackConfig }) {
|
|
715
|
+
if (!unpackConfig.mpa) {
|
|
716
|
+
let htmlConfig = unpackConfig.html || {}, { template, templateContent } = getHtmlTemplateOrContent(htmlConfig.template, unpackConfig.root), templateParameters = {
|
|
717
|
+
mountId: htmlConfig.mountId,
|
|
718
|
+
title: isFunction(htmlConfig.title) ? htmlConfig.title({
|
|
719
|
+
entryName: 'index'
|
|
720
|
+
}) : htmlConfig.title || '',
|
|
721
|
+
headTag: htmlConfig.headTag || '',
|
|
722
|
+
...htmlConfig.templateParameters
|
|
723
|
+
};
|
|
724
|
+
config.plugins.push(new rspack.HtmlRspackPlugin({
|
|
725
|
+
template,
|
|
726
|
+
templateContent,
|
|
727
|
+
templateParameters,
|
|
728
|
+
minify: !1,
|
|
729
|
+
chunks: [
|
|
730
|
+
'main'
|
|
731
|
+
]
|
|
732
|
+
}));
|
|
733
|
+
}
|
|
734
|
+
return config;
|
|
666
735
|
}
|
|
667
|
-
let { RawSource, SourceMapSource } = rspack.sources, isJsFile = /\.[cm]?js(\?.*)?$/i, jsMinify_PLUGIN_NAME = 'JsMinifyPlugin';
|
|
736
|
+
let { RawSource: RawSource, SourceMapSource: SourceMapSource } = rspack.sources, isJsFile = /\.[cm]?js(\?.*)?$/i, jsMinify_PLUGIN_NAME = 'JsMinifyPlugin';
|
|
668
737
|
class JsMinifyPlugin {
|
|
738
|
+
minifyOptions;
|
|
739
|
+
customMinify;
|
|
740
|
+
constructor(options = {}){
|
|
741
|
+
let { implementation, ...minifyOptions } = options;
|
|
742
|
+
this.customMinify = implementation?.minify, this.minifyOptions = minifyOptions;
|
|
743
|
+
}
|
|
669
744
|
apply(compiler) {
|
|
670
745
|
let meta = JSON.stringify({
|
|
671
746
|
name: jsMinify_PLUGIN_NAME,
|
|
672
|
-
version: "3.
|
|
747
|
+
version: "3.8.1",
|
|
673
748
|
options: this.minifyOptions
|
|
674
749
|
});
|
|
675
750
|
compiler.hooks.compilation.tap(jsMinify_PLUGIN_NAME, (compilation)=>{
|
|
@@ -703,21 +778,23 @@ class JsMinifyPlugin {
|
|
|
703
778
|
}
|
|
704
779
|
}));
|
|
705
780
|
}
|
|
706
|
-
constructor(options = {}){
|
|
707
|
-
_define_property(this, "minifyOptions", void 0), _define_property(this, "customMinify", void 0);
|
|
708
|
-
let { implementation, ...minifyOptions } = options;
|
|
709
|
-
this.customMinify = implementation?.minify, this.minifyOptions = minifyOptions;
|
|
710
|
-
}
|
|
711
|
-
}
|
|
712
|
-
function loadingAnimation_define_property(obj, key, value) {
|
|
713
|
-
return key in obj ? Object.defineProperty(obj, key, {
|
|
714
|
-
value: value,
|
|
715
|
-
enumerable: !0,
|
|
716
|
-
configurable: !0,
|
|
717
|
-
writable: !0
|
|
718
|
-
}) : obj[key] = value, obj;
|
|
719
781
|
}
|
|
720
782
|
class LoadingAnimation {
|
|
783
|
+
chars = [
|
|
784
|
+
'⠋',
|
|
785
|
+
'⠙',
|
|
786
|
+
'⠹',
|
|
787
|
+
'⠸',
|
|
788
|
+
'⠼',
|
|
789
|
+
'⠴',
|
|
790
|
+
'⠦',
|
|
791
|
+
'⠧',
|
|
792
|
+
'⠇',
|
|
793
|
+
'⠏'
|
|
794
|
+
];
|
|
795
|
+
currentIndex = 0;
|
|
796
|
+
lastUpdateTime = 0;
|
|
797
|
+
interval = 100;
|
|
721
798
|
getCurrentChar() {
|
|
722
799
|
let now = Date.now();
|
|
723
800
|
return now - this.lastUpdateTime >= this.interval && (this.currentIndex = (this.currentIndex + 1) % this.chars.length, this.lastUpdateTime = now), this.chars[this.currentIndex];
|
|
@@ -725,110 +802,16 @@ class LoadingAnimation {
|
|
|
725
802
|
reset() {
|
|
726
803
|
this.currentIndex = 0, this.lastUpdateTime = 0;
|
|
727
804
|
}
|
|
728
|
-
constructor(){
|
|
729
|
-
loadingAnimation_define_property(this, "chars", [
|
|
730
|
-
'⠋',
|
|
731
|
-
'⠙',
|
|
732
|
-
'⠹',
|
|
733
|
-
'⠸',
|
|
734
|
-
'⠼',
|
|
735
|
-
'⠴',
|
|
736
|
-
'⠦',
|
|
737
|
-
'⠧',
|
|
738
|
-
'⠇',
|
|
739
|
-
'⠏'
|
|
740
|
-
]), loadingAnimation_define_property(this, "currentIndex", 0), loadingAnimation_define_property(this, "lastUpdateTime", 0), loadingAnimation_define_property(this, "interval", 100);
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
function progressBar_define_property(obj, key, value) {
|
|
744
|
-
return key in obj ? Object.defineProperty(obj, key, {
|
|
745
|
-
value: value,
|
|
746
|
-
enumerable: !0,
|
|
747
|
-
configurable: !0,
|
|
748
|
-
writable: !0
|
|
749
|
-
}) : obj[key] = value, obj;
|
|
750
805
|
}
|
|
751
806
|
class ProgressBar {
|
|
807
|
+
prefix = 'transforming';
|
|
808
|
+
loadingAnimation = new LoadingAnimation();
|
|
752
809
|
update({ current: originalCurrent, message = '' }) {
|
|
753
810
|
let { columns: terminalWidth } = process.stdout, current = originalCurrent;
|
|
754
811
|
originalCurrent >= 0.98 && (current = 1);
|
|
755
812
|
let loadingChar = this.loadingAnimation.getCurrentChar(), messageWidth = terminalWidth - this.prefix.length - (1 === current ? 10 : 9);
|
|
756
813
|
logUpdate(`${loadingChar} ${this.prefix} (${Math.floor(100 * current)}%) ${colors.dim(message.slice(0, messageWidth).padEnd(messageWidth, ' '))}`), 1 === current && clearLine();
|
|
757
814
|
}
|
|
758
|
-
constructor(){
|
|
759
|
-
progressBar_define_property(this, "prefix", 'transforming'), progressBar_define_property(this, "loadingAnimation", new LoadingAnimation());
|
|
760
|
-
}
|
|
761
|
-
}
|
|
762
|
-
let gzip = promisify(node_zlib.gzip), numberFormatter = new Intl.NumberFormat('en', {
|
|
763
|
-
maximumFractionDigits: 2,
|
|
764
|
-
minimumFractionDigits: 2
|
|
765
|
-
}), displaySize = (bytes)=>`${numberFormatter.format(bytes / 1000)} kB`;
|
|
766
|
-
async function getCompressedSize(content) {
|
|
767
|
-
return (await gzip(content)).length;
|
|
768
|
-
}
|
|
769
|
-
let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i;
|
|
770
|
-
async function printFileSize({ root, stats }) {
|
|
771
|
-
let chunkGroups = [
|
|
772
|
-
{
|
|
773
|
-
type: 'HTML',
|
|
774
|
-
color: 'green',
|
|
775
|
-
chunks: []
|
|
776
|
-
},
|
|
777
|
-
{
|
|
778
|
-
type: 'Assets',
|
|
779
|
-
color: 'yellow',
|
|
780
|
-
chunks: []
|
|
781
|
-
},
|
|
782
|
-
{
|
|
783
|
-
type: 'CSS',
|
|
784
|
-
color: 'magenta',
|
|
785
|
-
chunks: []
|
|
786
|
-
},
|
|
787
|
-
{
|
|
788
|
-
type: 'JS',
|
|
789
|
-
color: 'cyan',
|
|
790
|
-
chunks: []
|
|
791
|
-
}
|
|
792
|
-
], chunkGroupMap = chunkGroups.reduce((acc, cur)=>(acc[cur.type] = cur, acc), {}), distPath = stats.compilation.outputOptions.path, distFolder = node_path.relative(root, distPath), assets = Object.entries(stats.compilation.assets), longest = 0, totalSize = 0, totalCompressedSize = 0;
|
|
793
|
-
logUpdate('computing gzip size...'), await Promise.all(assets.map(async ([assetName, value])=>{
|
|
794
|
-
let content, compressedSize, filePath = assetName.split('?')[0];
|
|
795
|
-
try {
|
|
796
|
-
content = value.source();
|
|
797
|
-
} catch {
|
|
798
|
-
content = node_fs.readFileSync(node_path.join(distPath, filePath));
|
|
799
|
-
}
|
|
800
|
-
let size = Buffer.byteLength(content);
|
|
801
|
-
compressedSize = COMPRESSIBLE_REGEX.test(filePath) ? await getCompressedSize(content) : size, totalSize += size, totalCompressedSize += compressedSize;
|
|
802
|
-
let chunk = {
|
|
803
|
-
name: node_path.basename(filePath),
|
|
804
|
-
path: `${distFolder}/${filePath}`,
|
|
805
|
-
size,
|
|
806
|
-
compressedSize
|
|
807
|
-
};
|
|
808
|
-
switch(chunk.path.length > longest && (longest = chunk.path.length), node_path.extname(filePath)){
|
|
809
|
-
case '.html':
|
|
810
|
-
chunkGroupMap.HTML.chunks.push(chunk);
|
|
811
|
-
break;
|
|
812
|
-
case '.css':
|
|
813
|
-
chunkGroupMap.CSS.chunks.push(chunk);
|
|
814
|
-
break;
|
|
815
|
-
case '.js':
|
|
816
|
-
case '.wasm':
|
|
817
|
-
chunkGroupMap.JS.chunks.push(chunk);
|
|
818
|
-
break;
|
|
819
|
-
default:
|
|
820
|
-
chunkGroupMap.Assets.chunks.push(chunk);
|
|
821
|
-
}
|
|
822
|
-
})), logUpdate(`✓ computed gzip size (${assets.length})`), console.log();
|
|
823
|
-
let sizePad = displaySize(totalSize).length, compressPad = displaySize(totalCompressedSize).length;
|
|
824
|
-
chunkGroups.forEach((group)=>{
|
|
825
|
-
group.chunks.sort((a, b)=>a.size - b.size).forEach((chunk)=>{
|
|
826
|
-
let isLarge = 'JS' === group.type && chunk.size / 1000 > 500, relativeOutDir = node_path.dirname(chunk.path) + '/', log = colors.dim(relativeOutDir);
|
|
827
|
-
log += colors[group.color](chunk.name.padEnd(longest + 2 - relativeOutDir.length)), log += colors[isLarge ? 'yellow' : 'dim'](displaySize(chunk.size).padStart(sizePad)), console.log(log += colors.dim(` │ gzip: ${displaySize(chunk.compressedSize).padStart(compressPad)}`));
|
|
828
|
-
});
|
|
829
|
-
});
|
|
830
|
-
let log = colors.blue('Total'.padEnd(longest + 2));
|
|
831
|
-
log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` │ gzip: ${displaySize(totalCompressedSize)}`));
|
|
832
815
|
}
|
|
833
816
|
function isLikelyFile(filePath) {
|
|
834
817
|
return (filePath.split(sep).pop() || '').includes('.');
|
|
@@ -850,10 +833,7 @@ let getCompileTime = (stats)=>stats.toJson({
|
|
|
850
833
|
}).time / 1000, sameCount = 0;
|
|
851
834
|
async function compileDone(compiler, stats) {
|
|
852
835
|
let root = compiler.options.context;
|
|
853
|
-
if (!stats.hasErrors()) if (utils_isProd())
|
|
854
|
-
root,
|
|
855
|
-
stats
|
|
856
|
-
}), logger_logger.ready(colors.green(`built in ${prettyTime(getCompileTime(stats))}`));
|
|
836
|
+
if (!stats.hasErrors()) if (utils_isProd()) logger_logger.ready(colors.green(`built in ${prettyTime(getCompileTime(stats))}`));
|
|
857
837
|
else {
|
|
858
838
|
let fileInfo = function(changedFiles, removedFiles, root) {
|
|
859
839
|
if (!changedFiles?.length && !removedFiles?.length) return null;
|
|
@@ -877,36 +857,59 @@ async function compileDone(compiler, stats) {
|
|
|
877
857
|
logger_logger.debug(`${colors.cyan(packageName)}: ${colors.yellow(count)} modules`);
|
|
878
858
|
});
|
|
879
859
|
}
|
|
880
|
-
isDebug() || logger_logger.clear(), console.log(colors.dim(getTime()), colors.cyan(`[${
|
|
860
|
+
isDebug() || logger_logger.clear(), console.log(colors.dim(getTime()), colors.cyan(`[${getCurrentUnpackConfig()._context.callerName}]`), colors.brand(utils_isDevServer() ? 'hmr update' : 'build'), `${colors.dim(fileInfo)}${sameCount > 1 ? ` ${colors.yellow(`(x${sameCount})`)}` : ''}`, isDebug() ? colors.dim(`| ${prettyTime(getCompileTime(stats))} (${stats.compilation.modules.size} modules)`) : '');
|
|
881
861
|
}
|
|
882
862
|
}
|
|
883
863
|
let progress_PLUGIN_NAME = 'ProgressPlugin';
|
|
884
|
-
class
|
|
864
|
+
class ProgressLitePlugin {
|
|
885
865
|
apply(compiler) {
|
|
886
866
|
compiler.hooks.afterDone.tap(progress_PLUGIN_NAME, async (stats)=>{
|
|
887
867
|
await compileDone(compiler, stats);
|
|
888
868
|
});
|
|
889
869
|
}
|
|
890
870
|
}
|
|
891
|
-
class
|
|
892
|
-
|
|
893
|
-
super.apply(compiler), compiler.hooks.afterDone.tap(progress_PLUGIN_NAME, async (stats)=>{
|
|
894
|
-
await compileDone(compiler, stats);
|
|
895
|
-
});
|
|
896
|
-
}
|
|
871
|
+
class ProgressPlugin extends rspack.ProgressPlugin {
|
|
872
|
+
progressBar = new ProgressBar();
|
|
897
873
|
constructor(){
|
|
898
|
-
var key, value;
|
|
899
874
|
super((percentage, msg, ...args)=>{
|
|
900
875
|
utils_isProd() && this.progressBar.update({
|
|
901
876
|
current: percentage,
|
|
902
877
|
message: `${msg} ${args.join(' ')}`
|
|
903
878
|
});
|
|
904
|
-
})
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
})
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
apply(compiler) {
|
|
882
|
+
super.apply(compiler), compiler.hooks.afterDone.tap(progress_PLUGIN_NAME, async (stats)=>{
|
|
883
|
+
await compileDone(compiler, stats);
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
let registerHooks_PLUGIN_NAME = 'RegisterHooksPlugin';
|
|
888
|
+
class RegisterHooksPlugin {
|
|
889
|
+
isFirstCompile = !0;
|
|
890
|
+
apply(compiler) {
|
|
891
|
+
compiler.hooks.beforeCompile.tapPromise(registerHooks_PLUGIN_NAME, async ()=>{
|
|
892
|
+
await applyPluginsByHook('buildStart', async (impl)=>{
|
|
893
|
+
await impl({
|
|
894
|
+
compiler,
|
|
895
|
+
isFirstCompile: this.isFirstCompile,
|
|
896
|
+
isWatch: isWatch()
|
|
897
|
+
});
|
|
898
|
+
});
|
|
899
|
+
}), compiler.hooks.done.tapPromise(registerHooks_PLUGIN_NAME, async (stats)=>{
|
|
900
|
+
await applyPluginsByHook('buildEnd', async (impl)=>{
|
|
901
|
+
await impl({
|
|
902
|
+
compiler,
|
|
903
|
+
isFirstCompile: this.isFirstCompile,
|
|
904
|
+
isWatch: isWatch(),
|
|
905
|
+
stats
|
|
906
|
+
});
|
|
907
|
+
}), this.isFirstCompile = !1;
|
|
908
|
+
}), compiler.hooks.compilation.tap(registerHooks_PLUGIN_NAME, (compilation)=>{
|
|
909
|
+
rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeEmit.tapPromise(registerHooks_PLUGIN_NAME, async (data)=>(await applyPluginsByHook('transformHtml', async (impl)=>{
|
|
910
|
+
data.html = await impl(data.html);
|
|
911
|
+
}), data));
|
|
912
|
+
});
|
|
910
913
|
}
|
|
911
914
|
}
|
|
912
915
|
async function applyTypeCheckConfig({ config, unpackConfig }) {
|
|
@@ -938,19 +941,25 @@ async function applyTypeCheckConfig({ config, unpackConfig }) {
|
|
|
938
941
|
}
|
|
939
942
|
})), config;
|
|
940
943
|
}
|
|
944
|
+
var bundler_config_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
941
945
|
async function getBundlerConfig(originalUnpackConfig) {
|
|
946
|
+
setCurrentUnpackConfig(originalUnpackConfig);
|
|
942
947
|
let { plugins, bundlerConfig, ...rest } = originalUnpackConfig;
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
948
|
+
await applyPluginsByHook('config', async (impl)=>{
|
|
949
|
+
rest = await impl(rest, {
|
|
950
|
+
...originalUnpackConfig._context,
|
|
951
|
+
mergeConfig: mergeConfig
|
|
952
|
+
});
|
|
946
953
|
});
|
|
947
954
|
let unpackConfig = {
|
|
948
955
|
...rest,
|
|
949
956
|
plugins,
|
|
950
957
|
bundlerConfig
|
|
951
958
|
};
|
|
952
|
-
|
|
953
|
-
|
|
959
|
+
setCurrentUnpackConfig(unpackConfig), await applyPluginsByHook('configResolved', async (impl)=>{
|
|
960
|
+
await impl(unpackConfig);
|
|
961
|
+
});
|
|
962
|
+
let tsconfigPath = node_path.resolve(unpackConfig.root, 'tsconfig.json'), isTs = node_fs.existsSync(tsconfigPath), minifyOptions = isPlainObject(unpackConfig.build?.minify) ? unpackConfig.build?.minify : {}, { publicVars, filePaths: envFilePaths } = function({ cwd = process.cwd(), mode = getNodeEnv(), prefixes = [
|
|
954
963
|
'PUBLIC_'
|
|
955
964
|
], processEnv = process.env } = {}) {
|
|
956
965
|
if ('local' === mode) throw Error(`${colors.yellow('local')} cannot be used as a value for env mode, because ${colors.yellow('.env.local')} represents a temporary local file. Please use another value.`);
|
|
@@ -1018,14 +1027,14 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1018
1027
|
}),
|
|
1019
1028
|
crossOriginLoading: 'anonymous',
|
|
1020
1029
|
pathinfo: !1,
|
|
1021
|
-
publicPath: unpackConfig.
|
|
1030
|
+
publicPath: unpackConfig.base,
|
|
1022
1031
|
webassemblyModuleFilename: 'wasm/[contenthash:8].module.wasm',
|
|
1023
1032
|
assetModuleFilename: 'assets/[name].[contenthash:8][ext]'
|
|
1024
1033
|
},
|
|
1025
1034
|
infrastructureLogging: {
|
|
1026
1035
|
level: 'error'
|
|
1027
1036
|
},
|
|
1028
|
-
devtool: unpackConfig.
|
|
1037
|
+
devtool: unpackConfig.sourceMap,
|
|
1029
1038
|
module: {
|
|
1030
1039
|
rules: [
|
|
1031
1040
|
{
|
|
@@ -1055,22 +1064,6 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1055
1064
|
...publicVars,
|
|
1056
1065
|
...unpackConfig.define
|
|
1057
1066
|
}),
|
|
1058
|
-
!unpackConfig.mpa && new rspack.HtmlRspackPlugin({
|
|
1059
|
-
template: unpackConfig.html?.template || void 0,
|
|
1060
|
-
templateContent: unpackConfig.html?.templateContent || (unpackConfig.html?.template ? void 0 : TEMPLATE_CONTENT),
|
|
1061
|
-
templateParameters: {
|
|
1062
|
-
mountId: unpackConfig.html.mountId,
|
|
1063
|
-
title: isFunction(unpackConfig.html?.title) ? unpackConfig.html?.title({
|
|
1064
|
-
entryName: 'index'
|
|
1065
|
-
}) : unpackConfig.html?.title || '',
|
|
1066
|
-
headTag: unpackConfig.html?.headTag || '',
|
|
1067
|
-
...unpackConfig.html?.templateParameters
|
|
1068
|
-
},
|
|
1069
|
-
minify: !1,
|
|
1070
|
-
chunks: [
|
|
1071
|
-
'main'
|
|
1072
|
-
]
|
|
1073
|
-
}),
|
|
1074
1067
|
unpackConfig.performance?.removeMomentLocale && new rspack.IgnorePlugin({
|
|
1075
1068
|
resourceRegExp: /^\.\/locale$/,
|
|
1076
1069
|
contextRegExp: /moment$/
|
|
@@ -1078,7 +1071,8 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1078
1071
|
unpackConfig.build?.copy && new rspack.CopyRspackPlugin({
|
|
1079
1072
|
patterns: unpackConfig.build.copy
|
|
1080
1073
|
}),
|
|
1081
|
-
new
|
|
1074
|
+
new RegisterHooksPlugin(),
|
|
1075
|
+
unpackConfig.build?.progressBar ? new ProgressPlugin() : new ProgressLitePlugin()
|
|
1082
1076
|
].filter(Boolean),
|
|
1083
1077
|
externals: unpackConfig.externals,
|
|
1084
1078
|
resolve: {
|
|
@@ -1119,7 +1113,7 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1119
1113
|
},
|
|
1120
1114
|
optimization: {
|
|
1121
1115
|
moduleIds: isDev() ? 'named' : 'deterministic',
|
|
1122
|
-
minimize: !!unpackConfig.build?.minify,
|
|
1116
|
+
minimize: !!unpackConfig.build?.minify && utils_isProd(),
|
|
1123
1117
|
minimizer: [
|
|
1124
1118
|
new JsMinifyPlugin(mergeConfig({
|
|
1125
1119
|
compress: {
|
|
@@ -1139,8 +1133,23 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1139
1133
|
performance: {
|
|
1140
1134
|
hints: !1
|
|
1141
1135
|
}
|
|
1142
|
-
};
|
|
1143
|
-
|
|
1136
|
+
}, transformPlugins = getNormalizedPluginsByHook('transform');
|
|
1137
|
+
return transformPlugins.length && config.module.rules.push({
|
|
1138
|
+
test: SCRIPT_REGEX,
|
|
1139
|
+
enforce: 'pre',
|
|
1140
|
+
exclude: /node_modules/,
|
|
1141
|
+
use: [
|
|
1142
|
+
{
|
|
1143
|
+
loader: node_path.resolve(bundler_config_dirname, './transformLoader.js'),
|
|
1144
|
+
options: {
|
|
1145
|
+
plugins: transformPlugins
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
]
|
|
1149
|
+
}), config = await applyHtmlConfig({
|
|
1150
|
+
config,
|
|
1151
|
+
unpackConfig
|
|
1152
|
+
}), config = (({ config, unpackConfig })=>{
|
|
1144
1153
|
let { chunkSplit } = unpackConfig.performance || {};
|
|
1145
1154
|
if (chunkSplit?.strategy) {
|
|
1146
1155
|
let forceSplittingGroups = {};
|
|
@@ -1304,7 +1313,7 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1304
1313
|
}
|
|
1305
1314
|
},
|
|
1306
1315
|
isDev() && {
|
|
1307
|
-
loader: node_path.resolve(css_dirname, './typedCssModulesLoader.
|
|
1316
|
+
loader: node_path.resolve(css_dirname, './typedCssModulesLoader.js'),
|
|
1308
1317
|
options: {
|
|
1309
1318
|
modules
|
|
1310
1319
|
}
|
|
@@ -1404,7 +1413,7 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1404
1413
|
unpackConfig
|
|
1405
1414
|
}),
|
|
1406
1415
|
unpackConfig
|
|
1407
|
-
}), unpackConfig.
|
|
1416
|
+
}), unpackConfig.performance?.cache && (config = await applyCacheConfig({
|
|
1408
1417
|
config,
|
|
1409
1418
|
unpackConfig,
|
|
1410
1419
|
envFilePaths
|
|
@@ -1454,12 +1463,13 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1454
1463
|
}({
|
|
1455
1464
|
config,
|
|
1456
1465
|
unpackConfig
|
|
1457
|
-
})),
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1466
|
+
})), await applyPluginsByHook('bundlerConfig', async (impl)=>{
|
|
1467
|
+
config = await impl(config, {
|
|
1468
|
+
...unpackConfig._context,
|
|
1469
|
+
unpackConfig,
|
|
1470
|
+
mergeConfig: mergeConfig
|
|
1471
|
+
});
|
|
1472
|
+
}), unpackConfig.bundlerConfig && (config = isFunction(unpackConfig.bundlerConfig) ? await unpackConfig.bundlerConfig(config, {
|
|
1463
1473
|
mergeConfig: mergeConfig
|
|
1464
1474
|
}) : mergeConfig(config, unpackConfig.bundlerConfig)), config;
|
|
1465
1475
|
}
|
|
@@ -1539,302 +1549,7 @@ function execAsync(command, options) {
|
|
|
1539
1549
|
});
|
|
1540
1550
|
});
|
|
1541
1551
|
}
|
|
1542
|
-
|
|
1543
|
-
let SPECIAL_NO_ENTRY_DEPS = [
|
|
1544
|
-
'@iconify-icons/material-symbols'
|
|
1545
|
-
], getExternalLibraryName = (pkgName)=>{
|
|
1546
|
-
let externalAlias = {
|
|
1547
|
-
react: 'React',
|
|
1548
|
-
'react-dom': 'ReactDOM',
|
|
1549
|
-
'react-router-dom': 'ReactRouterDOM'
|
|
1550
|
-
};
|
|
1551
|
-
return externalAlias[pkgName] ? externalAlias[pkgName] : pkgName.replace(/^@/, '').split(/[/\-.]/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase() + part.slice(1)).join('');
|
|
1552
|
-
}, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`, prebundleDeps = async ({ unpackConfig })=>{
|
|
1553
|
-
var externals;
|
|
1554
|
-
let existExternals, cacheDir, shouldTransformDeepImport = !1, count = {
|
|
1555
|
-
total: 0,
|
|
1556
|
-
bundled: 0
|
|
1557
|
-
}, failedDeps = [], root = unpackConfig.root, CACHE_PATH = unpackConfig._context.cachePath, failedDepsCachePath = node_path.resolve(root, CACHE_PATH, 'failed-deps.json'), failedCache = node_fs.existsSync(failedDepsCachePath) ? JSON.parse(node_fs.readFileSync(failedDepsCachePath, 'utf-8')) : {}, updateProgress = ()=>{
|
|
1558
|
-
let errMsg = failedDeps.length > 0 ? ` failed: ${failedDeps.join(', ')}` : '';
|
|
1559
|
-
logUpdate(`${colors.magenta('»')} optimizing dependencies (${count.bundled}/${count.total})${errMsg}`), count.total === count.bundled + failedDeps.length && console.log();
|
|
1560
|
-
}, userOptions = isPlainObject(unpackConfig.dev?.prebundle) ? unpackConfig.dev.prebundle : {}, ignoreCSSDeps = userOptions.ignoreCSS || [], packageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'package.json'), 'utf-8')), excludeDeps = [
|
|
1561
|
-
...(externals = unpackConfig.externals, existExternals = new Set(), Array.isArray(externals) ? externals.forEach((item)=>{
|
|
1562
|
-
isPlainObject(item) && Object.keys(item).forEach((key)=>{
|
|
1563
|
-
existExternals.add(key);
|
|
1564
|
-
});
|
|
1565
|
-
}) : isPlainObject(externals) && Object.keys(externals).forEach((key)=>{
|
|
1566
|
-
existExternals.add(key);
|
|
1567
|
-
}), Array.from(existExternals) || []),
|
|
1568
|
-
...userOptions.exclude || []
|
|
1569
|
-
], needBundleDeps = (Array.isArray(userOptions.include) && userOptions.include.length > 0 ? userOptions.include : Object.keys(packageJson.dependencies || {})).filter((pkgName)=>!excludeDeps.includes(pkgName)).map((pkgName)=>{
|
|
1570
|
-
let packageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'node_modules', pkgName, 'package.json'), 'utf-8')), version = packageJson.version;
|
|
1571
|
-
if (failedCache[pkgName] === version) return;
|
|
1572
|
-
let entry = ((packageJson)=>{
|
|
1573
|
-
if (packageJson.module) return packageJson.module;
|
|
1574
|
-
if (packageJson.exports) {
|
|
1575
|
-
if (isString(packageJson.exports)) return packageJson.exports;
|
|
1576
|
-
let defaultExport = packageJson.exports['.'];
|
|
1577
|
-
if (defaultExport) {
|
|
1578
|
-
if (isString(defaultExport)) return defaultExport;
|
|
1579
|
-
if (isString(defaultExport.import)) return defaultExport.import;
|
|
1580
|
-
if (isString(defaultExport.browser)) return defaultExport.browser;
|
|
1581
|
-
if (isString(defaultExport.default)) return defaultExport.default;
|
|
1582
|
-
}
|
|
1583
|
-
if (isString(packageJson.exports.default)) return packageJson.exports.default;
|
|
1584
|
-
}
|
|
1585
|
-
if (packageJson.main) return packageJson.main;
|
|
1586
|
-
})(packageJson);
|
|
1587
|
-
if (!entry) {
|
|
1588
|
-
if (SPECIAL_NO_ENTRY_DEPS.includes(pkgName)) {
|
|
1589
|
-
let syntheticEntry = (({ root, pkgName })=>{
|
|
1590
|
-
let pkgDir = node_path.resolve(root, 'node_modules', pkgName);
|
|
1591
|
-
if (!node_fs.existsSync(pkgDir)) return;
|
|
1592
|
-
let indexPath = node_path.resolve(pkgDir, 'index.ts'), content = globSync('**/*.{js,jsx,ts,tsx}', {
|
|
1593
|
-
cwd: pkgDir,
|
|
1594
|
-
absolute: !1
|
|
1595
|
-
}).filter((p)=>{
|
|
1596
|
-
let base = node_path.basename(p);
|
|
1597
|
-
return !(p.endsWith('.d.ts') || /^index\.(t|j)sx?$/.test(base)) && 'package.json' !== base;
|
|
1598
|
-
}).map((file)=>{
|
|
1599
|
-
let normalized = file.split(node_path.sep).join('/'), exportName = pathToExportIdentifier(normalized);
|
|
1600
|
-
return `export { default as ${exportName} } from './${normalized}'`;
|
|
1601
|
-
}).join('\n');
|
|
1602
|
-
return node_fs.writeFileSync(indexPath, content, 'utf-8'), indexPath;
|
|
1603
|
-
})({
|
|
1604
|
-
root,
|
|
1605
|
-
pkgName
|
|
1606
|
-
});
|
|
1607
|
-
if (syntheticEntry) return shouldTransformDeepImport = !0, {
|
|
1608
|
-
name: pkgName,
|
|
1609
|
-
entry: syntheticEntry,
|
|
1610
|
-
version
|
|
1611
|
-
};
|
|
1612
|
-
}
|
|
1613
|
-
failedCache[pkgName] = version;
|
|
1614
|
-
return;
|
|
1615
|
-
}
|
|
1616
|
-
return {
|
|
1617
|
-
name: pkgName,
|
|
1618
|
-
entry: node_path.resolve(root, 'node_modules', pkgName, entry),
|
|
1619
|
-
version
|
|
1620
|
-
};
|
|
1621
|
-
}).filter(Boolean), depExternals = Object.fromEntries(Array.from(new Set([
|
|
1622
|
-
'react',
|
|
1623
|
-
'react-dom',
|
|
1624
|
-
'react-router-dom',
|
|
1625
|
-
...Array.isArray(userOptions.externals) ? userOptions.externals : []
|
|
1626
|
-
])).map((pkg)=>[
|
|
1627
|
-
pkg,
|
|
1628
|
-
getExternalValue(pkg)
|
|
1629
|
-
])), bundledDeps = await Promise.all(needBundleDeps.map((depInfo)=>(({ name, entry, version })=>new Promise((resolve)=>{
|
|
1630
|
-
let pkgDir = node_path.resolve(root, CACHE_PATH, 'umd', name), outDir = node_path.resolve(pkgDir, version), getResult = ()=>({
|
|
1631
|
-
name,
|
|
1632
|
-
assets: globSync('**/index.{js,css}', {
|
|
1633
|
-
cwd: outDir,
|
|
1634
|
-
absolute: !0
|
|
1635
|
-
})
|
|
1636
|
-
});
|
|
1637
|
-
if (node_fs.existsSync(outDir)) return void resolve(getResult());
|
|
1638
|
-
count.total++, updateProgress();
|
|
1639
|
-
let getSwcOptions = ({ tsx })=>({
|
|
1640
|
-
jsc: {
|
|
1641
|
-
parser: {
|
|
1642
|
-
tsx,
|
|
1643
|
-
syntax: "typescript",
|
|
1644
|
-
dynamicImport: !0,
|
|
1645
|
-
decorators: !0
|
|
1646
|
-
},
|
|
1647
|
-
transform: {
|
|
1648
|
-
react: {
|
|
1649
|
-
runtime: 'automatic'
|
|
1650
|
-
}
|
|
1651
|
-
}
|
|
1652
|
-
}
|
|
1653
|
-
}), compiler = rspack({
|
|
1654
|
-
entry: {
|
|
1655
|
-
index: entry
|
|
1656
|
-
},
|
|
1657
|
-
context: root,
|
|
1658
|
-
mode: 'development',
|
|
1659
|
-
output: {
|
|
1660
|
-
clean: !0,
|
|
1661
|
-
path: outDir,
|
|
1662
|
-
pathinfo: !1,
|
|
1663
|
-
library: {
|
|
1664
|
-
name: getExternalLibraryName(name),
|
|
1665
|
-
type: 'umd',
|
|
1666
|
-
umdNamedDefine: !0
|
|
1667
|
-
},
|
|
1668
|
-
globalObject: 'this'
|
|
1669
|
-
},
|
|
1670
|
-
devtool: !1,
|
|
1671
|
-
module: {
|
|
1672
|
-
rules: [
|
|
1673
|
-
{
|
|
1674
|
-
test: /\.(j|t)s$/,
|
|
1675
|
-
use: [
|
|
1676
|
-
{
|
|
1677
|
-
loader: 'builtin:swc-loader',
|
|
1678
|
-
options: getSwcOptions({
|
|
1679
|
-
tsx: !1
|
|
1680
|
-
})
|
|
1681
|
-
}
|
|
1682
|
-
]
|
|
1683
|
-
},
|
|
1684
|
-
{
|
|
1685
|
-
test: /\.(j|t)sx$/,
|
|
1686
|
-
use: [
|
|
1687
|
-
{
|
|
1688
|
-
loader: 'builtin:swc-loader',
|
|
1689
|
-
options: getSwcOptions({
|
|
1690
|
-
tsx: !0
|
|
1691
|
-
})
|
|
1692
|
-
}
|
|
1693
|
-
]
|
|
1694
|
-
},
|
|
1695
|
-
{
|
|
1696
|
-
test: /\.less$/,
|
|
1697
|
-
type: 'css/auto',
|
|
1698
|
-
use: [
|
|
1699
|
-
{
|
|
1700
|
-
loader: getCompiledPkgPath('less-loader'),
|
|
1701
|
-
options: {
|
|
1702
|
-
lessOptions: {
|
|
1703
|
-
javascriptEnabled: !0
|
|
1704
|
-
},
|
|
1705
|
-
implementation: getUserDepPath(root, 'less')
|
|
1706
|
-
}
|
|
1707
|
-
}
|
|
1708
|
-
]
|
|
1709
|
-
},
|
|
1710
|
-
{
|
|
1711
|
-
test: /\.s[ac]ss$/i,
|
|
1712
|
-
type: 'css/auto',
|
|
1713
|
-
use: [
|
|
1714
|
-
{
|
|
1715
|
-
loader: getCompiledPkgPath('sass-loader'),
|
|
1716
|
-
options: {
|
|
1717
|
-
api: 'modern-compiler',
|
|
1718
|
-
implementation: getUserDepPath(root, [
|
|
1719
|
-
'sass-embedded',
|
|
1720
|
-
'sass'
|
|
1721
|
-
])
|
|
1722
|
-
}
|
|
1723
|
-
}
|
|
1724
|
-
]
|
|
1725
|
-
}
|
|
1726
|
-
]
|
|
1727
|
-
},
|
|
1728
|
-
optimization: {
|
|
1729
|
-
splitChunks: !1
|
|
1730
|
-
},
|
|
1731
|
-
experiments: {
|
|
1732
|
-
css: !0
|
|
1733
|
-
},
|
|
1734
|
-
externals: depExternals
|
|
1735
|
-
});
|
|
1736
|
-
compiler.run((_, stats)=>{
|
|
1737
|
-
let isFailed = !1;
|
|
1738
|
-
stats?.hasErrors() ? (isFailed = !0, failedDeps.push(name), failedCache[name] = version, removeDir(outDir)) : count.bundled++, updateProgress(), compiler.close(()=>{
|
|
1739
|
-
resolve(isFailed ? void 0 : getResult());
|
|
1740
|
-
});
|
|
1741
|
-
});
|
|
1742
|
-
}))(depInfo)));
|
|
1743
|
-
cacheDir = node_path.dirname(failedDepsCachePath), node_fs.existsSync(cacheDir) || node_fs.mkdirSync(cacheDir, {
|
|
1744
|
-
recursive: !0
|
|
1745
|
-
}), node_fs.writeFileSync(failedDepsCachePath, JSON.stringify(failedCache, null, 2), 'utf-8');
|
|
1746
|
-
let cachePath = node_path.resolve(root, CACHE_PATH, 'umd'), staticServer = node_http.createServer((req, res)=>{
|
|
1747
|
-
if (res.setHeader('Access-Control-Allow-Origin', '*'), 'OPTIONS' === req.method) {
|
|
1748
|
-
res.writeHead(204), res.end();
|
|
1749
|
-
return;
|
|
1750
|
-
}
|
|
1751
|
-
let url = req.url || '';
|
|
1752
|
-
if (url.startsWith("/umd/")) {
|
|
1753
|
-
let relativePath = url.replace("/umd/", '');
|
|
1754
|
-
if (relativePath.includes('..')) {
|
|
1755
|
-
res.writeHead(403), res.end();
|
|
1756
|
-
return;
|
|
1757
|
-
}
|
|
1758
|
-
let filePath = node_path.join(cachePath, relativePath);
|
|
1759
|
-
if (node_fs.existsSync(filePath)) {
|
|
1760
|
-
let stat = node_fs.statSync(filePath);
|
|
1761
|
-
if (stat.isFile()) {
|
|
1762
|
-
let mtime = stat.mtime.toUTCString(), ext = node_path.extname(filePath);
|
|
1763
|
-
if (res.setHeader('Cache-Control', 'no-cache'), res.setHeader('Last-Modified', mtime), '.js' === ext && res.setHeader('Content-Type', "application/javascript"), '.css' === ext && res.setHeader('Content-Type', 'text/css'), req.headers['if-modified-since'] === mtime) {
|
|
1764
|
-
res.writeHead(304), res.end();
|
|
1765
|
-
return;
|
|
1766
|
-
}
|
|
1767
|
-
res.writeHead(200), node_fs.createReadStream(filePath).pipe(res);
|
|
1768
|
-
return;
|
|
1769
|
-
}
|
|
1770
|
-
}
|
|
1771
|
-
}
|
|
1772
|
-
res.writeHead(404), res.end();
|
|
1773
|
-
}), port = await getPort();
|
|
1774
|
-
staticServer.listen(port), addRestartCleaner(()=>new Promise((resolve)=>staticServer.close(()=>resolve(void 0))));
|
|
1775
|
-
let externals1 = {}, jsAssets = [], cssAssets = [], preJsAssets = [];
|
|
1776
|
-
bundledDeps.filter(Boolean).forEach((dep)=>{
|
|
1777
|
-
dep && (externals1[dep.name] = getExternalValue(dep.name), dep.assets.forEach((absPath)=>{
|
|
1778
|
-
let relativePath = node_path.relative(cachePath, absPath), preDeps = [
|
|
1779
|
-
'react',
|
|
1780
|
-
'react-dom',
|
|
1781
|
-
'react-router-dom'
|
|
1782
|
-
], serverPath = `//localhost:${port}/umd/${relativePath}`;
|
|
1783
|
-
switch(node_path.extname(relativePath)){
|
|
1784
|
-
case '.js':
|
|
1785
|
-
preDeps.includes(dep.name) ? preJsAssets.push({
|
|
1786
|
-
path: serverPath,
|
|
1787
|
-
order: preDeps.indexOf(dep.name)
|
|
1788
|
-
}) : jsAssets.push(serverPath);
|
|
1789
|
-
break;
|
|
1790
|
-
case '.css':
|
|
1791
|
-
ignoreCSSDeps.includes(dep.name) || cssAssets.push(serverPath);
|
|
1792
|
-
}
|
|
1793
|
-
}));
|
|
1794
|
-
});
|
|
1795
|
-
let existingExternals = unpackConfig.externals ? Array.isArray(unpackConfig.externals) ? unpackConfig.externals : [
|
|
1796
|
-
unpackConfig.externals
|
|
1797
|
-
] : [];
|
|
1798
|
-
return unpackConfig.externals = [
|
|
1799
|
-
externals1,
|
|
1800
|
-
...existingExternals
|
|
1801
|
-
], unpackConfig.plugins.push({
|
|
1802
|
-
name: 'unpack:prebundle',
|
|
1803
|
-
config: (config)=>{
|
|
1804
|
-
let originalHeadTag = config.html?.headTag || '', sortedPreTags = preJsAssets.sort((a, b)=>a.order - b.order).map((item)=>item.path).map((item)=>`<script defer src="${item}"></script>`);
|
|
1805
|
-
return set(config, [
|
|
1806
|
-
'html',
|
|
1807
|
-
'headTag'
|
|
1808
|
-
], `${sortedPreTags.join('')}${originalHeadTag}`), config;
|
|
1809
|
-
},
|
|
1810
|
-
bundlerConfig: (config)=>{
|
|
1811
|
-
let PLUGIN_NAME = 'PluginInjectAssets';
|
|
1812
|
-
return config.plugins.push({
|
|
1813
|
-
apply: (compiler)=>{
|
|
1814
|
-
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
|
|
1815
|
-
rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(PLUGIN_NAME, async (args)=>(args.assets.js.unshift(...jsAssets), args.assets.css.unshift(...cssAssets), args));
|
|
1816
|
-
});
|
|
1817
|
-
}
|
|
1818
|
-
}), shouldTransformDeepImport && config.module.rules.push({
|
|
1819
|
-
test: /\.[jt]sx?$/,
|
|
1820
|
-
exclude: /node_modules/,
|
|
1821
|
-
use: [
|
|
1822
|
-
{
|
|
1823
|
-
loader: node_path.resolve(prebundleDeps_dirname, './transformDeepImportLoader.mjs'),
|
|
1824
|
-
options: {
|
|
1825
|
-
packages: SPECIAL_NO_ENTRY_DEPS
|
|
1826
|
-
}
|
|
1827
|
-
}
|
|
1828
|
-
]
|
|
1829
|
-
}), config;
|
|
1830
|
-
}
|
|
1831
|
-
}), unpackConfig;
|
|
1832
|
-
};
|
|
1833
|
-
async function unpackDev(originalUnpackConfig) {
|
|
1834
|
-
let unpackConfig = originalUnpackConfig;
|
|
1835
|
-
unpackConfig.dev?.prebundle && (unpackConfig = await prebundleDeps({
|
|
1836
|
-
unpackConfig
|
|
1837
|
-
}));
|
|
1552
|
+
async function unpackDev(unpackConfig) {
|
|
1838
1553
|
let compiler = rspack(await getBundlerConfig(unpackConfig)), port = await getPort(unpackConfig.server?.port), proxyConfig = unpackConfig.server?.proxy;
|
|
1839
1554
|
isPlainObject(proxyConfig) && (proxyConfig = Object.entries(proxyConfig).map(([contextStr, target])=>{
|
|
1840
1555
|
let baseConfig = {
|
|
@@ -1849,7 +1564,7 @@ async function unpackDev(originalUnpackConfig) {
|
|
|
1849
1564
|
target
|
|
1850
1565
|
};
|
|
1851
1566
|
}));
|
|
1852
|
-
let devServerOptions = {
|
|
1567
|
+
let devPublicPath = normalizePublicPath(unpackConfig.base), devServerOptions = {
|
|
1853
1568
|
hot: !0,
|
|
1854
1569
|
port,
|
|
1855
1570
|
open: !1,
|
|
@@ -1858,62 +1573,50 @@ async function unpackDev(originalUnpackConfig) {
|
|
|
1858
1573
|
},
|
|
1859
1574
|
proxy: proxyConfig,
|
|
1860
1575
|
devMiddleware: {
|
|
1576
|
+
publicPath: devPublicPath,
|
|
1861
1577
|
writeToDisk: unpackConfig.dev?.writeToDisk
|
|
1862
1578
|
}
|
|
1863
|
-
};
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1579
|
+
}, pluginMiddlewares = [];
|
|
1580
|
+
await applyPluginsByHook('setupMiddlewares', async (impl)=>{
|
|
1581
|
+
pluginMiddlewares = await impl(pluginMiddlewares);
|
|
1582
|
+
}), devServerOptions.setupMiddlewares = (middlewares)=>(middlewares.unshift((req, _, next)=>{
|
|
1583
|
+
let accept = req.headers.accept;
|
|
1584
|
+
if ('string' == typeof accept && accept.includes('html')) {
|
|
1585
|
+
let url = req.url || '/';
|
|
1586
|
+
'/' === devPublicPath ? req.url = '/index.html' : (url === devPublicPath.slice(0, -1) || url.startsWith(devPublicPath)) && (req.url = `${devPublicPath}index.html`);
|
|
1587
|
+
}
|
|
1588
|
+
next();
|
|
1589
|
+
}), middlewares.unshift(rspack.lazyCompilationMiddleware(compiler)), [
|
|
1590
|
+
...pluginMiddlewares,
|
|
1591
|
+
...middlewares
|
|
1592
|
+
]);
|
|
1867
1593
|
let server = new RspackDevServer(devServerOptions, compiler);
|
|
1868
|
-
await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v3.
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
printAddressUrls(port, unpackConfig.server?.host);
|
|
1879
|
-
},
|
|
1880
|
-
restartServer: async ()=>{
|
|
1881
|
-
logger_logger.clear(), await cleanUpBeforeRestart(), createUnpack({
|
|
1882
|
-
cwd: currentDevUnpackConfig.root,
|
|
1883
|
-
config: currentDevUnpackConfig
|
|
1884
|
-
}).dev();
|
|
1885
|
-
}
|
|
1886
|
-
});
|
|
1887
|
-
}
|
|
1888
|
-
function printAddressUrls(port, host) {
|
|
1889
|
-
let addressUrls = getAddressUrls({
|
|
1890
|
-
port
|
|
1891
|
-
}), colorPrefix = colors.brand('➜');
|
|
1892
|
-
addressUrls.forEach((addr, index)=>{
|
|
1893
|
-
let url;
|
|
1894
|
-
if (!host && 0 !== index) {
|
|
1895
|
-
1 === index && console.log(` ${colors.dim(colorPrefix)} ${colors.bold(colors.dim('Network:'))} ${colors.dim('use')} ${colors.bold('--host')} ${colors.dim('to expose')}`);
|
|
1896
|
-
return;
|
|
1897
|
-
}
|
|
1898
|
-
console.log(` ${colorPrefix} ${colors.bold(addr.label)}${(url = addr.url, colors.cyan(url.replace(/:(\d+)\//, (_, port)=>`:${colors.bold(port)}/`)))}`);
|
|
1899
|
-
});
|
|
1594
|
+
await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v3.8.1${unpackConfig.performance?.cache ? ' ϟ' : ''}`)} ${colors.dim('ready in')} ${colors.bold(Math.ceil(performance.now() - getUnpackStartTime()))} ${colors.dim('ms')}\n`), printServerUrls({
|
|
1595
|
+
port,
|
|
1596
|
+
host: unpackConfig.server?.host,
|
|
1597
|
+
base: unpackConfig.base
|
|
1598
|
+
}), addRestartCleaner(()=>server.stop(), ()=>new Promise((resolve)=>compiler.close(()=>resolve())));
|
|
1599
|
+
let open = unpackConfig.server?.open, url = isString(open) ? open : `http://localhost:${port}${devPublicPath}`;
|
|
1600
|
+
return open && openBrowser(url), {
|
|
1601
|
+
port,
|
|
1602
|
+
url
|
|
1603
|
+
};
|
|
1900
1604
|
}
|
|
1901
1605
|
function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'unpack' }) {
|
|
1902
1606
|
let _context = {
|
|
1903
1607
|
callerName,
|
|
1904
|
-
version: "3.
|
|
1608
|
+
version: "3.8.1",
|
|
1905
1609
|
cachePath: 'node_modules/.unpack'
|
|
1906
|
-
}
|
|
1907
|
-
|
|
1908
|
-
let resolveConfig = (mode)=>{
|
|
1909
|
-
let isProd;
|
|
1610
|
+
}, resolveConfig = (mode)=>{
|
|
1611
|
+
let rootPath, outputPath, basePath, cachedTraceMap, fs, isValidMethodName, parseFrame, formatOriginalLocation, formatFullStack, resolveErrorLocationAndStack, shouldTransformDeepImport, preJsAssets, jsAssets, cssAssets, bundledDepsCachePath, deepImportPkgPattern, deepImportRegex, root;
|
|
1910
1612
|
return {
|
|
1911
1613
|
...mergeConfig({
|
|
1912
1614
|
root: cwd,
|
|
1615
|
+
base: '/',
|
|
1616
|
+
sourceMap: 'production' !== mode && 'cheap-module-source-map',
|
|
1913
1617
|
build: {
|
|
1914
1618
|
outDir: 'dist',
|
|
1915
|
-
minify:
|
|
1916
|
-
sourceMap: !isProd && 'cheap-module-source-map',
|
|
1619
|
+
minify: !0,
|
|
1917
1620
|
filenameHash: !0,
|
|
1918
1621
|
target: 'es2022'
|
|
1919
1622
|
},
|
|
@@ -1932,11 +1635,616 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
|
|
|
1932
1635
|
chunkSplit: {
|
|
1933
1636
|
strategy: 'single-vendor'
|
|
1934
1637
|
},
|
|
1935
|
-
printFileSize: !0
|
|
1638
|
+
printFileSize: !0,
|
|
1639
|
+
cache: !0
|
|
1936
1640
|
},
|
|
1937
1641
|
typeCheck: !0,
|
|
1938
1642
|
envPrefix: [
|
|
1939
1643
|
'PUBLIC_'
|
|
1644
|
+
],
|
|
1645
|
+
plugins: [
|
|
1646
|
+
(rootPath = '', outputPath = '', basePath = '/', cachedTraceMap = new Map(), fs = null, isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), parseFrame = async (frame)=>{
|
|
1647
|
+
let { file, column, lineNumber } = frame;
|
|
1648
|
+
if (!file || null == lineNumber || null == column) return;
|
|
1649
|
+
let localPath = file;
|
|
1650
|
+
try {
|
|
1651
|
+
let pathname = new URL(file).pathname;
|
|
1652
|
+
if ('/' !== basePath) {
|
|
1653
|
+
let normalizedBase = basePath;
|
|
1654
|
+
pathname.startsWith(normalizedBase) && (pathname = pathname.slice(normalizedBase.length));
|
|
1655
|
+
}
|
|
1656
|
+
localPath = node_path.join(outputPath, pathname);
|
|
1657
|
+
} catch {
|
|
1658
|
+
node_path.isAbsolute(file) || (localPath = node_path.join(outputPath, file));
|
|
1659
|
+
}
|
|
1660
|
+
let sourceMapPath = `${localPath}.map`;
|
|
1661
|
+
try {
|
|
1662
|
+
if (!fs.existsSync(sourceMapPath)) return;
|
|
1663
|
+
let tracer = cachedTraceMap.get(sourceMapPath);
|
|
1664
|
+
if (!tracer) {
|
|
1665
|
+
let readFile = promisify(fs.readFile), sourceMapContent = await readFile(sourceMapPath, 'utf-8');
|
|
1666
|
+
if (!sourceMapContent) return;
|
|
1667
|
+
tracer = new TraceMap(sourceMapContent), cachedTraceMap.set(sourceMapPath, tracer);
|
|
1668
|
+
}
|
|
1669
|
+
let originalPosition = originalPositionFor(tracer, {
|
|
1670
|
+
line: lineNumber,
|
|
1671
|
+
column: column
|
|
1672
|
+
});
|
|
1673
|
+
return {
|
|
1674
|
+
sourceMapPath,
|
|
1675
|
+
originalPosition
|
|
1676
|
+
};
|
|
1677
|
+
} catch {
|
|
1678
|
+
return;
|
|
1679
|
+
}
|
|
1680
|
+
}, formatOriginalLocation = (originalMapping)=>{
|
|
1681
|
+
let { source, line, column } = originalMapping;
|
|
1682
|
+
if (!source) return;
|
|
1683
|
+
let relativeSource = source;
|
|
1684
|
+
if (source.includes('webpack://')) {
|
|
1685
|
+
let segments = (relativeSource = source.replace(/webpack:\/\/\/?/, '')).split(/[\\/]/);
|
|
1686
|
+
[
|
|
1687
|
+
'src',
|
|
1688
|
+
'node_modules'
|
|
1689
|
+
].includes(segments[1]) && (segments.shift(), relativeSource = segments.join('/'));
|
|
1690
|
+
}
|
|
1691
|
+
let result = relativeSource;
|
|
1692
|
+
return null !== line && (result += null === column ? `:${line}` : `:${line}:${column}`), result;
|
|
1693
|
+
}, formatFullStack = async (stackFrames)=>{
|
|
1694
|
+
let allLines = [], srcLines = [];
|
|
1695
|
+
for (let frame of stackFrames){
|
|
1696
|
+
let parsedFrame = await parseFrame(frame), { methodName } = frame, parts = [];
|
|
1697
|
+
methodName && isValidMethodName(methodName) && parts.push(methodName);
|
|
1698
|
+
let parsed = !1;
|
|
1699
|
+
if (parsedFrame) {
|
|
1700
|
+
let { originalPosition } = parsedFrame, originalLocation = formatOriginalLocation(originalPosition);
|
|
1701
|
+
originalLocation && (parts.push(originalLocation), parsed = !0);
|
|
1702
|
+
}
|
|
1703
|
+
if (!parsed && frame.file) try {
|
|
1704
|
+
let url = new URL(frame.file);
|
|
1705
|
+
parts.push(`${url.pathname}:${frame.lineNumber}:${frame.column}`);
|
|
1706
|
+
} catch {
|
|
1707
|
+
parts.push(`${frame.file}:${frame.lineNumber}:${frame.column}`);
|
|
1708
|
+
}
|
|
1709
|
+
if (parts.length > 0) {
|
|
1710
|
+
let loc = parts.length > 1 ? `(${parts[1]})` : parts[0].includes(':') ? `(${parts[0]})` : parts[0], func = parts.length > 1 ? parts[0] : parts[0].includes(':') ? '' : parts[0], line = func ? `\n at ${func} ${loc}` : `\n at ${loc}`;
|
|
1711
|
+
allLines.push(line);
|
|
1712
|
+
let locationText = loc.startsWith('(') && loc.endsWith(')') ? loc.slice(1, -1) : loc;
|
|
1713
|
+
/(^|[\\/])src[\\/]/.test(locationText) && srcLines.push(line);
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
return srcLines.length > 0 ? srcLines.join('') : allLines.join('');
|
|
1717
|
+
}, resolveErrorLocationAndStack = async (item)=>{
|
|
1718
|
+
let locationFromMsg = item.message ? ((message)=>{
|
|
1719
|
+
let match = message.match(/((?:[A-Za-z]:)?\/[^\s:]+):(\d+):(\d+)/);
|
|
1720
|
+
if (!match) return;
|
|
1721
|
+
let [, absPath, line, column] = match, source = absPath;
|
|
1722
|
+
return absPath.startsWith(rootPath + node_path.sep) && (source = node_path.relative(rootPath, absPath)), `${source}:${Number(line)}:${Number(column)}`;
|
|
1723
|
+
})(item.message) : null;
|
|
1724
|
+
if (locationFromMsg) return {
|
|
1725
|
+
locationSuffix: colors.dim(`(${locationFromMsg})`),
|
|
1726
|
+
stackString: ''
|
|
1727
|
+
};
|
|
1728
|
+
if (!item.stack) return {
|
|
1729
|
+
locationSuffix: '',
|
|
1730
|
+
stackString: ''
|
|
1731
|
+
};
|
|
1732
|
+
let parsedFrames = parse(item.stack), userFrame = parsedFrames.find((frame)=>frame.file && null !== frame.lineNumber && null !== frame.column && browserLogs_SCRIPT_REGEX.test(frame.file));
|
|
1733
|
+
if (userFrame) {
|
|
1734
|
+
let parsedUserFrame = await parseFrame(userFrame), loc = parsedUserFrame ? formatOriginalLocation(parsedUserFrame.originalPosition) : null;
|
|
1735
|
+
if (loc) return {
|
|
1736
|
+
locationSuffix: colors.dim(`(${loc})`),
|
|
1737
|
+
stackString: ''
|
|
1738
|
+
};
|
|
1739
|
+
}
|
|
1740
|
+
let formattedStack = await formatFullStack(parsedFrames);
|
|
1741
|
+
return {
|
|
1742
|
+
locationSuffix: '',
|
|
1743
|
+
stackString: colors.dim(formattedStack)
|
|
1744
|
+
};
|
|
1745
|
+
}, {
|
|
1746
|
+
name: 'unpack:browser-logs',
|
|
1747
|
+
apply: (config, { command })=>'dev' === command && config.dev?.browserLogs,
|
|
1748
|
+
buildStart: async ({ isFirstCompile, compiler })=>{
|
|
1749
|
+
isFirstCompile && (fs = compiler.outputFileSystem);
|
|
1750
|
+
},
|
|
1751
|
+
configResolved: (config)=>{
|
|
1752
|
+
rootPath = config.root, outputPath = node_path.join(rootPath, config.build.outDir), basePath = normalizePublicPath(config.base);
|
|
1753
|
+
},
|
|
1754
|
+
transformHtml: (html)=>injectToHead(html, `<script>
|
|
1755
|
+
;(() => {
|
|
1756
|
+
if (typeof window === 'undefined' || typeof console === 'undefined') return
|
|
1757
|
+
const endpoint = '${BROWSER_LOGS_ENDPOINT}'
|
|
1758
|
+
const levels = ['error', 'warn', 'debug']
|
|
1759
|
+
|
|
1760
|
+
const send = (level, args) => {
|
|
1761
|
+
try {
|
|
1762
|
+
const argsList = Array.prototype.slice.call(args)
|
|
1763
|
+
if (level === 'debug') {
|
|
1764
|
+
const stackHolder = new Error()
|
|
1765
|
+
stackHolder.name = ''
|
|
1766
|
+
stackHolder.message = ''
|
|
1767
|
+
argsList.push(stackHolder)
|
|
1768
|
+
}
|
|
1769
|
+
const payload = {
|
|
1770
|
+
level,
|
|
1771
|
+
time: new Date().toLocaleTimeString(),
|
|
1772
|
+
args: argsList.map((item) => {
|
|
1773
|
+
try {
|
|
1774
|
+
if (item instanceof Error) {
|
|
1775
|
+
const name = item.name || ''
|
|
1776
|
+
const msg = item.message ? ': ' + item.message : ''
|
|
1777
|
+
return {
|
|
1778
|
+
type: 'error',
|
|
1779
|
+
message: name + msg,
|
|
1780
|
+
stack: item.stack,
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
if (item === null) {
|
|
1784
|
+
return { type: 'null', message: 'null' }
|
|
1785
|
+
}
|
|
1786
|
+
const t = typeof item
|
|
1787
|
+
if (['string', 'number', 'boolean'].includes(t)) {
|
|
1788
|
+
return { type: t, message: item }
|
|
1789
|
+
}
|
|
1790
|
+
if (['undefined', 'function', 'symbol', 'bigint'].includes(t)) {
|
|
1791
|
+
return { type: t, message: String(item) }
|
|
1792
|
+
}
|
|
1793
|
+
return { type: 'object', message: JSON.stringify(item) }
|
|
1794
|
+
} catch (e) {
|
|
1795
|
+
return { type: 'unknown', message: String(item) }
|
|
1796
|
+
}
|
|
1797
|
+
}),
|
|
1798
|
+
}
|
|
1799
|
+
const body = JSON.stringify(payload)
|
|
1800
|
+
if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
|
|
1801
|
+
navigator.sendBeacon(endpoint, body)
|
|
1802
|
+
} else if (typeof fetch === 'function') {
|
|
1803
|
+
fetch(endpoint, {
|
|
1804
|
+
method: 'POST',
|
|
1805
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1806
|
+
body,
|
|
1807
|
+
keepalive: true,
|
|
1808
|
+
}).catch(() => {})
|
|
1809
|
+
}
|
|
1810
|
+
} catch (e) {}
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
levels.forEach((level) => {
|
|
1814
|
+
const original = console[level]
|
|
1815
|
+
if (!original || typeof original !== 'function') return
|
|
1816
|
+
console[level] = (...args) => {
|
|
1817
|
+
try {
|
|
1818
|
+
original.apply(console, args)
|
|
1819
|
+
} finally {
|
|
1820
|
+
send(level, args)
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
})
|
|
1824
|
+
|
|
1825
|
+
window.addEventListener('error', (event) => {
|
|
1826
|
+
send('error', [event.error || event.message])
|
|
1827
|
+
})
|
|
1828
|
+
window.addEventListener('unhandledrejection', (event) => {
|
|
1829
|
+
send('error', [event.reason])
|
|
1830
|
+
})
|
|
1831
|
+
})()
|
|
1832
|
+
</script>`),
|
|
1833
|
+
setupMiddlewares: (middlewares)=>[
|
|
1834
|
+
(req, res, next)=>{
|
|
1835
|
+
if ('POST' !== req.method || !req.url?.startsWith(BROWSER_LOGS_ENDPOINT)) return next();
|
|
1836
|
+
let raw = '';
|
|
1837
|
+
req.on('data', (chunk)=>{
|
|
1838
|
+
raw += chunk.toString();
|
|
1839
|
+
}), req.on('end', async ()=>{
|
|
1840
|
+
try {
|
|
1841
|
+
let { level, time, args = [] } = JSON.parse(raw || '{}'), formattedArgs = await Promise.all(args.map(async (item)=>{
|
|
1842
|
+
if (!item) return '';
|
|
1843
|
+
if ('error' === item.type) {
|
|
1844
|
+
let { locationSuffix, stackString } = await resolveErrorLocationAndStack(item), msg = item.message || '', suffix = locationSuffix ? msg ? ` ${locationSuffix}` : locationSuffix : '';
|
|
1845
|
+
return `${msg}${suffix}${stackString}`;
|
|
1846
|
+
}
|
|
1847
|
+
switch(item.type){
|
|
1848
|
+
case 'string':
|
|
1849
|
+
return ((message)=>{
|
|
1850
|
+
let trimmed = message.trim();
|
|
1851
|
+
if (!trimmed) return !0;
|
|
1852
|
+
let normalizedFirstLine = (trimmed.split('\n', 1)[0]?.trim() || '').replace(/`/g, '');
|
|
1853
|
+
return /^at\s+/.test(normalizedFirstLine);
|
|
1854
|
+
})(item.message) ? '' : item.message;
|
|
1855
|
+
case 'null':
|
|
1856
|
+
return null;
|
|
1857
|
+
case 'undefined':
|
|
1858
|
+
return;
|
|
1859
|
+
case 'object':
|
|
1860
|
+
return JSON.parse(item.message || '');
|
|
1861
|
+
default:
|
|
1862
|
+
return item.message;
|
|
1863
|
+
}
|
|
1864
|
+
})), outputArgs = ((args)=>{
|
|
1865
|
+
if (args.length < 2 || 'string' != typeof args[0]) return args;
|
|
1866
|
+
let template = args[0];
|
|
1867
|
+
if (!/%[sdifoOj%c%]/.test(template)) return args;
|
|
1868
|
+
let rest = args.slice(1), cleanedTemplate = '';
|
|
1869
|
+
for(let i = 0; i < template.length; i++){
|
|
1870
|
+
let ch = template[i];
|
|
1871
|
+
if ('%' !== ch || i + 1 >= template.length) {
|
|
1872
|
+
cleanedTemplate += ch;
|
|
1873
|
+
continue;
|
|
1874
|
+
}
|
|
1875
|
+
let next = template[i + 1];
|
|
1876
|
+
if ('%' === next) {
|
|
1877
|
+
cleanedTemplate += '%%', i++;
|
|
1878
|
+
continue;
|
|
1879
|
+
}
|
|
1880
|
+
if ('c' === next) {
|
|
1881
|
+
rest.length > 0 && rest.shift(), i++;
|
|
1882
|
+
continue;
|
|
1883
|
+
}
|
|
1884
|
+
cleanedTemplate += `%${next}`, i++;
|
|
1885
|
+
}
|
|
1886
|
+
return [
|
|
1887
|
+
format(cleanedTemplate, ...rest)
|
|
1888
|
+
];
|
|
1889
|
+
})(formattedArgs), prefix = colors.dim(`[browser ${time}]`);
|
|
1890
|
+
switch(level){
|
|
1891
|
+
case 'error':
|
|
1892
|
+
logger_logger.error(`${prefix} ${outputArgs.join(' ')}`);
|
|
1893
|
+
break;
|
|
1894
|
+
case 'warn':
|
|
1895
|
+
logger_logger.warn(`${prefix} ${outputArgs.join(' ')}`);
|
|
1896
|
+
break;
|
|
1897
|
+
case 'debug':
|
|
1898
|
+
logger_logger.info(prefix, ...outputArgs);
|
|
1899
|
+
}
|
|
1900
|
+
} catch (e) {
|
|
1901
|
+
logger_logger.error('Failed to parse browser log payload', e);
|
|
1902
|
+
} finally{
|
|
1903
|
+
res.statusCode = 204, res.end();
|
|
1904
|
+
}
|
|
1905
|
+
});
|
|
1906
|
+
},
|
|
1907
|
+
...middlewares
|
|
1908
|
+
]
|
|
1909
|
+
}),
|
|
1910
|
+
(shouldTransformDeepImport = !1, preJsAssets = [], jsAssets = [], cssAssets = [], bundledDepsCachePath = '', deepImportPkgPattern = [
|
|
1911
|
+
...SPECIAL_NO_ENTRY_DEPS
|
|
1912
|
+
].sort((a, b)=>b.length - a.length).map((name)=>name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), deepImportRegex = RegExp(`import\\s+([a-zA-Z0-9_$]+)\\s+from\\s+['"]((${deepImportPkgPattern})/[^'"]+)['"]`, 'g'), {
|
|
1913
|
+
name: 'unpack:prebundle',
|
|
1914
|
+
apply: (config, { command })=>'dev' === command && !!config.dev?.prebundle,
|
|
1915
|
+
config: async (config, context)=>{
|
|
1916
|
+
var externals;
|
|
1917
|
+
let existExternals, cacheDir, root = config.root;
|
|
1918
|
+
bundledDepsCachePath = node_path.resolve(root, context.cachePath, 'umd');
|
|
1919
|
+
let count = {
|
|
1920
|
+
total: 0,
|
|
1921
|
+
bundled: 0
|
|
1922
|
+
}, failedDepsJsonPath = node_path.resolve(root, context.cachePath, 'failed-deps.json'), failedDeps = [], failedCache = node_fs.existsSync(failedDepsJsonPath) ? JSON.parse(node_fs.readFileSync(failedDepsJsonPath, 'utf-8')) : {}, updateProgress = ()=>{
|
|
1923
|
+
let errMsg = failedDeps.length > 0 ? ` failed: ${failedDeps.join(', ')}` : '';
|
|
1924
|
+
logUpdate(`${colors.magenta('»')} optimizing dependencies (${count.bundled}/${count.total})${errMsg}`), count.total === count.bundled + failedDeps.length && console.log();
|
|
1925
|
+
}, userOptions = isPlainObject(config.dev?.prebundle) ? config.dev.prebundle : {}, ignoreCSSDeps = userOptions.ignoreCSS || [], packageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'package.json'), 'utf-8')), excludeDeps = [
|
|
1926
|
+
...(externals = config.externals, existExternals = new Set(), Array.isArray(externals) ? externals.forEach((item)=>{
|
|
1927
|
+
isPlainObject(item) && Object.keys(item).forEach((key)=>{
|
|
1928
|
+
existExternals.add(key);
|
|
1929
|
+
});
|
|
1930
|
+
}) : isPlainObject(externals) && Object.keys(externals).forEach((key)=>{
|
|
1931
|
+
existExternals.add(key);
|
|
1932
|
+
}), Array.from(existExternals) || []),
|
|
1933
|
+
...userOptions.exclude || []
|
|
1934
|
+
], needBundleDeps = (Array.isArray(userOptions.include) && userOptions.include.length > 0 ? userOptions.include : Object.keys(packageJson.dependencies || {})).filter((pkgName)=>!excludeDeps.includes(pkgName)).map((pkgName)=>{
|
|
1935
|
+
let depPackageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'node_modules', pkgName, 'package.json'), 'utf-8')), version = depPackageJson.version;
|
|
1936
|
+
if (failedCache[pkgName] === version) return;
|
|
1937
|
+
let entry = ((packageJson)=>{
|
|
1938
|
+
if (packageJson.module) return packageJson.module;
|
|
1939
|
+
if (packageJson.exports) {
|
|
1940
|
+
if (isString(packageJson.exports)) return packageJson.exports;
|
|
1941
|
+
let defaultExport = packageJson.exports['.'];
|
|
1942
|
+
if (defaultExport) {
|
|
1943
|
+
if (isString(defaultExport)) return defaultExport;
|
|
1944
|
+
if (isString(defaultExport.import)) return defaultExport.import;
|
|
1945
|
+
if (isString(defaultExport.browser)) return defaultExport.browser;
|
|
1946
|
+
if (isString(defaultExport.default)) return defaultExport.default;
|
|
1947
|
+
}
|
|
1948
|
+
if (isString(packageJson.exports.default)) return packageJson.exports.default;
|
|
1949
|
+
}
|
|
1950
|
+
if (packageJson.main) return packageJson.main;
|
|
1951
|
+
})(depPackageJson);
|
|
1952
|
+
if (!entry) {
|
|
1953
|
+
if (SPECIAL_NO_ENTRY_DEPS.includes(pkgName)) {
|
|
1954
|
+
let syntheticEntry = (({ root, pkgName })=>{
|
|
1955
|
+
let pkgDir = node_path.resolve(root, 'node_modules', pkgName);
|
|
1956
|
+
if (!node_fs.existsSync(pkgDir)) return;
|
|
1957
|
+
let indexPath = node_path.resolve(pkgDir, 'index.ts'), content = globSync('**/*.{js,jsx,ts,tsx}', {
|
|
1958
|
+
cwd: pkgDir,
|
|
1959
|
+
absolute: !1
|
|
1960
|
+
}).filter((p)=>{
|
|
1961
|
+
let base = node_path.basename(p);
|
|
1962
|
+
return !(p.endsWith('.d.ts') || /^index\.(t|j)sx?$/.test(base)) && 'package.json' !== base;
|
|
1963
|
+
}).map((file)=>{
|
|
1964
|
+
let normalized = file.split(node_path.sep).join('/'), exportName = pathToExportIdentifier(normalized);
|
|
1965
|
+
return `export { default as ${exportName} } from './${normalized}'`;
|
|
1966
|
+
}).join('\n');
|
|
1967
|
+
return node_fs.writeFileSync(indexPath, content, 'utf-8'), indexPath;
|
|
1968
|
+
})({
|
|
1969
|
+
root,
|
|
1970
|
+
pkgName
|
|
1971
|
+
});
|
|
1972
|
+
if (syntheticEntry) return shouldTransformDeepImport = !0, {
|
|
1973
|
+
name: pkgName,
|
|
1974
|
+
entry: syntheticEntry,
|
|
1975
|
+
version
|
|
1976
|
+
};
|
|
1977
|
+
}
|
|
1978
|
+
failedCache[pkgName] = version;
|
|
1979
|
+
return;
|
|
1980
|
+
}
|
|
1981
|
+
return {
|
|
1982
|
+
name: pkgName,
|
|
1983
|
+
entry: node_path.resolve(root, 'node_modules', pkgName, entry),
|
|
1984
|
+
version
|
|
1985
|
+
};
|
|
1986
|
+
}).filter(Boolean), depExternals = Object.fromEntries(Array.from(new Set([
|
|
1987
|
+
'react',
|
|
1988
|
+
'react-dom',
|
|
1989
|
+
'react-router-dom',
|
|
1990
|
+
...Array.isArray(userOptions.externals) ? userOptions.externals : []
|
|
1991
|
+
])).map((pkg)=>[
|
|
1992
|
+
pkg,
|
|
1993
|
+
getExternalValue(pkg)
|
|
1994
|
+
])), bundledDeps = await Promise.all(needBundleDeps.map((depInfo)=>(({ name, entry, version })=>new Promise((resolve)=>{
|
|
1995
|
+
let pkgDir = node_path.resolve(bundledDepsCachePath, name), outDir = node_path.resolve(pkgDir, version), getResult = ()=>({
|
|
1996
|
+
name,
|
|
1997
|
+
assets: globSync('**/index.{js,css}', {
|
|
1998
|
+
cwd: outDir,
|
|
1999
|
+
absolute: !0
|
|
2000
|
+
})
|
|
2001
|
+
});
|
|
2002
|
+
if (node_fs.existsSync(outDir)) return void resolve(getResult());
|
|
2003
|
+
count.total++, updateProgress();
|
|
2004
|
+
let getSwcOptions = ({ tsx })=>({
|
|
2005
|
+
jsc: {
|
|
2006
|
+
parser: {
|
|
2007
|
+
tsx,
|
|
2008
|
+
syntax: "typescript",
|
|
2009
|
+
dynamicImport: !0,
|
|
2010
|
+
decorators: !0
|
|
2011
|
+
},
|
|
2012
|
+
transform: {
|
|
2013
|
+
react: {
|
|
2014
|
+
runtime: 'automatic'
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
}), compiler = rspack({
|
|
2019
|
+
entry: {
|
|
2020
|
+
index: entry
|
|
2021
|
+
},
|
|
2022
|
+
context: root,
|
|
2023
|
+
mode: 'development',
|
|
2024
|
+
output: {
|
|
2025
|
+
clean: !0,
|
|
2026
|
+
path: outDir,
|
|
2027
|
+
pathinfo: !1,
|
|
2028
|
+
library: {
|
|
2029
|
+
name: getExternalLibraryName(name),
|
|
2030
|
+
type: 'umd',
|
|
2031
|
+
umdNamedDefine: !0
|
|
2032
|
+
},
|
|
2033
|
+
globalObject: 'this'
|
|
2034
|
+
},
|
|
2035
|
+
devtool: !1,
|
|
2036
|
+
module: {
|
|
2037
|
+
rules: [
|
|
2038
|
+
{
|
|
2039
|
+
test: JS_REGEX,
|
|
2040
|
+
use: [
|
|
2041
|
+
{
|
|
2042
|
+
loader: 'builtin:swc-loader',
|
|
2043
|
+
options: getSwcOptions({
|
|
2044
|
+
tsx: !1
|
|
2045
|
+
})
|
|
2046
|
+
}
|
|
2047
|
+
]
|
|
2048
|
+
},
|
|
2049
|
+
{
|
|
2050
|
+
test: JSX_REGEX,
|
|
2051
|
+
use: [
|
|
2052
|
+
{
|
|
2053
|
+
loader: 'builtin:swc-loader',
|
|
2054
|
+
options: getSwcOptions({
|
|
2055
|
+
tsx: !0
|
|
2056
|
+
})
|
|
2057
|
+
}
|
|
2058
|
+
]
|
|
2059
|
+
},
|
|
2060
|
+
{
|
|
2061
|
+
test: /\.less$/,
|
|
2062
|
+
type: 'css/auto',
|
|
2063
|
+
use: [
|
|
2064
|
+
{
|
|
2065
|
+
loader: getCompiledPkgPath('less-loader'),
|
|
2066
|
+
options: {
|
|
2067
|
+
lessOptions: {
|
|
2068
|
+
javascriptEnabled: !0
|
|
2069
|
+
},
|
|
2070
|
+
implementation: getUserDepPath(root, 'less')
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
]
|
|
2074
|
+
},
|
|
2075
|
+
{
|
|
2076
|
+
test: /\.s[ac]ss$/i,
|
|
2077
|
+
type: 'css/auto',
|
|
2078
|
+
use: [
|
|
2079
|
+
{
|
|
2080
|
+
loader: getCompiledPkgPath('sass-loader'),
|
|
2081
|
+
options: {
|
|
2082
|
+
api: 'modern-compiler',
|
|
2083
|
+
implementation: getUserDepPath(root, [
|
|
2084
|
+
'sass-embedded',
|
|
2085
|
+
'sass'
|
|
2086
|
+
])
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
]
|
|
2090
|
+
}
|
|
2091
|
+
]
|
|
2092
|
+
},
|
|
2093
|
+
optimization: {
|
|
2094
|
+
splitChunks: !1
|
|
2095
|
+
},
|
|
2096
|
+
experiments: {
|
|
2097
|
+
css: !0
|
|
2098
|
+
},
|
|
2099
|
+
externals: depExternals
|
|
2100
|
+
});
|
|
2101
|
+
compiler.run((_, stats)=>{
|
|
2102
|
+
let isFailed = !1;
|
|
2103
|
+
stats?.hasErrors() ? (isFailed = !0, failedDeps.push(name), failedCache[name] = version, removeDir(outDir)) : count.bundled++, updateProgress(), compiler.close(()=>{
|
|
2104
|
+
resolve(isFailed ? void 0 : getResult());
|
|
2105
|
+
});
|
|
2106
|
+
});
|
|
2107
|
+
}))(depInfo)));
|
|
2108
|
+
cacheDir = node_path.dirname(failedDepsJsonPath), node_fs.existsSync(cacheDir) || node_fs.mkdirSync(cacheDir, {
|
|
2109
|
+
recursive: !0
|
|
2110
|
+
}), node_fs.writeFileSync(failedDepsJsonPath, JSON.stringify(failedCache, null, 2), 'utf-8');
|
|
2111
|
+
let externals1 = {};
|
|
2112
|
+
bundledDeps.filter(Boolean).forEach((dep)=>{
|
|
2113
|
+
dep && (externals1[dep.name] = getExternalValue(dep.name), dep.assets.forEach((absPath)=>{
|
|
2114
|
+
let relativePath = node_path.relative(bundledDepsCachePath, absPath), preDeps = [
|
|
2115
|
+
'react',
|
|
2116
|
+
'react-dom',
|
|
2117
|
+
'react-router-dom'
|
|
2118
|
+
], serverPath = `/umd/${relativePath}`;
|
|
2119
|
+
switch(node_path.extname(relativePath)){
|
|
2120
|
+
case '.js':
|
|
2121
|
+
preDeps.includes(dep.name) ? preJsAssets.push({
|
|
2122
|
+
path: serverPath,
|
|
2123
|
+
order: preDeps.indexOf(dep.name)
|
|
2124
|
+
}) : jsAssets.push(serverPath);
|
|
2125
|
+
break;
|
|
2126
|
+
case '.css':
|
|
2127
|
+
ignoreCSSDeps.includes(dep.name) || cssAssets.push(serverPath);
|
|
2128
|
+
}
|
|
2129
|
+
}));
|
|
2130
|
+
});
|
|
2131
|
+
let existingExternals = config.externals ? Array.isArray(config.externals) ? config.externals : [
|
|
2132
|
+
config.externals
|
|
2133
|
+
] : [];
|
|
2134
|
+
return config.externals = [
|
|
2135
|
+
externals1,
|
|
2136
|
+
...existingExternals
|
|
2137
|
+
], config;
|
|
2138
|
+
},
|
|
2139
|
+
transform: (code, id)=>shouldTransformDeepImport && JSX_REGEX.test(id) && code.includes('import') && SPECIAL_NO_ENTRY_DEPS.some((pkg)=>code.includes(pkg)) ? code.replace(deepImportRegex, (_, localName, importPath, pkgName)=>{
|
|
2140
|
+
let exportName = pathToExportIdentifier(importPath.slice(pkgName.length + 1));
|
|
2141
|
+
return `import { ${exportName} as ${localName} } from '${pkgName}'`;
|
|
2142
|
+
}) : null,
|
|
2143
|
+
transformHtml: (html)=>injectToHead(html, preJsAssets.sort((a, b)=>a.order - b.order).map((item)=>item.path).map((item)=>`<script defer src="${item}"></script>`).join('')),
|
|
2144
|
+
setupMiddlewares: (middlewares)=>[
|
|
2145
|
+
(req, res, next)=>{
|
|
2146
|
+
if ('string' != typeof req.url) return void next();
|
|
2147
|
+
let url = new URL(req.url, 'http://localhost');
|
|
2148
|
+
if (!url.pathname.startsWith("/umd/")) return void next();
|
|
2149
|
+
let relativePath = url.pathname.replace("/umd/", '');
|
|
2150
|
+
if (relativePath.includes('..')) {
|
|
2151
|
+
res.statusCode = 403, res.end();
|
|
2152
|
+
return;
|
|
2153
|
+
}
|
|
2154
|
+
let filePath = node_path.join(bundledDepsCachePath, relativePath);
|
|
2155
|
+
if (!node_fs.existsSync(filePath)) return void next();
|
|
2156
|
+
let stat = node_fs.statSync(filePath);
|
|
2157
|
+
if (!stat.isFile()) return void next();
|
|
2158
|
+
let mtime = stat.mtime.toUTCString(), ext = node_path.extname(filePath);
|
|
2159
|
+
if (res.setHeader('Cache-Control', 'no-cache'), res.setHeader('Last-Modified', mtime), '.js' === ext && res.setHeader('Content-Type', "application/javascript"), '.css' === ext && res.setHeader('Content-Type', 'text/css'), req.headers['if-modified-since'] === mtime) {
|
|
2160
|
+
res.statusCode = 304, res.end();
|
|
2161
|
+
return;
|
|
2162
|
+
}
|
|
2163
|
+
res.statusCode = 200, node_fs.createReadStream(filePath).pipe(res);
|
|
2164
|
+
},
|
|
2165
|
+
...middlewares
|
|
2166
|
+
],
|
|
2167
|
+
bundlerConfig: (config)=>{
|
|
2168
|
+
let PLUGIN_NAME = 'InjectAssetsPlugin';
|
|
2169
|
+
return config.plugins.push({
|
|
2170
|
+
apply: (compiler)=>{
|
|
2171
|
+
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
|
|
2172
|
+
rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(PLUGIN_NAME, async (args)=>(args.assets.js.unshift(...jsAssets), args.assets.css.unshift(...cssAssets), args));
|
|
2173
|
+
});
|
|
2174
|
+
}
|
|
2175
|
+
}), config;
|
|
2176
|
+
}
|
|
2177
|
+
}),
|
|
2178
|
+
(root = '', {
|
|
2179
|
+
name: 'unpack:file-size',
|
|
2180
|
+
apply: (config, { mode })=>'production' === mode && config.performance?.printFileSize,
|
|
2181
|
+
configResolved (config) {
|
|
2182
|
+
root = config.root;
|
|
2183
|
+
},
|
|
2184
|
+
buildEnd: async (options)=>{
|
|
2185
|
+
let { stats } = options, chunkGroups = [
|
|
2186
|
+
{
|
|
2187
|
+
type: 'HTML',
|
|
2188
|
+
color: 'green',
|
|
2189
|
+
chunks: []
|
|
2190
|
+
},
|
|
2191
|
+
{
|
|
2192
|
+
type: 'Assets',
|
|
2193
|
+
color: 'yellow',
|
|
2194
|
+
chunks: []
|
|
2195
|
+
},
|
|
2196
|
+
{
|
|
2197
|
+
type: 'CSS',
|
|
2198
|
+
color: 'magenta',
|
|
2199
|
+
chunks: []
|
|
2200
|
+
},
|
|
2201
|
+
{
|
|
2202
|
+
type: 'JS',
|
|
2203
|
+
color: 'cyan',
|
|
2204
|
+
chunks: []
|
|
2205
|
+
}
|
|
2206
|
+
], chunkGroupMap = chunkGroups.reduce((acc, cur)=>(acc[cur.type] = cur, acc), {}), distPath = stats.compilation.outputOptions.path, distFolder = node_path.relative(root, distPath), assets = Object.entries(stats.compilation.assets), longest = 0, totalSize = 0, totalCompressedSize = 0;
|
|
2207
|
+
logUpdate('computing gzip size...'), await Promise.all(assets.map(async ([assetName, value])=>{
|
|
2208
|
+
let content, compressedSize, filePath = assetName.split('?')[0];
|
|
2209
|
+
try {
|
|
2210
|
+
content = value.source();
|
|
2211
|
+
} catch {
|
|
2212
|
+
content = node_fs.readFileSync(node_path.join(distPath, filePath));
|
|
2213
|
+
}
|
|
2214
|
+
let size = Buffer.byteLength(content);
|
|
2215
|
+
compressedSize = COMPRESSIBLE_REGEX.test(filePath) ? await getCompressedSize(content) : size, totalSize += size, totalCompressedSize += compressedSize;
|
|
2216
|
+
let chunk = {
|
|
2217
|
+
name: node_path.basename(filePath),
|
|
2218
|
+
path: `${distFolder}/${filePath}`,
|
|
2219
|
+
size,
|
|
2220
|
+
compressedSize
|
|
2221
|
+
};
|
|
2222
|
+
switch(chunk.path.length > longest && (longest = chunk.path.length), node_path.extname(filePath)){
|
|
2223
|
+
case '.html':
|
|
2224
|
+
chunkGroupMap.HTML.chunks.push(chunk);
|
|
2225
|
+
break;
|
|
2226
|
+
case '.css':
|
|
2227
|
+
chunkGroupMap.CSS.chunks.push(chunk);
|
|
2228
|
+
break;
|
|
2229
|
+
case '.js':
|
|
2230
|
+
case '.wasm':
|
|
2231
|
+
chunkGroupMap.JS.chunks.push(chunk);
|
|
2232
|
+
break;
|
|
2233
|
+
default:
|
|
2234
|
+
chunkGroupMap.Assets.chunks.push(chunk);
|
|
2235
|
+
}
|
|
2236
|
+
})), logUpdate(`✓ computed gzip size (${assets.length})`), console.log();
|
|
2237
|
+
let sizePad = displaySize(totalSize).length, compressPad = displaySize(totalCompressedSize).length;
|
|
2238
|
+
chunkGroups.forEach((group)=>{
|
|
2239
|
+
group.chunks.sort((a, b)=>a.size - b.size).forEach((chunk)=>{
|
|
2240
|
+
let isLarge = 'JS' === group.type && chunk.size / 1000 > 500, relativeOutDir = node_path.dirname(chunk.path) + '/', log = colors.dim(relativeOutDir);
|
|
2241
|
+
log += colors[group.color](chunk.name.padEnd(longest + 2 - relativeOutDir.length)), log += colors[isLarge ? 'yellow' : 'dim'](displaySize(chunk.size).padStart(sizePad)), console.log(log += colors.dim(` │ gzip: ${displaySize(chunk.compressedSize).padStart(compressPad)}`));
|
|
2242
|
+
});
|
|
2243
|
+
});
|
|
2244
|
+
let log = colors.blue('Total'.padEnd(longest + 2));
|
|
2245
|
+
log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` │ gzip: ${displaySize(totalCompressedSize)}`));
|
|
2246
|
+
}
|
|
2247
|
+
})
|
|
1940
2248
|
]
|
|
1941
2249
|
}, userConfig),
|
|
1942
2250
|
_context
|
|
@@ -1947,14 +2255,14 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
|
|
|
1947
2255
|
let mode = watch ? 'development' : 'production';
|
|
1948
2256
|
setNodeEnv(mode);
|
|
1949
2257
|
let config = resolveConfig(mode);
|
|
1950
|
-
console.log(colors.brand(`${callerName} v3.
|
|
2258
|
+
console.log(colors.brand(`${callerName} v3.8.1${config.performance?.cache ? ' ϟ' : ''}`), colors.cyan(`building for ${mode}...`)), await unpackBuild(config);
|
|
1951
2259
|
},
|
|
1952
2260
|
dev: async ()=>{
|
|
1953
|
-
|
|
2261
|
+
setUnpackStartTime(performance.now());
|
|
1954
2262
|
let mode = 'development';
|
|
1955
2263
|
setNodeEnv(mode), setDevServer(!0);
|
|
1956
2264
|
let config = resolveConfig(mode);
|
|
1957
|
-
await unpackDev(config);
|
|
2265
|
+
return await unpackDev(config);
|
|
1958
2266
|
},
|
|
1959
2267
|
clean: ()=>{
|
|
1960
2268
|
let root = userConfig.root || cwd, relativeDir = _context.cachePath, absDir = node_path.resolve(root, relativeDir);
|
|
@@ -1975,5 +2283,5 @@ async function createChokidar(pathOrGlobs, root = process.cwd(), options) {
|
|
|
1975
2283
|
...options
|
|
1976
2284
|
});
|
|
1977
2285
|
}
|
|
1978
|
-
var
|
|
1979
|
-
export { CSS_MODULES_LOCAL_IDENT_NAME, CSS_MODULES_REGEX, DEFAULT_DEV_HOST, DEV_DEFAULT_FILENAME, EXPORT_LOCALS_CONVENTION,
|
|
2286
|
+
var src_CSS_NAMED_EXPORT = !1;
|
|
2287
|
+
export { CSS_MODULES_LOCAL_IDENT_NAME, CSS_MODULES_REGEX, DEFAULT_DEV_HOST, DEV_DEFAULT_FILENAME, EXPORT_LOCALS_CONVENTION, JSX_REGEX, JS_REGEX, NODE_MODULES_REGEX, PROD_DEFAULT_FILENAME, SCRIPT_REGEX, TEMPLATE_CONTENT, addRestartCleaner, cleanUpBeforeRestart, clearLine, colors, convertBasicAnsiColors, createChokidar, createUnpack, debounce, defineConfig, esVersionToBrowserslist, findExists, getAddressUrls, getCompiledPkgPath, getCurrentUnpackConfig, getHtmlTemplateOrContent, getIpv4Interfaces, getNodeEnv, getOrSetDefault, getPathInJs, getPort, getTime, getUnpackStartTime, getUserDepPath, getUserDepVersion, injectToHead, isBoolean, isCSSModules, isDebug, isDev, isEmptyDir, isFileExists, isFileSync, isFunction, isNodeVersionAtLeast, isObject, isPlainObject, isRegExp, isString, isUndefined, isWatch, isWin, launchEditor, loadConfig, logUpdate, logger_LogColor as LogColor, logger_logger as logger, mergeConfig, normalizePublicPath, openBrowser, pLimit, pathExists, pathToExportIdentifier, prettyTime, printServerUrls, removeDir, resolveConfigPath, rspack, set, setCurrentUnpackConfig, setDevServer, setNodeEnv, setUnpackStartTime, setupCliShortcuts, src_CSS_NAMED_EXPORT as CSS_NAMED_EXPORT, trackPerformance, utils_isDevServer as isDevServer, utils_isProd as isProd };
|