@unpackjs/core 3.2.7 → 3.3.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/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ let lastTrackTime, lastFileInfo, logger;
1
2
  import __rslib_shim_module__ from 'module';
2
3
  let require = __rslib_shim_module__.createRequire(import.meta.url);
3
4
  import { fileURLToPath as __webpack_fileURLToPath__ } from "node:url";
@@ -6,14 +7,14 @@ import * as __WEBPACK_EXTERNAL_MODULE__compiled_webpack_bundle_analyzer_index_js
6
7
  import * as __WEBPACK_EXTERNAL_MODULE__compiled_webpack_merge_index_js_efd91626__ from "../compiled/webpack-merge/index.js";
7
8
  import { experiments, rspack } from "@rspack/core";
8
9
  import picocolors from "picocolors";
9
- import node_fs from "node:fs";
10
- import node_path, { join, sep } from "node:path";
11
- import { pathToFileURL } from "node:url";
12
- import { createJiti } from "jiti";
13
10
  import node_readline from "node:readline";
11
+ import node_fs from "node:fs";
14
12
  import node_net from "node:net";
15
13
  import node_os, { platform } from "node:os";
14
+ import node_path, { join, sep } from "node:path";
16
15
  import portfinder from "portfinder";
16
+ import { pathToFileURL } from "node:url";
17
+ import { createJiti } from "jiti";
17
18
  import { expand } from "dotenv-expand";
18
19
  import { TsCheckerRspackPlugin } from "ts-checker-rspack-plugin";
19
20
  import node_assert from "node:assert";
@@ -22,9 +23,9 @@ import typed_css_modules from "typed-css-modules";
22
23
  import { exec, spawn } from "node:child_process";
23
24
  import { promisify } from "node:util";
24
25
  import node_zlib from "node:zlib";
26
+ import { RspackDevServer } from "@rspack/dev-server";
25
27
  import cors from "cors";
26
28
  import express from "express";
27
- import webpack_dev_server from "webpack-dev-server";
28
29
  import chokidar from "chokidar";
