@rslib/core 0.1.4 → 0.1.5

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
@@ -8,10 +8,7 @@ import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
8
8
  import * as __WEBPACK_EXTERNAL_MODULE_tinyglobby__ from "tinyglobby";
9
9
  import * as __WEBPACK_EXTERNAL_MODULE_node_module__ from "node:module";
10
10
  import * as __WEBPACK_EXTERNAL_MODULE_module__ from "module";
11
- /**
12
- * Node.js built-in modules.
13
- * Copied from https://github.com/webpack/webpack/blob/dd44b206a9c50f4b4cb4d134e1a0bd0387b159a3/lib/node/NodeTargetPlugin.js#L12-L72
14
- */ const nodeBuiltInModules = [
11
+ const nodeBuiltInModules = [
15
12
  'assert',
16
13
  'assert/strict',
17
14
  'async_hooks',
@@ -67,15 +64,10 @@ import * as __WEBPACK_EXTERNAL_MODULE_module__ from "module";
67
64
  'worker_threads',
68
65
  'zlib',
69
66
  /^node:/,
70
- // cspell:word pnpapi
71
- // Yarn PnP adds pnpapi as "builtin"
72
67
  'pnpapi'
73
68
  ];
74
69
  async function calcLongestCommonPath(absPaths) {
75
70
  if (0 === absPaths.length) return null;
76
- // we support two cases
77
- // 1. /packages-a/src/index.ts
78
- // 2. D:/packages-a/src/index.ts
79
71
  const sep = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep;
80
72
  const splitPaths = absPaths.map((p)=>p.split(sep));
81
73
  let lcaFragments = splitPaths[0];
@@ -130,7 +122,6 @@ function isPluginIncluded(pluginName, plugins) {
130
122
  }
131
123
  function checkMFPlugin(config, sharedPlugins) {
132
124
  if ('mf' !== config.format) return true;
133
- // https://github.com/module-federation/core/blob/4e5c4b96ee45899f3ba5904b8927768980d5ad0e/packages/rsbuild-plugin/src/cli/index.ts#L17
134
125
  const added = isPluginIncluded('rsbuild:module-federation-enhanced', [
135
126
  ...sharedPlugins || [],
136
127
  ...config.plugins || []
@@ -150,11 +141,12 @@ function debounce(func, wait) {
150
141
  }, wait);
151
142
  };
152
143
  }
153
- /**
154
- * Check if running in a TTY context
155
- */ const isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !process.env.CI;
144
+ const isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !process.env.CI;
156
145
  const isIntermediateOutputFormat = (format)=>'cjs' === format || 'esm' === format;
157
- // setup the logger level
146
+ const windowsSlashRegex = /\\/g;
147
+ function normalizeSlash(p) {
148
+ return p.replace(windowsSlashRegex, '/');
149
+ }
158
150
  if (process.env.DEBUG) __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.level = 'verbose';
159
151
  function initNodeEnv() {
160
152
  if (!process.env.NODE_ENV) {
@@ -166,12 +158,20 @@ function initNodeEnv() {
166
158
  }
167
159
  function prepareCli() {
168
160
  initNodeEnv();
169
- // Print a blank line to keep the greet log nice.
170
- // Some package managers automatically output a blank line, some do not.
171
161
  const { npm_execpath } = process.env;
172
162
  if (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) console.log();
173
- __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.greet(` Rslib v0.1.4\n`);
163
+ __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.greet(` Rslib v0.1.5\n`);
174
164
  }
165
+ const composeAssetConfig = (bundle, format)=>{
166
+ if ('esm' === format || 'cjs' === format) {
167
+ if (bundle) return {
168
+ output: {
169
+ dataUriLimit: 0
170
+ }
171
+ };
172
+ }
173
+ return {};
174
+ };
175
175
  const DEFAULT_CONFIG_NAME = 'rslib.config';
176
176
  const DEFAULT_CONFIG_EXTENSIONS = [
177
177
  '.js',
@@ -238,10 +238,7 @@ function isCssFile(filepath) {
238
238
  return CSS_EXTENSIONS_PATTERN.test(filepath);
239
239
  }
240
240
  const CSS_MODULE_REG = /\.module\.\w+$/i;
241
- /**
242
- * This function is modified based on
243
- * https://github.com/web-infra-dev/rspack/blob/7b80a45a1c58de7bc506dbb107fad6fda37d2a1f/packages/rspack/src/loader-runner/index.ts#L903
244
- */ const PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/;
241
+ const PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/;
245
242
  function parsePathQueryFragment(str) {
246
243
  const match = PATH_QUERY_FRAGMENT_REGEXP.exec(str);
247
244
  return {
@@ -256,7 +253,6 @@ function isCssModulesFile(filepath, auto) {
256
253
  if (auto instanceof RegExp) return auto.test(filepath);
257
254
  if ('function' == typeof auto) {
258
255
  const { path, query, fragment } = parsePathQueryFragment(filepath);
259
- // this is a mock for loader
260
256
  return auto(path, query, fragment);
261
257
  }
262
258
  return false;
@@ -269,16 +265,11 @@ function isCssGlobalFile(filepath, auto) {
269
265
  }
270
266
  function cssExternalHandler(request, callback, jsExtension, auto, isStyleRedirect) {
271
267
  const isCssModulesRequest = isCssModulesFile(request, auto);
272
- // cssExtract would execute the file handled by css-loader, so we cannot external the "helper import" from css-loader
273
- // do not external @rsbuild/core/compiled/css-loader/noSourceMaps.js, sourceMaps.js, api.mjs etc.
274
268
  if (/compiled\/css-loader\//.test(request)) return callback();
275
- // 1. css modules: import './CounterButton.module.scss' -> import './CounterButton.module.mjs'
276
- // 2. css global: import './CounterButton.scss' -> import './CounterButton.css'
277
269
  if ('.' === request[0] && isCssFile(request)) {
278
- // preserve import './CounterButton.module.scss'
279
- if (!isStyleRedirect) return callback(null, request);
280
- if (isCssModulesRequest) return callback(null, request.replace(/\.[^.]+$/, jsExtension));
281
- return callback(null, request.replace(/\.[^.]+$/, '.css'));
270
+ if (!isStyleRedirect) return callback(void 0, request);
271
+ if (isCssModulesRequest) return callback(void 0, request.replace(/\.[^.]+$/, jsExtension));
272
+ return callback(void 0, request.replace(/\.[^.]+$/, '.css'));
282
273
  }
283
274
  return false;
284
275
  }
@@ -322,14 +313,11 @@ const composeCssConfig = (rootDir, bundle = true)=>{
322
313
  ],
323
314
  tools: {
324
315
  cssLoader: {
325
- // Otherwise, external variables will be executed by css-extract and cause an error.
326
- // e.g: `@import url('./a.css');`
327
316
  import: false
328
317
  }
329
318
  }
330
319
  };
331
320
  };
332
- // The shim will be injected in PostEntryPlugin.
333
321
  const importMetaUrlShim = `const __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
334
322
  return typeof document === 'undefined'
335
323
  ? new (require('url'.replace('', '')).URL)('file:' + __filename).href
@@ -337,10 +325,6 @@ const importMetaUrlShim = `const __rslib_import_meta_url__ = /*#__PURE__*/ (func
337
325
  new URL('main.js', document.baseURI).href;
338
326
  })();
339
327
  `;
340
- // This Rsbuild plugin will shim `import.meta.url` for CommonJS modules.
341
- // - Replace `import.meta.url` with `importMetaUrl`.
342
- // - Inject `importMetaUrl` to the end of the module (can't inject at the beginning because of `"use strict";`).
343
- // This is a short-term solution, and we hope to provide built-in polyfills like `node.__filename` on Rspack side.
344
328
  const pluginCjsImportMetaUrlShim = ()=>({
345
329
  name: 'rsbuild:cjs-import-meta-url-shim',
346
330
  setup (api) {
@@ -363,7 +347,6 @@ const pluginEsmRequireShim = ()=>({
363
347
  config.plugins ??= [];
364
348
  config.plugins.push(new __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.rspack.BannerPlugin({
365
349
  banner: requireShim,
366
- // Just before minify stage, to perform tree shaking.
367
350
  stage: __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE - 1,
368
351
  raw: true,
369
352
  include: /\.(js|cjs)$/
@@ -406,12 +389,10 @@ class EntryChunkPlugin {
406
389
  const content = compiler.inputFileSystem.readFileSync(filename, {
407
390
  encoding: 'utf-8'
408
391
  });
409
- // Shebang
410
392
  if (content.startsWith(SHEBANG_PREFIX)) {
411
393
  const shebangMatch = matchFirstLine(content, SHEBANG_REGEX);
412
394
  if (shebangMatch) this.shebangEntries[name] = shebangMatch;
413
395
  }
414
- // React directive
415
396
  const reactDirective = matchFirstLine(content, REACT_DIRECTIVE_REGEX);
416
397
  if (reactDirective) this.reactDirectives[name] = reactDirective;
417
398
  }
@@ -442,7 +423,6 @@ class EntryChunkPlugin {
442
423
  });
443
424
  compilation.hooks.processAssets.tap({
444
425
  name: EntryChunkPlugin_PLUGIN_NAME,
445
- // Just after minify stage, to avoid from being minified.
446
426
  stage: __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.rspack.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING - 1
447
427
  }, (assets)=>{
448
428
  const chunkAsset = Object.keys(assets);
@@ -451,12 +431,10 @@ class EntryChunkPlugin {
451
431
  const reactDirectiveValue = this.reactDirectives[name];
452
432
  if (shebangValue || reactDirectiveValue) compilation.updateAsset(name, (old)=>{
453
433
  const replaceSource = new __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.rspack.sources.ReplaceSource(old);
454
- // Shebang
455
434
  if (shebangValue) {
456
435
  replaceSource.insert(0, `${shebangValue}\n`);
457
436
  this.shebangInjectedAssets.add(name);
458
437
  }
459
- // React directives
460
438
  if (reactDirectiveValue) replaceSource.insert(0, `${reactDirectiveValue}\n`);
461
439
  return replaceSource;
462
440
  });
@@ -545,13 +523,7 @@ const RSPACK_TARGET_UNLISTED_MODERN_ECMA_VERSIONS = [
545
523
  'es2024',
546
524
  'esnext'
547
525
  ];
548
- /**
549
- * The esX to browserslist mapping is transformed from esbuild:
550
- * https://github.com/evanw/esbuild/blob/main/internal/compat/js_table.go
551
- * It does not completely align with the browserslist query of Rsbuild now:
552
- * https://github.com/rspack-contrib/browserslist-to-es-version
553
- * TODO: align with Rsbuild, we may should align with SWC
554
- */ const ESX_TO_BROWSERSLIST = {
526
+ const ESX_TO_BROWSERSLIST = {
555
527
  es5: {
556
528
  chrome: '5.0.0',
557
529
  edge: '12.0.0',
@@ -656,10 +628,7 @@ function transformSyntaxToRspackTarget(syntax) {
656
628
  const normalizedSyntaxItem = syntaxItem.toLowerCase();
657
629
  if (normalizedSyntaxItem.startsWith('es')) {
658
630
  if (normalizedSyntaxItem in ESX_TO_BROWSERSLIST) {
659
- // The latest EcmaScript version supported by Rspack's `target` is es2022.
660
- // Higher versions are treated as es2022.
661
631
  if (RSPACK_TARGET_UNLISTED_MODERN_ECMA_VERSIONS.includes(normalizedSyntaxItem)) return 'es2022';
662
- // The es6 is the same as es2015, compatible with rspack API schema
663
632
  if ('es6' === normalizedSyntaxItem) return 'es2015';
664
633
  return normalizedSyntaxItem;
665
634
  }
@@ -695,7 +664,7 @@ function transformSyntaxToBrowserslist(syntax, target) {
695
664
  }
696
665
  const POSIX_SEP_RE = new RegExp('\\' + __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep, 'g');
697
666
  const NATIVE_SEP_RE = new RegExp('\\' + __WEBPACK_EXTERNAL_MODULE_node_path__["default"].sep, 'g');
698
- /** @type {Map<string,RegExp>}*/ const PATTERN_REGEX_CACHE = new Map();
667
+ const PATTERN_REGEX_CACHE = new Map();
699
668
  const GLOB_ALL_PATTERN = "**/*";
700
669
  const TS_EXTENSIONS = [
701
670
  '.ts',
@@ -713,10 +682,7 @@ const TSJS_EXTENSIONS = TS_EXTENSIONS.concat(util_JS_EXTENSIONS);
713
682
  const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext)=>ext.substring(1)).join('|')})`;
714
683
  const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext)=>ext.substring(1)).join('|')})`;
715
684
  const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep === __WEBPACK_EXTERNAL_MODULE_node_path__["default"].sep;
716
- /**
717
- * @template T
718
- * @returns {{resolve:(result:T)=>void, reject:(error:any)=>void, promise: Promise<T>}}
719
- */ function util_makePromise() {
685
+ function util_makePromise() {
720
686
  let resolve, reject;
721
687
  const promise = new Promise((res, rej)=>{
722
688
  resolve = res;
@@ -728,12 +694,8 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
728
694
  reject
729
695
  };
730
696
  }
731
- /**
732
- * @param {string} filename
733
- * @param {import('./cache.js').TSConfckCache} [cache]
734
- * @returns {Promise<string|void>}
735
- */ async function util_resolveTSConfigJson(filename, cache) {
736
- if ('.json' !== __WEBPACK_EXTERNAL_MODULE_node_path__["default"].extname(filename)) return; // ignore files that are not json
697
+ async function util_resolveTSConfigJson(filename, cache) {
698
+ if ('.json' !== __WEBPACK_EXTERNAL_MODULE_node_path__["default"].extname(filename)) return;
737
699
  const tsconfig = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(filename);
738
700
  if (cache && (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename))) return tsconfig;
739
701
  return __WEBPACK_EXTERNAL_MODULE_node_fs__.promises.stat(tsconfig).then((stat)=>{
@@ -741,57 +703,18 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
741
703
  throw new Error(`${filename} exists but is not a regular file.`);
742
704
  });
743
705
  }
744
- /**
745
- *
746
- * @param {string} dir an absolute directory path
747
- * @returns {boolean} if dir path includes a node_modules segment
748
- */ const util_isInNodeModules = IS_POSIX ? (dir)=>dir.includes('/node_modules/') : (dir)=>dir.match(/[/\\]node_modules[/\\]/);
749
- /**
750
- * convert posix separator to native separator
751
- *
752
- * eg.
753
- * windows: C:/foo/bar -> c:\foo\bar
754
- * linux: /foo/bar -> /foo/bar
755
- *
756
- * @param {string} filename with posix separators
757
- * @returns {string} filename with native separators
758
- */ const posix2native = IS_POSIX ? (filename)=>filename : (filename)=>filename.replace(POSIX_SEP_RE, __WEBPACK_EXTERNAL_MODULE_node_path__["default"].sep);
759
- /**
760
- * convert native separator to posix separator
761
- *
762
- * eg.
763
- * windows: C:\foo\bar -> c:/foo/bar
764
- * linux: /foo/bar -> /foo/bar
765
- *
766
- * @param {string} filename - filename with native separators
767
- * @returns {string} filename with posix separators
768
- */ const util_native2posix = IS_POSIX ? (filename)=>filename : (filename)=>filename.replace(NATIVE_SEP_RE, __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep);
769
- /**
770
- * converts params to native separator, resolves path and converts native back to posix
771
- *
772
- * needed on windows to handle posix paths in tsconfig
773
- *
774
- * @param dir {string|null} directory to resolve from
775
- * @param filename {string} filename or pattern to resolve
776
- * @returns string
777
- */ const resolve2posix = IS_POSIX ? (dir, filename)=>dir ? __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(dir, filename) : __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(filename) : (dir, filename)=>util_native2posix(dir ? __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(posix2native(dir), posix2native(filename)) : __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(posix2native(filename)));
778
- /**
779
- *
780
- * @param {import('./public.d.ts').TSConfckParseResult} result
781
- * @param {import('./public.d.ts').TSConfckParseOptions} [options]
782
- * @returns {string[]}
783
- */ function util_resolveReferencedTSConfigFiles(result, options) {
706
+ const util_isInNodeModules = IS_POSIX ? (dir)=>dir.includes('/node_modules/') : (dir)=>dir.match(/[/\\]node_modules[/\\]/);
707
+ const posix2native = IS_POSIX ? (filename)=>filename : (filename)=>filename.replace(POSIX_SEP_RE, __WEBPACK_EXTERNAL_MODULE_node_path__["default"].sep);
708
+ const util_native2posix = IS_POSIX ? (filename)=>filename : (filename)=>filename.replace(NATIVE_SEP_RE, __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep);
709
+ const resolve2posix = IS_POSIX ? (dir, filename)=>dir ? __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(dir, filename) : __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(filename) : (dir, filename)=>util_native2posix(dir ? __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(posix2native(dir), posix2native(filename)) : __WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(posix2native(filename)));
710
+ function util_resolveReferencedTSConfigFiles(result, options) {
784
711
  const dir = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].dirname(result.tsconfigFile);
785
712
  return result.tsconfig.references.map((ref)=>{
786
713
  const refPath = ref.path.endsWith('.json') ? ref.path : __WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(ref.path, options?.configName ?? 'tsconfig.json');
787
714
  return resolve2posix(dir, refPath);
788
715
  });
789
716
  }
790
- /**
791
- * @param {string} filename
792
- * @param {import('./public.d.ts').TSConfckParseResult} result
793
- * @returns {import('./public.d.ts').TSConfckParseResult}
794
- */ function util_resolveSolutionTSConfig(filename, result) {
717
+ function util_resolveSolutionTSConfig(filename, result) {
795
718
  const allowJs = result.tsconfig.compilerOptions?.allowJs;
796
719
  const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
797
720
  if (result.referenced && extensions.some((ext)=>filename.endsWith(ext)) && !util_isIncluded(filename, result)) {
@@ -800,12 +723,7 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
800
723
  }
801
724
  return result;
802
725
  }
803
- /**
804
- *
805
- * @param {string} filename
806
- * @param {import('./public.d.ts').TSConfckParseResult} result
807
- * @returns {boolean}
808
- */ function util_isIncluded(filename, result) {
726
+ function util_isIncluded(filename, result) {
809
727
  const dir = util_native2posix(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].dirname(result.tsconfigFile));
810
728
  const files = (result.tsconfig.files || []).map((file)=>resolve2posix(dir, file));
811
729
  const absoluteFilename = resolve2posix(null, filename);
@@ -820,18 +738,9 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
820
738
  }
821
739
  return false;
822
740
  }
823
- /**
824
- * test filenames agains glob patterns in tsconfig
825
- *
826
- * @param filename {string} posix style abolute path to filename to test
827
- * @param dir {string} posix style absolute path to directory of tsconfig containing patterns
828
- * @param patterns {string[]} glob patterns to match against
829
- * @param allowJs {boolean} allowJs setting in tsconfig to include js extensions in checks
830
- * @returns {boolean} true when at least one pattern matches filename
831
- */ function isGlobMatch(filename, dir, patterns, allowJs) {
741
+ function isGlobMatch(filename, dir, patterns, allowJs) {
832
742
  const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
833
743
  return patterns.some((pattern)=>{
834
- // filename must end with part of pattern that comes after last wildcard
835
744
  let lastWildcardIndex = pattern.length;
836
745
  let hasWildcard = false;
837
746
  let hasExtension = false;
@@ -855,19 +764,14 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
855
764
  if (hasWildcard && hasSlash) break;
856
765
  }
857
766
  if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
858
- // add implicit glob
859
767
  pattern += `${pattern.endsWith('/') ? '' : '/'}${GLOB_ALL_PATTERN}`;
860
768
  lastWildcardIndex = pattern.length - 1;
861
769
  hasWildcard = true;
862
770
  }
863
- // if pattern does not end with wildcard, filename must end with pattern after last wildcard
864
771
  if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
865
- // if pattern ends with *, filename must end with a default extension
866
772
  if (pattern.endsWith('*') && !extensions.some((ext)=>filename.endsWith(ext))) return false;
867
- // for **/* , filename must start with the dir
868
773
  if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
869
774
  const resolvedPattern = resolve2posix(dir, pattern);
870
- // filename must start with part of pattern that comes before first wildcard
871
775
  let firstWildcardIndex = -1;
872
776
  for(let i = 0; i < resolvedPattern.length; i++)if ('*' === resolvedPattern[i] || '?' === resolvedPattern[i]) {
873
777
  firstWildcardIndex = i;
@@ -875,22 +779,15 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
875
779
  break;
876
780
  }
877
781
  if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
878
- if (!hasWildcard) // no wildcard in pattern, filename must be equal to resolved pattern
879
- return filename === resolvedPattern;
880
- if (firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN) // singular glob-all pattern and we already validated prefix and suffix matches
881
- return true;
882
- // complex pattern, use regex to check it
782
+ if (!hasWildcard) return filename === resolvedPattern;
783
+ if (firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN) return true;
883
784
  if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
884
785
  const regex = pattern2regex(resolvedPattern, allowJs);
885
786
  PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
886
787
  return regex.test(filename);
887
788
  });
888
789
  }
889
- /**
890
- * @param {string} resolvedPattern
891
- * @param {boolean} allowJs
892
- * @returns {RegExp}
893
- */ function pattern2regex(resolvedPattern, allowJs) {
790
+ function pattern2regex(resolvedPattern, allowJs) {
894
791
  let regexStr = '^';
895
792
  for(let i = 0; i < resolvedPattern.length; i++){
896
793
  const char = resolvedPattern[i];
@@ -901,7 +798,7 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
901
798
  if ('*' === char) {
902
799
  if ('*' === resolvedPattern[i + 1] && '/' === resolvedPattern[i + 2]) {
903
800
  i += 2;
904
- regexStr += '(?:[^\\/]*\\/)*'; // zero or more path segments
801
+ regexStr += '(?:[^\\/]*\\/)*';
905
802
  continue;
906
803
  }
907
804
  regexStr += '[^\\/]*';
@@ -910,27 +807,14 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
910
807
  if ('/.+^${}()|[]\\'.includes(char)) regexStr += "\\";
911
808
  regexStr += char;
912
809
  }
913
- // add known file endings if pattern ends on *
914
810
  if (resolvedPattern.endsWith('*')) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
915
811
  regexStr += '$';
916
812
  return new RegExp(regexStr);
917
813
  }
918
- /**
919
- * replace tokens like ${configDir}
920
- * @param {any} tsconfig
921
- * @param {string} configDir
922
- * @returns {any}
923
- */ function util_replaceTokens(tsconfig, configDir) {
924
- return JSON.parse(JSON.stringify(tsconfig)// replace ${configDir}
925
- .replaceAll(/"\${configDir}/g, `"${util_native2posix(configDir)}`));
926
- }
927
- /**
928
- * find the closest tsconfig.json file
929
- *
930
- * @param {string} filename - path to file to find tsconfig for (absolute or relative to cwd)
931
- * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
932
- * @returns {Promise<string|null>} absolute path to closest tsconfig.json or null if not found
933
- */ async function find(filename, options) {
814
+ function util_replaceTokens(tsconfig, configDir) {
815
+ return JSON.parse(JSON.stringify(tsconfig).replaceAll(/"\${configDir}/g, `"${util_native2posix(configDir)}`));
816
+ }
817
+ async function find(filename, options) {
934
818
  let dir = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].dirname(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].resolve(filename));
935
819
  if (options?.ignoreNodeModules && util_isInNodeModules(dir)) return null;
936
820
  const cache = options?.cache;
@@ -945,12 +829,7 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
945
829
  }, options);
946
830
  return promise;
947
831
  }
948
- /**
949
- *
950
- * @param {string} dir
951
- * @param {{promise:Promise<string|null>,resolve:(result:string|null)=>void,reject:(err:any)=>void}} madePromise
952
- * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
953
- */ function findUp(dir, { resolve, reject, promise }, options) {
832
+ function findUp(dir, { resolve, reject, promise }, options) {
954
833
  const { cache, root, configName } = options ?? {};
955
834
  if (cache) {
956
835
  if (cache.hasConfigPath(dir, configName)) {
@@ -980,38 +859,13 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
980
859
  }
981
860
  });
982
861
  }
983
- /**
984
- * @typedef WalkState
985
- * @interface
986
- * @property {string[]} files - files
987
- * @property {number} calls - number of ongoing calls
988
- * @property {(dir: string)=>boolean} skip - function to skip dirs
989
- * @property {boolean} err - error flag
990
- * @property {string[]} configNames - config file names
991
- */ __WEBPACK_EXTERNAL_MODULE_node_path__["default"].sep;
992
- /*
993
- this file contains code from strip-bom and strip-json-comments by Sindre Sorhus
994
- https://github.com/sindresorhus/strip-json-comments/blob/v4.0.0/index.js
995
- https://github.com/sindresorhus/strip-bom/blob/v5.0.0/index.js
996
- licensed under MIT, see ../LICENSE
997
- */ /**
998
- * convert content of tsconfig.json to regular json
999
- *
1000
- * @param {string} tsconfigJson - content of tsconfig.json
1001
- * @returns {string} content as regular json, comments and dangling commas have been replaced with whitespace
1002
- */ function toJson(tsconfigJson) {
862
+ __WEBPACK_EXTERNAL_MODULE_node_path__["default"].sep;
863
+ function toJson(tsconfigJson) {
1003
864
  const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
1004
- if ('' === stripped.trim()) // only whitespace left after stripping, return empty object so that JSON.parse still works
1005
- return '{}';
865
+ if ('' === stripped.trim()) return '{}';
1006
866
  return stripped;
1007
867
  }
1008
- /**
1009
- * replace dangling commas from pseudo-json string with single space
1010
- * implementation heavily inspired by strip-json-comments
1011
- *
1012
- * @param {string} pseudoJson
1013
- * @returns {string}
1014
- */ function stripDanglingComma(pseudoJson) {
868
+ function stripDanglingComma(pseudoJson) {
1015
869
  let insideString = false;
1016
870
  let offset = 0;
1017
871
  let result = '';
@@ -1040,13 +894,7 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
1040
894
  }
1041
895
  return result + pseudoJson.substring(offset);
1042
896
  }
1043
- // start strip-json-comments
1044
- /**
1045
- *
1046
- * @param {string} jsonString
1047
- * @param {number} quotePosition
1048
- * @returns {boolean}
1049
- */ function isEscaped(jsonString, quotePosition) {
897
+ function isEscaped(jsonString, quotePosition) {
1050
898
  let index = quotePosition - 1;
1051
899
  let backslashCount = 0;
1052
900
  while('\\' === jsonString[index]){
@@ -1055,22 +903,14 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
1055
903
  }
1056
904
  return Boolean(backslashCount % 2);
1057
905
  }
1058
- /**
1059
- *
1060
- * @param {string} string
1061
- * @param {number?} start
1062
- * @param {number?} end
1063
- */ function strip(string, start, end) {
906
+ function strip(string, start, end) {
1064
907
  return string.slice(start, end).replace(/\S/g, ' ');
1065
908
  }
1066
909
  const singleComment = Symbol('singleComment');
1067
910
  const multiComment = Symbol('multiComment');
1068
- /**
1069
- * @param {string} jsonString
1070
- * @returns {string}
1071
- */ function stripJsonComments(jsonString) {
911
+ function stripJsonComments(jsonString) {
1072
912
  let isInsideString = false;
1073
- /** @type {false | symbol} */ let isInsideComment = false;
913
+ let isInsideComment = false;
1074
914
  let offset = 0;
1075
915
  let result = '';
1076
916
  for(let index = 0; index < jsonString.length; index++){
@@ -1112,14 +952,7 @@ const multiComment = Symbol('multiComment');
1112
952
  }
1113
953
  return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
1114
954
  }
1115
- // end strip-json-comments
1116
- // start strip-bom
1117
- /**
1118
- * @param {string} string
1119
- * @returns {string}
1120
- */ function stripBom(string) {
1121
- // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
1122
- // conversion translates it to FEFF (UTF-16 BOM).
955
+ function stripBom(string) {
1123
956
  if (0xfeff === string.charCodeAt(0)) return string.slice(1);
1124
957
  return string;
1125
958
  }
@@ -1127,17 +960,10 @@ const not_found_result = {
1127
960
  tsconfigFile: null,
1128
961
  tsconfig: {}
1129
962
  };
1130
- /**
1131
- * parse the closest tsconfig.json file
1132
- *
1133
- * @param {string} filename - path to a tsconfig .json or a source file or directory (absolute or relative to cwd)
1134
- * @param {import('./public.d.ts').TSConfckParseOptions} [options] - options
1135
- * @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
1136
- * @throws {TSConfckParseError}
1137
- */ async function parse(filename, options) {
1138
- /** @type {import('./cache.js').TSConfckCache} */ const cache = options?.cache;
963
+ async function parse(filename, options) {
964
+ const cache = options?.cache;
1139
965
  if (cache?.hasParseResult(filename)) return getParsedDeep(filename, cache, options);
1140
- const { resolve, reject, /** @type {Promise<import('./public.d.ts').TSConfckParseResult>}*/ promise } = util_makePromise();
966
+ const { resolve, reject, promise } = util_makePromise();
1141
967
  cache?.setParseResult(filename, promise, true);
1142
968
  try {
1143
969
  let tsconfigFile = await util_resolveTSConfigJson(filename, cache) || await find(filename, options);
@@ -1161,13 +987,7 @@ const not_found_result = {
1161
987
  }
1162
988
  return promise;
1163
989
  }
1164
- /**
1165
- * ensure extends and references are parsed
1166
- *
1167
- * @param {string} filename - cached file
1168
- * @param {import('./cache.js').TSConfckCache} cache - cache
1169
- * @param {import('./public.d.ts').TSConfckParseOptions} options - options
1170
- */ async function getParsedDeep(filename, cache, options) {
990
+ async function getParsedDeep(filename, cache, options) {
1171
991
  const result = await cache.getParseResult(filename);
1172
992
  if (result.tsconfig.extends && !result.extended || result.tsconfig.references && !result.referenced) {
1173
993
  const promise = Promise.all([
@@ -1179,13 +999,7 @@ const not_found_result = {
1179
999
  }
1180
1000
  return result;
1181
1001
  }
1182
- /**
1183
- *
1184
- * @param {string} tsconfigFile - path to tsconfig file
1185
- * @param {import('./cache.js').TSConfckCache} [cache] - cache
1186
- * @param {boolean} [skipCache] - skip cache
1187
- * @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
1188
- */ async function parseFile(tsconfigFile, cache, skipCache) {
1002
+ async function parseFile(tsconfigFile, cache, skipCache) {
1189
1003
  if (!skipCache && cache?.hasParseResult(tsconfigFile) && !cache.getParseResult(tsconfigFile)._isRootFile_) return cache.getParseResult(tsconfigFile);
1190
1004
  const promise = __WEBPACK_EXTERNAL_MODULE_node_fs__.promises.readFile(tsconfigFile, 'utf-8').then(toJson).then((json)=>{
1191
1005
  const parsed = JSON.parse(json);
@@ -1200,23 +1014,12 @@ const not_found_result = {
1200
1014
  if (!skipCache && (!cache?.hasParseResult(tsconfigFile) || !cache.getParseResult(tsconfigFile)._isRootFile_)) cache?.setParseResult(tsconfigFile, promise);
1201
1015
  return promise;
1202
1016
  }
1203
- /**
1204
- * normalize to match the output of ts.parseJsonConfigFileContent
1205
- *
1206
- * @param {any} tsconfig - typescript tsconfig output
1207
- * @param {string} dir - directory
1208
- */ function normalizeTSConfig(tsconfig, dir) {
1209
- // set baseUrl to absolute path
1017
+ function normalizeTSConfig(tsconfig, dir) {
1210
1018
  const baseUrl = tsconfig.compilerOptions?.baseUrl;
1211
1019
  if (baseUrl && !baseUrl.startsWith('${') && !__WEBPACK_EXTERNAL_MODULE_node_path__["default"].isAbsolute(baseUrl)) tsconfig.compilerOptions.baseUrl = resolve2posix(dir, baseUrl);
1212
1020
  return tsconfig;
1213
1021
  }
1214
- /**
1215
- *
1216
- * @param {import('./public.d.ts').TSConfckParseResult} result
1217
- * @param {import('./public.d.ts').TSConfckParseOptions} [options]
1218
- * @returns {Promise<void>}
1219
- */ async function parseReferences(result, options) {
1022
+ async function parseReferences(result, options) {
1220
1023
  if (!result.tsconfig.references) return;
1221
1024
  const referencedFiles = util_resolveReferencedTSConfigFiles(result, options);
1222
1025
  const referenced = await Promise.all(referencedFiles.map((file)=>parseFile(file, options?.cache)));
@@ -1226,32 +1029,23 @@ const not_found_result = {
1226
1029
  });
1227
1030
  result.referenced = referenced;
1228
1031
  }
1229
- /**
1230
- * @param {import('./public.d.ts').TSConfckParseResult} result
1231
- * @param {import('./cache.js').TSConfckCache}[cache]
1232
- * @returns {Promise<void>}
1233
- */ async function parseExtends(result, cache) {
1032
+ async function parseExtends(result, cache) {
1234
1033
  if (!result.tsconfig.extends) return;
1235
- // use result as first element in extended
1236
- // but dereference tsconfig so that mergeExtended can modify the original without affecting extended[0]
1237
- /** @type {import('./public.d.ts').TSConfckParseResult[]} */ const extended = [
1034
+ const extended = [
1238
1035
  {
1239
1036
  tsconfigFile: result.tsconfigFile,
1240
1037
  tsconfig: JSON.parse(JSON.stringify(result.tsconfig))
1241
1038
  }
1242
1039
  ];
1243
- // flatten extends graph into extended
1244
1040
  let pos = 0;
1245
- /** @type {string[]} */ const extendsPath = [];
1041
+ const extendsPath = [];
1246
1042
  let currentBranchDepth = 0;
1247
1043
  while(pos < extended.length){
1248
1044
  const extending = extended[pos];
1249
1045
  extendsPath.push(extending.tsconfigFile);
1250
1046
  if (extending.tsconfig.extends) {
1251
- // keep following this branch
1252
1047
  currentBranchDepth += 1;
1253
- /** @type {string[]} */ let resolvedExtends;
1254
- // reverse because typescript 5.0 treats ['a','b','c'] as c extends b extends a
1048
+ let resolvedExtends;
1255
1049
  resolvedExtends = Array.isArray(extending.tsconfig.extends) ? extending.tsconfig.extends.reverse().map((ex)=>resolveExtends(ex, extending.tsconfigFile)) : [
1256
1050
  resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)
1257
1051
  ];
@@ -1262,27 +1056,18 @@ const not_found_result = {
1262
1056
  ]).join(' -> ');
1263
1057
  throw new TSConfckParseError(`Circular dependency in "extends": ${circle}`, 'EXTENDS_CIRCULAR', result.tsconfigFile);
1264
1058
  }
1265
- // add new extends to the list directly after current
1266
1059
  extended.splice(pos + 1, 0, ...await Promise.all(resolvedExtends.map((file)=>parseFile(file, cache))));
1267
1060
  } else {
1268
- // reached a leaf, backtrack to the last branching point and continue
1269
1061
  extendsPath.splice(-currentBranchDepth);
1270
1062
  currentBranchDepth = 0;
1271
1063
  }
1272
1064
  pos += 1;
1273
1065
  }
1274
1066
  result.extended = extended;
1275
- // skip first as it is the original config
1276
1067
  for (const ext of result.extended.slice(1))extendTSConfig(result, ext);
1277
1068
  }
1278
- /**
1279
- *
1280
- * @param {string} extended
1281
- * @param {string} from
1282
- * @returns {string}
1283
- */ function resolveExtends(extended, from) {
1284
- if ('..' === extended) // see #149
1285
- extended = '../tsconfig.json';
1069
+ function resolveExtends(extended, from) {
1070
+ if ('..' === extended) extended = '../tsconfig.json';
1286
1071
  const req = (0, __WEBPACK_EXTERNAL_MODULE_module__.createRequire)(from);
1287
1072
  let error;
1288
1073
  try {
@@ -1297,7 +1082,6 @@ const not_found_result = {
1297
1082
  }
1298
1083
  throw new TSConfckParseError(`failed to resolve "extends":"${extended}" in ${from}`, 'EXTENDS_RESOLVE', from, error);
1299
1084
  }
1300
- // references, extends and custom keys are not carried over
1301
1085
  const EXTENDABLE_KEYS = [
1302
1086
  'compilerOptions',
1303
1087
  'files',
@@ -1308,12 +1092,7 @@ const EXTENDABLE_KEYS = [
1308
1092
  'typeAcquisition',
1309
1093
  'buildOptions'
1310
1094
  ];
1311
- /**
1312
- *
1313
- * @param {import('./public.d.ts').TSConfckParseResult} extending
1314
- * @param {import('./public.d.ts').TSConfckParseResult} extended
1315
- * @returns void
1316
- */ function extendTSConfig(extending, extended) {
1095
+ function extendTSConfig(extending, extended) {
1317
1096
  const extendingConfig = extending.tsconfig;
1318
1097
  const extendedConfig = extended.tsconfig;
1319
1098
  const relativePath = util_native2posix(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].relative(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].dirname(extending.tsconfigFile), __WEBPACK_EXTERNAL_MODULE_node_path__["default"].dirname(extended.tsconfigFile)));
@@ -1330,11 +1109,9 @@ const EXTENDABLE_KEYS = [
1330
1109
  }
1331
1110
  }
1332
1111
  const REBASE_KEYS = [
1333
- // root
1334
1112
  'files',
1335
1113
  'include',
1336
1114
  'exclude',
1337
- // compilerOptions
1338
1115
  'baseUrl',
1339
1116
  'rootDir',
1340
1117
  'rootDirs',
@@ -1342,53 +1119,24 @@ const REBASE_KEYS = [
1342
1119
  'outDir',
1343
1120
  'outFile',
1344
1121
  'declarationDir',
1345
- // watchOptions
1346
1122
  'excludeDirectories',
1347
1123
  'excludeFiles'
1348
1124
  ];
1349
- /** @typedef {string | string[]} PathValue */ /**
1350
- *
1351
- * @param {string} key
1352
- * @param {PathValue} value
1353
- * @param {string} prependPath
1354
- * @returns {PathValue}
1355
- */ function rebaseRelative(key, value, prependPath) {
1125
+ function rebaseRelative(key, value, prependPath) {
1356
1126
  if (!REBASE_KEYS.includes(key)) return value;
1357
1127
  if (Array.isArray(value)) return value.map((x)=>rebasePath(x, prependPath));
1358
1128
  return rebasePath(value, prependPath);
1359
1129
  }
1360
- /**
1361
- *
1362
- * @param {string} value
1363
- * @param {string} prependPath
1364
- * @returns {string}
1365
- */ function rebasePath(value, prependPath) {
1130
+ function rebasePath(value, prependPath) {
1366
1131
  if (__WEBPACK_EXTERNAL_MODULE_node_path__["default"].isAbsolute(value) || value.startsWith('${configDir}')) return value;
1367
- // relative paths use posix syntax in tsconfig
1368
1132
  return __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.normalize(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.join(prependPath, value));
1369
1133
  }
1370
1134
  class TSConfckParseError extends Error {
1371
- /**
1372
- * error code
1373
- * @type {string}
1374
- */ code;
1375
- /**
1376
- * error cause
1377
- * @type { Error | undefined}
1378
- */ cause;
1379
- /**
1380
- * absolute path of tsconfig file where the error happened
1381
- * @type {string}
1382
- */ tsconfigFile;
1383
- /**
1384
- *
1385
- * @param {string} message - error message
1386
- * @param {string} code - error code
1387
- * @param {string} tsconfigFile - path to tsconfig file
1388
- * @param {Error?} cause - cause of this error
1389
- */ constructor(message, code, tsconfigFile, cause){
1135
+ code;
1136
+ cause;
1137
+ tsconfigFile;
1138
+ constructor(message, code, tsconfigFile, cause){
1390
1139
  super(message);
1391
- // Set the prototype explicitly.
1392
1140
  Object.setPrototypeOf(this, TSConfckParseError.prototype);
1393
1141
  this.name = TSConfckParseError.name;
1394
1142
  this.code = code;
@@ -1396,11 +1144,7 @@ class TSConfckParseError extends Error {
1396
1144
  this.tsconfigFile = tsconfigFile;
1397
1145
  }
1398
1146
  }
1399
- /**
1400
- *
1401
- * @param {any} tsconfig
1402
- * @param {string} tsconfigFile
1403
- */ function applyDefaults(tsconfig, tsconfigFile) {
1147
+ function applyDefaults(tsconfig, tsconfigFile) {
1404
1148
  if (isJSConfig(tsconfigFile)) tsconfig.compilerOptions = {
1405
1149
  ...DEFAULT_JSCONFIG_COMPILER_OPTIONS,
1406
1150
  ...tsconfig.compilerOptions
@@ -1413,9 +1157,7 @@ const DEFAULT_JSCONFIG_COMPILER_OPTIONS = {
1413
1157
  skipLibCheck: true,
1414
1158
  noEmit: true
1415
1159
  };
1416
- /**
1417
- * @param {string} configFileName
1418
- */ function isJSConfig(configFileName) {
1160
+ function isJSConfig(configFileName) {
1419
1161
  return 'jsconfig.json' === __WEBPACK_EXTERNAL_MODULE_node_path__["default"].basename(configFileName);
1420
1162
  }
1421
1163
  async function loadTsconfig(root, tsconfigPath = 'tsconfig.json') {
@@ -1459,9 +1201,7 @@ const composeExternalsWarnConfig = (format, ...externalsArray)=>{
1459
1201
  if ('esm' !== format) return {};
1460
1202
  const externals = [];
1461
1203
  for (const e of externalsArray.filter(Boolean))if (Array.isArray(e)) externals.push(...e);
1462
- else // @ts-ignore
1463
- externals.push(e);
1464
- // Match logic is derived from https://github.com/webpack/webpack/blob/94aba382eccf3de1004d235045d4462918dfdbb7/lib/ExternalModuleFactoryPlugin.js#L166-L293.
1204
+ else externals.push(e);
1465
1205
  const matchUserExternals = (externals, request, callback)=>{
1466
1206
  if ('string' == typeof externals) {
1467
1207
  if (externals === request) {
@@ -1532,9 +1272,6 @@ const composeAutoExternalConfig = (options)=>{
1532
1272
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.warn('autoExternal configuration will not be applied due to read package.json failed');
1533
1273
  return {};
1534
1274
  }
1535
- // User externals configuration has higher priority than autoExternal
1536
- // eg: autoExternal: ['react'], user: output: { externals: { react: 'react-1' } }
1537
- // Only handle the case where the externals type is object, string / string[] does not need to be processed, other types are too complex.
1538
1275
  const userExternalKeys = userExternals && isObject(userExternals) ? Object.keys(userExternals) : [];
1539
1276
  const externalOptions = {
1540
1277
  dependencies: true,
@@ -1556,7 +1293,6 @@ const composeAutoExternalConfig = (options)=>{
1556
1293
  return externals.length ? {
1557
1294
  output: {
1558
1295
  externals: [
1559
- // Exclude dependencies, e.g. `react`, `react/jsx-runtime`
1560
1296
  ...uniqueExternals.map((dep)=>new RegExp(`^${dep}($|\\/|\\\\)`)),
1561
1297
  ...uniqueExternals
1562
1298
  ]
@@ -1566,10 +1302,7 @@ const composeAutoExternalConfig = (options)=>{
1566
1302
  function composeMinifyConfig(config) {
1567
1303
  const minify = config.output?.minify;
1568
1304
  const format = config.format;
1569
- if (void 0 !== minify) // User's minify configuration will be merged afterwards.
1570
- return {};
1571
- // When minify is not specified, Rslib will use a sane default for minify options.
1572
- // The default options will only perform dead code elimination and unused code elimination.
1305
+ if (void 0 !== minify) return {};
1573
1306
  return {
1574
1307
  output: {
1575
1308
  minify: {
@@ -1578,13 +1311,11 @@ function composeMinifyConfig(config) {
1578
1311
  jsOptions: {
1579
1312
  minimizerOptions: {
1580
1313
  mangle: false,
1581
- // MF assets are loaded over the network, which means they will not be compressed by the project. Therefore, minifying them is necessary.
1582
1314
  minify: 'mf' === format,
1583
1315
  compress: {
1584
1316
  defaults: false,
1585
1317
  unused: true,
1586
1318
  dead_code: true,
1587
- // remoteEntry's global variable will be tree-shaken if `toplevel` is enabled in "mf" format
1588
1319
  toplevel: 'mf' !== format
1589
1320
  },
1590
1321
  format: {
@@ -1672,7 +1403,6 @@ async function createConstantRsbuildConfig() {
1672
1403
  rspack: {
1673
1404
  optimization: {
1674
1405
  splitChunks: {
1675
- // Splitted "sync" chunks will make entry modules can't be inlined.
1676
1406
  chunks: 'async'
1677
1407
  },
1678
1408
  moduleIds: 'named',
@@ -1685,8 +1415,6 @@ async function createConstantRsbuildConfig() {
1685
1415
  }
1686
1416
  }
1687
1417
  },
1688
- // TypeScript-specific behavior: if the extension is ".js" or ".jsx", try replacing it with ".ts" or ".tsx"
1689
- // see https://github.com/web-infra-dev/rslib/issues/41
1690
1418
  resolve: {
1691
1419
  extensionAlias: {
1692
1420
  '.js': [
@@ -1830,8 +1558,6 @@ const composeFormatConfig = ({ format, bundle = true, umdName, pkgJson })=>{
1830
1558
  output: {
1831
1559
  uniqueName: pkgJson.name
1832
1560
  },
1833
- // can not set nodeEnv to false, because mf format should build shared module.
1834
- // If nodeEnv is false, the process.env.NODE_ENV in third-party packages's will not be replaced
1835
1561
  optimization: {
1836
1562
  nodeEnv: 'production',
1837
1563
  moduleIds: 'deterministic'
@@ -1850,8 +1576,6 @@ const formatRsbuildPlugin = ()=>({
1850
1576
  name: 'rsbuild:format',
1851
1577
  setup (api) {
1852
1578
  api.modifyBundlerChain((config, { CHAIN_ID })=>{
1853
- // Fix for https://github.com/web-infra-dev/rslib/issues/499.
1854
- // Prevent parsing and try bundling `new URL()` in ESM format.
1855
1579
  config.module.rule(CHAIN_ID.RULE.JS).parser({
1856
1580
  url: false
1857
1581
  });
@@ -1886,7 +1610,6 @@ const composeShimsConfig = (format, shims)=>{
1886
1610
  tools: {
1887
1611
  rspack: {
1888
1612
  node: {
1889
- // "__dirname" and "__filename" shims will automatically be enabled when `output.module` is `true`
1890
1613
  __dirname: !!resolvedShims.esm.__dirname && 'node-module',
1891
1614
  __filename: !!resolvedShims.esm.__filename && 'node-module'
1892
1615
  }
@@ -1918,16 +1641,10 @@ const composeShimsConfig = (format, shims)=>{
1918
1641
  };
1919
1642
  const composeModuleImportWarn = (request)=>`The externalized commonjs request ${__WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__["default"].green(`"${request}"`)} will use ${__WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__["default"].blue('"module"')} external type in ESM format. If you want to specify other external type, considering set the request and type with ${__WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__["default"].blue('"output.externals"')}.`;
1920
1643
  const composeExternalsConfig = (format, externals)=>{
1921
- // TODO: Define the internal externals config in Rsbuild's externals instead
1922
- // Rspack's externals as they will not be merged from different fields. All externals
1923
- // should to be unified and merged together in the future.
1924
1644
  const externalsTypeMap = {
1925
1645
  esm: 'module-import',
1926
1646
  cjs: 'commonjs-import',
1927
1647
  umd: 'umd',
1928
- // If use 'var', when projects import an external package like '@pkg', this will cause a syntax error such as 'var pkg = @pkg'.
1929
- // If use 'umd', the judgement conditions may be affected by other packages that define variables like 'define'.
1930
- // Therefore, we use 'global' to satisfy both web and node environments.
1931
1648
  mf: 'global'
1932
1649
  };
1933
1650
  switch(format){
@@ -1971,7 +1688,6 @@ const composeAutoExtensionConfig = (config, autoExtension, pkgJson)=>{
1971
1688
  };
1972
1689
  };
1973
1690
  const composeSyntaxConfig = (target, syntax)=>{
1974
- // Defaults to ESNext, Rslib will assume all of the latest JavaScript and CSS features are supported.
1975
1691
  if (syntax) return {
1976
1692
  tools: {
1977
1693
  rspack: (config)=>{
@@ -1992,7 +1708,6 @@ const composeSyntaxConfig = (target, syntax)=>{
1992
1708
  }
1993
1709
  },
1994
1710
  output: {
1995
- // If `syntax` is not defined, Rslib will try to determine by the `target`, with the last version of the target.
1996
1711
  overrideBrowserslist: ESX_TO_BROWSERSLIST.esnext(target)
1997
1712
  }
1998
1713
  };
@@ -2022,36 +1737,24 @@ const composeEntryConfig = async (entries, bundle, root, cssModulesAuto)=>{
2022
1737
  },
2023
1738
  lcp: null
2024
1739
  };
2025
- // In bundleless mode, resolve glob patterns and convert them to entry object.
2026
1740
  const resolvedEntries = {};
2027
1741
  for (const key of Object.keys(entries)){
2028
1742
  const entry = entries[key];
2029
- // Entries in bundleless mode could be:
2030
- // 1. A string of glob pattern: { entry: { index: 'src/*.ts' } }
2031
- // 2. An array of glob patterns: { entry: { index: ['src/*.ts', 'src/*.tsx'] } }
2032
- // Not supported for now: entry description object
2033
1743
  const entryFiles = Array.isArray(entry) ? entry : 'string' == typeof entry ? [
2034
1744
  entry
2035
1745
  ] : null;
2036
1746
  if (!entryFiles) throw new Error('Entry can only be a string or an array of strings for now');
2037
- // Turn entries in array into each separate entry.
2038
1747
  const globEntryFiles = await (0, __WEBPACK_EXTERNAL_MODULE_tinyglobby__.glob)(entryFiles, {
2039
1748
  cwd: root,
2040
1749
  absolute: true
2041
1750
  });
2042
- // Filter the glob resolved entry files based on the allowed extensions
2043
1751
  const resolvedEntryFiles = globEntryFiles.filter((file)=>ENTRY_EXTENSIONS_PATTERN.test(file));
2044
1752
  if (0 === resolvedEntryFiles.length) throw new Error(`Cannot find ${resolvedEntryFiles}`);
2045
- // Similar to `rootDir` in tsconfig and `outbase` in esbuild.
2046
1753
  const lcp = await calcLongestCommonPath(resolvedEntryFiles);
2047
- // Using the longest common path of all non-declaration input files by default.
2048
1754
  const outBase = null === lcp ? root : lcp;
2049
1755
  function getEntryName(file) {
2050
1756
  const { dir, name } = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].parse(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].relative(outBase, file));
2051
- // Entry filename contains nested path to preserve source directory structure.
2052
1757
  const entryFileName = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(dir, name);
2053
- // 1. we mark the global css files (which will generate empty js chunk in cssExtract), and deleteAsset in RemoveCssExtractAssetPlugin
2054
- // 2. avoid the same name e.g: `index.ts` and `index.css`
2055
1758
  if (isCssGlobalFile(file, cssModulesAuto)) return `${RSLIB_CSS_ENTRY_FLAG}/${entryFileName}`;
2056
1759
  return entryFileName;
2057
1760
  }
@@ -2072,39 +1775,52 @@ const composeEntryConfig = async (entries, bundle, root, cssModulesAuto)=>{
2072
1775
  lcp
2073
1776
  };
2074
1777
  };
2075
- const composeBundleConfig = (jsExtension, redirect, cssModulesAuto, bundle)=>{
2076
- if (bundle) return {};
2077
- const isStyleRedirect = redirect.style ?? true;
1778
+ const composeBundlelessExternalConfig = (jsExtension, redirect, cssModulesAuto, bundle)=>{
1779
+ if (bundle) return {
1780
+ config: {}
1781
+ };
1782
+ const isStyleRedirected = redirect.style ?? true;
1783
+ const jsRedirectPath = redirect.js?.path ?? true;
1784
+ const jsRedirectExtension = redirect.js?.extension ?? true;
1785
+ let resolver;
2078
1786
  return {
2079
- output: {
2080
- externals: [
2081
- (data, callback)=>{
2082
- // Issuer is not empty string when the module is imported by another module.
2083
- // Prevent from externalizing entry modules here.
2084
- if (data.contextInfo.issuer) {
2085
- // Node.js ECMAScript module loader does no extension searching.
2086
- // Add a file extension according to autoExtension config
2087
- // when data.request is a relative path and do not have an extension.
2088
- // If data.request already have an extension, we replace it with new extension
2089
- // This may result in a change in semantics,
2090
- // user should use copy to keep origin file or use another separate entry to deal this
2091
- let request = data.request;
2092
- const cssExternal = cssExternalHandler(request, callback, jsExtension, cssModulesAuto, isStyleRedirect);
2093
- if (false !== cssExternal) return cssExternal;
2094
- if ('.' === request[0]) {
2095
- const ext = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.extname)(request);
2096
- if (ext) {
2097
- if (!JS_EXTENSIONS_PATTERN.test(request)) // If it does not match jsExtensionsPattern, we should do nothing, eg: ./foo.png
2098
- return callback();
2099
- request = request.replace(/\.[^.]+$/, jsExtension);
2100
- } else // TODO: add redirect.extension option
2101
- request = `${request}${jsExtension}`;
1787
+ resolvedJsRedirect: {
1788
+ path: jsRedirectPath,
1789
+ extension: jsRedirectExtension
1790
+ },
1791
+ config: {
1792
+ output: {
1793
+ externals: [
1794
+ async (data, callback)=>{
1795
+ const { request, getResolve, context, contextInfo } = data;
1796
+ if (!request || !getResolve || !context || !contextInfo) return callback();
1797
+ if (!resolver) resolver = await getResolve();
1798
+ if (contextInfo.issuer) {
1799
+ let resolvedRequest = request;
1800
+ const cssExternal = cssExternalHandler(resolvedRequest, callback, jsExtension, cssModulesAuto, isStyleRedirected);
1801
+ if (false !== cssExternal) return cssExternal;
1802
+ if (jsRedirectPath) {
1803
+ try {
1804
+ resolvedRequest = await resolver(context, resolvedRequest);
1805
+ } catch (e) {
1806
+ __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.debug(`Failed to resolve ${resolvedRequest} with resolver`);
1807
+ }
1808
+ resolvedRequest = normalizeSlash(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].relative(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].dirname(contextInfo.issuer), resolvedRequest));
1809
+ if ('.' !== resolvedRequest[0]) resolvedRequest = `./${resolvedRequest}`;
1810
+ }
1811
+ if (jsRedirectExtension) {
1812
+ const ext = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.extname)(resolvedRequest);
1813
+ if (ext) {
1814
+ if (!JS_EXTENSIONS_PATTERN.test(resolvedRequest)) return callback();
1815
+ resolvedRequest = resolvedRequest.replace(/\.[^.]+$/, jsExtension);
1816
+ } else resolvedRequest = `${resolvedRequest}${jsExtension}`;
1817
+ }
1818
+ return callback(void 0, resolvedRequest);
2102
1819
  }
2103
- return callback(null, request);
1820
+ callback();
2104
1821
  }
2105
- callback();
2106
- }
2107
- ]
1822
+ ]
1823
+ }
2108
1824
  }
2109
1825
  };
2110
1826
  };
@@ -2112,7 +1828,6 @@ const composeDtsConfig = async (libConfig, dtsExtension)=>{
2112
1828
  const { format, autoExternal, banner, footer } = libConfig;
2113
1829
  let { dts } = libConfig;
2114
1830
  if (false === dts || void 0 === dts) return {};
2115
- // DTS default to bundleless whether js is bundle or not
2116
1831
  if (true === dts) dts = {
2117
1832
  bundle: false
2118
1833
  };
@@ -2120,7 +1835,6 @@ const composeDtsConfig = async (libConfig, dtsExtension)=>{
2120
1835
  return {
2121
1836
  plugins: [
2122
1837
  pluginDts({
2123
- // Only setting ⁠dts.bundle to true will generate the bundled d.ts.
2124
1838
  bundle: dts?.bundle,
2125
1839
  distPath: dts?.distPath,
2126
1840
  build: dts?.build,
@@ -2133,10 +1847,9 @@ const composeDtsConfig = async (libConfig, dtsExtension)=>{
2133
1847
  ]
2134
1848
  };
2135
1849
  };
2136
- const composeTargetConfig = (target, format)=>{
2137
- let defaultTarget = target;
2138
- if (!defaultTarget) defaultTarget = 'mf' === format ? 'web' : 'node';
2139
- switch(defaultTarget){
1850
+ const composeTargetConfig = (userTarget, format)=>{
1851
+ const target = userTarget ?? ('mf' === format ? 'web' : 'node');
1852
+ switch(target){
2140
1853
  case 'web':
2141
1854
  return {
2142
1855
  config: {
@@ -2148,7 +1861,8 @@ const composeTargetConfig = (target, format)=>{
2148
1861
  }
2149
1862
  }
2150
1863
  },
2151
- target: 'web'
1864
+ target: 'web',
1865
+ externalsConfig: {}
2152
1866
  };
2153
1867
  case 'node':
2154
1868
  return {
@@ -2161,26 +1875,18 @@ const composeTargetConfig = (target, format)=>{
2161
1875
  }
2162
1876
  },
2163
1877
  output: {
2164
- // When output.target is 'node', Node.js's built-in will be treated as externals of type `node-commonjs`.
2165
- // Simply override the built-in modules to make them external.
2166
- // https://github.com/webpack/webpack/blob/dd44b206a9c50f4b4cb4d134e1a0bd0387b159a3/lib/node/NodeTargetPlugin.js#L81
2167
- externals: nodeBuiltInModules,
2168
1878
  target: 'node'
2169
1879
  }
2170
1880
  },
2171
- target: 'node'
1881
+ target: 'node',
1882
+ externalsConfig: {
1883
+ output: {
1884
+ externals: nodeBuiltInModules
1885
+ }
1886
+ }
2172
1887
  };
2173
- // TODO: Support `neutral` target, however Rsbuild don't list it as an option in the target field.
2174
- // case 'neutral':
2175
- // return {
2176
- // tools: {
2177
- // rspack: {
2178
- // target: ['web', 'node'],
2179
- // },
2180
- // },
2181
- // };
2182
1888
  default:
2183
- throw new Error(`Unsupported platform: ${defaultTarget}`);
1889
+ throw new Error(`Unsupported platform: ${target}`);
2184
1890
  }
2185
1891
  };
2186
1892
  const composeExternalHelpersConfig = (externalHelpers, pkgJson)=>{
@@ -2213,7 +1919,6 @@ const composeExternalHelpersConfig = (externalHelpers, pkgJson)=>{
2213
1919
  };
2214
1920
  async function composeLibRsbuildConfig(config, sharedPlugins) {
2215
1921
  checkMFPlugin(config, sharedPlugins);
2216
- // Get the absolute path of the root directory to align with Rsbuild's default behavior
2217
1922
  const rootPath = config.root ? getAbsolutePath(process.cwd(), config.root) : process.cwd();
2218
1923
  const pkgJson = readPackageJson(rootPath);
2219
1924
  const { compilerOptions } = await loadTsconfig(rootPath, config.source?.tsconfigPath);
@@ -2227,10 +1932,10 @@ async function composeLibRsbuildConfig(config, sharedPlugins) {
2227
1932
  umdName
2228
1933
  });
2229
1934
  const externalHelpersConfig = composeExternalHelpersConfig(externalHelpers, pkgJson);
2230
- const externalsConfig = composeExternalsConfig(format, config.output?.externals);
1935
+ const userExternalsConfig = composeExternalsConfig(format, config.output?.externals);
2231
1936
  const { config: autoExtensionConfig, jsExtension, dtsExtension } = composeAutoExtensionConfig(config, autoExtension, pkgJson);
2232
- const bundleConfig = composeBundleConfig(jsExtension, redirect, cssModulesAuto, bundle);
2233
- const { config: targetConfig, target } = composeTargetConfig(config.output?.target, format);
1937
+ const { config: bundlelessExternalConfig } = composeBundlelessExternalConfig(jsExtension, redirect, cssModulesAuto, bundle);
1938
+ const { config: targetConfig, externalsConfig: targetExternalsConfig, target } = composeTargetConfig(config.output?.target, format);
2234
1939
  const syntaxConfig = composeSyntaxConfig(target, config?.syntax);
2235
1940
  const autoExternalConfig = composeAutoExternalConfig({
2236
1941
  format: format,
@@ -2240,15 +1945,16 @@ async function composeLibRsbuildConfig(config, sharedPlugins) {
2240
1945
  });
2241
1946
  const { entryConfig, lcp } = await composeEntryConfig(config.source?.entry, config.bundle, rootPath, cssModulesAuto);
2242
1947
  const cssConfig = composeCssConfig(lcp, config.bundle);
1948
+ const assetConfig = composeAssetConfig(bundle, format);
2243
1949
  const entryChunkConfig = composeEntryChunkConfig({
2244
1950
  enabledImportMetaUrlShim: enabledShims.cjs['import.meta.url']
2245
1951
  });
2246
1952
  const dtsConfig = await composeDtsConfig(config, dtsExtension);
2247
- const externalsWarnConfig = composeExternalsWarnConfig(format, autoExternalConfig?.output?.externals, externalsConfig?.output?.externals);
1953
+ const externalsWarnConfig = composeExternalsWarnConfig(format, autoExternalConfig?.output?.externals, userExternalsConfig?.output?.externals);
2248
1954
  const minifyConfig = composeMinifyConfig(config);
2249
1955
  const bannerFooterConfig = composeBannerFooterConfig(banner, footer);
2250
1956
  const decoratorsConfig = composeDecoratorsConfig(compilerOptions, config.source?.decorators?.version);
2251
- return (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(formatConfig, shimsConfig, externalHelpersConfig, externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, cssConfig, entryChunkConfig, minifyConfig, dtsConfig, bannerFooterConfig, decoratorsConfig);
1957
+ return (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(formatConfig, shimsConfig, syntaxConfig, externalHelpersConfig, autoExtensionConfig, targetConfig, externalsWarnConfig, autoExternalConfig, targetExternalsConfig, userExternalsConfig, bundlelessExternalConfig, entryConfig, cssConfig, assetConfig, entryChunkConfig, minifyConfig, dtsConfig, bannerFooterConfig, decoratorsConfig);
2252
1958
  }
2253
1959
  async function composeCreateRsbuildConfig(rslibConfig) {
2254
1960
  const constantRsbuildConfig = await createConstantRsbuildConfig();
@@ -2256,27 +1962,13 @@ async function composeCreateRsbuildConfig(rslibConfig) {
2256
1962
  if (!libConfigsArray) throw new Error(`Expect lib field to be an array, but got ${libConfigsArray}.`);
2257
1963
  const libConfigPromises = libConfigsArray.map(async (libConfig)=>{
2258
1964
  const userConfig = (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(sharedRsbuildConfig, libConfig);
2259
- // Merge the configuration of each environment based on the shared Rsbuild
2260
- // configuration and Lib configuration in the settings.
2261
1965
  const libRsbuildConfig = await composeLibRsbuildConfig(userConfig, sharedPlugins);
2262
- // Reset certain fields because they will be completely overridden by the upcoming merge.
2263
- // We don't want to retain them in the final configuration.
2264
- // The reset process should occur after merging the library configuration.
2265
1966
  userConfig.source ??= {};
2266
1967
  userConfig.source.entry = {};
2267
- // Already manually sort and merge the externals configuration.
2268
1968
  userConfig.output ??= {};
2269
1969
  delete userConfig.output.externals;
2270
1970
  const config = {
2271
1971
  format: libConfig.format,
2272
- // The merge order represents the priority of the configuration
2273
- // The priorities from high to low are as follows:
2274
- // 1 - userConfig: users can configure any Rsbuild and Rspack config
2275
- // 2 - libRsbuildConfig: the configuration that we compose from Rslib unique config and userConfig from 1
2276
- // 3 - constantRsbuildConfig: the built-in best practice Rsbuild configuration we provide in Rslib
2277
- // We should state in the document that the built-in configuration should not be changed optionally
2278
- // In compose process of 2, we may read some config from 1, and reassemble the related config,
2279
- // so before final mergeRsbuildConfig, we reset some specified fields
2280
1972
  config: (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(constantRsbuildConfig, libRsbuildConfig, omit(userConfig, {
2281
1973
  id: true,
2282
1974
  bundle: true,
@@ -2301,7 +1993,6 @@ async function composeCreateRsbuildConfig(rslibConfig) {
2301
1993
  }
2302
1994
  async function composeRsbuildEnvironments(rslibConfig) {
2303
1995
  const rsbuildConfigWithLibInfo = await composeCreateRsbuildConfig(rslibConfig);
2304
- // User provided ids should take precedence over generated ids.
2305
1996
  const usedIds = rsbuildConfigWithLibInfo.map(({ id })=>id).filter(Boolean);
2306
1997
  const environments = {};
2307
1998
  const formatCount = rsbuildConfigWithLibInfo.reduce((acc, { format })=>{
@@ -2333,7 +2024,6 @@ async function watchFilesForRestart(files, restart) {
2333
2024
  const chokidar = await import("../compiled/chokidar/index.js");
2334
2025
  const watcher = chokidar.watch(files, {
2335
2026
  ignoreInitial: true,
2336
- // If watching fails due to read permissions, the errors will be suppressed silently.
2337
2027
  ignorePermissionErrors: true
2338
2028
  });
2339
2029
  const callback = debounce(async (filePath)=>{
@@ -2348,9 +2038,7 @@ async function watchFilesForRestart(files, restart) {
2348
2038
  watcher.on('unlink', callback);
2349
2039
  }
2350
2040
  let cleaners = [];
2351
- /**
2352
- * Add a cleaner to handle side effects
2353
- */ const onBeforeRestart = (cleaner)=>{
2041
+ const onBeforeRestart = (cleaner)=>{
2354
2042
  cleaners.push(cleaner);
2355
2043
  };
2356
2044
  const clearConsole = ()=>{
@@ -2435,8 +2123,7 @@ async function startMFDevServer(config) {
2435
2123
  async function initMFRsbuild(rslibConfig) {
2436
2124
  const rsbuildConfigObject = await composeCreateRsbuildConfig(rslibConfig);
2437
2125
  const mfRsbuildConfig = rsbuildConfigObject.find((config)=>'mf' === config.format);
2438
- if (!mfRsbuildConfig) // no mf format, return.
2439
- return;
2126
+ if (!mfRsbuildConfig) return;
2440
2127
  mfRsbuildConfig.config = changeEnvToDev(mfRsbuildConfig.config);
2441
2128
  const rsbuildInstance = await (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.createRsbuild)({
2442
2129
  rsbuildConfig: {
@@ -2474,7 +2161,7 @@ const repeatableOption = (value, previous)=>(previous ?? []).concat([
2474
2161
  value
2475
2162
  ]);
2476
2163
  function runCli() {
2477
- __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.name('rslib').usage('<command> [options]').version("0.1.4");
2164
+ __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.name('rslib').usage('<command> [options]').version("0.1.5");
2478
2165
  const buildCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('build');
2479
2166
  const inspectCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('inspect');
2480
2167
  const mfDevCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('mf dev');
@@ -2501,7 +2188,6 @@ function runCli() {
2501
2188
  });
2502
2189
  inspectCommand.description('inspect the Rsbuild / Rspack configs of Rslib projects').option('--lib <id>', 'inspect the specified library (may be repeated)', repeatableOption).option('--output <output>', 'specify inspect content output path', '.rsbuild').option('--verbose', 'show full function definitions in output').action(async (options)=>{
2503
2190
  try {
2504
- // TODO: inspect should output Rslib's config
2505
2191
  const { config } = await init(options);
2506
2192
  await inspect(config, {
2507
2193
  lib: options.lib,
@@ -2519,7 +2205,6 @@ function runCli() {
2519
2205
  try {
2520
2206
  const cliMfDev = async ()=>{
2521
2207
  const { config, watchFiles } = await init(options);
2522
- // TODO: support lib option in mf dev server
2523
2208
  await startMFDevServer(config);
2524
2209
  watchFilesForRestart(watchFiles, async ()=>{
2525
2210
  await cliMfDev();
@@ -2534,6 +2219,6 @@ function runCli() {
2534
2219
  });
2535
2220
  __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.parse();
2536
2221
  }
2537
- const src_rslib_entry_version = "0.1.4";
2222
+ const src_rslib_entry_version = "0.1.5";
2538
2223
  var __webpack_exports__logger = __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger;
2539
2224
  export { build, defineConfig, inspect, loadConfig, prepareCli, runCli, startMFDevServer, composeCreateRsbuildConfig as unstable_composeCreateRsbuildConfig, src_rslib_entry_version as version, __webpack_exports__logger as logger };