@unpackjs/core 3.9.2 → 4.1.0
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/bin/unpack.js +8 -0
- package/compiled/css-loader/index.js +20 -20
- package/compiled/less-loader/index.js +8 -8
- package/compiled/postcss-loader/index.js +49 -52
- package/compiled/sass-loader/index.js +8 -8
- package/dist/index.js +889 -651
- package/dist/transformLoader.js +1 -1
- package/dist/typedCssModulesLoader.js +117 -10
- package/dist-types/bundler-config/helpers.d.ts.map +1 -1
- package/dist-types/bundler-config/index.d.ts.map +1 -1
- package/dist-types/bundler-config/loaders/typedCssModulesLoader.d.ts.map +1 -1
- package/dist-types/bundler-config/{experimentCss.d.ts → nativeCss.d.ts} +2 -2
- package/dist-types/bundler-config/nativeCss.d.ts.map +1 -0
- package/dist-types/cli/index.d.ts +2 -0
- package/dist-types/cli/index.d.ts.map +1 -0
- package/dist-types/cli/injectFramework.d.ts +6 -0
- package/dist-types/cli/injectFramework.d.ts.map +1 -0
- package/dist-types/{cliShortcuts.d.ts → cli/shortcuts.d.ts} +1 -1
- package/dist-types/cli/shortcuts.d.ts.map +1 -0
- package/dist-types/createUnpack.d.ts.map +1 -1
- package/dist-types/index.d.ts +1 -1
- package/dist-types/index.d.ts.map +1 -1
- package/dist-types/plugin.d.ts.map +1 -1
- package/dist-types/plugins/fileSize.d.ts.map +1 -1
- package/dist-types/plugins/glob.d.ts +3 -0
- package/dist-types/plugins/glob.d.ts.map +1 -0
- package/dist-types/plugins/prebundle.d.ts.map +1 -1
- package/dist-types/plugins/svgIcons.d.ts +9 -0
- package/dist-types/plugins/svgIcons.d.ts.map +1 -0
- package/dist-types/types/config.d.ts +33 -12
- package/dist-types/types/config.d.ts.map +1 -1
- package/dist-types/types/plugin.d.ts +2 -1
- package/dist-types/types/plugin.d.ts.map +1 -1
- package/dist-types/utils.d.ts +1 -1
- package/dist-types/utils.d.ts.map +1 -1
- package/package.json +9 -4
- package/dist-types/bundler-config/experimentCss.d.ts.map +0 -1
- package/dist-types/cliShortcuts.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -7,15 +7,16 @@ import * as __rspack_external__compiled_launch_editor_index_js_29002383 from "..
|
|
|
7
7
|
import * as __rspack_external__compiled_webpack_merge_index_js_efd91626 from "../compiled/webpack-merge/index.js";
|
|
8
8
|
import { __webpack_require__ } from "./rslib-runtime.js";
|
|
9
9
|
import { rspack } from "@rspack/core";
|
|
10
|
-
import
|
|
10
|
+
import cac from "cac";
|
|
11
11
|
import node_fs from "node:fs";
|
|
12
|
+
import node_readline from "node:readline";
|
|
12
13
|
import node_os, { platform } from "node:os";
|
|
13
14
|
import portfinder from "portfinder";
|
|
15
|
+
import { glob as external_tinyglobby_glob, globSync } from "tinyglobby";
|
|
14
16
|
import { format, promisify } from "node:util";
|
|
15
17
|
import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
|
|
16
18
|
import { parse } from "stacktrace-parser";
|
|
17
19
|
import node_zlib from "node:zlib";
|
|
18
|
-
import { glob, globSync } from "tinyglobby";
|
|
19
20
|
import { expand } from "dotenv-expand";
|
|
20
21
|
import node_assert from "node:assert";
|
|
21
22
|
import { RspackDevServer } from "@rspack/dev-server";
|
|
@@ -95,15 +96,6 @@ function convertBasicAnsiColors(input) {
|
|
|
95
96
|
return `${styleSeq}${open}`;
|
|
96
97
|
}) : '';
|
|
97
98
|
}
|
|
98
|
-
let restartCleaners = [], addRestartCleaner = (...cleaners)=>{
|
|
99
|
-
restartCleaners.push(...cleaners);
|
|
100
|
-
}, cleanUpBeforeRestart = async ()=>{
|
|
101
|
-
await Promise.all(restartCleaners.map((cleaner)=>cleaner())), restartCleaners.length = 0;
|
|
102
|
-
}, currentUnpackConfig = {}, getCurrentUnpackConfig = ()=>currentUnpackConfig, setCurrentUnpackConfig = (config)=>{
|
|
103
|
-
currentUnpackConfig = config;
|
|
104
|
-
}, unpackStartTime = 0, getUnpackStartTime = ()=>unpackStartTime, setUnpackStartTime = (time)=>{
|
|
105
|
-
unpackStartTime = time;
|
|
106
|
-
};
|
|
107
99
|
var LogColor, logger_LogColor = ((LogColor = {}).error = "red", LogColor.warn = "yellow", LogColor.info = "cyan", LogColor.ready = "green", LogColor.event = "magenta", LogColor.wait = "blue", LogColor);
|
|
108
100
|
let CSS_MODULES_LOCAL_IDENT_NAME = '[path][name]__[local]--[hash:5]', CSS_MODULES_EXPORTS_CONVENTION = 'camel-case', DEV_DEFAULT_FILENAME = {
|
|
109
101
|
js: 'js/[name].js',
|
|
@@ -128,7 +120,7 @@ let CSS_MODULES_LOCAL_IDENT_NAME = '[path][name]__[local]--[hash:5]', CSS_MODULE
|
|
|
128
120
|
</body>
|
|
129
121
|
</html>`, JS_REGEX = /\.[jt]s$/, JSX_REGEX = /\.[jt]sx$/, SCRIPT_REGEX = /\.[jt]sx?$/;
|
|
130
122
|
var utils_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
131
|
-
let { merge:
|
|
123
|
+
let { merge: utils_mergeConfig } = __webpack_require__("compiled/webpack-merge"), { default: launchEditor } = __webpack_require__("compiled/launch-editor"), getNodeEnv = ()=>process.env.NODE_ENV, setNodeEnv = (env)=>{
|
|
132
124
|
process.env.NODE_ENV = env;
|
|
133
125
|
}, setDevServer = (isDevServer)=>{
|
|
134
126
|
process.env.DEV_SERVER = isDevServer ? 'true' : 'false';
|
|
@@ -376,58 +368,6 @@ let injectToHead = (html, script)=>html.replace(/<head(\s*[^>]*)>/i, (match)=>`$
|
|
|
376
368
|
})(type, message, ...args);
|
|
377
369
|
};
|
|
378
370
|
}), logger);
|
|
379
|
-
async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer }) {
|
|
380
|
-
let shortcuts = [
|
|
381
|
-
restartServer ? {
|
|
382
|
-
key: 'r',
|
|
383
|
-
description: 'restart server',
|
|
384
|
-
action: restartServer
|
|
385
|
-
} : null,
|
|
386
|
-
{
|
|
387
|
-
key: 'u',
|
|
388
|
-
description: 'show server url',
|
|
389
|
-
action: printUrls
|
|
390
|
-
},
|
|
391
|
-
{
|
|
392
|
-
key: 'o',
|
|
393
|
-
description: 'open in browser',
|
|
394
|
-
action: openPage
|
|
395
|
-
},
|
|
396
|
-
{
|
|
397
|
-
key: 'c',
|
|
398
|
-
description: 'clear console',
|
|
399
|
-
action: ()=>{
|
|
400
|
-
logger_logger.clear();
|
|
401
|
-
}
|
|
402
|
-
},
|
|
403
|
-
{
|
|
404
|
-
key: 'q',
|
|
405
|
-
description: 'quit',
|
|
406
|
-
action: async ()=>{
|
|
407
|
-
try {
|
|
408
|
-
await closeServer();
|
|
409
|
-
} finally{
|
|
410
|
-
process.exit(0);
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
].filter(Boolean), colorPrefix = colors.brand(colors.dim('➜'));
|
|
415
|
-
help && console.log(!0 === help ? ` ${colorPrefix} ${colors.dim('press')} ${colors.bold('h + enter')} ${colors.dim('to show help')}` : ` ${colorPrefix} ${help}`);
|
|
416
|
-
let { createInterface } = await import("node:readline"), rl = createInterface({
|
|
417
|
-
input: process.stdin
|
|
418
|
-
});
|
|
419
|
-
rl.on('line', (input)=>{
|
|
420
|
-
if ('h' === input) {
|
|
421
|
-
let message = '\n Shortcuts\n';
|
|
422
|
-
for (let shortcut of shortcuts){
|
|
423
|
-
let fullDescription = `${colors.dim('press')} ${colors.bold(`${shortcut.key} + enter`)} ${colors.dim(`to ${shortcut.description}`)}`;
|
|
424
|
-
message += ` ${fullDescription}\n`;
|
|
425
|
-
}
|
|
426
|
-
console.log(message);
|
|
427
|
-
}
|
|
428
|
-
for (let shortcut of shortcuts)if (input === shortcut.key) return void shortcut.action();
|
|
429
|
-
}), addRestartCleaner(()=>rl.close());
|
|
430
|
-
}
|
|
431
371
|
var config_filename = __rspack_fileURLToPath(import.meta.url);
|
|
432
372
|
async function loadConfig({ cliOptions, command }) {
|
|
433
373
|
'build' === command ? setNodeEnv(cliOptions?.watch ? 'development' : 'production') : (setNodeEnv('development'), setDevServer(!0));
|
|
@@ -528,32 +468,87 @@ let removeDir = (dir)=>{
|
|
|
528
468
|
recursive: !0,
|
|
529
469
|
force: !0
|
|
530
470
|
});
|
|
471
|
+
}, restartCleaners = [], addRestartCleaner = (...cleaners)=>{
|
|
472
|
+
restartCleaners.push(...cleaners);
|
|
473
|
+
}, cleanUpBeforeRestart = async ()=>{
|
|
474
|
+
await Promise.all(restartCleaners.map((cleaner)=>cleaner())), restartCleaners.length = 0;
|
|
475
|
+
}, currentUnpackConfig = {}, getCurrentUnpackConfig = ()=>currentUnpackConfig, setCurrentUnpackConfig = (config)=>{
|
|
476
|
+
currentUnpackConfig = config;
|
|
477
|
+
}, unpackStartTime = 0, getUnpackStartTime = ()=>unpackStartTime, setUnpackStartTime = (time)=>{
|
|
478
|
+
unpackStartTime = time;
|
|
531
479
|
}, STYLE_IMPORT_RE = /import\s+([\s\S]+?)\s+from\s+(['"])(.*?\.(?:css|less|scss|sass))\2/g, TYPE_IMPORT_CLAUSE_RE = /^\s*type\b/, STYLE_EXT_HINTS = [
|
|
532
480
|
'.css',
|
|
533
481
|
'.less',
|
|
534
482
|
'.scss',
|
|
535
483
|
'.sass'
|
|
536
|
-
], BROWSER_LOGS_ENDPOINT = '/__browser_logs__',
|
|
484
|
+
], BROWSER_LOGS_ENDPOINT = '/__browser_logs__', SOURCE_REGEX = /\.(js|jsx|mjs|cjs|ts|tsx|mts|cts|vue|svelte)$/, gzip = promisify(node_zlib.gzip), numberFormatter = new Intl.NumberFormat('en', {
|
|
537
485
|
maximumFractionDigits: 2,
|
|
538
486
|
minimumFractionDigits: 2
|
|
539
487
|
}), displaySize = (bytes)=>`${numberFormatter.format(bytes / 1000)} kB`;
|
|
540
488
|
async function getCompressedSize(content) {
|
|
541
489
|
return (await gzip(content)).length;
|
|
542
490
|
}
|
|
543
|
-
let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i,
|
|
491
|
+
let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i, GLOB_MAGIC_RE = /[*?[\]{}()!@+|]/, normalizeBaseDir = (raw)=>{
|
|
492
|
+
let normalized = raw.replace(/\\/g, '/');
|
|
493
|
+
return normalized && '.' !== normalized ? (normalized.startsWith('/') ? normalized = normalized.replace(/\/{2,}/g, '/') : normalized.startsWith('.') || (normalized = `./${normalized}`), (normalized = normalized.replace(/\/{2,}/g, '/')).endsWith('/') && (normalized = normalized.slice(0, -1)), '.' === normalized ? './' : normalized) : './';
|
|
494
|
+
}, toRegexLiteral = (source)=>`/${source.replace(/\\?\//g, (value)=>'/' === value ? '\\/' : value)}/`, parseGlob = (pattern)=>{
|
|
495
|
+
let normalized = pattern.replace(/\\/g, '/'), isAbs = normalized.startsWith('/'), normalizedForParse = isAbs ? `.${normalized}` : normalized, globIndex = normalizedForParse.search(GLOB_MAGIC_RE), slashIndex = -1 === globIndex ? normalizedForParse.lastIndexOf('/') : normalizedForParse.lastIndexOf('/', globIndex), baseDirRaw = slashIndex >= 0 ? normalizedForParse.slice(0, slashIndex) : '.', globPart = slashIndex >= 0 ? normalizedForParse.slice(slashIndex + 1) : normalizedForParse, recursive = normalizedForParse.includes('**'), baseDir = isAbs ? normalizeBaseDir(`/${baseDirRaw.replace(/^\.\//, '')}`) : normalizeBaseDir(baseDirRaw);
|
|
496
|
+
return {
|
|
497
|
+
baseDir,
|
|
498
|
+
regExpSource: ((glob)=>{
|
|
499
|
+
let expansions;
|
|
500
|
+
if (!glob) return '^\\.\\/.*$';
|
|
501
|
+
let { replaced, expansions: expansions1 } = (expansions = [], {
|
|
502
|
+
replaced: glob.replace(/\{([^}]+)\}/g, (_, inner)=>(expansions.push(inner), `__BRACE_${expansions.length - 1}__`)),
|
|
503
|
+
expansions
|
|
504
|
+
}), source = replaced.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
505
|
+
return source = (source = (source = (source = (source = (source = source.replace(/__BRACE_(\d+)__/g, (_, index)=>{
|
|
506
|
+
let parts = (expansions1[Number(index)] || '').split(',').map((part)=>part.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
507
|
+
return `(${parts.join('|')})`;
|
|
508
|
+
})).replace(/\\\(([^)]+)\\\)\\\?/g, (_, inner)=>`(?:${inner})?`)).replace(/\\\*\\\*\\\//g, '(?:.*\\/)?')).replace(/\\\*\\\*/g, '.*')).replace(/\\\*/g, '[^/]*')).replace(/\\\?/g, '[^/]'), `^(?:\\.\\/)?${source}$`;
|
|
509
|
+
})(globPart),
|
|
510
|
+
recursive,
|
|
511
|
+
publicPrefix: './' === baseDir ? './' : baseDir
|
|
512
|
+
};
|
|
513
|
+
}, hasEager = (rawOptions)=>!!rawOptions && /eager\s*:\s*true/.test(rawOptions), SPECIAL_NO_ENTRY_DEPS = [
|
|
544
514
|
'@iconify-icons/material-symbols'
|
|
515
|
+
], FRAMEWORKS = [
|
|
516
|
+
'react',
|
|
517
|
+
'react-dom',
|
|
518
|
+
'react-router-dom',
|
|
519
|
+
'vue',
|
|
520
|
+
'vue-router'
|
|
545
521
|
], getExternalLibraryName = (pkgName)=>{
|
|
546
522
|
let externalAlias = {
|
|
547
|
-
react: 'React',
|
|
548
523
|
'react-dom': 'ReactDOM',
|
|
549
524
|
'react-router-dom': 'ReactRouterDOM'
|
|
550
525
|
};
|
|
551
526
|
return externalAlias[pkgName] ? externalAlias[pkgName] : pkgName.replace(/^@/, '').split(/[/\-.]/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase() + part.slice(1)).join('');
|
|
552
|
-
}, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`,
|
|
527
|
+
}, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`, REGISTER_ID = 'virtual-svg-icons-register', NAMES_ID = 'virtual-svg-icons-names', normalizeSvg = (content)=>content.replace(/<\?xml[\s\S]*?\?>/gi, '').replace(/<!DOCTYPE[\s\S]*?>/gi, '').replace(/<!--[\s\S]*?-->/g, '').trim(), extractSvgContent = (content)=>{
|
|
528
|
+
let match = content.match(/<svg\b([^>]*)>/i), viewBoxMatch = match?.[1]?.match(/viewBox\s*=\s*["']([^"']+)["']/i);
|
|
529
|
+
return {
|
|
530
|
+
inner: content.replace(/^[\s\S]*?<svg\b[^>]*>/i, '').replace(/<\/svg>[\s\S]*$/i, '').trim(),
|
|
531
|
+
viewBox: viewBoxMatch?.[1]
|
|
532
|
+
};
|
|
533
|
+
}, readSvgFiles = (dir, collected = [])=>{
|
|
534
|
+
if (!node_fs.existsSync(dir)) return collected;
|
|
535
|
+
for (let entry of node_fs.readdirSync(dir, {
|
|
536
|
+
withFileTypes: !0
|
|
537
|
+
})){
|
|
538
|
+
let fullPath = node_path.join(dir, entry.name);
|
|
539
|
+
entry.isDirectory() ? readSvgFiles(fullPath, collected) : entry.isFile() && entry.name.toLowerCase().endsWith('.svg') && collected.push(fullPath);
|
|
540
|
+
}
|
|
541
|
+
return collected;
|
|
542
|
+
}, toSymbolId = (filePath, iconDir, symbolId)=>{
|
|
543
|
+
let relative = node_path.relative(iconDir, filePath), parsed = node_path.parse(relative), dir = parsed.dir.split(node_path.sep).filter(Boolean).join('-'), name = parsed.name;
|
|
544
|
+
if ('function' == typeof symbolId) return symbolId(name, filePath);
|
|
545
|
+
let id = (symbolId || 'icon-[dir]-[name]').replace(/\[name\]/g, name).replace(/\[dir\]/g, dir);
|
|
546
|
+
return id.replace(/--+/g, '-').replace(/^-+|-+$/g, '');
|
|
547
|
+
}, DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
|
|
553
548
|
function getNormalizedPluginsByHook(hook) {
|
|
554
549
|
let pluginMap = new Map();
|
|
555
|
-
return getCurrentUnpackConfig().plugins?.forEach((plugin)=>{
|
|
556
|
-
((plugin, hook)=>{
|
|
550
|
+
return (getCurrentUnpackConfig().plugins?.flat(1 / 0) || []).forEach((plugin)=>{
|
|
551
|
+
plugin && ((plugin, hook)=>{
|
|
557
552
|
if (!plugin[hook]) return !1;
|
|
558
553
|
let apply = plugin.apply;
|
|
559
554
|
if (!apply) return !0;
|
|
@@ -613,7 +608,7 @@ async function applyCacheConfig({ config, unpackConfig, envFilePaths }) {
|
|
|
613
608
|
let cacheConfig = isPlainObject(unpackConfig.performance.cache) ? unpackConfig.performance.cache : {}, buildDependencies = await getBuildDependencies(unpackConfig.root);
|
|
614
609
|
buildDependencies.userBuildDependencies = cacheConfig.buildDependencies || [], buildDependencies.envFilePaths = envFilePaths;
|
|
615
610
|
let cacheDirectory = node_path.resolve(unpackConfig.root, cacheConfig.cacheDirectory || `${unpackConfig._context.cachePath}/cache`, utils_isDevServer() ? 'dev' : 'build');
|
|
616
|
-
return
|
|
611
|
+
return utils_mergeConfig(config, {
|
|
617
612
|
cache: !0,
|
|
618
613
|
experiments: {
|
|
619
614
|
cache: {
|
|
@@ -713,7 +708,7 @@ let MODULE_PATH_REGEX = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\
|
|
|
713
708
|
};
|
|
714
709
|
async function getEntry(root, customEntry) {
|
|
715
710
|
let entry;
|
|
716
|
-
if (entry = customEntry ? node_path.resolve(root, customEntry) : (await
|
|
711
|
+
if (entry = customEntry ? node_path.resolve(root, customEntry) : (await external_tinyglobby_glob('(index|Index).{js,ts,jsx,tsx}', {
|
|
717
712
|
cwd: node_path.join(root, 'src'),
|
|
718
713
|
absolute: !0
|
|
719
714
|
}))[0], !node_fs.existsSync(entry)) throw Error('could not find entry file');
|
|
@@ -743,6 +738,7 @@ async function applyHtmlConfig({ config, unpackConfig }) {
|
|
|
743
738
|
]
|
|
744
739
|
})), config;
|
|
745
740
|
}
|
|
741
|
+
var nativeCss_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
746
742
|
let { RawSource: RawSource, SourceMapSource: SourceMapSource } = rspack.sources, isJsFile = /\.[cm]?js(\?.*)?$/i, jsMinify_PLUGIN_NAME = 'JsMinifyPlugin';
|
|
747
743
|
class JsMinifyPlugin {
|
|
748
744
|
minifyOptions;
|
|
@@ -754,7 +750,7 @@ class JsMinifyPlugin {
|
|
|
754
750
|
apply(compiler) {
|
|
755
751
|
let meta = JSON.stringify({
|
|
756
752
|
name: jsMinify_PLUGIN_NAME,
|
|
757
|
-
version: "
|
|
753
|
+
version: "4.1.0",
|
|
758
754
|
options: this.minifyOptions
|
|
759
755
|
});
|
|
760
756
|
compiler.hooks.compilation.tap(jsMinify_PLUGIN_NAME, (compilation)=>{
|
|
@@ -842,8 +838,9 @@ let getCompileTime = (stats)=>stats.toJson({
|
|
|
842
838
|
timings: !0
|
|
843
839
|
}).time / 1000, sameCount = 0;
|
|
844
840
|
async function compileDone(compiler, stats) {
|
|
841
|
+
if (stats.hasErrors()) return;
|
|
845
842
|
let root = compiler.options.context;
|
|
846
|
-
if (
|
|
843
|
+
if (utils_isProd()) logger_logger.ready(colors.green(`built in ${prettyTime(getCompileTime(stats))}`));
|
|
847
844
|
else {
|
|
848
845
|
let fileInfo = function(changedFiles, removedFiles, root) {
|
|
849
846
|
if (!changedFiles?.length && !removedFiles?.length) return null;
|
|
@@ -958,7 +955,7 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
958
955
|
await applyPluginsByHook('config', async (impl)=>{
|
|
959
956
|
rest = await impl(rest, {
|
|
960
957
|
...originalUnpackConfig._context,
|
|
961
|
-
mergeConfig:
|
|
958
|
+
mergeConfig: utils_mergeConfig
|
|
962
959
|
});
|
|
963
960
|
});
|
|
964
961
|
let unpackConfig = {
|
|
@@ -1125,12 +1122,12 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1125
1122
|
moduleIds: isDev() ? 'named' : 'deterministic',
|
|
1126
1123
|
minimize: !!unpackConfig.build?.minify && utils_isProd(),
|
|
1127
1124
|
minimizer: [
|
|
1128
|
-
new JsMinifyPlugin(
|
|
1125
|
+
new JsMinifyPlugin(utils_mergeConfig({
|
|
1129
1126
|
compress: {
|
|
1130
1127
|
target: unpackConfig.build.target
|
|
1131
1128
|
}
|
|
1132
1129
|
}, minifyOptions.oxc || {})),
|
|
1133
|
-
new rspack.LightningCssMinimizerRspackPlugin(
|
|
1130
|
+
new rspack.LightningCssMinimizerRspackPlugin(utils_mergeConfig({
|
|
1134
1131
|
minimizerOptions: {
|
|
1135
1132
|
targets: esVersionToBrowserslist(unpackConfig.build.target)
|
|
1136
1133
|
}
|
|
@@ -1190,7 +1187,7 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1190
1187
|
}
|
|
1191
1188
|
return config;
|
|
1192
1189
|
})({
|
|
1193
|
-
config: config = unpackConfig.
|
|
1190
|
+
config: config = unpackConfig.css?.native ? function({ config, unpackConfig }) {
|
|
1194
1191
|
config.output.cssFilename = getOutputFilename({
|
|
1195
1192
|
type: 'css',
|
|
1196
1193
|
hash: unpackConfig.build?.filenameHash
|
|
@@ -1219,28 +1216,33 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1219
1216
|
});
|
|
1220
1217
|
let withCssModules = ({ use })=>({
|
|
1221
1218
|
resourceQuery: /[?&]module(?:[=&]|$)/,
|
|
1222
|
-
use
|
|
1219
|
+
use: [
|
|
1220
|
+
isDev() && {
|
|
1221
|
+
loader: node_path.resolve(nativeCss_dirname, './typedCssModulesLoader.js')
|
|
1222
|
+
},
|
|
1223
|
+
...use
|
|
1224
|
+
].filter(Boolean),
|
|
1223
1225
|
type: 'css/module'
|
|
1224
1226
|
}), getLessLoader = ()=>({
|
|
1225
1227
|
loader: getCompiledPkgPath('less-loader'),
|
|
1226
|
-
options: {
|
|
1227
|
-
lessOptions:
|
|
1228
|
+
options: utils_mergeConfig({
|
|
1229
|
+
lessOptions: {
|
|
1228
1230
|
javascriptEnabled: !0
|
|
1229
|
-
},
|
|
1231
|
+
},
|
|
1230
1232
|
implementation: getUserDepPath(unpackConfig.root, 'less'),
|
|
1231
1233
|
sourceMap
|
|
1232
|
-
}
|
|
1234
|
+
}, unpackConfig.css?.lessLoader || {})
|
|
1233
1235
|
}), getCssLoader = ()=>unpackConfig.css?.transformer === 'lightningcss' ? {
|
|
1234
1236
|
loader: 'builtin:lightningcss-loader',
|
|
1235
1237
|
options: {
|
|
1236
1238
|
targets: esVersionToBrowserslist(unpackConfig.build.target),
|
|
1237
|
-
...unpackConfig.css?.
|
|
1239
|
+
...unpackConfig.css?.lightningcssLoader
|
|
1238
1240
|
}
|
|
1239
1241
|
} : {
|
|
1240
1242
|
loader: getCompiledPkgPath('postcss-loader'),
|
|
1241
1243
|
options: {
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
+
sourceMap,
|
|
1245
|
+
...unpackConfig.css?.postcssLoader
|
|
1244
1246
|
}
|
|
1245
1247
|
}, getSassLoader = ()=>({
|
|
1246
1248
|
loader: getCompiledPkgPath('sass-loader'),
|
|
@@ -1250,8 +1252,8 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1250
1252
|
'sass-embedded',
|
|
1251
1253
|
'sass'
|
|
1252
1254
|
]),
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
+
sourceMap,
|
|
1256
|
+
...unpackConfig.css?.sassLoader
|
|
1255
1257
|
}
|
|
1256
1258
|
});
|
|
1257
1259
|
return config.module.rules.push({
|
|
@@ -1350,13 +1352,13 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1350
1352
|
loader: 'builtin:lightningcss-loader',
|
|
1351
1353
|
options: {
|
|
1352
1354
|
targets: esVersionToBrowserslist(unpackConfig.build.target),
|
|
1353
|
-
...unpackConfig.css?.
|
|
1355
|
+
...unpackConfig.css?.lightningcssLoader
|
|
1354
1356
|
}
|
|
1355
1357
|
} : {
|
|
1356
1358
|
loader: getCompiledPkgPath('postcss-loader'),
|
|
1357
1359
|
options: {
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
+
sourceMap,
|
|
1361
|
+
...unpackConfig.css?.postcssLoader
|
|
1360
1362
|
}
|
|
1361
1363
|
};
|
|
1362
1364
|
return config.module.rules.push({
|
|
@@ -1368,13 +1370,13 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1368
1370
|
getCssLoader(),
|
|
1369
1371
|
{
|
|
1370
1372
|
loader: getCompiledPkgPath('less-loader'),
|
|
1371
|
-
options: {
|
|
1372
|
-
lessOptions:
|
|
1373
|
+
options: utils_mergeConfig({
|
|
1374
|
+
lessOptions: {
|
|
1373
1375
|
javascriptEnabled: !0
|
|
1374
|
-
},
|
|
1376
|
+
},
|
|
1375
1377
|
implementation: getUserDepPath(unpackConfig.root, 'less'),
|
|
1376
1378
|
sourceMap
|
|
1377
|
-
}
|
|
1379
|
+
}, unpackConfig.css?.lessLoader || {})
|
|
1378
1380
|
}
|
|
1379
1381
|
]
|
|
1380
1382
|
}), config.module.rules.push({
|
|
@@ -1400,8 +1402,8 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1400
1402
|
'sass-embedded',
|
|
1401
1403
|
'sass'
|
|
1402
1404
|
]),
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
+
sourceMap,
|
|
1406
|
+
...unpackConfig.css?.sassLoader
|
|
1405
1407
|
}
|
|
1406
1408
|
}
|
|
1407
1409
|
]
|
|
@@ -1461,11 +1463,11 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1461
1463
|
config = await impl(config, {
|
|
1462
1464
|
...unpackConfig._context,
|
|
1463
1465
|
unpackConfig,
|
|
1464
|
-
mergeConfig:
|
|
1466
|
+
mergeConfig: utils_mergeConfig
|
|
1465
1467
|
});
|
|
1466
1468
|
}), unpackConfig.bundlerConfig && (config = isFunction(unpackConfig.bundlerConfig) ? await unpackConfig.bundlerConfig(config, {
|
|
1467
|
-
mergeConfig:
|
|
1468
|
-
}) :
|
|
1469
|
+
mergeConfig: utils_mergeConfig
|
|
1470
|
+
}) : utils_mergeConfig(config, unpackConfig.bundlerConfig)), config;
|
|
1469
1471
|
}
|
|
1470
1472
|
async function unpackBuild(unpackConfig) {
|
|
1471
1473
|
let compiler = rspack(await getBundlerConfig(unpackConfig)), handler = (err, stats)=>{
|
|
@@ -1586,7 +1588,7 @@ async function unpackDev(unpackConfig) {
|
|
|
1586
1588
|
...middlewares
|
|
1587
1589
|
]);
|
|
1588
1590
|
let server = new RspackDevServer(devServerOptions, compiler);
|
|
1589
|
-
await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())}
|
|
1591
|
+
await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v4.1.0${unpackConfig.performance?.cache ? ' ϟ' : ''}`)} ${colors.dim('ready in')} ${colors.bold(Math.ceil(performance.now() - getUnpackStartTime()))} ${colors.dim('ms')}\n`), printServerUrls({
|
|
1590
1592
|
port,
|
|
1591
1593
|
host: unpackConfig.server.host,
|
|
1592
1594
|
base: unpackConfig.base
|
|
@@ -1600,162 +1602,161 @@ async function unpackDev(unpackConfig) {
|
|
|
1600
1602
|
function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'unpack' }) {
|
|
1601
1603
|
let _context = {
|
|
1602
1604
|
callerName,
|
|
1603
|
-
version: "
|
|
1605
|
+
version: "4.1.0",
|
|
1604
1606
|
cachePath: 'node_modules/.unpack'
|
|
1605
1607
|
}, resolveConfig = (mode)=>{
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1608
|
+
var options;
|
|
1609
|
+
let rootPath, outputPath, basePath, cachedTraceMap, fs, isValidMethodName, parseFrame, formatOriginalLocation, formatFullStack, resolveErrorLocationAndStack, shouldTransformDeepImport, preJsAssets, jsAssets, cssAssets, bundledDepsCachePath, deepImportPkgPattern, deepImportRegex, plugin, root, rootPath1, inject, domId, registerCode, namesCode, virtualModules, ensureVirtualModules, mergedConfig = utils_mergeConfig({
|
|
1610
|
+
root: cwd,
|
|
1611
|
+
base: '/',
|
|
1612
|
+
sourceMap: 'production' !== mode && 'cheap-module-source-map',
|
|
1613
|
+
build: {
|
|
1614
|
+
outDir: 'dist',
|
|
1615
|
+
minify: !0,
|
|
1616
|
+
filenameHash: !0,
|
|
1617
|
+
target: 'es2023'
|
|
1618
|
+
},
|
|
1619
|
+
server: {
|
|
1620
|
+
port: 3000,
|
|
1621
|
+
host: !1
|
|
1622
|
+
},
|
|
1623
|
+
html: {
|
|
1624
|
+
mountId: 'root'
|
|
1625
|
+
},
|
|
1626
|
+
css: {
|
|
1627
|
+
transformer: 'postcss',
|
|
1628
|
+
sourceMap: !1
|
|
1629
|
+
},
|
|
1630
|
+
performance: {
|
|
1631
|
+
chunkSplit: {
|
|
1632
|
+
strategy: 'single-vendor'
|
|
1628
1633
|
},
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1634
|
+
printFileSize: !0
|
|
1635
|
+
},
|
|
1636
|
+
typeCheck: !0,
|
|
1637
|
+
envPrefix: [
|
|
1638
|
+
'PUBLIC_',
|
|
1639
|
+
'VITE_'
|
|
1640
|
+
],
|
|
1641
|
+
plugins: [
|
|
1642
|
+
{
|
|
1643
|
+
name: 'unpack:auto-css-modules',
|
|
1644
|
+
transform: {
|
|
1645
|
+
filter: {
|
|
1646
|
+
test: JSX_REGEX
|
|
1647
|
+
},
|
|
1648
|
+
handler: (code)=>STYLE_EXT_HINTS.some((ext)=>code.includes(ext)) ? code.replace(STYLE_IMPORT_RE, (full, importClause, quote, spec)=>TYPE_IMPORT_CLAUSE_RE.test(importClause) || spec.includes('?') || spec.includes('#') ? full : `import ${importClause} from ${quote}${spec}?module${quote}`) : null
|
|
1649
|
+
}
|
|
1635
1650
|
},
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
test: JSX_REGEX
|
|
1646
|
-
},
|
|
1647
|
-
handler: (code)=>STYLE_EXT_HINTS.some((ext)=>code.includes(ext)) ? code.replace(STYLE_IMPORT_RE, (full, importClause, quote, spec)=>TYPE_IMPORT_CLAUSE_RE.test(importClause) || spec.includes('?') || spec.includes('#') ? full : `import ${importClause} from ${quote}${spec}?module${quote}`) : null
|
|
1651
|
+
(rootPath = '', outputPath = '', basePath = '/', cachedTraceMap = new Map(), fs = null, isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), parseFrame = async (frame)=>{
|
|
1652
|
+
let { file, column, lineNumber } = frame;
|
|
1653
|
+
if (!file || null == lineNumber || null == column) return;
|
|
1654
|
+
let localPath = file;
|
|
1655
|
+
try {
|
|
1656
|
+
let pathname = new URL(file).pathname;
|
|
1657
|
+
if ('/' !== basePath) {
|
|
1658
|
+
let normalizedBase = basePath;
|
|
1659
|
+
pathname.startsWith(normalizedBase) && (pathname = pathname.slice(normalizedBase.length));
|
|
1648
1660
|
}
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
} catch {
|
|
1662
|
-
node_path.isAbsolute(file) || (localPath = node_path.join(outputPath, file));
|
|
1661
|
+
localPath = node_path.join(outputPath, pathname);
|
|
1662
|
+
} catch {
|
|
1663
|
+
node_path.isAbsolute(file) || (localPath = node_path.join(outputPath, file));
|
|
1664
|
+
}
|
|
1665
|
+
let sourceMapPath = `${localPath}.map`;
|
|
1666
|
+
try {
|
|
1667
|
+
if (!fs.existsSync(sourceMapPath)) return;
|
|
1668
|
+
let tracer = cachedTraceMap.get(sourceMapPath);
|
|
1669
|
+
if (!tracer) {
|
|
1670
|
+
let readFile = promisify(fs.readFile), sourceMapContent = await readFile(sourceMapPath, 'utf-8');
|
|
1671
|
+
if (!sourceMapContent) return;
|
|
1672
|
+
tracer = new TraceMap(sourceMapContent), cachedTraceMap.set(sourceMapPath, tracer);
|
|
1663
1673
|
}
|
|
1664
|
-
let
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1674
|
+
let originalPosition = originalPositionFor(tracer, {
|
|
1675
|
+
line: lineNumber,
|
|
1676
|
+
column: column
|
|
1677
|
+
});
|
|
1678
|
+
return {
|
|
1679
|
+
sourceMapPath,
|
|
1680
|
+
originalPosition
|
|
1681
|
+
};
|
|
1682
|
+
} catch {
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
}, formatOriginalLocation = (originalMapping)=>{
|
|
1686
|
+
let { source, line, column } = originalMapping;
|
|
1687
|
+
if (!source) return;
|
|
1688
|
+
let relativeSource = source;
|
|
1689
|
+
if (source.includes('webpack://')) {
|
|
1690
|
+
let segments = (relativeSource = source.replace(/webpack:\/\/\/?/, '')).split(/[\\/]/);
|
|
1691
|
+
[
|
|
1692
|
+
'src',
|
|
1693
|
+
'node_modules'
|
|
1694
|
+
].includes(segments[1]) && (segments.shift(), relativeSource = segments.join('/'));
|
|
1695
|
+
}
|
|
1696
|
+
let result = relativeSource;
|
|
1697
|
+
return null !== line && (result += null === column ? `:${line}` : `:${line}:${column}`), result;
|
|
1698
|
+
}, formatFullStack = async (stackFrames)=>{
|
|
1699
|
+
let allLines = [], srcLines = [];
|
|
1700
|
+
for (let frame of stackFrames){
|
|
1701
|
+
let parsedFrame = await parseFrame(frame), { methodName } = frame, parts = [];
|
|
1702
|
+
methodName && isValidMethodName(methodName) && parts.push(methodName);
|
|
1703
|
+
let parsed = !1;
|
|
1704
|
+
if (parsedFrame) {
|
|
1705
|
+
let { originalPosition } = parsedFrame, originalLocation = formatOriginalLocation(originalPosition);
|
|
1706
|
+
originalLocation && (parts.push(originalLocation), parsed = !0);
|
|
1707
|
+
}
|
|
1708
|
+
if (!parsed && frame.file) try {
|
|
1709
|
+
let url = new URL(frame.file);
|
|
1710
|
+
parts.push(`${url.pathname}:${frame.lineNumber}:${frame.column}`);
|
|
1681
1711
|
} catch {
|
|
1682
|
-
|
|
1712
|
+
parts.push(`${frame.file}:${frame.lineNumber}:${frame.column}`);
|
|
1683
1713
|
}
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
let segments = (relativeSource = source.replace(/webpack:\/\/\/?/, '')).split(/[\\/]/);
|
|
1690
|
-
[
|
|
1691
|
-
'src',
|
|
1692
|
-
'node_modules'
|
|
1693
|
-
].includes(segments[1]) && (segments.shift(), relativeSource = segments.join('/'));
|
|
1714
|
+
if (parts.length > 0) {
|
|
1715
|
+
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}`;
|
|
1716
|
+
allLines.push(line);
|
|
1717
|
+
let locationText = loc.startsWith('(') && loc.endsWith(')') ? loc.slice(1, -1) : loc;
|
|
1718
|
+
/(^|[\\/])src[\\/]/.test(locationText) && srcLines.push(line);
|
|
1694
1719
|
}
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
/(^|[\\/])src[\\/]/.test(locationText) && srcLines.push(line);
|
|
1718
|
-
}
|
|
1719
|
-
}
|
|
1720
|
-
return srcLines.length > 0 ? srcLines[0] : allLines.join('');
|
|
1721
|
-
}, resolveErrorLocationAndStack = async (item)=>{
|
|
1722
|
-
let locationFromMsg = item.message ? ((message)=>{
|
|
1723
|
-
let match = message.match(/((?:[A-Za-z]:)?\/[^\s:]+):(\d+):(\d+)/);
|
|
1724
|
-
if (!match) return;
|
|
1725
|
-
let [, absPath, line, column] = match, source = absPath;
|
|
1726
|
-
return absPath.startsWith(rootPath + node_path.sep) && (source = node_path.relative(rootPath, absPath)), `${source}:${Number(line)}:${Number(column)}`;
|
|
1727
|
-
})(item.message) : null;
|
|
1728
|
-
if (locationFromMsg) return {
|
|
1729
|
-
locationSuffix: colors.dim(`(${locationFromMsg})`),
|
|
1730
|
-
stackString: ''
|
|
1731
|
-
};
|
|
1732
|
-
if (!item.stack) return {
|
|
1733
|
-
locationSuffix: '',
|
|
1720
|
+
}
|
|
1721
|
+
return srcLines.length > 0 ? srcLines[0] : allLines.join('');
|
|
1722
|
+
}, resolveErrorLocationAndStack = async (item)=>{
|
|
1723
|
+
let locationFromMsg = item.message ? ((message)=>{
|
|
1724
|
+
let match = message.match(/((?:[A-Za-z]:)?\/[^\s:]+):(\d+):(\d+)/);
|
|
1725
|
+
if (!match) return;
|
|
1726
|
+
let [, absPath, line, column] = match, source = absPath;
|
|
1727
|
+
return absPath.startsWith(rootPath + node_path.sep) && (source = node_path.relative(rootPath, absPath)), `${source}:${Number(line)}:${Number(column)}`;
|
|
1728
|
+
})(item.message) : null;
|
|
1729
|
+
if (locationFromMsg) return {
|
|
1730
|
+
locationSuffix: colors.dim(`(${locationFromMsg})`),
|
|
1731
|
+
stackString: ''
|
|
1732
|
+
};
|
|
1733
|
+
if (!item.stack) return {
|
|
1734
|
+
locationSuffix: '',
|
|
1735
|
+
stackString: ''
|
|
1736
|
+
};
|
|
1737
|
+
let parsedFrames = parse(item.stack), userFrame = parsedFrames.find((frame)=>frame.file && null !== frame.lineNumber && null !== frame.column && SOURCE_REGEX.test(frame.file));
|
|
1738
|
+
if (userFrame) {
|
|
1739
|
+
let parsedUserFrame = await parseFrame(userFrame), loc = parsedUserFrame ? formatOriginalLocation(parsedUserFrame.originalPosition) : null;
|
|
1740
|
+
if (loc) return {
|
|
1741
|
+
locationSuffix: colors.dim(`(${loc})`),
|
|
1734
1742
|
stackString: ''
|
|
1735
1743
|
};
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
buildStart: async ({ isFirstCompile, compiler })=>{
|
|
1753
|
-
isFirstCompile && (fs = compiler.outputFileSystem);
|
|
1754
|
-
},
|
|
1755
|
-
configResolved: (config)=>{
|
|
1756
|
-
rootPath = config.root, outputPath = node_path.join(rootPath, config.build.outDir), basePath = normalizePublicPath(config.base);
|
|
1757
|
-
},
|
|
1758
|
-
transformHtml: (html)=>injectToHead(html, `<script>
|
|
1744
|
+
}
|
|
1745
|
+
let formattedStack = await formatFullStack(parsedFrames);
|
|
1746
|
+
return {
|
|
1747
|
+
locationSuffix: '',
|
|
1748
|
+
stackString: colors.dim(formattedStack)
|
|
1749
|
+
};
|
|
1750
|
+
}, {
|
|
1751
|
+
name: 'unpack:browser-logs',
|
|
1752
|
+
apply: (config, { command })=>'dev' === command && config.dev?.browserLogs,
|
|
1753
|
+
buildStart: async ({ isFirstCompile, compiler })=>{
|
|
1754
|
+
isFirstCompile && (fs = compiler.outputFileSystem);
|
|
1755
|
+
},
|
|
1756
|
+
configResolved: (config)=>{
|
|
1757
|
+
rootPath = config.root, outputPath = node_path.join(rootPath, config.build.outDir), basePath = normalizePublicPath(config.base);
|
|
1758
|
+
},
|
|
1759
|
+
transformHtml: (html)=>injectToHead(html, `<script>
|
|
1759
1760
|
;(() => {
|
|
1760
1761
|
if (typeof window === 'undefined' || typeof console === 'undefined') return
|
|
1761
1762
|
const endpoint = '${BROWSER_LOGS_ENDPOINT}'
|
|
@@ -1834,431 +1835,545 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
|
|
|
1834
1835
|
})
|
|
1835
1836
|
})()
|
|
1836
1837
|
</script>`),
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1838
|
+
setupMiddlewares: (middlewares)=>[
|
|
1839
|
+
(req, res, next)=>{
|
|
1840
|
+
if ('POST' !== req.method || !req.url?.startsWith(BROWSER_LOGS_ENDPOINT)) return next();
|
|
1841
|
+
let raw = '';
|
|
1842
|
+
req.on('data', (chunk)=>{
|
|
1843
|
+
raw += chunk.toString();
|
|
1844
|
+
}), req.on('end', async ()=>{
|
|
1845
|
+
try {
|
|
1846
|
+
let { level, time, args = [] } = JSON.parse(raw || '{}'), formattedArgs = await Promise.all(args.map(async (item)=>{
|
|
1847
|
+
if (!item) return '';
|
|
1848
|
+
if ('error' === item.type) {
|
|
1849
|
+
let { locationSuffix, stackString } = await resolveErrorLocationAndStack(item), msg = item.message || '', suffix = locationSuffix ? msg ? ` ${locationSuffix}` : locationSuffix : '';
|
|
1850
|
+
return `${msg}${suffix}${stackString}`;
|
|
1851
|
+
}
|
|
1852
|
+
switch(item.type){
|
|
1853
|
+
case 'string':
|
|
1854
|
+
let trimmed;
|
|
1855
|
+
return (trimmed = item.message.trim()) ? trimmed.split(/\r?\n/g).filter((line)=>{
|
|
1856
|
+
let normalized = line.trim().replace(/`/g, '');
|
|
1857
|
+
return !!normalized && !/^at\s+/.test(normalized);
|
|
1858
|
+
}).join('\n').trim() : '';
|
|
1859
|
+
case 'null':
|
|
1860
|
+
return null;
|
|
1861
|
+
case 'undefined':
|
|
1862
|
+
return;
|
|
1863
|
+
case 'object':
|
|
1864
|
+
return JSON.parse(item.message || '');
|
|
1865
|
+
default:
|
|
1866
|
+
return item.message;
|
|
1867
|
+
}
|
|
1868
|
+
})), outputArgs = ((args)=>{
|
|
1869
|
+
if (args.length < 2 || 'string' != typeof args[0]) return args;
|
|
1870
|
+
let template = args[0];
|
|
1871
|
+
if (!/%[sdifoOj%c%]/.test(template)) return args;
|
|
1872
|
+
let rest = args.slice(1), cleanedTemplate = '';
|
|
1873
|
+
for(let i = 0; i < template.length; i++){
|
|
1874
|
+
let ch = template[i];
|
|
1875
|
+
if ('%' !== ch || i + 1 >= template.length) {
|
|
1876
|
+
cleanedTemplate += ch;
|
|
1877
|
+
continue;
|
|
1850
1878
|
}
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
let normalized = line.trim().replace(/`/g, '');
|
|
1856
|
-
return !!normalized && !/^at\s+/.test(normalized);
|
|
1857
|
-
}).join('\n').trim() : '';
|
|
1858
|
-
case 'null':
|
|
1859
|
-
return null;
|
|
1860
|
-
case 'undefined':
|
|
1861
|
-
return;
|
|
1862
|
-
case 'object':
|
|
1863
|
-
return JSON.parse(item.message || '');
|
|
1864
|
-
default:
|
|
1865
|
-
return item.message;
|
|
1879
|
+
let next = template[i + 1];
|
|
1880
|
+
if ('%' === next) {
|
|
1881
|
+
cleanedTemplate += '%%', i++;
|
|
1882
|
+
continue;
|
|
1866
1883
|
}
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
if (!/%[sdifoOj%c%]/.test(template)) return args;
|
|
1871
|
-
let rest = args.slice(1), cleanedTemplate = '';
|
|
1872
|
-
for(let i = 0; i < template.length; i++){
|
|
1873
|
-
let ch = template[i];
|
|
1874
|
-
if ('%' !== ch || i + 1 >= template.length) {
|
|
1875
|
-
cleanedTemplate += ch;
|
|
1876
|
-
continue;
|
|
1877
|
-
}
|
|
1878
|
-
let next = template[i + 1];
|
|
1879
|
-
if ('%' === next) {
|
|
1880
|
-
cleanedTemplate += '%%', i++;
|
|
1881
|
-
continue;
|
|
1882
|
-
}
|
|
1883
|
-
if ('c' === next) {
|
|
1884
|
-
rest.length > 0 && rest.shift(), i++;
|
|
1885
|
-
continue;
|
|
1886
|
-
}
|
|
1887
|
-
cleanedTemplate += `%${next}`, i++;
|
|
1884
|
+
if ('c' === next) {
|
|
1885
|
+
rest.length > 0 && rest.shift(), i++;
|
|
1886
|
+
continue;
|
|
1888
1887
|
}
|
|
1889
|
-
|
|
1890
|
-
format(cleanedTemplate, ...rest)
|
|
1891
|
-
];
|
|
1892
|
-
})(formattedArgs), prefix = colors.dim(`[browser ${time}]`);
|
|
1893
|
-
switch(level){
|
|
1894
|
-
case 'error':
|
|
1895
|
-
console.log(colors.red(`${prefix} ${format(...outputArgs)}`));
|
|
1896
|
-
break;
|
|
1897
|
-
case 'warn':
|
|
1898
|
-
console.log(colors.yellow(`${prefix} ${format(...outputArgs)}`));
|
|
1899
|
-
break;
|
|
1900
|
-
case 'debug':
|
|
1901
|
-
console.log(prefix, ...outputArgs);
|
|
1888
|
+
cleanedTemplate += `%${next}`, i++;
|
|
1902
1889
|
}
|
|
1903
|
-
|
|
1904
|
-
|
|
1890
|
+
return [
|
|
1891
|
+
format(cleanedTemplate, ...rest)
|
|
1892
|
+
];
|
|
1893
|
+
})(formattedArgs), prefix = colors.dim(`[browser ${time}]`);
|
|
1894
|
+
switch(level){
|
|
1895
|
+
case 'error':
|
|
1896
|
+
console.log(colors.red(`${prefix} ${format(...outputArgs)}`));
|
|
1897
|
+
break;
|
|
1898
|
+
case 'warn':
|
|
1899
|
+
console.log(colors.yellow(`${prefix} ${format(...outputArgs)}`));
|
|
1900
|
+
break;
|
|
1901
|
+
case 'debug':
|
|
1902
|
+
console.log(prefix, ...outputArgs);
|
|
1905
1903
|
}
|
|
1904
|
+
} finally{
|
|
1905
|
+
res.statusCode = 204, res.end();
|
|
1906
|
+
}
|
|
1907
|
+
});
|
|
1908
|
+
},
|
|
1909
|
+
...middlewares
|
|
1910
|
+
]
|
|
1911
|
+
}),
|
|
1912
|
+
{
|
|
1913
|
+
name: 'unpack:glob',
|
|
1914
|
+
transform: {
|
|
1915
|
+
filter: {
|
|
1916
|
+
test: JS_REGEX
|
|
1917
|
+
},
|
|
1918
|
+
handler: (code)=>code.includes('import.meta.glob') ? code.replace(/import\.meta\.glob\s*\(\s*(\[[\s\S]*?\]|(['"])([^'"]+)\2)\s*(?:,\s*({[\s\S]*?}))?\s*\)/g, (_, patternGroup, __, pattern, rawOptions)=>{
|
|
1919
|
+
if (patternGroup.trim().startsWith('[')) {
|
|
1920
|
+
let items, includes, excludes, { includes: includes1, excludes: excludes1 } = (items = [], patternGroup.replace(/(['"])([^'"]+)\1/g, (_, __, value)=>(items.push(value), '')), includes = [], excludes = [], items.forEach((item)=>{
|
|
1921
|
+
if (item.startsWith('!')) {
|
|
1922
|
+
let normalized = item.slice(1).trim();
|
|
1923
|
+
normalized && excludes.push(normalized);
|
|
1924
|
+
return;
|
|
1925
|
+
}
|
|
1926
|
+
includes.push(item);
|
|
1927
|
+
}), {
|
|
1928
|
+
includes,
|
|
1929
|
+
excludes
|
|
1906
1930
|
});
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1931
|
+
return includes1.length ? (({ includes, excludes, eager })=>{
|
|
1932
|
+
let excludeMatchers = excludes.map((item)=>toRegexLiteral(item.regExpSource)).join(', '), includeItems = includes.map((item)=>{
|
|
1933
|
+
let prefix = './' === item.publicPrefix ? '' : `${item.publicPrefix}/`, mapKeyExpr = './' === item.publicPrefix ? "key.startsWith('./') ? key : './' + key" : `${JSON.stringify(prefix)} + (key.startsWith('./') ? key.slice(2) : key)`;
|
|
1934
|
+
return `{
|
|
1935
|
+
context: import.meta.webpackContext(${JSON.stringify(item.baseDir)}, { recursive: ${item.recursive}, regExp: ${toRegexLiteral(item.regExpSource)} }),
|
|
1936
|
+
mapKey: (key) => ${mapKeyExpr}
|
|
1937
|
+
}`;
|
|
1938
|
+
}).join(', '), excludeList = excludeMatchers ? `[${excludeMatchers}]` : '[]';
|
|
1939
|
+
return `(() => {
|
|
1940
|
+
const modules = {}
|
|
1941
|
+
const includeContexts = [${includeItems}]
|
|
1942
|
+
const excludeMatchers = ${excludeList}
|
|
1943
|
+
const isExcluded = (path) => excludeMatchers.some((matcher) => matcher.test(path))
|
|
1944
|
+
for (const { context, mapKey } of includeContexts) {
|
|
1945
|
+
for (const key of context.keys()) {
|
|
1946
|
+
const path = mapKey(key)
|
|
1947
|
+
if (isExcluded(path)) continue
|
|
1948
|
+
if (!modules[path]) {
|
|
1949
|
+
modules[path] = ${eager ? 'context(key)' : '() => Promise.resolve(context(key))'}
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
return modules
|
|
1954
|
+
})()`;
|
|
1955
|
+
})({
|
|
1956
|
+
includes: includes1.map(parseGlob),
|
|
1957
|
+
excludes: excludes1.map(parseGlob),
|
|
1958
|
+
eager: hasEager(rawOptions)
|
|
1959
|
+
}) : '({})';
|
|
1960
|
+
}
|
|
1961
|
+
let { baseDir, regExpSource, recursive, publicPrefix } = parseGlob(pattern);
|
|
1962
|
+
return (({ baseDir, regExpSource, recursive, eager, publicPrefix })=>{
|
|
1963
|
+
let prefix = './' === publicPrefix ? '' : `${publicPrefix}/`, mapKeyExpr = './' === publicPrefix ? "key.startsWith('./') ? key : './' + key" : `${JSON.stringify(prefix)} + (key.startsWith('./') ? key.slice(2) : key)`;
|
|
1964
|
+
return `(() => {
|
|
1965
|
+
const context = import.meta.webpackContext(${JSON.stringify(baseDir)}, { recursive: ${recursive}, regExp: ${toRegexLiteral(regExpSource)} })
|
|
1966
|
+
const modules = {}
|
|
1967
|
+
for (const key of context.keys()) {
|
|
1968
|
+
const path = ${mapKeyExpr}
|
|
1969
|
+
modules[path] = ${eager ? 'context(key)' : '() => Promise.resolve(context(key))'}
|
|
1970
|
+
}
|
|
1971
|
+
return modules
|
|
1972
|
+
})()`;
|
|
1973
|
+
})({
|
|
1974
|
+
baseDir,
|
|
1975
|
+
regExpSource,
|
|
1976
|
+
recursive,
|
|
1977
|
+
eager: hasEager(rawOptions),
|
|
1978
|
+
publicPrefix
|
|
1979
|
+
});
|
|
1980
|
+
}) : null
|
|
1981
|
+
}
|
|
1982
|
+
},
|
|
1983
|
+
(shouldTransformDeepImport = !1, preJsAssets = [], jsAssets = [], cssAssets = [], bundledDepsCachePath = '', deepImportPkgPattern = [
|
|
1984
|
+
...SPECIAL_NO_ENTRY_DEPS
|
|
1985
|
+
].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'), plugin = {
|
|
1986
|
+
name: 'unpack:prebundle',
|
|
1987
|
+
apply: (config, { command })=>'dev' === command && !!config.dev?.prebundle,
|
|
1988
|
+
config: async (config, context)=>{
|
|
1989
|
+
var externals;
|
|
1990
|
+
let existExternals, root = config.root;
|
|
1991
|
+
bundledDepsCachePath = node_path.resolve(root, context.cachePath, 'umd');
|
|
1992
|
+
let count = {
|
|
1993
|
+
total: 0,
|
|
1994
|
+
bundled: 0
|
|
1995
|
+
}, 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 = ()=>{
|
|
1996
|
+
let errMsg = failedDeps.length > 0 ? ` failed: ${failedDeps.join(', ')}` : '';
|
|
1997
|
+
logUpdate(`${colors.magenta('»')} optimizing dependencies (${count.bundled}/${count.total})${errMsg}`), count.total === count.bundled + failedDeps.length && console.log();
|
|
1998
|
+
}, 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 = [
|
|
1999
|
+
...(externals = config.externals, existExternals = new Set(), Array.isArray(externals) ? externals.forEach((item)=>{
|
|
2000
|
+
isPlainObject(item) && Object.keys(item).forEach((key)=>{
|
|
1932
2001
|
existExternals.add(key);
|
|
1933
|
-
})
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
if (isString(
|
|
1950
|
-
|
|
1951
|
-
if (packageJson.main) return packageJson.main;
|
|
1952
|
-
})(depPackageJson);
|
|
1953
|
-
if (!entry) {
|
|
1954
|
-
if (SPECIAL_NO_ENTRY_DEPS.includes(pkgName)) {
|
|
1955
|
-
let syntheticEntry = (({ root, pkgName })=>{
|
|
1956
|
-
let pkgDir = node_path.resolve(root, 'node_modules', pkgName);
|
|
1957
|
-
if (!node_fs.existsSync(pkgDir)) return;
|
|
1958
|
-
let indexPath = node_path.resolve(pkgDir, 'index.ts'), content = globSync('**/*.{js,jsx,ts,tsx}', {
|
|
1959
|
-
cwd: pkgDir,
|
|
1960
|
-
absolute: !1
|
|
1961
|
-
}).filter((p)=>{
|
|
1962
|
-
let base = node_path.basename(p);
|
|
1963
|
-
return !(p.endsWith('.d.ts') || /^index\.(t|j)sx?$/.test(base)) && 'package.json' !== base;
|
|
1964
|
-
}).map((file)=>{
|
|
1965
|
-
let normalized = file.split(node_path.sep).join('/'), exportName = pathToExportIdentifier(normalized);
|
|
1966
|
-
return `export { default as ${exportName} } from './${normalized}'`;
|
|
1967
|
-
}).join('\n');
|
|
1968
|
-
return node_fs.writeFileSync(indexPath, content, 'utf-8'), indexPath;
|
|
1969
|
-
})({
|
|
1970
|
-
root,
|
|
1971
|
-
pkgName
|
|
1972
|
-
});
|
|
1973
|
-
if (syntheticEntry) return shouldTransformDeepImport = !0, {
|
|
1974
|
-
name: pkgName,
|
|
1975
|
-
entry: syntheticEntry,
|
|
1976
|
-
version
|
|
1977
|
-
};
|
|
2002
|
+
});
|
|
2003
|
+
}) : isPlainObject(externals) && Object.keys(externals).forEach((key)=>{
|
|
2004
|
+
existExternals.add(key);
|
|
2005
|
+
}), Array.from(existExternals) || []),
|
|
2006
|
+
...userOptions.exclude || []
|
|
2007
|
+
], needBundleDeps = (Array.isArray(userOptions.include) && userOptions.include.length > 0 ? userOptions.include : Object.keys(packageJson.dependencies || {})).filter((pkgName)=>!excludeDeps.includes(pkgName)).map((pkgName)=>{
|
|
2008
|
+
let depPackageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'node_modules', pkgName, 'package.json'), 'utf-8')), version = depPackageJson.version;
|
|
2009
|
+
if (failedCache[pkgName] === version) return;
|
|
2010
|
+
let entry = ((packageJson)=>{
|
|
2011
|
+
if (packageJson.module) return packageJson.module;
|
|
2012
|
+
if (packageJson.exports) {
|
|
2013
|
+
if (isString(packageJson.exports)) return packageJson.exports;
|
|
2014
|
+
let defaultExport = packageJson.exports['.'];
|
|
2015
|
+
if (defaultExport) {
|
|
2016
|
+
if (isString(defaultExport)) return defaultExport;
|
|
2017
|
+
if (isString(defaultExport.import)) return defaultExport.import;
|
|
2018
|
+
if (isString(defaultExport.browser)) return defaultExport.browser;
|
|
2019
|
+
if (isString(defaultExport.default)) return defaultExport.default;
|
|
1978
2020
|
}
|
|
1979
|
-
|
|
1980
|
-
return;
|
|
2021
|
+
if (isString(packageJson.exports.default)) return packageJson.exports.default;
|
|
1981
2022
|
}
|
|
1982
|
-
return
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2023
|
+
if (packageJson.main) return packageJson.main;
|
|
2024
|
+
})(depPackageJson);
|
|
2025
|
+
if (!entry) {
|
|
2026
|
+
if (SPECIAL_NO_ENTRY_DEPS.includes(pkgName)) {
|
|
2027
|
+
let syntheticEntry = (({ root, pkgName })=>{
|
|
2028
|
+
let pkgDir = node_path.resolve(root, 'node_modules', pkgName);
|
|
2029
|
+
if (!node_fs.existsSync(pkgDir)) return;
|
|
2030
|
+
let indexPath = node_path.resolve(pkgDir, 'index.ts'), content = globSync('**/*.{js,jsx,ts,tsx}', {
|
|
2031
|
+
cwd: pkgDir,
|
|
2032
|
+
absolute: !1
|
|
2033
|
+
}).filter((p)=>{
|
|
2034
|
+
let base = node_path.basename(p);
|
|
2035
|
+
return !(p.endsWith('.d.ts') || /^index\.(t|j)sx?$/.test(base)) && 'package.json' !== base;
|
|
2036
|
+
}).map((file)=>{
|
|
2037
|
+
let normalized = file.split(node_path.sep).join('/'), exportName = pathToExportIdentifier(normalized);
|
|
2038
|
+
return `export { default as ${exportName} } from './${normalized}'`;
|
|
2039
|
+
}).join('\n');
|
|
2040
|
+
return node_fs.writeFileSync(indexPath, content, 'utf-8'), indexPath;
|
|
2041
|
+
})({
|
|
2042
|
+
root,
|
|
2043
|
+
pkgName
|
|
2044
|
+
});
|
|
2045
|
+
if (syntheticEntry) return shouldTransformDeepImport = !0, {
|
|
2046
|
+
name: pkgName,
|
|
2047
|
+
entry: syntheticEntry,
|
|
2048
|
+
version
|
|
2049
|
+
};
|
|
2050
|
+
}
|
|
2051
|
+
failedCache[pkgName] = version;
|
|
2052
|
+
return;
|
|
2053
|
+
}
|
|
2054
|
+
return {
|
|
2055
|
+
name: pkgName,
|
|
2056
|
+
entry: node_path.resolve(root, 'node_modules', pkgName, entry),
|
|
2057
|
+
version
|
|
2058
|
+
};
|
|
2059
|
+
}).filter(Boolean), depExternals = Object.fromEntries(Array.from(new Set([
|
|
2060
|
+
...FRAMEWORKS,
|
|
2061
|
+
...Array.isArray(userOptions.externals) ? userOptions.externals : []
|
|
2062
|
+
])).map((pkg)=>[
|
|
2063
|
+
pkg,
|
|
2064
|
+
getExternalValue(pkg)
|
|
2065
|
+
])), bundledDeps = await Promise.all(needBundleDeps.map((depInfo)=>(({ name, entry, version })=>new Promise((resolve)=>{
|
|
2066
|
+
let pkgDir = node_path.resolve(bundledDepsCachePath, name), outDir = node_path.resolve(pkgDir, version), getResult = ()=>({
|
|
2067
|
+
name,
|
|
2068
|
+
assets: globSync('**/index.{js,css}', {
|
|
2069
|
+
cwd: outDir,
|
|
2070
|
+
absolute: !0
|
|
2071
|
+
})
|
|
2072
|
+
});
|
|
2073
|
+
if (node_fs.existsSync(outDir)) return void resolve(getResult());
|
|
2074
|
+
count.total++, updateProgress();
|
|
2075
|
+
let getSwcOptions = ({ tsx })=>({
|
|
2076
|
+
jsc: {
|
|
2077
|
+
parser: {
|
|
2078
|
+
tsx,
|
|
2079
|
+
syntax: "typescript",
|
|
2080
|
+
dynamicImport: !0,
|
|
2081
|
+
decorators: !0
|
|
2082
|
+
},
|
|
2083
|
+
transform: {
|
|
2084
|
+
react: {
|
|
2085
|
+
runtime: 'automatic'
|
|
2017
2086
|
}
|
|
2018
2087
|
}
|
|
2019
|
-
}
|
|
2020
|
-
|
|
2021
|
-
|
|
2088
|
+
}
|
|
2089
|
+
}), compiler = rspack({
|
|
2090
|
+
entry: {
|
|
2091
|
+
index: entry
|
|
2092
|
+
},
|
|
2093
|
+
context: root,
|
|
2094
|
+
mode: 'development',
|
|
2095
|
+
output: {
|
|
2096
|
+
clean: !0,
|
|
2097
|
+
path: outDir,
|
|
2098
|
+
pathinfo: !1,
|
|
2099
|
+
library: {
|
|
2100
|
+
name: getExternalLibraryName(name),
|
|
2101
|
+
type: 'umd',
|
|
2102
|
+
umdNamedDefine: !0
|
|
2022
2103
|
},
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
type: 'umd',
|
|
2032
|
-
umdNamedDefine: !0
|
|
2104
|
+
globalObject: 'this'
|
|
2105
|
+
},
|
|
2106
|
+
devtool: !1,
|
|
2107
|
+
module: {
|
|
2108
|
+
rules: [
|
|
2109
|
+
{
|
|
2110
|
+
test: /\.(png|jpe?g|gif|webp)$/i,
|
|
2111
|
+
type: 'asset'
|
|
2033
2112
|
},
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
options: {
|
|
2068
|
-
lessOptions: {
|
|
2069
|
-
javascriptEnabled: !0
|
|
2070
|
-
},
|
|
2071
|
-
implementation: getUserDepPath(root, 'less')
|
|
2072
|
-
}
|
|
2113
|
+
{
|
|
2114
|
+
test: JS_REGEX,
|
|
2115
|
+
use: [
|
|
2116
|
+
{
|
|
2117
|
+
loader: 'builtin:swc-loader',
|
|
2118
|
+
options: getSwcOptions({
|
|
2119
|
+
tsx: !1
|
|
2120
|
+
})
|
|
2121
|
+
}
|
|
2122
|
+
]
|
|
2123
|
+
},
|
|
2124
|
+
{
|
|
2125
|
+
test: JSX_REGEX,
|
|
2126
|
+
use: [
|
|
2127
|
+
{
|
|
2128
|
+
loader: 'builtin:swc-loader',
|
|
2129
|
+
options: getSwcOptions({
|
|
2130
|
+
tsx: !0
|
|
2131
|
+
})
|
|
2132
|
+
}
|
|
2133
|
+
]
|
|
2134
|
+
},
|
|
2135
|
+
{
|
|
2136
|
+
test: /\.less$/,
|
|
2137
|
+
type: 'css/auto',
|
|
2138
|
+
use: [
|
|
2139
|
+
{
|
|
2140
|
+
loader: getCompiledPkgPath('less-loader'),
|
|
2141
|
+
options: {
|
|
2142
|
+
lessOptions: {
|
|
2143
|
+
javascriptEnabled: !0
|
|
2144
|
+
},
|
|
2145
|
+
implementation: getUserDepPath(root, 'less')
|
|
2073
2146
|
}
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2147
|
+
}
|
|
2148
|
+
]
|
|
2149
|
+
},
|
|
2150
|
+
{
|
|
2151
|
+
test: /\.s[ac]ss$/i,
|
|
2152
|
+
type: 'css/auto',
|
|
2153
|
+
use: [
|
|
2154
|
+
{
|
|
2155
|
+
loader: getCompiledPkgPath('sass-loader'),
|
|
2156
|
+
options: {
|
|
2157
|
+
api: 'modern-compiler',
|
|
2158
|
+
implementation: getUserDepPath(root, [
|
|
2159
|
+
'sass-embedded',
|
|
2160
|
+
'sass'
|
|
2161
|
+
])
|
|
2089
2162
|
}
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2163
|
+
}
|
|
2164
|
+
]
|
|
2165
|
+
}
|
|
2166
|
+
]
|
|
2167
|
+
},
|
|
2168
|
+
optimization: {
|
|
2169
|
+
splitChunks: !1
|
|
2170
|
+
},
|
|
2171
|
+
experiments: {
|
|
2172
|
+
css: !0
|
|
2173
|
+
},
|
|
2174
|
+
externals: depExternals
|
|
2175
|
+
});
|
|
2176
|
+
compiler.run((_, stats)=>{
|
|
2177
|
+
let isFailed = !1;
|
|
2178
|
+
stats?.hasErrors() ? (isFailed = !0, failedDeps.push(name), failedCache[name] = version, removeDir(outDir)) : count.bundled++, updateProgress(), compiler.close(()=>{
|
|
2179
|
+
resolve(isFailed ? void 0 : getResult());
|
|
2107
2180
|
});
|
|
2108
|
-
}))(depInfo)));
|
|
2109
|
-
((cache)=>{
|
|
2110
|
-
if (0 === Object.keys(cache).length) {
|
|
2111
|
-
node_fs.existsSync(failedDepsJsonPath) && node_fs.unlinkSync(failedDepsJsonPath);
|
|
2112
|
-
return;
|
|
2113
|
-
}
|
|
2114
|
-
let cacheDir = node_path.dirname(failedDepsJsonPath);
|
|
2115
|
-
node_fs.existsSync(cacheDir) || node_fs.mkdirSync(cacheDir, {
|
|
2116
|
-
recursive: !0
|
|
2117
|
-
}), node_fs.writeFileSync(failedDepsJsonPath, JSON.stringify(cache, null, 2), 'utf-8');
|
|
2118
|
-
})(failedCache);
|
|
2119
|
-
let externals1 = {};
|
|
2120
|
-
bundledDeps.filter(Boolean).forEach((dep)=>{
|
|
2121
|
-
dep && (externals1[dep.name] = getExternalValue(dep.name), dep.assets.forEach((absPath)=>{
|
|
2122
|
-
let relativePath = node_path.relative(bundledDepsCachePath, absPath), preDeps = [
|
|
2123
|
-
'react',
|
|
2124
|
-
'react-dom',
|
|
2125
|
-
'react-router-dom'
|
|
2126
|
-
], serverPath = `/umd/${relativePath}`;
|
|
2127
|
-
switch(node_path.extname(relativePath)){
|
|
2128
|
-
case '.js':
|
|
2129
|
-
preDeps.includes(dep.name) ? preJsAssets.push({
|
|
2130
|
-
path: serverPath,
|
|
2131
|
-
order: preDeps.indexOf(dep.name)
|
|
2132
|
-
}) : jsAssets.push(serverPath);
|
|
2133
|
-
break;
|
|
2134
|
-
case '.css':
|
|
2135
|
-
ignoreCSSDeps.includes(dep.name) || cssAssets.push(serverPath);
|
|
2136
|
-
}
|
|
2137
|
-
}));
|
|
2138
|
-
});
|
|
2139
|
-
let existingExternals = config.externals ? Array.isArray(config.externals) ? config.externals : [
|
|
2140
|
-
config.externals
|
|
2141
|
-
] : [];
|
|
2142
|
-
return config.externals = [
|
|
2143
|
-
externals1,
|
|
2144
|
-
...existingExternals
|
|
2145
|
-
], shouldTransformDeepImport && (plugin.transform = {
|
|
2146
|
-
filter: {
|
|
2147
|
-
test: JSX_REGEX
|
|
2148
|
-
},
|
|
2149
|
-
handler: (code)=>SPECIAL_NO_ENTRY_DEPS.some((pkg)=>code.includes(pkg)) ? code.replace(deepImportRegex, (_, localName, importPath, pkgName)=>{
|
|
2150
|
-
let exportName = pathToExportIdentifier(importPath.slice(pkgName.length + 1));
|
|
2151
|
-
return `import { ${exportName} as ${localName} } from '${pkgName}'`;
|
|
2152
|
-
}) : null
|
|
2153
|
-
}), config;
|
|
2154
|
-
},
|
|
2155
|
-
transformHtml: (html)=>injectToHead(html, preJsAssets.sort((a, b)=>a.order - b.order).map((item)=>item.path).map((item)=>`<script defer src="${item}"></script>`).join('')),
|
|
2156
|
-
setupMiddlewares: (middlewares)=>[
|
|
2157
|
-
(req, res, next)=>{
|
|
2158
|
-
if ('string' != typeof req.url) return void next();
|
|
2159
|
-
let url = new URL(req.url, 'http://localhost');
|
|
2160
|
-
if (!url.pathname.startsWith("/umd/")) return void next();
|
|
2161
|
-
let relativePath = url.pathname.replace("/umd/", '');
|
|
2162
|
-
if (relativePath.includes('..')) {
|
|
2163
|
-
res.statusCode = 403, res.end();
|
|
2164
|
-
return;
|
|
2165
|
-
}
|
|
2166
|
-
let filePath = node_path.join(bundledDepsCachePath, relativePath);
|
|
2167
|
-
if (!node_fs.existsSync(filePath)) return void next();
|
|
2168
|
-
let stat = node_fs.statSync(filePath);
|
|
2169
|
-
if (!stat.isFile()) return void next();
|
|
2170
|
-
let mtime = stat.mtime.toUTCString(), ext = node_path.extname(filePath);
|
|
2171
|
-
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) {
|
|
2172
|
-
res.statusCode = 304, res.end();
|
|
2173
|
-
return;
|
|
2174
|
-
}
|
|
2175
|
-
res.statusCode = 200, node_fs.createReadStream(filePath).pipe(res);
|
|
2176
|
-
},
|
|
2177
|
-
...middlewares
|
|
2178
|
-
],
|
|
2179
|
-
bundlerConfig: (config)=>{
|
|
2180
|
-
let PLUGIN_NAME = 'InjectAssetsPlugin';
|
|
2181
|
-
return config.plugins.push({
|
|
2182
|
-
apply: (compiler)=>{
|
|
2183
|
-
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
|
|
2184
|
-
rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(PLUGIN_NAME, async (args)=>(args.assets.js.unshift(...jsAssets), args.assets.css.unshift(...cssAssets), args));
|
|
2185
2181
|
});
|
|
2186
|
-
}
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
},
|
|
2203
|
-
{
|
|
2204
|
-
type: 'Assets',
|
|
2205
|
-
color: 'yellow',
|
|
2206
|
-
chunks: []
|
|
2207
|
-
},
|
|
2208
|
-
{
|
|
2209
|
-
type: 'CSS',
|
|
2210
|
-
color: 'magenta',
|
|
2211
|
-
chunks: []
|
|
2212
|
-
},
|
|
2213
|
-
{
|
|
2214
|
-
type: 'JS',
|
|
2215
|
-
color: 'cyan',
|
|
2216
|
-
chunks: []
|
|
2217
|
-
}
|
|
2218
|
-
], 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;
|
|
2219
|
-
logUpdate('computing gzip size...'), await Promise.all(assets.map(async ([assetName, value])=>{
|
|
2220
|
-
let content, compressedSize, filePath = assetName.split('?')[0];
|
|
2221
|
-
try {
|
|
2222
|
-
content = value.source();
|
|
2223
|
-
} catch {
|
|
2224
|
-
content = node_fs.readFileSync(node_path.join(distPath, filePath));
|
|
2225
|
-
}
|
|
2226
|
-
let size = Buffer.byteLength(content);
|
|
2227
|
-
compressedSize = COMPRESSIBLE_REGEX.test(filePath) ? await getCompressedSize(content) : size, totalSize += size, totalCompressedSize += compressedSize;
|
|
2228
|
-
let chunk = {
|
|
2229
|
-
name: node_path.basename(filePath),
|
|
2230
|
-
path: `${distFolder}/${filePath}`,
|
|
2231
|
-
size,
|
|
2232
|
-
compressedSize
|
|
2233
|
-
};
|
|
2234
|
-
switch(chunk.path.length > longest && (longest = chunk.path.length), node_path.extname(filePath)){
|
|
2235
|
-
case '.html':
|
|
2236
|
-
chunkGroupMap.HTML.chunks.push(chunk);
|
|
2237
|
-
break;
|
|
2238
|
-
case '.css':
|
|
2239
|
-
chunkGroupMap.CSS.chunks.push(chunk);
|
|
2240
|
-
break;
|
|
2182
|
+
}))(depInfo)));
|
|
2183
|
+
((cache)=>{
|
|
2184
|
+
if (0 === Object.keys(cache).length) {
|
|
2185
|
+
node_fs.existsSync(failedDepsJsonPath) && node_fs.unlinkSync(failedDepsJsonPath);
|
|
2186
|
+
return;
|
|
2187
|
+
}
|
|
2188
|
+
let cacheDir = node_path.dirname(failedDepsJsonPath);
|
|
2189
|
+
node_fs.existsSync(cacheDir) || node_fs.mkdirSync(cacheDir, {
|
|
2190
|
+
recursive: !0
|
|
2191
|
+
}), node_fs.writeFileSync(failedDepsJsonPath, JSON.stringify(cache, null, 2), 'utf-8');
|
|
2192
|
+
})(failedCache);
|
|
2193
|
+
let externals1 = {};
|
|
2194
|
+
bundledDeps.filter(Boolean).forEach((dep)=>{
|
|
2195
|
+
dep && (externals1[dep.name] = getExternalValue(dep.name), dep.assets.forEach((absPath)=>{
|
|
2196
|
+
let relativePath = node_path.relative(bundledDepsCachePath, absPath), serverPath = `/umd/${relativePath}`;
|
|
2197
|
+
switch(node_path.extname(relativePath)){
|
|
2241
2198
|
case '.js':
|
|
2242
|
-
|
|
2243
|
-
|
|
2199
|
+
FRAMEWORKS.includes(dep.name) ? preJsAssets.push({
|
|
2200
|
+
path: serverPath,
|
|
2201
|
+
order: FRAMEWORKS.indexOf(dep.name)
|
|
2202
|
+
}) : jsAssets.push(serverPath);
|
|
2244
2203
|
break;
|
|
2245
|
-
|
|
2246
|
-
|
|
2204
|
+
case '.css':
|
|
2205
|
+
ignoreCSSDeps.includes(dep.name) || cssAssets.push(serverPath);
|
|
2206
|
+
}
|
|
2207
|
+
}));
|
|
2208
|
+
});
|
|
2209
|
+
let existingExternals = config.externals ? Array.isArray(config.externals) ? config.externals : [
|
|
2210
|
+
config.externals
|
|
2211
|
+
] : [];
|
|
2212
|
+
return config.externals = [
|
|
2213
|
+
externals1,
|
|
2214
|
+
...existingExternals
|
|
2215
|
+
], shouldTransformDeepImport && (plugin.transform = {
|
|
2216
|
+
filter: {
|
|
2217
|
+
test: JSX_REGEX
|
|
2218
|
+
},
|
|
2219
|
+
handler: (code)=>SPECIAL_NO_ENTRY_DEPS.some((pkg)=>code.includes(pkg)) ? code.replace(deepImportRegex, (_, localName, importPath, pkgName)=>{
|
|
2220
|
+
let exportName = pathToExportIdentifier(importPath.slice(pkgName.length + 1));
|
|
2221
|
+
return `import { ${exportName} as ${localName} } from '${pkgName}'`;
|
|
2222
|
+
}) : null
|
|
2223
|
+
}), config;
|
|
2224
|
+
},
|
|
2225
|
+
transformHtml: (html)=>injectToHead(html, preJsAssets.sort((a, b)=>a.order - b.order).map((item)=>item.path).map((item)=>`<script defer src="${item}"></script>`).join('')),
|
|
2226
|
+
setupMiddlewares: (middlewares)=>[
|
|
2227
|
+
(req, res, next)=>{
|
|
2228
|
+
if ('string' != typeof req.url) return void next();
|
|
2229
|
+
let url = new URL(req.url, 'http://localhost');
|
|
2230
|
+
if (!url.pathname.startsWith("/umd/")) return void next();
|
|
2231
|
+
let relativePath = url.pathname.replace("/umd/", '');
|
|
2232
|
+
if (relativePath.includes('..')) {
|
|
2233
|
+
res.statusCode = 403, res.end();
|
|
2234
|
+
return;
|
|
2235
|
+
}
|
|
2236
|
+
let filePath = node_path.join(bundledDepsCachePath, relativePath);
|
|
2237
|
+
if (!node_fs.existsSync(filePath)) return void next();
|
|
2238
|
+
let stat = node_fs.statSync(filePath);
|
|
2239
|
+
if (!stat.isFile()) return void next();
|
|
2240
|
+
let mtime = stat.mtime.toUTCString(), ext = node_path.extname(filePath);
|
|
2241
|
+
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) {
|
|
2242
|
+
res.statusCode = 304, res.end();
|
|
2243
|
+
return;
|
|
2247
2244
|
}
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2245
|
+
res.statusCode = 200, node_fs.createReadStream(filePath).pipe(res);
|
|
2246
|
+
},
|
|
2247
|
+
...middlewares
|
|
2248
|
+
],
|
|
2249
|
+
bundlerConfig: (config)=>{
|
|
2250
|
+
let PLUGIN_NAME = 'InjectAssetsPlugin';
|
|
2251
|
+
return config.plugins.push({
|
|
2252
|
+
apply: (compiler)=>{
|
|
2253
|
+
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
|
|
2254
|
+
rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(PLUGIN_NAME, async (args)=>(args.assets.js.unshift(...jsAssets), args.assets.css.unshift(...cssAssets), args));
|
|
2254
2255
|
});
|
|
2256
|
+
}
|
|
2257
|
+
}), config;
|
|
2258
|
+
}
|
|
2259
|
+
}),
|
|
2260
|
+
(root = '', {
|
|
2261
|
+
name: 'unpack:file-size',
|
|
2262
|
+
apply: (config, { mode })=>'production' === mode && config.performance?.printFileSize,
|
|
2263
|
+
configResolved (config) {
|
|
2264
|
+
root = config.root;
|
|
2265
|
+
},
|
|
2266
|
+
buildEnd: async (options)=>{
|
|
2267
|
+
let { stats } = options;
|
|
2268
|
+
if (stats.hasErrors()) return;
|
|
2269
|
+
let chunkGroups = [
|
|
2270
|
+
{
|
|
2271
|
+
type: 'HTML',
|
|
2272
|
+
color: 'green',
|
|
2273
|
+
chunks: []
|
|
2274
|
+
},
|
|
2275
|
+
{
|
|
2276
|
+
type: 'Assets',
|
|
2277
|
+
color: 'yellow',
|
|
2278
|
+
chunks: []
|
|
2279
|
+
},
|
|
2280
|
+
{
|
|
2281
|
+
type: 'CSS',
|
|
2282
|
+
color: 'magenta',
|
|
2283
|
+
chunks: []
|
|
2284
|
+
},
|
|
2285
|
+
{
|
|
2286
|
+
type: 'JS',
|
|
2287
|
+
color: 'cyan',
|
|
2288
|
+
chunks: []
|
|
2289
|
+
}
|
|
2290
|
+
], 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;
|
|
2291
|
+
logUpdate('computing gzip size...'), await Promise.all(assets.map(async ([assetName, value])=>{
|
|
2292
|
+
let content, compressedSize, filePath = assetName.split('?')[0];
|
|
2293
|
+
try {
|
|
2294
|
+
content = value.source();
|
|
2295
|
+
} catch {
|
|
2296
|
+
content = node_fs.readFileSync(node_path.join(distPath, filePath));
|
|
2297
|
+
}
|
|
2298
|
+
let size = Buffer.byteLength(content);
|
|
2299
|
+
compressedSize = COMPRESSIBLE_REGEX.test(filePath) ? await getCompressedSize(content) : size, totalSize += size, totalCompressedSize += compressedSize;
|
|
2300
|
+
let chunk = {
|
|
2301
|
+
name: node_path.basename(filePath),
|
|
2302
|
+
path: `${distFolder}/${filePath}`,
|
|
2303
|
+
size,
|
|
2304
|
+
compressedSize
|
|
2305
|
+
};
|
|
2306
|
+
switch(chunk.path.length > longest && (longest = chunk.path.length), node_path.extname(filePath)){
|
|
2307
|
+
case '.html':
|
|
2308
|
+
chunkGroupMap.HTML.chunks.push(chunk);
|
|
2309
|
+
break;
|
|
2310
|
+
case '.css':
|
|
2311
|
+
chunkGroupMap.CSS.chunks.push(chunk);
|
|
2312
|
+
break;
|
|
2313
|
+
case '.js':
|
|
2314
|
+
case '.wasm':
|
|
2315
|
+
chunkGroupMap.JS.chunks.push(chunk);
|
|
2316
|
+
break;
|
|
2317
|
+
default:
|
|
2318
|
+
chunkGroupMap.Assets.chunks.push(chunk);
|
|
2319
|
+
}
|
|
2320
|
+
})), logUpdate(`✓ computed gzip size (${assets.length})`), console.log();
|
|
2321
|
+
let sizePad = displaySize(totalSize).length, compressPad = displaySize(totalCompressedSize).length;
|
|
2322
|
+
chunkGroups.forEach((group)=>{
|
|
2323
|
+
group.chunks.sort((a, b)=>a.size - b.size).forEach((chunk)=>{
|
|
2324
|
+
let isLarge = 'JS' === group.type && chunk.size / 1000 > 500, relativeOutDir = node_path.dirname(chunk.path) + '/', log = colors.dim(relativeOutDir);
|
|
2325
|
+
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)}`));
|
|
2255
2326
|
});
|
|
2256
|
-
|
|
2257
|
-
|
|
2327
|
+
});
|
|
2328
|
+
let log = colors.blue('Total'.padEnd(longest + 2));
|
|
2329
|
+
log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` │ gzip: ${displaySize(totalCompressedSize)}`));
|
|
2330
|
+
}
|
|
2331
|
+
})
|
|
2332
|
+
]
|
|
2333
|
+
}, userConfig);
|
|
2334
|
+
return mergedConfig.svgIcons && mergedConfig.plugins?.push((options = mergedConfig.svgIcons, rootPath1 = '', inject = options.inject || 'body-last', domId = options.customDomId || '__svg__icons__dom__', registerCode = '', namesCode = '', virtualModules = null, ensureVirtualModules = ()=>{
|
|
2335
|
+
let root;
|
|
2336
|
+
if (!rootPath1) return;
|
|
2337
|
+
let { svg, names } = ((iconDirs, symbolId, customDomId)=>{
|
|
2338
|
+
let symbols = [], names = [], idSet = new Set();
|
|
2339
|
+
for (let dir of iconDirs)for (let file of readSvgFiles(dir)){
|
|
2340
|
+
let { inner, viewBox } = extractSvgContent(normalizeSvg(node_fs.readFileSync(file, 'utf-8'))), id = toSymbolId(file, dir, symbolId);
|
|
2341
|
+
!id || idSet.has(id) || (idSet.add(id), names.push(id), symbols.push(`<symbol id="${id}"${viewBox ? ` viewBox="${viewBox}"` : ''}>${inner}</symbol>`));
|
|
2342
|
+
}
|
|
2343
|
+
return {
|
|
2344
|
+
svg: `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="${customDomId}" style="position: absolute; width: 0; height: 0" aria-hidden="true">${symbols.join('')}</svg>`,
|
|
2345
|
+
names
|
|
2346
|
+
};
|
|
2347
|
+
})((root = rootPath1, (options.iconDirs || []).map((dir)=>node_path.isAbsolute(dir) ? dir : node_path.resolve(root, dir))), options.symbolId, domId);
|
|
2348
|
+
registerCode = `const svgDomId = ${JSON.stringify(domId)}\nconst svgHtml = ${JSON.stringify(svg)}\nconst inject = (position) => {\n if (typeof document === 'undefined') return\n if (document.getElementById(svgDomId)) return\n const div = document.createElement('div')\n div.innerHTML = svgHtml\n const svgEl = div.firstElementChild\n if (!svgEl) return\n if (position === 'head' && document.head) {\n document.head.prepend(svgEl)\n return\n }\n const body = document.body\n if (!body) return\n if (position === 'body-first' && body.firstChild) {\n body.insertBefore(svgEl, body.firstChild)\n } else {\n body.appendChild(svgEl)\n }\n}\nconst mount = () => inject(${JSON.stringify(inject)})\nif (typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', mount)\n } else {\n mount()\n }\n}\nexport default mount`, namesCode = `export const svgIconNames = ${JSON.stringify(names)}\nexport default svgIconNames`;
|
|
2349
|
+
}, {
|
|
2350
|
+
name: 'unpack:svg-icons',
|
|
2351
|
+
configResolved: (config)=>{
|
|
2352
|
+
rootPath1 = config.root || process.cwd(), ensureVirtualModules();
|
|
2353
|
+
},
|
|
2354
|
+
bundlerConfig: (config, { mergeConfig })=>(virtualModules || (virtualModules = new rspack.experiments.VirtualModulesPlugin({
|
|
2355
|
+
[REGISTER_ID]: registerCode || 'export default null',
|
|
2356
|
+
[NAMES_ID]: namesCode || 'export default []'
|
|
2357
|
+
})), mergeConfig(config, {
|
|
2358
|
+
plugins: [
|
|
2359
|
+
virtualModules,
|
|
2360
|
+
{
|
|
2361
|
+
apply: (compiler)=>{
|
|
2362
|
+
compiler.hooks.thisCompilation.tap('UnpackSvgIconsVirtualModules', ()=>{
|
|
2363
|
+
ensureVirtualModules(), virtualModules?.writeModule?.(REGISTER_ID, registerCode || 'export default null'), virtualModules?.writeModule?.(NAMES_ID, namesCode || 'export default []');
|
|
2364
|
+
});
|
|
2365
|
+
}
|
|
2258
2366
|
}
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2367
|
+
]
|
|
2368
|
+
})),
|
|
2369
|
+
transform: {
|
|
2370
|
+
filter: {
|
|
2371
|
+
test: JS_REGEX
|
|
2372
|
+
},
|
|
2373
|
+
handler: (code)=>code.includes('virtual:svg-icons-') ? code.replace('virtual:svg-icons-', 'virtual-svg-icons-') : null
|
|
2374
|
+
}
|
|
2375
|
+
})), {
|
|
2376
|
+
...mergedConfig,
|
|
2262
2377
|
_context
|
|
2263
2378
|
};
|
|
2264
2379
|
};
|
|
@@ -2267,7 +2382,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
|
|
|
2267
2382
|
let mode = watch ? 'development' : 'production';
|
|
2268
2383
|
setNodeEnv(mode);
|
|
2269
2384
|
let config = resolveConfig(mode);
|
|
2270
|
-
console.log(colors.brand(`${callerName}
|
|
2385
|
+
console.log(colors.brand(`${callerName} v4.1.0${config.performance?.cache ? ' ϟ' : ''}`), colors.cyan(`building for ${mode}...`)), await unpackBuild(config);
|
|
2271
2386
|
},
|
|
2272
2387
|
dev: async ()=>{
|
|
2273
2388
|
setUnpackStartTime(performance.now());
|
|
@@ -2285,7 +2400,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
|
|
|
2285
2400
|
let GLOB_REGEX = /[*?{}[\]()!@+|]/;
|
|
2286
2401
|
async function createChokidar(pathOrGlobs, root = process.cwd(), options) {
|
|
2287
2402
|
let watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
|
|
2288
|
-
if (globPatterns.length) for (let file of (await
|
|
2403
|
+
if (globPatterns.length) for (let file of (await external_tinyglobby_glob(globPatterns, {
|
|
2289
2404
|
cwd: root,
|
|
2290
2405
|
absolute: !0
|
|
2291
2406
|
})))watchFiles.add(file);
|
|
@@ -2295,5 +2410,128 @@ async function createChokidar(pathOrGlobs, root = process.cwd(), options) {
|
|
|
2295
2410
|
...options
|
|
2296
2411
|
});
|
|
2297
2412
|
}
|
|
2413
|
+
var injectFramework_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
2414
|
+
async function injectFrameworkPluginForDebug(userConfig) {
|
|
2415
|
+
var plugin;
|
|
2416
|
+
let raw, framework, framework1 = (raw = process.env.FRAMEWORK, (framework = raw?.trim().toLowerCase()) ? 'react' === framework || 'vue' === framework ? framework : (logger_logger.warn(`Unknown FRAMEWORK "${raw}", fallback to "react".`), 'react') : 'react'), pluginPath = node_path.resolve(injectFramework_dirname, `../../plugin-${framework1}/dist/index.js`);
|
|
2417
|
+
node_fs.existsSync(pluginPath) && (plugin = (0, (await import(pluginPath))[`plugin${framework1.charAt(0).toUpperCase() + framework1.slice(1)}`])(), userConfig.plugins ? userConfig.plugins.unshift(plugin) : userConfig.plugins = [
|
|
2418
|
+
plugin
|
|
2419
|
+
]);
|
|
2420
|
+
}
|
|
2421
|
+
async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer }) {
|
|
2422
|
+
let shortcuts = [
|
|
2423
|
+
restartServer ? {
|
|
2424
|
+
key: 'r',
|
|
2425
|
+
description: 'restart server',
|
|
2426
|
+
action: restartServer
|
|
2427
|
+
} : null,
|
|
2428
|
+
{
|
|
2429
|
+
key: 'u',
|
|
2430
|
+
description: 'show server url',
|
|
2431
|
+
action: printUrls
|
|
2432
|
+
},
|
|
2433
|
+
{
|
|
2434
|
+
key: 'o',
|
|
2435
|
+
description: 'open in browser',
|
|
2436
|
+
action: openPage
|
|
2437
|
+
},
|
|
2438
|
+
{
|
|
2439
|
+
key: 'c',
|
|
2440
|
+
description: 'clear console',
|
|
2441
|
+
action: ()=>{
|
|
2442
|
+
logger_logger.clear();
|
|
2443
|
+
}
|
|
2444
|
+
},
|
|
2445
|
+
{
|
|
2446
|
+
key: 'q',
|
|
2447
|
+
description: 'quit',
|
|
2448
|
+
action: async ()=>{
|
|
2449
|
+
try {
|
|
2450
|
+
await closeServer();
|
|
2451
|
+
} finally{
|
|
2452
|
+
process.exit(0);
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
].filter(Boolean), colorPrefix = colors.brand(colors.dim('➜'));
|
|
2457
|
+
help && console.log(!0 === help ? ` ${colorPrefix} ${colors.dim('press')} ${colors.bold('h + enter')} ${colors.dim('to show help')}` : ` ${colorPrefix} ${help}`);
|
|
2458
|
+
let { createInterface } = await import("node:readline"), rl = createInterface({
|
|
2459
|
+
input: process.stdin
|
|
2460
|
+
});
|
|
2461
|
+
rl.on('line', (input)=>{
|
|
2462
|
+
if ('h' === input) {
|
|
2463
|
+
let message = '\n Shortcuts\n';
|
|
2464
|
+
for (let shortcut of shortcuts){
|
|
2465
|
+
let fullDescription = `${colors.dim('press')} ${colors.bold(`${shortcut.key} + enter`)} ${colors.dim(`to ${shortcut.description}`)}`;
|
|
2466
|
+
message += ` ${fullDescription}\n`;
|
|
2467
|
+
}
|
|
2468
|
+
console.log(message);
|
|
2469
|
+
}
|
|
2470
|
+
for (let shortcut of shortcuts)if (input === shortcut.key) return void shortcut.action();
|
|
2471
|
+
}), addRestartCleaner(()=>rl.close());
|
|
2472
|
+
}
|
|
2473
|
+
let withErrorHandling = (action)=>async (options)=>{
|
|
2474
|
+
try {
|
|
2475
|
+
await action(options);
|
|
2476
|
+
} catch (e) {
|
|
2477
|
+
logger_logger.error(e), process.exit(1);
|
|
2478
|
+
}
|
|
2479
|
+
};
|
|
2480
|
+
async function setupUnpack(cliOptions, command) {
|
|
2481
|
+
cliOptions.debug && (process.env.DEBUG = 'unpack');
|
|
2482
|
+
let userConfig = await loadConfig({
|
|
2483
|
+
cliOptions,
|
|
2484
|
+
command
|
|
2485
|
+
});
|
|
2486
|
+
return await injectFrameworkPluginForDebug(userConfig), {
|
|
2487
|
+
unpack: createUnpack({
|
|
2488
|
+
cwd: userConfig.root,
|
|
2489
|
+
config: userConfig
|
|
2490
|
+
}),
|
|
2491
|
+
config: userConfig
|
|
2492
|
+
};
|
|
2493
|
+
}
|
|
2494
|
+
function runCLI() {
|
|
2495
|
+
let cli = cac('unpack');
|
|
2496
|
+
cli.option('-c, --config <file>', 'Use specified config file').option('-r, --root <dir>', 'Specify root directory').option('-d, --debug', 'Show debug logs');
|
|
2497
|
+
let devCommand = cli.command('', 'Start dev server').alias('dev'), buildCommand = cli.command('build', 'Build for production'), cleanCommand = cli.command('clean', 'Clean cache directory');
|
|
2498
|
+
buildCommand.option('-w, --watch', 'Rebuilds when modules have changed on disk').option('--analyze', 'Analyze the size of output files').action(withErrorHandling(async (options)=>{
|
|
2499
|
+
let { unpack } = await setupUnpack(options, 'build');
|
|
2500
|
+
await unpack.build({
|
|
2501
|
+
watch: options.watch
|
|
2502
|
+
});
|
|
2503
|
+
})), cleanCommand.action(withErrorHandling(async (options)=>{
|
|
2504
|
+
let { unpack } = await setupUnpack(options, 'build');
|
|
2505
|
+
unpack.clean();
|
|
2506
|
+
}));
|
|
2507
|
+
let startServer = withErrorHandling(async (options)=>{
|
|
2508
|
+
let { unpack, config } = await setupUnpack(options, 'dev'), { port, url } = await unpack.dev();
|
|
2509
|
+
await setupCliShortcuts({
|
|
2510
|
+
openPage: async ()=>{
|
|
2511
|
+
await openBrowser(url);
|
|
2512
|
+
},
|
|
2513
|
+
closeServer: async ()=>{
|
|
2514
|
+
await cleanUpBeforeRestart(), process.exit(0);
|
|
2515
|
+
},
|
|
2516
|
+
printUrls: ()=>{
|
|
2517
|
+
printServerUrls({
|
|
2518
|
+
port,
|
|
2519
|
+
host: config.server.host,
|
|
2520
|
+
base: config.base
|
|
2521
|
+
});
|
|
2522
|
+
},
|
|
2523
|
+
restartServer: async ()=>{
|
|
2524
|
+
logger_logger.clear(), await cleanUpBeforeRestart(), startServer(options);
|
|
2525
|
+
}
|
|
2526
|
+
});
|
|
2527
|
+
let watcher = await createChokidar([
|
|
2528
|
+
'unpack.config.*'
|
|
2529
|
+
], config.root);
|
|
2530
|
+
watcher.on('change', async (file)=>{
|
|
2531
|
+
logger_logger.clear(), logger_logger.info(`${node_path.basename(file)} changed, restarting server...`), await watcher.close(), await cleanUpBeforeRestart(), startServer(options);
|
|
2532
|
+
});
|
|
2533
|
+
});
|
|
2534
|
+
devCommand.option('-o, --open [url]', 'Open browser on startup').option('--port <port>', 'Specify port').option('--host', 'Expose hostname').action(startServer), cli.help(), cli.version("4.1.0"), cli.parse();
|
|
2535
|
+
}
|
|
2298
2536
|
var src_CSS_MODULES_NAMED_EXPORT = !1;
|
|
2299
|
-
export { ALL_INTERFACES_IPV4, CSS_MODULES_EXPORTS_CONVENTION, CSS_MODULES_LOCAL_IDENT_NAME, DEV_DEFAULT_FILENAME, JSX_REGEX, JS_REGEX, LOCALHOST, 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, 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,
|
|
2537
|
+
export { ALL_INTERFACES_IPV4, CSS_MODULES_EXPORTS_CONVENTION, CSS_MODULES_LOCAL_IDENT_NAME, DEV_DEFAULT_FILENAME, JSX_REGEX, JS_REGEX, LOCALHOST, NODE_MODULES_REGEX, PROD_DEFAULT_FILENAME, SCRIPT_REGEX, TEMPLATE_CONTENT, addRestartCleaner, cleanUpBeforeRestart, clearLine, colors, convertBasicAnsiColors, createChokidar, createUnpack, debounce, defineConfig, esVersionToBrowserslist, external_tinyglobby_glob as glob, findExists, getAddressUrls, getCompiledPkgPath, getCurrentUnpackConfig, getHtmlTemplateOrContent, getIpv4Interfaces, getNodeEnv, getOrSetDefault, getPathInJs, getPort, getTime, getUnpackStartTime, getUserDepPath, getUserDepVersion, globSync, injectToHead, isBoolean, 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, normalizePublicPath, openBrowser, pLimit, pathExists, pathToExportIdentifier, prettyTime, printServerUrls, removeDir, resolveConfigPath, rspack, runCLI, set, setCurrentUnpackConfig, setDevServer, setNodeEnv, setUnpackStartTime, src_CSS_MODULES_NAMED_EXPORT as CSS_MODULES_NAMED_EXPORT, trackPerformance, utils_isDevServer as isDevServer, utils_isProd as isProd, utils_mergeConfig as mergeConfig };
|