29
30
  var LogColor, __webpack_modules__ = {
30
31
  "compiled/webpack-bundle-analyzer": function(module) {
@@ -51,8 +52,14 @@ let colors = {
51
52
  for (let char of chars)isWord(char) && (r += rStep, g += gStep, b += bStep), output += `\x1b[38;2;${Math.round(r)};${Math.round(g)};${Math.round(b)}m${char}\x1b[39m`;
52
53
  return output;
53
54
  }
55
+ }, restartCleaners = [], addRestartCleaner = (...cleaners)=>{
56
+ restartCleaners.push(...cleaners);
57
+ }, cleanUpBeforeRestart = async ()=>{
58
+ await Promise.all(restartCleaners.map((cleaner)=>cleaner())), restartCleaners.length = 0;
59
+ }, currentDevUnpackConfig = {}, setCurrentDevUnpackConfig = (config)=>{
60
+ currentDevUnpackConfig = config;
54
61
  };
55
- var logger_LogColor = ((LogColor = {}).error = "red", LogColor.warn = "yellow", LogColor.info = "cyan", LogColor.ready = "green", LogColor.event = "magenta", LogColor.wait = "blue", LogColor.debug = "dim", LogColor);
62
+ var logger_LogColor = ((LogColor = {}).error = "red", LogColor.warn = "yellow", LogColor.info = "cyan", LogColor.ready = "green", LogColor.event = "magenta", LogColor.wait = "blue", LogColor);
56
63
  let CSS_MODULES_LOCAL_IDENT_NAME = '[path][name]__[local]--[hash:5]', CSS_MODULES_REGEX = /\.module\.\w+$/i, DEV_DEFAULT_FILENAME = {
57
64
  js: 'js/[name].js',
58
65
  jsAsync: 'js/async/[name].js',
@@ -63,7 +70,7 @@ let CSS_MODULES_LOCAL_IDENT_NAME = '[path][name]__[local]--[hash:5]', CSS_MODULE
63
70
  jsAsync: 'js/async/[name].[contenthash:8].js',
64
71
  css: 'css/[name].[contenthash:8].css',
65
72
  cssAsync: 'css/async/[name].[contenthash:8].css'
66
- }, EXPORT_LOCALS_CONVENTION = 'camel-case-only', TEMP_DIR = 'node_modules/.unpack', NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, CSS_NAMED_EXPORT = !1, THREAD_OPTIONS = {
73
+ }, EXPORT_LOCALS_CONVENTION = 'camel-case-only', TEMP_DIR = 'node_modules/.unpack', NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, THREAD_OPTIONS = {
67
74
  workers: 2
68
75
  }, DEFAULT_DEV_HOST = '0.0.0.0', TEMPLATE_CONTENT = ({ title = '', headTag = '', mountId = '' })=>`<!DOCTYPE html>
69
76
  <html lang="en">
@@ -177,12 +184,11 @@ let debounce = (fn, delay)=>{
177
184
  });
178
185
  return addressUrls;
179
186
  }, trackPerformance = (msg)=>{
180
- let k = '__unpack_last_track_time';
181
- if (!global[k]) {
182
- global[k] = performance.now();
187
+ if (!lastTrackTime) {
188
+ lastTrackTime = performance.now();
183
189
  return;
184
190
  }
185
- msg && console.log(` ${msg} ${colors.dim('in')} ${colors.yellow(`${(performance.now() - global[k]).toFixed(2)}ms`)}`), global[k] = performance.now();
191
+ msg && console.log(` ${msg} ${colors.dim('in')} ${colors.yellow(`${(performance.now() - lastTrackTime).toFixed(2)}ms`)}`), lastTrackTime = performance.now();
186
192
  }, getPathInJs = (absPath)=>JSON.stringify(absPath).slice(1, -1), mergeConfig = merge, getUserDepVersion = (root, dep)=>{
187
193
  let depPath = getUserDepPath(root, dep);
188
194
  if (depPath) return JSON.parse(node_fs.readFileSync(node_path.resolve(depPath, 'package.json'), 'utf-8')).version;
@@ -223,50 +229,98 @@ let isCSSModules = ({ resourcePath, modules })=>{
223
229
  if (!browsers) throw Error(`Unsupported ES version: ${esVersion}`);
224
230
  return browsers;
225
231
  }, logger_prefixes = {
226
- wait: "\u25CB",
227
- error: "\u2A2F",
228
- warn: "\u26A0",
229
- info: "\u2139",
230
- ready: "\u2713",
231
- event: "\xbb",
232
- debug: "\u279C"
233
- }, logger_logger = (()=>{
234
- let logger = {
235
- clear: ()=>{
236
- let repeatCount = process.stdout.rows - 2;
237
- console.log(repeatCount > 0 ? '\n'.repeat(repeatCount) : ''), node_readline.cursorTo(process.stdout, 0, 0), node_readline.clearScreenDown(process.stdout);
238
- },
239
- greet: (msg)=>{
240
- let { npm_execpath, npm_lifecycle_event } = process.env;
241
- (!npm_execpath || 'npx' === npm_lifecycle_event || npm_execpath.includes('npx-cli') || npm_execpath.includes('.bun') || npm_execpath.includes('yarn')) && console.log(), console.log(msg);
242
- }
232
+ wait: '○',
233
+ error: '⨯',
234
+ warn: '⚠',
235
+ info: 'ℹ',
236
+ ready: '✓',
237
+ event: '»'
238
+ }, logger_logger = (logger = {
239
+ clear: ()=>{
240
+ let repeatCount = process.stdout.rows - 2;
241
+ console.log(repeatCount > 0 ? '\n'.repeat(repeatCount) : ''), node_readline.cursorTo(process.stdout, 0, 0), node_readline.clearScreenDown(process.stdout);
242
+ },
243
+ greet: (msg)=>{
244
+ let { npm_execpath, npm_lifecycle_event } = process.env;
245
+ (!npm_execpath || 'npx' === npm_lifecycle_event || npm_execpath.includes('npx-cli') || npm_execpath.includes('.bun') || npm_execpath.includes('yarn')) && console.log(), console.log(msg);
246
+ },
247
+ debug: (message, ...args)=>{
248
+ isDebug() && console.log(`${colors.gray(colors.dim(getTime()))} ${message}`, ...args);
249
+ }
250
+ }, Object.keys(logger_prefixes).forEach((type)=>{
251
+ logger[type] = (message, ...args)=>{
252
+ ((type, message, ...args)=>{
253
+ let label = colors[logger_LogColor[type]](logger_prefixes[type]), text = '';
254
+ switch(type){
255
+ case 'error':
256
+ if (message instanceof Error) if (message.stack) {
257
+ let [name, ...rest] = message.stack.split('\n');
258
+ name.startsWith('Error: ') && (name = name.slice(7), rest = rest.map((line)=>line.slice(2))), text = `${colors.red(name)}\n${colors.dim(rest.join('\n'))}`;
259
+ } else text = colors.red(message.message);
260
+ else text = colors.red(message);
261
+ break;
262
+ case 'warn':
263
+ text = colors.yellow(message);
264
+ break;
265
+ default:
266
+ text = message;
267
+ }
268
+ console.log(`${label} ${text}`, ...args);
269
+ })(type, message, ...args);
243
270
  };
244
- return Object.keys(logger_prefixes).forEach((type)=>{
245
- logger[type] = (message, ...args)=>{
246
- ((type, message, ...args)=>{
247
- let label = colors[logger_LogColor[type]](logger_prefixes[type]), text = '';
248
- switch(type){
249
- case 'error':
250
- if (message instanceof Error) if (message.stack) {
251
- let [name, ...rest] = message.stack.split('\n');
252
- name.startsWith('Error: ') && (name = name.slice(7), rest = rest.map((line)=>line.slice(2))), text = `${colors.red(name)}\n${colors.dim(rest.join('\n'))}`;
253
- } else text = colors.red(message.message);
254
- else text = colors.red(message);
255
- break;
256
- case 'warn':
257
- text = colors.yellow(message);
258
- break;
259
- case 'debug':
260
- text = `${colors.dim(getTime())} ${colors.magenta('debug')} ${message}`;
261
- break;
262
- default:
263
- text = message;
271
+ }), logger);
272
+ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer }) {
273
+ let shortcuts = [
274
+ restartServer ? {
275
+ key: 'r',
276
+ description: 'restart server',
277
+ action: restartServer
278
+ } : null,
279
+ {
280
+ key: 'u',
281
+ description: 'show server url',
282
+ action: printUrls
283
+ },
284
+ {
285
+ key: 'o',
286
+ description: 'open in browser',
287
+ action: openPage
288
+ },
289
+ {
290
+ key: 'c',
291
+ description: 'clear console',
292
+ action: ()=>{
293
+ logger_logger.clear();
294
+ }
295
+ },
296
+ {
297
+ key: 'q',
298
+ description: 'quit',
299
+ action: async ()=>{
300
+ try {
301
+ await closeServer();
302
+ } finally{
303
+ process.exit(0);
264
304
  }
265
- ('debug' !== type || isDebug()) && console.log(`${label} ${text}`, ...args);
266
- })(type, message, ...args);
267
- };
268
- }), logger;
269
- })();
305
+ }
306
+ }
307
+ ].filter(Boolean), colorPrefix = colors.green(colors.dim('➜'));
308
+ help && console.log(!0 === help ? ` ${colorPrefix} ${colors.dim('press')} ${colors.bold('h + enter')} ${colors.dim('to show help')}` : ` ${colorPrefix} ${help}`);
309
+ let { createInterface } = await import("node:readline"), rl = createInterface({
310
+ input: process.stdin
311
+ });
312
+ rl.on('line', (input)=>{
313
+ if ('h' === input) {
314
+ let message = '\n Shortcuts\n';
315
+ for (let shortcut of shortcuts){
316
+ let fullDescription = `${colors.dim('press')} ${colors.bold(`${shortcut.key} + enter`)} ${colors.dim(`to ${shortcut.description}`)}`;
317
+ message += ` ${fullDescription}\n`;
318
+ }
319
+ console.log(message);
320
+ }
321
+ for (let shortcut of shortcuts)if (input === shortcut.key) return void shortcut.action();
322
+ }), addRestartCleaner(()=>rl.close());
323
+ }
270
324
  var config_filename = __webpack_fileURLToPath__(import.meta.url);
271
325
  async function loadConfig({ cliOptions, command }) {
272
326
  'build' === command ? setNodeEnv((null == cliOptions ? void 0 : cliOptions.watch) ? 'development' : 'production') : (setNodeEnv('development'), setDevServer(!0));
@@ -317,7 +371,10 @@ async function loadConfig({ cliOptions, command }) {
317
371
  'bundleAnalyze'
318
372
  ], cliOptions.analyze), (null == cliOptions ? void 0 : cliOptions.root) && setValueByPath(configExport, [
319
373
  'root'
320
- ], root), configExport;
374
+ ], root), (null == cliOptions ? void 0 : cliOptions.host) && setValueByPath(configExport, [
375
+ 'server',
376
+ 'host'
377
+ ], cliOptions.host), configExport;
321
378
  }
322
379
  function defineConfig(config) {
323
380
  return config;
@@ -571,7 +628,7 @@ class TypedCssModulesPlugin {
571
628
  constructor(options){
572
629
  _define_property(this, "dtsCreator", void 0), _define_property(this, "useIncremental", !1), _define_property(this, "globPattern", 'src/**/*.{css,less,scss}'), _define_property(this, "userOptions", void 0), this.userOptions = options, this.dtsCreator = new DtsCreator({
573
630
  camelCase: !0,
574
- namedExports: CSS_NAMED_EXPORT
631
+ namedExports: !1
575
632
  });
576
633
  }
577
634
  }
@@ -588,7 +645,7 @@ class JsMinifyPlugin {
588
645
  apply(compiler) {
589
646
  let meta = JSON.stringify({
590
647
  name: jsMinify_PLUGIN_NAME,
591
- version: "3.2.7",
648
+ version: "3.3.0",
592
649
  options: this.minifyOptions
593
650
  });
594
651
  compiler.hooks.compilation.tap(jsMinify_PLUGIN_NAME, (compilation)=>{
@@ -719,16 +776,16 @@ class LoadingAnimation {
719
776
  }
720
777
  constructor(){
721
778
  loadingAnimation_define_property(this, "chars", [
722
- "\u280B",
723
- "\u2819",
724
- "\u2839",
725
- "\u2838",
726
- "\u283C",
727
- "\u2834",
728
- "\u2826",
729
- "\u2827",
730
- "\u2807",
731
- "\u280F"
779
+ '⠋',
780
+ '⠙',
781
+ '⠹',
782
+ '⠸',
783
+ '⠼',
784
+ '⠴',
785
+ '⠦',
786
+ '⠧',
787
+ '⠇',
788
+ '⠏'
732
789
  ]), loadingAnimation_define_property(this, "currentIndex", 0), loadingAnimation_define_property(this, "lastUpdateTime", 0), loadingAnimation_define_property(this, "interval", 100);
733
790
  }
734
791
  }
@@ -794,7 +851,7 @@ async function printFileSize({ root, stats }) {
794
851
  }), longest = 0, totalSize = 0, totalCompressedSize = 0;
795
852
  await Promise.all(origin.assets.map(async (asset)=>{
796
853
  let content = await node_fs.promises.readFile(node_path.join(distPath, asset.name)), size = content.length, compressedSize = await getCompressedSize(content);
797
- totalSize += size, totalCompressedSize += compressedSize, compressedCount++, logUpdate(`${loadingAnimation.getCurrentChar()} computing gzip size (${compressedCount})...`), compressedCount === origin.assets.length && (logUpdate(`\u{2713} computed gzip size (${compressedCount})`), console.log());
854
+ totalSize += size, totalCompressedSize += compressedSize, compressedCount++, logUpdate(`${loadingAnimation.getCurrentChar()} computing gzip size (${compressedCount})...`), compressedCount === origin.assets.length && (logUpdate(`✓ computed gzip size (${compressedCount})`), console.log());
798
855
  let chunk = {
799
856
  name: node_path.basename(asset.name),
800
857
  path: `${distFolder}/${asset.name}`,
@@ -820,11 +877,11 @@ async function printFileSize({ root, stats }) {
820
877
  chunkGroups.forEach((group)=>{
821
878
  group.chunks.sort((a, b)=>a.size - b.size).forEach((chunk)=>{
822
879
  let isLarge = 'JS' === group.type && chunk.size / 1000 > 500, relativeOutDir = node_path.dirname(chunk.path) + '/', log = colors.dim(relativeOutDir);
823
- log += colors[group.color](chunk.name.padEnd(longest + 2 - relativeOutDir.length)), log += colors[isLarge ? 'yellow' : 'dim'](displaySize(chunk.size).padStart(sizePad)), chunk.compressedSize && (log += colors.dim(` \u{2502} gzip: ${displaySize(chunk.compressedSize).padStart(compressPad)}`)), console.log(log);
880
+ log += colors[group.color](chunk.name.padEnd(longest + 2 - relativeOutDir.length)), log += colors[isLarge ? 'yellow' : 'dim'](displaySize(chunk.size).padStart(sizePad)), chunk.compressedSize && (log += colors.dim(` gzip: ${displaySize(chunk.compressedSize).padStart(compressPad)}`)), console.log(log);
824
881
  });
825
882
  });
826
883
  let log = colors.blue('Total'.padEnd(longest + 2));
827
- log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` \u{2502} gzip: ${displaySize(totalCompressedSize)}`));
884
+ log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` gzip: ${displaySize(totalCompressedSize)}`));
828
885
  }
829
886
  function isLikelyFile(filePath) {
830
887
  return (filePath.split(sep).pop() || '').includes('.');
@@ -834,29 +891,13 @@ function formatFileList(paths, rootPath) {
834
891
  0 === files.length && (files = [
835
892
  paths[0]
836
893
  ]);
837
- let fileInfo = files.slice(0, 1).map((file)=>(function(originalFilePath, root) {
838
- let prefix = root.endsWith(sep) ? root : root + sep, filePath = originalFilePath;
839
- filePath.startsWith(prefix) && (filePath = filePath.slice(prefix.length));
840
- let parts = filePath.split(sep).filter(Boolean);
841
- return parts.length > 3 ? parts.slice(-3).join(sep) : parts.join(sep);
842
- })(file, rootPath)).join(', ');
894
+ let fileInfo = files.slice(0, 1).map((file)=>{
895
+ let prefix, filePath, parts;
896
+ return prefix = rootPath.endsWith(sep) ? rootPath : rootPath + sep, (filePath = file).startsWith(prefix) && (filePath = filePath.slice(prefix.length)), (parts = filePath.split(sep).filter(Boolean)).length > 3 ? parts.slice(-3).join(sep) : parts.join(sep);
897
+ }).join(', ');
843
898
  return files.length > 1 ? `${fileInfo} and ${files.length - 1} more` : fileInfo;
844
899
  }
845
- function printDevLog(compiler, root) {
846
- let changedFiles = compiler.modifiedFiles ? Array.from(compiler.modifiedFiles) : null;
847
- if (null == changedFiles ? void 0 : changedFiles.length) {
848
- let fileInfo = formatFileList(changedFiles, root);
849
- logger_logger.wait(`building ${colors.dim(fileInfo)}`);
850
- return;
851
- }
852
- let removedFiles = compiler.removedFiles ? Array.from(compiler.removedFiles) : null;
853
- if (null == removedFiles ? void 0 : removedFiles.length) {
854
- let fileInfo = formatFileList(removedFiles, root);
855
- logger_logger.wait(`building ${colors.dim(`removed ${fileInfo}`)}`);
856
- return;
857
- }
858
- logger_logger.wait('building...');
859
- }
900
+ let sameCount = 0;
860
901
  async function compileDone(compiler, stats) {
861
902
  let compileTime = stats.toJson({
862
903
  preset: 'errors-only',
@@ -867,27 +908,35 @@ async function compileDone(compiler, stats) {
867
908
  stats
868
909
  }), logger_logger.ready(colors.green(`built in ${prettyTime(compileTime)}`));
869
910
  else {
870
- if (isDebug()) {
871
- let modules = stats.compilation.modules, nodeModulesStats = new Map(), nodeModulesPath = node_path.resolve(root, 'node_modules');
872
- modules.forEach((module)=>{
911
+ let fileInfo = function(changedFiles, removedFiles, root) {
912
+ if (!(null == changedFiles ? void 0 : changedFiles.length) && !(null == removedFiles ? void 0 : removedFiles.length)) return null;
913
+ if ((null == changedFiles ? void 0 : changedFiles.length) && (null == removedFiles ? void 0 : removedFiles.length)) {
914
+ let changedInfo = formatFileList(changedFiles, root), removedInfo = formatFileList(removedFiles, root);
915
+ return `${changedInfo}, removed ${removedInfo}`;
916
+ }
917
+ return (null == changedFiles ? void 0 : changedFiles.length) ? formatFileList(changedFiles, root) : (null == removedFiles ? void 0 : removedFiles.length) ? `removed ${formatFileList(removedFiles, root)}` : null;
918
+ }(compiler.modifiedFiles ? Array.from(compiler.modifiedFiles) : null, compiler.removedFiles ? Array.from(compiler.removedFiles) : null, root);
919
+ if (!fileInfo) return;
920
+ if (fileInfo === lastFileInfo ? sameCount++ : (lastFileInfo = fileInfo, sameCount = 1), isDebug()) {
921
+ var modules;
922
+ let nodeModulesStats, nodeModulesPath;
923
+ Object.entries((modules = stats.compilation.modules, nodeModulesStats = {}, nodeModulesPath = node_path.resolve(root, 'node_modules'), modules.forEach((module)=>{
873
924
  let { resource } = module;
874
925
  if (null == resource ? void 0 : resource.includes(nodeModulesPath)) {
875
926
  let packageName, pathParts = node_path.relative(nodeModulesPath, resource).split(sep);
876
- (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.set(packageName, (nodeModulesStats.get(packageName) || 0) + 1);
927
+ (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);
877
928
  }
878
- }), nodeModulesStats.size > 0 && Array.from(nodeModulesStats.entries()).sort((a, b)=>a[1] - b[1]).forEach(([packageName, count])=>{
929
+ }), nodeModulesStats)).sort((a, b)=>a[1] - b[1]).forEach(([packageName, count])=>{
879
930
  logger_logger.debug(`${colors.cyan(packageName)}: ${colors.yellow(count)} modules`);
880
931
  });
881
932
  }
882
- logger_logger.ready(`built in ${prettyTime(compileTime)}${isDebug() ? ` (${stats.compilation.modules.size} modules)` : ''}`);
933
+ isDebug() || logger_logger.clear(), console.log(colors.dim(getTime()), colors.cyan(colors.bold(`[${global.__unpack_caller_name}]`)), colors.green(utils_isDevServer() ? 'hmr update' : 'build'), `${colors.dim(fileInfo)}${sameCount > 1 ? ` ${colors.yellow(`(x${sameCount})`)}` : ''}`, isDebug() ? colors.dim(`| ${prettyTime(compileTime)} (${stats.compilation.modules.size} modules)`) : '');
883
934
  }
884
935
  }
885
936
  let progress_PLUGIN_NAME = 'ProgressPlugin';
886
937
  class ProgressLiteRspackPlugin {
887
938
  apply(compiler) {
888
- compiler.hooks.watchRun.tap(progress_PLUGIN_NAME, ()=>{
889
- (!utils_isDevServer() || global.__unpack_dev_server_started) && printDevLog(compiler, compiler.options.context);
890
- }), compiler.hooks.run.tap(progress_PLUGIN_NAME, ()=>{
939
+ compiler.hooks.run.tap(progress_PLUGIN_NAME, ()=>{
891
940
  logger_logger.info('build started...');
892
941
  }), compiler.hooks.afterDone.tap(progress_PLUGIN_NAME, async (stats)=>{
893
942
  await compileDone(compiler, stats);
@@ -896,9 +945,7 @@ class ProgressLiteRspackPlugin {
896
945
  }
897
946
  class ProgressRspackPlugin extends rspack.ProgressPlugin {
898
947
  apply(compiler) {
899
- super.apply(compiler), compiler.hooks.watchRun.tap(progress_PLUGIN_NAME, ()=>{
900
- (!utils_isDevServer() || global.__unpack_dev_server_started) && printDevLog(compiler, compiler.options.context);
901
- }), compiler.hooks.afterDone.tap(progress_PLUGIN_NAME, async (stats)=>{
948
+ super.apply(compiler), compiler.hooks.afterDone.tap(progress_PLUGIN_NAME, async (stats)=>{
902
949
  await compileDone(compiler, stats);
903
950
  });
904
951
  }
@@ -1097,10 +1144,9 @@ async function getBundlerConfig(originalUnpackConfig) {
1097
1144
  let filePath = module.replace(/^.*!/, ''), relativePath = node_path.relative(unpackConfig.root, filePath);
1098
1145
  return relativePath.startsWith('..') ? filePath : relativePath;
1099
1146
  }).slice(0, -1);
1100
- if (2 + uniquePaths.join(" \u2192 ").length > (process.stdout.columns || 80)) {
1101
- console.log('');
1102
- let arrow = "\u21B3 ", lastIndex = uniquePaths.length - 1;
1103
- uniquePaths.forEach((p, i)=>{
1147
+ if (2 + uniquePaths.join(' ').length > (process.stdout.columns || 80)) {
1148
+ let arrow, lastIndex;
1149
+ console.log(''), arrow = '↳ ', lastIndex = uniquePaths.length - 1, uniquePaths.forEach((p, i)=>{
1104
1150
  switch(i){
1105
1151
  case 0:
1106
1152
  console.log(` ${p}`);
@@ -1113,12 +1159,10 @@ async function getBundlerConfig(originalUnpackConfig) {
1113
1159
  }
1114
1160
  }), console.log(` ${arrow}${uniquePaths[0]}`), console.log('');
1115
1161
  } else {
1116
- let line1 = ' ', downArrowPos = 0;
1117
- uniquePaths.forEach((p, i)=>{
1118
- line1 += p, i < uniquePaths.length - 1 ? line1 += " \u2192 " : downArrowPos = line1.length - 1;
1119
- });
1120
- let lineLength = downArrowPos - 2;
1121
- console.log(''), console.log(line1), console.log(' ' + ' '.repeat(0) + "\u2191" + ' '.repeat(downArrowPos - 2 - 1) + "\u2193"), console.log(' ' + ' '.repeat(0) + "\u2514" + "\u2500".repeat(lineLength - 1) + "\u2518"), console.log('');
1162
+ let line1, downArrowPos, lineLength;
1163
+ line1 = ' ', downArrowPos = 0, uniquePaths.forEach((p, i)=>{
1164
+ line1 += p, i < uniquePaths.length - 1 ? line1 += ' ' : downArrowPos = line1.length - 1;
1165
+ }), lineLength = downArrowPos - 2, console.log(''), console.log(line1), console.log(' ' + ' '.repeat(0) + '↑' + ' '.repeat(downArrowPos - 2 - 1) + '↓'), console.log(' ' + ' '.repeat(0) + '└' + '─'.repeat(lineLength - 1) + '┘'), console.log('');
1122
1166
  }
1123
1167
  },
1124
1168
  onEnd () {
@@ -1161,9 +1205,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1161
1205
  experiments: {
1162
1206
  css: !1,
1163
1207
  asyncWebAssembly: !0,
1164
- lazyBarrel: !0,
1165
- inlineEnum: !0,
1166
- typeReexportsPresence: !0
1208
+ lazyBarrel: !0
1167
1209
  },
1168
1210
  optimization: {
1169
1211
  moduleIds: isDev() ? 'named' : 'deterministic',
@@ -1234,7 +1276,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1234
1276
  'parser',
1235
1277
  'css/module'
1236
1278
  ], {
1237
- namedExports: CSS_NAMED_EXPORT
1279
+ namedExports: !1
1238
1280
  }), setValueByPath(config, [
1239
1281
  'module',
1240
1282
  'generator',
@@ -1387,7 +1429,7 @@ async function getBundlerConfig(originalUnpackConfig) {
1387
1429
  })(),
1388
1430
  localIdentName: !1 !== modules && (modules.localIdentName || CSS_MODULES_LOCAL_IDENT_NAME),
1389
1431
  exportLocalsConvention: EXPORT_LOCALS_CONVENTION,
1390
- namedExport: CSS_NAMED_EXPORT
1432
+ namedExport: !1
1391
1433
  },
1392
1434
  sourceMap
1393
1435
  }
@@ -1503,7 +1545,6 @@ async function unpackBuild(unpackConfig) {
1503
1545
  };
1504
1546
  isWatch() ? compiler.watch({}, handler) : compiler.run(handler);
1505
1547
  }
1506
- let restartCleaners = [];
1507
1548
  var openBrowser_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url));
1508
1549
  async function openBrowser(url) {
1509
1550
  if ('darwin' === process.platform) try {
@@ -1572,19 +1613,20 @@ let getExternalLibraryName = (pkgName)=>({
1572
1613
  'react-dom': 'ReactDOM',
1573
1614
  'react-router-dom': 'ReactRouterDOM'
1574
1615
  })[pkgName] || pkgName, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`, prebundleDeps = async ({ unpackConfig })=>{
1575
- var _unpackConfig_dev;
1576
- let count = {
1616
+ var _unpackConfig_dev, externals;
1617
+ let existExternals, cacheDir, count = {
1577
1618
  total: 0,
1578
1619
  bundled: 0
1579
1620
  }, failedDeps = [], root = unpackConfig.root, failedDepsCachePath = node_path.resolve(root, TEMP_DIR, 'failed-deps.json'), failedCache = node_fs.existsSync(failedDepsCachePath) ? JSON.parse(node_fs.readFileSync(failedDepsCachePath, 'utf-8')) : {}, updateProgress = ()=>{
1580
- logUpdate(`${colors.magenta("\xbb")} optimizing dependencies (${count.bundled}/${count.total})`), count.total === count.bundled + failedDeps.length && console.log();
1621
+ logUpdate(`${colors.magenta('»')} optimizing dependencies (${count.bundled}/${count.total})`), count.total === count.bundled + failedDeps.length && console.log();
1581
1622
  }, userOptions = isPlainObject(null == (_unpackConfig_dev = unpackConfig.dev) ? void 0 : _unpackConfig_dev.prebundle) ? unpackConfig.dev.prebundle : {}, ignoreCSSDeps = userOptions.ignoreCSS || [], packageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'package.json'), 'utf-8')), excludeDeps = [
1582
- ...((externals)=>{
1583
- let existExternals = new Set();
1584
- return Array.isArray(externals) ? externals.forEach((item)=>{
1585
- isPlainObject(item) && Object.keys(item).forEach((key)=>existExternals.add(key));
1586
- }) : isPlainObject(externals) && Object.keys(externals).forEach((key)=>existExternals.add(key)), Array.from(existExternals);
1587
- })(unpackConfig.externals) || [],
1623
+ ...(externals = unpackConfig.externals, existExternals = new Set(), Array.isArray(externals) ? externals.forEach((item)=>{
1624
+ isPlainObject(item) && Object.keys(item).forEach((key)=>{
1625
+ existExternals.add(key);
1626
+ });
1627
+ }) : isPlainObject(externals) && Object.keys(externals).forEach((key)=>{
1628
+ existExternals.add(key);
1629
+ }), Array.from(existExternals) || []),
1588
1630
  ...userOptions.exclude || []
1589
1631
  ], shouldIncludeDeps = Object.keys(packageJson.dependencies).filter((pkgName)=>!excludeDeps.includes(pkgName)), noEntryDeps = [], needBundleDeps = shouldIncludeDeps.map((pkgName)=>{
1590
1632
  let packageJson = JSON.parse(node_fs.readFileSync(node_path.resolve(root, 'node_modules', pkgName, 'package.json'), 'utf-8')), version = packageJson.version;
@@ -1730,17 +1772,17 @@ let getExternalLibraryName = (pkgName)=>({
1730
1772
  resolve(isFailed ? void 0 : getResult());
1731
1773
  });
1732
1774
  });
