@unpackjs/core 4.0.0 → 4.2.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/compiled/css-loader/index.js +48 -39
- package/compiled/css-loader/package.json +1 -1
- 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 +1024 -623
- package/dist/transformLoader.js +12 -3
- 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/transformLoader.d.ts +1 -0
- package/dist-types/bundler-config/loaders/transformLoader.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/bundler-config/plugins/registerHooks.d.ts.map +1 -1
- package/dist-types/cli/index.d.ts.map +1 -1
- package/dist-types/cli/injectFramework.d.ts +6 -0
- package/dist-types/cli/injectFramework.d.ts.map +1 -0
- package/dist-types/createUnpack.d.ts.map +1 -1
- package/dist-types/plugin.d.ts +8 -1
- package/dist-types/plugin.d.ts.map +1 -1
- package/dist-types/plugins/autoCssModules.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/plugins/unocss.d.ts +5 -0
- package/dist-types/plugins/unocss.d.ts.map +1 -0
- package/dist-types/types/config.d.ts +38 -12
- package/dist-types/types/config.d.ts.map +1 -1
- package/dist-types/types/plugin.d.ts +13 -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 +12 -7
- package/dist-types/bundler-config/experimentCss.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -6,17 +6,19 @@ 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
8
|
import { __webpack_require__ } from "./rslib-runtime.js";
|
|
9
|
-
import { rspack } from "@rspack/core";
|
|
10
|
-
import node_fs from "node:fs";
|
|
9
|
+
import { Compilation, rspack } from "@rspack/core";
|
|
11
10
|
import cac from "cac";
|
|
11
|
+
import node_fs from "node:fs";
|
|
12
12
|
import node_readline from "node:readline";
|
|
13
13
|
import node_os, { platform } from "node:os";
|
|
14
14
|
import portfinder from "portfinder";
|
|
15
|
+
import { glob as external_tinyglobby_glob, globSync } from "tinyglobby";
|
|
15
16
|
import { format, promisify } from "node:util";
|
|
16
17
|
import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
|
|
17
18
|
import { parse } from "stacktrace-parser";
|
|
18
19
|
import node_zlib from "node:zlib";
|
|
19
|
-
import {
|
|
20
|
+
import { createHash } from "node:crypto";
|
|
21
|
+
import magic_string from "magic-string";
|
|
20
22
|
import { expand } from "dotenv-expand";
|
|
21
23
|
import node_assert from "node:assert";
|
|
22
24
|
import { RspackDevServer } from "@rspack/dev-server";
|
|
@@ -120,7 +122,7 @@ let CSS_MODULES_LOCAL_IDENT_NAME = '[path][name]__[local]--[hash:5]', CSS_MODULE
|
|
|
120
122
|
</body>
|
|
121
123
|
</html>`, JS_REGEX = /\.[jt]s$/, JSX_REGEX = /\.[jt]sx$/, SCRIPT_REGEX = /\.[jt]sx?$/;
|
|
122
124
|
var utils_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
123
|
-
let { merge:
|
|
125
|
+
let { merge: utils_mergeConfig } = __webpack_require__("compiled/webpack-merge"), { default: launchEditor } = __webpack_require__("compiled/launch-editor"), getNodeEnv = ()=>process.env.NODE_ENV, setNodeEnv = (env)=>{
|
|
124
126
|
process.env.NODE_ENV = env;
|
|
125
127
|
}, setDevServer = (isDevServer)=>{
|
|
126
128
|
process.env.DEV_SERVER = isDevServer ? 'true' : 'false';
|
|
@@ -476,31 +478,107 @@ let removeDir = (dir)=>{
|
|
|
476
478
|
currentUnpackConfig = config;
|
|
477
479
|
}, unpackStartTime = 0, getUnpackStartTime = ()=>unpackStartTime, setUnpackStartTime = (time)=>{
|
|
478
480
|
unpackStartTime = time;
|
|
479
|
-
}, STYLE_IMPORT_RE = /import\s+([\s\S]
|
|
481
|
+
}, STYLE_IMPORT_RE = /import\s+((?:(?!\nimport\s)[\s\S])*?)\s+from\s+(['"])([^'"]+?\.(?:css|less|scss|sass)(?:\?[^'"]+)?(?:#[^'"]+)?)\2/g, TYPE_IMPORT_CLAUSE_RE = /^\s*type\b/, STYLE_EXT_HINTS = [
|
|
480
482
|
'.css',
|
|
481
483
|
'.less',
|
|
482
484
|
'.scss',
|
|
483
485
|
'.sass'
|
|
484
|
-
], BROWSER_LOGS_ENDPOINT = '/__browser_logs__',
|
|
486
|
+
], 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', {
|
|
485
487
|
maximumFractionDigits: 2,
|
|
486
488
|
minimumFractionDigits: 2
|
|
487
489
|
}), displaySize = (bytes)=>`${numberFormatter.format(bytes / 1000)} kB`;
|
|
488
490
|
async function getCompressedSize(content) {
|
|
489
491
|
return (await gzip(content)).length;
|
|
490
492
|
}
|
|
491
|
-
let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i,
|
|
493
|
+
let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i, GLOB_MAGIC_RE = /[*?[\]{}()!@+|]/, normalizeBaseDir = (raw)=>{
|
|
494
|
+
let normalized = raw.replace(/\\/g, '/');
|
|
495
|
+
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) : './';
|
|
496
|
+
}, toRegexLiteral = (source)=>`/${source.replace(/\\?\//g, (value)=>'/' === value ? '\\/' : value)}/`, parseGlob = (pattern)=>{
|
|
497
|
+
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);
|
|
498
|
+
return {
|
|
499
|
+
baseDir,
|
|
500
|
+
regExpSource: ((glob)=>{
|
|
501
|
+
let expansions;
|
|
502
|
+
if (!glob) return '^\\.\\/.*$';
|
|
503
|
+
let { replaced, expansions: expansions1 } = (expansions = [], {
|
|
504
|
+
replaced: glob.replace(/\{([^}]+)\}/g, (_, inner)=>(expansions.push(inner), `__BRACE_${expansions.length - 1}__`)),
|
|
505
|
+
expansions
|
|
506
|
+
}), source = replaced.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
507
|
+
return source = (source = (source = (source = (source = (source = source.replace(/__BRACE_(\d+)__/g, (_, index)=>{
|
|
508
|
+
let parts = (expansions1[Number(index)] || '').split(',').map((part)=>part.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
509
|
+
return `(${parts.join('|')})`;
|
|
510
|
+
})).replace(/\\\(([^)]+)\\\)\\\?/g, (_, inner)=>`(?:${inner})?`)).replace(/\\\*\\\*\\\//g, '(?:.*\\/)?')).replace(/\\\*\\\*/g, '.*')).replace(/\\\*/g, '[^/]*')).replace(/\\\?/g, '[^/]'), `^(?:\\.\\/)?${source}$`;
|
|
511
|
+
})(globPart),
|
|
512
|
+
recursive,
|
|
513
|
+
publicPrefix: './' === baseDir ? './' : baseDir
|
|
514
|
+
};
|
|
515
|
+
}, hasEager = (rawOptions)=>!!rawOptions && /eager\s*:\s*true/.test(rawOptions), SPECIAL_NO_ENTRY_DEPS = [
|
|
492
516
|
'@iconify-icons/material-symbols'
|
|
517
|
+
], FRAMEWORKS = [
|
|
518
|
+
'react',
|
|
519
|
+
'react-dom',
|
|
520
|
+
'react-router-dom',
|
|
521
|
+
'vue',
|
|
522
|
+
'vue-router'
|
|
493
523
|
], getExternalLibraryName = (pkgName)=>{
|
|
494
524
|
let externalAlias = {
|
|
495
|
-
react: 'React',
|
|
496
525
|
'react-dom': 'ReactDOM',
|
|
497
526
|
'react-router-dom': 'ReactRouterDOM'
|
|
498
527
|
};
|
|
499
528
|
return externalAlias[pkgName] ? externalAlias[pkgName] : pkgName.replace(/^@/, '').split(/[/\-.]/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase() + part.slice(1)).join('');
|
|
500
|
-
}, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`,
|
|
529
|
+
}, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`, normalizeSvg = (content)=>content.replace(/<\?xml[\s\S]*?\?>/gi, '').replace(/<!DOCTYPE[\s\S]*?>/gi, '').replace(/<!--[\s\S]*?-->/g, '').trim(), extractSvgContent = (content)=>{
|
|
530
|
+
let match = content.match(/<svg\b([^>]*)>/i), viewBoxMatch = match?.[1]?.match(/viewBox\s*=\s*["']([^"']+)["']/i);
|
|
531
|
+
return {
|
|
532
|
+
inner: content.replace(/^[\s\S]*?<svg\b[^>]*>/i, '').replace(/<\/svg>[\s\S]*$/i, '').trim(),
|
|
533
|
+
viewBox: viewBoxMatch?.[1]
|
|
534
|
+
};
|
|
535
|
+
}, readSvgFiles = (dir, collected = [])=>{
|
|
536
|
+
if (!node_fs.existsSync(dir)) return collected;
|
|
537
|
+
for (let entry of node_fs.readdirSync(dir, {
|
|
538
|
+
withFileTypes: !0
|
|
539
|
+
})){
|
|
540
|
+
let fullPath = node_path.join(dir, entry.name);
|
|
541
|
+
entry.isDirectory() ? readSvgFiles(fullPath, collected) : entry.isFile() && entry.name.toLowerCase().endsWith('.svg') && collected.push(fullPath);
|
|
542
|
+
}
|
|
543
|
+
return collected;
|
|
544
|
+
}, toSymbolId = (filePath, iconDir, symbolId)=>{
|
|
545
|
+
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;
|
|
546
|
+
if ('function' == typeof symbolId) return symbolId(name, filePath);
|
|
547
|
+
let id = (symbolId || 'icon-[dir]-[name]').replace(/\[name\]/g, name).replace(/\[dir\]/g, dir);
|
|
548
|
+
return id.replace(/--+/g, '-').replace(/^-+|-+$/g, '');
|
|
549
|
+
}, UNOCSS_CONFIG_FILES = [
|
|
550
|
+
'unocss.config.mjs',
|
|
551
|
+
'unocss.config.ts',
|
|
552
|
+
'unocss.config.js',
|
|
553
|
+
'unocss.config.mts',
|
|
554
|
+
'uno.config.mjs',
|
|
555
|
+
'uno.config.ts',
|
|
556
|
+
'uno.config.js',
|
|
557
|
+
'uno.config.mts'
|
|
558
|
+
], loadConfigFile = async (configFilePath)=>{
|
|
559
|
+
if (/\.(?:js|mjs)$/.test(configFilePath)) {
|
|
560
|
+
let configFileURL = pathToFileURL(configFilePath).href, exportModule = await import(`${configFileURL}?t=${Date.now()}`);
|
|
561
|
+
return exportModule.default ? exportModule.default : exportModule;
|
|
562
|
+
}
|
|
563
|
+
let { createJiti } = await import("jiti"), jiti = createJiti(import.meta.url, {
|
|
564
|
+
moduleCache: !1,
|
|
565
|
+
interopDefault: !0,
|
|
566
|
+
nativeModules: [
|
|
567
|
+
'@rspack/core',
|
|
568
|
+
"typescript"
|
|
569
|
+
]
|
|
570
|
+
});
|
|
571
|
+
return await jiti.import(configFilePath, {
|
|
572
|
+
default: !0
|
|
573
|
+
});
|
|
574
|
+
}, LAYER_MARK_ALL = '__ALL__', HASH_PLACEHOLDER_RE = /#--unocss-hash--\s*\{\s*content\s*:\s*\\*"([^\\"]+)\\*";?\s*\}/g, LAYER_PLACEHOLDER_RE = /#--unocss--\s*\{\s*layer\s*:\s*(.+?)\s*(?:;\s*escape-view\s*:\s*(.+?)\s*)?;?\s*\}/g, SKIP_START_COMMENT = '@unocss-skip-start', SKIP_END_COMMENT = '@unocss-skip-end', SKIP_COMMENT_RE = RegExp(`(?://\\s*?${SKIP_START_COMMENT}\\s*?|/\\*\\s*?${SKIP_START_COMMENT}\\s*?\\*/|<!--\\s*?${SKIP_START_COMMENT}\\s*?-->)[\\s\\S]*?(?://\\s*?${SKIP_END_COMMENT}\\s*?|/\\*\\s*?${SKIP_END_COMMENT}\\s*?\\*/|<!--\\s*?${SKIP_END_COMMENT}\\s*?-->)`, 'g'), getCssEscaperForJsContent = (view)=>{
|
|
575
|
+
if (!view) return (css)=>css;
|
|
576
|
+
let prefix = {};
|
|
577
|
+
return view.trim().replace(/(\\*)\\(["'`\\])/g, (_, bs, char)=>(prefix[char] = bs.replace(/\\\\/g, '\\'), '')), (css)=>css.replace(/["'`\\]/g, (v)=>(prefix[v] || '') + v);
|
|
578
|
+
}, DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
|
|
501
579
|
function getNormalizedPluginsByHook(hook) {
|
|
502
580
|
let pluginMap = new Map();
|
|
503
|
-
|
|
581
|
+
(getCurrentUnpackConfig().plugins?.flat(1 / 0) || []).forEach((plugin)=>{
|
|
504
582
|
plugin && ((plugin, hook)=>{
|
|
505
583
|
if (!plugin[hook]) return !1;
|
|
506
584
|
let apply = plugin.apply;
|
|
@@ -511,12 +589,60 @@ function getNormalizedPluginsByHook(hook) {
|
|
|
511
589
|
};
|
|
512
590
|
return 'string' == typeof apply ? apply === env.command : !!apply(getCurrentUnpackConfig(), env);
|
|
513
591
|
})(plugin, hook) && pluginMap.set(plugin.name, plugin);
|
|
514
|
-
})
|
|
592
|
+
});
|
|
593
|
+
let normalizedPlugins = Array.from(pluginMap.values()), enforceOrder = (plugin)=>'pre' === plugin.enforce ? 0 : 'post' === plugin.enforce ? 2 : 1;
|
|
594
|
+
return normalizedPlugins.map((plugin, index)=>({
|
|
595
|
+
plugin,
|
|
596
|
+
index
|
|
597
|
+
})).sort((a, b)=>{
|
|
598
|
+
let diff = enforceOrder(a.plugin) - enforceOrder(b.plugin);
|
|
599
|
+
return 0 !== diff ? diff : a.index - b.index;
|
|
600
|
+
}).map((item)=>item.plugin);
|
|
515
601
|
}
|
|
602
|
+
let createPluginHookTimer = (plugin, hook)=>{
|
|
603
|
+
let startTime = 0;
|
|
604
|
+
return {
|
|
605
|
+
start: ()=>{
|
|
606
|
+
startTime = performance.now();
|
|
607
|
+
},
|
|
608
|
+
end: ()=>{
|
|
609
|
+
let duration = performance.now() - startTime;
|
|
610
|
+
logger_logger.debug(`${colors.magenta('[plugin]')} ${colors.cyan(plugin.name)} ${colors.blue(hook)} ${colors.dim('in')} ${colors.yellow(`${duration.toFixed(2)}ms`)}`);
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
}, TRANSFORM_TIMING_STORE = Symbol.for('unpack:transformTimingMap'), globalScope = globalThis, transformTimingMap = globalScope[TRANSFORM_TIMING_STORE] ?? new WeakMap();
|
|
516
614
|
async function applyPluginsByHook(hook, runner) {
|
|
615
|
+
let shouldMeasure = 'processAssets' !== hook && 'transform' !== hook;
|
|
616
|
+
for (let plugin of getNormalizedPluginsByHook(hook)){
|
|
617
|
+
let impl = plugin[hook];
|
|
618
|
+
if (!shouldMeasure) {
|
|
619
|
+
await runner(impl, plugin);
|
|
620
|
+
continue;
|
|
621
|
+
}
|
|
622
|
+
let timer = createPluginHookTimer(plugin, hook);
|
|
623
|
+
timer.start();
|
|
624
|
+
try {
|
|
625
|
+
await runner(impl, plugin);
|
|
626
|
+
} finally{
|
|
627
|
+
timer.end();
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
function applyPluginsByHookSync(hook, runner) {
|
|
632
|
+
let shouldMeasure = 'processAssets' !== hook && 'transform' !== hook;
|
|
517
633
|
for (let plugin of getNormalizedPluginsByHook(hook)){
|
|
518
634
|
let impl = plugin[hook];
|
|
519
|
-
|
|
635
|
+
if (!shouldMeasure) {
|
|
636
|
+
runner(impl, plugin);
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
let timer = createPluginHookTimer(plugin, hook);
|
|
640
|
+
timer.start();
|
|
641
|
+
try {
|
|
642
|
+
runner(impl, plugin);
|
|
643
|
+
} finally{
|
|
644
|
+
timer.end();
|
|
645
|
+
}
|
|
520
646
|
}
|
|
521
647
|
}
|
|
522
648
|
async function applyBuildAnalyzeConfig({ config, unpackConfig }) {
|
|
@@ -561,7 +687,7 @@ async function applyCacheConfig({ config, unpackConfig, envFilePaths }) {
|
|
|
561
687
|
let cacheConfig = isPlainObject(unpackConfig.performance.cache) ? unpackConfig.performance.cache : {}, buildDependencies = await getBuildDependencies(unpackConfig.root);
|
|
562
688
|
buildDependencies.userBuildDependencies = cacheConfig.buildDependencies || [], buildDependencies.envFilePaths = envFilePaths;
|
|
563
689
|
let cacheDirectory = node_path.resolve(unpackConfig.root, cacheConfig.cacheDirectory || `${unpackConfig._context.cachePath}/cache`, utils_isDevServer() ? 'dev' : 'build');
|
|
564
|
-
return
|
|
690
|
+
return utils_mergeConfig(config, {
|
|
565
691
|
cache: !0,
|
|
566
692
|
experiments: {
|
|
567
693
|
cache: {
|
|
@@ -575,6 +701,7 @@ async function applyCacheConfig({ config, unpackConfig, envFilePaths }) {
|
|
|
575
701
|
}
|
|
576
702
|
});
|
|
577
703
|
}
|
|
704
|
+
globalScope[TRANSFORM_TIMING_STORE] = transformTimingMap;
|
|
578
705
|
let MODULE_PATH_REGEX = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\/])?([^\\/]+)/, SPLIT_STRATEGY_DISPATCHER = {
|
|
579
706
|
'split-by-module': function(ctx) {
|
|
580
707
|
let { forceSplittingGroups, defaultConfig } = ctx;
|
|
@@ -661,7 +788,7 @@ let MODULE_PATH_REGEX = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\
|
|
|
661
788
|
};
|
|
662
789
|
async function getEntry(root, customEntry) {
|
|
663
790
|
let entry;
|
|
664
|
-
if (entry = customEntry ? node_path.resolve(root, customEntry) : (await
|
|
791
|
+
if (entry = customEntry ? node_path.resolve(root, customEntry) : (await external_tinyglobby_glob('(index|Index).{js,ts,jsx,tsx}', {
|
|
665
792
|
cwd: node_path.join(root, 'src'),
|
|
666
793
|
absolute: !0
|
|
667
794
|
}))[0], !node_fs.existsSync(entry)) throw Error('could not find entry file');
|
|
@@ -691,6 +818,7 @@ async function applyHtmlConfig({ config, unpackConfig }) {
|
|
|
691
818
|
]
|
|
692
819
|
})), config;
|
|
693
820
|
}
|
|
821
|
+
var nativeCss_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
694
822
|
let { RawSource: RawSource, SourceMapSource: SourceMapSource } = rspack.sources, isJsFile = /\.[cm]?js(\?.*)?$/i, jsMinify_PLUGIN_NAME = 'JsMinifyPlugin';
|
|
695
823
|
class JsMinifyPlugin {
|
|
696
824
|
minifyOptions;
|
|
@@ -702,7 +830,7 @@ class JsMinifyPlugin {
|
|
|
702
830
|
apply(compiler) {
|
|
703
831
|
let meta = JSON.stringify({
|
|
704
832
|
name: jsMinify_PLUGIN_NAME,
|
|
705
|
-
version: "4.
|
|
833
|
+
version: "4.2.0",
|
|
706
834
|
options: this.minifyOptions
|
|
707
835
|
});
|
|
708
836
|
compiler.hooks.compilation.tap(jsMinify_PLUGIN_NAME, (compilation)=>{
|
|
@@ -805,15 +933,15 @@ async function compileDone(compiler, stats) {
|
|
|
805
933
|
if (!fileInfo) return;
|
|
806
934
|
if (fileInfo === lastFileInfo ? sameCount++ : (lastFileInfo = fileInfo, sameCount = 1), isDebug()) {
|
|
807
935
|
var modules;
|
|
808
|
-
let nodeModulesStats, nodeModulesPath;
|
|
809
|
-
Object.entries((modules = stats.compilation.modules, nodeModulesStats = {}, nodeModulesPath = node_path.resolve(root, 'node_modules'), modules.forEach((module)=>{
|
|
936
|
+
let nodeModulesStats, nodeModulesPath, sortedStats;
|
|
937
|
+
(sortedStats = Object.entries((modules = stats.compilation.modules, nodeModulesStats = {}, nodeModulesPath = node_path.resolve(root, 'node_modules'), modules.forEach((module)=>{
|
|
810
938
|
let { resource } = module;
|
|
811
939
|
if (resource?.includes(nodeModulesPath)) {
|
|
812
940
|
let packageName, pathParts = node_path.relative(nodeModulesPath, resource).split(sep);
|
|
813
941
|
(packageName = '.pnpm' === pathParts[0] && pathParts.length >= 4 ? pathParts[3].startsWith('@') ? `${pathParts[3]}/${pathParts[4]}` : pathParts[3] : pathParts[0].startsWith('@') ? `${pathParts[0]}/${pathParts[1]}` : pathParts[0]) && (nodeModulesStats[packageName] = (nodeModulesStats[packageName] || 0) + 1);
|
|
814
942
|
}
|
|
815
|
-
}), nodeModulesStats)).sort((a, b)=>a[1] - b[1]).forEach(([packageName, count])=>{
|
|
816
|
-
|
|
943
|
+
}), nodeModulesStats)).sort((a, b)=>a[1] - b[1])).forEach(([packageName, count], i)=>{
|
|
944
|
+
i >= sortedStats.length - 10 && logger_logger.debug(`[dependency] ${colors.cyan(packageName)}: ${colors.yellow(count)} modules`);
|
|
817
945
|
});
|
|
818
946
|
}
|
|
819
947
|
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)`) : '');
|
|
@@ -847,7 +975,8 @@ let registerHooks_PLUGIN_NAME = 'RegisterHooksPlugin';
|
|
|
847
975
|
class RegisterHooksPlugin {
|
|
848
976
|
isFirstCompile = !0;
|
|
849
977
|
apply(compiler) {
|
|
850
|
-
|
|
978
|
+
let virtualModulesPlugin = new rspack.experiments.VirtualModulesPlugin();
|
|
979
|
+
virtualModulesPlugin.apply(compiler), compiler.hooks.beforeCompile.tapPromise(registerHooks_PLUGIN_NAME, async ()=>{
|
|
851
980
|
await applyPluginsByHook('buildStart', async (impl)=>{
|
|
852
981
|
await impl({
|
|
853
982
|
compiler,
|
|
@@ -856,18 +985,54 @@ class RegisterHooksPlugin {
|
|
|
856
985
|
});
|
|
857
986
|
});
|
|
858
987
|
}), compiler.hooks.done.tapPromise(registerHooks_PLUGIN_NAME, async (stats)=>{
|
|
859
|
-
|
|
860
|
-
await impl
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
988
|
+
try {
|
|
989
|
+
await applyPluginsByHook('buildEnd', async (impl)=>{
|
|
990
|
+
await impl({
|
|
991
|
+
compiler,
|
|
992
|
+
isFirstCompile: this.isFirstCompile,
|
|
993
|
+
isWatch: isWatch(),
|
|
994
|
+
stats
|
|
995
|
+
});
|
|
865
996
|
});
|
|
866
|
-
}
|
|
997
|
+
} finally{
|
|
998
|
+
stats?.compilation && ((compilation)=>{
|
|
999
|
+
let pluginMap = transformTimingMap.get(compilation);
|
|
1000
|
+
if (pluginMap) {
|
|
1001
|
+
for (let [pluginName, total] of pluginMap)logger_logger.debug(`${colors.magenta('[plugin]')} ${colors.cyan(pluginName)} ${colors.blue('transform')} ${colors.dim('in')} ${colors.yellow(`${total.toFixed(2)}ms`)}`);
|
|
1002
|
+
transformTimingMap.delete(compilation);
|
|
1003
|
+
}
|
|
1004
|
+
})(stats.compilation);
|
|
1005
|
+
}
|
|
1006
|
+
this.isFirstCompile = !1;
|
|
867
1007
|
}), compiler.hooks.compilation.tap(registerHooks_PLUGIN_NAME, (compilation)=>{
|
|
868
1008
|
rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeEmit.tapPromise(registerHooks_PLUGIN_NAME, async (data)=>(await applyPluginsByHook('transformHtml', async (impl)=>{
|
|
869
1009
|
data.html = await impl(data.html);
|
|
870
1010
|
}), data));
|
|
1011
|
+
}), compiler.hooks.thisCompilation.tap(registerHooks_PLUGIN_NAME, (compilation)=>{
|
|
1012
|
+
applyPluginsByHookSync('virtualModules', (impl)=>{
|
|
1013
|
+
Object.entries(impl()).forEach(([path, content])=>{
|
|
1014
|
+
virtualModulesPlugin.writeModule(path, content);
|
|
1015
|
+
});
|
|
1016
|
+
}), applyPluginsByHook('processAssets', (impl, plugin)=>{
|
|
1017
|
+
let { stage, handler } = impl;
|
|
1018
|
+
compilation.hooks.processAssets.tapPromise({
|
|
1019
|
+
name: registerHooks_PLUGIN_NAME,
|
|
1020
|
+
stage
|
|
1021
|
+
}, async (assets)=>{
|
|
1022
|
+
let timer = createPluginHookTimer(plugin, 'processAssets');
|
|
1023
|
+
timer.start();
|
|
1024
|
+
try {
|
|
1025
|
+
await handler({
|
|
1026
|
+
assets,
|
|
1027
|
+
compilation,
|
|
1028
|
+
sources: rspack.sources,
|
|
1029
|
+
compiler
|
|
1030
|
+
});
|
|
1031
|
+
} finally{
|
|
1032
|
+
timer.end();
|
|
1033
|
+
}
|
|
1034
|
+
});
|
|
1035
|
+
});
|
|
871
1036
|
});
|
|
872
1037
|
}
|
|
873
1038
|
}
|
|
@@ -907,7 +1072,7 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
907
1072
|
await applyPluginsByHook('config', async (impl)=>{
|
|
908
1073
|
rest = await impl(rest, {
|
|
909
1074
|
...originalUnpackConfig._context,
|
|
910
|
-
mergeConfig:
|
|
1075
|
+
mergeConfig: utils_mergeConfig
|
|
911
1076
|
});
|
|
912
1077
|
});
|
|
913
1078
|
let unpackConfig = {
|
|
@@ -928,14 +1093,14 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
928
1093
|
`.env.${mode}`,
|
|
929
1094
|
`.env.${mode}.local`
|
|
930
1095
|
].map((filename)=>join(cwd, filename)).filter(isFileSync), parsed = {};
|
|
931
|
-
for (let envPath of filePaths)Object.assign(parsed, function(src) {
|
|
1096
|
+
for (let envPath of filePaths)logger_logger.debug('loading env file:', colors.dim(envPath)), Object.assign(parsed, function(src) {
|
|
932
1097
|
let match, obj = {}, lines = src.toString();
|
|
933
1098
|
for(lines = lines.replace(/\r\n?/gm, '\n'); null != (match = DOTENV_LINE.exec(lines));){
|
|
934
1099
|
let key = match[1], value = match[2] || '', maybeQuote = (value = value.trim())[0];
|
|
935
1100
|
value = value.replace(/^(['"`])([\s\S]*)\1$/gm, '$2'), '"' === maybeQuote && (value = (value = value.replace(/\\n/g, '\n')).replace(/\\r/g, '\r')), obj[key] = value;
|
|
936
1101
|
}
|
|
937
1102
|
return obj;
|
|
938
|
-
}(node_fs.readFileSync(envPath)))
|
|
1103
|
+
}(node_fs.readFileSync(envPath)));
|
|
939
1104
|
parsed.NODE_ENV && (processEnv.NODE_ENV = parsed.NODE_ENV), expand({
|
|
940
1105
|
parsed,
|
|
941
1106
|
processEnv
|
|
@@ -1074,12 +1239,12 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1074
1239
|
moduleIds: isDev() ? 'named' : 'deterministic',
|
|
1075
1240
|
minimize: !!unpackConfig.build?.minify && utils_isProd(),
|
|
1076
1241
|
minimizer: [
|
|
1077
|
-
new JsMinifyPlugin(
|
|
1242
|
+
new JsMinifyPlugin(utils_mergeConfig({
|
|
1078
1243
|
compress: {
|
|
1079
1244
|
target: unpackConfig.build.target
|
|
1080
1245
|
}
|
|
1081
1246
|
}, minifyOptions.oxc || {})),
|
|
1082
|
-
new rspack.LightningCssMinimizerRspackPlugin(
|
|
1247
|
+
new rspack.LightningCssMinimizerRspackPlugin(utils_mergeConfig({
|
|
1083
1248
|
minimizerOptions: {
|
|
1084
1249
|
targets: esVersionToBrowserslist(unpackConfig.build.target)
|
|
1085
1250
|
}
|
|
@@ -1093,9 +1258,9 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1093
1258
|
hints: !1
|
|
1094
1259
|
}
|
|
1095
1260
|
};
|
|
1096
|
-
|
|
1097
|
-
let { filter, handler } =
|
|
1098
|
-
config.module.rules.
|
|
1261
|
+
return applyPluginsByHookSync('transform', (impl, plugin)=>{
|
|
1262
|
+
let { filter, handler } = impl;
|
|
1263
|
+
config.module.rules.unshift({
|
|
1099
1264
|
exclude: NODE_MODULES_REGEX,
|
|
1100
1265
|
...filter,
|
|
1101
1266
|
enforce: 'pre',
|
|
@@ -1103,13 +1268,13 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1103
1268
|
{
|
|
1104
1269
|
loader: node_path.resolve(bundler_config_dirname, './transformLoader.js'),
|
|
1105
1270
|
options: {
|
|
1106
|
-
handler
|
|
1271
|
+
handler,
|
|
1272
|
+
pluginName: plugin.name
|
|
1107
1273
|
}
|
|
1108
1274
|
}
|
|
1109
1275
|
]
|
|
1110
1276
|
});
|
|
1111
|
-
}
|
|
1112
|
-
return config = (({ config, unpackConfig })=>{
|
|
1277
|
+
}), config = (({ config, unpackConfig })=>{
|
|
1113
1278
|
let { chunkSplit } = unpackConfig.performance || {};
|
|
1114
1279
|
if (chunkSplit?.strategy) {
|
|
1115
1280
|
let forceSplittingGroups = {};
|
|
@@ -1139,7 +1304,7 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1139
1304
|
}
|
|
1140
1305
|
return config;
|
|
1141
1306
|
})({
|
|
1142
|
-
config: config = unpackConfig.
|
|
1307
|
+
config: config = unpackConfig.css?.native ? function({ config, unpackConfig }) {
|
|
1143
1308
|
config.output.cssFilename = getOutputFilename({
|
|
1144
1309
|
type: 'css',
|
|
1145
1310
|
hash: unpackConfig.build?.filenameHash
|
|
@@ -1168,28 +1333,33 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1168
1333
|
});
|
|
1169
1334
|
let withCssModules = ({ use })=>({
|
|
1170
1335
|
resourceQuery: /[?&]module(?:[=&]|$)/,
|
|
1171
|
-
use
|
|
1336
|
+
use: [
|
|
1337
|
+
isDev() && {
|
|
1338
|
+
loader: node_path.resolve(nativeCss_dirname, './typedCssModulesLoader.js')
|
|
1339
|
+
},
|
|
1340
|
+
...use
|
|
1341
|
+
].filter(Boolean),
|
|
1172
1342
|
type: 'css/module'
|
|
1173
1343
|
}), getLessLoader = ()=>({
|
|
1174
1344
|
loader: getCompiledPkgPath('less-loader'),
|
|
1175
|
-
options: {
|
|
1176
|
-
lessOptions:
|
|
1345
|
+
options: utils_mergeConfig({
|
|
1346
|
+
lessOptions: {
|
|
1177
1347
|
javascriptEnabled: !0
|
|
1178
|
-
},
|
|
1348
|
+
},
|
|
1179
1349
|
implementation: getUserDepPath(unpackConfig.root, 'less'),
|
|
1180
1350
|
sourceMap
|
|
1181
|
-
}
|
|
1351
|
+
}, unpackConfig.css?.lessLoader || {})
|
|
1182
1352
|
}), getCssLoader = ()=>unpackConfig.css?.transformer === 'lightningcss' ? {
|
|
1183
1353
|
loader: 'builtin:lightningcss-loader',
|
|
1184
1354
|
options: {
|
|
1185
1355
|
targets: esVersionToBrowserslist(unpackConfig.build.target),
|
|
1186
|
-
...unpackConfig.css?.
|
|
1356
|
+
...unpackConfig.css?.lightningcssLoader
|
|
1187
1357
|
}
|
|
1188
1358
|
} : {
|
|
1189
1359
|
loader: getCompiledPkgPath('postcss-loader'),
|
|
1190
1360
|
options: {
|
|
1191
|
-
|
|
1192
|
-
|
|
1361
|
+
sourceMap,
|
|
1362
|
+
...unpackConfig.css?.postcssLoader
|
|
1193
1363
|
}
|
|
1194
1364
|
}, getSassLoader = ()=>({
|
|
1195
1365
|
loader: getCompiledPkgPath('sass-loader'),
|
|
@@ -1199,8 +1369,8 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1199
1369
|
'sass-embedded',
|
|
1200
1370
|
'sass'
|
|
1201
1371
|
]),
|
|
1202
|
-
|
|
1203
|
-
|
|
1372
|
+
sourceMap,
|
|
1373
|
+
...unpackConfig.css?.sassLoader
|
|
1204
1374
|
}
|
|
1205
1375
|
});
|
|
1206
1376
|
return config.module.rules.push({
|
|
@@ -1299,13 +1469,13 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1299
1469
|
loader: 'builtin:lightningcss-loader',
|
|
1300
1470
|
options: {
|
|
1301
1471
|
targets: esVersionToBrowserslist(unpackConfig.build.target),
|
|
1302
|
-
...unpackConfig.css?.
|
|
1472
|
+
...unpackConfig.css?.lightningcssLoader
|
|
1303
1473
|
}
|
|
1304
1474
|
} : {
|
|
1305
1475
|
loader: getCompiledPkgPath('postcss-loader'),
|
|
1306
1476
|
options: {
|
|
1307
|
-
|
|
1308
|
-
|
|
1477
|
+
sourceMap,
|
|
1478
|
+
...unpackConfig.css?.postcssLoader
|
|
1309
1479
|
}
|
|
1310
1480
|
};
|
|
1311
1481
|
return config.module.rules.push({
|
|
@@ -1317,13 +1487,13 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1317
1487
|
getCssLoader(),
|
|
1318
1488
|
{
|
|
1319
1489
|
loader: getCompiledPkgPath('less-loader'),
|
|
1320
|
-
options: {
|
|
1321
|
-
lessOptions:
|
|
1490
|
+
options: utils_mergeConfig({
|
|
1491
|
+
lessOptions: {
|
|
1322
1492
|
javascriptEnabled: !0
|
|
1323
|
-
},
|
|
1493
|
+
},
|
|
1324
1494
|
implementation: getUserDepPath(unpackConfig.root, 'less'),
|
|
1325
1495
|
sourceMap
|
|
1326
|
-
}
|
|
1496
|
+
}, unpackConfig.css?.lessLoader || {})
|
|
1327
1497
|
}
|
|
1328
1498
|
]
|
|
1329
1499
|
}), config.module.rules.push({
|
|
@@ -1349,8 +1519,8 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1349
1519
|
'sass-embedded',
|
|
1350
1520
|
'sass'
|
|
1351
1521
|
]),
|
|
1352
|
-
|
|
1353
|
-
|
|
1522
|
+
sourceMap,
|
|
1523
|
+
...unpackConfig.css?.sassLoader
|
|
1354
1524
|
}
|
|
1355
1525
|
}
|
|
1356
1526
|
]
|
|
@@ -1410,11 +1580,11 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1410
1580
|
config = await impl(config, {
|
|
1411
1581
|
...unpackConfig._context,
|
|
1412
1582
|
unpackConfig,
|
|
1413
|
-
mergeConfig:
|
|
1583
|
+
mergeConfig: utils_mergeConfig
|
|
1414
1584
|
});
|
|
1415
1585
|
}), unpackConfig.bundlerConfig && (config = isFunction(unpackConfig.bundlerConfig) ? await unpackConfig.bundlerConfig(config, {
|
|
1416
|
-
mergeConfig:
|
|
1417
|
-
}) :
|
|
1586
|
+
mergeConfig: utils_mergeConfig
|
|
1587
|
+
}) : utils_mergeConfig(config, unpackConfig.bundlerConfig)), config;
|
|
1418
1588
|
}
|
|
1419
1589
|
async function unpackBuild(unpackConfig) {
|
|
1420
1590
|
let compiler = rspack(await getBundlerConfig(unpackConfig)), handler = (err, stats)=>{
|
|
@@ -1535,7 +1705,7 @@ async function unpackDev(unpackConfig) {
|
|
|
1535
1705
|
...middlewares
|
|
1536
1706
|
]);
|
|
1537
1707
|
let server = new RspackDevServer(devServerOptions, compiler);
|
|
1538
|
-
await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v4.
|
|
1708
|
+
await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v4.2.0`)} ${colors.dim('ready in')} ${colors.bold(Math.ceil(performance.now() - getUnpackStartTime()))} ${colors.dim('ms')}\n`), printServerUrls({
|
|
1539
1709
|
port,
|
|
1540
1710
|
host: unpackConfig.server.host,
|
|
1541
1711
|
base: unpackConfig.base
|
|
@@ -1549,162 +1719,160 @@ async function unpackDev(unpackConfig) {
|
|
|
1549
1719
|
function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'unpack' }) {
|
|
1550
1720
|
let _context = {
|
|
1551
1721
|
callerName,
|
|
1552
|
-
version: "4.
|
|
1722
|
+
version: "4.2.0",
|
|
1553
1723
|
cachePath: 'node_modules/.unpack'
|
|
1554
1724
|
}, resolveConfig = (mode)=>{
|
|
1555
|
-
let rootPath, outputPath, basePath, cachedTraceMap, fs, isValidMethodName, parseFrame, formatOriginalLocation, formatFullStack, resolveErrorLocationAndStack, shouldTransformDeepImport, preJsAssets, jsAssets, cssAssets, bundledDepsCachePath, deepImportPkgPattern, deepImportRegex, plugin, root
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1725
|
+
let rootPath, outputPath, basePath, cachedTraceMap, fs, isValidMethodName, parseFrame, formatOriginalLocation, formatFullStack, resolveErrorLocationAndStack, shouldTransformDeepImport, preJsAssets, jsAssets, cssAssets, bundledDepsCachePath, deepImportPkgPattern, deepImportRegex, plugin, root, uno, configFilePath, configOrPathFromUnpackConfig, defaultsFromUnpackConfig, compilerRef, VIRTUAL_UNO_CSS_ID, rootDir, unoConfig, tokens, tasks, requestedLayers, layerImportRE, ensureReady, invalidate, flushTasks, getVirtualLayerId, getVirtualModuleContent, hash, restoreSkipCode, applyUnoTransformers, getResolvedLayers, optionsFromUnpackConfig, rootPath1, registerCode, namesCode, defaultConfig = {
|
|
1726
|
+
root: cwd,
|
|
1727
|
+
base: '/',
|
|
1728
|
+
sourceMap: 'production' !== mode && 'cheap-module-source-map',
|
|
1729
|
+
build: {
|
|
1730
|
+
outDir: 'dist',
|
|
1731
|
+
minify: !0,
|
|
1732
|
+
filenameHash: !0,
|
|
1733
|
+
target: 'es2023'
|
|
1734
|
+
},
|
|
1735
|
+
server: {
|
|
1736
|
+
port: 3000,
|
|
1737
|
+
host: !1
|
|
1738
|
+
},
|
|
1739
|
+
html: {
|
|
1740
|
+
mountId: 'root'
|
|
1741
|
+
},
|
|
1742
|
+
css: {
|
|
1743
|
+
transformer: 'postcss',
|
|
1744
|
+
sourceMap: !1
|
|
1745
|
+
},
|
|
1746
|
+
performance: {
|
|
1747
|
+
chunkSplit: {
|
|
1748
|
+
strategy: 'single-vendor'
|
|
1577
1749
|
},
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1750
|
+
printFileSize: !0
|
|
1751
|
+
},
|
|
1752
|
+
typeCheck: !0,
|
|
1753
|
+
envPrefix: [
|
|
1754
|
+
'PUBLIC_',
|
|
1755
|
+
'VITE_'
|
|
1756
|
+
],
|
|
1757
|
+
plugins: [
|
|
1758
|
+
{
|
|
1759
|
+
name: 'unpack:auto-css-modules',
|
|
1760
|
+
transform: {
|
|
1761
|
+
filter: {
|
|
1762
|
+
test: /\.(?:[jt]sx|vue)$/
|
|
1763
|
+
},
|
|
1764
|
+
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
|
|
1765
|
+
}
|
|
1584
1766
|
},
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
test: JSX_REGEX
|
|
1595
|
-
},
|
|
1596
|
-
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
|
|
1767
|
+
(rootPath = '', outputPath = '', basePath = '/', cachedTraceMap = new Map(), fs = null, isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), parseFrame = async (frame)=>{
|
|
1768
|
+
let { file, column, lineNumber } = frame;
|
|
1769
|
+
if (!file || null == lineNumber || null == column) return;
|
|
1770
|
+
let localPath = file;
|
|
1771
|
+
try {
|
|
1772
|
+
let pathname = new URL(file).pathname;
|
|
1773
|
+
if ('/' !== basePath) {
|
|
1774
|
+
let normalizedBase = basePath;
|
|
1775
|
+
pathname.startsWith(normalizedBase) && (pathname = pathname.slice(normalizedBase.length));
|
|
1597
1776
|
}
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
} catch {
|
|
1611
|
-
node_path.isAbsolute(file) || (localPath = node_path.join(outputPath, file));
|
|
1777
|
+
localPath = node_path.join(outputPath, pathname);
|
|
1778
|
+
} catch {
|
|
1779
|
+
node_path.isAbsolute(file) || (localPath = node_path.join(outputPath, file));
|
|
1780
|
+
}
|
|
1781
|
+
let sourceMapPath = `${localPath}.map`;
|
|
1782
|
+
try {
|
|
1783
|
+
if (!fs.existsSync(sourceMapPath)) return;
|
|
1784
|
+
let tracer = cachedTraceMap.get(sourceMapPath);
|
|
1785
|
+
if (!tracer) {
|
|
1786
|
+
let readFile = promisify(fs.readFile), sourceMapContent = await readFile(sourceMapPath, 'utf-8');
|
|
1787
|
+
if (!sourceMapContent) return;
|
|
1788
|
+
tracer = new TraceMap(sourceMapContent), cachedTraceMap.set(sourceMapPath, tracer);
|
|
1612
1789
|
}
|
|
1613
|
-
let
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1790
|
+
let originalPosition = originalPositionFor(tracer, {
|
|
1791
|
+
line: lineNumber,
|
|
1792
|
+
column: column
|
|
1793
|
+
});
|
|
1794
|
+
return {
|
|
1795
|
+
sourceMapPath,
|
|
1796
|
+
originalPosition
|
|
1797
|
+
};
|
|
1798
|
+
} catch {
|
|
1799
|
+
return;
|
|
1800
|
+
}
|
|
1801
|
+
}, formatOriginalLocation = (originalMapping)=>{
|
|
1802
|
+
let { source, line, column } = originalMapping;
|
|
1803
|
+
if (!source) return;
|
|
1804
|
+
let relativeSource = source;
|
|
1805
|
+
if (source.includes('webpack://')) {
|
|
1806
|
+
let segments = (relativeSource = source.replace(/webpack:\/\/\/?/, '')).split(/[\\/]/);
|
|
1807
|
+
[
|
|
1808
|
+
'src',
|
|
1809
|
+
'node_modules'
|
|
1810
|
+
].includes(segments[1]) && (segments.shift(), relativeSource = segments.join('/'));
|
|
1811
|
+
}
|
|
1812
|
+
let result = relativeSource;
|
|
1813
|
+
return null !== line && (result += null === column ? `:${line}` : `:${line}:${column}`), result;
|
|
1814
|
+
}, formatFullStack = async (stackFrames)=>{
|
|
1815
|
+
let allLines = [], srcLines = [];
|
|
1816
|
+
for (let frame of stackFrames){
|
|
1817
|
+
let parsedFrame = await parseFrame(frame), { methodName } = frame, parts = [];
|
|
1818
|
+
methodName && isValidMethodName(methodName) && parts.push(methodName);
|
|
1819
|
+
let parsed = !1;
|
|
1820
|
+
if (parsedFrame) {
|
|
1821
|
+
let { originalPosition } = parsedFrame, originalLocation = formatOriginalLocation(originalPosition);
|
|
1822
|
+
originalLocation && (parts.push(originalLocation), parsed = !0);
|
|
1632
1823
|
}
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
let segments = (relativeSource = source.replace(/webpack:\/\/\/?/, '')).split(/[\\/]/);
|
|
1639
|
-
[
|
|
1640
|
-
'src',
|
|
1641
|
-
'node_modules'
|
|
1642
|
-
].includes(segments[1]) && (segments.shift(), relativeSource = segments.join('/'));
|
|
1824
|
+
if (!parsed && frame.file) try {
|
|
1825
|
+
let url = new URL(frame.file);
|
|
1826
|
+
parts.push(`${url.pathname}:${frame.lineNumber}:${frame.column}`);
|
|
1827
|
+
} catch {
|
|
1828
|
+
parts.push(`${frame.file}:${frame.lineNumber}:${frame.column}`);
|
|
1643
1829
|
}
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
let parsedFrame = await parseFrame(frame), { methodName } = frame, parts = [];
|
|
1650
|
-
methodName && isValidMethodName(methodName) && parts.push(methodName);
|
|
1651
|
-
let parsed = !1;
|
|
1652
|
-
if (parsedFrame) {
|
|
1653
|
-
let { originalPosition } = parsedFrame, originalLocation = formatOriginalLocation(originalPosition);
|
|
1654
|
-
originalLocation && (parts.push(originalLocation), parsed = !0);
|
|
1655
|
-
}
|
|
1656
|
-
if (!parsed && frame.file) try {
|
|
1657
|
-
let url = new URL(frame.file);
|
|
1658
|
-
parts.push(`${url.pathname}:${frame.lineNumber}:${frame.column}`);
|
|
1659
|
-
} catch {
|
|
1660
|
-
parts.push(`${frame.file}:${frame.lineNumber}:${frame.column}`);
|
|
1661
|
-
}
|
|
1662
|
-
if (parts.length > 0) {
|
|
1663
|
-
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}`;
|
|
1664
|
-
allLines.push(line);
|
|
1665
|
-
let locationText = loc.startsWith('(') && loc.endsWith(')') ? loc.slice(1, -1) : loc;
|
|
1666
|
-
/(^|[\\/])src[\\/]/.test(locationText) && srcLines.push(line);
|
|
1667
|
-
}
|
|
1830
|
+
if (parts.length > 0) {
|
|
1831
|
+
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}`;
|
|
1832
|
+
allLines.push(line);
|
|
1833
|
+
let locationText = loc.startsWith('(') && loc.endsWith(')') ? loc.slice(1, -1) : loc;
|
|
1834
|
+
/(^|[\\/])src[\\/]/.test(locationText) && srcLines.push(line);
|
|
1668
1835
|
}
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1836
|
+
}
|
|
1837
|
+
return srcLines.length > 0 ? srcLines[0] : allLines.join('');
|
|
1838
|
+
}, resolveErrorLocationAndStack = async (item)=>{
|
|
1839
|
+
let locationFromMsg = item.message ? ((message)=>{
|
|
1840
|
+
let match = message.match(/((?:[A-Za-z]:)?\/[^\s:]+):(\d+):(\d+)/);
|
|
1841
|
+
if (!match) return;
|
|
1842
|
+
let [, absPath, line, column] = match, source = absPath;
|
|
1843
|
+
return absPath.startsWith(rootPath + node_path.sep) && (source = node_path.relative(rootPath, absPath)), `${source}:${Number(line)}:${Number(column)}`;
|
|
1844
|
+
})(item.message) : null;
|
|
1845
|
+
if (locationFromMsg) return {
|
|
1846
|
+
locationSuffix: colors.dim(`(${locationFromMsg})`),
|
|
1847
|
+
stackString: ''
|
|
1848
|
+
};
|
|
1849
|
+
if (!item.stack) return {
|
|
1850
|
+
locationSuffix: '',
|
|
1851
|
+
stackString: ''
|
|
1852
|
+
};
|
|
1853
|
+
let parsedFrames = parse(item.stack), userFrame = parsedFrames.find((frame)=>frame.file && null !== frame.lineNumber && null !== frame.column && SOURCE_REGEX.test(frame.file));
|
|
1854
|
+
if (userFrame) {
|
|
1855
|
+
let parsedUserFrame = await parseFrame(userFrame), loc = parsedUserFrame ? formatOriginalLocation(parsedUserFrame.originalPosition) : null;
|
|
1856
|
+
if (loc) return {
|
|
1857
|
+
locationSuffix: colors.dim(`(${loc})`),
|
|
1683
1858
|
stackString: ''
|
|
1684
1859
|
};
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
buildStart: async ({ isFirstCompile, compiler })=>{
|
|
1702
|
-
isFirstCompile && (fs = compiler.outputFileSystem);
|
|
1703
|
-
},
|
|
1704
|
-
configResolved: (config)=>{
|
|
1705
|
-
rootPath = config.root, outputPath = node_path.join(rootPath, config.build.outDir), basePath = normalizePublicPath(config.base);
|
|
1706
|
-
},
|
|
1707
|
-
transformHtml: (html)=>injectToHead(html, `<script>
|
|
1860
|
+
}
|
|
1861
|
+
let formattedStack = await formatFullStack(parsedFrames);
|
|
1862
|
+
return {
|
|
1863
|
+
locationSuffix: '',
|
|
1864
|
+
stackString: colors.dim(formattedStack)
|
|
1865
|
+
};
|
|
1866
|
+
}, {
|
|
1867
|
+
name: 'unpack:browser-logs',
|
|
1868
|
+
apply: (config, { command })=>'dev' === command && config.dev?.browserLogs,
|
|
1869
|
+
buildStart: async ({ isFirstCompile, compiler })=>{
|
|
1870
|
+
isFirstCompile && (fs = compiler.outputFileSystem);
|
|
1871
|
+
},
|
|
1872
|
+
configResolved: (config)=>{
|
|
1873
|
+
rootPath = config.root, outputPath = node_path.join(rootPath, config.build.outDir), basePath = normalizePublicPath(config.base);
|
|
1874
|
+
},
|
|
1875
|
+
transformHtml: (html)=>injectToHead(html, `<script>
|
|
1708
1876
|
;(() => {
|
|
1709
1877
|
if (typeof window === 'undefined' || typeof console === 'undefined') return
|
|
1710
1878
|
const endpoint = '${BROWSER_LOGS_ENDPOINT}'
|
|
@@ -1783,433 +1951,665 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
|
|
|
1783
1951
|
})
|
|
1784
1952
|
})()
|
|
1785
1953
|
</script>`),
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1954
|
+
setupMiddlewares: (middlewares)=>[
|
|
1955
|
+
(req, res, next)=>{
|
|
1956
|
+
if ('POST' !== req.method || !req.url?.startsWith(BROWSER_LOGS_ENDPOINT)) return next();
|
|
1957
|
+
let raw = '';
|
|
1958
|
+
req.on('data', (chunk)=>{
|
|
1959
|
+
raw += chunk.toString();
|
|
1960
|
+
}), req.on('end', async ()=>{
|
|
1961
|
+
try {
|
|
1962
|
+
let { level, time, args = [] } = JSON.parse(raw || '{}'), formattedArgs = await Promise.all(args.map(async (item)=>{
|
|
1963
|
+
if (!item) return '';
|
|
1964
|
+
if ('error' === item.type) {
|
|
1965
|
+
let { locationSuffix, stackString } = await resolveErrorLocationAndStack(item), msg = item.message || '', suffix = locationSuffix ? msg ? ` ${locationSuffix}` : locationSuffix : '';
|
|
1966
|
+
return `${msg}${suffix}${stackString}`;
|
|
1967
|
+
}
|
|
1968
|
+
switch(item.type){
|
|
1969
|
+
case 'string':
|
|
1970
|
+
let trimmed;
|
|
1971
|
+
return (trimmed = item.message.trim()) ? trimmed.split(/\r?\n/g).filter((line)=>{
|
|
1972
|
+
let normalized = line.trim().replace(/`/g, '');
|
|
1973
|
+
return !!normalized && !/^at\s+/.test(normalized);
|
|
1974
|
+
}).join('\n').trim() : '';
|
|
1975
|
+
case 'null':
|
|
1976
|
+
return null;
|
|
1977
|
+
case 'undefined':
|
|
1978
|
+
return;
|
|
1979
|
+
case 'object':
|
|
1980
|
+
return JSON.parse(item.message || '');
|
|
1981
|
+
default:
|
|
1982
|
+
return item.message;
|
|
1983
|
+
}
|
|
1984
|
+
})), outputArgs = ((args)=>{
|
|
1985
|
+
if (args.length < 2 || 'string' != typeof args[0]) return args;
|
|
1986
|
+
let template = args[0];
|
|
1987
|
+
if (!/%[sdifoOj%c%]/.test(template)) return args;
|
|
1988
|
+
let rest = args.slice(1), cleanedTemplate = '';
|
|
1989
|
+
for(let i = 0; i < template.length; i++){
|
|
1990
|
+
let ch = template[i];
|
|
1991
|
+
if ('%' !== ch || i + 1 >= template.length) {
|
|
1992
|
+
cleanedTemplate += ch;
|
|
1993
|
+
continue;
|
|
1799
1994
|
}
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
let normalized = line.trim().replace(/`/g, '');
|
|
1805
|
-
return !!normalized && !/^at\s+/.test(normalized);
|
|
1806
|
-
}).join('\n').trim() : '';
|
|
1807
|
-
case 'null':
|
|
1808
|
-
return null;
|
|
1809
|
-
case 'undefined':
|
|
1810
|
-
return;
|
|
1811
|
-
case 'object':
|
|
1812
|
-
return JSON.parse(item.message || '');
|
|
1813
|
-
default:
|
|
1814
|
-
return item.message;
|
|
1995
|
+
let next = template[i + 1];
|
|
1996
|
+
if ('%' === next) {
|
|
1997
|
+
cleanedTemplate += '%%', i++;
|
|
1998
|
+
continue;
|
|
1815
1999
|
}
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
if (!/%[sdifoOj%c%]/.test(template)) return args;
|
|
1820
|
-
let rest = args.slice(1), cleanedTemplate = '';
|
|
1821
|
-
for(let i = 0; i < template.length; i++){
|
|
1822
|
-
let ch = template[i];
|
|
1823
|
-
if ('%' !== ch || i + 1 >= template.length) {
|
|
1824
|
-
cleanedTemplate += ch;
|
|
1825
|
-
continue;
|
|
1826
|
-
}
|
|
1827
|
-
let next = template[i + 1];
|
|
1828
|
-
if ('%' === next) {
|
|
1829
|
-
cleanedTemplate += '%%', i++;
|
|
1830
|
-
continue;
|
|
1831
|
-
}
|
|
1832
|
-
if ('c' === next) {
|
|
1833
|
-
rest.length > 0 && rest.shift(), i++;
|
|
1834
|
-
continue;
|
|
1835
|
-
}
|
|
1836
|
-
cleanedTemplate += `%${next}`, i++;
|
|
2000
|
+
if ('c' === next) {
|
|
2001
|
+
rest.length > 0 && rest.shift(), i++;
|
|
2002
|
+
continue;
|
|
1837
2003
|
}
|
|
1838
|
-
|
|
1839
|
-
format(cleanedTemplate, ...rest)
|
|
1840
|
-
];
|
|
1841
|
-
})(formattedArgs), prefix = colors.dim(`[browser ${time}]`);
|
|
1842
|
-
switch(level){
|
|
1843
|
-
case 'error':
|
|
1844
|
-
console.log(colors.red(`${prefix} ${format(...outputArgs)}`));
|
|
1845
|
-
break;
|
|
1846
|
-
case 'warn':
|
|
1847
|
-
console.log(colors.yellow(`${prefix} ${format(...outputArgs)}`));
|
|
1848
|
-
break;
|
|
1849
|
-
case 'debug':
|
|
1850
|
-
console.log(prefix, ...outputArgs);
|
|
2004
|
+
cleanedTemplate += `%${next}`, i++;
|
|
1851
2005
|
}
|
|
1852
|
-
|
|
1853
|
-
|
|
2006
|
+
return [
|
|
2007
|
+
format(cleanedTemplate, ...rest)
|
|
2008
|
+
];
|
|
2009
|
+
})(formattedArgs), prefix = colors.dim(`[browser ${time}]`);
|
|
2010
|
+
switch(level){
|
|
2011
|
+
case 'error':
|
|
2012
|
+
console.log(colors.red(`${prefix} ${format(...outputArgs)}`));
|
|
2013
|
+
break;
|
|
2014
|
+
case 'warn':
|
|
2015
|
+
console.log(colors.yellow(`${prefix} ${format(...outputArgs)}`));
|
|
2016
|
+
break;
|
|
2017
|
+
case 'debug':
|
|
2018
|
+
console.log(prefix, ...outputArgs);
|
|
1854
2019
|
}
|
|
2020
|
+
} finally{
|
|
2021
|
+
res.statusCode = 204, res.end();
|
|
2022
|
+
}
|
|
2023
|
+
});
|
|
2024
|
+
},
|
|
2025
|
+
...middlewares
|
|
2026
|
+
]
|
|
2027
|
+
}),
|
|
2028
|
+
{
|
|
2029
|
+
name: 'unpack:glob',
|
|
2030
|
+
transform: {
|
|
2031
|
+
filter: {
|
|
2032
|
+
test: JS_REGEX
|
|
2033
|
+
},
|
|
2034
|
+
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)=>{
|
|
2035
|
+
if (patternGroup.trim().startsWith('[')) {
|
|
2036
|
+
let items, includes, excludes, { includes: includes1, excludes: excludes1 } = (items = [], patternGroup.replace(/(['"])([^'"]+)\1/g, (_, __, value)=>(items.push(value), '')), includes = [], excludes = [], items.forEach((item)=>{
|
|
2037
|
+
if (item.startsWith('!')) {
|
|
2038
|
+
let normalized = item.slice(1).trim();
|
|
2039
|
+
normalized && excludes.push(normalized);
|
|
2040
|
+
return;
|
|
2041
|
+
}
|
|
2042
|
+
includes.push(item);
|
|
2043
|
+
}), {
|
|
2044
|
+
includes,
|
|
2045
|
+
excludes
|
|
1855
2046
|
});
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
2047
|
+
return includes1.length ? (({ includes, excludes, eager })=>{
|
|
2048
|
+
let excludeMatchers = excludes.map((item)=>toRegexLiteral(item.regExpSource)).join(', '), includeItems = includes.map((item)=>{
|
|
2049
|
+
let prefix = './' === item.publicPrefix ? '' : `${item.publicPrefix}/`, mapKeyExpr = './' === item.publicPrefix ? "key.startsWith('./') ? key : './' + key" : `${JSON.stringify(prefix)} + (key.startsWith('./') ? key.slice(2) : key)`;
|
|
2050
|
+
return `{
|
|
2051
|
+
context: import.meta.webpackContext(${JSON.stringify(item.baseDir)}, { recursive: ${item.recursive}, regExp: ${toRegexLiteral(item.regExpSource)} }),
|
|
2052
|
+
mapKey: (key) => ${mapKeyExpr}
|
|
2053
|
+
}`;
|
|
2054
|
+
}).join(', '), excludeList = excludeMatchers ? `[${excludeMatchers}]` : '[]';
|
|
2055
|
+
return `(() => {
|
|
2056
|
+
const modules = {}
|
|
2057
|
+
const includeContexts = [${includeItems}]
|
|
2058
|
+
const excludeMatchers = ${excludeList}
|
|
2059
|
+
const isExcluded = (path) => excludeMatchers.some((matcher) => matcher.test(path))
|
|
2060
|
+
for (const { context, mapKey } of includeContexts) {
|
|
2061
|
+
for (const key of context.keys()) {
|
|
2062
|
+
const path = mapKey(key)
|
|
2063
|
+
if (isExcluded(path)) continue
|
|
2064
|
+
if (!modules[path]) {
|
|
2065
|
+
modules[path] = ${eager ? 'context(key)' : '() => Promise.resolve(context(key))'}
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
return modules
|
|
2070
|
+
})()`;
|
|
2071
|
+
})({
|
|
2072
|
+
includes: includes1.map(parseGlob),
|
|
2073
|
+
excludes: excludes1.map(parseGlob),
|
|
2074
|
+
eager: hasEager(rawOptions)
|
|
2075
|
+
}) : '({})';
|
|
2076
|
+
}
|
|
2077
|
+
let { baseDir, regExpSource, recursive, publicPrefix } = parseGlob(pattern);
|
|
2078
|
+
return (({ baseDir, regExpSource, recursive, eager, publicPrefix })=>{
|
|
2079
|
+
let prefix = './' === publicPrefix ? '' : `${publicPrefix}/`, mapKeyExpr = './' === publicPrefix ? "key.startsWith('./') ? key : './' + key" : `${JSON.stringify(prefix)} + (key.startsWith('./') ? key.slice(2) : key)`;
|
|
2080
|
+
return `(() => {
|
|
2081
|
+
const context = import.meta.webpackContext(${JSON.stringify(baseDir)}, { recursive: ${recursive}, regExp: ${toRegexLiteral(regExpSource)} })
|
|
2082
|
+
const modules = {}
|
|
2083
|
+
for (const key of context.keys()) {
|
|
2084
|
+
const path = ${mapKeyExpr}
|
|
2085
|
+
modules[path] = ${eager ? 'context(key)' : '() => Promise.resolve(context(key))'}
|
|
2086
|
+
}
|
|
2087
|
+
return modules
|
|
2088
|
+
})()`;
|
|
2089
|
+
})({
|
|
2090
|
+
baseDir,
|
|
2091
|
+
regExpSource,
|
|
2092
|
+
recursive,
|
|
2093
|
+
eager: hasEager(rawOptions),
|
|
2094
|
+
publicPrefix
|
|
2095
|
+
});
|
|
2096
|
+
}) : null
|
|
2097
|
+
}
|
|
2098
|
+
},
|
|
2099
|
+
(shouldTransformDeepImport = !1, preJsAssets = [], jsAssets = [], cssAssets = [], bundledDepsCachePath = '', deepImportPkgPattern = [
|
|
2100
|
+
...SPECIAL_NO_ENTRY_DEPS
|
|
2101
|
+
].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 = {
|
|
2102
|
+
name: 'unpack:prebundle',
|
|
2103
|
+
apply: (config, { command })=>'dev' === command && !!config.dev?.prebundle,
|
|
2104
|
+
config: async (config, context)=>{
|
|
2105
|
+
var externals;
|
|
2106
|
+
let existExternals, root = config.root;
|
|
2107
|
+
bundledDepsCachePath = node_path.resolve(root, context.cachePath, 'umd');
|
|
2108
|
+
let count = {
|
|
2109
|
+
total: 0,
|
|
2110
|
+
bundled: 0
|
|
2111
|
+
}, 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 = ()=>{
|
|
2112
|
+
let errMsg = failedDeps.length > 0 ? ` failed: ${failedDeps.join(', ')}` : '';
|
|
2113
|
+
logUpdate(`${colors.magenta('»')} optimizing dependencies (${count.bundled}/${count.total})${errMsg}`), count.total === count.bundled + failedDeps.length && console.log();
|
|
2114
|
+
}, 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 = [
|
|
2115
|
+
...(externals = config.externals, existExternals = new Set(), Array.isArray(externals) ? externals.forEach((item)=>{
|
|
2116
|
+
isPlainObject(item) && Object.keys(item).forEach((key)=>{
|
|
1881
2117
|
existExternals.add(key);
|
|
1882
|
-
})
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
if (isString(
|
|
1899
|
-
|
|
1900
|
-
if (packageJson.main) return packageJson.main;
|
|
1901
|
-
})(depPackageJson);
|
|
1902
|
-
if (!entry) {
|
|
1903
|
-
if (SPECIAL_NO_ENTRY_DEPS.includes(pkgName)) {
|
|
1904
|
-
let syntheticEntry = (({ root, pkgName })=>{
|
|
1905
|
-
let pkgDir = node_path.resolve(root, 'node_modules', pkgName);
|
|
1906
|
-
if (!node_fs.existsSync(pkgDir)) return;
|
|
1907
|
-
let indexPath = node_path.resolve(pkgDir, 'index.ts'), content = globSync('**/*.{js,jsx,ts,tsx}', {
|
|
1908
|
-
cwd: pkgDir,
|
|
1909
|
-
absolute: !1
|
|
1910
|
-
}).filter((p)=>{
|
|
1911
|
-
let base = node_path.basename(p);
|
|
1912
|
-
return !(p.endsWith('.d.ts') || /^index\.(t|j)sx?$/.test(base)) && 'package.json' !== base;
|
|
1913
|
-
}).map((file)=>{
|
|
1914
|
-
let normalized = file.split(node_path.sep).join('/'), exportName = pathToExportIdentifier(normalized);
|
|
1915
|
-
return `export { default as ${exportName} } from './${normalized}'`;
|
|
1916
|
-
}).join('\n');
|
|
1917
|
-
return node_fs.writeFileSync(indexPath, content, 'utf-8'), indexPath;
|
|
1918
|
-
})({
|
|
1919
|
-
root,
|
|
1920
|
-
pkgName
|
|
1921
|
-
});
|
|
1922
|
-
if (syntheticEntry) return shouldTransformDeepImport = !0, {
|
|
1923
|
-
name: pkgName,
|
|
1924
|
-
entry: syntheticEntry,
|
|
1925
|
-
version
|
|
1926
|
-
};
|
|
2118
|
+
});
|
|
2119
|
+
}) : isPlainObject(externals) && Object.keys(externals).forEach((key)=>{
|
|
2120
|
+
existExternals.add(key);
|
|
2121
|
+
}), Array.from(existExternals) || []),
|
|
2122
|
+
...userOptions.exclude || []
|
|
2123
|
+
], needBundleDeps = (Array.isArray(userOptions.include) && userOptions.include.length > 0 ? userOptions.include : Object.keys(packageJson.dependencies || {})).filter((pkgName)=>!excludeDeps.includes(pkgName)).map((pkgName)=>{
|
|
2124
|
+
let depPackageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'node_modules', pkgName, 'package.json'), 'utf-8')), version = depPackageJson.version;
|
|
2125
|
+
if (failedCache[pkgName] === version) return;
|
|
2126
|
+
let entry = ((packageJson)=>{
|
|
2127
|
+
if (packageJson.module) return packageJson.module;
|
|
2128
|
+
if (packageJson.exports) {
|
|
2129
|
+
if (isString(packageJson.exports)) return packageJson.exports;
|
|
2130
|
+
let defaultExport = packageJson.exports['.'];
|
|
2131
|
+
if (defaultExport) {
|
|
2132
|
+
if (isString(defaultExport)) return defaultExport;
|
|
2133
|
+
if (isString(defaultExport.import)) return defaultExport.import;
|
|
2134
|
+
if (isString(defaultExport.browser)) return defaultExport.browser;
|
|
2135
|
+
if (isString(defaultExport.default)) return defaultExport.default;
|
|
1927
2136
|
}
|
|
1928
|
-
|
|
1929
|
-
return;
|
|
2137
|
+
if (isString(packageJson.exports.default)) return packageJson.exports.default;
|
|
1930
2138
|
}
|
|
1931
|
-
return
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
2139
|
+
if (packageJson.main) return packageJson.main;
|
|
2140
|
+
})(depPackageJson);
|
|
2141
|
+
if (!entry) {
|
|
2142
|
+
if (SPECIAL_NO_ENTRY_DEPS.includes(pkgName)) {
|
|
2143
|
+
let syntheticEntry = (({ root, pkgName })=>{
|
|
2144
|
+
let pkgDir = node_path.resolve(root, 'node_modules', pkgName);
|
|
2145
|
+
if (!node_fs.existsSync(pkgDir)) return;
|
|
2146
|
+
let indexPath = node_path.resolve(pkgDir, 'index.ts'), content = globSync('**/*.{js,jsx,ts,tsx}', {
|
|
2147
|
+
cwd: pkgDir,
|
|
2148
|
+
absolute: !1
|
|
2149
|
+
}).filter((p)=>{
|
|
2150
|
+
let base = node_path.basename(p);
|
|
2151
|
+
return !(p.endsWith('.d.ts') || /^index\.(t|j)sx?$/.test(base)) && 'package.json' !== base;
|
|
2152
|
+
}).map((file)=>{
|
|
2153
|
+
let normalized = file.split(node_path.sep).join('/'), exportName = pathToExportIdentifier(normalized);
|
|
2154
|
+
return `export { default as ${exportName} } from './${normalized}'`;
|
|
2155
|
+
}).join('\n');
|
|
2156
|
+
return node_fs.writeFileSync(indexPath, content, 'utf-8'), indexPath;
|
|
2157
|
+
})({
|
|
2158
|
+
root,
|
|
2159
|
+
pkgName
|
|
2160
|
+
});
|
|
2161
|
+
if (syntheticEntry) return shouldTransformDeepImport = !0, {
|
|
2162
|
+
name: pkgName,
|
|
2163
|
+
entry: syntheticEntry,
|
|
2164
|
+
version
|
|
2165
|
+
};
|
|
2166
|
+
}
|
|
2167
|
+
failedCache[pkgName] = version;
|
|
2168
|
+
return;
|
|
2169
|
+
}
|
|
2170
|
+
return {
|
|
2171
|
+
name: pkgName,
|
|
2172
|
+
entry: node_path.resolve(root, 'node_modules', pkgName, entry),
|
|
2173
|
+
version
|
|
2174
|
+
};
|
|
2175
|
+
}).filter(Boolean), depExternals = Object.fromEntries(Array.from(new Set([
|
|
2176
|
+
...FRAMEWORKS,
|
|
2177
|
+
...Array.isArray(userOptions.externals) ? userOptions.externals : []
|
|
2178
|
+
])).map((pkg)=>[
|
|
2179
|
+
pkg,
|
|
2180
|
+
getExternalValue(pkg)
|
|
2181
|
+
])), bundledDeps = await Promise.all(needBundleDeps.map((depInfo)=>(({ name, entry, version })=>new Promise((resolve)=>{
|
|
2182
|
+
let pkgDir = node_path.resolve(bundledDepsCachePath, name), outDir = node_path.resolve(pkgDir, version), getResult = ()=>({
|
|
2183
|
+
name,
|
|
2184
|
+
assets: globSync('**/index.{js,css}', {
|
|
2185
|
+
cwd: outDir,
|
|
2186
|
+
absolute: !0
|
|
2187
|
+
})
|
|
2188
|
+
});
|
|
2189
|
+
if (node_fs.existsSync(outDir)) return void resolve(getResult());
|
|
2190
|
+
count.total++, updateProgress();
|
|
2191
|
+
let getSwcOptions = ({ tsx })=>({
|
|
2192
|
+
jsc: {
|
|
2193
|
+
parser: {
|
|
2194
|
+
tsx,
|
|
2195
|
+
syntax: "typescript",
|
|
2196
|
+
dynamicImport: !0,
|
|
2197
|
+
decorators: !0
|
|
2198
|
+
},
|
|
2199
|
+
transform: {
|
|
2200
|
+
react: {
|
|
2201
|
+
runtime: 'automatic'
|
|
1966
2202
|
}
|
|
1967
2203
|
}
|
|
1968
|
-
}
|
|
1969
|
-
|
|
1970
|
-
|
|
2204
|
+
}
|
|
2205
|
+
}), compiler = rspack({
|
|
2206
|
+
entry: {
|
|
2207
|
+
index: entry
|
|
2208
|
+
},
|
|
2209
|
+
context: root,
|
|
2210
|
+
mode: 'development',
|
|
2211
|
+
output: {
|
|
2212
|
+
clean: !0,
|
|
2213
|
+
path: outDir,
|
|
2214
|
+
pathinfo: !1,
|
|
2215
|
+
library: {
|
|
2216
|
+
name: getExternalLibraryName(name),
|
|
2217
|
+
type: 'umd',
|
|
2218
|
+
umdNamedDefine: !0
|
|
1971
2219
|
},
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
type: 'umd',
|
|
1981
|
-
umdNamedDefine: !0
|
|
2220
|
+
globalObject: 'this'
|
|
2221
|
+
},
|
|
2222
|
+
devtool: !1,
|
|
2223
|
+
module: {
|
|
2224
|
+
rules: [
|
|
2225
|
+
{
|
|
2226
|
+
test: /\.(png|jpe?g|gif|webp)$/i,
|
|
2227
|
+
type: 'asset'
|
|
1982
2228
|
},
|
|
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
|
-
options: {
|
|
2017
|
-
lessOptions: {
|
|
2018
|
-
javascriptEnabled: !0
|
|
2019
|
-
},
|
|
2020
|
-
implementation: getUserDepPath(root, 'less')
|
|
2021
|
-
}
|
|
2229
|
+
{
|
|
2230
|
+
test: JS_REGEX,
|
|
2231
|
+
use: [
|
|
2232
|
+
{
|
|
2233
|
+
loader: 'builtin:swc-loader',
|
|
2234
|
+
options: getSwcOptions({
|
|
2235
|
+
tsx: !1
|
|
2236
|
+
})
|
|
2237
|
+
}
|
|
2238
|
+
]
|
|
2239
|
+
},
|
|
2240
|
+
{
|
|
2241
|
+
test: JSX_REGEX,
|
|
2242
|
+
use: [
|
|
2243
|
+
{
|
|
2244
|
+
loader: 'builtin:swc-loader',
|
|
2245
|
+
options: getSwcOptions({
|
|
2246
|
+
tsx: !0
|
|
2247
|
+
})
|
|
2248
|
+
}
|
|
2249
|
+
]
|
|
2250
|
+
},
|
|
2251
|
+
{
|
|
2252
|
+
test: /\.less$/,
|
|
2253
|
+
type: 'css/auto',
|
|
2254
|
+
use: [
|
|
2255
|
+
{
|
|
2256
|
+
loader: getCompiledPkgPath('less-loader'),
|
|
2257
|
+
options: {
|
|
2258
|
+
lessOptions: {
|
|
2259
|
+
javascriptEnabled: !0
|
|
2260
|
+
},
|
|
2261
|
+
implementation: getUserDepPath(root, 'less')
|
|
2022
2262
|
}
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2263
|
+
}
|
|
2264
|
+
]
|
|
2265
|
+
},
|
|
2266
|
+
{
|
|
2267
|
+
test: /\.s[ac]ss$/i,
|
|
2268
|
+
type: 'css/auto',
|
|
2269
|
+
use: [
|
|
2270
|
+
{
|
|
2271
|
+
loader: getCompiledPkgPath('sass-loader'),
|
|
2272
|
+
options: {
|
|
2273
|
+
api: 'modern-compiler',
|
|
2274
|
+
implementation: getUserDepPath(root, [
|
|
2275
|
+
'sass-embedded',
|
|
2276
|
+
'sass'
|
|
2277
|
+
])
|
|
2038
2278
|
}
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2279
|
+
}
|
|
2280
|
+
]
|
|
2281
|
+
}
|
|
2282
|
+
]
|
|
2283
|
+
},
|
|
2284
|
+
optimization: {
|
|
2285
|
+
splitChunks: !1
|
|
2286
|
+
},
|
|
2287
|
+
experiments: {
|
|
2288
|
+
css: !0
|
|
2289
|
+
},
|
|
2290
|
+
externals: depExternals
|
|
2291
|
+
});
|
|
2292
|
+
compiler.run((_, stats)=>{
|
|
2293
|
+
let isFailed = !1;
|
|
2294
|
+
stats?.hasErrors() ? (isFailed = !0, failedDeps.push(name), failedCache[name] = version, removeDir(outDir)) : count.bundled++, updateProgress(), compiler.close(()=>{
|
|
2295
|
+
resolve(isFailed ? void 0 : getResult());
|
|
2056
2296
|
});
|
|
2057
|
-
})
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2297
|
+
});
|
|
2298
|
+
}))(depInfo)));
|
|
2299
|
+
((cache)=>{
|
|
2300
|
+
if (0 === Object.keys(cache).length) {
|
|
2301
|
+
node_fs.existsSync(failedDepsJsonPath) && node_fs.unlinkSync(failedDepsJsonPath);
|
|
2302
|
+
return;
|
|
2303
|
+
}
|
|
2304
|
+
let cacheDir = node_path.dirname(failedDepsJsonPath);
|
|
2305
|
+
node_fs.existsSync(cacheDir) || node_fs.mkdirSync(cacheDir, {
|
|
2306
|
+
recursive: !0
|
|
2307
|
+
}), node_fs.writeFileSync(failedDepsJsonPath, JSON.stringify(cache, null, 2), 'utf-8');
|
|
2308
|
+
})(failedCache);
|
|
2309
|
+
let externals1 = {};
|
|
2310
|
+
bundledDeps.filter(Boolean).forEach((dep)=>{
|
|
2311
|
+
dep && (externals1[dep.name] = getExternalValue(dep.name), dep.assets.forEach((absPath)=>{
|
|
2312
|
+
let relativePath = node_path.relative(bundledDepsCachePath, absPath), serverPath = `/umd/${relativePath}`;
|
|
2313
|
+
switch(node_path.extname(relativePath)){
|
|
2314
|
+
case '.js':
|
|
2315
|
+
FRAMEWORKS.includes(dep.name) ? preJsAssets.push({
|
|
2316
|
+
path: serverPath,
|
|
2317
|
+
order: FRAMEWORKS.indexOf(dep.name)
|
|
2318
|
+
}) : jsAssets.push(serverPath);
|
|
2319
|
+
break;
|
|
2320
|
+
case '.css':
|
|
2321
|
+
ignoreCSSDeps.includes(dep.name) || cssAssets.push(serverPath);
|
|
2322
|
+
}
|
|
2323
|
+
}));
|
|
2324
|
+
});
|
|
2325
|
+
let existingExternals = config.externals ? Array.isArray(config.externals) ? config.externals : [
|
|
2326
|
+
config.externals
|
|
2327
|
+
] : [];
|
|
2328
|
+
return config.externals = [
|
|
2329
|
+
externals1,
|
|
2330
|
+
...existingExternals
|
|
2331
|
+
], shouldTransformDeepImport && (plugin.transform = {
|
|
2332
|
+
filter: {
|
|
2333
|
+
test: JSX_REGEX
|
|
2334
|
+
},
|
|
2335
|
+
handler: (code)=>SPECIAL_NO_ENTRY_DEPS.some((pkg)=>code.includes(pkg)) ? code.replace(deepImportRegex, (_, localName, importPath, pkgName)=>{
|
|
2336
|
+
let exportName = pathToExportIdentifier(importPath.slice(pkgName.length + 1));
|
|
2337
|
+
return `import { ${exportName} as ${localName} } from '${pkgName}'`;
|
|
2338
|
+
}) : null
|
|
2339
|
+
}), config;
|
|
2340
|
+
},
|
|
2341
|
+
transformHtml: (html)=>injectToHead(html, preJsAssets.sort((a, b)=>a.order - b.order).map((item)=>item.path).map((item)=>`<script defer src="${item}"></script>`).join('')),
|
|
2342
|
+
setupMiddlewares: (middlewares)=>[
|
|
2343
|
+
(req, res, next)=>{
|
|
2344
|
+
if ('string' != typeof req.url) return void next();
|
|
2345
|
+
let url = new URL(req.url, 'http://localhost');
|
|
2346
|
+
if (!url.pathname.startsWith("/umd/")) return void next();
|
|
2347
|
+
let relativePath = url.pathname.replace("/umd/", '');
|
|
2348
|
+
if (relativePath.includes('..')) {
|
|
2349
|
+
res.statusCode = 403, res.end();
|
|
2061
2350
|
return;
|
|
2062
2351
|
}
|
|
2063
|
-
let
|
|
2064
|
-
node_fs.existsSync(
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2352
|
+
let filePath = node_path.join(bundledDepsCachePath, relativePath);
|
|
2353
|
+
if (!node_fs.existsSync(filePath)) return void next();
|
|
2354
|
+
let stat = node_fs.statSync(filePath);
|
|
2355
|
+
if (!stat.isFile()) return void next();
|
|
2356
|
+
let mtime = stat.mtime.toUTCString(), ext = node_path.extname(filePath);
|
|
2357
|
+
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) {
|
|
2358
|
+
res.statusCode = 304, res.end();
|
|
2359
|
+
return;
|
|
2360
|
+
}
|
|
2361
|
+
res.statusCode = 200, node_fs.createReadStream(filePath).pipe(res);
|
|
2362
|
+
},
|
|
2363
|
+
...middlewares
|
|
2364
|
+
],
|
|
2365
|
+
bundlerConfig: (config)=>{
|
|
2366
|
+
let PLUGIN_NAME = 'InjectAssetsPlugin';
|
|
2367
|
+
return config.plugins.push({
|
|
2368
|
+
apply: (compiler)=>{
|
|
2369
|
+
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
|
|
2370
|
+
rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(PLUGIN_NAME, async (args)=>(args.assets.js.unshift(...jsAssets), args.assets.css.unshift(...cssAssets), args));
|
|
2371
|
+
});
|
|
2372
|
+
}
|
|
2373
|
+
}), config;
|
|
2374
|
+
}
|
|
2375
|
+
}),
|
|
2376
|
+
(root = '', {
|
|
2377
|
+
name: 'unpack:file-size',
|
|
2378
|
+
apply: (config, { mode })=>'production' === mode && config.performance?.printFileSize,
|
|
2379
|
+
configResolved (config) {
|
|
2380
|
+
root = config.root;
|
|
2381
|
+
},
|
|
2382
|
+
buildEnd: async (options)=>{
|
|
2383
|
+
let { stats } = options;
|
|
2384
|
+
if (stats.hasErrors()) return;
|
|
2385
|
+
let chunkGroups = [
|
|
2386
|
+
{
|
|
2387
|
+
type: 'HTML',
|
|
2388
|
+
color: 'green',
|
|
2389
|
+
chunks: []
|
|
2390
|
+
},
|
|
2391
|
+
{
|
|
2392
|
+
type: 'Assets',
|
|
2393
|
+
color: 'yellow',
|
|
2394
|
+
chunks: []
|
|
2395
|
+
},
|
|
2396
|
+
{
|
|
2397
|
+
type: 'CSS',
|
|
2398
|
+
color: 'magenta',
|
|
2399
|
+
chunks: []
|
|
2400
|
+
},
|
|
2401
|
+
{
|
|
2402
|
+
type: 'JS',
|
|
2403
|
+
color: 'cyan',
|
|
2404
|
+
chunks: []
|
|
2405
|
+
}
|
|
2406
|
+
], 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;
|
|
2407
|
+
logUpdate('computing gzip size...'), await Promise.all(assets.map(async ([assetName, value])=>{
|
|
2408
|
+
let content, compressedSize, filePath = assetName.split('?')[0];
|
|
2409
|
+
try {
|
|
2410
|
+
content = value.source();
|
|
2411
|
+
} catch {
|
|
2412
|
+
content = node_fs.readFileSync(node_path.join(distPath, filePath));
|
|
2413
|
+
}
|
|
2414
|
+
let size = Buffer.byteLength(content);
|
|
2415
|
+
compressedSize = COMPRESSIBLE_REGEX.test(filePath) ? await getCompressedSize(content) : size, totalSize += size, totalCompressedSize += compressedSize;
|
|
2416
|
+
let chunk = {
|
|
2417
|
+
name: node_path.basename(filePath),
|
|
2418
|
+
path: `${distFolder}/${filePath}`,
|
|
2419
|
+
size,
|
|
2420
|
+
compressedSize
|
|
2421
|
+
};
|
|
2422
|
+
switch(chunk.path.length > longest && (longest = chunk.path.length), node_path.extname(filePath)){
|
|
2423
|
+
case '.html':
|
|
2424
|
+
chunkGroupMap.HTML.chunks.push(chunk);
|
|
2425
|
+
break;
|
|
2426
|
+
case '.css':
|
|
2427
|
+
chunkGroupMap.CSS.chunks.push(chunk);
|
|
2428
|
+
break;
|
|
2429
|
+
case '.js':
|
|
2430
|
+
case '.wasm':
|
|
2431
|
+
chunkGroupMap.JS.chunks.push(chunk);
|
|
2432
|
+
break;
|
|
2433
|
+
default:
|
|
2434
|
+
chunkGroupMap.Assets.chunks.push(chunk);
|
|
2435
|
+
}
|
|
2436
|
+
})), logUpdate(`✓ computed gzip size (${assets.length})`), console.log();
|
|
2437
|
+
let sizePad = displaySize(totalSize).length, compressPad = displaySize(totalCompressedSize).length;
|
|
2438
|
+
chunkGroups.forEach((group)=>{
|
|
2439
|
+
group.chunks.sort((a, b)=>a.size - b.size).forEach((chunk)=>{
|
|
2440
|
+
let isLarge = 'JS' === group.type && chunk.size / 1000 > 500, relativeOutDir = node_path.dirname(chunk.path) + '/', log = colors.dim(relativeOutDir);
|
|
2441
|
+
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)}`));
|
|
2442
|
+
});
|
|
2443
|
+
});
|
|
2444
|
+
let log = colors.blue('Total'.padEnd(longest + 2));
|
|
2445
|
+
log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` │ gzip: ${displaySize(totalCompressedSize)}`));
|
|
2446
|
+
}
|
|
2447
|
+
}),
|
|
2448
|
+
(VIRTUAL_UNO_CSS_ID = 'uno.css', rootDir = process.cwd(), unoConfig = {}, tokens = new Set(), tasks = [], requestedLayers = new Set([
|
|
2449
|
+
LAYER_MARK_ALL
|
|
2450
|
+
]), layerImportRE = /(['"])uno\.css\?layer=([^'"]+)\1/g, ensureReady = async ()=>{
|
|
2451
|
+
var root, configOrPath;
|
|
2452
|
+
let core = await import("@unocss/core"), resolvedConfigOrPath = (root = rootDir, 'string' != typeof (configOrPath = (void 0) ?? configOrPathFromUnpackConfig) || node_path.isAbsolute(configOrPath) ? configOrPath : node_path.resolve(root, configOrPath)), resolvedDefaults = (void 0) ?? defaultsFromUnpackConfig, configFromOption = {};
|
|
2453
|
+
if (isPlainObject(resolvedConfigOrPath) ? configFromOption = resolvedConfigOrPath : isString(resolvedConfigOrPath) && (configFilePath = resolvedConfigOrPath), configFilePath || (configFilePath = ((root, customConfig)=>{
|
|
2454
|
+
for (let file of UNOCSS_CONFIG_FILES){
|
|
2455
|
+
let configFile = node_path.join(root, file);
|
|
2456
|
+
if (node_fs.existsSync(configFile)) return configFile;
|
|
2457
|
+
}
|
|
2458
|
+
})(rootDir)), configFilePath && node_fs.existsSync(configFilePath)) {
|
|
2459
|
+
let loaded = await loadConfigFile(configFilePath);
|
|
2460
|
+
if (isFunction(loaded)) {
|
|
2461
|
+
let result = await loaded({
|
|
2462
|
+
env: isDev() ? 'development' : 'production',
|
|
2463
|
+
command: isDev() ? 'dev' : 'build'
|
|
2087
2464
|
});
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2465
|
+
result && (configFromOption = utils_mergeConfig(configFromOption, result));
|
|
2466
|
+
} else loaded && (configFromOption = utils_mergeConfig(configFromOption, loaded));
|
|
2467
|
+
}
|
|
2468
|
+
resolvedDefaults && (configFromOption = utils_mergeConfig(resolvedDefaults, configFromOption)), unoConfig = configFromOption;
|
|
2469
|
+
let createGenerator = core.createGenerator;
|
|
2470
|
+
if (!createGenerator) throw Error('Failed to load "createGenerator" from "@unocss/core".');
|
|
2471
|
+
uno = await createGenerator(unoConfig), tokens = new Set();
|
|
2472
|
+
}, invalidate = ()=>{
|
|
2473
|
+
setTimeout(()=>{
|
|
2474
|
+
compilerRef.watching.invalidate(), logger_logger.debug(colors.yellow('[unocss] Invalidation triggered.'));
|
|
2475
|
+
}, 0);
|
|
2476
|
+
}, flushTasks = async ()=>{
|
|
2477
|
+
if (!tasks.length) return;
|
|
2478
|
+
let pending = tasks.map((t)=>t());
|
|
2479
|
+
tasks = [], await Promise.all(pending);
|
|
2480
|
+
}, getVirtualLayerId = (layer)=>`${VIRTUAL_UNO_CSS_ID}?layer=${encodeURIComponent(layer)}`, getVirtualModuleContent = (layer)=>{
|
|
2481
|
+
let code, layer1, layersKey = Array.from(requestedLayers).sort().join(','), hash = (code = `${Date.now()}|${layer}|${layersKey}`, createHash('sha256').update(code).digest('hex').slice(0, 8));
|
|
2482
|
+
return `#--unocss-hash--{content:"${hash}"}${layer1 = encodeURIComponent(layer), `#--unocss--{layer:${layer1};escape-view:\\"\\'\\\`\\\\}`}`;
|
|
2483
|
+
}, hash = (str)=>{
|
|
2484
|
+
let i, l, hVal = 0x811c9dc5;
|
|
2485
|
+
for(i = 0, l = str.length; i < l; i++)hVal ^= str.charCodeAt(i), hVal += (hVal << 1) + (hVal << 4) + (hVal << 7) + (hVal << 8) + (hVal << 24);
|
|
2486
|
+
return `00000${(hVal >>> 0).toString(36)}`.slice(-6);
|
|
2487
|
+
}, restoreSkipCode = (code, map)=>{
|
|
2488
|
+
let next = code;
|
|
2489
|
+
for (let [withHashKey, matched] of map.entries())next = next.replaceAll(withHashKey, matched);
|
|
2490
|
+
return next;
|
|
2491
|
+
}, applyUnoTransformers = async (original, id, enforce = 'default')=>{
|
|
2492
|
+
if (!uno || original.includes('@unocss-ignore')) return null;
|
|
2493
|
+
let transformers = (uno.config.transformers || []).filter((i)=>(i.enforce || 'default') === enforce);
|
|
2494
|
+
if (!transformers.length) return null;
|
|
2495
|
+
let skipMap = new Map(), code = original, s = new magic_string(((code, map, rules, keyFlag)=>{
|
|
2496
|
+
let next = code;
|
|
2497
|
+
for (let item of Array.from(next.matchAll(rules)))if (null != item) {
|
|
2498
|
+
let matched = item[0], withHashKey = `${keyFlag}${hash(matched)}`;
|
|
2499
|
+
map.set(withHashKey, matched), next = next.replace(matched, withHashKey);
|
|
2500
|
+
}
|
|
2501
|
+
return next;
|
|
2502
|
+
})(code, skipMap, SKIP_COMMENT_RE, '@unocss-skip-placeholder-'));
|
|
2503
|
+
for (let t of transformers)(!t.idFilter || t.idFilter(id)) && (await t.transform(s, id, {
|
|
2504
|
+
uno,
|
|
2505
|
+
tokens,
|
|
2506
|
+
invalidate
|
|
2507
|
+
}), s.hasChanged() && (s = new magic_string(code = restoreSkipCode(s.toString(), skipMap))));
|
|
2508
|
+
return code !== original ? code : null;
|
|
2509
|
+
}, getResolvedLayers = ()=>Array.from(requestedLayers).filter((layer)=>layer !== LAYER_MARK_ALL), {
|
|
2510
|
+
name: 'unpack:unocss',
|
|
2511
|
+
apply: (config)=>!!config.unocss,
|
|
2512
|
+
config: (config, { mergeConfig })=>mergeConfig(config, {
|
|
2513
|
+
performance: {
|
|
2514
|
+
cache: !1
|
|
2515
|
+
}
|
|
2516
|
+
}),
|
|
2517
|
+
configResolved: async (config)=>{
|
|
2518
|
+
if (rootDir = config.root || process.cwd(), Array.isArray(config.unocss)) {
|
|
2519
|
+
let [configOrPathValue, defaultsValue] = config.unocss;
|
|
2520
|
+
configOrPathFromUnpackConfig = configOrPathValue, defaultsFromUnpackConfig = defaultsValue;
|
|
2521
|
+
}
|
|
2522
|
+
await ensureReady();
|
|
2523
|
+
},
|
|
2524
|
+
bundlerConfig: (config)=>(config.lazyCompilation = !1, config),
|
|
2525
|
+
buildStart ({ compiler }) {
|
|
2526
|
+
compilerRef = compiler;
|
|
2527
|
+
},
|
|
2528
|
+
transform: {
|
|
2529
|
+
filter: {
|
|
2530
|
+
test: /\.(vue|svelte|[jt]sx?|vine\.ts|mdx?|astro|elm|php|phtml|marko)($|\?)/
|
|
2103
2531
|
},
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2532
|
+
handler: async (code, id)=>{
|
|
2533
|
+
var task;
|
|
2534
|
+
if (JS_REGEX.test(id) && !code.includes('@unocss-include')) return null;
|
|
2535
|
+
let transformedCode = code, preTransformed = await applyUnoTransformers(transformedCode, id, 'pre');
|
|
2536
|
+
null != preTransformed && (transformedCode = preTransformed);
|
|
2537
|
+
let defaultTransformed = await applyUnoTransformers(transformedCode, id, 'default');
|
|
2538
|
+
null != defaultTransformed && (transformedCode = defaultTransformed);
|
|
2539
|
+
let postTransformed = await applyUnoTransformers(transformedCode, id, 'post');
|
|
2540
|
+
return null != postTransformed && (transformedCode = postTransformed), transformedCode.includes('uno.css?layer=') && (transformedCode = transformedCode.replace(layerImportRE, (_, quote, layer)=>{
|
|
2541
|
+
let decodedLayer = ((layer)=>{
|
|
2542
|
+
try {
|
|
2543
|
+
return decodeURIComponent(layer);
|
|
2544
|
+
} catch {
|
|
2545
|
+
return layer;
|
|
2114
2546
|
}
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
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) {
|
|
2121
|
-
res.statusCode = 304, res.end();
|
|
2122
|
-
return;
|
|
2123
|
-
}
|
|
2124
|
-
res.statusCode = 200, node_fs.createReadStream(filePath).pipe(res);
|
|
2125
|
-
},
|
|
2126
|
-
...middlewares
|
|
2127
|
-
],
|
|
2128
|
-
bundlerConfig: (config)=>{
|
|
2129
|
-
let PLUGIN_NAME = 'InjectAssetsPlugin';
|
|
2130
|
-
return config.plugins.push({
|
|
2131
|
-
apply: (compiler)=>{
|
|
2132
|
-
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
|
|
2133
|
-
rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeAssetTagGeneration.tapPromise(PLUGIN_NAME, async (args)=>(args.assets.js.unshift(...jsAssets), args.assets.css.unshift(...cssAssets), args));
|
|
2134
|
-
});
|
|
2135
|
-
}
|
|
2136
|
-
}), config;
|
|
2547
|
+
})(layer);
|
|
2548
|
+
return requestedLayers.add(decodedLayer), `${quote}${getVirtualLayerId(decodedLayer)}${quote}`;
|
|
2549
|
+
})), task = async ()=>{
|
|
2550
|
+
await uno.applyExtractors(code.replace(SKIP_COMMENT_RE, ''), id, tokens);
|
|
2551
|
+
}, tasks.push(task), transformedCode === code ? null : transformedCode;
|
|
2137
2552
|
}
|
|
2138
|
-
}
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
buildEnd: async (options)=>{
|
|
2146
|
-
let { stats } = options;
|
|
2147
|
-
if (stats.hasErrors()) return;
|
|
2148
|
-
let chunkGroups = [
|
|
2149
|
-
{
|
|
2150
|
-
type: 'HTML',
|
|
2151
|
-
color: 'green',
|
|
2152
|
-
chunks: []
|
|
2153
|
-
},
|
|
2154
|
-
{
|
|
2155
|
-
type: 'Assets',
|
|
2156
|
-
color: 'yellow',
|
|
2157
|
-
chunks: []
|
|
2158
|
-
},
|
|
2159
|
-
{
|
|
2160
|
-
type: 'CSS',
|
|
2161
|
-
color: 'magenta',
|
|
2162
|
-
chunks: []
|
|
2163
|
-
},
|
|
2164
|
-
{
|
|
2165
|
-
type: 'JS',
|
|
2166
|
-
color: 'cyan',
|
|
2167
|
-
chunks: []
|
|
2168
|
-
}
|
|
2169
|
-
], 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;
|
|
2170
|
-
logUpdate('computing gzip size...'), await Promise.all(assets.map(async ([assetName, value])=>{
|
|
2171
|
-
let content, compressedSize, filePath = assetName.split('?')[0];
|
|
2172
|
-
try {
|
|
2173
|
-
content = value.source();
|
|
2174
|
-
} catch {
|
|
2175
|
-
content = node_fs.readFileSync(node_path.join(distPath, filePath));
|
|
2176
|
-
}
|
|
2177
|
-
let size = Buffer.byteLength(content);
|
|
2178
|
-
compressedSize = COMPRESSIBLE_REGEX.test(filePath) ? await getCompressedSize(content) : size, totalSize += size, totalCompressedSize += compressedSize;
|
|
2179
|
-
let chunk = {
|
|
2180
|
-
name: node_path.basename(filePath),
|
|
2181
|
-
path: `${distFolder}/${filePath}`,
|
|
2182
|
-
size,
|
|
2183
|
-
compressedSize
|
|
2184
|
-
};
|
|
2185
|
-
switch(chunk.path.length > longest && (longest = chunk.path.length), node_path.extname(filePath)){
|
|
2186
|
-
case '.html':
|
|
2187
|
-
chunkGroupMap.HTML.chunks.push(chunk);
|
|
2188
|
-
break;
|
|
2189
|
-
case '.css':
|
|
2190
|
-
chunkGroupMap.CSS.chunks.push(chunk);
|
|
2191
|
-
break;
|
|
2192
|
-
case '.js':
|
|
2193
|
-
case '.wasm':
|
|
2194
|
-
chunkGroupMap.JS.chunks.push(chunk);
|
|
2195
|
-
break;
|
|
2196
|
-
default:
|
|
2197
|
-
chunkGroupMap.Assets.chunks.push(chunk);
|
|
2198
|
-
}
|
|
2199
|
-
})), logUpdate(`✓ computed gzip size (${assets.length})`), console.log();
|
|
2200
|
-
let sizePad = displaySize(totalSize).length, compressPad = displaySize(totalCompressedSize).length;
|
|
2201
|
-
chunkGroups.forEach((group)=>{
|
|
2202
|
-
group.chunks.sort((a, b)=>a.size - b.size).forEach((chunk)=>{
|
|
2203
|
-
let isLarge = 'JS' === group.type && chunk.size / 1000 > 500, relativeOutDir = node_path.dirname(chunk.path) + '/', log = colors.dim(relativeOutDir);
|
|
2204
|
-
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)}`));
|
|
2205
|
-
});
|
|
2553
|
+
},
|
|
2554
|
+
processAssets: {
|
|
2555
|
+
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
|
|
2556
|
+
handler: async ({ compilation, sources })=>{
|
|
2557
|
+
if (await flushTasks(), !uno) return;
|
|
2558
|
+
let resolvedLayers = getResolvedLayers(), result = await uno.generate(tokens, {
|
|
2559
|
+
minify: !0
|
|
2206
2560
|
});
|
|
2207
|
-
let
|
|
2208
|
-
|
|
2561
|
+
for (let file of Object.keys(compilation.assets)){
|
|
2562
|
+
if ('*' === file || file.includes('vendor')) continue;
|
|
2563
|
+
let code = compilation.assets[file].source().toString();
|
|
2564
|
+
if (!code.includes('#--unocss')) continue;
|
|
2565
|
+
let isJsAsset = /\.(?:[cm]?js|[cm]?jsx)$/.test(file), replaced = !1;
|
|
2566
|
+
code = (code = code.replace(HASH_PLACEHOLDER_RE, '')).replace(LAYER_PLACEHOLDER_RE, (_, layer, escapeView)=>{
|
|
2567
|
+
replaced = !0;
|
|
2568
|
+
let css = layer.trim() === LAYER_MARK_ALL ? result.getLayers(void 0, resolvedLayers) : result.getLayer(layer) || '';
|
|
2569
|
+
return isJsAsset ? getCssEscaperForJsContent(escapeView)(css) : css;
|
|
2570
|
+
}), replaced && compilation.updateAsset(file, new sources.RawSource(code));
|
|
2571
|
+
}
|
|
2209
2572
|
}
|
|
2210
|
-
}
|
|
2211
|
-
|
|
2212
|
-
|
|
2573
|
+
},
|
|
2574
|
+
virtualModules: ()=>({
|
|
2575
|
+
[VIRTUAL_UNO_CSS_ID]: getVirtualModuleContent(LAYER_MARK_ALL),
|
|
2576
|
+
...getResolvedLayers().reduce((acc, layer)=>(acc[getVirtualLayerId(layer)] = getVirtualModuleContent(layer), acc), {})
|
|
2577
|
+
})
|
|
2578
|
+
}),
|
|
2579
|
+
(rootPath1 = '', registerCode = '', namesCode = '', {
|
|
2580
|
+
name: 'unpack:svg-icons',
|
|
2581
|
+
apply: (config)=>!!config.svgIcons,
|
|
2582
|
+
configResolved: (config)=>{
|
|
2583
|
+
rootPath1 = config.root || process.cwd(), optionsFromUnpackConfig = config.svgIcons, (()=>{
|
|
2584
|
+
let root, resolvedOptions = (void 0) ?? optionsFromUnpackConfig, inject = resolvedOptions.inject || 'body-last', domId = resolvedOptions.customDomId || '__svg__icons__dom__', { svg, names } = ((iconDirs, symbolId, customDomId)=>{
|
|
2585
|
+
let symbols = [], names = [], idSet = new Set();
|
|
2586
|
+
for (let dir of iconDirs)for (let file of readSvgFiles(dir)){
|
|
2587
|
+
let { inner, viewBox } = extractSvgContent(normalizeSvg(node_fs.readFileSync(file, 'utf-8'))), id = toSymbolId(file, dir, symbolId);
|
|
2588
|
+
!id || idSet.has(id) || (idSet.add(id), names.push(id), symbols.push(`<symbol id="${id}"${viewBox ? ` viewBox="${viewBox}"` : ''}>${inner}</symbol>`));
|
|
2589
|
+
}
|
|
2590
|
+
return {
|
|
2591
|
+
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>`,
|
|
2592
|
+
names
|
|
2593
|
+
};
|
|
2594
|
+
})((root = rootPath1, (resolvedOptions.iconDirs || []).map((dir)=>node_path.isAbsolute(dir) ? dir : node_path.resolve(root, dir))), resolvedOptions.symbolId, domId);
|
|
2595
|
+
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`;
|
|
2596
|
+
})();
|
|
2597
|
+
},
|
|
2598
|
+
virtualModules: ()=>({
|
|
2599
|
+
'~svg-icons-register': registerCode || 'export default null',
|
|
2600
|
+
'~svg-icons-names': namesCode || 'export default []'
|
|
2601
|
+
}),
|
|
2602
|
+
transform: {
|
|
2603
|
+
filter: {
|
|
2604
|
+
test: JS_REGEX
|
|
2605
|
+
},
|
|
2606
|
+
handler: (code)=>code.includes('virtual:svg-icons-') ? code.replace('virtual:svg-icons-', '~svg-icons-') : null
|
|
2607
|
+
}
|
|
2608
|
+
})
|
|
2609
|
+
]
|
|
2610
|
+
};
|
|
2611
|
+
return {
|
|
2612
|
+
...utils_mergeConfig(defaultConfig, userConfig),
|
|
2213
2613
|
_context
|
|
2214
2614
|
};
|
|
2215
2615
|
};
|
|
@@ -2218,7 +2618,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
|
|
|
2218
2618
|
let mode = watch ? 'development' : 'production';
|
|
2219
2619
|
setNodeEnv(mode);
|
|
2220
2620
|
let config = resolveConfig(mode);
|
|
2221
|
-
console.log(colors.brand(`${callerName} v4.
|
|
2621
|
+
console.log(colors.brand(`${callerName} v4.2.0`), colors.cyan(`building for ${mode}...`)), await unpackBuild(config);
|
|
2222
2622
|
},
|
|
2223
2623
|
dev: async ()=>{
|
|
2224
2624
|
setUnpackStartTime(performance.now());
|
|
@@ -2236,7 +2636,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
|
|
|
2236
2636
|
let GLOB_REGEX = /[*?{}[\]()!@+|]/;
|
|
2237
2637
|
async function createChokidar(pathOrGlobs, root = process.cwd(), options) {
|
|
2238
2638
|
let watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
|
|
2239
|
-
if (globPatterns.length) for (let file of (await
|
|
2639
|
+
if (globPatterns.length) for (let file of (await external_tinyglobby_glob(globPatterns, {
|
|
2240
2640
|
cwd: root,
|
|
2241
2641
|
absolute: !0
|
|
2242
2642
|
})))watchFiles.add(file);
|
|
@@ -2246,6 +2646,14 @@ async function createChokidar(pathOrGlobs, root = process.cwd(), options) {
|
|
|
2246
2646
|
...options
|
|
2247
2647
|
});
|
|
2248
2648
|
}
|
|
2649
|
+
var injectFramework_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
2650
|
+
async function injectFrameworkPluginForDebug(userConfig) {
|
|
2651
|
+
var plugin;
|
|
2652
|
+
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`);
|
|
2653
|
+
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 = [
|
|
2654
|
+
plugin
|
|
2655
|
+
]);
|
|
2656
|
+
}
|
|
2249
2657
|
async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer }) {
|
|
2250
2658
|
let shortcuts = [
|
|
2251
2659
|
restartServer ? {
|
|
@@ -2298,7 +2706,6 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
|
|
|
2298
2706
|
for (let shortcut of shortcuts)if (input === shortcut.key) return void shortcut.action();
|
|
2299
2707
|
}), addRestartCleaner(()=>rl.close());
|
|
2300
2708
|
}
|
|
2301
|
-
var cli_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
2302
2709
|
let withErrorHandling = (action)=>async (options)=>{
|
|
2303
2710
|
try {
|
|
2304
2711
|
await action(options);
|
|
@@ -2311,14 +2718,8 @@ async function setupUnpack(cliOptions, command) {
|
|
|
2311
2718
|
let userConfig = await loadConfig({
|
|
2312
2719
|
cliOptions,
|
|
2313
2720
|
command
|
|
2314
|
-
})
|
|
2315
|
-
|
|
2316
|
-
let { pluginReact } = await import(pluginReactPath);
|
|
2317
|
-
userConfig.plugins ? userConfig.plugins.unshift(pluginReact()) : userConfig.plugins = [
|
|
2318
|
-
pluginReact()
|
|
2319
|
-
];
|
|
2320
|
-
}
|
|
2321
|
-
return {
|
|
2721
|
+
});
|
|
2722
|
+
return await injectFrameworkPluginForDebug(userConfig), {
|
|
2322
2723
|
unpack: createUnpack({
|
|
2323
2724
|
cwd: userConfig.root,
|
|
2324
2725
|
config: userConfig
|
|
@@ -2366,7 +2767,7 @@ function runCLI() {
|
|
|
2366
2767
|
logger_logger.clear(), logger_logger.info(`${node_path.basename(file)} changed, restarting server...`), await watcher.close(), await cleanUpBeforeRestart(), startServer(options);
|
|
2367
2768
|
});
|
|
2368
2769
|
});
|
|
2369
|
-
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.
|
|
2770
|
+
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.2.0"), cli.parse();
|
|
2370
2771
|
}
|
|
2371
2772
|
var src_CSS_MODULES_NAMED_EXPORT = !1;
|
|
2372
|
-
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,
|
|
2773
|
+
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 };
|