1733
- }))(depInfo))), cacheDir = node_path.dirname(failedDepsCachePath);
1734
- node_fs.existsSync(cacheDir) || node_fs.mkdirSync(cacheDir, {
1775
+ }))(depInfo)));
1776
+ cacheDir = node_path.dirname(failedDepsCachePath), node_fs.existsSync(cacheDir) || node_fs.mkdirSync(cacheDir, {
1735
1777
  recursive: !0
1736
1778
  }), node_fs.writeFileSync(failedDepsCachePath, JSON.stringify(failedCache, null, 2), 'utf-8'), failedDeps[0] && logger_logger.warn(`something went wrong while optimizing "${colors.bold(failedDeps.join(', '))}"`);
1737
1779
  let cachePath = node_path.resolve(root, TEMP_DIR, 'umd'), app = express();
1738
1780
  app.use(cors()), app.use("/umd", express.static(cachePath));
1739
1781
  let port = await getPort(), staticServer = app.listen(port, ()=>{});
1740
- restartCleaners.push(()=>new Promise((resolve)=>staticServer.close(()=>resolve())));
1741
- let externals = {}, jsAssets = [], cssAssets = [], preJsAssets = [];
1782
+ addRestartCleaner(()=>new Promise((resolve)=>staticServer.close(()=>resolve())));
1783
+ let externals1 = {}, jsAssets = [], cssAssets = [], preJsAssets = [];
1742
1784
  return bundledDeps.filter(Boolean).forEach((dep)=>{
1743
- dep && (externals[dep.name] = getExternalValue(dep.name), dep.assets.forEach((absPath)=>{
1785
+ dep && (externals1[dep.name] = getExternalValue(dep.name), dep.assets.forEach((absPath)=>{
1744
1786
  let relativePath = node_path.relative(cachePath, absPath), preDeps = [
1745
1787
  'react',
1746
1788
  'react-dom',
@@ -1758,10 +1800,10 @@ let getExternalLibraryName = (pkgName)=>({
1758
1800
  }
1759
1801
  }));
1760
1802
  }), unpackConfig.externals = Array.isArray(unpackConfig.externals) ? [
1761
- externals,
1803
+ externals1,
1762
1804
  ...unpackConfig.externals
1763
1805
  ] : {
1764
- ...externals,
1806
+ ...externals1,
1765
1807
  ...unpackConfig.externals
1766
1808
  }, unpackConfig.plugins.push({
1767
1809
  name: 'unpack:prebundle',
@@ -1786,7 +1828,7 @@ let getExternalLibraryName = (pkgName)=>({
1786
1828
  }), unpackConfig;
1787
1829
  };
1788
1830
  async function unpackDev(originalUnpackConfig) {
1789
- var _unpackConfig_dev, _unpackConfig_server, _unpackConfig_server1, _unpackConfig_dev1, _unpackConfig_server2;
1831
+ var _unpackConfig_dev, _unpackConfig_server, _unpackConfig_server1, _unpackConfig_dev1, _unpackConfig_server2, _unpackConfig_server3;
1790
1832
  let unpackConfig = originalUnpackConfig;
1791
1833
  (null == (_unpackConfig_dev = unpackConfig.dev) ? void 0 : _unpackConfig_dev.prebundle) && (unpackConfig = await prebundleDeps({
1792
1834
  unpackConfig
@@ -1821,67 +1863,90 @@ async function unpackDev(originalUnpackConfig) {
1821
1863
  var _req_headers_accept;
1822
1864
  (null == (_req_headers_accept = req.headers.accept) ? void 0 : _req_headers_accept.includes('html')) && (req.url = '/index.html'), next();
1823
1865
  }), middlewares.unshift(experiments.lazyCompilationMiddleware(compiler)), middlewares);
1824
- let server = new webpack_dev_server(devServerOptions, compiler);
1825
- await server.start(), logger_logger.greet(` ${colors.green(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v3.2.7`)} ${colors.dim(`ready in ${colors.reset(Math.ceil(performance.now() - global.__unpack_start_time))}ms`)}\n`), getAddressUrls({
1826
- port: port
1827
- }).forEach((addr)=>{
1866
+ let server = new RspackDevServer(devServerOptions, compiler);
1867
+ await server.start(), logger_logger.greet(` ${colors.green(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v3.3.0`)} ${colors.dim('ready in')} ${colors.bold(Math.ceil(performance.now() - global.__unpack_start_time))} ms\n`), printAddressUrls(port, null == (_unpackConfig_server2 = unpackConfig.server) ? void 0 : _unpackConfig_server2.host), addRestartCleaner(async ()=>await server.stop(), ()=>new Promise((resolve)=>compiler.close(()=>resolve())));
1868
+ let open = null == (_unpackConfig_server3 = unpackConfig.server) ? void 0 : _unpackConfig_server3.open, url = isString(open) ? open : `http://localhost:${port}`;
1869
+ open && openBrowser(url), setupCliShortcuts({
1870
+ openPage: async ()=>{
1871
+ await openBrowser(url);
1872
+ },
1873
+ closeServer: async ()=>{
1874
+ await cleanUpBeforeRestart(), process.exit(0);
1875
+ },
1876
+ printUrls: ()=>{
1877
+ var _unpackConfig_server;
1878
+ printAddressUrls(port, null == (_unpackConfig_server = unpackConfig.server) ? void 0 : _unpackConfig_server.host);
1879
+ },
1880
+ restartServer: async ()=>{
1881
+ logger_logger.clear(), await cleanUpBeforeRestart(), createUnpack({
1882
+ cwd: currentDevUnpackConfig.root,
1883
+ config: currentDevUnpackConfig
1884
+ }).dev();
1885
+ }
1886
+ });
1887
+ }
1888
+ function printAddressUrls(port, host) {
1889
+ let addressUrls = getAddressUrls({
1890
+ port
1891
+ }), colorPrefix = colors.green('➜');
1892
+ addressUrls.forEach((addr, index)=>{
1828
1893
  let url;
1829
- console.log(` ${colors.green(colors.dim("\u279C"))} ${colors.dim(addr.label)}${(url = addr.url, colors.cyan(url.replace(/:(\d+)\//, (_, port)=>`:${colors.bold(port)}/`)))}`);
1830
- }), logger_logger.wait('building...'), global.__unpack_dev_server_started = !0, restartCleaners.push(async ()=>await server.stop(), ()=>new Promise((resolve)=>compiler.close(()=>resolve())), ()=>{
1831
- global.__unpack_dev_server_started = !1;
1894
+ if (!host && 0 !== index) {
1895
+ 1 === index && console.log(` ${colors.dim(colorPrefix)} ${colors.bold(colors.dim('Network:'))} ${colors.dim('use')} ${colors.bold('--host')} ${colors.dim('to expose')}`);
1896
+ return;
1897
+ }
1898
+ console.log(` ${colorPrefix} ${colors.bold(addr.label)}${(url = addr.url, colors.cyan(url.replace(/:(\d+)\//, (_, port)=>`:${colors.bold(port)}/`)))}`);
1832
1899
  });
1833
- let open = null == (_unpackConfig_server2 = unpackConfig.server) ? void 0 : _unpackConfig_server2.open;
1834
- if (open) {
1835
- let url = isString(open) ? open : `http://localhost:${port}`;
1836
- await openBrowser(url);
1837
- }
1838
1900
  }
1839
1901
  function createUnpack({ cwd = process.cwd(), config, callerName = 'unpack' }) {
1840
- let resolveConfig = ()=>({
1841
- ...mergeConfig({
1842
- root: cwd,
1843
- build: {
1844
- outDir: 'dist',
1845
- minify: isProd(),
1846
- sourceMap: !isProd() && 'cheap-module-source-map',
1847
- parallel: !0,
1848
- filenameHash: !0,
1849
- target: 'es2022'
1850
- },
1851
- dev: {
1852
- lazyCompilation: !0
1853
- },
1854
- server: {
1855
- port: 3000
1856
- },
1857
- html: {
1858
- mountId: 'root'
1859
- },
1860
- css: {
1861
- modules: !0,
1862
- transformer: 'postcss',
1863
- sourceMap: !1
1864
- },
1865
- performance: {
1866
- chunkSplit: {
1867
- strategy: 'split-by-experience'
1868
- }
1869
- },
1870
- typeCheck: !0,
1871
- envPrefix: [
1872
- 'PUBLIC_'
1873
- ]
1874
- }, config),
1902
+ let resolveConfig = ()=>{
1903
+ let defaultConfig = {
1904
+ root: cwd,
1905
+ build: {
1906
+ outDir: 'dist',
1907
+ minify: isProd(),
1908
+ sourceMap: !isProd() && 'cheap-module-source-map',
1909
+ parallel: !0,
1910
+ filenameHash: !0,
1911
+ target: 'es2022'
1912
+ },
1913
+ dev: {
1914
+ lazyCompilation: !0
1915
+ },
1916
+ server: {
1917
+ port: 3000
1918
+ },
1919
+ html: {
1920
+ mountId: 'root'
1921
+ },
1922
+ css: {
1923
+ modules: !0,
1924
+ transformer: 'postcss',
1925
+ sourceMap: !1
1926
+ },
1927
+ performance: {
1928
+ chunkSplit: {
1929
+ strategy: 'split-by-experience'
1930
+ }
1931
+ },
1932
+ typeCheck: !0,
1933
+ envPrefix: [
1934
+ 'PUBLIC_'
1935
+ ]
1936
+ };
1937
+ return global.__unpack_caller_name = callerName, {
1938
+ ...mergeConfig(defaultConfig, config),
1875
1939
  _context: {
1876
1940
  callerName,
1877
- version: "3.2.7"
1941
+ version: "3.3.0"
1878
1942
  }
1879
- });
1943
+ };
1944
+ };
1880
1945
  return {
1881
1946
  build: async ({ watch } = {})=>{
1882
1947
  setNodeEnv(watch ? 'development' : 'production');
1883
1948
  let config = resolveConfig();
1884
- console.log(colors.rainbow(`${callerName} v3.2.7`), colors.green(`building for ${getNodeEnv()}...`)), await unpackBuild(config);
1949
+ console.log(colors.rainbow(`${callerName} v3.3.0`), colors.green(`building for ${getNodeEnv()}...`)), await unpackBuild(config);
1885
1950
  },
1886
1951
  dev: async ()=>{
1887
1952
  global.__unpack_start_time = performance.now(), setNodeEnv('development'), setDevServer(!0);
@@ -1903,4 +1968,5 @@ async function createChokidar(pathOrGlobs, root = process.cwd(), options) {
1903
1968
  ...options
1904
1969
  });
1905
1970
  }
1906
- export { CSS_MODULES_LOCAL_IDENT_NAME, CSS_MODULES_REGEX, CSS_NAMED_EXPORT, DEFAULT_DEV_HOST, DEV_DEFAULT_FILENAME, EXPORT_LOCALS_CONVENTION, logger_LogColor as LogColor, NODE_MODULES_REGEX, PROD_DEFAULT_FILENAME, TEMPLATE_CONTENT, TEMP_DIR, THREAD_OPTIONS, clearLine, colors, createChokidar, createUnpack, debounce, defineConfig, esVersionToBrowserslist, findExists, getAddressUrls, getCompiledPkgPath, getIpv4Interfaces, getNodeEnv, getPathInJs, getPort, getTime, getUserDepPath, getUserDepVersion, getValueByPath, isBoolean, isCI, isCSSModules, isDebug, isDev, utils_isDevServer as isDevServer, isEmptyDir, isFileExists, isFileSync, isFunction, isNodeVersionAtLeast, isObject, isPlainObject, isProd, isRegExp, isString, isUndefined, isWatch, isWin, loadConfig, logUpdate, logger_logger as logger, mergeConfig, pathExists, prettyTime, removeDir, resolveConfigPath, restartCleaners, rspack, setDevServer, setNodeEnv, setValueByPath, trackPerformance };
1971
+ var __webpack_exports__CSS_NAMED_EXPORT = !1;
1972
+ export { CSS_MODULES_LOCAL_IDENT_NAME, CSS_MODULES_REGEX, DEFAULT_DEV_HOST, DEV_DEFAULT_FILENAME, EXPORT_LOCALS_CONVENTION, logger_LogColor as LogColor, NODE_MODULES_REGEX, PROD_DEFAULT_FILENAME, TEMPLATE_CONTENT, TEMP_DIR, THREAD_OPTIONS, addRestartCleaner, cleanUpBeforeRestart, clearLine, colors, createChokidar, createUnpack, currentDevUnpackConfig, debounce, defineConfig, esVersionToBrowserslist, findExists, getAddressUrls, getCompiledPkgPath, getIpv4Interfaces, getNodeEnv, getPathInJs, getPort, getTime, getUserDepPath, getUserDepVersion, getValueByPath, isBoolean, isCI, isCSSModules, isDebug, isDev, utils_isDevServer as isDevServer, isEmptyDir, isFileExists, isFileSync, isFunction, isNodeVersionAtLeast, isObject, isPlainObject, isProd, isRegExp, isString, isUndefined, isWatch, isWin, loadConfig, logUpdate, logger_logger as logger, mergeConfig, pathExists, prettyTime, removeDir, resolveConfigPath, rspack, setCurrentDevUnpackConfig, setDevServer, setNodeEnv, setValueByPath, setupCliShortcuts, trackPerformance, __webpack_exports__CSS_NAMED_EXPORT as CSS_NAMED_EXPORT };